diff --git a/.deepsource.toml b/.deepsource.toml new file mode 100644 index 0000000..2dddb56 --- /dev/null +++ b/.deepsource.toml @@ -0,0 +1,8 @@ +version = 1 + +[[analyzers]] +name = "javascript" + + [analyzers.meta] + plugins = ["react"] + environment = ["nodejs"] \ No newline at end of file diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b512c09 --- /dev/null +++ b/.dockerignore @@ -0,0 +1 @@ +node_modules \ No newline at end of file diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..488ca99 --- /dev/null +++ b/.env.example @@ -0,0 +1,5 @@ +BASE_URL = +ALGOLIA_API_KEY = +ALGOLIA_APP_ID = +GTM_ID = +GA_ID = \ No newline at end of file diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..5a392e8 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @ajay-dhangar \ No newline at end of file diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..a8c4257 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,13 @@ +# These are supported funding model platforms + +github: Ajay-Dhangar # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: ajay_dhangar # Replace with a single Patreon username +open_collective: codeharborhub # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..034f9ea --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,55 @@ +name: Bug report 🐞 +description: File a bug report +title: "[Bug]: " +labels: bug +body: + - type: checkboxes + id: existing-issue + attributes: + label: Is there an existing issue for this? + description: Please search to see if an issue already exists for the bug you encountered. + options: + - label: I have searched the existing issues + required: true + - type: textarea + id: what-happened + attributes: + label: Describe the bug + description: A concise description of what you are experiencing. + placeholder: Tell us what you see! + validations: + required: true + - type: textarea + id: expected-behaviour + attributes: + label: Expected behavior + description: A clear and concise description of what you expected to happen. + validations: + required: true + - type: textarea + id: screenshots + attributes: + label: Add ScreenShots + description: Add sufficient ScreenShots to explain your issue. + - type: dropdown + id: devices + attributes: + label: On which device are you experiencing this bug? + multiple: true + options: + - Android + - iPhone + - Linux + - Chrome + - Windows + - type: checkboxes + id: terms + attributes: + label: Record + options: + - label: "I have read the Contributing Guidelines" + required: true + - label: "I'm a GSSOC'24 contributor" + required: False + - label: "I have starred the repository" + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..df81a68 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,12 @@ +contact_links: + - name: CodeHarborHub Q&A + url: https://codeharborhub.github.io/community/supports#-how-to-get-support + about: Get help from the community with any questions or issues. + + - name: CodeHarborHub Features + url: https://codeharborhub.github.io/community/features + about: Explore the features and capabilities of CodeHarborHub. + + - name: Meet the Founder or Owner + url: https://codeharborhub.github.io/me/ + about: Learn more about the founder and owner of CodeHarborHub. diff --git a/.github/ISSUE_TEMPLATE/documentation.yml b/.github/ISSUE_TEMPLATE/documentation.yml new file mode 100644 index 0000000..5d9975b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/documentation.yml @@ -0,0 +1,84 @@ +name: πŸ“ Documentation Update +description: Improve Documentation +title: "[Documentation Update]: " +labels: 'enhancement' +body: + - type: checkboxes + id: existing-issue + attributes: + label: Is there an existing issue for this? + description: Please search to see if an issue already exists for the updates you want to make. + options: + - label: I have searched the existing issues + required: true + + - type: textarea + id: issue-description + attributes: + label: Issue Description + description: Please provide a clear description of the documentation update you are suggesting. + placeholder: Describe the improvement or correction you'd like to see in the documentation. + validations: + required: true + + - type: textarea + id: suggested-change + attributes: + label: Suggested Change + description: Provide details of the proposed change to the documentation. + placeholder: Explain how the documentation should be updated or corrected. + validations: + required: true + + - type: textarea + id: rationale + attributes: + label: Rationale + description: Why is this documentation update necessary or beneficial? + placeholder: Explain the importance or reasoning behind the suggested change. + validations: + required: false + + - type: dropdown + id: urgency + attributes: + label: Urgency + description: How urgently do you believe this documentation update is needed? + options: + - High + - Medium + - Low + default: 0 + validations: + required: true + + - type: checkboxes + id: terms + attributes: + label: Acknowledgements + description: Ensure you have read and agree to the project's guidelines. + options: + - label: I have read the Contributing Guidelines + required: true + - label: I'm a GSSOC'24 contributor + required: false + - label: I have starred the repository + required: true + - label: I have read and followed the Contribution Guidelines + required: true + - label: I have followed the code style guidelines of this project + required: true + - label: I have checked for any existing open issues that my pull request may address + required: true + - label: I have ensured that my changes do not break any existing functionality + required: true + - label: Each contributor is allowed to create a maximum of 4 issues per day. This helps us manage and address issues efficiently + required: true + - label: I have read the resources for guidance listed below + required: true + - label: I have not used AI-generated content (e.g., ChatGPT, other AI tools) + required: true + - label: I have not used content from existing sites (e.g., text, images) + required: true + - label: I have followed all security rules and only shared trusted resources + required: true diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..cac7ac7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,63 @@ +name: ✨ Feature Request +description: Suggest a feature +title: "[Feature Request]: " +labels: enhancement +body: + - type: checkboxes + id: existing-issue + attributes: + label: Is there an existing issue for this? + description: Please search to see if an issue already exists for this feature. + options: + - label: I have searched the existing issues + required: true + - type: textarea + id: feature-description + attributes: + label: Feature Description + description: Please provide a detailed description of the feature you are requesting. + placeholder: Describe the new feature or enhancement you'd like to see. + validations: + required: true + - type: textarea + id: use-case + attributes: + label: Use Case + description: How would this feature enhance your use of the project? + placeholder: Describe a specific use case or scenario where this feature would be beneficial. + validations: + required: true + - type: textarea + id: benefits + attributes: + label: Benefits + description: What benefits would this feature bring to the project or community? + placeholder: Explain the advantages of implementing this feature. + - type: textarea + id: screenShots + attributes: + label: Add ScreenShots + description: If any... + - type: dropdown + id: priority + attributes: + label: Priority + description: How important is this feature to you? + options: + - High + - Medium + - Low + default: 0 + validations: + required: true + - type: checkboxes + id: terms + attributes: + label: Record + options: + - label: "I have read the Contributing Guidelines" + required: true + - label: "I'm a GSSOC'24 contributor" + required: false + - label: "I have starred the repository" + required: true diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..6f1d79f --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,27 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file + +version: 2 +updates: + - package-ecosystem: "npm" # Using npm for Docusaurus + directory: "/" + schedule: + interval: "daily" # Changed to daily from weekly + # open-pull-requests-limit: 0 # Disable version updates for npm dependencies + labels: + - 'pr: dependencies' + + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 99 + labels: + - 'pr: dependencies' + + - package-ecosystem: "docker" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..ae8b4e5 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,86 @@ +## Related Issue + +[Cite any related issue(s) this pull request addresses. If none, simply state "None”] + +## Description + +[Please include a brief description of the changes or features added] + +## Type of PR + +- [ ] Bug fix +- [ ] Feature enhancement +- [ ] Documentation update +- [ ] Security enhancement +- [ ] Other (specify): _______________ + +## Screenshots / Videos (if applicable) + +[Attach any relevant screenshots or videos demonstrating the changes] + +## Checklist +- [ ] I have performed a self-review of my code. +- [ ] I have read and followed the Contribution Guidelines. +- [ ] I have tested the changes thoroughly before submitting this pull request. +- [ ] I have provided relevant issue numbers, screenshots, and videos after making the changes. +- [ ] I have commented my code, particularly in hard-to-understand areas. +- [ ] I have followed the code style guidelines of this project. +- [ ] I have checked for any existing open issues that my pull request may address. +- [ ] I have ensured that my changes do not break any existing functionality. +- [ ] Each contributor is allowed to create a maximum of 4 issues per day. This helps us manage and address issues efficiently. +- [ ] I have read the resources for guidance listed below. +- [ ] I have followed security best practices in my code changes. + +## Additional Context + +[Include any additional information or context that might be helpful for reviewers.] + +## Resources for Guidance + +Please read the following resources before submitting your contribution: + +- [ ] [Code Harbor Hub Community Features](https://www.codeharborhub.live/community/features) +- [ ] [Docusaurus Documentation](https://docusaurus.io/docs/create-doc) +- [ ] [React.js Documentation](https://legacy.reactjs.org/docs/getting-started.html) +- [ ] [Markdown Guide](https://www.markdownguide.org/) +- [ ] [MDX Documentation](https://mdxjs.com/docs/) +- [ ] [Mermaid Documentation](https://mermaid.js.org/) + +**Resources for DSA Features on Our Site:** + +- [ ] [Tabs: Switch Languages](https://www.codeharborhub.live/community/features#multi-language-support-code-blocks) +- [ ] [Line Numbering](https://www.codeharborhub.live/community/features#line-numbering) +- [ ] [Math Equations](https://www.codeharborhub.live/community/features#math-equations-with-katex) + +## Contribution Guidelines + +Thank you for considering contributing to our project! To ensure smooth collaboration and effective contribution management, please adhere to the following guidelines: + +### Issue Creation + +1. **Limit on Issues:** + - Each contributor is allowed to create a maximum of **4 issues per day**. This helps us manage and address issues efficiently. + +### Contribution Levels + +2. **Basic Contributions:** + - This project is primarily focused on documentation. Most of the setup has been completed, so contributors will generally need to work on basic code tasks, such as writing tests. + - For these tasks, issues will be assigned the **level1** label. + +3. **Acknowledging Hard Work:** + - If a contributor puts in significant effort on a task, the issue will be upgraded to **level2**. This is our way of recognizing and appreciating extra effort. + +4. **Feature Additions and Component Work:** + - Contributors working on new features or components using JSX/TSX will be assigned a level based on the complexity and quality of their work. + - The more complex and valuable the contribution, the higher the level assigned. + +### Level Definitions + +- **Level1:** + - Tasks are straightforward, such as fixing minor bugs, writing tests, or making simple documentation updates. +- **Level2:** + - Tasks require more effort, such as addressing complex bugs, improving existing features, or making substantial documentation improvements. +- **Level3:** + - Tasks are highly complex and involve significant new feature development, major refactoring, or extensive contributions to the project’s core components. + +We look forward to your contributions and appreciate your effort in helping us improve the project! diff --git a/.github/workflows/auto-content-on-labels.yml b/.github/workflows/auto-content-on-labels.yml new file mode 100644 index 0000000..17e1dd5 --- /dev/null +++ b/.github/workflows/auto-content-on-labels.yml @@ -0,0 +1,34 @@ +name: Auto Content on Labels + +on: + issues: + types: [opened] + pull_request: + types: [opened] + +jobs: + addContent: + runs-on: ubuntu-latest + steps: + - name: Check for Labels + id: check_labels + run: echo "::set-output name=labels::${{ toJson(github.event.issue.labels) }}" + + - name: Add Guidance Comment + if: ${{ contains(steps.check_labels.outputs.labels, 'dsa-solution') }} + uses: actions/github-script@v7 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const issueOrPR = github.context.payload.issue || github.context.payload.pull_request; + const comment = ` + Hello there! 🌟 It looks like you've added the \`dsa-solution\` label. + Please refer to our guidance on Data Structures & Algorithms solutions here: [DSA Solution Guidance](https://github.com/orgs/CodeHarborHub/discussions/3369#discussion-6940372). + Thank you! + `; + github.issues.createComment({ + issue_number: issueOrPR.number, + owner: github.context.repo.owner, + repo: github.context.repo.repo, + body: comment + }); diff --git a/.github/workflows/autocomment-iss-close.yml b/.github/workflows/autocomment-iss-close.yml new file mode 100644 index 0000000..93c41cb --- /dev/null +++ b/.github/workflows/autocomment-iss-close.yml @@ -0,0 +1,29 @@ +name: Comment on Issue Close + +on: + issues: + types: [closed] + +jobs: + greet-on-close: + runs-on: ubuntu-latest + permissions: + issues: write + steps: + - name: Greet User + uses: actions/github-script@v7 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const issue = context.payload.issue; + const issueCreator = issue.user.login; + const issueNumber = issue.number; + + const greetingMessage = `Hello @${issueCreator}! Your issue #${issueNumber} has been closed. Thank you for your contribution!`; + + github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + body: greetingMessage + }); \ No newline at end of file diff --git a/.github/workflows/close-old-issue.yml b/.github/workflows/close-old-issue.yml new file mode 100644 index 0000000..0776386 --- /dev/null +++ b/.github/workflows/close-old-issue.yml @@ -0,0 +1,37 @@ +name: Close Old Issues +on: + schedule: + - cron: "0 0 * * *" + +jobs: + close-issues: + runs-on: ubuntu-latest + + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + + - name: Close Old Issues + run: | + open_issues=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ + "https://api.github.com/repos/${{ github.repository }}/issues?state=open" \ + | jq -r '.[] | .number') + for issue in $open_issues; do + # Get the last updated timestamp of the issue + last_updated=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ + "https://api.github.com/repos/${{ github.repository }}/issues/$issue" \ + | jq -r '.updated_at') + days_since_update=$(( ( $(date +%s) - $(date -d "$last_updated" +%s) ) / 86400 )) + if [ $days_since_update -gt 30 ]; then + curl -s -X PATCH -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ + -H "Accept: application/vnd.github.v3+json" \ + -d '{"state":"closed"}' \ + "https://api.github.com/repos/${{ github.repository }}/issues/$issue" + + # Add a comment explaining when the issue will be closed + curl -s -X POST -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ + -H "Accept: application/vnd.github.v3+json" \ + -d '{"body":"This issue has been automatically closed because it has been inactive for more than 30 days. If you believe this is still relevant, feel free to reopen it or create a new one. Thank you!"}' \ + "https://api.github.com/repos/${{ github.repository }}/issues/$issue/comments" + fi + done \ No newline at end of file diff --git a/.github/workflows/close-old-pr.yml b/.github/workflows/close-old-pr.yml new file mode 100644 index 0000000..f304416 --- /dev/null +++ b/.github/workflows/close-old-pr.yml @@ -0,0 +1,34 @@ +name: Close Stale PRs + +on: + schedule: + - cron: '0 0 * * *' # Runs daily at midnight + pull_request: + types: + - opened + - reopened + - synchronize + +permissions: + pull-requests: write + issues: write + +jobs: + close_stale_prs: + runs-on: ubuntu-latest + permissions: + pull-requests: write + + steps: + - uses: actions/stale@v9 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + stale-pr-message: 'This PR has been automatically closed due to inactivity from the owner for 15 days.' + days-before-pr-stale: 15 + days-before-pr-close: 0 + exempt-pr-author: false + exempt-pr-labels: '' + only-labels: '' + operations-per-run: 30 + remove-stale-when-updated: true + debug-only: false \ No newline at end of file diff --git a/.github/workflows/codacy.yml b/.github/workflows/codacy.yml new file mode 100644 index 0000000..3a52ede --- /dev/null +++ b/.github/workflows/codacy.yml @@ -0,0 +1,61 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. + +# This workflow checks out code, performs a Codacy security scan +# and integrates the results with the +# GitHub Advanced Security code scanning feature. For more information on +# the Codacy security scan action usage and parameters, see +# https://github.com/codacy/codacy-analysis-cli-action. +# For more information on Codacy Analysis CLI in general, see +# https://github.com/codacy/codacy-analysis-cli. + +name: Codacy Security Scan + +on: + push: + branches: [ "main" ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ "main" ] + schedule: + - cron: '41 23 * * 2' + +permissions: + contents: read + +jobs: + codacy-security-scan: + permissions: + contents: read # for actions/checkout to fetch code + security-events: write # for github/codeql-action/upload-sarif to upload SARIF results + actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status + name: Codacy Security Scan + runs-on: ubuntu-latest + steps: + # Checkout the repository to the GitHub Actions runner + - name: Checkout code + uses: actions/checkout@v4 + + # Execute Codacy Analysis CLI and generate a SARIF output with the security issues identified during the analysis + - name: Run Codacy Analysis CLI + uses: codacy/codacy-analysis-cli-action@09916000460adeeedc96b9704f86deba53e2ad5d + with: + # Check https://github.com/codacy/codacy-analysis-cli#project-token to get your project token from your Codacy repository + # You can also omit the token and run the tools that support default configurations + project-token: ${{ secrets.CODACY_PROJECT_TOKEN }} + verbose: true + output: results.sarif + format: sarif + # Adjust severity of non-security issues + gh-code-scanning-compat: true + # Force 0 exit code to allow SARIF file generation + # This will handover control about PR rejection to the GitHub side + max-allowed-issues: 2147483647 + + # Upload the SARIF file generated in the previous step + - name: Upload SARIF results file + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: results.sarif diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..b3cb14e --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,51 @@ +name: Deploy to GitHub Pages + +on: + push: + branches: + - main + # Review gh actions docs if you want to further define triggers, paths, etc + # https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#on + +jobs: + build: + name: Build CodeHarborHub + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-node@v4 + with: + node-version: 18 + cache: npm + + - name: Install dependencies + run: npm install --frozen-lockfile + - name: Build website + run: npm run build + + - name: Upload Build Artifact + uses: actions/upload-pages-artifact@v3 + with: + path: build + + deploy: + name: Deploy to GitHub Pages + needs: build + + # Grant GITHUB_TOKEN the permissions required to make a Pages deployment + permissions: + pages: write # to deploy to Pages + id-token: write # to verify the deployment originates from an appropriate source + + # Deploy to the github-pages environment + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + + runs-on: ubuntu-latest + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml new file mode 100644 index 0000000..3f53646 --- /dev/null +++ b/.github/workflows/docker-image.yml @@ -0,0 +1,18 @@ +name: Docker Image CI + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +jobs: + + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - name: Build the Docker image + run: docker build . --file Dockerfile --tag my-image-name:$(date +%s) diff --git a/.github/workflows/greetings.yml b/.github/workflows/greetings.yml new file mode 100644 index 0000000..6a34356 --- /dev/null +++ b/.github/workflows/greetings.yml @@ -0,0 +1,61 @@ +name: 'Greetings' + +on: + issues: + types: [opened] + pull_request_target: + types: [opened] + +permissions: + issues: write + pull-requests: write + +jobs: + welcome: + runs-on: ubuntu-latest + + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Greet first-time contributors + id: greet + uses: actions/first-interaction@v1 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + issue-message: | + Hi @${{ github.actor }}! πŸ‘‹ Thank you for opening your first issue on CodeHarborHub. We're excited to hear your thoughts and help you out. You've raised a great topic! Please provide as much detail as you can so we can assist you effectively. Welcome aboard! + pr-message: | + Hi @${{ github.actor }}! πŸ‘‹ Thank you for submitting your first pull request to CodeHarborHub. Great job on the contribution! πŸŽ‰ We appreciate your efforts and our team will review it soon. If you have any questions or need further assistance, feel free to reach out. Keep up the great work! + + - name: Assign issue or pull request to team member + if: github.event_name == 'issues' || github.event_name == 'pull_request_target' + run: | + ISSUE_NUMBER=${{ github.event.issue.number || github.event.pull_request.number }} + curl -X POST -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ + -d '{"assignees":["team-member"]}' \ + "https://api.github.com/repos/${{ github.repository }}/issues/${ISSUE_NUMBER}" + + - name: Welcome message for community contributors + if: github.event_name == 'issues' || github.event_name == 'pull_request_target' + uses: EddieHubCommunity/gh-action-community/src/welcome@main + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + issue-message: "Hi @${{ github.actor }}! Thanks for opening this issue. We appreciate your contribution to this open-source project. Your input is valuable and we aim to respond or assign your issue as soon as possible. Thanks again!" + pr-message: "Great job, @${{ github.actor }}! πŸŽ‰ Thank you for submitting your pull request to CodeHarborHub. We appreciate your contribution and enthusiasm! Our team will review it soon. If you have any questions or need further assistance, feel free to reach out. Thanks for contributing!" + + - name: Label first-time issues + if: github.event_name == 'issues' + run: | + ISSUE_NUMBER=${{ github.event.issue.number }} + curl -X POST -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ + -d '{"labels":["CodeHarborHub - Thanks for creating an issue!"]}' \ + "https://api.github.com/repos/${{ github.repository }}/issues/${ISSUE_NUMBER}" + + - name: Label first-time pull requests + if: github.event_name == 'pull_request_target' + run: | + PR_NUMBER=${{ github.event.pull_request.number }} + curl -X POST -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ + -d '{"labels":["CodeHarborHub - Thanks for creating a pull request!"]}' \ + "https://api.github.com/repos/${{ github.repository }}/issues/${PR_NUMBER}" diff --git a/.github/workflows/issue_creation_workflow.yml b/.github/workflows/issue_creation_workflow.yml new file mode 100644 index 0000000..45e4a9f --- /dev/null +++ b/.github/workflows/issue_creation_workflow.yml @@ -0,0 +1,49 @@ +name: Issue Creation Workflow + +on: + issues: + types: [opened] + +jobs: + check-issue: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: '14' + + - name: Retrieve Contributor's Open Issues + id: retrieve-issues + run: | + ISSUE_COUNT=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" "https://api.github.com/search/issues?q=is:open+author:${{ github.event.issue.user.login }}+repo:${{ github.repository }}" | jq -r '.total_count') + echo "::set-output name=issue_count::$ISSUE_COUNT" + + - name: Check Contributor's Open Issues Count + run: | + issue_count=${{ steps.retrieve-issues.outputs.issue_count }} + if [ "$issue_count" -ge 4 ]; then + echo "Contributor ${{ github.event.issue.user.login }} has $issue_count open issues. Please complete your existing open issues before creating a new one." + exit 1 + fi + + - name: Validate Issue Content + id: validate-issue + run: | + issue_body="${{ github.event.issue.body }}" + if [[ "$issue_body" == *"AI-generated content"* ]] || [[ "$issue_body" == *"existing sites"* ]]; then + echo "Issue body contains disallowed content." + exit 1 + fi + + - name: Check for Security and Trust + run: | + issue_body="${{ github.event.issue.body }}" + if [[ "$issue_body" != *"security"* ]] || [[ "$issue_body" != *"trust"* ]]; then + echo "Issue does not mention security or trust." + exit 1 + fi diff --git a/.github/workflows/lighthouse-report.yml b/.github/workflows/lighthouse-report.yml new file mode 100644 index 0000000..f448886 --- /dev/null +++ b/.github/workflows/lighthouse-report.yml @@ -0,0 +1,71 @@ +name: Lighthouse Report + +on: + pull_request_target: + branches: + - main + - codeharborhub-v** + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + lighthouse-report: + permissions: + pull-requests: write # for marocchino/sticky-pull-request-comment + name: Lighthouse Report + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4.2.0 + + - name: Use Node.js + uses: actions/setup-node@v4.0.4 + with: + node-version: 20 + + - name: Install dependencies + run: npm ci + + - name: Build website + run: npm run build + + - name: Audit URLs using Lighthouse + id: lighthouse_audit + uses: treosh/lighthouse-ci-action@12.1.0 + with: + urls: | + http://localhost:3000/dsa + http://localhost:3000/dsa/problems + http://localhost:3000/dsa/problems/category/leetcode-problems + http://localhost:3000/dsa/solutions + http://localhost:3000/dsa/solutions/category/leetcode-solutions + http://localhost:3000/dsa/tags + configPath: ./.github/workflows/lighthouserc.json + uploadArtifacts: true + temporaryPublicStorage: true + + - name: Format lighthouse score + id: format_lighthouse_score + uses: actions/github-script@v7.0.1 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const results = ${{ steps.lighthouse_audit.outputs.manifest }} + const links = ${{ steps.lighthouse_audit.outputs.links }} + const createLighthouseReport = (await import(`${process.env.GITHUB_WORKSPACE}/admin/scripts/formatLighthouseReport.js`)).default; + const comment = createLighthouseReport({ results, links }); + core.setOutput("comment", comment); + + - name: Add Lighthouse stats as comment + id: comment_to_pr + uses: marocchino/sticky-pull-request-comment@v2.9.0 + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + number: ${{ github.event.pull_request.number }} + header: lighthouse + message: ${{ steps.format_lighthouse_score.outputs.comment }} diff --git a/.github/workflows/lighthouserc.json b/.github/workflows/lighthouserc.json new file mode 100644 index 0000000..dadffd0 --- /dev/null +++ b/.github/workflows/lighthouserc.json @@ -0,0 +1,20 @@ +{ + "ci": { + "collect": { + "startServerCommand": "npm run serve", + "startServerReadyPattern": "Serving", + "startServerReadyTimeout": 10000, + "numberOfRuns": 1, + "settings": { + "skipAudits": [ + "robots-txt", + "canonical", + "tap-targets", + "is-crawlable", + "works-offline", + "offline-start-url" + ] + } + } + } +} diff --git a/.github/workflows/pr_creation_workflow.yml b/.github/workflows/pr_creation_workflow.yml new file mode 100644 index 0000000..acf5438 --- /dev/null +++ b/.github/workflows/pr_creation_workflow.yml @@ -0,0 +1,66 @@ +name: PR Creation Workflow + +on: + pull_request: + types: [opened, edited] + +jobs: + check-pr: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: '14' + + - name: Validate PR Description + id: validate-pr + run: | + pr_body="${{ github.event.pull_request.body }}" + required_checkboxes=( + "I have performed a self-review of my code." + "I have read and followed the Contribution Guidelines." + "I have tested the changes thoroughly before submitting this pull request." + "I have provided relevant issue numbers, screenshots, and videos after making the changes." + "I have commented my code, particularly in hard-to-understand areas." + "I have followed the code style guidelines of this project." + "I have checked for any existing open issues that my pull request may address." + "I have ensured that my changes do not break any existing functionality." + "Each contributor is allowed to create a maximum of 4 issues per day. This helps us manage and address issues efficiently." + "I have read the resources for guidance listed below." + "I have not used AI-generated content (e.g., ChatGPT, other AI tools)." + "I have not used content from existing sites (e.g., text, images)." + "I have followed all security rules and only shared trusted resources." + ) + for checkbox in "${required_checkboxes[@]}"; do + if [[ "$pr_body" != *"$checkbox"* ]]; then + echo "Missing required checkbox: $checkbox" + exit 1 + fi + done + + - name: Retrieve Contributors + run: | + CONTRIBUTORS=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" https://api.github.com/repos/${{ github.repository }}/contributors | jq -r '.[].login') + echo "::set-output name=contributors::$CONTRIBUTORS" + + - name: Count Open Issues for Each Contributor + id: count-issues + run: | + for contributor in ${{ steps.retrieve-contributors.outputs.contributors }}; do + ISSUE_COUNT=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" "https://api.github.com/search/issues?q=is:open+author:${contributor}+repo:${{ github.repository }}" | jq -r '.total_count') + echo "::set-output name=${contributor}_issue_count::$ISSUE_COUNT" + done + + - name: Check Contributor's Open Issues Count + run: | + contributor=${{ github.event.pull_request.user.login }} + issue_count=${{ steps.count-issues.outputs["${contributor}_issue_count"] }} + if [ "$issue_count" -ge 4 ]; then + echo "Contributor $contributor has $issue_count open issues. Please complete your existing open issues before creating a new one." + exit 1 + fi diff --git a/.github/workflows/release-package.yml b/.github/workflows/release-package.yml new file mode 100644 index 0000000..902b75a --- /dev/null +++ b/.github/workflows/release-package.yml @@ -0,0 +1,33 @@ +name: CodeHarborHub Package + +on: + release: + types: [created] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 16 + - run: npm ci + - run: npm test + + publish-gpr: + needs: build + runs-on: ubuntu-latest + permissions: + packages: write + contents: read + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 16 + registry-url: https://npm.pkg.github.com/ + - run: npm ci + - run: npm publish + env: + NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}} diff --git a/.github/workflows/test-deploy.yml b/.github/workflows/test-deploy.yml new file mode 100644 index 0000000..e6921d7 --- /dev/null +++ b/.github/workflows/test-deploy.yml @@ -0,0 +1,26 @@ +name: Test deployment + +on: + pull_request: + branches: + - main + # Review gh actions docs if you want to further define triggers, paths, etc + # https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#on + +jobs: + test-deploy: + name: Test deployment + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-node@v4 + with: + node-version: 18 + cache: npm + + - name: Install dependencies + run: npm install --frozen-lockfile + - name: Test build website + run: npm run build diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b083ed4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +# Dependencies +/node_modules + +# Production +/build + +# Generated files +.docusaurus +.cache-loader + +# Misc +.DS_Store +.env +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..5fe5041 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +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. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +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. + +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 to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and 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. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +Email. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**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. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**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. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**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. + +### 4. Permanent Ban + +**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. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..cceac95 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,136 @@ +# Contributing to CodeHarborHub + +Thank you for considering contributing to Code Harbor Hub! We welcome contributions from everyone. + +## How to Contribute + +To contribute to this project, please follow these steps: + +1. **Fork** the repository by clicking on the "Fork" button on the top right corner of this page. +2. **Clone** your fork of the repository to your local machine: + + ```bash + git clone https://github.com/your-username/codeharborhub.git + ``` + +3. **Create a new branch** for your changes: + + ```bash + git checkout -b my-contribution + ``` + +4. **Make your changes** and commit them to your branch: + + ```bash + git commit -am "Add your commit message here" + ``` + +5. **Push** your changes to your fork: + + ```bash + git push origin my-contribution + ``` + +6. Submit a **Pull Request** (PR) to the `main` branch of the original repository. Ensure that your PR includes a clear description of the changes you've made and any relevant information about your contribution. + +### Alternatively contribute using GitHub Desktop + +1. **Open GitHub Desktop:** + Launch GitHub Desktop and log in to your GitHub account if you haven't already. + +2. **Clone the Repository:** + - If you haven't cloned the CodeHarborHub repository yet, you can do so by clicking on the "File" menu and selecting "Clone Repository." + - Choose the CodeHarborHub repository from the list of repositories on GitHub and clone it to your local machine. + +3. **Switch to the Correct Branch:** + - Ensure you are on the branch that you want to submit a pull request for. + - If you need to switch branches, you can do so by clicking on the "Current Branch" dropdown menu and selecting the desired branch. + +4. **Make Changes:** + Make your changes to the code or files in the repository using your preferred code editor. + +5. **Commit Changes:** + - In GitHub Desktop, you'll see a list of the files you've changed. Check the box next to each file you want to include in the commit. + - Enter a summary and description for your changes in the "Summary" and "Description" fields, respectively. Click the "Commit to " button to commit your changes to the local branch. + +6. **Push Changes to GitHub:** + After committing your changes, click the "Push origin" button in the top right corner of GitHub Desktop to push your changes to your forked repository on GitHub. + +7. **Create a Pull Request:** + - Go to the GitHub website and navigate to your fork of the CodeHarborHub repository. + - You should see a button to "Compare & pull request" between your fork and the original repository. Click on it. + +8. **Review and Submit:** + - On the pull request page, review your changes and add any additional information, such as a title and description, that you want to include with your pull request. + - Once you're satisfied, click the "Create pull request" button to submit your pull request. + +9. **Wait for Review:** + Your pull request will now be available for review by the project maintainers. They may provide feedback or ask for changes before merging your pull request into the main branch of the CodeHarborHub repository. + +⭐️ Support the Project +If you find this project helpful, please consider giving it a star on GitHub! Your support helps to grow the project and reach more contributors. + + +## Code Style +Please adhere to the coding style guidelines used in this project. Consistent coding style helps make the codebase more maintainable and readable for everyone. + + +## Testing +Before submitting a PR, ensure that your changes pass any relevant tests. If you're adding new features or fixing bugs, consider adding tests to cover the changes you've made. + + +## Pull Request Process +1.Ensure that you have self reviewed your code. +2.Make sure you have added the proper description for the functionality of the code. +3.I have commented my code, particularly in hard-to-understand areas. +4.Add screenshot it help in review. +5.Submit your PR by giving the necesarry information in PR template and hang tight we will review it really soon. + + +## Community Guidelines +We expect all contributors to adhere to the following community guidelines: + +1.Be respectful and considerate towards others. +2.Use inclusive language and promote a welcoming environment. +3.Avoid personal attacks, harassment, or discrimination. +4.Keep discussions on-topic and constructive. +5.Help others and contribute positively to the community. + + +## Resources for Guidance +Here are some resources that may be helpful as you contribute to Code Harbor Hub: +- [Docusaurus Documentation](https://docusaurus.io/docs/docs-introduction) +- [React.js Documentation](https://legacy.reactjs.org/docs/getting-started.html) +- [Markdown Guide](https://www.markdownguide.org/) +- [MDX Documentation](https://mdxjs.com/docs/) +- [Mermaid Documentation](https://mermaid.js.org/) + + +## Code Reviews +Be open to feedback and constructive criticism from other contributors. +Participate in code reviews by reviewing and providing feedback. + + +## Feature Requests +Suggest new features or improvements that you believe would enhance the project. + +## Contributing Guidelines +Issue Creation Limit +Each contributor is allowed to create up to 4 issues per day. If a contributor exceeds this limit, any additional issues beyond the fourth will be closed automatically. +Please adhere to this guideline to ensure a manageable and productive workflow for all participants. + + +## Code of Conduct +By participating in this project, you agree to abide by our [Code of Conduct](CODE_OF_CONDUCT.md). Please ensure that all interactions are respectful and constructive. + + +## Spread the Word +Share your experience and the project with others. +Spread the word about the project on social media, developer forums, or any relevant community platforms. +Thank you for your valuable contribution and for being a part of the Clueless Community! Together, we can make a difference. + + +## Questions or Need Help? +If you have any questions about contributing or need assistance with anything, feel free to reach out to us by opening an issue or contacting one of the maintainers listed in the `README.md` file. + +Thank you for contributing to CodeHarborHub! diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..bc875f6 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +FROM node:22-alpine AS builder + +WORKDIR /app + +COPY package*.json ./ +RUN npm install + +COPY . . + +RUN npm run build + +FROM nginx:alpine AS nginx + +COPY --from=builder /app/build /usr/share/nginx/html + +EXPOSE 80 + +CMD ["nginx", "-g", "daemon off;"] \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..1846d1f --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 CodeHarborHub + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Learn.md b/Learn.md new file mode 100644 index 0000000..0c45467 --- /dev/null +++ b/Learn.md @@ -0,0 +1,41 @@ +# CodeHarbourHub +Visit our website [CodeHarbourHub](https://www.codeharborhub.live/) + +## Table of Contents + +- [Introduction](#introduction) +- [Features](#features) +- [Contributing Guidelines](#contributing-guidelines) +- [Code of Conduct](#code-of-conduct) +- [Socials](#socials) + +## Introduction + +Welcome to "CodeHarbourHub" - Our mission at CodeHarbourHub to provide accessible and comprehensive educational resources to learners of all levels, from Beginners learners to Advanced professionals. +We're the exclusive platform offering a comprehensive tech curriculum, taught by industry masters, completely free. Join our vibrant community, master in-demand skills, and launch your dream tech career. + +## Features +- **In-Depth Tutorials**: Dive into comprehensive tutorials covering a wide range of programming languages like C++, Java, Python, JavaScript and Typescript and frameworks like ReactJS along with Data Structures and Algorithms. +![](/assets/Tutorials.png) + +- **Courses for Mastery**: Enroll in structured courses designed to take your skills to the next level. They range from learning a particular language and implementing them hands-on as projects to enhance learning. +![](/assets/Courses.png) + +- **Inspiring Showcases**: Explore inspiring showcases of real-world projects and innovative web solutions. +![](/assets/Showcase.png) + +- **Engaging Community**: Connect with a vibrant community of developers, share knowledge, and collaborate on projects. +![](/assets/Community.png) + +## Contributing Guidelines + +For the enthusiasts who want to contribute to CodeHarbourHub, please refer to our [Contributing Guildelines](https://github.com/CodeHarborHub/codeharborhub/blob/main/CONTRIBUTING.md) + +## Code of Conduct + +For all the enthusiastic contributers, please refer to the [Code of Conduct](https://github.com/CodeHarborHub/codeharborhub/blob/main/CODE_OF_CONDUCT.md) + +## Socials +Stay updated with the latest news and announcements: +- [LinkedIn](https://www.linkedin.com/groups/14232119/) +- [Twitter](https://twitter.com/CodesWithAjay) diff --git a/README.md b/README.md new file mode 100644 index 0000000..de36a31 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# CodeHarborHub DSA - Data Structures and Algorithms + +Welcome to the CodeHarborHub DSA repository. This repository is a collection of data structures and algorithms. The repository is divided into three main sections: + +1. DSA Docs: This section contains the documentation of the data structures and algorithms. The documentation is written in markdown format and is divided into different sections. The documentation is written in a simple and easy-to-understand language. +2. DSA Problems: This section contains the problems related to data structures and algorithms. The problems are divided into different categories and are written in a simple and easy-to-understand language. +3. DSA Solutions: This section contains the solutions to the problems related to data structures and algorithms. The solutions are written in different programming languages and are divided into different categories. + +The main goal of this repository is to provide a comprehensive collection of data structures and algorithms. The repository is open to contributions from the community. If you have any suggestions or feedback, feel free to create an issue or a pull request. \ No newline at end of file diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..034e848 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Use this section to tell people about which versions of your project are +currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 5.1.x | :white_check_mark: | +| 5.0.x | :x: | +| 4.0.x | :white_check_mark: | +| < 4.0 | :x: | + +## Reporting a Vulnerability + +Use this section to tell people how to report a vulnerability. + +Tell them where to go, how often they can expect to get an update on a +reported vulnerability, what to expect if the vulnerability is accepted or +declined, etc. diff --git a/admin/scripts/formatLighthouseReport.js b/admin/scripts/formatLighthouseReport.js new file mode 100644 index 0000000..56e829f --- /dev/null +++ b/admin/scripts/formatLighthouseReport.js @@ -0,0 +1,88 @@ +// @ts-check + +/** + * @typedef {Record<'performance' | 'accessibility' | 'best-practices' | 'seo', + * number>} LighthouseSummary + */ + +/** @type {Record} */ +const summaryKeys = { + performance: "Performance", + accessibility: "Accessibility", + "best-practices": "Best Practices", + seo: "SEO", +}; + +/** @param {number} rawScore */ +const scoreEntry = (rawScore) => { + const score = Math.round(rawScore * 100); + const scoreIcon = score >= 90 ? "🟒" : score >= 50 ? "🟑" : "πŸ”΄"; + return `${scoreIcon} ${score}`; +}; + +/** + * @param {string} url + * @returns {module:url.URL} + */ +function createURL(url) { + try { + return new URL(url); + } catch (e) { + throw new Error(`Can't create URL for string=${url}`, { cause: e }); + } +} + +/** + * @param {Object} param0 + * @param {string} param0.url + * @param {LighthouseSummary} param0.summary + * @param {string} param0.reportUrl + */ +const createMarkdownTableRow = ({ url, summary, reportUrl }) => + [ + `| [${createURL(url).pathname}](${url})`, + .../** @type {(keyof LighthouseSummary)[]} */ ( + Object.keys(summaryKeys) + ).map((k) => scoreEntry(summary[k])), + `[πŸ“„](${reportUrl}) |`, + ].join(" | "); + +const createMarkdownTableHeader = () => [ + ["| URL 🌐", ...Object.values(summaryKeys), "πŸ“Š |"].join(" | "), + ["|---", ...Array(Object.keys(summaryKeys).length).fill("---"), "---|"].join( + "|", + ), +]; + +/** + * @param {Object} param0 + * @param {Record} param0.links + * @param {{url: string, summary: LighthouseSummary}[]} param0.results + */ +const createLighthouseReport = ({ results, links }) => { + const tableHeader = createMarkdownTableHeader(); + const tableBody = results.map((result) => { + const testUrl = /** @type {string} */ ( + Object.keys(links).find((key) => key === result.url) + ); + const reportPublicUrl = /** @type {string} */ (links[testUrl]); + + return createMarkdownTableRow({ + url: testUrl, + summary: result.summary, + reportUrl: reportPublicUrl, + }); + }); + const comment = [ + "### ⚑️ Lighthouse Report for the Deploy Preview of this PR πŸš€", + "", + "πŸ”— Site: [CodeHarborHub](https://github.com/CodeHarborHub/codeharborhub.github.io) | [Live Site](https://codeharborhub.github.io/)", + "", + ...tableHeader, + ...tableBody, + "", + ]; + return comment.join("\n"); +}; + +export default createLighthouseReport; diff --git a/admin/scripts/package.json b/admin/scripts/package.json new file mode 100644 index 0000000..89eb29c --- /dev/null +++ b/admin/scripts/package.json @@ -0,0 +1,13 @@ +{ + "name": "chh-scripts", + "description": "These are the scripts used in various places of CodeHarborHub to automate tasks.", + "private": true, + "license": "MIT", + "type": "module", + "version": "1.0.0", + "main": "formatLighthouseReport.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "ajay-dhangar" +} diff --git a/assets/606 ex1.png b/assets/606 ex1.png new file mode 100644 index 0000000..e020ae9 Binary files /dev/null and b/assets/606 ex1.png differ diff --git a/assets/606 ex2.png b/assets/606 ex2.png new file mode 100644 index 0000000..07410af Binary files /dev/null and b/assets/606 ex2.png differ diff --git a/assets/Aho_Corasick_algo.png b/assets/Aho_Corasick_algo.png new file mode 100644 index 0000000..761ba75 Binary files /dev/null and b/assets/Aho_Corasick_algo.png differ diff --git a/assets/Avl-Tree.png b/assets/Avl-Tree.png new file mode 100644 index 0000000..68fa46b Binary files /dev/null and b/assets/Avl-Tree.png differ diff --git a/assets/Boyer_Moore_algo.png b/assets/Boyer_Moore_algo.png new file mode 100644 index 0000000..cc139a2 Binary files /dev/null and b/assets/Boyer_Moore_algo.png differ diff --git a/assets/Burrows_Wheeler_Transform.png b/assets/Burrows_Wheeler_Transform.png new file mode 100644 index 0000000..e9f94b9 Binary files /dev/null and b/assets/Burrows_Wheeler_Transform.png differ diff --git a/assets/Community.png b/assets/Community.png new file mode 100644 index 0000000..16bf81d Binary files /dev/null and b/assets/Community.png differ diff --git a/assets/Courses.png b/assets/Courses.png new file mode 100644 index 0000000..e4ff2bc Binary files /dev/null and b/assets/Courses.png differ diff --git a/assets/Hash-Table-Search.png b/assets/Hash-Table-Search.png new file mode 100644 index 0000000..dd0eb1b Binary files /dev/null and b/assets/Hash-Table-Search.png differ diff --git a/assets/Jump_Search.jpg b/assets/Jump_Search.jpg new file mode 100644 index 0000000..5520401 Binary files /dev/null and b/assets/Jump_Search.jpg differ diff --git a/assets/KMP_algo.png b/assets/KMP_algo.png new file mode 100644 index 0000000..eefa8c2 Binary files /dev/null and b/assets/KMP_algo.png differ diff --git a/assets/LinearSearch_GFG.webp b/assets/LinearSearch_GFG.webp new file mode 100644 index 0000000..a8d1c4a Binary files /dev/null and b/assets/LinearSearch_GFG.webp differ diff --git a/assets/Manachers_Algorithm.png b/assets/Manachers_Algorithm.png new file mode 100644 index 0000000..0a6acc4 Binary files /dev/null and b/assets/Manachers_Algorithm.png differ diff --git a/assets/Naive_Pattern_Matching_algo.png b/assets/Naive_Pattern_Matching_algo.png new file mode 100644 index 0000000..707c0f9 Binary files /dev/null and b/assets/Naive_Pattern_Matching_algo.png differ diff --git a/assets/Screenshot 2024-06-16 145014.png b/assets/Screenshot 2024-06-16 145014.png new file mode 100644 index 0000000..a8b4a3c Binary files /dev/null and b/assets/Screenshot 2024-06-16 145014.png differ diff --git a/assets/Showcase.png b/assets/Showcase.png new file mode 100644 index 0000000..ad3de60 Binary files /dev/null and b/assets/Showcase.png differ diff --git a/assets/Tutorials.png b/assets/Tutorials.png new file mode 100644 index 0000000..53f7b76 Binary files /dev/null and b/assets/Tutorials.png differ diff --git a/assets/bb1.png b/assets/bb1.png new file mode 100644 index 0000000..9b264c9 Binary files /dev/null and b/assets/bb1.png differ diff --git a/assets/bb2.png b/assets/bb2.png new file mode 100644 index 0000000..c333b3a Binary files /dev/null and b/assets/bb2.png differ diff --git a/assets/bb3.png b/assets/bb3.png new file mode 100644 index 0000000..f7e2906 Binary files /dev/null and b/assets/bb3.png differ diff --git a/assets/binnary-search-.webp b/assets/binnary-search-.webp new file mode 100644 index 0000000..a7fcaed Binary files /dev/null and b/assets/binnary-search-.webp differ diff --git a/assets/ford.png b/assets/ford.png new file mode 100644 index 0000000..64ac672 Binary files /dev/null and b/assets/ford.png differ diff --git a/assets/ford2.png b/assets/ford2.png new file mode 100644 index 0000000..635681b Binary files /dev/null and b/assets/ford2.png differ diff --git a/assets/knnclassifier.png b/assets/knnclassifier.png new file mode 100644 index 0000000..5249cdb Binary files /dev/null and b/assets/knnclassifier.png differ diff --git a/assets/kthNearest.png b/assets/kthNearest.png new file mode 100644 index 0000000..9c4e891 Binary files /dev/null and b/assets/kthNearest.png differ diff --git a/assets/random1.png b/assets/random1.png new file mode 100644 index 0000000..2d8324f Binary files /dev/null and b/assets/random1.png differ diff --git a/assets/random2.png b/assets/random2.png new file mode 100644 index 0000000..32b277a Binary files /dev/null and b/assets/random2.png differ diff --git a/assets/random3.png b/assets/random3.png new file mode 100644 index 0000000..022ff04 Binary files /dev/null and b/assets/random3.png differ diff --git a/assets/tsp.png b/assets/tsp.png new file mode 100644 index 0000000..09550ea Binary files /dev/null and b/assets/tsp.png differ diff --git a/babel.config.js b/babel.config.js new file mode 100644 index 0000000..e00595d --- /dev/null +++ b/babel.config.js @@ -0,0 +1,3 @@ +module.exports = { + presets: [require.resolve('@docusaurus/core/lib/babel/preset')], +}; diff --git a/config.json b/config.json new file mode 100644 index 0000000..222eba7 --- /dev/null +++ b/config.json @@ -0,0 +1,48 @@ +{ + "index_name": "ajay-dhangario", + "start_urls": [ + "https://ajay-dhangar.github.io/" + ], + "sitemap_urls": [ + "https://ajay-dhangar.github.io/sitemap.xml" + ], + "sitemap_alternate_links": true, + "stop_urls": [], + "selectors": { + "lvl0": { + "selector": "(//ul[contains(@class,'menu__list')]//a[contains(@class, 'menu__link menu__link--sublist menu__link--active')]/text() | //nav[contains(@class, 'navbar')]//a[contains(@class, 'navbar__link--active')]/text())[last()]", + "type": "xpath", + "global": true, + "default_value": "Documentation" + }, + "lvl1": "header h1", + "lvl2": "article h2", + "lvl3": "article h3", + "lvl4": "article h4", + "lvl5": "article h5, article td:first-child", + "lvl6": "article h6", + "text": "article p, article li, article td:last-child" + }, + "strip_chars": " .,;:#", + "custom_settings": { + "separatorsToIndex": "_", + "attributesForFaceting": [ + "language", + "version", + "type", + "docusaurus_tag" + ], + "attributesToRetrieve": [ + "hierarchy", + "content", + "anchor", + "url", + "url_without_anchor", + "type" + ] + }, + "conversation_id": [ + "833762294" + ], + "nb_hits": 46250 +} diff --git a/deployment-app.yml b/deployment-app.yml new file mode 100644 index 0000000..c435aca --- /dev/null +++ b/deployment-app.yml @@ -0,0 +1,22 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + # Unique key of the Deployment instance + name: my-node-app +spec: + # 2 Pods should exist at all times. + replicas: 2 + selector: + matchLabels: + app: node-app + template: + metadata: + labels: + # Apply this label to pods and default + # the Deployment label selector to this value + app: node-app + spec: + containers: + - name: node-app + # Run this image + image: #put your image name which you push in dockerhub diff --git a/docs/Advance/Approximation algorithms.md b/docs/Advance/Approximation algorithms.md new file mode 100644 index 0000000..0f46cb4 --- /dev/null +++ b/docs/Advance/Approximation algorithms.md @@ -0,0 +1,130 @@ +--- +id: approximation-algorithm +title: Approximation Algorithm +sidebar_label: Approximation Algorithm +tags: + - Approximation Algorithm + - data-structures + - advance + - javascript + - python + - c++ + - java + - programming +sidebar_position: 11 +--- + +## Approximation Algorithm + +An approximation algorithm is a way of dealing with NP-completeness for an optimization problem. This technique does not guarantee the best solution. The goal of the approximation algorithm is to come as close as possible to the optimal solution in polynomial time. Such algorithms are called approximation algorithms or heuristic algorithms. + +## Features of Approximation Algorithm : + +Here, we will discuss the features of the Approximation Algorithm as follows. + +- An approximation algorithm guarantees to run in polynomial time though it does not guarantee the most effective solution. +- An approximation algorithm guarantees to seek out high accuracy and top quality solution(say within 1% of optimum) +- Approximation algorithms are used to get an answer near the (optimal) solution of an optimization problem in polynomial time + +## Performance Ratios for approximation algorithms : + +Here, we will discuss the performance ratios of the Approximation Algorithm as follows. + +1. Scenario-1 : + +Suppose that we are working on an optimization problem in which each potential solution has a cost, and we wish to find a near-optimal solution. Depending on the problem, we may define an optimal solution as one with maximum possible cost or one with minimum possible cost,i.e, the problem can either be a maximization or minimization problem. + +We say that an algorithm for a problem has an appropriate ratio of P(n) if, for any input size n, the cost C of the solution produced by the algorithm is within a factor of P(n) of the cost C\* of an optimal solution as follows. + +``` +max(C/C*,C*/C)<=P(n) +``` + +2. Scenario-2 : + +If an algorithm reaches an approximation ratio of P(n), then we call it a P(n)-approximation algorithm. + +For a maximization problem, 0< C < C*, and the ratio of C*/C gives the factor by which the cost of an optimal solution is larger than the cost of the approximate algorithm. + +For a minimization problem, 0< C* < C, and the ratio of C/C* gives the factor by which the cost of an approximate solution is larger than the cost of an optimal solution. + +## Some examples of the Approximation algorithm : + +Here, we will discuss some examples of the Approximation Algorithm as follows. + +1. The Vertex Cover Problem – + In the vertex cover problem, the optimization problem is to find the vertex cover with the fewest vertices, and the approximation problem is to find the vertex cover with few vertices. + +2. Travelling Salesman Problem – + In the traveling salesperson problem, the optimization problem is to find the shortest cycle, and the approximation problem is to find a short cycle. + +3. The Set Covering Problem – + This is an optimization problem that models many problems that require resources to be allocated. Here, a logarithmic approximation ratio is used. + +4. The Subset Sum Problem – + In the Subset sum problem, the optimization problem is to find a subset of x1,Γ—2,Γ—3…xn whose sum is as large as possible but not larger than the target value t. + +## Techniques for Designing Approximation Algorithms + +Several techniques are commonly used to design approximation algorithms. Here are a few: + +- Greedy Algorithms + Greedy algorithms build up a solution piece by piece, always choosing the next piece that offers the most immediate benefit. While they don't always produce the optimal solution, they can often get close. + +### Example: + +The Knapsack Problem +In the fractional knapsack problem, a greedy algorithm can be used to achieve the optimal solution. The algorithm sorts items by their value-to-weight ratio and then picks items with the highest ratio first. + +- Local Search + Local search algorithms start with an initial solution and iteratively make small adjustments to improve it. This process continues until no further improvements can be made. + +### Example: + +The k-Center Problem +Local search can be used for the k-center problem, where the goal is to select k centers to minimize the maximum distance from any point to its nearest center. The algorithm starts with an arbitrary set of centers and repeatedly swaps out centers to reduce the maximum distance. + +- Dynamic Programming + Dynamic programming breaks down a problem into simpler subproblems and solves each subproblem just once, storing the solutions. + +### Example: + +The Traveling Salesman Problem (TSP) +For the TSP, a dynamic programming approach can be combined with a heuristic to find an approximate solution. For instance, using the Held-Karp algorithm provides a lower bound, which can then be improved with heuristics like nearest neighbor or Christofides' algorithm. + +- Linear Programming and Rounding + This technique involves solving a linear programming relaxation of the problem and then rounding the solution to obtain an integer solution. + +### Example: + +The Set Cover Problem +In the set cover problem, you can solve the linear programming relaxation and then use a rounding technique to get an integer solution. The approximation ratio for this method is O(logn), where n is the number of elements to be covered. + +## Approximation Schemes + +- Polynomial-Time Approximation Scheme (PTAS) +A PTAS is an algorithm that takes an input Ο΅ and produces a solution that is within (1+Ο΅) of the optimal solution in polynomial time for any fixed Ο΅. + +## Example: +The Euclidean TSP +For the Euclidean TSP, there exists a PTAS that can find a solution within (1+Ο΅) of the optimal solution in polynomial time. + +- Fully Polynomial-Time Approximation Scheme (FPTAS) +An FPTAS is a stronger version of PTAS that runs in polynomial time in both the input size and 1/πœ– + +## Example: +The Knapsack Problem +For the 0/1 knapsack problem, an FPTAS can be used to find a solution that is within (1+Ο΅) of the optimal solution in time polynomial in both the number of items and 1/πœ– + +## Applications of Approximation Algorithms + +Approximation algorithms are crucial in various fields where exact solutions are computationally infeasible: + +- Network Design +In network design, problems like the minimum spanning tree, Steiner tree, and network flow optimization often rely on approximation algorithms to provide near-optimal solutions efficiently. + +- Resource Allocation +Approximation algorithms help in efficiently allocating resources in problems like scheduling, bin packing, and load balancing. + +- Data Analysis +In large-scale data analysis, problems such as clustering and dimensionality reduction are often tackled using approximation techniques to handle massive datasets within reasonable time frames. diff --git a/docs/Advance/Backtracking.md b/docs/Advance/Backtracking.md new file mode 100644 index 0000000..0707dbb --- /dev/null +++ b/docs/Advance/Backtracking.md @@ -0,0 +1,456 @@ +--- +id: 03-Backtracking +title: Introduction to Backtracking +sidebar_label: Backtracking in DSA +tags: + - Backtracking + - data-structures + - binary-tree + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial +sidebar_position: 3 +--- + +## Backtracking + + Backtracking is a form of recursion. + + The usual scenario is that you are faced with a number of option, and you must choose one of these. After you make your choice you will get a new set of options; just what set of options you get depends on what choice you made. This procedure is repeated over and until you reach a final state. If you made a good sequence of choices, your final state is a goal state; If you didn't, it isn't. + + Conceptually, you start at the root of a tree; the tree probably has some good leaves and some bad leaves, though it maybe that the leaves are all good or all bad. You want to get to a good leaf. At each node, beginning with the root, you choose one of its children to move to, and you keep this up until you get to a leaf. + + Suppose you get to a bad leaf. You can backtrackto continue the search for a good leaf by revoking your most recent choice, and trying out the next option in that set of options. If you run out of options, revoke the choice that got you here, and try another choice at that node. If you end up at the root with no options left, there are no good leaves to be found. + + This needs an example: + + ![alt text](image-3.png) + + 1. Starting at Root, your options are A and B. You choose A. + + 2. At A, your options are C and D. You choose C. + + 3. C is bad. Go back to A. + + 4. At A, you have already tried C, and it failed. Try D. + + 5. D is bad. Go back to A. + + 6. At A, you have no options left to try. Go back to Root. + + 7. At Root, you have already tried A. Try B. + + 8. At B, your options are E and F. Try E. + + 9. E is good. Congratulations! + + "In this example we drew a picture of a tree. The tree is an abstract model of the possible sequences of choices we could make. There is also a data structure called a tree, but usually we don't have a data structure to tell us what choices we have. (If we do have an actual tree data structure, backtracking on it is called depth-first tree searching.)" + +## The backtracking algorithm. + +``` + boolean solve(Node n) { + if n is a leaf node { + if the leaf is a goal node, + return true else return false + } else { + for each child c of n { + if solve(c) + succeeds, return true + } + return false + } + } +``` + +" Notice that the algorithm is expressed as a boolean function. This is essential to understanding the algorithm. If solve(n) is true, that means node n is part of a solution--that is, node n is one of the nodes on a path from the root to some goal node. We say that n is solvable. If solve(n) is false, then there is no path that includes n to any goal node. " + +## How does this work? + + 1) If any child of n is solvable, then n is solvable. + 2) If no child of n is solvable, then n is not solvable. + +Hence, to decide whether any non-leaf node n is solvable (part of a path to a goal node), all you have to do is test whether any child of n is solvable. This is done recursively, on each child of n. In the above code, this is done by the lines + +``` +for each child c of n { + if solve(c) succeeds, return true + } + return false +``` + +Eventually the recursion will "bottom" out at a leaf node. If the leaf node is a goal node, it is solvable; if the leaf node is not a goal node, it is not solvable. This is our base case. In the above code, this is done by the lines + +``` + if n is a leaf node { + if the leaf is a goal node, return true + else return false + } +``` + +The backtracking algorithm is simple but important. You should understand it thoroughly. Another way of stating it is as follows: + +## To search a tree: + +1. If the tree consists of a single leaf, test whether it is a goal node. +2. Otherwise, search the subtrees until you find one containing a goal node, or until you have searched them all unsuccessfully. + +## Non-recursive backtracking, using a stack + +Backtracking is a rather typical recursive algorithm, and any recursive algorithm can be rewritten as a stack algorithm. In fact, that is how your recursive algorithms are translated into machine or assembly language. + +``` + boolean solve(Node n) { + put node n on the stack; + while the stack is not empty { + if the node at the top of the stack is a leaf { + if it is a goal node, return true + else pop it off the stack + } + else { + if the node at the top of the stack has untried children + push the next untried child onto the stack + else pop the node off the stack + } + return false + } + } +``` + +Starting from the root, the only nodes that can be pushed onto the stack are the children of the node currently on the top of the stack, and these are only pushed on one child at a time; hence, the nodes on the stack at all times describe a valid path in the tree. Nodes are removed from the stack only when it is known that they have no goal nodes among their descendents. Therefore, if the root node gets removed (making the stack empty), there must have been no goal nodes at all, and no solution to the problem. + +When the stack algorithm terminates successfully, the nodes on the stack form (in reverse order) a path from the root to a goal node. + +Similarly, when the recursive algorithm finds a goal node, the path information is embodied (in reverse order) in the sequence of recursive calls. Thus as the recursion unwinds, the path can be recovered one node at a time, by (for instance) printing the node at the current level, or storing it in an array. + +Here is the recursive backtracking algorithm, modified slightly to print (in reverse order) the nodes along the successful path: + +``` + boolean solve(Node n) { + if n is a leaf node { + if the leaf is a goal node { + print n return true + } + else return false + } + else { + for each child c of n { + if solve(c) succeeds { + print n return true + } + } + return false + } + } +``` + +## Keeping backtracking simple + +All of these versions of the backtracking algorithm are pretty simple, but when applied to a real problem, they can get pretty cluttered up with details. Even determining whether the node is a leaf can be complex: + +for example, if the path represents a series of moves in a chess endgame problem, the leaves are the checkmate and stalemate solutions + +To keep the program clean, therefore, tests like this should be buried in methods. In a chess game, for example, you could test whether a node is a leaf by writing a gameOver method (or you could even call it isLeaf). This method would encapsulate all the ugly details of figuring out whether any possible moves remain. + +Notice that the backtracking altorithms require us to keep track, for each node on the current path, which of its children have been tried already (so we don't have to try them again). In the above code we made this look simple, by just saying for each child c of n. In reality, it may be difficult to figure out what the possible children are, and there may be no obvious way to step through them. In chess, for example, a node can represent one arrangement of pieces on a chessboard, and each child of that node can represent the arrangement after some piece has made a legal move. How do you find these children, and how do you keep track of which ones you've already examined? + +The most straightforward way to keep track of which children of the node have been tried is as follows: Upon initial entry to the node (that is, when you first get there from above), make a list of all its children. As you try each child, take it off the list. When the list is empty, there are no remaining untried children, and you can return "failure." This is a simple approach, but it may require quite a lot of additional work. + +There is an easier way to keep track of which children have been tried, if you can define an ordering on the children. If there is an ordering, and you know which child you just tried, you can determine which child to try next. + +For example, you might be able to number the children 1 through n, and try them in numerical order. Then, if you have just tried child k, you know that you have already tried children 1 through k-1, and you have not yet tried children k+1 through n. Or, if you are trying to color a map with just four colors, you can always try red first, then yellow, then green, then blue. If child yellow fails, you know to try child green next. If you are searching a maze, you can try choices in the order left, straight, right (or perhaps north, east, south, west). + +It isn't always easy to find a simple way to order the children of a node. In the chess game example, you might number your pieces (or perhaps the squares of the board) and try them in numerical order; but in addition each piece may also have several moves, and these must also be ordered. You can probably find some way to order the children of a node. If the ordering scheme is simple enough, you should use it; but if it is too cumbersome, you are better off keeping a list of untried children. + +## Example: Tree Search + +For starters, let's do the simplest possible example of backtracking, which is searching an actual tree. We will also use the simplest kind of tree, a binary tree. + +A binary tree is a data structure composed of nodes. One node is designated as the root node. Each node can reference (point to) zero, one, or two other nodes, which are called its children. The children are referred to as the left child and/or the right child. All nodes are reachable (by one or more steps) from the root node, and there are no cycles. For our purposes, although this is not part of the definition of a binary tree, we will say that a node might or might not be a goal node, and will contain its name. The first example in this paper (which we repeat here) shows a binary tree. + +Here's a definition of the BinaryTree class: + +``` +public class BinaryTree { + BinaryTree leftChild = null; + BinaryTree rightChild = null; + boolean isGoalNode = false; String name; + BinaryTree(String name, BinaryTree left, BinaryTree right, boolean isGoalNode) { + this.name = name; + leftChild = left; + rightChild = right; + this.isGoalNode = isGoalNode; + } + } +``` + +Next we will create a TreeSearch class, and in it we will define a method makeTree() which constructs the above binary tree. + +``` + static BinaryTree makeTree() { + BinaryTree root, a, b, c, d, e, f; + c = new BinaryTree("C", null, null, false); + d = new BinaryTree("D", null, null, false); + e = new BinaryTree("E", null, null, true); + f = new BinaryTree("F", null, null, false); + a = new BinaryTree("A", c, d, false); + b = new BinaryTree("B", e, f, false); + root = new BinaryTree("Root", a, b, false); + return root; + } +``` + +Here's a main program to create a binary tree and try to solve it: + +``` + public static void main(String args[]) { + BinaryTree tree = makeTree(); + System.out.println(solvable(tree)); + } +``` + +And finally, here's the recursive backtracking routine to "solve" the binary tree by finding a goal node. + +``` + static boolean solvable(BinaryTree node) { + /* 1 */ if (node == null) return false; + /* 2 */ if (node.isGoalNode) return true; + /* 3 */ if (solvable(node.leftChild)) return true; + /* 4 */ if (solvable(node.rightChild)) return true; + /* 5 */ return false; + } + +``` + +Here's what the numbered lines are doing: + + 1. If we are given a null node, it's not solvable. This statement is so that we can call this method with the children of a node, without first checking whether those children actually exist. + + 2. If the node we are given is a goal node, return success. + + 3. See if the left child of node is solvable, and if so, conclude that node is solvable. We will only get to this line if node is non-null and is not a goal node, says to + + 4. Do the same thing for the right child. + + 5. Since neither child of node is solvable, node itself is not solvable. + +This program runs correctly and produces the unenlightening result true. + +Each time we ask for another node, we have to check if it is null. In the above we put that check as the first thing in solvable. An alternative would be to check first whether each child exists, and recur only if they do. Here's that alternative version: + +``` +static boolean solvable(BinaryTree node) { + if (node.isGoalNode) return true; + if (node.leftChild != null && solvable(node. + leftChild)) + return true; + if (node.rightChild != null && solvable(node. + rightChild)) + return true; + return false; + } +``` + +I think the first version is simpler, but the second version is slightly more efficient. + +## What are the children? + +One of the things that simplifies the above binary tree search is that, at each choice point, you can ignore all the previous choices. Previous choices don't give you any information about what you should do next; as far as you know, both the left and the right child are possible solutions. In many problems, however, you may be able to eliminate children immediately, without recursion. + +Consider, for example, the problem of four-coloring a map. It is a theorem of mathematics that any map on a plane, no matter how convoluted the countries are, can be colored with at most four colors, so that no two countries that share a border are the same color. + +To color a map, you choose a color for the first country, then a color for the second country, and so on, until all countries are colored. + +There are two ways to do this: + + Method 1: + Try each of the four possible colors, and recur. When you run out of countries, check whether you are at a goal node. + + Method 2: + Try only those colors that have not already been used for an adjacent country, and recur. If and when you run out of countries, you have successfully colored the map. + +boolean mapIsOK() +Used by method 1 to check (at a leaf node) whether the entire map is colored correctly. + +boolean okToColor(int row, int column, int color) +Used by method 2 to check, at every node, whether there is an adjacent node already colored with the given color. + +int[] nextRowAndColumn(int row, int column) +Used by both methods to find the next "country" (actually, the row and column of the next square on the checkerboard). + +Here's the code for method 1: + +``` +boolean explore1(int row, int column, int color) { + if (row >= NUM_ROWS) + return mapIsOK(); + map[row][column] = color; + for (int nextColor = RED; nextColor <= BLUE; nextColor++) { + int[] next=nextRowAndColumn(row, column); + if(explore1(next[0],next[1],nextColor)) + return true; + } + return false; + } + +``` + +And here's the code for method 2: + +``` + boolean explore2(int row, int column, int color) { + if (row >= NUM_ROWS)return true; + if (okToColor(row, column, color)) { + map[row][column] = color; + for(int nextColor=RED; nextColor <=BLUE; nextColor++){ + int[] next = nextRowAndColumn(row, column); + if (explore2(next[0],next[1],nextColor)) + return true; + } + } + return false; + } +``` + +Those appear pretty similar, and you might think they are equally good. However, the timing information suggests otherwise: + +| | 2 by 3 map | 3 by 3 map | 3 by 4 map | +| --------- | ---------- | ---------- | ------------------- | +| Method 1: | 60 ms | 940 ms | 60530 ms (1 minute) | +| Method 2: | 0 ms | 0 ms | 0 ms | + +The zeros in the above table indicate times too short to measure (less than 1 millisecond). Why this huge difference? Either of these methods could have exponential growth. Eliminating a node automatically eliminates all of its descendents, and this will often prevent exponential growth. Conversely, by waiting to check until a leaf node is reached, exponential growth is practically guaranteed. If there is any way to eliminate children (reduce the set of choices), do so! + +## Debugging techniques + +Often our first try at a program doesn't work, and we need to debug it. Debuggers are helpful, but sometimes we need to fall back on inserting print statements. There are some simple tricks to making effective use of print statements. These tricks can be applied to any program, but are especially useful when you are trying to debug recursive routines. + +### Trick #1: Indent when you print method entries and exits. + +Often, the best debugging technique is to print every method call and return (or at least the most important ones). You probably want to print, for each method, what parameters it came in with, and what value it leaves with. However, if you just print a long list of these, it's hard to match up method exits with their corresponding entries. Indenting to show the level of nesting can help. + +### Trick #2: Use specialized print methods for debugging. + +Don't clutter up your actual code more than you must. Also, remember that code inserted for debugging purposes can itself contain bugs, or (in the worst case) can affect the results, so be very careful with it. + +Here's our debugging code. For this trivial program, there's almost more debugging code than actual code, but in larger programs the proportions will be better. + +``` +static String indent = ""; + static String name(BinaryTree node) { + if (node == null) return null; + else return node.name; + } + static void enter(BinaryTree node) { + System.out.println(indent + + "Entering solvable(" + name(node) + ")"); + indent = indent + "| "; + } + static boolean yes(BinaryTree node) { + indent = indent.substring(3); + System.out.println(indent + "solvable(" + name(node) + ") returns true"); + return true; + } + static boolean no(BinaryTree node) { + indent = indent.substring(3); + System.out.println(indent + "solvable(" + name(node) + ") returns false"); + return false; + } +``` + +To use this code, we modify solvable as follows: + +``` + static boolean solvable(BinaryTree node) { + enter(node); + if (node == null) return no(node); + if (node.isGoalNode) return yes(node); + if (solvable(node.leftChild)) return yes(node); + if (solvable(node.rightChild)) return yes(node); + return no(node); + } +``` + +And we get these results: + +``` + Entering solvable(Root) + | Entering solvable(A) + | | Entering solvable(C) + | | | Entering solvable(null) + | | | solvable(null) returns false + | | | Entering solvable(null) + | | | solvable(null) returns false + | | solvable(C) returns false + | | Entering solvable(D) + | | | Entering solvable(null) + | | | solvable(null) returns false + | | | Entering solvable(null) + | | | solvable(null) returns false + | | solvable(D) returns false + | solvable(A) returns false + | Entering solvable(B) + | | Entering solvable(E) + | | solvable(E) returns true + | solvable(B) returns true solvable(Root) returns true true + +``` + +### Trick #3: Never discard your debugging statements. + +Writing debugging statements is programming, too. Often it's as much work to debug the debugging statements as it is to debug the actual program. Once your program is working, why throw this code away? + +Obviously, you don't want to print out all this debugging information from a program you are ready to submit (or to turn over to your manager). You could comment out your debugging calls, but that can be a lot of work. What's more, in the above example, you would have to replace every return(yes(node)) with return(true), and every return(no(node)) with return false. With all these changes, you might introduce new bugs into your program. + +The simple solution is to make your debugging statements conditional. For example, + +``` + static final boolean debugging = false; + static void enter(BinaryTree node) { + if (debugging) { + System.out.println(indent + "Entering solvable(" + name(node) + ")"); + indent = indent + "| "; + } + } + static boolean yes(BinaryTree node) { + if (debugging) { + indent = indent.substring(3); + System.out.println(indent +"solvable(" + name(node) + ") returns true"); + } + return true; + } + static boolean no(BinaryTree node) { + if (debugging) { + indent = indent.substring(3); + System.out.println(indent +"solvable(" + name(node) + ") returns false"); + } + return false; + } +``` + +In industry, actual programs often have multiple flags to control different aspects of debugging. Don't worry too much about making your code larger; modern compilers will notice that since the variable debugging is final, it can never be true, and the controlled code will be discarded. + +### Trick #4: Create an Exception. + +If an Exception is thrown, you can get information about just where it happened by sending it the message printStackTrace(PrintStream). Since an Exception is an object like any other, you can create and throw your own Exceptions. However, Java programmers don't always realize that you can create an Exception without throwing it. For example, the following code + +``` + new Exception("Checkpoint + Charlie").printStackTrace(System.out); + +``` + +will print out a message something like this, and the program will then continue normally. That is, the above code just acts like a print statement. + +``` + java.lang.Exception: Checkpoint Charlie + at TreeSearch.solvable(TreeSearch.java:53) + at TreeSearch.solvable(TreeSearch.java:57) + at TreeSearch.main(TreeSearch.java:72) + at __SHELL38.run(__SHELL38.java:16) + at bluej.runtime.ExecServer.suspendExecution(Unknown Source) +``` diff --git a/docs/Advance/Backtracking_leetcode.md b/docs/Advance/Backtracking_leetcode.md new file mode 100644 index 0000000..3a76689 --- /dev/null +++ b/docs/Advance/Backtracking_leetcode.md @@ -0,0 +1,59 @@ +--- +id: 02-Leetcode Backtracking Practice Questions +title: Leetcode Backtracking Practice Questions +sidebar_label: Leetcode Backtracking Practice Questions +tags: + - Backtracking + - data-structures + - binary-tree + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial +sidebar_position: 3 +--- + +# Backtracking Problems on LeetCode + +1. [46. Permutations](https://leetcode.com/problems/permutations/) + +2. [47. Permutations II](https://leetcode.com/problems/permutations-ii/) + +3. [39. Combination Sum](https://leetcode.com/problems/combination-sum/) + +4. [40. Combination Sum II](https://leetcode.com/problems/combination-sum-ii/) + +5. [78. Subsets](https://leetcode.com/problems/subsets/) + +6. [90. Subsets II](https://leetcode.com/problems/subsets-ii/) + +7. [77. Combinations](https://leetcode.com/problems/combinations/) + +8. [216. Combination Sum III](https://leetcode.com/problems/combination-sum-iii/) + +9. [22. Generate Parentheses](https://leetcode.com/problems/generate-parentheses/) + +10. [51. N-Queens](https://leetcode.com/problems/n-queens/) + +11. [52. N-Queens II](https://leetcode.com/problems/n-queens-ii/) + +12. [79. Word Search](https://leetcode.com/problems/word-search/) + +13. [212. Word Search II](https://leetcode.com/problems/word-search-ii/) + +14. [131. Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) + +15. [93. Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) + +16. [17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) + +17. [282. Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) + +18. [491. Increasing Subsequences](https://leetcode.com/problems/increasing-subsequences/) + +19. [526. Beautiful Arrangement](https://leetcode.com/problems/beautiful-arrangement/) + +20. [254. Factor Combinations](https://leetcode.com/problems/factor-combinations/) diff --git a/docs/Advance/Branch and Bound.md b/docs/Advance/Branch and Bound.md new file mode 100644 index 0000000..5189edd --- /dev/null +++ b/docs/Advance/Branch and Bound.md @@ -0,0 +1,115 @@ +--- +id: branch-and-bound +title: Branch and Bound +sidebar_label: Branch and Bound in DSA +tags: + - Branch and Bound + - data-structures + - intermediate + - javascript + - python + - c++ + - java + - programming +sidebar_position: 8 +--- + +## Branch and Bound + +The Branch and Bound Algorithm is a method used in combinatorial optimization problems to systematically search for the best solution. It works by dividing the problem into smaller subproblems, or branches, and then eliminating certain branches based on bounds on the optimal solution. This process continues until the best solution is found or all branches have been explored. + +## How it works: + +Branch and bound is an algorithmic technique used in computer science to solve optimization problems. Branch and bound is a systematic way of exploring all possible solutions to a problem by dividing the problem space into smaller sub-problems and then applying bounds or constraints to eliminate certain subproblems from consideration. + +## Characteristics of Branch and Bound: + +- Optimal solution: The algorithm is designed to find the optimal solution to an optimization problem by searching the solution space in a systematic way. +- Upper and lower bounds: The algorithm uses upper and lower bounds to reduce the size of the search space and eliminate subproblems that cannot contain the optimal solution. +- Pruning: The algorithm prunes the search tree by eliminating subproblems that cannot contain the optimal solution or are not worth exploring further. +- Backtracking: The algorithm uses backtracking to return to a previous node in the search tree when a dead end is reached or when a better solution is found. + +## Different search techniques in branch and bound: + +The Branch algorithms incorporate different search techniques to traverse a state space tree. Different search techniques used in B&B are listed below: + +- LC search +- BFS +- DFS + +1. LC search (Least Cost Search): +It uses a heuristic cost function to compute the bound values at each node. Nodes are added to the list of live nodes as soon as they get generated. +The node with the least value of a cost function selected as a next E-node. + +2. BFS(Breadth First Search): +It is also known as a FIFO search. +It maintains the list of live nodes in first-in-first-out order i.e, in a queue, The live nodes are searched in the FIFO order to make them next E-nodes. + +3. DFS (Depth First Search): +It is also known as a LIFO search. +It maintains the list of live nodes in last-in-first-out order i.e. in a stack. +The live nodes are searched in the LIFO order to make them next E-nodes. + +## When to apply Branch and Bound Algorithm? + +Branch and bound is an effective solution to some problems, which we have already discussed. We’ll discuss all such cases where branching and binding are appropriate in this section. + +It is appropriate to use a branch and bound approach if the given problem is discrete optimization. Discrete optimization refers to problems in which the variables belong to the discrete set. Examples of such problems include 0-1 Integer Programming and Network Flow problems. + +When it comes to combinatory optimization problems, branch and bound work well. An optimization problem is optimized by combinatory optimization by finding its maximum or minimum based on its objective function. The combinatory optimization problems include Boolean Satisfiability and Integer Linear Programming. + +## Types of Branch and Bound Solutions: + +The solution of the Branch and the bound problem can be represented in two ways: + +Variable size solution: Using this solution, we can find the subset of the given set that gives the optimized solution to the given problem. For example, if we have to select a combination of elements from A, B, C, D that optimizes the given problem, and it is found that A and B together give the best solution, then the solution will be A, B. + +Fixed-size solution: There are 0s and 1s in this solution, with the digit at the ith position indicating whether the ith element should be included, for the above example, the solution will be given by 1, 1, 0, 0, here 1 represent that we have select the element which at ith position and 0 represent we don’t select the element at ith position. + +## Classification of Branch and Bound Problems: +The Branch and Bound method can be classified into three types based on the order in which the state space tree is searched. + +FIFO Branch and Bound +LIFO Branch and Bound +Least Cost-Branch and Bound + +1. FIFO Branch and Bound +First-In-First-Out is an approach to the branch and bound problem that uses the queue approach to create a state-space tree. In this case, the breadth-first search is performed, that is, the elements at a certain level are all searched, and then the elements at the next level are searched, starting with the first child of the first node at the previous level. + +For a given set A, B, C, D, the state space tree will be constructed as follows : + +![Example](../../assets/bb1.png) + +2. LIFO Branch and Bound +The Last-In-First-Out approach for this problem uses stack in creating the state space tree. When nodes are added to a state space tree, they are added to a stack. After all nodes of a level have been added, we pop the topmost element from the stack and explore it. + +For a given set A, B, C, D, the state space tree will be constructed as follows : + +![Example](../../assets/bb2.png) + +3. Least Cost-Branch and Bound +To explore the state space tree, this method uses the cost function. The previous two methods also calculate the cost function at each node but the cost is not been used for further exploration. + +![Example](../../assets/bb3.png) + +## Applications of Branch and Bound: + +- Traveling salesman problem: Branch and bound is used to solve the traveling salesman problem, which involves finding the shortest possible path that visits a set of cities and returns from where it started to visit the set of cities. +- Knapsack problem: Branch and bound is used to solve the knapsack problem, which involves finding the optimized combination of items to pack into a knapsack of limited capacity. +- Resource allocation: Branch and bound is used to solve resource allocation problems, like scheduling work on machines or assigning work to workers. +- Network optimization: Branch and bound is used to solve network optimization problems, it helps in finding the optimized path or flow through a network. +- Game playing: Branch and bound is used in some of the game-playing algorithms, like chess or tic-tac or 16 puzzle problem, to explore the various possible moves and find the optimized strategies. + +## Advantages of Branch and Bound: + +- Optimal solution: Branch and bound algorithm is created to find the best answer to an optimization issue by methodically searching the solution space. +- Reduces search space: The algorithm uses lower and upper bounds to cut down on the size of the search area and get rid of sub-problems that can not have the best answer. +- Proven performance: The branch and bound approach has been used extensively in numerous applications and has been shown to be successful in locating the best solutions to challenging optimization problems. +- Incremental improvement: The algorithm starts with an initial lower bound and iterations improve it until an optimized solution is found. + +## Disadvantages of Branch and Bound: + +- Exponential time complexity: The branch and bound algorithm’s worst-case time complexity is exponential in the size of the input, making it unsuitable for handling complex optimization issues. +- Memory-intensive: To store the search tree and the current best answer, the method needs a lot of memory. When dealing with numerous instances of the issue, this may become a problem. +- Sensitivity to problem-specific parameters: The quality of the problem-specific constraints utilized determines how well the method performs, and sometimes it might be challenging to discover good bounds. +- Limited scalability: Due to the size of the search tree which expands exponentially with the size of the problem, the Branch and Bound technique may not scale effectively for problems with huge search spaces. \ No newline at end of file diff --git a/docs/Advance/Computability.md b/docs/Advance/Computability.md new file mode 100644 index 0000000..55ac1e6 --- /dev/null +++ b/docs/Advance/Computability.md @@ -0,0 +1,142 @@ +--- +id: computability-classes +title: Computability Classes +sidebar_label: Computability Classes +tags: + - Computability Classes + - data-structures + - intermediate + - javascript + - python + - c++ + - java + - programming +sidebar_position: 9 +--- + +## Tractable and Intractable +- Generally we think of problems that are solvable by polynomial time +algorithms as being tractable, and problems that require superpolynomial +time as being intractable. +- Sometimes the line between what is an β€˜easy’ problem and what is a +β€˜hard’ problem is a fine one. +- For example, β€œFind the shortest path from vertex x to vertex y in a given +weighted graph”. This can be solved efficiently without much difficulty. +- However, if we ask for the longest path (without cycles) from +x to +y, we +have a problem for which no one knows a solution better than an +exhaustive search + +## Computability Classes + +In computer science, there exist some problems whose solutions are not yet found, the problems are divided into classes known as Complexity Classes. In complexity theory, a Complexity Class is a set of problems with related complexity. These classes help scientists to group problems based on how much time and space they require to solve problems and verify the solutions. It is the branch of the theory of computation that deals with the resources required to solve a problem. + +The common resources are time and space, meaning how much time the algorithm takes to solve a problem and the corresponding memory usage. + +## Complexity + +The time complexity of an algorithm is used to describe the number of steps required to solve a problem, but it can also be used to describe how long it takes to verify the answer. +The space complexity of an algorithm describes how much memory is required for the algorithm to operate. +Complexity classes are useful in organising similar types of problems. + +## Types of Complexity Classes + +- P Class +- NP Class +- CoNP Class +- NP-hard +- NP-complete + +## P Class + The P in the P class stands for Polynomial Time. It is the collection of decision problems(problems with a β€œyes” or β€œno” answer) that can be solved by a deterministic machine in polynomial time. + +### Features: + +- The solution to P problems is easy to find. +- P is often a class of computational problems that are solvable and tractable. Tractable means that the problems can be solved in theory as well as in practice. But the problems that can be solved in theory but not in practice are known as intractable. + +This class contains many problems: +``` +Calculating the greatest common divisor. +Finding a maximum matching. +Merge Sort +``` + +## NP Class +The NP in NP class stands for Non-deterministic Polynomial Time. It is the collection of decision problems that can be solved by a non-deterministic machine in polynomial time. + +### Features: + +- The solutions of the NP class are hard to find since they are being solved by a non-deterministic machine but the solutions are easy to verify. +- Problems of NP can be verified by a Turing machine in polynomial time. + +### Example: + +Let us consider an example to better understand the NP class. Suppose there is a company having a total of 1000 employees having unique employee IDs. Assume that there are 200 rooms available for them. A selection of 200 employees must be paired together, but the CEO of the company has the data of some employees who can’t work in the same room due to personal reasons. +This is an example of an NP problem. Since it is easy to check if the given choice of 200 employees proposed by a coworker is satisfactory or not i.e. no pair taken from the coworker list appears on the list given by the CEO. But generating such a list from scratch seems to be so hard as to be completely impractical. + +It indicates that if someone can provide us with the solution to the problem, we can find the correct and incorrect pair in polynomial time. Thus for the NP class problem, the answer is possible, which can be calculated in polynomial time. + +This class contains many problems that one would like to be able to solve effectively: +``` +Boolean Satisfiability Problem (SAT). +Hamiltonian Path Problem. +Graph coloring. +``` + +## Co-NP Class +Co-NP stands for the complement of NP Class. It means if the answer to a problem in Co-NP is No, then there is proof that can be checked in polynomial time. + +### Features: + +- If a problem X is in NP, then its complement X’ is also in CoNP. +- For an NP and CoNP problem, there is no need to verify all the answers at once in polynomial time, there is a need to verify only one particular answer β€œyes” or β€œno” in polynomial time for a problem to be in NP or CoNP. + +Some example problems for CoNP are: +``` +To check prime number. +Integer Factorization. +``` + +## NP-hard class +An NP-hard problem is at least as hard as the hardest problem in NP and it is a class of problems such that every problem in NP reduces to NP-hard. + +### Features: + +- All NP-hard problems are not in NP. +- It takes a long time to check them. This means if a solution for an NP-hard problem is given then it takes a long time to check whether it is right or not. +- A problem A is in NP-hard if, for every problem L in NP, there exists a polynomial-time reduction from L to A. + +Some of the examples of problems in Np-hard are: +``` +Halting problem. +Qualified Boolean formulas. +No Hamiltonian cycle. +``` + +## NP-complete class +A problem is NP-complete if it is both NP and NP-hard. NP-complete problems are the hard problems in NP. + +### Features: + +- NP-complete problems are special as any problem in NP class can be transformed or reduced into NP-complete problems in polynomial time. +- If one could solve an NP-complete problem in polynomial time, then one could also solve any NP problem in polynomial time. + +Some example problems include: +``` +Hamiltonian Cycle. +Satisfiability. +Vertex cover. +``` + + +| Complexity Class | Characteristic feature | +|------------------|-----------------------------------------------| +|P| Easily solvable in polynomial time. | +| NP |Yes, answers can be checked in polynomial time. | +| Co NP | No, answers can be checked in polynomial time. | +| NP Hard | All NP-hard problems are not in NP and it takes a long time to check them. | +|NP Complete | A problem that is NP and NP-hard is NP-complete. + | + diff --git a/docs/Advance/DynamicProgramming.md b/docs/Advance/DynamicProgramming.md new file mode 100644 index 0000000..f1fc528 --- /dev/null +++ b/docs/Advance/DynamicProgramming.md @@ -0,0 +1,1386 @@ +--- +id: 01-Dynamic Programming +title: Introduction to Dynamic Programming +sidebar_label: Dynamic Programming +tags: + - dsa + - data-structures + - binary-tree + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial +sidebar_position: 1 +--- + +# Dynamic Programming in DSA + +Dynamic Programming is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of subproblems so that we do not have to re-compute them when needed later. This simple optimization reduces time complexities from exponential to polynomial. + +## Characteristics of Dynamic Programming Algorithm: + +1. In general, dynamic programming (DP) is one of the most powerful techniques for solving a certain class of problems. + +2. There is an elegant way to formulate the approach and a very simple thinking process, and the coding part is very easy. + +3. Essentially, it is a simple idea, after solving a problem with a given input, save the result as a reference for future use, so you won’t have to re-solve it.. briefly β€˜Remember your Past’. + +4. It is a big hint for DP if the given problem can be broken up into smaller sub-problems, and these smaller subproblems can be divided into still smaller ones, and in this process, you see some overlapping subproblems. + +5. Additionally, the optimal solutions to the subproblems contribute to the optimal solution of the given problem (referred to as the Optimal Substructure Property). + +6. The solutions to the subproblems are stored in a table or array (memoization) or in a bottom-up manner (tabulation) to avoid redundant computation. + +7. The solution to the problem can be constructed from the solutions to the subproblems. + +8. Dynamic programming can be implemented using a recursive algorithm, where the solutions to subproblems are found recursively, or using an iterative algorithm, where the solutions are found by working through the subproblems in a specific order. + +## Dynamic programming works on following principles: + +1. Characterize structure of optimal solution, i.e. build a mathematical model of the solution. +2. Recursively define the value of the optimal solution. +3. Using bottom-up approach, compute the value of the optimal solution for each possible subproblems. +4. Construct optimal solution for the original problem using information computed in the previous step. + +## Applications: + +Dynamic programming is used to solve optimization problems. It is used to solve many real-life problems such as, + +(i) Make a change problem + +(ii) Knapsack problem + +(iii) Optimal binary search tree + +## What is the difference between a Dynamic programming algorithm and recursion? + +1. In dynamic programming, problems are solved by breaking them down into smaller ones to solve the larger ones, while recursion is when a function is called and executed by itself. While dynamic programming can function without making use of recursion techniques, since the purpose of dynamic programming is to optimize and accelerate the process, programmers usually make use of recursion techniques to accelerate and turn the process efficiently. + +2. When a function can execute a specific task by calling itself, receive the name of the recursive function. In order to perform and accomplish the work, this function calls itself when it has to be executed. + +3. Using dynamic programming, you can break a problem into smaller parts, called subproblems, to solve it. Dynamic programming involves solving the problem for the first time, then using memoization to store the solutions. + +4. Therefore, the main difference between the two techniques is their intended use; recursion is used to automate a function, whereas dynamic programming is an optimization technique used to solve problems. + +5. Recursive functions recognize when they are needed, execute themselves, then stop working. When the function identifies the moment it is needed, it calls itself and is executed; this is called a recursive case. As a result, the function must stop once the task is completed, known as the base case. + +6. By establishing states, dynamic programming recognizes the problem and divides it into sub-problems in order to solve the whole scene. After solving these sub-problems, or variables, the programmer must establish a mathematical relationship between them. Last but not least, these solutions and results are stored as algorithms, so they can be accessed in the future without having to solve the whole problem again. + +## Techniques to solve Dynamic Programming Problems: + +1. Top-Down(Memoization): + Break down the given problem in order to begin solving it. If you see that the problem has already been solved, return the saved answer. If it hasn’t been solved, solve it and save it. This is usually easy to think of and very intuitive, This is referred to as Memoization. + +2. Bottom-Up(Tabulation): + Analyze the problem and see in what order the subproblems are solved, and work your way up from the trivial subproblem to the given problem. This process ensures that the subproblems are solved before the main problem. This is referred to as Dynamic Programming. + + ![alt text](image.png) + +## Tabulation vs Memoization: + +There are two different ways to store the values so that the values of a sub-problem can be reused. Here, will discuss two patterns of solving dynamic programming (DP) problems: + +1. Tabulation: Bottom Up +2. Memoization: Top Down + +Before getting to the definitions of the above two terms consider the following statements: + +(i) Version 1: I will study the theory of DP from GeeksforGeeks, then I will practice some problems on classic DP and hence I will master DP. + +(ii) Version 2: To Master DP, I would have to practice Dynamic problems and practice problems – Firstly, I would have to study some theories of DP from GeeksforGeeks + +Both versions say the same thing, the difference simply lies in the way of conveying the message and that’s exactly what Bottom-Up and Top-Down DP do. Version 1 can be related to Bottom-Up DP and Version-2 can be related to Top-Down DP. + +| | Tabulation | Memoization | Memoization | +| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **State** | State transition relation is difficult to think | State transition relation is easy to think | State transition relation is easy to think | +| **Code** | Code gets complicated when a lot of conditions are required | Code is easy and less complicated | Code is easy and less complicated | +| **Speed** | Fast, as we directly access previous states from the table | Slow due to a lot of recursive calls and return statements | Slow due to a lot of recursive calls and return statements | +| **Subproblem solving** | If all subproblems must be solved at least once, a bottom-up dynamic programming algorithm usually outperforms a top-down memoized algorithm by a constant factor | If some subproblems in the subproblem space need not be solved at all, the memoized solution has the advantage of solving only those subproblems that are definitely required | If some subproblems in the subproblem space need not be solved at all, the memoized solution has the advantage of solving only those subproblems that are definitely required | +| **Table entries** | In the Tabulated version, starting from the first entry, all entries are filled one by one | Unlike the Tabulated version, all entries of the lookup table are not necessarily filled in Memoized version. The table is filled on demand. | Unlike the Tabulated version, all entries of the lookup table are not necessarily filled in Memoized version. The table is filled on demand. | +| **Approach** | Generally, tabulation (dynamic programming) is an iterative approach | On the other hand, memoization is a recursive approach. | On the other hand, memoization is a recursive approach. | + +## How to solve a Dynamic Programming Problem? + +To dynamically solve a problem, we need to check two necessary conditions: + +1. Overlapping Subproblems: When the solutions to the same subproblems are needed repetitively for solving the actual problem. The problem is said to have overlapping subproblems property. + +2. Optimal Substructure Property: If the optimal solution of the given problem can be obtained by using optimal solutions of its subproblems then the problem is said to have Optimal Substructure Property. + +### Steps to solve a Dynamic programming problem: + +1. Identify if it is a Dynamic programming problem. +2. Decide a state expression with the Least parameters. +3. Formulate state and transition relationships. +4. Do tabulation (or memorization). + +#### 1. How to classify a problem as a Dynamic Programming algorithm Problem? + +Typically, all the problems that require maximizing or minimizing certain quantities or counting problems that say to count the arrangements under certain conditions or certain probability problems can be solved by using Dynamic Programming. +All dynamic programming problems satisfy the overlapping subproblems property and most of the classic Dynamic programming problems also satisfy the optimal substructure property. Once we observe these properties in a given problem be sure that it can be solved using Dynamic Programming. + +#### 2. Deciding the state: + +Problems with dynamic programming are mostly concerned with the state and its transition. The most fundamental phase must be carried out with extreme care because the state transition depends on the state definition you select. + +State: + +A state is a collection of characteristics that can be used to specifically describe a given position or standing in a given challenge. To minimise state space, this set of parameters has to be as compact as feasible. + +#### 3 Formulating a relation among the states: + +The hardest part of a Dynamic Programming challenge is this step, which calls for a lot of intuition, observation, and training. + +Example: + +Given 3 numbers {1, 3, 5}, the task is to tell the total number of ways we can form a number N using the sum of the given three numbers. (allowing repetitions and different arrangements). + +The total number of ways to form 6 is: 8 + +``` +1+1+1+1+1+1 +1+1+1+3 +1+1+3+1 +1+3+1+1 +3+1+1+1 +3+3 +1+5 +5+1 +``` + +### Following are the steps to solve the problem: + +1. We choose a state for the given problem. +2. N will be used as the determining factor for the state because it can be used to identify any subproblem. +3. The DP state will resemble state(N), where the state(N) is the total number of arrangements required to create N using the elements 1, 3, and 5. Identify the relationship of the transition between any two states. +4. We must now calculate the state (N). + +#### 3.1 How to Compute the state? + +As we can only use 1, 3, or 5 to form a given number N. Let us assume that we know the result for N = 1, 2, 3, 4, 5, 6 + +Let us say we know the result for: +state (n = 1), state (n = 2), state (n = 3) ……… state (n = 6) +Now, we wish to know the result of the state (n = 7). See, we can only add 1, 3, and 5. Now we can get a sum total of 7 in the following 3 ways: + +1. Adding 1 to all possible combinations of state (n = 6) + Eg: [ (1+1+1+1+1+1) + 1] + +``` +[ (1+1+1+3) + 1] +[ (1+1+3+1) + 1] +[ (1+3+1+1) + 1] +[ (3+1+1+1) + 1] +[ (3+3) + 1] +[ (1+5) + 1] +[ (5+1) + 1] +``` + +2. Adding 3 to all possible combinations of state (n = 4); + +``` +[(1+1+1+1) + 3] +[(1+3) + 3] +[(3+1) + 3] +``` + +3. Adding 5 to all possible combinations of state(n = 2) + +``` +[ (1+1) + 5] +``` + +(Note how it sufficient to add only on the right-side – all the add-from-left-side cases are covered, either in the same state, or another, e.g. [ 1+(1+1+1+3)] is not needed in state (n=6) because it’s covered by state (n = 4) [(1+1+1+1) + 3]) + +Now, think carefully and satisfy yourself that the above three cases are covering all possible ways to form a sum total of 7; +Therefore, we can say that result for + +``` +state(7) = state (6) + state (4) + state (2) +OR +state(7) = state (7-1) + state (7-3) + state (7-5) +In general, +state(n) = state(n-1) + state(n-3) + state(n-5) +``` + +Below is the implementation for the above approach: + + + + + ```js + function solve(n) { + // base case + if (n < 0) { + return 0; + } + if (n === 0) { + return 1; + } + return solve(n - 1) + solve(n - 3) + solve(n - 5); + } + ``` + + + + ```java + public class RecursionExample { + public static int solve(int n) { + // base case + if (n < 0) { + return 0; + } + if (n == 0) { + return 1; + } + return solve(n - 1) + solve(n - 3) + solve(n - 5); + } + } + ``` + + + + ```python + def solve(n): + # base case + if n < 0: + return 0 + if n == 0: + return 1 + return solve(n - 1) + solve(n - 3) + solve(n - 5) + ``` + + + + ```c + int solve(int n) { + // base case + if (n < 0) { + return 0; + } + if (n == 0) { + return 1; + } + return solve(n - 1) + solve(n - 3) + solve(n - 5); + } + ``` + + + + ```cpp + int solve(int n) { + // base case + if (n < 0) { + return 0; + } + if (n == 0) { + return 1; + } + return solve(n - 1) + solve(n - 3) + solve(n - 5); + } + ``` + + + + ```ts + function solve(n: number): number { + // base case + if (n < 0) { + return 0; + } + if (n === 0) { + return 1; + } + return solve(n - 1) + solve(n - 3) + solve(n - 5); + } + ``` + + + +Time Complexity: O(3n), As at every stage we need to take three decisions and the height of the tree will be of the order of n. +Auxiliary Space: O(n), The extra space is used due to the recursion call stack. + +The above code seems exponential as it is calculating the same state again and again. So, we just need to add memoization. + +4. Adding memoization or tabulation for the state + The simplest portion of a solution based on dynamic programming is this. Simply storing the state solution will allow us to access it from memory the next time that state is needed. + +Adding memoization to the above code: + +// Number of Arrangements with Memoization + +// Number of Arrangements with Memoization + + + + + ```js + const MAXN = 1000; // or any appropriate maximum value + const dp = new Array(MAXN).fill(-1); + + function solve(n) { + // base case + if (n < 0) { + return 0; + } + if (n === 0) { + return 1; + } + + // Checking if already calculated + if (dp[n] !== -1) { + return dp[n]; + } + + // Storing the result and returning + return dp[n] = solve(n - 1) + solve(n - 3) + solve(n - 5); + } + ``` + + + + ```java + public class RecursionExample { + static final int MAXN = 1000; // or any appropriate maximum value + static int[] dp = new int[MAXN]; + + static { + for (int i = 0; i < MAXN; i++) { + dp[i] = -1; + } + } + + public static int solve(int n) { + // base case + if (n < 0) { + return 0; + } + if (n == 0) { + return 1; + } + + // Checking if already calculated + if (dp[n] != -1) { + return dp[n]; + } + + // Storing the result and returning + return dp[n] = solve(n - 1) + solve(n - 3) + solve(n - 5); + } + } + ``` + + + + ```python + MAXN = 1000 # or any appropriate maximum value + dp = [-1] * MAXN + + def solve(n): + # base case + if n < 0: + return 0 + if n == 0: + return 1 + + # Checking if already calculated + if dp[n] != -1: + return dp[n] + + # Storing the result and returning + dp[n] = solve(n - 1) + solve(n - 3) + solve(n - 5) + return dp[n] + ``` + + + + ```c + #define MAXN 1000 // or any appropriate maximum value + + int dp[MAXN]; + + // Initialize dp array + void initialize_dp() { + for (int i = 0; i < MAXN; i++) { + dp[i] = -1; + } + } + + int solve(int n) { + // base case + if (n < 0) { + return 0; + } + if (n == 0) { + return 1; + } + + // Checking if already calculated + if (dp[n] != -1) { + return dp[n]; + } + + // Storing the result and returning + return dp[n] = solve(n - 1) + solve(n - 3) + solve(n - 5); + } + ``` + + + + ```cpp + #define MAXN 1000 // or any appropriate maximum value + + int dp[MAXN]; + + // Initialize dp array + void initialize_dp() { + for (int i = 0; i < MAXN; i++) { + dp[i] = -1; + } + } + + int solve(int n) { + // base case + if (n < 0) { + return 0; + } + if (n == 0) { + return 1; + } + + // Checking if already calculated + if (dp[n] != -1) { + return dp[n]; + } + + // Storing the result and returning + return dp[n] = solve(n - 1) + solve(n - 3) + solve(n - 5); + } + ``` + + + + ```ts + const MAXN = 1000; // or any appropriate maximum value + const dp: number[] = new Array(MAXN).fill(-1); + + function solve(n: number): number { + // base case + if (n < 0) { + return 0; + } + if (n === 0) { + return 1; + } + + // Checking if already calculated + if (dp[n] !== -1) { + return dp[n]; + } + + // Storing the result and returning + return dp[n] = solve(n - 1) + solve(n - 3) + solve(n - 5); + } + ``` + + + + +Time Complexity: O(n), As we just need to make 3n function calls and there will be no repetitive calculations as we are returning previously calculated results. +Auxiliary Space: O(n), The extra space is used due to the recursion call stack. + +### How to solve Dynamic Programming problems through Example? + +Problem: Let’s find the Fibonacci sequence up to the nth term. A Fibonacci series is the sequence of numbers in which each number is the sum of the two preceding ones. For example, 0, 1, 1, 2, 3, and so on. Here, each number is the sum of the two preceding numbers. + +Naive Approach: The basic way to find the nth Fibonacci number is to use recursion. + +Below is the implementation for the above approach: + +// Fibonacci Number + + + + + ```cpp + #include + using namespace std; + + // Function to find nth fibonacci number + int fib(int n) + { + if (n <= 1) { + return n; + } + int x = fib(n - 1); + int y = fib(n - 2); + + return x + y; + } + + // Drivers code + int main() + { + int n = 5; + + // Function Call + cout << fib(n); + return 0; + } + ``` + + + + ```java + public class FibonacciExample { + // Function to find nth fibonacci number + public static int fib(int n) { + if (n <= 1) { + return n; + } + int x = fib(n - 1); + int y = fib(n - 2); + return x + y; + } + + // Drivers code + public static void main(String[] args) { + int n = 5; + // Function Call + System.out.println(fib(n)); + } + } + ``` + + + + ```python + # Function to find nth fibonacci number + def fib(n): + if n <= 1: + return n + x = fib(n - 1) + y = fib(n - 2) + return x + y + + # Drivers code + if __name__ == "__main__": + n = 5 + # Function Call + print(fib(n)) + ``` + + + + ```c + #include + + // Function to find nth fibonacci number + int fib(int n) + { + if (n <= 1) { + return n; + } + int x = fib(n - 1); + int y = fib(n - 2); + + return x + y; + } + + // Drivers code + int main() + { + int n = 5; + + // Function Call + printf("%d\n", fib(n)); + return 0; + } + ``` + + + + ```js + // Function to find nth fibonacci number + function fib(n) { + if (n <= 1) { + return n; + } + let x = fib(n - 1); + let y = fib(n - 2); + return x + y; + } + + // Drivers code + let n = 5; + // Function Call + console.log(fib(n)); + ``` + + + + ```ts + // Function to find nth fibonacci number + function fib(n: number): number { + if (n <= 1) { + return n; + } + let x = fib(n - 1); + let y = fib(n - 2); + return x + y; + } + + // Drivers code + let n: number = 5; + // Function Call + console.log(fib(n)); + ``` + + + + +Complexity Analysis: + +Time Complexity: O(2n) + +1. Here, for every n, we are required to make a recursive call to fib(n – 1) and fib(n – 2). For fib(n – 1), we will again make the recursive call to fib(n – 2) and fib(n – 3). Similarly, for fib(n – 2), recursive calls are made on fib(n – 3) and fib(n – 4) until we reach the base case. + +2. During each recursive call, we perform constant work(k) (adding previous outputs to obtain the current output). We perform 2nK work at every level (where n = 0, 1, 2, …). Since n is the number of calls needed to reach 1, we are performing 2n-1k at the final level. Total work can be calculated as: + +3. If we draw the recursion tree of the Fibonacci recursion then we found the maximum height of the tree will be n and hence the space complexity of the Fibonacci recursion will be O(n). + +4. Efficient approach: As it is a very terrible complexity(Exponential), thus we need to optimize it with an efficient method. (Memoization) + +Let’s look at the example below for finding the 5th Fibonacci number. + +![alt text](image-2.png) + +### Observations: + +``` +1. The entire program repeats recursive calls. As in the above figure, for calculating fib(4), we need the value of fib(3) (first recursive call over fib(3)), and for calculating fib(5), we again need the value of fib(3)(second similar recursive call over fib(3)). + +2. Both of these recursive calls are shown above in the outlining circle. + +3. Similarly, there are many others for which we are repeating the recursive calls. + +4. Recursion generally involves repeated recursive calls, which increases the program’s time complexity. + +5. By storing the output of previously encountered values (preferably in arrays, as these can be traversed and extracted most efficiently), we can overcome this problem. The next time we make a recursive call over these values, we will use their already stored outputs instead of calculating them all over again. + +6. In this way, we can improve the performance of our code. Memoization is the process of storing each recursive call’s output for later use, preventing the code from calculating it again. + +7. Way to memoize: To achieve this in our example we will simply take an answer array initialized to -1. As we make a recursive call, we will first check if the value stored in the answer array corresponding to that position is -1. The value -1 indicates that we haven’t calculated it yet and have to recursively compute it. The output must be stored in the answer array so that, next time, if the same value is encountered, it can be directly used from the answer array. + +Now in this process of memoization, considering the above Fibonacci numbers example, it can be observed that the total number of unique calls will be at most (n + 1) only. + +``` + +Below is the implementation for the above approach: + +## Fibonacci Number with Memoization + + + + + ```cpp + #include + using namespace std; + + // Helper Function + int fibo_helper(int n, int* ans) + { + // Base case + if (n <= 1) { + return n; + } + + // To check if output already exists + if (ans[n] != -1) { + return ans[n]; + } + + // Calculate output + int x = fibo_helper(n - 1, ans); + int y = fibo_helper(n - 2, ans); + + // Saving the output for future use + ans[n] = x + y; + + // Returning the final output + return ans[n]; + } + + int fibo(int n) + { + int* ans = new int[n + 1]; + + // Initializing with -1 + for (int i = 0; i <= n; i++) { + ans[i] = -1; + } + + // Calling helper function + return fibo_helper(n, ans); + } + + // Drivers code + int main() + { + int n = 5; + + // Function Call + cout << fibo(n) << endl; + return 0; + } + ``` + + + + ```java + public class FibonacciMemoization { + // Helper Function + static int fibo_helper(int n, int[] ans) { + // Base case + if (n <= 1) { + return n; + } + + // To check if output already exists + if (ans[n] != -1) { + return ans[n]; + } + + // Calculate output + int x = fibo_helper(n - 1, ans); + int y = fibo_helper(n - 2, ans); + + // Saving the output for future use + ans[n] = x + y; + + // Returning the final output + return ans[n]; + } + + // Function to find nth fibonacci number with memoization + static int fibo(int n) { + int[] ans = new int[n + 1]; + + // Initializing with -1 + for (int i = 0; i <= n; i++) { + ans[i] = -1; + } + + // Calling helper function + return fibo_helper(n, ans); + } + + // Drivers code + public static void main(String[] args) { + int n = 5; + + // Function Call + System.out.println(fibo(n)); + } + } + ``` + + + + ```python + # Function to find nth fibonacci number with memoization + def fibo(n): + # Helper Function + def fibo_helper(n, ans): + # Base case + if n <= 1: + return n + + # To check if output already exists + if ans[n] != -1: + return ans[n] + + # Calculate output + x = fibo_helper(n - 1, ans) + y = fibo_helper(n - 2, ans) + + # Saving the output for future use + ans[n] = x + y + + # Returning the final output + return ans[n] + + # Initialize ans array with -1 + ans = [-1] * (n + 1) + + # Calling helper function + return fibo_helper(n, ans) + + # Drivers code + if __name__ == "__main__": + n = 5 + + # Function Call + print(fibo(n)) + ``` + + + + ```c + #include + #include + + // Helper Function + int fibo_helper(int n, int* ans) + { + // Base case + if (n <= 1) { + return n; + } + + // To check if output already exists + if (ans[n] != -1) { + return ans[n]; + } + + // Calculate output + int x = fibo_helper(n - 1, ans); + int y = fibo_helper(n - 2, ans); + + // Saving the output for future use + ans[n] = x + y; + + // Returning the final output + return ans[n]; + } + + // Function to find nth fibonacci number with memoization + int fibo(int n) + { + int* ans = (int*)malloc((n + 1) * sizeof(int)); + + // Initializing with -1 + for (int i = 0; i <= n; i++) { + ans[i] = -1; + } + + // Calling helper function + int result = fibo_helper(n, ans); + + // Free memory allocated to ans + free(ans); + + return result; + } + + // Drivers code + int main() + { + int n = 5; + + // Function Call + printf("%d\n", fibo(n)); + return 0; + } + ``` + + + + ```js + // Function to find nth fibonacci number with memoization + function fibo(n) { + // Helper Function + function fibo_helper(n, ans) { + // Base case + if (n <= 1) { + return n; + } + + // To check if output already exists + if (ans[n] !== -1) { + return ans[n]; + } + + // Calculate output + let x = fibo_helper(n - 1, ans); + let y = fibo_helper(n - 2, ans); + + // Saving the output for future use + ans[n] = x + y; + + // Returning the final output + return ans[n]; + } + + // Initialize ans array with -1 + let ans = new Array(n + 1).fill(-1); + + // Calling helper function + return fibo_helper(n, ans); + } + + // Drivers code + let n = 5; + + // Function Call + console.log(fibo(n)); + ``` + + + + ```ts + // Function to find nth fibonacci number with memoization + function fibo(n: number): number { + // Helper Function + function fibo_helper(n: number, ans: number[]): number { + // Base case + if (n <= 1) { + return n; + } + + // To check if output already exists + if (ans[n] !== -1) { + return ans[n]; + } + + // Calculate output + let x = fibo_helper(n - 1, ans); + let y = fibo_helper(n - 2, ans); + + // Saving the output for future use + ans[n] = x + y; + + // Returning the final output + return ans[n]; + } + + // Initialize ans array with -1 + let ans: number[] = new Array(n + 1).fill(-1); + + // Calling helper function + return fibo_helper(n, ans); + } + + // Drivers code + let n: number = 5; + + // Function Call + console.log(fibo(n)); + ``` + + + + +Complexity analysis: + + Time complexity: O(n) + Auxiliary Space: O(n) + +## Optimized approach: + +Following a bottom-up approach to reach the desired index. This approach of converting recursion into iteration is known as Dynamic programming(DP). + +### Observation: + +``` +1. Finally, what we do is recursively call each response index field and calculate its value using previously saved outputs. + +2. Recursive calls terminate via the base case, which means we are already aware of the answers which should be stored in the base case indexes. + +3. In the case of Fibonacci numbers, these indices are 0 and 1 as f(ib0) = 0 and f(ib1) = 1. So we can directly assign these two values ​​into our answer array and then use them to calculate f(ib2), which is f(ib1) + f(ib0), and so on for each subsequent index. + +4. This can easily be done iteratively by running a loop from i = (2 to n). Finally, we get our answer at the 5th index of the array because we already know that the ith index contains the answer to the ith value. + +5. Simply, we first try to find out the dependence of the current value on previous values ​​and then use them to calculate our new value. Now, we are looking for those values which do not depend on other values, which means they are independent(base case values, since these, are the smallest problems +which we are already aware of). +``` + +// Fibonacci Number (Bottom-up Dynamic Programming) + + + + + ```cpp + #include + using namespace std; + + // Function for calculating the nth Fibonacci number + int fibo(int n) + { + int* ans = new int[n + 1]; + + // Storing the independent values in the answer array + ans[0] = 0; + ans[1] = 1; + + // Using the bottom-up approach + for (int i = 2; i <= n; i++) { + ans[i] = ans[i - 1] + ans[i - 2]; + } + + // Returning the final index + return ans[n]; + } + + // Drivers code + int main() + { + int n = 5; + + // Function Call + cout << fibo(n) << endl; + return 0; + } + ``` + + + + ```java + public class FibonacciBottomUp { + // Function for calculating the nth Fibonacci number + static int fibo(int n) { + int[] ans = new int[n + 1]; + + // Storing the independent values in the answer array + ans[0] = 0; + ans[1] = 1; + + // Using the bottom-up approach + for (int i = 2; i <= n; i++) { + ans[i] = ans[i - 1] + ans[i - 2]; + } + + // Returning the final index + return ans[n]; + } + + // Drivers code + public static void main(String[] args) { + int n = 5; + + // Function Call + System.out.println(fibo(n)); + } + } + ``` + + + + ```python + # Function for calculating the nth Fibonacci number + def fibo(n): + ans = [0] * (n + 1) + + # Storing the independent values in the answer array + ans[0] = 0 + ans[1] = 1 + + # Using the bottom-up approach + for i in range(2, n + 1): + ans[i] = ans[i - 1] + ans[i - 2] + + # Returning the final index + return ans[n] + + # Drivers code + if __name__ == "__main__": + n = 5 + + # Function Call + print(fibo(n)) + ``` + + + + ```c + #include + #include + + // Function for calculating the nth Fibonacci number + int fibo(int n) + { + int* ans = (int*)malloc((n + 1) * sizeof(int)); + + // Storing the independent values in the answer array + ans[0] = 0; + ans[1] = 1; + + // Using the bottom-up approach + for (int i = 2; i <= n; i++) { + ans[i] = ans[i - 1] + ans[i - 2]; + } + + // Returning the final index + return ans[n]; + } + + // Drivers code + int main() + { + int n = 5; + + // Function Call + printf("%d\n", fibo(n)); + return 0; + } + ``` + + + + ```js + // Function for calculating the nth Fibonacci number + function fibo(n) { + let ans = new Array(n + 1); + + // Storing the independent values in the answer array + ans[0] = 0; + ans[1] = 1; + + // Using the bottom-up approach + for (let i = 2; i <= n; i++) { + ans[i] = ans[i - 1] + ans[i - 2]; + } + + // Returning the final index + return ans[n]; + } + + // Drivers code + let n = 5; + + // Function Call + console.log(fibo(n)); + ``` + + + + ```ts + // Function for calculating the nth Fibonacci number + function fibo(n: number): number { + let ans: number[] = new Array(n + 1); + + // Storing the independent values in the answer array + ans[0] = 0; + ans[1] = 1; + + // Using the bottom-up approach + for (let i = 2; i <= n; i++) { + ans[i] = ans[i - 1] + ans[i - 2]; + } + + // Returning the final index + return ans[n]; + } + + // Drivers code + let n: number = 5; + + // Function Call + console.log(fibo(n)); + ``` + + + + +Complexity analysis: + + Time complexity: O(n) + Auxiliary Space: O(n) + +### Optimization of above method (Space Optimization Approch) + +``` +1. in above code we can see that the current state of any fibonacci number depend only on prev two number + +2. so using this observation we can conclude that we did not need to store the whole table of size n but instead of that we can only store the prev two values + +3. so this way we can optimize the space complexity in the above code O(n) to O(1) +``` + +// Fibonacci Number (Bottom-up Approach with Optimized Space) + + + + + ```cpp + #include + using namespace std; + + // Function for calculating the nth Fibonacci number + int fibo(int n) + { + int prevPrev = 0, prev = 1, curr = 1; + + // Using the bottom-up approach + for (int i = 2; i <= n; i++) { + curr = prev + prevPrev; + prevPrev = prev; + prev = curr; + } + + // Returning the final answer + return curr; + } + + // Drivers code + int main() + { + int n = 5; + + // Function Call + cout << fibo(n) << endl; + return 0; + } + ``` + + + + ```java + public class FibonacciBottomUpOptimized { + // Function for calculating the nth Fibonacci number + static int fibo(int n) { + int prevPrev = 0, prev = 1, curr = 1; + + // Using the bottom-up approach + for (int i = 2; i <= n; i++) { + curr = prev + prevPrev; + prevPrev = prev; + prev = curr; + } + + // Returning the final answer + return curr; + } + + // Drivers code + public static void main(String[] args) { + int n = 5; + + // Function Call + System.out.println(fibo(n)); + } + } + ``` + + + + ```python + # Function for calculating the nth Fibonacci number + def fibo(n): + prevPrev, prev, curr = 0, 1, 1 + + # Using the bottom-up approach + for i in range(2, n + 1): + curr = prev + prevPrev + prevPrev = prev + prev = curr + + # Returning the final answer + return curr + + # Drivers code + if __name__ == "__main__": + n = 5 + + # Function Call + print(fibo(n)) + ``` + + + + ```c + #include + + // Function for calculating the nth Fibonacci number + int fibo(int n) + { + int prevPrev = 0, prev = 1, curr = 1; + + // Using the bottom-up approach + for (int i = 2; i <= n; i++) { + curr = prev + prevPrev; + prevPrev = prev; + prev = curr; + } + + // Returning the final answer + return curr; + } + + // Drivers code + int main() + { + int n = 5; + + // Function Call + printf("%d\n", fibo(n)); + return 0; + } + ``` + + + + ```js + // Function for calculating the nth Fibonacci number + function fibo(n) { + let prevPrev = 0, prev = 1, curr = 1; + + // Using the bottom-up approach + for (let i = 2; i <= n; i++) { + curr = prev + prevPrev; + prevPrev = prev; + prev = curr; + } + + // Returning the final answer + return curr; + } + + // Drivers code + let n = 5; + + // Function Call + console.log(fibo(n)); + ``` + + + + ```ts + // Function for calculating the nth Fibonacci number + function fibo(n: number): number { + let prevPrev: number = 0, prev: number = 1, curr: number = 1; + + // Using the bottom-up approach + for (let i: number = 2; i <= n; i++) { + curr = prev + prevPrev; + prevPrev = prev; + prev = curr; + } + + // Returning the final answer + return curr; + } + + // Drivers code + let n: number = 5; + + // Function Call + console.log(fibo(n)); + ``` + + + + +## Conclusion: + +In conclusion, dynamic programming is a powerful problem-solving technique that is used for optimization problems. Dynamic programming is a superior form of recursion that overcomes its limitations. It involves breaking down a problem into smaller subproblems, solving each subproblem independently, and using the solutions to these subproblems to construct the overall solution. The key characteristics of a dynamic programming algorithm include overlapping subproblems, optimal substructure, memoization or tabulation, and the use of either iterative or recursive methods. + +Dynamic programming has several advantages over other problem-solving techniques, including efficiency, simplicity, flexibility, optimality, clarity, and code reusability. It is not just recursion, although it can be implemented using a recursive algorithm. Dynamic programming is different from greedy algorithms in that it breaks down the problem into smaller subproblems, solves each subproblem independently, and uses the solutions to the subproblems to construct the overall solution. + +The basics of dynamic programming include breaking down a problem into smaller subproblems, solving each subproblem independently, storing the solutions to subproblems to avoid redundant computation, using the solutions to the subproblems to construct the overall solution and using the principle of optimality to ensure that the solution is optimal. However, DP can occasionally be challenging to comprehend, making it a well-liked option for coding interviews. Understanding how DP functions work can be useful to everyone, whether they are a professional or a student getting ready for the placements. + +Overall, dynamic programming is a valuable tool for solving complex optimization problems and can lead to more efficient and effective solutions. diff --git a/docs/Advance/Greedy.md b/docs/Advance/Greedy.md new file mode 100644 index 0000000..f3f5753 --- /dev/null +++ b/docs/Advance/Greedy.md @@ -0,0 +1,175 @@ +--- +id: 04-Greedy +title: Introduction to Greedy +sidebar_label: Greedy in DSA +tags: + - Greedy + - data-structures + - binary-tree + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial +sidebar_position: 4 +--- + +Greedy Algorithm is defined as a method for solving optimization problems by taking decisions that result in the most evident and immediate benefit irrespective of the final outcome. It works for cases where minimization or maximization leads to the required solution. + +## What is Greedy Algorithm? + +A greedy algorithm is a problem-solving technique that makes the best local choice at each step in the hope of finding the global optimum solution. It prioritizes immediate benefits over long-term consequences, making decisions based on the current situation without considering future implications. While this approach can be efficient and straightforward, it doesn’t guarantee the best overall outcome for all problems. + +However, it’s important to note that not all problems are suitable for greedy algorithms. They work best when the problem exhibits the following properties: + +1. Greedy Choice Property: The optimal solution can be constructed by making the best local choice at each step. +2. Optimal Substructure: The optimal solution to the problem contains the optimal solutions to its subproblems. + +## Characteristics of Greedy Algorithm + +Here are the characteristics of a greedy algorithm: + +1. Greedy algorithms are simple and easy to implement. + +2. They are efficient in terms of time complexity, often providing quick solutions. + +3. Greedy algorithms are used for optimization problems where a locally optimal choice leads to a globally optimal solution. + +4. These algorithms do not reconsider previous choices, as they make decisions based on current information without looking ahead. + +5. Greedy algorithms are suitable for problems for optimal substructure. + +These characteristics help to define the nature and usage of greedy algorithms in problem-solving. + +## Examples of Greedy Algorithm + +Several well-known algorithms fall under the category of greedy algorithms. Here are a few examples: + + 1. Dijkstra’s Algorithm: This algorithm finds the shortest path between two nodes in a graph. It works by repeatedly choosing the shortest edge available from the current node. + + 2. Kruskal’s Algorithm: This algorithm finds the minimum spanning tree of a graph. It works by repeatedly choosing the edge with the minimum weight that does not create a cycle. + + 3. Fractional Knapsack Problem: This problem involves selecting items with the highest value-to-weight ratio to fill a knapsack with a limited capacity. The greedy algorithm selects items in decreasing order of their value-to-weight ratio until the knapsack is full. + + 4. Scheduling and Resource Allocation: The greedy algorithm can be used to schedule jobs or allocate resources in an efficient manner. + + 5. Coin Change Problem: The greedy algorithm can be used to make change for a given amount with the minimum number of coins, by always choosing the coin with the highest value that is less than the remaining amount to be changed. + + 6. Huffman Coding: The greedy algorithm can be used to generate a prefix-free code for data compression, by constructing a binary tree in a way that the frequency of each character is taken into consideration. + +## Why to use Greedy Approach? + +Here are some reasons why you might use the Greedy Approach: + +1. Simple and easy to understand: The Greedy Approach is straightforward and easy to implement, making it a good choice for beginners. + +2. Fast and efficient: It usually finds a solution quickly, making it suitable for problems where time is a constraint. + +3. Provides a good enough solution: While not always optimal, the Greedy Approach often finds a solution that is close to the best possible solution. + +4. Can be used as a building block for other algorithms: The Greedy Approach can be used as a starting point for developing more complex algorithms. + +5. Useful for a variety of problems: The Greedy Approach can be applied to a wide range of optimization problems, including knapsack problems, scheduling problems, and routing problems. + +However, it’s important to remember that the Greedy Approach doesn’t always find the optimal solution. There are cases where it can lead to suboptimal solutions. Therefore, it is necessary to carefully consider the problem and the potential drawbacks before using the Greedy Approach. + +## How does the Greedy Algorithm works? + +Greedy Algorithm solve optimization problems by making the best local choice at each step in the hope of finding the global optimum. It’s like taking the best option available at each moment, hoping it will lead to the best overall outcome. + +Here’s how it works: + +1. Start with the initial state of the problem. This is the starting point from where you begin making choices. + +2. Evaluate all possible choices you can make from the current state. Consider all the options available at that specific moment. + +3. Choose the option that seems best at that moment, regardless of future consequences. This is the β€œgreedy” part – you take the best option available now, even if it might not be the best in the long run. + +4. Move to the new state based on your chosen option. This becomes your new starting point for the next iteration. + +5. Repeat steps 2-4 until you reach the goal state or no further progress is possible. Keep making the best local choices until you reach the end of the problem or get stuck.. + +Example: + +Let’s say you have a set of coins with values {1, 2, 5, 10, 20, 50, 100} and you need to give minimum number of coin to someone change for 36. + +``` +The greedy algorithm for making change would work as follows: + + 1. Start with the largest coin value that is less than or equal to the amount to be changed. In this case, the largest coin less than 36 is 20. + + 2. Subtract the largest coin value from the amount to be changed, and add the coin to the solution. In this case, subtracting 20 from 36 gives 16, and we add a 20 coin to the solution. + + 3. Repeat steps 1 and 2 until the amount to be changed becomes 0. + + So, using the greedy algorithm, the solution for making change for 36 would be one 20 coins, one 10 coin, one 5 coins and one 1 coin needed. +``` + +Note: This is just one example, and other greedy choices could have been made at each step. However, in this case, the greedy approach leads to the optimal solution. + +The greedy algorithm is not always the optimal solution for every optimization problem, as shown in the example below. + +``` +1. One such example where the Greedy Approach fails is to find the Maximum weighted path of nodes in the given graph. + + + ![alt text](image-4.png) + + +2. In the above graph starting from the root node 10 if we greedily select the next node to obtain the most weighted path the next selected node will be 5 that will take the total sum to 15 and the path will end as there is no child of 5 but the path 10 -> 5 is not the maximum weight path. + + ![alt text](image-5.png) + +3. In order to find the most weighted path all possible path sum must be computed and their path sum must be compared to get the desired result, it is visible that the most weighted path in the above graph is 10 -> 1 -> 30 that gives the path sum 41. + + ![alt text](image-6.png) + +In such cases Greedy approach wouldn’t work instead complete paths from root to leaf node has to be considered to get the correct answer i.e. the most weighted path, This can be achieved by recursively checking all the paths and calculating their weight. + +``` + +| Criteria | Greedy Algorithm | Dynamic Programming | +| ----------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------ | +| Basic Idea | Makes the locally optimal choice at each stage | Solves subproblems and builds up to the optimal solution | +| Optimal Solution | Not always guaranteed to provide the globally optimal solution | Guarantees the globally optimal solution | +| Time Complexity | Typically faster; often linear or polynomial time | Usually slower due to solving overlapping subproblems | +| Space Complexity | Requires less memory; often constant or linear space | Requires more memory due to storing intermediate results | +| Subproblems Overlapping | Does not handle overlapping subproblems | Handles overlapping subproblems efficiently | +| Examples | Finding minimum spanning tree, Huffman coding | Matrix chain multiplication, shortest path problems | +| Applications | Used when a greedy choice at each step leads to the globally optimal solution | Applied when the problem can be broken down into overlapping subproblems | + +## Applications of Greedy Algorithms: + +1. Dijkstra’s shortest path algorithm: Finds the shortest path between two nodes in a graph. + +2. Kruskal’s minimum spanning tree algorithm: Finds the minimum spanning tree for a weighted graph. + +3. Huffman coding: Creates an optimal prefix code for a set of symbols based on their frequencies. + +4. Fractional knapsack problem: Determines the most valuable items to carry in a knapsack with a limited weight capacity. + +5. Activity selection problem: Chooses the maximum number of non-overlapping activities from a set of activities. + +## Advantages of Greedy Algorithms: + + 1. Simple and easy to understand: Greedy algorithms are often straightforward to implement and reason about. + + 2. Efficient for certain problems: They can provide optimal solutions for specific problems, like finding the shortest path in a graph with non-negative edge weights. + + 3. Fast execution time: Greedy algorithms generally have lower time complexity compared to other algorithms for certain problems. + + 4. Intuitive and easy to explain: The decision-making process in a greedy algorithm is often easy to understand and justify. + + 5. Can be used as building blocks for more complex algorithms: Greedy algorithms can be combined with other techniques to design more sophisticated algorithms for challenging problems. + +## Disadvantages of the Greedy Approach: + + 1. Not always optimal: Greedy algorithms prioritize local optima over global optima, leading to suboptimal solutions in some cases. + + 2. Difficult to prove optimality: Proving the optimality of a greedy algorithm can be challenging, requiring careful analysis. + + 3. Sensitive to input order: The order of input data can affect the solution generated by a greedy algorithm. + + 4. Limited applicability: Greedy algorithms are not suitable for all problems and may not be applicable to problems with complex constraints. diff --git a/docs/Advance/RabinKarp_README.md b/docs/Advance/RabinKarp_README.md new file mode 100644 index 0000000..3a84e6f --- /dev/null +++ b/docs/Advance/RabinKarp_README.md @@ -0,0 +1,263 @@ +--- +id: rabin-karp +title: Rabin Karp Algorithm Solution +sidebar_label: 0004 - Rabin Karp Algorithm +tags: [Rabin Karp, Substring Search, Algorithm, C++] +description: Efficient solution to the Rabin Karp algorithm problem using C++. +--- + +## Problem Statement + +### Problem Description + +The Rabin Karp algorithm searches for a pattern in a text using a hashing function. It compares the hash value of the pattern with the hash value of substrings of the text. If the hash values match, it performs a further comparison to confirm the match. + +### Examples + +**Example 1:** + +```plaintext +Input: Text = "GEEKS FOR GEEKS", Pattern = "GEEK" +Output: Pattern found at index 0 + Pattern found at index 10 +``` + +**Example 2:** + +```plaintext +Input: Text = "ABABDABACDABABCABAB", Pattern = "ABABCABAB" +Output: Pattern found at index 10 +``` + +### Constraints +- The input should be a text and a pattern. +- The algorithm should efficiently handle large texts and multiple pattern searches. + +## Solution of Given Problem + +### Intuition and Approach + +The Rabin Karp algorithm follows these steps: + +1. Calculate the hash value of the pattern. +2. Calculate the hash value of the first substring of the text with the same length as the pattern. +3. Slide the pattern over the text one by one and compare the hash value of the current substring of the text with the hash value of the pattern. +4. If the hash values match, perform a further comparison to confirm the match. +5. If the hash values do not match, continue to the next substring. + +### Approaches + +#### Codes in Different Languages + + + + + + ```cpp +#include +using namespace std; + +#define d 256 + +void search(string pat, string txt, int q) { + int M = pat.length(); + int N = txt.length(); + int i, j; + int p = 0; + int t = 0; + int h = 1; + + for (i = 0; i < M - 1; i++) + h = (h * d) % q; + + for (i = 0; i < M; i++) { + p = (d * p + pat[i]) % q; + t = (d * t + txt[i]) % q; + } + + for (i = 0; i <= N - M; i++) { + if (p == t) { + for (j = 0; j < M; j++) { + if (txt[i + j] != pat[j]) + break; + } + if (j == M) + cout << "Pattern found at index " << i << endl; + } + if (i < N - M) { + t = (d * (t - txt[i] * h) + txt[i + M]) % q; + if (t < 0) + t = (t + q); + } + } +} + +int main() { + string txt = "GEEKS FOR GEEKS"; + string pat = "GEEK"; + int q = 101; + search(pat, txt, q); + return 0; +} + ``` + + +```Python showLineNumbers +def search(pat, txt, q): + d = 256 + M = len(pat) + N = len(txt) + p = 0 + t = 0 + h = 1 + + for i in range(M - 1): + h = (h * d) % q + + for i in range(M): + p = (d * p + ord(pat[i])) % q + t = (d * t + ord(txt[i])) % q + + for i in range(N - M + 1): + if p == t: + for j in range(M): + if txt[i + j] != pat[j]: + break + if j == M - 1: + print("Pattern found at index", i) + if i < N - M: + t = (d * (t - ord(txt[i]) * h) + ord(txt[i + M])) % q + if t < 0: + t = t + q + +txt = "GEEKS FOR GEEKS" +pat = "GEEK" +q = 101 +search(pat, txt, q) + + +``` + + +``` jsx showLineNumbers +import java.util.*; + +public class RabinKarp { + public final static int d = 256; + + static void search(String pat, String txt, int q) { + int M = pat.length(); + int N = txt.length(); + int i, j; + int p = 0; // hash value for pattern + int t = 0; // hash value for txt + int h = 1; + + for (i = 0; i < M - 1; i++) + h = (h * d) % q; + + for (i = 0; i < M; i++) { + p = (d * p + pat.charAt(i)) % q; + t = (d * t + txt.charAt(i)) % q; + } + + for (i = 0; i <= N - M; i++) { + if (p == t) { + for (j = 0; j < M; j++) { + if (txt.charAt(i + j) != pat.charAt(j)) + break; + } + if (j == M) + System.out.println("Pattern found at index " + i); + } + if (i < N - M) { + t = (d * (t - txt.charAt(i) * h) + txt.charAt(i + M)) % q; + if (t < 0) + t = (t + q); + } + } + } + + public static void main(String[] args) { + String txt = "GEEKS FOR GEEKS"; + String pat = "GEEK"; + int q = 101; + search(pat, txt, q); + } +} + +``` + + + +``` jsx showLineNumbers +function search(pat, txt, q) { + const d = 256; + const M = pat.length; + const N = txt.length; + let p = 0; + let t = 0; + let h = 1; + + for (let i = 0; i < M - 1; i++) + h = (h * d) % q; + + for (let i = 0; i < M; i++) { + p = (d * p + pat.charCodeAt(i)) % q; + t = (d * t + txt.charCodeAt(i)) % q; + } + + for (let i = 0; i <= N - M; i++) { + if (p == t) { + let j; + for (j = 0; j < M; j++) { + if (txt.charAt(i + j) != pat.charAt(j)) + break; + } + if (j == M) + console.log("Pattern found at index " + i); + } + if (i < N - M) { + t = (d * (t - txt.charCodeAt(i) * h) + txt.charCodeAt(i + M)) % q; + if (t < 0) + t = (t + q); + } + } +} + +const txt = "GEEKS FOR GEEKS"; +const pat = "GEEK"; +const q = 101; +search(pat, txt, q); + +``` + + + + + +### Complexity Analysis + +- **Time Complexity:** Average case: $O(n + m)$, Worst case: $O(nm)$ (if all characters of the pattern and text are the same). +- **Space Complexity:** $O(1)$. +- Where `n` is the length of the text and `m` is the length of the pattern. + +## Video Explanation of Given Problem + + + +--- + +

Authors:

+ +
+{['sjain1909'].map(username => ( + +))} +
diff --git a/docs/Advance/Randomised Algorithm.md b/docs/Advance/Randomised Algorithm.md new file mode 100644 index 0000000..5ddb2c8 --- /dev/null +++ b/docs/Advance/Randomised Algorithm.md @@ -0,0 +1,91 @@ +--- +id: randomised-algorithm +title: Randomised Algorithm +sidebar_label: Randomised Algorithm +tags: + - Randomised Algorithm + - data-structures + - advance + - javascript + - python + - c++ + - java + - programming +sidebar_position: 10 +--- + +## Randomised Algorithm + +Randomized algorithms in data structures and algorithms (DSA) are algorithms that use randomness in their computations to achieve a desired outcome. These algorithms introduce randomness to improve efficiency or simplify the algorithm design. By incorporating random choices into their processes, randomized algorithms can often provide faster solutions or better approximations compared to deterministic algorithms. + +They are particularly useful in situations where exact solutions are difficult to find or when a probabilistic approach is acceptable. + +## Example + +For example, in Randomized Quick Sort, we use a random number to pick the next pivot (or we randomly shuffle the array). Typically, this randomness is used to reduce time complexity or space complexity in other standard algorithms. + +## Random variable + +A random variable in statistics is a function that assigns a real value to an outcome in the sample space of a random experiment. For example: if you roll a die, you can assign a number to each possible outcome. + +Random variables can have specific values or any value in a range. + +There are two basic types of random variables, + +- Discrete Random Variables +- Continuous Random Variables + +## Understanding + +Randomized algorithm is a different design approach taken by the standard algorithms where few random bits are added to a part of their logic. They are different from deterministic algorithms; deterministic algorithms follow a definite procedure to get the same output every time an input is passed where randomized algorithms produce a different output every time they’re executed. It is important to note that it is not the input that is randomized, but the logic of the standard algorithm + +![Figure 1: Deterministic Algorithm](../../assets/random1.png) +Deterministic Algorithm + +Unlike deterministic algorithms, randomized algorithms consider randomized bits of the logic along with the input that in turn contribute towards obtaining the output. + +![Figure 2: Randomized Algorithm](../../assets/random2.png) + Randomized Algorithm + +However, the probability of randomized algorithms providing incorrect output cannot be ruled out either. Hence, the process called amplification is performed to reduce the likelihood of these erroneous outputs. Amplification is also an algorithm that is applied to execute some parts of the randomized algorithms multiple times to increase the probability of correctness. However, too much amplification can also exceed the time constraints making the algorithm ineffective. + +## Classification of Randomized Algorithms + +Randomized algorithms are classified based on whether they have time constraints as the random variable or deterministic values. They are designed in their two common forms βˆ’ Las Vegas and Monte Carlo. + +![](../../assets/random3.png) + +``` +- Las Vegas βˆ’ The Las Vegas method of randomized algorithms never gives incorrect outputs, making the time constraint as the random variable. For example, in string matching algorithms, las vegas algorithms start from the beginning once they encounter an error. This increases the probability of correctness. Eg., Randomized Quick Sort Algorithm. + +- Monte Carlo βˆ’ The Monte Carlo method of randomized algorithms focuses on finishing the execution within the given time constraint. Therefore, the running time of this method is deterministic. For example, in string matching, if monte carlo encounters an error, it restarts the algorithm from the same point. Thus, saving time. Eg., Karger’s Minimum Cut Algorithm +``` + +## Need for Randomized Algorithms + +This approach is usually adopted to reduce the time complexity and space complexity. But there might be some ambiguity about how adding randomness will decrease the runtime and memory stored, instead of increasing; we will understand that using the game theory. + +## The Game Theory and Randomized Algorithms + +The basic idea of game theory actually provides with few models that help understand how decision-makers in a game interact with each other. These game theoretical models use assumptions to figure out the decision-making structure of the players in a game. The popular assumptions made by these theoretical models are that the players are both rational and take into account what the opponent player would decide to do in a particular situation of a game. We will apply this theory on randomized algorithms. + +## Zero-sum game + +The zero-sum game is a mathematical representation of the game theory. It has two players where the result is a gain for one player while it is an equivalent loss to the other player. So, the net improvement is the sum of both players’ status which sums up to zero. + +Randomized algorithms are based on the zero-sum game of designing an algorithm that gives lowest time complexity for all inputs. There are two players in the game; one designs the algorithm and the opponent provides with inputs for the algorithm. The player two needs to give the input in such a way that it will yield the worst time complexity for them to win the game. Whereas, the player one needs to design an algorithm that takes minimum time to execute any input given. + +For example, consider the quick sort algorithm where the main algorithm starts from selecting the pivot element. But, if the player in zero-sum game chooses the sorted list as an input, the standard algorithm provides the worst case time complexity. Therefore, randomizing the pivot selection would execute the algorithm faster than the worst time complexity. However, even if the algorithm chose the first element as pivot randomly and obtains the worst time complexity, executing it another time with the same input will solve the problem since it chooses another pivot this time. + +On the other hand, for algorithms like merge sort the time complexity does not depend on the input; even if the algorithm is randomized the time complexity will always remain the same. Hence, randomization is only applied on algorithms whose complexity depends on the input. + +## Examples +Few popular examples of the Randomized algorithms are βˆ’ + +Randomized Quick Sort Algorithm + +Karger’s Minimum Cut Algorithm + +Fisher-Yates Shuffle Algorithm + +The Subset Sum Problem \ No newline at end of file diff --git a/docs/Advance/SegmentTree.md b/docs/Advance/SegmentTree.md new file mode 100644 index 0000000..57a9f27 --- /dev/null +++ b/docs/Advance/SegmentTree.md @@ -0,0 +1,91 @@ +# Segment Tree + +A Segment Tree is a data structure that allows efficient range queries and updates on an array. It is particularly useful for problems where you need to perform multiple range queries and updates on an array. + +## Key Features + +- **Space Complexity:** O(n) +- **Time Complexity for Updates:** O(log n) +- **Time Complexity for Queries:** O(log n) + +## Algorithm Description + +A Segment Tree is a binary tree where each node represents an interval or segment of the array. The tree allows efficient querying of aggregate information (such as sum, minimum, or maximum) over any segment of the array, as well as efficient updates to individual elements. + +### Operations + +1. **Build:** Construct the tree from the given array. +2. **Update:** Update an element in the array and propagate the change through the tree. +3. **Query:** Calculate the aggregate information over a specified range of the array. + +## Python Implementation + +Here is a Python implementation of a Segment Tree for range sum queries: + +```python +class SegmentTree: + def __init__(self, data): + self.n = len(data) + self.tree = [0] * (2 * self.n) + self.build(data) + + def build(self, data): + # Initialize leaves in the segment tree + for i in range(self.n): + self.tree[self.n + i] = data[i] + # Build the tree by calculating parents + for i in range(self.n - 1, 0, -1): + self.tree[i] = self.tree[i * 2] + self.tree[i * 2 + 1] + + def update(self, index, value): + # Update the value at the leaf node + index += self.n + self.tree[index] = value + # Propagate the update up the tree + while index > 1: + index //= 2 + self.tree[index] = self.tree[2 * index] + self.tree[2 * index + 1] + + def query(self, left, right): + # Query the sum in the range [left, right) + result = 0 + left += self.n + right += self.n + while left < right: + if left % 2: + result += self.tree[left] + left += 1 + if right % 2: + right -= 1 + result += self.tree[right] + left //= 2 + right //= 2 + return result +``` + +# Example usage +if __name__ == "__main__": + data = [1, 3, 5, 7, 9, 11] + seg_tree = SegmentTree(data) + + print("Initial Segment Tree:", seg_tree.tree) + + # Query the sum of range [1, 5) + print("Sum of range [1, 5):", seg_tree.query(1, 5)) + + # Update index 2 to value 6 + seg_tree.update(2, 6) + print("Segment Tree after update:", seg_tree.tree) + + # Query again after the update + print("Sum of range [1, 5) after update:", seg_tree.query(1, 5)) +# Explanation +The SegmentTree class initializes the tree and provides methods for building the tree, updating elements, and querying ranges. +The build method constructs the tree by initializing the leaves with the input data and then building the parent nodes. +The update method updates an element at a given index and propagates the change up the tree. +The query method calculates the sum of elements within a specified range by traversing the tree. + + +## Conclusion +Segment Trees are powerful data structures for handling range queries and updates efficiently. They are widely used in scenarios requiring frequent and dynamic range queries, such as in competitive programming, database indexing, and real-time data analysis. + diff --git a/docs/Advance/_category_.json b/docs/Advance/_category_.json new file mode 100644 index 0000000..fe5b675 --- /dev/null +++ b/docs/Advance/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Advance", + "position": 3, + "link": { + "type": "generated-index", + "description": "Learn the Advance topic of the Data Structures." + } +} diff --git a/docs/Advance/aho-corasick.md b/docs/Advance/aho-corasick.md new file mode 100644 index 0000000..da2416f --- /dev/null +++ b/docs/Advance/aho-corasick.md @@ -0,0 +1,198 @@ +--- +id: aho-corasick-algorithm +title: Aho-Corasick Algorithm for Efficient String Matching +sidebar_label: 0011 - Aho-Corasick Algorithm +tags: [Aho-Corasick, String Matching, Algorithm, C++, Problem Solving] +description: This is a solution for implementing the Aho-Corasick Algorithm to search multiple patterns simultaneously in a given text. +--- + +## Problem Statement + +### Problem Description + +The Aho-Corasick Algorithm is designed for searching multiple patterns simultaneously within a given text. It constructs a finite state machine that resembles a digital tree with additional links between nodes, allowing efficient transitions between patterns. + +### Examples + +**Example 1:** + +```plaintext +Input: +Patterns: {"he", "she", "his", "hers"} +Text: "ahishers" +Output: +Pattern found: he at index 1 +Pattern found: his at index 1 +Pattern found: she at index 3 +Pattern found: hers at index 4 + +Explanation: All the patterns are efficiently found within the text. +``` + +### Constraints + +- The input consists of multiple patterns and a single text. +- The algorithm should handle large patterns and text sizes efficiently. + +## Solution of Given Problem + +### Intuition and Approach + +The Aho-Corasick Algorithm follows these steps: + +1. Build a Trie: Insert all patterns into a trie. +2. Construct Failure Links: Create failure links to enable efficient transitions when a mismatch occurs. +3. Search the Text: Use the trie and failure links to search the text for all patterns simultaneously. + +### Approaches + +#### Codes in Different Languages + + + + + ```cpp + #include + using namespace std; + + struct TrieNode { + unordered_map children; + TrieNode* failure; + vector output; + TrieNode() : failure(nullptr) {} +}; + +class AhoCorasick { + TrieNode* root; + vector patterns; + +public: + AhoCorasick() { + root = new TrieNode(); + } + + void addPattern(const string& pattern, int index) { + TrieNode* node = root; + for (char c : pattern) { + if (node->children.find(c) == node->children.end()) { + node->children[c] = new TrieNode(); + } + node = node->children[c]; + } + node->output.push_back(index); + } + + void buildFailureLinks() { + queue q; + root->failure = root; + for (auto& child : root->children) { + child.second->failure = root; + q.push(child.second); + } + + while (!q.empty()) { + TrieNode* current = q.front(); + q.pop(); + + for (auto& child : current->children) { + char c = child.first; + TrieNode* fail = current->failure; + + while (fail != root && fail->children.find(c) == fail->children.end()) { + fail = fail->failure; + } + + if (fail->children.find(c) != fail->children.end()) { + child.second->failure = fail->children[c]; + } else { + child.second->failure = root; + } + + child.second->output.insert(child.second->output.end(), + child.second->failure->output.begin(), child.second->failure->output.end()); + + q.push(child.second); + } + } + } + + void search(const string& text) { + TrieNode* node = root; + for (int i = 0; i < text.size(); ++i) { + char c = text[i]; + while (node != root && node->children.find(c) == node->children.end()) { + node = node->failure; + } + + if (node->children.find(c) != node->children.end()) { + node = node->children[c]; + } else { + node = root; + } + + if (!node->output.empty()) { + for (int index : node->output) { + cout << "Pattern found: " << patterns[index] << " at index " << i - patterns[index].size() + 1 << "\n"; + } + } + } + } + + void initialize(const vector& patterns) { + this->patterns = patterns; + for (int i = 0; i < patterns.size(); ++i) { + addPattern(patterns[i], i); + } + buildFailureLinks(); + } +}; + +int main() { + int n; + cout << "Enter number of patterns: "; + cin >> n; + vector patterns(n); + cout << "Enter patterns:\n"; + for (int i = 0; i < n; ++i) { + cin >> patterns[i]; + } + + string text; + cout << "Enter text: "; + cin >> text; + + AhoCorasick ac; + ac.initialize(patterns); + ac.search(text); + + return 0; +} + ``` + + + +### Complexity Analysis + +- **Time Complexity:** $O(N + M + Z)$ where `N` is the length of the text, `M` is the total length of all patterns, and `Z` is the number of pattern occurrences. +- **Space Complexity:** $O(M)$ + +The time complexity accounts for building the trie, constructing failure links, and searching the text. The space complexity is linear with respect to the total length of the patterns. + +## Video Explanation of Given Problem + + +--- + +

Authors:

+ +
+{['sjain1909'].map(username => ( + +))} +
diff --git a/docs/Advance/bellman-ford.md b/docs/Advance/bellman-ford.md new file mode 100644 index 0000000..c19f421 --- /dev/null +++ b/docs/Advance/bellman-ford.md @@ -0,0 +1,134 @@ +--- +id: bellman-ford +title: Bellman-Ford Algorithm Solution +sidebar_label: 0004 - Bellman-Ford Algorithm +tags: [Bellman-Ford, Shortest Path, Algorithm, C++, Problem Solving] +description: This is a solution to the Bellman-Ford algorithm problem. +--- + +## Problem Statement + +### Problem Description + +The Bellman-Ford algorithm computes the shortest paths from a single source vertex to all other vertices in a weighted graph. It is designed to find the shortest paths from a source vertex to all other vertices in a graph, even if the graph contains edges with negative weights. It can also detect negative weight cycles. + +### Examples + +**Example 1:** + +```plaintext +Input: Vertices = 5, Edges = {(0, 1, -1), (0, 2, 4), (1, 2, 3), (1, 3, 2), (1, 4, 2), (3, 1, 1), (3, 4, 5), (4, 3, -3)} +Source: 0 +Output: +0: 0 +1: -1 +2: 2 +3: 1 +4: -2 +``` + +### Constraints + +- The graph may contain negative weight edges. +- The algorithm should handle up to 10^5 vertices and edges. + +## Solution of Given Problem + +### Intuition and Approach + +The Bellman-Ford algorithm follows these steps: + +1. Initialize the distance to the source vertex as zero and all other vertices as infinite. +2. Relax all edges |V| - 1 times, where |V| is the number of vertices. +3. Check for negative weight cycles by iterating over all edges again. + +### Approaches + +#### Codes in Different Languages + + + + + ```cpp + #include + using namespace std; + + struct Edge { + int src, dest, weight; + }; + + void BellmanFord(vector& edges, int V, int E, int src) { + vector dist(V, INT_MAX); + dist[src] = 0; + + for (int i = 1; i <= V - 1; ++i) { + for (int j = 0; j < E; ++j) { + if (dist[edges[j].src] != INT_MAX && dist[edges[j].src] + edges[j].weight < dist[edges[j].dest]) { + dist[edges[j].dest] = dist[edges[j].src] + edges[j].weight; + } + } + } + + for (int j = 0; j < E; ++j) { + if (dist[edges[j].src] != INT_MAX && dist[edges[j].src] + edges[j].weight < dist[edges[j].dest]) { + cout << "Graph contains negative weight cycle\n"; + return; + } + } + + cout << "Vertex Distance from Source:\n"; + for (int i = 0; i < V; ++i) { + cout << i << "\t\t" << dist[i] << "\n"; + } + } + + int main() { + int V, E; + cout << "Enter the number of vertices: "; + cin >> V; + cout << "Enter the number of edges: "; + cin >> E; + + vector edges(E); + for (int i = 0; i < E; ++i) { + cout << "Enter edge (src dest weight): "; + cin >> edges[i].src >> edges[i].dest >> edges[i].weight; + } + + int src; + cout << "Enter the source vertex: "; + cin >> src; + + BellmanFord(edges, V, E, src); + + return 0; + } + ``` + + + +### Complexity Analysis + +- **Time Complexity:** $O(V*E)$ +- **Space Complexity:** $O(V)$ + +The time complexity is determined by the relaxation of edges in the graph. The space complexity is linear due to the storage of distances. + +## Video Explanation of Given Problem + + +--- + +

Authors:

+ +
+{['sjain1909'].map(username => ( + +))} +
diff --git a/docs/Advance/binaryTree-mirror-rotation.md b/docs/Advance/binaryTree-mirror-rotation.md new file mode 100644 index 0000000..76b1848 --- /dev/null +++ b/docs/Advance/binaryTree-mirror-rotation.md @@ -0,0 +1,216 @@ +--- +id: binary-tree-mirror-rotate +title: Binary Tree Mirror and Rotation Solution +sidebar_label: 0005 - Binary Tree Mirror and Rotation +tags: [Binary Tree, Mirror Image, Tree Rotation, Algorithm, C++, Problem Solving] +description: This is a solution to create the mirror image and perform rotations (left and right) on a binary tree. +--- + +## Problem Statement + +### Problem Description + +Implement a feature to create the mirror image and perform rotations (left and right) on a binary tree. This functionality will allow users to easily transform binary trees for various algorithmic and visualization purposes. + +### Examples + +**Example 1:** + +```plaintext +Input: Binary Tree = [4, 2, 7, 1, 3, 6, 9] + + 4 + / \ + 2 7 + / \ / \ + 1 3 6 9 + +Mirror Image Output: + + 4 + / \ + 7 2 + / \ / \ + 9 6 3 1 + +``` +**Example 2:** + +```plaintext +Input: Binary Tree = [4, 2, 7, 1, 3, 6, 9] +Rotation (Left) Output: + + 2 + / \ + 1 4 + \ + 7 + / \ + 6 9 + +Rotation (Right) Output: + + 7 + / \ + 4 9 + / \ + 2 6 + / \ + 1 3 + + +``` +### Constraints + +- The input is a binary tree. +- The tree can have up to 10^5 nodes. + +## Solution of Given Problem + +### Intuition and Approach + +To solve the problem, we can break it down into three parts: + +1. Mirror Image: +- Swap the left and right children of each node recursively. + +2. Left Rotation: +- Rotate the tree around a specific node such that the node's right child becomes its parent. + +3. Right Rotation: +- Rotate the tree around a specific node such that the node's left child becomes its parent. + +### Approaches + +#### Codes in Different Languages + + + + + ```cpp +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +void mirror(TreeNode* node) { + if (node == NULL) + return; + + swap(node->left, node->right); + mirror(node->left); + mirror(node->right); +} + +TreeNode* leftRotate(TreeNode* root) { + if (root == NULL || root->right == NULL) + return root; + + TreeNode* newRoot = root->right; + root->right = newRoot->left; + newRoot->left = root; + + return newRoot; +} + +TreeNode* rightRotate(TreeNode* root) { + if (root == NULL || root->left == NULL) + return root; + + TreeNode* newRoot = root->left; + root->left = newRoot->right; + newRoot->right = root; + + return newRoot; +} + +void inorder(TreeNode* root) { + if (root == NULL) + return; + inorder(root->left); + cout << root->val << " "; + inorder(root->right); +} + +int main() { + int n, val; + cout << "Enter the number of nodes in the tree: "; + cin >> n; + + if (n == 0) { + cout << "The tree is empty." << endl; + return 0; + } + + cout << "Enter the values of the nodes: "; + vector nodes(n); + for (int i = 0; i < n; ++i) { + cin >> val; + nodes[i] = new TreeNode(val); + } + + for (int i = 0; i < n; ++i) { + int leftIndex, rightIndex; + cout << "Enter the left and right child indices for node with value " << nodes[i]->val << " (use -1 for no child): "; + cin >> leftIndex >> rightIndex; + if (leftIndex != -1) nodes[i]->left = nodes[leftIndex]; + if (rightIndex != -1) nodes[i]->right = nodes[rightIndex]; + } + + TreeNode* root = nodes[0]; + + cout << "Original Tree: "; + inorder(root); + cout << "\n"; + + mirror(root); + cout << "Mirror Image: "; + inorder(root); + cout << "\n"; + + root = leftRotate(root); + cout << "Left Rotation: "; + inorder(root); + cout << "\n"; + + root = rightRotate(root); + cout << "Right Rotation: "; + inorder(root); + cout << "\n"; + + return 0; +} + ``` + + + +### Complexity Analysis + +- **Time Complexity:** $O(n)$ +- **Space Complexity:** $O(h)$, where `h` is the height of the tree (due to the recursion stack). + +The time complexity is linear because each node is visited once. The space complexity is determined by the depth of the recursion stack. + +## Video Explanation of Given Problem + + +--- + +

Authors:

+ +
+{['sjain1909'].map(username => ( + +))} +
diff --git a/docs/Advance/bitManipulation.md b/docs/Advance/bitManipulation.md new file mode 100644 index 0000000..00a623e --- /dev/null +++ b/docs/Advance/bitManipulation.md @@ -0,0 +1,484 @@ +--- +id: 05-Bit Manipulation +title: Introduction to Bit Manipulation +sidebar_label: Bit Manipulation in DSA +tags: + - Bit Manipulation + - data-structures + - binary-tree + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial +sidebar_position: 4 +--- + +# Introduction to Bit Manipulation + +Bit Manipulation is a technique used in a variety of problems to get the solution in an optimized way. This technique is very effective from a Competitive Programming point of view. It is all about Bitwise Operators which directly works upon binary numbers or bits of numbers that help the implementation fast. Below are the Bitwise Operators that are used: + + 1. Bitwise AND (&) + 2. Bitwise OR (|) + 3. Bitwise XOR (^) + 4. Bitwise NOT (!) + +All data in computer programs are internally stored as bits, i.e., as numbers 0 and 1. + +## Bit representation + +In programming, an n-bit integer is internally stored as a binary number that consists of n bits. For example, the C++ type int is a 32-bit type, which means that every int number consists of 32 bits. + +The int number 43 = 00000000000000000000000000101011 + +The bits in the representation are indexed from right to left. To convert a bit representation bk Β·Β·Β·b2 b1 b0 into a number, we can use the formula +bk2k +…+ b222 + b121 + b020. + +E.g., 1Β·25+1Β·23 +1Β·21 +1Β·20 = 43. + +The bit representation of a number is either signed or unsigned. +Usually, a signed representation is used, which means that both negative and positive numbers can be represented. +A signed variable of n bits can contain any integer between -2n-1 and 2n-1 – 1 +The int type in C++ is a signed type, so an int variable can contain any integer between -231 and 231 – 1. + +The first bit in a signed representation is the sign of the number, 0 for non-negative numbers and 1 for negative numbers and the remaining nβˆ’1 bits contain the magnitude of the number. + +Two’s complement is used, which means that the opposite number of a number is calculated by first inverting all the bits in the number, and then increasing the number by one. +The bit representation of the int number βˆ’43 is 11111111111111111111111111010101 +In an unsigned representation, only non-negative numbers can be used, but the upper bound for the values is larger. +An unsigned variable of n bits can contain any integer between 0 and 2n βˆ’1. + +In C++, an unsigned int variable can contain any integer between 0 and 232 βˆ’1. +There is a connection between the representations: +A signed number βˆ’x equals an unsigned number 2n βˆ’ x. +For example, the following pseudo-code snippet shows that the signed number +x = βˆ’43 equals the unsigned number y = 232 βˆ’43: + + ![alt text](image-7.png) + +If a number is larger than the upper bound of the bit representation, the number will overflow. In a signed representation, the next number after 2n-1 – 1 is -2n-1, and in an unsigned representation, the next number after 2n -1 is 0. For example, consider the following pseudo-code snippet: + + ![alt text](image-8.png) + +Initially, the value of x is 231 βˆ’1. This is the largest value that can be stored in an int variable, so the next number after 231 βˆ’1 is βˆ’231 . + +## Bitwise Operations: + +Below is the table to illustrate the result when the operation is performed using Bitwise Operators. Here 0s or 1s mean a sequence of 0 or 1 respectively. + +| Operators | Operations | Result | +| --------- | ---------- | ------ | --- | +| XOR | X **^** 0s | X | +| XOR | X **^** 1s | ~X | +| XOR | X **^** X | 0 | +| AND | X & 0s | 0 | +| AND | X & 1s | X | +| AND | X & X | X | +| OR | X | 0s | X | +| OR | X | 1s | 1s | +| OR | X | X | X | + +## Get Bit: + +This method is used to find the bit at a particular position(say i) of the given number N. The idea is to find the Bitwise AND of the given number and 2i that can be represented as (1 `<<` i). If the value return is 1 then the bit at the ith position is set. Otherwise, it is unset. + +Below is the pseudo-code for the same: + + + + + ```cpp + // Function to get the bit at the + // ith position + bool getBit(int num, int i) { + // Return true if the bit is + // set. Otherwise return false + return ((num & (1 << i)) != 0); + } + + // Driver code + #include + int main() { + int num = 5; // Binary representation: 101 + int i = 1; // Checking the 2nd bit (0-based index) + std::cout << getBit(num, i) << std::endl; // Output: 0 (false) + + i = 2; // Checking the 3rd bit (0-based index) + std::cout << getBit(num, i) << std::endl; // Output: 1 (true) + + return 0; + } + ``` + + + + ```java + public class Solution { + // Function to get the bit at the ith position + public static boolean getBit(int num, int i) { + // Return true if the bit is set. Otherwise return false + return ((num & (1 << i)) != 0); + } + + // Driver code + public static void main(String[] args) { + int num = 5; // Binary representation: 101 + int i = 1; // Checking the 2nd bit (0-based index) + System.out.println(getBit(num, i)); // Output: false + + i = 2; // Checking the 3rd bit (0-based index) + System.out.println(getBit(num, i)); // Output: true + } + } + ``` + + + + ```python + # Function to get the bit at the ith position + def getBit(num: int, i: int) -> bool: + # Return true if the bit is set. Otherwise return false + return (num & (1 << i)) != 0 + + # Driver code + if __name__ == "__main__": + num = 5 # Binary representation: 101 + i = 1 # Checking the 2nd bit (0-based index) + print(getBit(num, i)) # Output: False + + i = 2 # Checking the 3rd bit (0-based index) + print(getBit(num, i)) # Output: True + ``` + + + + ```c + #include + #include + + // Function to get the bit at the ith position + bool getBit(int num, int i) { + // Return true if the bit is set. Otherwise return false + return ((num & (1 << i)) != 0); + } + + // Driver code + int main() { + int num = 5; // Binary representation: 101 + int i = 1; // Checking the 2nd bit (0-based index) + printf("%d\n", getBit(num, i)); // Output: 0 (false) + + i = 2; // Checking the 3rd bit (0-based index) + printf("%d\n", getBit(num, i)); // Output: 1 (true) + + return 0; + } + ``` + + + + +## Set Bit: + +This method is used to set the bit at a particular position(say i) of the given number N. The idea is to update the value of the given number N to the Bitwise OR of the given number N and 2i that can be represented as (1 `<<` i). If the value return is 1 then the bit at the ith position is set. Otherwise, it is unset. + +Below is the pseudo-code for the same: + + + + + ```cpp + // Function to set the bit at the + // ith position + int setBit(int num, int i) { + // Sets the ith bit and return + // the updated value + return num | (1 << i); + } + + // Driver code + #include + int main() { + int num = 5; // Binary representation: 101 + int i = 1; // Setting the 2nd bit (0-based index) + std::cout << setBit(num, i) << std::endl; // Output: 7 (111) + + i = 0; // Setting the 1st bit (0-based index) + std::cout << setBit(num, i) << std::endl; // Output: 5 (101, unchanged) + + return 0; + } + ``` + + + + ```java + public class Solution { + // Function to set the bit at the ith position + public static int setBit(int num, int i) { + // Sets the ith bit and return + // the updated value + return num | (1 << i); + } + + // Driver code + public static void main(String[] args) { + int num = 5; // Binary representation: 101 + int i = 1; // Setting the 2nd bit (0-based index) + System.out.println(setBit(num, i)); // Output: 7 (111) + + i = 0; // Setting the 1st bit (0-based index) + System.out.println(setBit(num, i)); // Output: 5 (101, unchanged) + } + } + ``` + + + + ```python + # Function to set the bit at the ith position + def setBit(num: int, i: int) -> int: + # Sets the ith bit and return + # the updated value + return num | (1 << i) + + # Driver code + if __name__ == "__main__": + num = 5 # Binary representation: 101 + i = 1 # Setting the 2nd bit (0-based index) + print(setBit(num, i)) # Output: 7 (111) + + i = 0 # Setting the 1st bit (0-based index) + print(setBit(num, i)) # Output: 5 (101, unchanged) + ``` + + + + ```c + #include + + // Function to set the bit at the ith position + int setBit(int num, int i) { + // Sets the ith bit and return + // the updated value + return num | (1 << i); + } + + // Driver code + int main() { + int num = 5; // Binary representation: 101 + int i = 1; // Setting the 2nd bit (0-based index) + printf("%d\n", setBit(num, i)); // Output: 7 (111) + + i = 0; // Setting the 1st bit (0-based index) + printf("%d\n", setBit(num, i)); // Output: 5 (101, unchanged) + + return 0; + } + ``` + + + + +## Clear Bit: + +This method is used to clear the bit at a particular position(say i) of the given number N. The idea is to update the value of the given number N to the Bitwise AND of the given number N and the compliment of 2i that can be represented as ~(1 `<<` i). If the value return is 1 then the bit at the ith position is set. Otherwise, it is unset. + +Below is the pseudo-code for the same: + + + + + ```cpp + // Function to clear the bit at the + // ith position + int clearBit(int num, int i) { + // Create the mask for the ith + // bit unset + int mask = ~(1 << i); + + // Return the updated value + return num & mask; + } + + // Driver code + #include + int main() { + int num = 5; // Binary representation: 101 + int i = 0; // Clearing the 1st bit (0-based index) + std::cout << clearBit(num, i) << std::endl; // Output: 4 (100) + + i = 2; // Clearing the 3rd bit (0-based index) + std::cout << clearBit(num, i) << std::endl; // Output: 1 (001) + + return 0; + } + ``` + + + + ```java + public class Solution { + // Function to clear the bit at the ith position + public static int clearBit(int num, int i) { + // Create the mask for the ith + // bit unset + int mask = ~(1 << i); + + // Return the updated value + return num & mask; + } + + // Driver code + public static void main(String[] args) { + int num = 5; // Binary representation: 101 + int i = 0; // Clearing the 1st bit (0-based index) + System.out.println(clearBit(num, i)); // Output: 4 (100) + + i = 2; // Clearing the 3rd bit (0-based index) + System.out.println(clearBit(num, i)); // Output: 1 (001) + } + } + ``` + + + + ```python + # Function to clear the bit at the ith position + def clearBit(num: int, i: int) -> int: + # Create the mask for the ith + # bit unset + mask = ~(1 << i) + + # Return the updated value + return num & mask + + # Driver code + if __name__ == "__main__": + num = 5 # Binary representation: 101 + i = 0 # Clearing the 1st bit (0-based index) + print(clearBit(num, i)) # Output: 4 (100) + + i = 2 # Clearing the 3rd bit (0-based index) + print(clearBit(num, i)) # Output: 1 (001) + ``` + + + + ```c + #include + + // Function to clear the bit at the ith position + int clearBit(int num, int i) { + // Create the mask for the ith + // bit unset + int mask = ~(1 << i); + + // Return the updated value + return num & mask; + } + + // Driver code + int main() { + int num = 5; // Binary representation: 101 + int i = 0; // Clearing the 1st bit (0-based index) + printf("%d\n", clearBit(num, i)); // Output: 4 (100) + + i = 2; // Clearing the 3rd bit (0-based index) + printf("%d\n", clearBit(num, i)); // Output: 1 (001) + + return 0; + } + ``` + + + + +Below is the program that implements the above functionalities: + +// C++ program to implement all the +// above functionalities + +``` +#include +using namespace std; + +// Function to get the bit at the +// ith position +bool getBit(int num, int i) +{ +// Return true if the ith bit is +// set. Otherwise return false +return ((num & (1 << i)) != 0); +} + +// Function to set the ith bit of the +// given number num +int setBit(int num, int i) +{ +// Sets the ith bit and return +// the updated value +return num | (1 << i); +} + +// Function to clear the ith bit of +// the given number num +int clearBit(int num, int i) +{ + + // Create the mask for the ith + // bit unset + int mask = ~(1 << i); + + // Return the updated value + return num & mask; + +} + +// Driver Code +int main() +{ +// Given number N +int N = 70; + + cout << "The bit at the 3rd position from LSB is: " + << (getBit(N, 3) ? '1' : '0') + << endl; + + cout << "The value of the given number " + << "after setting the bit at " + << "LSB is: " + << setBit(N, 0) << endl; + + cout << "The value of the given number " + << "after clearing the bit at " + << "LSB is: " + << clearBit(N, 0) << endl; + + return 0; + +} +``` + +### Output + +``` + The bit at the 3rd position from LSB is: 0 + The value of the given number after setting the bit at LSB is: 71 + The value of the given number after clearing the bit at LSB is: 70 +``` + +Time Complexity: $O(1)$ +Auxiliary Space: $O(1)$ + +## Application of Bitwise Operator + +1. Bitwise operations are prominent in embedded systems, control systems, etc where memory(data transmission/data points) is still an issue. + +2. They are also useful in networking where it is important to reduce the amount of data, so booleans are packed together. Packing them together and taking them apart use bitwise operations and shift instructions. + +3. Bitwise operations are also heavily used in the compression and encryption of data. + +4. Useful in graphics programming, older GUIs are heavily dependent on bitwise operations like XOR(^) for selection highlighting and other overlays diff --git a/docs/Advance/bit_manipulation_leetcode.md b/docs/Advance/bit_manipulation_leetcode.md new file mode 100644 index 0000000..b7c925e --- /dev/null +++ b/docs/Advance/bit_manipulation_leetcode.md @@ -0,0 +1,79 @@ +--- +id: 05-Leetcode Bit Manipulation Practice Questions +title: Leetcode Bit Manipulation Practice Questions +sidebar_label: Leetcode Bit Manipulation Practice Questions +tags: + - Bit Manipulation + - data-structures + - binary-tree + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial +sidebar_position: 5 +--- + +# Bit Manipulation LeetCode Questions + +1. **[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/)** - Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). + +2. **[Power of Two](https://leetcode.com/problems/power-of-two/)** - Given an integer, write a function to determine if it is a power of two. + +3. **[Counting Bits](https://leetcode.com/problems/counting-bits/)** - Given a non negative integer number num, for every numbers i in the range 0 ≀ i ≀ num calculate the number of 1's in their binary representation and return them as an array. + +4. **[Reverse Bits](https://leetcode.com/problems/reverse-bits/)** - Reverse bits of a given 32 bits unsigned integer. + +5. **[Single Number](https://leetcode.com/problems/single-number/)** - Given a non-empty array of integers, every element appears twice except for one. Find that single one. + +6. **[Single Number II](https://leetcode.com/problems/single-number-ii/)** - Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. + +7. **[Single Number III](https://leetcode.com/problems/single-number-iii/)** - Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. + +8. **[Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/)** - Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. + +9. **[Missing Number](https://leetcode.com/problems/missing-number/)** - Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. + +10. **[Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/)** - All DNA is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T', finds all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. + +11. **[Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/)** - Given a range [m, n], return the bitwise AND of all numbers in this range, inclusive. + +12. **[UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/)** - A character in UTF8 can be from 1 to 4 bytes long. Given an array of integers representing the data, return whether it is a valid utf-8 encoding. + +13. **[Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/)** - The Hamming distance between two integers is the number of positions at which the corresponding bits are different. + +14. **[Binary Watch](https://leetcode.com/problems/binary-watch/)** - A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). + +15. **[Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/)** - Given an array of numbers, find the maximum result of ai XOR aj, where 0 ≀ i, j < n. + +16. **[Find the Difference](https://leetcode.com/problems/find-the-difference/)** - Given two strings s and t which consist of only lowercase letters. String t is generated by random shuffling string s and then add one more letter at a random position. Find the letter that was added in t. + +17. **[Binary Number with Alternating Bits](https://leetcode.com/problems/binary-number-with-alternating-bits/)** - Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. + +18. **[Complement of Base 10 Integer](https://leetcode.com/problems/complement-of-base-10-integer/)** - Every non-negative integer N has a binary representation. The complement of a number is the number you get when you flip every bit in its binary representation. + +19. **[Binary Gap](https://leetcode.com/problems/binary-gap/)** - Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N. + +20. **[Convert Binary Number in a Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/)** - Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. + +21. **[XOR Operation in an Array](https://leetcode.com/problems/xor-operation-in-an-array/)** - Given an integer n and an integer start, define an array nums where nums[i] = start + 2\*i (0-indexed) and n == nums.length. Return the bitwise XOR of all elements of nums. + +22. **[Find XOR Sum of All Pairs Bitwise AND](https://leetcode.com/problems/find-xor-sum-of-all-pairs-bitwise-and/)** - Given two arrays nums1 and nums2, find the XOR sum of all pairs bitwise AND. + +23. **[Sum of All Subset XOR Totals](https://leetcode.com/problems/sum-of-all-subset-xor-totals/)** - The XOR total of an array is defined as the bitwise XOR of all its elements. + +24. **[Minimum XOR Sum of Two Arrays](https://leetcode.com/problems/minimum-xor-sum-of-two-arrays/)** - You are given two integer arrays nums1 and nums2 of length n. Return the minimum possible XOR sum of pairs of integers. + +25. **[Check If a String Contains All Binary Codes of Size K](https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/)** - Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. + +26. **[Decode XORed Array](https://leetcode.com/problems/decode-xored-array/)** - Given an encoded array where encoded[i] = arr[i] XOR arr[i + 1], return the original array arr. + +27. **[Minimum One Bit Operations to Make Integers Zero](https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero/)** - Given an integer n, you must transform it into 0 using the minimum number of one bit operations you can perform. + +28. **[Maximum XOR for Each Query](https://leetcode.com/problems/maximum-xor-for-each-query/)** - You are given a sorted array and an integer, return the maximum XOR value for each query. + +29. **[Maximum Product of Splitted Binary Tree](https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/)** - Given a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. + +30. **[Maximum Good People Based on Statements](https://leetcode.com/problems/maximum-good-people-based-on-statements/)** - Given a list of statements about people, return the maximum number of good people based on the statements. diff --git a/docs/Advance/fenwickTree.md b/docs/Advance/fenwickTree.md new file mode 100644 index 0000000..7f5d3cd --- /dev/null +++ b/docs/Advance/fenwickTree.md @@ -0,0 +1,82 @@ +# Fenwick Tree (Binary Indexed Tree) + +A Fenwick Tree, also known as a Binary Indexed Tree (BIT), is a data structure that provides efficient methods for calculation and manipulation of the prefix sums of a table of values. + +## Key Features + +- **Space Complexity:** O(n) +- **Time Complexity for Updates:** O(log n) +- **Time Complexity for Queries:** O(log n) + +## Algorithm Description + +A Fenwick Tree is used to efficiently compute prefix sums and update elements. It is particularly useful in situations where there are frequent updates and prefix sum queries. + +### Operations + +1. **Initialization:** Create a tree of size n initialized to 0. +2. **Update:** Add a value to an element and propagate the change through the tree. +3. **Prefix Sum Query:** Calculate the sum of elements from the start of the array to a given index. + +## Python Implementation + +Here is a Python implementation of a Fenwick Tree: + +```python +class FenwickTree: + def __init__(self, size): + self.size = size + self.tree = [0] * (size + 1) + + def update(self, index, value): + """ + Adds `value` to the element at `index` in the Fenwick Tree. + """ + index += 1 # Fenwick Tree is 1-indexed + while index <= self.size: + self.tree[index] += value + index += index & -index + + def prefix_sum(self, index): + """ + Returns the sum of elements from the start to `index` in the Fenwick Tree. + """ + index += 1 # Fenwick Tree is 1-indexed + result = 0 + while index > 0: + result += self.tree[index] + index -= index & -index + return result + + def range_sum(self, left, right): + """ + Returns the sum of elements from `left` to `right` in the Fenwick Tree. + """ + return self.prefix_sum(right) - self.prefix_sum(left - 1) +``` +# Example usage +if __name__ == "__main__": + arr = [1, 7, 3, 0, 7, 8, 3, 2, 6, 2] + fenwick_tree = FenwickTree(len(arr)) + + # Build the Fenwick Tree + for i, val in enumerate(arr): + fenwick_tree.update(i, val) + + print("Prefix sum up to index 5:", fenwick_tree.prefix_sum(5)) + print("Range sum from index 2 to 6:", fenwick_tree.range_sum(2, 6)) + fenwick_tree.update(3, 5) # Update index 3 with +5 + print("Prefix sum up to index 5 after update:", fenwick_tree.prefix_sum(5)) + print("Range sum from index 2 to 6 after update:", fenwick_tree.range_sum(2, 6)) + + +# Explanation +The FenwickTree class initializes the tree with a given size and provides methods for updating elements and querying prefix sums. +The update method adds a value to an element at a given index and updates the tree accordingly. +The prefix_sum method calculates the sum of elements from the start to a given index. +The range_sum method calculates the sum of elements within a specified range by using the prefix sums. + +## Conclusion +Fenwick Trees are powerful and efficient data structures for handling prefix sums and updates in logarithmic time. They are particularly useful in scenarios involving frequent updates and queries, such as in competitive programming and real-time data analysis. + + diff --git a/docs/Advance/graph-versatility.md b/docs/Advance/graph-versatility.md new file mode 100644 index 0000000..da0af72 --- /dev/null +++ b/docs/Advance/graph-versatility.md @@ -0,0 +1,258 @@ +--- +id: versatile-graph-toolkit +title: Versatile Graph Toolkit +sidebar_label: 0005 - Versatile Graph Toolkit +tags: [Graph Algorithms, Dijkstra, Kruskal, DFS, BFS, C++, Problem Solving] +description: This is a solution for developing a versatile graph theory toolkit designed to address a wide range of DSA problems. +--- + +## Problem Statement + +### Problem Description + +The versatile graph theory toolkit provides implementations for fundamental graph algorithms such as Depth-First Search (DFS), Breadth-First Search (BFS), Dijkstra’s algorithm, and Kruskal’s algorithm. This toolkit offers an easy-to-use interface, enabling users to efficiently solve various DSA problems involving graph theory. + +### Examples + +**Example 1:** + +```plaintext +Input: +Number of vertices: 5 +Edges: +0 1 4 +0 2 2 +1 2 1 +1 3 5 +2 3 8 +2 4 10 +3 4 2 +Output: +DFS Traversal: 0 1 2 3 4 +BFS Traversal: 0 1 2 3 4 +Shortest Path from 0 to 4 (Dijkstra): 10 +Minimum Spanning Tree (Kruskal): +Edge: 1-2 Weight: 1 +Edge: 3-4 Weight: 2 +Edge: 0-2 Weight: 2 +Edge: 0-1 Weight: 4 + +``` + +### Constraints +- The toolkit should handle up to 10^5 vertices and edges. +- The graph can be directed or undirected, weighted or unweighted. + +## Solution of Given Problem + +### Intuition and Approach + +The versatile graph theory toolkit is designed with the following algorithms: + +1. Depth-First Search (DFS): Traverses the graph in a depthward motion, utilizing a stack or recursion. +2. Breadth-First Search (BFS): Traverses the graph level by level, utilizing a queue. +3. Dijkstra’s Algorithm: Finds the shortest path from a single source to all other vertices in a graph with non-negative weights. +4. Kruskal’s Algorithm: Finds the Minimum Spanning Tree (MST) for a graph by sorting edges and applying the union-find structure. + +### Approaches + +#### Codes in Different Languages + + + + + ```cpp + #include + using namespace std; + +void DFS(int v, vector>& adj, vector& visited) { + stack stack; + stack.push(v); + + while (!stack.empty()) { + int u = stack.top(); + stack.pop(); + + if (!visited[u]) { + cout << u << " "; + visited[u] = true; + } + + for (int i = adj[u].size() - 1; i >= 0; --i) { + if (!visited[adj[u][i]]) { + stack.push(adj[u][i]); + } + } + } +} + +void BFS(int v, vector>& adj, vector& visited) { + queue queue; + queue.push(v); + visited[v] = true; + + while (!queue.empty()) { + int u = queue.front(); + queue.pop(); + cout << u << " "; + + for (int i = 0; i < adj[u].size(); ++i) { + if (!visited[adj[u][i]]) { + queue.push(adj[u][i]); + visited[adj[u][i]] = true; + } + } + } +} + +void Dijkstra(int src, vector>>& adj, int V) { + vector dist(V, INT_MAX); + dist[src] = 0; + priority_queue, vector>, greater>> pq; + pq.push({0, src}); + + while (!pq.empty()) { + int u = pq.top().second; + pq.pop(); + + for (auto& edge : adj[u]) { + int v = edge.first; + int weight = edge.second; + + if (dist[u] + weight < dist[v]) { + dist[v] = dist[u] + weight; + pq.push({dist[v], v}); + } + } + } + + for (int i = 0; i < V; ++i) { + cout << "Distance from " << src << " to " << i << ": " << dist[i] << "\n"; + } +} + +struct Edge { + int u, v, weight; + bool operator<(const Edge& other) const { + return weight < other.weight; + } +}; + +int find(vector& parent, int i) { + if (parent[i] == -1) + return i; + return parent[i] = find(parent, parent[i]); +} + +void unionSets(vector& parent, vector& rank, int x, int y) { + int xroot = find(parent, x); + int yroot = find(parent, y); + + if (rank[xroot] < rank[yroot]) { + parent[xroot] = yroot; + } else if (rank[xroot] > rank[yroot]) { + parent[yroot] = xroot; + } else { + parent[yroot] = xroot; + rank[xroot]++; + } +} + +void Kruskal(vector& edges, int V) { + sort(edges.begin(), edges.end()); + vector parent(V, -1); + vector rank(V, 0); + vector result; + + for (auto& edge : edges) { + int x = find(parent, edge.u); + int y = find(parent, edge.v); + + if (x != y) { + result.push_back(edge); + unionSets(parent, rank, x, y); + } + } + + cout << "Minimum Spanning Tree:\n"; + for (auto& edge : result) { + cout << "Edge: " << edge.u << "-" << edge.v << " Weight: " << edge.weight << "\n"; + } +} + +int main() { + int V, E; + cout << "Enter the number of vertices: "; + cin >> V; + cout << "Enter the number of edges: "; + cin >> E; + + vector> adj(V); + vector>> adjWeighted(V); + vector edges; + + cout << "Enter the edges (u v weight): \n"; + for (int i = 0; i < E; ++i) { + int u, v, weight; + cin >> u >> v >> weight; + adj[u].push_back(v); + adj[v].push_back(u); + adjWeighted[u].push_back({v, weight}); + adjWeighted[v].push_back({u, weight}); + edges.push_back({u, v, weight}); + } + + vector visited(V, false); + cout << "DFS Traversal: "; + DFS(0, adj, visited); + cout << "\n"; + + fill(visited.begin(), visited.end(), false); + cout << "BFS Traversal: "; + BFS(0, adj, visited); + cout << "\n"; + + cout << "Shortest Path from 0 using Dijkstra's algorithm:\n"; + Dijkstra(0, adjWeighted, V); + cout << "\n"; + + cout << "Minimum Spanning Tree using Kruskal's algorithm:\n"; + Kruskal(edges, V); + cout << "\n"; + + return 0; +} +``` + + + + +### Complexity Analysis + +1. Time Complexity: Varies depending on the algorithm: +- DFS: $O(V + E)$ +- BFS: $O(V + E)$ +- Dijkstra’s Algorithm: $O((V + E) \log V)$ +- Kruskal’s Algorithm: $O(E \log E)$ +2. Space Complexity: $O(V + E)$ for adjacency lists and $O(V)$ for auxiliary structures. + +The time complexity is determined by the relaxation of edges in the graph. The space complexity is linear due to the storage of distances. + +## Video Explanation of Given Problem + + +--- + +

Authors:

+ +
+{['sjain1909'].map(username => ( + +))} +
diff --git a/docs/Advance/greedy-for-graph.md b/docs/Advance/greedy-for-graph.md new file mode 100644 index 0000000..0fbba97 --- /dev/null +++ b/docs/Advance/greedy-for-graph.md @@ -0,0 +1,222 @@ +--- +id: greedy-graph-optimization +title: Greedy Graph Optimization Solution +sidebar_label: 0004 - Greedy Graph Optimization +tags: [Greedy Algorithm, Graph Optimization, Minimum Spanning Tree, Shortest Path, Problem Solving] +description: This is a solution to the Greedy Graph Optimization problem. +--- + +## Problem Statement + +### Problem Description + +The Greedy Graph Optimization algorithm aims to solve common graph-related problems, such as finding a minimum spanning tree (MST) or the shortest path, by applying a greedy approach. This method ensures efficient computation and can be highly effective for large datasets. + +### Examples + +**Example 1:** + +```plaintext +Input: Graph = { + nodes: [0, 1, 2, 3], + edges: [ + { source: 0, target: 1, weight: 1 }, + { source: 0, target: 2, weight: 3 }, + { source: 1, target: 2, weight: 1 }, + { source: 1, target: 3, weight: 4 }, + { source: 2, target: 3, weight: 1 } + ] +} +Output: Edges in MST = [ + { source: 0, target: 1, weight: 1 }, + { source: 1, target: 2, weight: 1 }, + { source: 2, target: 3, weight: 1 } +] +``` +**Example 2:** + +```plaintext +Input: Graph = { + nodes: [0, 1, 2, 3], + edges: [ + { source: 0, target: 1, weight: 1 }, + { source: 0, target: 2, weight: 3 }, + { source: 1, target: 2, weight: 1 }, + { source: 1, target: 3, weight: 4 }, + { source: 2, target: 3, weight: 1 } + ], + start: 0, + end: 3 +} +Output: Shortest Path = [0, 1, 2, 3], Total Weight = 3 +``` + +### Constraints +- The graph is represented as an adjacency list. +- The weights of the edges are non-negative integers. +- The graph may contain cycles but no negative weight cycles. + +## Solution of Given Problem + +### Intuition and Approach + +The greedy algorithm provides an efficient approach to solving graph optimization problems. For the minimum spanning tree, we use Kruskal's algorithm. For the shortest path, we employ Dijkstra's algorithm. + +### Approaches + +#### Codes in Different Languages + + + + + ```cpp + #include + using namespace std; + class DSU { + vector parent, rank; + +public: + DSU(int n) { + parent.resize(n); + rank.resize(n, 0); + iota(parent.begin(), parent.end(), 0); + } + + int find(int u) { + if (u != parent[u]) + parent[u] = find(parent[u]); + return parent[u]; + } + + void union_set(int u, int v) { + u = find(u); + v = find(v); + if (u != v) { + if (rank[u] < rank[v]) + swap(u, v); + parent[v] = u; + if (rank[u] == rank[v]) + rank[u]++; + } + } +}; + +struct Edge { + int source, target, weight; + bool operator<(const Edge& other) const { + return weight < other.weight; + } +}; + +vector kruskal(int n, vector& edges) { + sort(edges.begin(), edges.end()); + DSU dsu(n); + vector mst; + for (auto& edge : edges) { + if (dsu.find(edge.source) != dsu.find(edge.target)) { + dsu.union_set(edge.source, edge.target); + mst.push_back(edge); + } + } + return mst; +} + +vector dijkstra(int n, vector>>& adj, int src) { + vector dist(n, INT_MAX); + dist[src] = 0; + priority_queue, vector>, greater>> pq; + pq.push({0, src}); + while (!pq.empty()) { + int d = pq.top().first; + int u = pq.top().second; + pq.pop(); + if (d != dist[u]) + continue; + for (auto& [v, w] : adj[u]) { + if (dist[u] + w < dist[v]) { + dist[v] = dist[u] + w; + pq.push({dist[v], v}); + } + } + } + return dist; +} +void userInput() { + int n, m; + cout << "Enter the number of nodes and edges:\n"; + cin >> n >> m; + + vector edges(m); + cout << "Enter the edges (source target weight):\n"; + for (int i = 0; i < m; ++i) { + cin >> edges[i].source >> edges[i].target >> edges[i].weight; + } + + int choice; + cout << "Enter 1 for MST (Kruskal) or 2 for Shortest Path (Dijkstra):\n"; + cin >> choice; + + if (choice == 1) { + vector mst = kruskal(n, edges); + cout << "Edges in MST:\n"; + for (auto& edge : mst) { + cout << edge.source << " - " << edge.target << " : " << edge.weight << "\n"; + } + } else if (choice == 2) { + vector>> adj(n); + for (auto& edge : edges) { + adj[edge.source].emplace_back(edge.target, edge.weight); + adj[edge.target].emplace_back(edge.source, edge.weight); // For undirected graph + } + int src; + cout << "Enter the source node:\n"; + cin >> src; + vector dist = dijkstra(n, adj, src); + cout << "Shortest paths from node " << src << ":\n"; + for (int i = 0; i < n; ++i) { + cout << "Node " << i << " : " << dist[i] << "\n"; + } + } else { + cout << "Invalid choice.\n"; + } +} + +int main() { + userInput(); + return 0; +} +``` + + + + +### Complexity Analysis + +- Time Complexity: +- Kruskal's Algorithm: $O(E \log E)$ +- Dijkstra's Algorithm: $O((E + V) \log V)$ +- Space Complexity: +- Kruskal's Algorithm: $O(V)$ +- Dijkstra's Algorithm: $O(V + E)$ +- Where `V` is the number of vertices and `E` is the number of edges. +- The time complexity is dominated by the operations on the priority queue and sorting of edges. +- The space complexity is linear due to the storage of the graph and auxiliary data structures. + +## Video Explanation of Given Problem + + + +--- + +

Authors:

+
+{['sjain1909'].map(username => ( + +))} +
diff --git a/docs/Advance/greedy-leetcode.md b/docs/Advance/greedy-leetcode.md new file mode 100644 index 0000000..b5f207a --- /dev/null +++ b/docs/Advance/greedy-leetcode.md @@ -0,0 +1,59 @@ +--- +id: 03-Leetcode Greedy Practice Questions +title: Leetcode Greedy Practice Questions +sidebar_label: Leetcode Greedy Practice Questions +tags: + - Greedy + - data-structures + - binary-tree + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial +sidebar_position: 4 +--- + +# LeetCode Greedy Algorithm Problems + +1. [Jump Game](https://leetcode.com/problems/jump-game/) + +2. [Candy](https://leetcode.com/problems/candy/) + +3. [Gas Station](https://leetcode.com/problems/gas-station/) + +4. [Assign Cookies](https://leetcode.com/problems/assign-cookies/) + +5. [Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) + +6. [Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/) + +7. [Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array/) + +8. [Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) + +9. [Minimum Number of Arrows to Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) + +10. [Lemonade Change](https://leetcode.com/problems/lemonade-change/) + +11. [Partition Labels](https://leetcode.com/problems/partition-labels/) + +12. [Task Scheduler](https://leetcode.com/problems/task-scheduler/) + +13. [Is Subsequence](https://leetcode.com/problems/is-subsequence/) + +14. [Hand of Straights](https://leetcode.com/problems/hand-of-straights/) + +15. [Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) + +16. [Monotone Increasing Digits](https://leetcode.com/problems/monotone-increasing-digits/) + +17. [Two City Scheduling](https://leetcode.com/problems/two-city-scheduling/) + +18. [Remove K Digits](https://leetcode.com/problems/remove-k-digits/) + +19. [Valid Parenthesis String](https://leetcode.com/problems/valid-parenthesis-string/) + +20. [Score After Flipping Matrix](https://leetcode.com/problems/score-after-flipping-matrix/) diff --git a/docs/Advance/huffman-coding.md b/docs/Advance/huffman-coding.md new file mode 100644 index 0000000..e5185a9 --- /dev/null +++ b/docs/Advance/huffman-coding.md @@ -0,0 +1,148 @@ +--- +id: huffman-coding +title: Huffman Coding Solution +sidebar_label: 0003 - Huffman Coding +tags: [Huffman Coding, Data Compression, Algorithm, C++, Problem Solving] +description: This is a solution to the Huffman Coding problem. +--- + +## Problem Statement + +### Problem Description + +Huffman Coding assigns variable-length codes to input characters, with shorter codes assigned to more frequent characters, resulting in efficient compression. Given a set of characters and their frequencies, the goal is to build a Huffman Tree and determine the Huffman codes for each character. + +### Examples + +**Example 1:** + +```plaintext +Input: Characters = {a, b, c, d, e, f}, Frequencies = {5, 9, 12, 13, 16, 45} +Output: +a: 1100 +b: 1101 +c: 100 +d: 101 +e: 111 +f: 0 +``` + +### Constraints +The input should be a set of characters and their respective frequencies. + +## Solution of Given Problem + +### Intuition and Approach + +The Huffman Coding algorithm follows these steps: + +1. Create a leaf node for each character and build a min heap of all leaf nodes. +2. Extract two nodes with the smallest frequency from the min heap. +3. Create a new internal node with a frequency equal to the sum of the two nodes' frequencies. +4. Add the new node to the min heap. +5. Repeat steps 2-4 until the heap contains only one node, which becomes the root of the Huffman Tree. +6. Assign binary codes to each character based on their position in the Huffman Tree. + +### Approaches + +#### Codes in Different Languages + + + + + ```cpp + #include + using namespace std; + struct MinHeapNode { + char data; + int freq; + MinHeapNode *left, *right; + + MinHeapNode(char data, int freq) { + left = right = nullptr; + this->data = data; + this->freq = freq; + } + }; + + struct compare { + bool operator()(MinHeapNode* left, MinHeapNode* right) { + return (left->freq > right->freq); + } + }; + void printCodes(struct MinHeapNode* root, string str) { + if (!root) + return; + + if (root->data != '$') + cout << root->data << ": " << str << "\n"; + + printCodes(root->left, str + "0"); + printCodes(root->right, str + "1"); + } + + void HuffmanCodes(char data[], int freq[], int size) { + struct MinHeapNode *left, *right, *top; + priority_queue, compare> minHeap; + + for (int i = 0; i < size; ++i) + minHeap.push(new MinHeapNode(data[i], freq[i])); + + while (minHeap.size() != 1) { + left = minHeap.top(); + minHeap.pop(); + + right = minHeap.top(); + minHeap.pop(); + + top = new MinHeapNode('$', left->freq + right->freq); + + top->left = left; + top->right = right; + + minHeap.push(top); + } + printCodes(minHeap.top(), ""); + } + + int main() { + char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'}; + int freq[] = {5, 9, 12, 13, 16, 45}; + int size = sizeof(arr) / sizeof(arr[0]); + + HuffmanCodes(arr, freq, size); + + return 0; + } + ``` + + + + +### Complexity Analysis + +- Time Complexity: $O(n \log n)$ +- Space Complexity: $O(n)$ +- Where `n` is the number of characters. +- The time complexity is dominated by the operations on the min heap. +- The space complexity is linear due to the storage of the Huffman Tree. + +## Video Explanation of Given Problem + + + +--- + +

Authors:

+ +
+{['sjain1909'].map(username => ( + +))} +
diff --git a/docs/Advance/image-1.png b/docs/Advance/image-1.png new file mode 100644 index 0000000..3eb14e0 Binary files /dev/null and b/docs/Advance/image-1.png differ diff --git a/docs/Advance/image-2.png b/docs/Advance/image-2.png new file mode 100644 index 0000000..3eb14e0 Binary files /dev/null and b/docs/Advance/image-2.png differ diff --git a/docs/Advance/image-3.png b/docs/Advance/image-3.png new file mode 100644 index 0000000..a4084cd Binary files /dev/null and b/docs/Advance/image-3.png differ diff --git a/docs/Advance/image-4.png b/docs/Advance/image-4.png new file mode 100644 index 0000000..7572fb8 Binary files /dev/null and b/docs/Advance/image-4.png differ diff --git a/docs/Advance/image-5.png b/docs/Advance/image-5.png new file mode 100644 index 0000000..9c99222 Binary files /dev/null and b/docs/Advance/image-5.png differ diff --git a/docs/Advance/image-6.png b/docs/Advance/image-6.png new file mode 100644 index 0000000..dc3bb60 Binary files /dev/null and b/docs/Advance/image-6.png differ diff --git a/docs/Advance/image-7.png b/docs/Advance/image-7.png new file mode 100644 index 0000000..2b4e995 Binary files /dev/null and b/docs/Advance/image-7.png differ diff --git a/docs/Advance/image-8.png b/docs/Advance/image-8.png new file mode 100644 index 0000000..944a5c5 Binary files /dev/null and b/docs/Advance/image-8.png differ diff --git a/docs/Advance/image.png b/docs/Advance/image.png new file mode 100644 index 0000000..9e17fba Binary files /dev/null and b/docs/Advance/image.png differ diff --git a/docs/Advance/knuth-morris-pratt.md b/docs/Advance/knuth-morris-pratt.md new file mode 100644 index 0000000..7881191 --- /dev/null +++ b/docs/Advance/knuth-morris-pratt.md @@ -0,0 +1,137 @@ +--- +id: knuth-morris-pratt +title: Knuth-Morris-Pratt (KMP) Algorithm +sidebar_label: 0006 - Knuth-Morris-Pratt Algorithm +tags: [KMP, String Matching, Algorithm, C++, Problem Solving] +description: This is a solution for implementing the Knuth-Morris-Pratt (KMP) algorithm for efficient substring searching and pattern matching. +--- + +## Problem Statement + +### Problem Description + +The Knuth-Morris-Pratt (KMP) algorithm is an efficient string searching algorithm that improves the performance of substring searches within a main string. The algorithm preprocesses the pattern to create a partial match table (also known as the "lps" array), which is used to skip unnecessary comparisons during the search process. + +### Examples + +**Example 1:** + +```plaintext +Input: +Text: "abxabcabcaby" +Pattern: "abcaby" +Output: +Pattern found at index 6 +``` + +### Constraints + +- The length of the text and the pattern can be up to 10^5. + +## Solution of Given Problem + +### Intuition and Approach + +The KMP algorithm follows these steps: + +1. Preprocessing the Pattern: Compute the longest proper prefix which is also a suffix (lps) array. +2. Searching the Text: Use the lps array to skip characters in the text while matching the pattern. + +### Approaches + +#### Codes in Different Languages + + + + + ```cpp +#include +using namespace std; +void computeLPSArray(string& pat, int M, vector& lps) { + int length = 0; + lps[0] = 0; + int i = 1; + + while (i < M) { + if (pat[i] == pat[length]) { + length++; + lps[i] = length; + i++; + } else { + if (length != 0) { + length = lps[length - 1]; + } else { + lps[i] = 0; + i++; + } + } + } +} + +void KMPSearch(string& pat, string& txt) { + int M = pat.length(); + int N = txt.length(); + + vector lps(M); + + computeLPSArray(pat, M, lps); + + int i = 0; + int j = 0; + while (i < N) { + if (pat[j] == txt[i]) { + j++; + i++; + } + + if (j == M) { + cout << "Pattern found at index " << i - j << "\n"; + j = lps[j - 1]; + } else if (i < N && pat[j] != txt[i]) { + if (j != 0) { + j = lps[j - 1]; + } else { + i++; + } + } + } +} + +int main() { + string txt, pat; + cout << "Enter the text: "; + cin >> txt; + cout << "Enter the pattern: "; + cin >> pat; + + KMPSearch(pat, txt); + + return 0; +} + ``` + + + +### Complexity Analysis + +- **Time Complexity:** $O(N + M)$ where N is the length of the text and M is the length of the pattern. +- **Space Complexity:** $O(M)$ for the lps array. + +## Video Explanation of Given Problem + + +--- + +

Authors:

+ +
+{['sjain1909'].map(username => ( + +))} +
diff --git a/docs/Advance/leetcodeDP.md b/docs/Advance/leetcodeDP.md new file mode 100644 index 0000000..42d9bcf --- /dev/null +++ b/docs/Advance/leetcodeDP.md @@ -0,0 +1,81 @@ +--- +id: 02-Leetcode DP Practice Questions +title: Leetcode DP Practice Questions +sidebar_label: Leetcode DP Practice Questions +tags: + - dsa + - data-structures + - binary-tree + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial +sidebar_position: 2 +--- + +Here is a list of some popular LeetCode dynamic programming problems: + +1. Climbing Stairs + +2. Maximum Subarray + +3. House Robber + +4. Decode Ways + +5. Coin Change + +6. Unique Paths + +7. Palindrome Partitioning II + +8. Regular Expression Matching + +9. Wildcard Matching + +10. Integer Break + +11. Best Time to Buy and Sell Stock + +12. Longest Palindromic Subsequence + +13. Minimum Path Sum + +14. Edit Distance + +15. Longest Increasing Subsequence + +16. Distinct Subsequences + +17. Jump Game + +18. Jump Game II + +19. Partition Equal Subset Sum + +20. Longest Valid Parentheses + +21. Word Break + +22. Word Break II + +23. Paint House + +24. Paint House II + +25. Unique Binary Search Trees + +26. Unique Binary Search Trees II + +27. Minimum Cost For Tickets + +28. Minimum Number of Taps to Open to Water a Garden + +29. Best Time to Buy and Sell Stock with Cooldown + +30. Perfect Squares + +These are some of the well-known dynamic programming problems on LeetCode. You can search for each problem by name on the LeetCode platform to find detailed descriptions, examples, and solutions provided by the community. diff --git a/docs/Advance/levenshtein-distance-algorithm.md b/docs/Advance/levenshtein-distance-algorithm.md new file mode 100644 index 0000000..1673d57 --- /dev/null +++ b/docs/Advance/levenshtein-distance-algorithm.md @@ -0,0 +1,108 @@ +--- +id: levenshtein-distance +title: Levenshtein Distance Algorithm +sidebar_label: 0007 - Levenshtein Distance Algorithm +tags: [Levenshtein Distance, String Matching, Algorithm, C++, Problem Solving] +description: This is a solution for implementing the Levenshtein Distance Algorithm for measuring the difference between two sequences. +--- + +## Problem Statement + +### Problem Description + +The Levenshtein Distance algorithm calculates the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into another. It is widely used in applications like spell checking, DNA sequencing, and natural language processing. + +### Examples + +**Example 1:** + +```plaintext +Input: +String1: "kitten" +String2: "sitting" +Output: +3 +Explanation: The Levenshtein Distance between "kitten" and "sitting" is 3 (kitten -> sitten -> sittin -> sitting). +``` + +### Constraints +- The length of both strings can be up to 10^3. + +## Solution of Given Problem + +### Intuition and Approach + +The Levenshtein Distance algorithm uses dynamic programming to efficiently compute the edit distance between two strings. It constructs a matrix where the cell at position (i, j) contains the Levenshtein Distance between the first i characters of the first string and the first j characters of the second string. + +### Approaches + +#### Codes in Different Languages + + + + + ```cpp + #include + using namespace std; + + int levenshteinDistance(const string& str1, const string& str2) { + int len1 = str1.size(); + int len2 = str2.size(); + vector> dp(len1 + 1, vector(len2 + 1)); + + for (int i = 0; i <= len1; ++i) { + for (int j = 0; j <= len2; ++j) { + if (i == 0) { + dp[i][j] = j; + } else if (j == 0) { + dp[i][j] = i; + } else if (str1[i - 1] == str2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1]; + } else { + dp[i][j] = 1 + min({dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]}); + } + } + } + + return dp[len1][len2]; +} + +int main() { + string str1, str2; + cout << "Enter the first string: "; + cin >> str1; + cout << "Enter the second string: "; + cin >> str2; + + int distance = levenshteinDistance(str1, str2); + cout << "The Levenshtein Distance between \"" << str1 << "\" and \"" << str2 << "\" is " << distance << ".\n"; + + return 0; +} + ``` + + + +### Complexity Analysis + +- **Time Complexity:** $O(N * M)$ where N is the length of the first string and M is the length of the second string. +- **Space Complexity:** $O(N * M)$ for the dynamic programming matrix. + +## Video Explanation of Given Problem + + +--- + +

Authors:

+ +
+{['sjain1909'].map(username => ( + +))} +
diff --git a/docs/Advance/pageRank.md b/docs/Advance/pageRank.md new file mode 100644 index 0000000..ce81b91 --- /dev/null +++ b/docs/Advance/pageRank.md @@ -0,0 +1,153 @@ +--- +id: pagerank-algorithm +title: PageRank Algorithm for Web Page Ranking +sidebar_label: 0010 - PageRank Algorithm +tags: [PageRank, Web Page Ranking, Algorithm, C++, Problem Solving] +description: This is a solution for implementing the PageRank Algorithm to rank web pages based on their importance and relevance. +--- + +## Problem Statement + +### Problem Description + +The PageRank Algorithm, developed by Google, ranks web pages in search engine results based on their importance and relevance. It assigns a numerical weighting to each element of a hyperlinked set of documents with the purpose of measuring its relative importance within the set. + +### Examples + +**Example 1:** + +```plaintext +Input: +Number of pages: 3 +Links: +0 -> 1 +1 -> 2 +2 -> 0 + +Output: +PageRank values: +Page 0: 0.33 +Page 1: 0.33 +Page 2: 0.33 + +Explanation: Each page has an equal rank since each links to the next in a circular manner. +``` + +### Constraints + +- The input is a directed graph where nodes represent web pages and edges represent links between them. +- The algorithm should handle graphs with up to 10^5 vertices and edges. + +## Solution of Given Problem + +### Intuition and Approach + +The PageRank Algorithm follows these steps: + +1. Initialize the rank of all pages to a uniform value. +2. For a fixed number of iterations or until convergence, update the rank of each page based on the ranks of pages linking to it. +3. Apply a damping factor to simulate the probability of a random web surfer following links. + +### Approaches + +#### Codes in Different Languages + + + + + ```cpp + #include + using namespace std; + + class PageRank { + int V; + vector> adj; + vector rank; + double damping; + int maxIter; + +public: + PageRank(int V, double damping = 0.85, int maxIter = 100) { + this->V = V; + this->damping = damping; + this->maxIter = maxIter; + adj.resize(V); + rank.resize(V, 1.0 / V); + } + + void addEdge(int v, int w) { + adj[v].push_back(w); + } + + void calculatePageRank() { + vector newRank(V, 0.0); + for (int iter = 0; iter < maxIter; ++iter) { + for (int i = 0; i < V; ++i) { + newRank[i] = (1 - damping) / V; + for (int j = 0; j < V; ++j) { + if (find(adj[j].begin(), adj[j].end(), i) != adj[j].end()) { + newRank[i] += damping * rank[j] / adj[j].size(); + } + } + } + rank = newRank; + } + } + + void printPageRank() { + for (int i = 0; i < V; ++i) { + cout << "Page " << i << ": " << rank[i] << "\n"; + } + } +}; + +int main() { + int V, E; + cout << "Enter the number of pages (vertices): "; + cin >> V; + cout << "Enter the number of links (edges): "; + cin >> E; + + PageRank pr(V); + for (int i = 0; i < E; ++i) { + int v, w; + cout << "Enter link (v -> w): "; + cin >> v >> w; + pr.addEdge(v, w); + } + + pr.calculatePageRank(); + cout << "PageRank values:\n"; + pr.printPageRank(); + + return 0; +} + ``` + + + +### Complexity Analysis + +- **Time Complexity:** $O(V + E)$ per iteration, where `V` is the number of vertices and `E` is the number of edges. +- **Space Complexity:** $O(V + E)$ + +The time complexity is linear with respect to the number of vertices and edges per iteration. The space complexity is linear due to the storage requirements for the adjacency list and rank vectors. + +## Video Explanation of Given Problem + + +--- + +

Authors:

+ +
+{['sjain1909'].map(username => ( + +))} +
diff --git a/docs/Advance/strassen-algorithm.md b/docs/Advance/strassen-algorithm.md new file mode 100644 index 0000000..55676bd --- /dev/null +++ b/docs/Advance/strassen-algorithm.md @@ -0,0 +1,187 @@ +--- +id: strassens-algorithm +title: Strassen's Algorithm for Matrix Multiplication +sidebar_label: 0008 - Strassen's Algorithm +tags: [Strassen's Algorithm, Matrix Multiplication, Algorithm, C++, Problem Solving] +description: This is a solution for implementing Strassen's Algorithm for efficient matrix multiplication. +--- + +## Problem Statement + +### Problem Description + +Strassen's Algorithm is an efficient matrix multiplication algorithm that reduces the time complexity compared to the conventional matrix multiplication approach. It is particularly useful for large matrices, providing significant performance improvements. + +### Examples + +**Example 1:** + +```plaintext +Input: +Matrix1: +1 2 +3 4 + +Matrix2: +5 6 +7 8 + +Output: +19 22 +43 50 +Explanation: The product of the two matrices is computed using Strassen's Algorithm. + +``` + +### Constraints + +- The matrices should be square matrices of size $2^n \times 2^n$. + +## Solution of Given Problem + +### Intuition and Approach + +Strassen's Algorithm breaks down matrix multiplication into smaller matrix multiplications and additions, reducing the overall number of multiplications required. It divides each matrix into four submatrices and recursively applies the same algorithm to these submatrices. + +### Approaches + +#### Codes in Different Languages + + + + + ```cpp + #include + using namespace std; + +vector> add(const vector>& A, const vector>& B) { + int n = A.size(); + vector> C(n, vector(n)); + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + C[i][j] = A[i][j] + B[i][j]; + return C; +} + +vector> subtract(const vector>& A, const vector>& B) { + int n = A.size(); + vector> C(n, vector(n)); + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + C[i][j] = A[i][j] - B[i][j]; + return C; +} + +vector> strassen(const vector>& A, const vector>& B) { + int n = A.size(); + if (n == 1) { + return {{A[0][0] * B[0][0]}}; + } + + int newSize = n / 2; + vector> a11(newSize, vector(newSize)); + vector> a12(newSize, vector(newSize)); + vector> a21(newSize, vector(newSize)); + vector> a22(newSize, vector(newSize)); + vector> b11(newSize, vector(newSize)); + vector> b12(newSize, vector(newSize)); + vector> b21(newSize, vector(newSize)); + vector> b22(newSize, vector(newSize)); + + for (int i = 0; i < newSize; ++i) { + for (int j = 0; j < newSize; ++j) { + a11[i][j] = A[i][j]; + a12[i][j] = A[i][j + newSize]; + a21[i][j] = A[i + newSize][j]; + a22[i][j] = A[i + newSize][j + newSize]; + b11[i][j] = B[i][j]; + b12[i][j] = B[i][j + newSize]; + b21[i][j] = B[i + newSize][j]; + b22[i][j] = B[i + newSize][j + newSize]; + } + } + + auto m1 = strassen(add(a11, a22), add(b11, b22)); + auto m2 = strassen(add(a21, a22), b11); + auto m3 = strassen(a11, subtract(b12, b22)); + auto m4 = strassen(a22, subtract(b21, b11)); + auto m5 = strassen(add(a11, a12), b22); + auto m6 = strassen(subtract(a21, a11), add(b11, b12)); + auto m7 = strassen(subtract(a12, a22), add(b21, b22)); + + vector> c11 = add(subtract(add(m1, m4), m5), m7); + vector> c12 = add(m3, m5); + vector> c21 = add(m2, m4); + vector> c22 = add(subtract(add(m1, m3), m2), m6); + + vector> C(n, vector(n)); + for (int i = 0; i < newSize; ++i) { + for (int j = 0; j < newSize; ++j) { + C[i][j] = c11[i][j]; + C[i][j + newSize] = c12[i][j]; + C[i + newSize][j] = c21[i][j]; + C[i + newSize][j + newSize] = c22[i][j]; + } + } + + return C; +} + +int main() { + int n; + cout << "Enter the size of the matrices (must be a power of 2): "; + cin >> n; + + vector> A(n, vector(n)); + vector> B(n, vector(n)); + + cout << "Enter elements of matrix A:\n"; + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + cin >> A[i][j]; + + cout << "Enter elements of matrix B:\n"; + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + cin >> B[i][j]; + + vector> C = strassen(A, B); + + cout << "Resultant matrix C after multiplication:\n"; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) + cout << C[i][j] << " "; + cout << "\n"; + } + + return 0; +} + ``` + + + +### Complexity Analysis + +- **Time Complexity:** $O(n^{\log_2 7}) \approx O(n^{2.81})$ +- **Space Complexity:** $O(n^2)$ + +The time complexity is significantly reduced compared to the traditional $O(n^3)$ matrix multiplication. The space complexity is determined by the storage requirements of the matrices. + +## Video Explanation of Given Problem + + +--- + +

Authors:

+ +
+{['sjain1909'].map(username => ( + +))} +
diff --git a/docs/Advance/tarjans algorithm.md b/docs/Advance/tarjans algorithm.md new file mode 100644 index 0000000..c8eca87 --- /dev/null +++ b/docs/Advance/tarjans algorithm.md @@ -0,0 +1,175 @@ +--- +id: tarjans-algorithm +title: Tarjan’s Algorithm for Strongly Connected Components +sidebar_label: 0009 - Tarjan’s Algorithm +tags: [Tarjan's Algorithm, Strongly Connected Components, Algorithm, C++, Problem Solving] +description: This is a solution for implementing Tarjan’s Algorithm to find strongly connected components in a directed graph. +--- + +## Problem Statement + +### Problem Description + +Tarjan’s Algorithm is used to find strongly connected components (SCCs) in a directed graph. SCCs are subgraphs where every vertex is reachable from every other vertex within the same subgraph. This algorithm is efficient and crucial for various graph-related problems. + +### Examples + +**Example 1:** + +```plaintext +Input: +Graph: +0 -> 1 +1 -> 2 +2 -> 0 +1 -> 3 +3 -> 4 + +Output: +SCCs: +0 2 1 +3 +4 + +Explanation: The graph contains three SCCs: {0, 1, 2}, {3}, and {4}. +``` + +### Constraints + +- The graph is a directed graph. +- The algorithm should handle graphs with up to 10^5 vertices and edges. + +## Solution of Given Problem + +### Intuition and Approach + +Tarjan’s Algorithm uses depth-first search (DFS) to traverse the graph and identifies SCCs using a stack and low-link values + +- The algorithm follows these steps: + +1. Initialize a stack to keep track of visited vertices. +2. Use a DFS traversal to explore the graph. +3. For each vertex, assign discovery and low-link values. +4. If a vertex's low-link value equals its discovery value, it is the root of an SCC. +5. Pop vertices from the stack until the root vertex is reached, forming an SCC. + +### Approaches + +#### Codes in Different Languages + + + + + ```cpp + #include + using namespace std; + + class TarjanSCC { + int V; + list *adj; + vector disc, low, stackMember; + stack st; + int time; + + void SCCUtil(int u) { + disc[u] = low[u] = ++time; + st.push(u); + stackMember[u] = true; + + for (int v : adj[u]) { + if (disc[v] == -1) { + SCCUtil(v); + low[u] = min(low[u], low[v]); + } + else if (stackMember[v] == true) { + low[u] = min(low[u], disc[v]); + } + } + + int w = 0; + if (low[u] == disc[u]) { + while (st.top() != u) { + w = st.top(); + cout << w << " "; + stackMember[w] = false; + st.pop(); + } + w = st.top(); + cout << w << "\n"; + stackMember[w] = false; + st.pop(); + } + } + +public: + TarjanSCC(int V) { + this->V = V; + adj = new list[V]; + disc = vector(V, -1); + low = vector(V, -1); + stackMember = vector(V, false); + time = 0; + } + + void addEdge(int v, int w) { + adj[v].push_back(w); + } + + void SCC() { + for (int i = 0; i < V; i++) { + if (disc[i] == -1) { + SCCUtil(i); + } + } + } +}; + +int main() { + int V, E; + cout << "Enter the number of vertices: "; + cin >> V; + cout << "Enter the number of edges: "; + cin >> E; + + TarjanSCC g(V); + for (int i = 0; i < E; ++i) { + int v, w; + cout << "Enter edge (v w): "; + cin >> v >> w; + g.addEdge(v, w); + } + + cout << "Strongly Connected Components are:\n"; + g.SCC(); + + return 0; +} + ``` + + + +### Complexity Analysis + +- **Time Complexity:** $O(V*E)$ +- **Space Complexity:** $O(V)$ + +The time complexity is determined by the relaxation of edges in the graph. The space complexity is linear due to the storage of distances. + +## Video Explanation of Given Problem + + +--- + +

Authors:

+ +
+{['sjain1909'].map(username => ( + +))} +
diff --git a/docs/Advance/trie.md b/docs/Advance/trie.md new file mode 100644 index 0000000..7c92d8c --- /dev/null +++ b/docs/Advance/trie.md @@ -0,0 +1,149 @@ +--- +id: 02-Trie +title: Introduction to Trie +sidebar_label: Trie +tags: + - dsa + - data-structures + - binary-tree + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial +sidebar_position: 2 +--- + +# Trie Data Structure and Algorithms + +## Introduction + +A Trie, also known as a prefix tree, is a type of search tree that is used to store a dynamic set of strings. The name "Trie" comes from the word "retrieval" as they are used to retrieve a key in a dataset of strings. Tries are particularly useful for tasks involving a large set of strings, such as dictionary words or contact lists. + +## Basic Structure + +A Trie is a tree-like data structure where each node represents a single character of a string. The root node is associated with an empty string. Each subsequent node represents the next character of the inserted string. Nodes that share a common prefix share the same path from the root. + +### Example + +``` + root + / | \ + t b c + /| \ \ + h o a a + / \ \ \ + e r t r + +/ \ \ + r k t +``` + +In the example above, the Trie stores the words "the", "their", "there", "bat", "cat", and "cart". + +## Operations + +### Insertion + +To insert a word into a Trie, we start at the root node and follow the path corresponding to the characters in the word. If a node for a character does not exist, we create a new node. After inserting all characters, we mark the last node as the end of a word. + +### Search + +To search for a word in a Trie, we follow the path corresponding to the characters in the word starting from the root. If we can follow the path for all characters and reach a node marked as the end of a word, the word exists in the Trie. + +### Deletion + +To delete a word from a Trie, we first ensure the word exists. If it does, we remove the nodes corresponding to the word's characters, starting from the last character and moving towards the root. If removing a node would break the path for another word, we stop the deletion process for that node. + +### Prefix Search + +A Trie can efficiently find all words with a given prefix. By following the path corresponding to the prefix characters, we can reach a node where all the sub-nodes form words with the given prefix. + +## Applications + +- **Autocomplete**: Tries are used to provide suggestions in search engines and text editors. +- **Spell Checker**: Tries store a large dictionary of words for quick lookup and suggestions. +- **IP Routing**: In networking, Tries can be used to store routing tables. +- **Genome Analysis**: Tries can store and search DNA sequences efficiently. + +## Advantages and Disadvantages + +### Advantages + +- **Fast Lookups**: O(n) complexity for search, insertion, and deletion where n is the length of the word. +- **Prefix Search**: Efficiently find all words with a given prefix. +- **Memory Efficiency**: Space optimization for storing keys with common prefixes. + +### Disadvantages + +- **Space Complexity**: Requires more memory compared to some other data structures, especially for a sparse dataset. +- **Implementation Complexity**: More complex to implement than basic data structures like arrays or linked lists. + +## Complexity Analysis + +- **Insertion**: O(n), where n is the length of the word. +- **Search**: O(n), where n is the length of the word. +- **Deletion**: O(n), where n is the length of the word. +- **Space Complexity**: O(ALPHABET*SIZE * n \_ m), where n is the number of keys and m is the average key length. + +## Example Implementation in Python + +```python +class TrieNode: + def __init__(self): + self.children = {} + self.is_end_of_word = False + +class Trie: + def __init__(self): + self.root = TrieNode() + + def insert(self, word): + node = self.root + for char in word: + if char not in node.children: + node.children[char] = TrieNode() + node = node.children[char] + node.is_end_of_word = True + + def search(self, word): + node = self.root + for char in word: + if char not in node.children: + return False + node = node.children[char] + return node.is_end_of_word + + def delete(self, word): + def _delete(node, word, depth): + if not node: + return False + if depth == len(word): + if node.is_end_of_word: + node.is_end_of_word = False + return len(node.children) == 0 + char = word[depth] + if char in node.children: + should_delete = _delete(node.children[char], word, depth + 1) + if should_delete: + del node.children[char] + return len(node.children) == 0 + return False + _delete(self.root, word, 0) + + def starts_with(self, prefix): + node = self.root + for char in prefix: + if char not in node.children: + return False + node = node.children[char] + return True +``` + +## References + +1. GeeksforGeeks - Trie +2. Wikipedia - Trie +3. TutorialsPoint - Trie diff --git a/docs/Advance/trie_practice_questions.md b/docs/Advance/trie_practice_questions.md new file mode 100644 index 0000000..e650ad5 --- /dev/null +++ b/docs/Advance/trie_practice_questions.md @@ -0,0 +1,139 @@ +--- +id: 02-Leetcode trie Practice Questions +title: Leetcode trie Practice Questions +sidebar_label: Leetcode trie Practice Questions +tags: + - dsa + - data-structures + - binary-tree + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial +sidebar_position: 2 +--- + +## Questions + +### 1. Implement Trie (Prefix Tree) + +**Problem:** Implement a trie with `insert`, `search`, and `startsWith` methods. + +**Link:** [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) + +### 2. Add and Search Word - Data structure design + +**Problem:** Design a data structure that supports adding new words and finding if a string matches any previously added string. + +**Link:** [Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/) + +### 3. Longest Word in Dictionary + +**Problem:** Find the longest word in the dictionary that can be built one character at a time by other words in the dictionary. + +**Link:** [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/) + +### 4. Replace Words + +**Problem:** Implement a function to replace all words in a sentence with their root forms using a dictionary of roots. + +**Link:** [Replace Words](https://leetcode.com/problems/replace-words/) + +### 5. Stream of Characters + +**Problem:** Design a class to search for strings in a stream of characters. + +**Link:** [Stream of Characters](https://leetcode.com/problems/stream-of-characters/) + +### 6. Design Search Autocomplete System + +**Problem:** Implement a search autocomplete system that supports inputting characters and returning the top 3 historical hot sentences. + +**Link:** [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) + +### 7. Prefix and Suffix Search + +**Problem:** Design a class that supports querying words with given prefix and suffix. + +**Link:** [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) + +### 8. Word Search II + +**Problem:** Given a 2D board and a list of words, find all words that can be formed by letters of the board. + +**Link:** [Word Search II](https://leetcode.com/problems/word-search-ii/) + +### 9. Map Sum Pairs + +**Problem:** Implement a MapSum class with insert and sum methods, which sum all keys with a given prefix. + +**Link:** [Map Sum Pairs](https://leetcode.com/problems/map-sum-pairs/) + +### 10. Design Add and Search Words Data Structure + +**Problem:** Design a data structure that supports adding new words and finding if a string matches any previously added string, with support for wildcards. + +**Link:** [Design Add and Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure/) + +### 11. Palindrome Pairs + +**Problem:** Given a list of unique words, find all pairs of distinct indices (i, j) such that the concatenation of words[i] and words[j] is a palindrome. + +**Link:** [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) + +### 12. Maximum XOR of Two Numbers in an Array + +**Problem:** Find the maximum XOR of two numbers in an array. + +**Link:** [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) + +### 13. Concatenated Words + +**Problem:** Find all concatenated words in a given dictionary of words. + +**Link:** [Concatenated Words](https://leetcode.com/problems/concatenated-words/) + +### 14. Design Phone Directory + +**Problem:** Design a phone directory that initially has all phone numbers available to be assigned and supports checking availability, getting a number, and releasing a number. + +**Link:** [Design Phone Directory](https://leetcode.com/problems/design-phone-directory/) + +### 15. Search Suggestions System + +**Problem:** Given an array of products and a search word, design a system that suggests at most 3 products as you type each character of the search word. + +**Link:** [Search Suggestions System](https://leetcode.com/problems/search-suggestions-system/) + +### 16. Word Filter + +**Problem:** Implement a WordFilter class that supports searching for words with a given prefix and suffix. + +**Link:** [Word Filter](https://leetcode.com/problems/word-filter/) + +### 17. Index Pairs of a String + +**Problem:** Given a string text and an array of words, return all index pairs [i, j] so that the substring text[i...j] is in the array of words. + +**Link:** [Index Pairs of a String](https://leetcode.com/problems/index-pairs-of-a-string/) + +### 18. Camelcase Matching + +**Problem:** Given a list of queries and a pattern, return a list of booleans where each boolean indicates whether the query matches the pattern. + +**Link:** [Camelcase Matching](https://leetcode.com/problems/camelcase-matching/) + +### 19. Prefix and Suffix Search + +**Problem:** Implement a class that supports querying words with a given prefix and suffix (similar to question 7 but can be a different version or extension). + +**Link:** [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) + +### 20. Delete Duplicate Folders in System + +**Problem:** Given a system of folders, delete all duplicate folders and return the list of unique folders. + +**Link:** [Delete Duplicate Folders in System](https://leetcode.com/problems/delete-duplicate-folders-in-system/) diff --git a/docs/Algorithms/Dynamic Programming/01-Fibonacci-Sequence.md b/docs/Algorithms/Dynamic Programming/01-Fibonacci-Sequence.md new file mode 100644 index 0000000..06edc3d --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/01-Fibonacci-Sequence.md @@ -0,0 +1,173 @@ +--- +id: fibonacci-sequence +title: Fibonacci Sequence using Dynamic Programming +sidebar_label: Fibonacci Sequence +tags: [python, java, c++, javascript, programming, algorithms, dynamic programming, tutorial, in-depth] +description: In this tutorial, we will learn about the Fibonacci sequence and its implementation using Dynamic Programming in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +# Fibonacci Sequence using Dynamic Programming + +The Fibonacci sequence is a classic example that can be efficiently solved using dynamic programming. The Fibonacci sequence is defined as: +$[ F(n) = F(n-1) + F(n-2) ]$ +with the base cases: +$[ F(0) = 0, F(1) = 1 ]$ + +## Problem Statement + +Given an integer (n), compute the (n)-th Fibonacci number. + +### Intuition + +The Fibonacci sequence can be computed using a naive recursive approach, but this results in exponential time complexity due to repeated calculations of the same values. Dynamic Programming (DP) offers a more efficient solution by storing previously computed values. + +## Naive Recursive Approach +The naive approach to calculating the Fibonacci sequence uses a simple recursive function which calls recursivly and has exponential time complexity. + +```python +def fibonacci_recursive(n): + if n <= 1: + return n + return fibonacci_recursive(n-1) + fibonacci_recursive(n-2) +``` + +## Dynamic Programming Approach + +Using DP, we store the results of subproblems to avoid redundant computations. This reduces the time complexity to $O(n)$. The dynamic programming (DP) approach solves the problem more efficiently by storing intermediate results to avoid redundant calculations + +### Bottom-Up Approach + +We iteratively compute the Fibonacci numbers from the bottom up, storing intermediate results. + +## Pseudocode for Fibonacci using DP + +#### Initialize: + +```markdown +dp[0] = 0 +dp[1] = 1 + +Loop from 2 to n: +dp[i] = dp[i-1] + dp[i-2] + +return dp[n] +``` +## Implementing Fibonacci using DP + +### Python Implementation + +```python +def fibonacci_dp(n): + # Base cases + if n <= 1: + return n + + # Initialize an array to store Fibonacci numbers + dp = [0] * (n + 1) + + # Base values + dp[0] = 0 + dp[1] = 1 + + # Calculate Fibonacci numbers from bottom-up + for i in range(2, n + 1): + dp[i] = dp[i-1] + dp[i-2] + + return dp[n] +``` + +### Java Implementation + +```java +public class Fibonacci { + public static int fibonacci_dp(int n) { + // Base cases + if (n <= 1) return n; + + // Initialize an array to store Fibonacci numbers + int[] dp = new int[n + 1]; + + // Base values + dp[0] = 0; + dp[1] = 1; + + // Calculate Fibonacci numbers from bottom-up + for (int i = 2; i <= n; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; + } + + public static void main(String[] args) { + int n = 10; + System.out.println("Fibonacci number at position " + n + " is: " + fibonacci_dp(n)); + } +} +``` +### C++ Implementation + +```cpp +#include +using namespace std; + +int fibonacci_dp(int n) { + // Base cases + if (n <= 1) return n; + + // Initialize an array to store Fibonacci numbers + int dp[n + 1]; + + // Base values + dp[0] = 0; + dp[1] = 1; + + // Calculate Fibonacci numbers from bottom-up + for (int i = 2; i <= n; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; +} + +int main() { + int n = 10; + cout << "Fibonacci number at position " << n << " is: " << fibonacci_dp(n) << endl; + return 0; +} +``` + +### JavaScript Implementation + +```javascript +function fibonacci_dp(n) { + // Base cases + if (n <= 1) return n; + + // Initialize an array to store Fibonacci numbers + let dp = new Array(n + 1).fill(0); + + // Base values + dp[0] = 0; + dp[1] = 1; + + // Calculate Fibonacci numbers from bottom-up + for (let i = 2; i <= n; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; +} + +let n = 10; +console.log("Fibonacci number at position " + n + " is: " + fibonacci_dp(n)); +``` + +## Complexity Analysis + +- Time Complexity: $O(n)$, since we are iterating from 2 to n. +- Space Complexity: $O(n)$, due to the array used for storing intermediate results. This can be optimized to $O(1)$ by only storing the last two values. + +## Conclusion + +Dynamic programming provides an efficient solution for computing Fibonacci numbers by reducing redundant calculations and storing intermediate results. This technique can be extended to solve other problems with overlapping subproblems and optimal substructure properties. \ No newline at end of file diff --git a/docs/Algorithms/Dynamic Programming/02-Kadanes-Algorithm.md b/docs/Algorithms/Dynamic Programming/02-Kadanes-Algorithm.md new file mode 100644 index 0000000..a0fa535 --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/02-Kadanes-Algorithm.md @@ -0,0 +1,199 @@ +--- +id: kadane-algorithm +title: Kadane’s Algorithm +sidebar_label: Kadane’s Algorithm +tags: [python, java, c++, javascript, programming, algorithms, subarray, array, tutorial, in-depth] +description: In this tutorial, we will learn about Kadane’s Algorithm and its implementation in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +# Kadane’s Algorithm +Kadane's algorithm is a greedy/dynamic programming algorithm that can be used on array problems to bring the time complexity down to +O(n). It is used to calculate the maximum sum subarray ending at a particular position. + +## Problem Statement +Given an integer array arr, find the contiguous subarray (containing at least one number) which has the largest sum and returns its sum. + +### Intuition +The question above is asking us to find a group of contiguous values in an array that give the largest sum. We are then asked to return that sum. +If we forget about Kadane's algorithm for a second, the brute force way to approach this would be to go through every single subarray and calculate the sum, while keeping track of a maximum sum. This will work but there is a lot of repeated work. For every iteration of our outer for loop, our inner loop does linear work. This makes the complexity +𝑂(𝑛^2). + +## Brute Force Approach + ```python + def bruteForce(nums): + maxSum = nums[0] + for i in range(len(nums)): + curSum = 0 + for j in range(i, len(nums)): + curSum += nums[j] + maxSum = max(maxSum, curSum) + return maxSum +``` + +## Optimized Approach - Kadane’s Algorithm +The intuition of the algorithm is not to consider the subarray as a part of the answer if its sum is less than 0. A subarray with a sum less than 0 will always reduce our answer and so this type of subarray cannot be a part of the subarray with maximum sum. + +Here, we will iterate the given array with a single loop and while iterating we will add the elements in a sum variable. Now, if at any point the sum becomes less than 0, we will set the sum as 0 as we are not going to consider any subarray with a negative sum. Among all the sums calculated, we will consider the maximum one. + +Thus we can solve this problem with a single loop. + +![image](https://imagedelivery.net/CLfkmk9Wzy8_9HRyug4EVA/f16c1a92-9cbd-43d4-ae6b-0d143e833d00/sharpen=1) + +## Pseudocode for Kadane’s Algorithm +##### Initialize: + - max_so_far = INT_MIN + - max_ending_here = 0 + + ##### Loop for each element of the array + + - (a) max_ending_here = max_ending_here + a[i] + - (b) if(max_so_far < max_ending_here) + max_so_far = max_ending_here + - (c) if(max_ending_here < 0) + max_ending_here = 0 +return max_so_far + +## Implementing Kadane’s Algorithm + +### Python Implementation + +```python +import sys + +def maxSubarraySum(arr, n): + maxi = -sys.maxsize-1 # maximum sum + sum = 0 + + for i in range(n): + sum += arr[i] + + if sum > maxi: + maxi = sum + + # If sum < 0: discard the sum calculated + if sum < 0: + sum = 0 + + # To consider the sum of the empty subarray + # uncomment the following check: + + #if maxi < 0: maxi = 0 + + return maxi + +``` + +### Java Implementation + +```java + +import java.util.*; + +public class Main { + public static long maxSubarraySum(int[] arr, int n) { + long maxi = Long.MIN_VALUE; // maximum sum + long sum = 0; + + for (int i = 0; i < n; i++) { + + sum += arr[i]; + + if (sum > maxi) { + maxi = sum; + } + + // If sum < 0: discard the sum calculated + if (sum < 0) { + sum = 0; + } + } + + // To consider the sum of the empty subarray + // uncomment the following check: + + //if (maxi < 0) maxi = 0; + + return maxi; + } + + public static void main(String args[]) { + int[] arr = { -2, 1, -3, 4, -1, 2, 1, -5, 4}; + int n = arr.length; + long maxSum = maxSubarraySum(arr, n); + System.out.println("The maximum subarray sum is: " + maxSum); + + } + +} +``` + +### C++ Implementation + +```cpp +long long maxSubarraySum(int arr[], int n) { + long long maxi = LONG_MIN; // maximum sum + long long sum = 0; + + for (int i = 0; i < n; i++) { + + sum += arr[i]; + + if (sum > maxi) { + maxi = sum; + } + + // If sum < 0: discard the sum calculated + if (sum < 0) { + sum = 0; + } + } + + // To consider the sum of the empty subarray + // uncomment the following check: + + //if (maxi < 0) maxi = 0; + + return maxi; +} + +``` + +### JavaScript Implementation + +```javascript +function maxSubarraySum(arr, n) { + let maxi = Number.MIN_SAFE_INTEGER; // maximum sum + let sum = 0; + + for (let i = 0; i < n; i++) { + sum += arr[i]; + + if (sum > maxi) { + maxi = sum; + } + + // If sum < 0: discard the sum calculated + if (sum < 0) { + sum = 0; + } + } + + // To consider the sum of the empty subarray + // uncomment the following check: + + //if (maxi < 0) maxi = 0; + + return maxi; +} +``` + +## Complexity Analysis + #### Time Complexity : + - $O(n)$ , We are using a single loop running N times. + + #### Space Complexity + - $O(1)$ , as Only Variables are used. +## Conclusion +- Kadane's algorithm offers a straightforward and efficient approach to solving the maximum sum subarray problem, making it a fundamental technique in algorithmic problem-solving and data analysis. + + diff --git a/docs/Algorithms/Dynamic Programming/03-Knapsack.md b/docs/Algorithms/Dynamic Programming/03-Knapsack.md new file mode 100644 index 0000000..5ab7e96 --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/03-Knapsack.md @@ -0,0 +1,78 @@ +The Knapsack problem is an example of the combinational optimization problem. This problem is also commonly known as the β€œRucksack Problemβ€œ. The name of the problem is defined from the maximization problem as mentioned below: + +Given a bag with maximum weight capacity of W and a set of items, each having a weight and a value associated with it. Decide the number of each item to take in a collection such that the total weight is less than the capacity and the total value is maximized. + +## Types of Knapsack Problem: + +### The knapsack problem can be classified into the following types: + +Fractional Knapsack Problem +0/1 Knapsack Problem +Bounded Knapsack Problem +Unbounded Knapsack Problem + +The 0/1 Knapsack problem can be defined as follows: + +We are given N items where each item has some weight (wi) and value (vi) associated with it. We are also given a bag with capacity W. The target is to put the items into the bag such that the sum of values associated with them is the maximum possible. + +Note that here we can either put an item completely into the bag or cannot put it at all. + +## Examples: + +Input: N = 3, W = 4, profit[] = {1, 2, 3}, weight[] = {4, 5, 1} +Output: 3 + +Explanation: There are two items which have weight less than or equal to 4. If we select the item with weight 4, the possible profit is 1. And if we select the item with weight 1, the possible profit is 3. So the maximum possible profit is 3. Note that we cannot put both the items with weight 4 and 1 together as the capacity of the bag is 4. + +Input: N = 3, W = 3, profit[] = {1, 2, 3}, weight[] = {4, 5, 6} +Output: 0 + +## Java Implementation + +```java +class Knapsack { + + // A utility function that returns + // maximum of two integers + static int max(int a, int b) { return (a > b) ? a : b; } + + // Returns the maximum value that + // can be put in a knapsack of + // capacity W + static int knapSack(int W, int wt[], int val[], int n) + { + // Base Case + if (n == 0 || W == 0) + return 0; + + // If weight of the nth item is + // more than Knapsack capacity W, + // then this item cannot be included + // in the optimal solution + if (wt[n - 1] > W) + return knapSack(W, wt, val, n - 1); + + // Return the maximum of two cases: + // (1) nth item included + // (2) not included + else + return max(val[n - 1] + + knapSack(W - wt[n - 1], wt, + val, n - 1), + knapSack(W, wt, val, n - 1)); + } + + // Driver code + public static void main(String args[]) + { + int profit[] = new int[] { 60, 100, 120 }; + int weight[] = new int[] { 10, 20, 30 }; + int W = 50; + int n = profit.length; + System.out.println(knapSack(W, weight, profit, n)); + } +} +``` + +### Time Complexity: $O(2N)$ +### Auxiliary Space: $O(N)$, Stack space required for recursion diff --git a/docs/Algorithms/Dynamic Programming/04-Longest-Common-Subsequence.md b/docs/Algorithms/Dynamic Programming/04-Longest-Common-Subsequence.md new file mode 100644 index 0000000..f20882f --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/04-Longest-Common-Subsequence.md @@ -0,0 +1,239 @@ +--- +id: longest-common-subsequence +title: Longest Common Subsequence (LCS) using Dynamic Programming +sidebar_label: Longest Common Subsequence (LCS) +tags: [python, java, c++, javascript, programming, algorithms, dynamic programming, tutorial, in-depth] +description: In this tutorial, we will learn about the Longest Common Subsequence (LCS) problem and its implementation using Dynamic Programming in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +# Longest Common Subsequence (LCS) using Dynamic Programming + +The Longest Common Subsequence (LCS) problem is a classic dynamic programming problem that finds the longest subsequence common to two sequences. + +## Problem Statement + +Given two sequences (X and Y), find the length of the longest common subsequence. + +### Intuition + +The LCS problem can be efficiently solved using dynamic programming. We can build a table to store the lengths of the longest common subsequences for various prefixes of the input sequences. + +## Naive Recursive Approach + +The naive recursive approach to solving the LCS problem has exponential time complexity and is not efficient for large inputs. + +```python +def lcs_recursive(X, Y, m, n): + if m == 0 or n == 0: + return 0 + elif X[m - 1] == Y[n - 1]: + return 1 + lcs_recursive(X, Y, m - 1, n - 1) + else: + return max(lcs_recursive(X, Y, m, n - 1), lcs_recursive(X, Y, m - 1, n)) +``` + +## Dynamic Programming Approach + +Using dynamic programming, we can efficiently solve the LCS problem by building a table and filling it iteratively. + +### Bottom-Up Approach + +We iteratively fill the table to find the length of the longest common subsequence. + +## Pseudocode for LCS using DP + +#### Initialize: + +```markdown +Let m be the length of sequence X +Let n be the length of sequence Y + +Create a table dp[m + 1][n + 1] to store lengths of LCS + +Loop from 0 to m: + Set dp[i][0] = 0 + +Loop from 0 to n: + Set dp[0][j] = 0 + +Loop from 1 to m: + Loop from 1 to n: + If X[i-1] == Y[j-1]: + dp[i][j] = dp[i-1][j-1] + 1 + Else: + dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + +Return dp[m][n] which represents the length of the LCS + +``` +### Example Output: +Given the input sequences: +- `X = "AGGTAB"` +- `Y = "GXTXAYB"` + +The length of the Longest Common Subsequence (LCS) between `X` and `Y` is `4`. + +### Output Explanation: +The Longest Common Subsequence (LCS) between `X` and `Y` is "GTAB", which has a length of `4`. + +You can verify this by manually checking the common subsequences: + +- "G", "G", "G", "A", "A", "B" +- "G", "G", "T", "A", "A", "B" +- "G", "X", "T", "A", "A", "B" +- "A", "G", "T", "A", "A", "B" +- "A", "X", "T", "A", "A", "B" +- "A", "G", "X", "A", "A", "B" +- "A", "G", "T", "X", "A", "B" +- "A", "G", "T", "A", "X", "B" +- "A", "G", "T", "A", "A", "X" + +Out of these, "GTAB" is the longest common subsequence with a length of `4`, hence the output. + +## Implementing LCS using DP + +### Python Implementation + +```python +def lcs_dp(X, Y): + # Get lengths of input sequences + m, n = len(X), len(Y) + + # Initialize a table to store lengths of LCS + dp = [[0] * (n + 1) for _ in range(m + 1)] + + # Iterate through the sequences to fill the table + for i in range(1, m + 1): + for j in range(1, n + 1): + # If characters match, increment LCS length + if X[i - 1] == Y[j - 1]: + dp[i][j] = dp[i - 1][j - 1] + 1 + else: + # Otherwise, take the maximum of previous LCS lengths + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + + # Return the length of LCS + return dp[m][n] + +``` + +### Java Implementation + +```java +public class LCS { + public static int lcs_dp(String X, String Y) { + // Get lengths of input sequences + int m = X.length(); + int n = Y.length(); + + // Initialize a table to store lengths of LCS + int[][] dp = new int[m + 1][n + 1]; + + // Iterate through the sequences to fill the table + for (int i = 1; i <= m; i++) { + for (int j = 1; j <= n; j++) { + // If characters match, increment LCS length + if (X.charAt(i - 1) == Y.charAt(j - 1)) + dp[i][j] = dp[i - 1][j - 1] + 1; + else + // Otherwise, take the maximum of previous LCS lengths + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + + // Return the length of LCS + return dp[m][n]; + } + + public static void main(String[] args) { + // Example usage + String X = "AGGTAB"; + String Y = "GXTXAYB"; + System.out.println("Length of LCS: " + lcs_dp(X, Y)); + } +} +``` +### C++ Implementation + +```cpp +#include +#include +using namespace std; + +int lcs_dp(string X, string Y) { + // Get lengths of input sequences + int m = X.length(); + int n = Y.length(); + + // Initialize a table to store lengths of LCS + int dp[m + 1][n + 1]; + + // Iterate through the sequences to fill the table + for (int i = 0; i <= m; i++) { + for (int j = 0; j <= n; j++) { + // Base case: if either sequence is empty, LCS length is 0 + if (i == 0 || j == 0) + dp[i][j] = 0; + // If characters match, increment LCS length + else if (X[i - 1] == Y[j - 1]) + dp[i][j] = dp[i - 1][j - 1] + 1; + else + // Otherwise, take the maximum of previous LCS lengths + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); + } + } + + // Return the length of LCS + return dp[m][n]; +} + +int main() { + // Example usage + string X = "AGGTAB"; + string Y = "GXTXAYB"; + cout << "Length of LCS: " << lcs_dp(X, Y) << endl; + return 0; +} +``` + +### JavaScript Implementation + +```javascript +function lcs_dp(X, Y) { + // Get lengths of input sequences + const m = X.length; + const n = Y.length; + + // Initialize a table to store lengths of LCS + const dp = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); + + // Iterate through the sequences to fill the table + for (let i = 1; i <= m; i++) { + for (let j = 1; j <= n; j++) { + // If characters match, increment LCS length + if (X[i - 1] === Y[j - 1]) + dp[i][j] = dp[i - 1][j - 1] + 1; + else + // Otherwise, take the maximum of previous LCS lengths + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + + // Return the length of LCS + return dp[m][n]; +} + +// Example usage +const X = "AGGTAB"; +const Y = "GXTXAYB"; +console.log("Length of LCS: " + lcs_dp(X, Y)); +``` + +## Complexity Analysis + +- Time Complexity: $O(m \times n)$, where m and n are the lengths of the input sequences X and Y, respectively. +- Space Complexity: $O(m \times n)$, due to the table used for dynamic programming. + +## Conclusion + +Dynamic programming provides an efficient solution for finding the longest common subsequence between two sequences by storing intermediate results and avoiding redundant calculations. This approach significantly reduces the time complexity compared to the naive recursive approach. diff --git a/docs/Algorithms/Dynamic Programming/05-Longest-Increasing-Subsequence.md b/docs/Algorithms/Dynamic Programming/05-Longest-Increasing-Subsequence.md new file mode 100644 index 0000000..994356b --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/05-Longest-Increasing-Subsequence.md @@ -0,0 +1,185 @@ +--- +id: longest-increasing-subsequence +title: Longest Increasing Subsequence (LIS) using Dynamic Programming +sidebar_label: Longest Increasing Subsequence (LIS) +tags: [python, java, c++, javascript, programming, algorithms, dynamic programming, tutorial, in-depth] +description: In this tutorial, we will learn about the Longest Increasing Subsequence (LIS) problem and its implementation using Dynamic Programming in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +# Longest Increasing Subsequence (LIS) using Dynamic Programming + +The Longest Increasing Subsequence (LIS) problem is a classic dynamic programming problem that finds the length of the longest subsequence in an array such that all elements of the subsequence are sorted in increasing order. + +## Problem Statement + +Given an array of integers, find the length of the longest increasing subsequence. + +### Intuition + +The LIS problem can be efficiently solved using dynamic programming. We can build a table to store the lengths of the longest increasing subsequences for various prefixes of the input array. + +## Dynamic Programming Approach + +Using dynamic programming, we can efficiently solve the LIS problem by building a table and filling it iteratively. + +### Bottom-Up Approach + +We iteratively fill the table to find the length of the longest increasing subsequence. + +## Pseudocode for LIS using DP + +#### Initialize: + +```markdown +Let n be the length of the input array nums + +Create an array dp of size n and initialize it with 1s (since each element is a subsequence of length 1) + +Loop from 1 to n: + Loop from 0 to i: + If nums[i] > nums[j]: + Update dp[i] to maximum of dp[i] and dp[j] + 1 + +Return the maximum value in dp which represents the length of the LIS + +``` + +### Example Output: +Given the input array: `nums = [10, 9, 2, 5, 3, 7, 101, 18]` +The length of the Longest Increasing Subsequence (LIS) in `nums` is `4`. + +### Output Explanation: + +The Longest Increasing Subsequence (LIS) in `nums` is `[2, 3, 7, 101]`, which has a length of `4`. + +You can verify this by manually checking the increasing subsequences: + +- [10, 101] +- [9, 101] +- [2, 5, 7, 101] +- [2, 3, 7, 101] + +Out of these, `[2, 3, 7, 101]` is the longest increasing subsequence with a length of `4`, hence the output. + +## Implementing LIS using DP + +### Python Implementation + +```python +def lis_dp(nums): + # Get length of input array + n = len(nums) + + # Initialize an array to store lengths of LIS + dp = [1] * n + + # Iterate through the array to fill the table + for i in range(1, n): + for j in range(i): + if nums[i] > nums[j]: + dp[i] = max(dp[i], dp[j] + 1) + + # Return the maximum value in dp which represents the length of the LIS + return max(dp) +``` + +### Java Implementation + +```java +public class LIS { + public static int lis_dp(int[] nums) { + // Get length of input array + int n = nums.length; + + // Initialize an array to store lengths of LIS + int[] dp = new int[n]; + Arrays.fill(dp, 1); + + // Iterate through the array to fill the table + for (int i = 1; i < n; i++) { + for (int j = 0; j < i; j++) { + if (nums[i] > nums[j]) + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + + // Return the maximum value in dp which represents the length of the LIS + return Arrays.stream(dp).max().getAsInt(); + } + + public static void main(String[] args) { + // Example usage + int[] nums = {10, 9, 2, 5, 3, 7, 101, 18}; + System.out.println("Length of LIS: " + lis_dp(nums)); + } +} +``` +### C++ Implementation + +```cpp +#include +#include +using namespace std; + +int lis_dp(vector& nums) { + // Get length of input array + int n = nums.size(); + + // Initialize an array to store lengths of LIS + vector dp(n, 1); + + // Iterate through the array to fill the table + for (int i = 1; i < n; i++) { + for (int j = 0; j < i; j++) { + if (nums[i] > nums[j]) + dp[i] = max(dp[i], dp[j] + 1); + } + } + + // Return the maximum value in dp which represents the length of the LIS + return *max_element(dp.begin(), dp.end()); +} + +int main() { + // Example usage + vector nums = {10, 9, 2, 5, 3, 7, 101, 18}; + cout << "Length of LIS: " << lis_dp(nums) << endl; + return 0; +} +``` + +### JavaScript Implementation + +```javascript +function lis_dp(nums) { + // Get length of input array + const n = nums.length; + + // Initialize an array to store lengths of LIS + const dp = new Array(n).fill(1); + + // Iterate through the array to fill the table + for (let i = 1; i < n; i++) { + for (let j = 0; j < i; j++) { + if (nums[i] > nums[j]) + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + + // Return the maximum value in dp which represents the length of the LIS + return Math.max(...dp); +} + +// Example usage +const nums = [10, 9, 2, 5, 3, 7, 101, 18]; +console.log("Length of LIS: " + lis_dp(nums)); +``` + +### Complexity Analysis + +- Time Complexity: $O(n^2)$, where n is the length of the input array `nums`. We iterate through the array twice to fill the table, each taking $O(n)$ time. +- Space Complexity: $O(n)$, where n is the length of the input array `nums`. We use an additional array of length n to store lengths of LIS. + +### Conclusion + +Dynamic programming provides an efficient solution for finding the length of the Longest Increasing Subsequence (LIS) in an array. By iteratively filling a table and storing intermediate results, we can achieve a time complexity of \( O(n^2) \), significantly better than the naive recursive approach. This approach allows us to efficiently solve the LIS problem for large input arrays. \ No newline at end of file diff --git a/docs/Algorithms/Dynamic Programming/06-Multistage-Graph.md b/docs/Algorithms/Dynamic Programming/06-Multistage-Graph.md new file mode 100644 index 0000000..b2d9aa3 --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/06-Multistage-Graph.md @@ -0,0 +1,225 @@ +--- + +id: multistage-graph +title: Multistage Graph Algorithm +sidebar_label: Multistage Graph Algorithm +tags: [python, java, c++, javascript, programming, algorithms, graph, shortest-path, data structures, tutorial, in-depth] +description: In this tutorial, we will learn about the Multistage Graph Algorithm and its implementation in Python, Java, C++, and JavaScript with detailed explanations and examples. + +--- + +# Multistage Graph Algorithm + +## Introduction + +A Multistage Graph is a directed graph in which vertices are divided into stages, with edges only directed from one stage to the next. The Multistage Graph Algorithm finds the shortest path from a source vertex in the first stage to a destination vertex in the last stage. + +## Key Concepts + +- **Stages**: The graph is divided into several stages. +- **Directed Edges**: Each edge connects a vertex in one stage to a vertex in the next stage. +- **Shortest Path**: The path from the source to the destination with the minimum total edge weight. + +## Steps + +1. Initialize a table to store the shortest path costs from each vertex to the destination. +2. Start from the destination vertex and move backwards to the source vertex. +3. For each vertex, calculate the shortest path cost to the destination by considering all possible paths through the subsequent stages. +4. The final value at the source vertex will be the shortest path cost. + + +![multistage](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTZcLRL-JXQ84J5e5F9BA6BzU76RAtn9vuAnw&s) +## Pseudocode + +Here’s the pseudocode for the Multistage Graph Algorithm: + +```python +function multistage_graph(graph, stages): + n = number of vertices in graph + cost = array of size n with initial values as infinity + cost[destination] = 0 + + for each vertex from destination to source: + for each edge from vertex: + cost[vertex] = min(cost[vertex], edge cost + cost[edge to vertex]) + + return cost[source] +``` + +## Implementation in Various Languages + +### Python + +```python +def multistage_graph(graph, stages): + n = len(graph) + cost = [float('inf')] * n + cost[-1] = 0 # Cost to reach destination from itself is 0 + + for i in range(n - 2, -1, -1): + for j in range(i + 1, n): + if graph[i][j] != float('inf'): + cost[i] = min(cost[i], graph[i][j] + cost[j]) + + return cost[0] + +# Example usage +graph = [ + [float('inf'), 1, 2, 5, float('inf'), float('inf'), float('inf')], + [float('inf'), float('inf'), float('inf'), float('inf'), 4, 11, float('inf')], + [float('inf'), float('inf'), float('inf'), float('inf'), 9, 5, 16], + [float('inf'), float('inf'), float('inf'), float('inf'), float('inf'), float('inf'), 2], + [float('inf'), float('inf'), float('inf'), float('inf'), float('inf'), float('inf'), 18], + [float('inf'), float('inf'), float('inf'), float('inf'), float('inf'), float('inf'), 13], + [float('inf'), float('inf'), float('inf'), float('inf'), float('inf'), float('inf'), float('inf')] +] + +stages = 4 +print(multistage_graph(graph, stages)) # Output: 17 +``` + +### Java + +```java +import java.util.Arrays; + +public class MultistageGraph { + public static int multistageGraph(int[][] graph, int stages) { + int n = graph.length; + int[] cost = new int[n]; + Arrays.fill(cost, Integer.MAX_VALUE); + cost[n - 1] = 0; // Cost to reach destination from itself is 0 + + for (int i = n - 2; i >= 0; i--) { + for (int j = i + 1; j < n; j++) { + if (graph[i][j] != Integer.MAX_VALUE) { + cost[i] = Math.min(cost[i], graph[i][j] + cost[j]); + } + } + } + + return cost[0]; + } + + public static void main(String[] args) { + int[][] graph = { + {Integer.MAX_VALUE, 1, 2, 5, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE}, + {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 4, 11, Integer.MAX_VALUE}, + {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 9, 5, 16}, + {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 2}, + {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 18}, + {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 13}, + {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE} + }; + + int stages = 4; + System.out.println(multistageGraph(graph, stages)); // Output: 17 + } +} +``` + +### C++ + +```cpp +#include +#include +#include +#include + +using namespace std; + +int multistageGraph(vector> &graph, int stages) { + int n = graph.size(); + vector cost(n, INT_MAX); + cost[n - 1] = 0; // Cost to reach destination from itself is 0 + + for (int i = n - 2; i >= 0; i--) { + for (int j = i + 1; j < n; j++) { + if (graph[i][j] != INT_MAX) { + cost[i] = min(cost[i], graph[i][j] + cost[j]); + } + } + } + + return cost[0]; +} + +int main() { + vector> graph = { + {INT_MAX, 1, 2, 5, INT_MAX, INT_MAX, INT_MAX}, + {INT_MAX, INT_MAX, INT_MAX, INT_MAX, 4, 11, INT_MAX}, + {INT_MAX, INT_MAX, INT_MAX, INT_MAX, 9, 5, 16}, + {INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, 2}, + {INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, 18}, + {INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, 13}, + {INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX, INT_MAX} + }; + + int stages = 4; + cout << multistageGraph(graph, stages) << endl; // Output: 17 + + return 0; +} +``` + +### JavaScript + +```javascript +function multistageGraph(graph, stages) { + const n = graph.length; + const cost = new Array(n).fill(Infinity); + cost[n - 1] = 0; // Cost to reach destination from itself is 0 + + for (let i = n - 2; i >= 0; i--) { + for (let j = i + 1; j < n; j++) { + if (graph[i][j] !== Infinity) { + cost[i] = Math.min(cost[i], graph[i][j] + cost[j]); + } + } + } + + return cost[0]; +} + +// Example usage +const graph = [ + [Infinity, 1, 2, 5, Infinity, Infinity, Infinity], + [Infinity, Infinity, Infinity, Infinity, 4, 11, Infinity], + [Infinity, Infinity, Infinity, Infinity, 9, 5, 16], + [Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, 2], + [Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, 18], + [Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, 13], + [Infinity, Infinity, Infinity, Infinity, Infinity, Infinity, Infinity] +]; + +const stages = 4; +console.log(multistageGraph(graph, stages)); // Output: 17 +``` + +## Example + +Consider a multistage graph with vertices and edges: + +```plaintext +graph = [ + [∞, 1, 2, 5, ∞, ∞, ∞], + [∞, ∞, ∞, ∞, 4, 11, ∞], + [∞, ∞, ∞, ∞, 9, 5, 16], + [∞, ∞, ∞, ∞, ∞, ∞, 2], + [∞, ∞, ∞, ∞, ∞, ∞, 18], + [∞, ∞, ∞, ∞, ∞, ∞, 13], + [∞, ∞, ∞, ∞, ∞, ∞, ∞] +] +``` + +1. Start from the destination vertex and move backwards. +2. Calculate the shortest path cost + + for each vertex considering all possible paths. +3. The shortest path cost from the source vertex will be the result. + +The shortest path cost is 17. + +## Conclusion + +The Multistage Graph Algorithm efficiently finds the shortest path in a graph divided into stages. It operates in $O(V^2)$ time complexity, making it suitable for graphs with a structured stage-based layout. Understanding and implementing this algorithm is essential for solving complex optimization problems in various applications. diff --git a/docs/Algorithms/Dynamic Programming/07-Matrix-Chain-Multiplication.md b/docs/Algorithms/Dynamic Programming/07-Matrix-Chain-Multiplication.md new file mode 100644 index 0000000..b4309e9 --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/07-Matrix-Chain-Multiplication.md @@ -0,0 +1,195 @@ +--- +id: matrix-chain-multiplication +title: Matrix Chain Multiplication using Dynamic Programming +sidebar_label: Matrix Chain Multiplication +tags: [python, java, c++, javascript, programming, algorithms, dynamic programming, tutorial, in-depth] +description: In this tutorial, we will learn about the Matrix Chain Multiplication problem and its solution using Dynamic Programming in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +# Matrix Chain Multiplication using Dynamic Programming + +Matrix Chain Multiplication is a classic optimization problem that can be solved efficiently using dynamic programming. The goal is to determine the most efficient way to multiply a given sequence of matrices. + +## Problem Statement + +Given a sequence of matrices, find the optimal way to parenthesize the matrix product such that the total number of scalar multiplications is minimized. + +### Intuition + +Matrix multiplication is associative, meaning that the order of multiplication can affect the computation cost. Dynamic programming helps by breaking down the problem into subproblems, solving each subproblem just once, and storing the results. + +## Dynamic Programming Approach + +Using dynamic programming, we build a table `dp` where `dp[i][j]` represents the minimum number of scalar multiplications needed to compute the product of matrices from `i` to `j`. + +## Pseudocode for Matrix Chain Multiplication using DP + +#### Initialize: + +```markdown +for i from 1 to n: + dp[i][i] = 0 + +for len from 2 to n: + for i from 1 to n-len+1: + j = i+len-1 + dp[i][j] = inf + for k from i to j-1: + q = dp[i][k] + dp[k+1][j] + p[i-1]*p[k]*p[j] + if q < dp[i][j]: + dp[i][j] = q + +return dp[1][n] +``` +### Example Output: + +Given the matrix dimensions: +- `p = [1, 2, 3, 4]` + +The minimum number of multiplications required to multiply the sequence of matrices is `18`. + +The matrix dimensions correspond to three matrices: +- A (1x2) +- B (2x3) +- C (3x4) + +By following the dynamic programming approach, the optimal way to multiply these matrices requires `18` scalar multiplications. The output is printed as: `Minimum number of multiplications is: 18` + +You can verify this by manually checking the optimal parenthesization: `((A * B) * C) requires (1*2*3) + (1*3*4) = 6 + 12 = 18` multiplications. + + +## Implementing Matrix Chain Multiplication using DP + +### Python Implementation + +```python +def matrix_chain_order(p): + n = len(p) - 1 # Number of matrices + dp = [[0 for _ in range(n)] for _ in range(n)] # DP table initialization + + # l is the chain length + for l in range(2, n + 1): # l=2 means multiplying two matrices at a time + for i in range(n - l + 1): + j = i + l - 1 + dp[i][j] = float('inf') # Initialize with infinity + for k in range(i, j): + # q = cost/scalar multiplications + q = dp[i][k] + dp[k + 1][j] + p[i] * p[k + 1] * p[j + 1] + if q < dp[i][j]: + dp[i][j] = q + + return dp[0][n - 1] # Minimum cost to multiply all matrices + +p = [1, 2, 3, 4] +print("Minimum number of multiplications is:", matrix_chain_order(p)) +``` + +### Java Implementation + +```java +public class MatrixChainMultiplication { + public static int matrixChainOrder(int[] p) { + int n = p.length - 1; // Number of matrices + int[][] dp = new int[n][n]; // DP table initialization + + // l is the chain length + for (int l = 2; l <= n; l++) { // l=2 means multiplying two matrices at a time + for (int i = 0; i < n - l + 1; i++) { + int j = i + l - 1; + dp[i][j] = Integer.MAX_VALUE; // Initialize with infinity + for (int k = i; k < j; k++) { + // q = cost/scalar multiplications + int q = dp[i][k] + dp[k + 1][j] + p[i] * p[k + 1] * p[j + 1]; + if (q < dp[i][j]) { + dp[i][j] = q; + } + } + } + } + + return dp[0][n - 1]; // Minimum cost to multiply all matrices + } + + public static void main(String[] args) { + int[] p = {1, 2, 3, 4}; + System.out.println("Minimum number of multiplications is: " + matrixChainOrder(p)); + } +} + +``` +### C++ Implementation + +```cpp +#include +#include +using namespace std; + +int matrixChainOrder(int p[], int n) { + int dp[n][n]; // DP table initialization + + // l is the chain length + for (int i = 1; i < n; i++) + dp[i][i] = 0; // Cost is zero when multiplying one matrix + + for (int l = 2; l < n; l++) { // l=2 means multiplying two matrices at a time + for (int i = 1; i < n - l + 1; i++) { + int j = i + l - 1; + dp[i][j] = INT_MAX; // Initialize with infinity + for (int k = i; k <= j - 1; k++) { + // q = cost/scalar multiplications + int q = dp[i][k] + dp[k + 1][j] + p[i - 1] * p[k] * p[j]; + if (q < dp[i][j]) { + dp[i][j] = q; + } + } + } + } + + return dp[1][n - 1]; // Minimum cost to multiply all matrices +} + +int main() { + int p[] = {1, 2, 3, 4}; + int n = sizeof(p) / sizeof(p[0]); + cout << "Minimum number of multiplications is: " << matrixChainOrder(p, n); + return 0; +} +``` + +### JavaScript Implementation + +```javascript +function matrixChainOrder(p) { + let n = p.length - 1; // Number of matrices + let dp = Array.from({ length: n }, () => Array(n).fill(0)); // DP table initialization + + // l is the chain length + for (let l = 2; l <= n; l++) { // l=2 means multiplying two matrices at a time + for (let i = 0; i < n - l + 1; i++) { + let j = i + l - 1; + dp[i][j] = Infinity; // Initialize with infinity + for (let k = i; k < j; k++) { + // q = cost/scalar multiplications + let q = dp[i][k] + dp[k + 1][j] + p[i] * p[k + 1] * p[j + 1]; + if (q < dp[i][j]) { + dp[i][j] = q; + } + } + } + } + + return dp[0][n - 1]; // Minimum cost to multiply all matrices +} + +let p = [1, 2, 3, 4]; +console.log("Minimum number of multiplications is:", matrixChainOrder(p)); +``` + +## Complexity Analysis + +- Time Complexity: $O(n^3)$, due to the three nested loops. +- Space Complexity: $O(n^2)$, for storing the DP table. + +## Conclusion + +Dynamic programming provides an efficient solution for the Matrix Chain Multiplication problem by breaking it into subproblems and storing intermediate results. This technique can be extended to solve other problems with overlapping subproblems and optimal substructure properties. \ No newline at end of file diff --git a/docs/Algorithms/Dynamic Programming/08-Coin-Change.md b/docs/Algorithms/Dynamic Programming/08-Coin-Change.md new file mode 100644 index 0000000..f27c77d --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/08-Coin-Change.md @@ -0,0 +1,185 @@ +--- +id: coin-change-problem +title: Coin Change Problem using Dynamic Programming +sidebar_label: Coin Change Problem +tags: [python, java, c++, javascript, programming, algorithms, dynamic programming, tutorial, in-depth] +description: In this tutorial, we will learn about the Coin Change Problem and its solution using Dynamic Programming in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +# Coin Change Problem using Dynamic Programming + +The Coin Change Problem is a classic algorithmic problem that aims to find the number of ways to make change for a given amount using a specific set of coin denominations. + +## Problem Statement + +Given a set of coins with different denominations and a total amount of money, determine the number of unique ways to make change for the given amount using any combination of coins. + +### Intuition + +The problem can be efficiently solved using dynamic programming. By breaking down the problem into smaller subproblems and storing the results, dynamic programming helps avoid redundant calculations. + +## Dynamic Programming Approach + +Using dynamic programming, we build a table `dp` where `dp[i][j]` represents the number of ways to make change for amount `j` using the first `i` coins. + +## Pseudocode for Coin Change Problem using DP + +#### Initialize: + +```markdown +dp[0][j] = 1 // Base case: one way to make change for amount 0 +dp[i][0] = 1 // Base case: one way to make change for any amount using 0 coins + +for i from 1 to n: + for j from 1 to amount: + if coins[i-1] > j: + dp[i][j] = dp[i-1][j] + else: + dp[i][j] = dp[i-1][j] + dp[i][j-coins[i-1]] + +return dp[n][amount] +``` + +### Example Output: + +Given the coins `[1, 2, 5]` and the amount `amount = 5`, the number of ways to make change is `4`. + +### Output Explanation: + +- There are four ways to make change for the amount `5` using the coins `[1, 2, 5]`: + - `[1, 1, 1, 1, 1]` + - `[1, 1, 1, 2]` + - `[1, 2, 2]` + - `[5]` + +## Implementing Coin Change using DP + +### Python Implementation + +```python +def coin_change(coins, amount): + n = len(coins) + dp = [[0] * (amount + 1) for _ in range(n + 1)] + for i in range(n + 1): + dp[i][0] = 1 + + for i in range(1, n + 1): + for j in range(1, amount + 1): + if coins[i - 1] > j: + dp[i][j] = dp[i - 1][j] + else: + dp[i][j] = dp[i - 1][j] + dp[i][j - coins[i - 1]] + + return dp[n][amount] + +coins = [1, 2, 5] +amount = 5 +print("Number of ways to make change:", coin_change(coins, amount)) + +``` + +### Java Implementation + +```java +public class CoinChange { + public static int coinChange(int[] coins, int amount) { + int n = coins.length; + int[][] dp = new int[n + 1][amount + 1]; + for (int i = 0; i <= n; i++) { + dp[i][0] = 1; + } + + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= amount; j++) { + if (coins[i - 1] > j) { + dp[i][j] = dp[i - 1][j]; + } else { + dp[i][j] = dp[i - 1][j] + dp[i][j - coins[i - 1]]; + } + } + } + + return dp[n][amount]; + } + + public static void main(String[] args) { + int[] coins = {1, 2, 5}; + int amount = 5; + System.out.println("Number of ways to make change: " + coinChange(coins, amount)); + } +} + +``` +### C++ Implementation + +```cpp +#include +#include +using namespace std; + +int coinChange(vector& coins, int amount) { + int n = coins.size(); + vector> dp(n + 1, vector(amount + 1, 0)); + for (int i = 0; i <= n; i++) { + dp[i][0] = 1; + } + + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= amount; j++) { + if (coins[i - 1] > j) { + dp[i][j] = dp[i - 1][j]; + } else { + dp[i][j] = dp[i - 1][j] + dp[i][j - coins[i - 1]]; + } + } + } + + return dp[n][amount]; +} + +int main() { + vector coins = {1, 2, 5}; + int amount = 5; + cout << "Number of ways to make change: " << coinChange(coins, amount) << endl; + return 0; +} + +``` + +### JavaScript Implementation + +```javascript +function coinChange(coins, amount) { + let n = coins.length; + let dp = new Array(n + 1).fill(0).map(() => new Array(amount + 1).fill(0)); + for (let i = 0; i <= n; i++) { + dp[i][0] = 1; + } + + for (let i = 1; i <= n; i++) { + for (let j = 1; j <= amount; j++) { + if (coins[i - 1] > j) { + dp[i][j] = dp[i - 1][j]; + } else { + dp[i][j] = dp[i - 1][j] + dp[i][j - coins[i - 1]]; + } + } + } + + return dp[n][amount]; +} + +let coins = [1, 2, 5]; +let amount = 5; +console.log("Number of ways to make change:", coinChange(coins, amount)); + +``` + +## Complexity Analysis + +- Time Complexity: $O(n \cdot \text{amount})$, where n is the number of coins and amount is the given amount. +- Space Complexity: $O(n \cdot \text{amount})$, for the DP table. + +## Conclusion + +Dynamic programming offers an efficient solution to the Coin Change Problem by breaking it down into subproblems and storing intermediate results. This technique helps determine the number of ways to make change for a given amount using a specific \ No newline at end of file diff --git a/docs/Algorithms/Dynamic Programming/09-Edit-Distance.md b/docs/Algorithms/Dynamic Programming/09-Edit-Distance.md new file mode 100644 index 0000000..7e2d21f --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/09-Edit-Distance.md @@ -0,0 +1,212 @@ +--- +id: edit-distance +title: Edit Distance using Dynamic Programming +sidebar_label: Edit Distance +tags: [python, java, c++, javascript, programming, algorithms, dynamic programming, tutorial, in-depth] +description: In this tutorial, we will learn about the Edit Distance problem and its solution using Dynamic Programming in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +# Edit Distance using Dynamic Programming + +Edit Distance, also known as Levenshtein distance, is a classic problem in computer science that measures the minimum number of operations required to transform one string into another. The allowed operations are insertion, deletion, and substitution. + +## Problem Statement + +Given two strings, find the minimum number of operations required to transform one string into the other. + +### Intuition + +The problem can be solved efficiently using dynamic programming by breaking it down into subproblems. The idea is to create a DP table where `dp[i][j]` represents the edit distance between the first `i` characters of the first string and the first `j` characters of the second string. + +## Dynamic Programming Approach + +Using dynamic programming, we fill the table based on the recurrence relation: +- If the characters are the same, no new operation is needed. +- If the characters are different, consider the minimum cost of the three operations: insertion, deletion, and substitution. + +## Pseudocode for Edit Distance using DP + +#### Initialize: + +```markdown +for i from 0 to m: + dp[i][0] = i +for j from 0 to n: + dp[0][j] = j + +for i from 1 to m: + for j from 1 to n: + if str1[i-1] == str2[j-1]: + dp[i][j] = dp[i-1][j-1] + else: + dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + +return dp[m][n] +``` + +### Example Output: + +Given the strings: +- str1 = "kitten" +- str2 = "sitting" + +The minimum edit distance between `str1` and `str2` is `3`. + +### Output Explanation: + +The edit distance of `3` can be achieved by the following operations: + +- Replace 'k' with 's': kitten -> sitten +- Replace 'e' with 'i': sitten -> sittin +- Insert 'g' at the end: sittin -> sitting + +Therefore, the output is: `Minimum edit distance is: 3` + +## Implementing Edit Distance using DP + +### Python Implementation + +```python +def edit_distance(str1, str2): + m, n = len(str1), len(str2) + dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)] # DP table initialization + + for i in range(m + 1): + for j in range(n + 1): + if i == 0: + dp[i][j] = j # If first string is empty, insert all characters of second string + elif j == 0: + dp[i][j] = i # If second string is empty, remove all characters of first string + elif str1[i - 1] == str2[j - 1]: + dp[i][j] = dp[i - 1][j - 1] + else: + dp[i][j] = 1 + min(dp[i - 1][j], # Remove + dp[i][j - 1], # Insert + dp[i - 1][j - 1]) # Replace + + return dp[m][n] + +str1 = "kitten" +str2 = "sitting" +print("Minimum edit distance is:", edit_distance(str1, str2)) + +``` + +### Java Implementation + +```java +public class EditDistance { + public static int editDistance(String str1, String str2) { + int m = str1.length(); + int n = str2.length(); + int[][] dp = new int[m + 1][n + 1]; // DP table initialization + + for (int i = 0; i <= m; i++) { + for (int j = 0; j <= n; j++) { + if (i == 0) { + dp[i][j] = j; // If first string is empty, insert all characters of second string + } else if (j == 0) { + dp[i][j] = i; // If second string is empty, remove all characters of first string + } else if (str1.charAt(i - 1) == str2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1]; + } else { + dp[i][j] = 1 + Math.min(dp[i - 1][j], // Remove + Math.min(dp[i][j - 1], // Insert + dp[i - 1][j - 1])); // Replace + } + } + } + + return dp[m][n]; + } + + public static void main(String[] args) { + String str1 = "kitten"; + String str2 = "sitting"; + System.out.println("Minimum edit distance is: " + editDistance(str1, str2)); + } +} + +``` +### C++ Implementation + +```cpp +#include +#include +#include +using namespace std; + +int editDistance(string str1, string str2) { + int m = str1.length(); + int n = str2.length(); + vector> dp(m + 1, vector(n + 1)); // DP table initialization + + for (int i = 0; i <= m; i++) { + for (int j = 0; j <= n; j++) { + if (i == 0) { + dp[i][j] = j; // If first string is empty, insert all characters of second string + } else if (j == 0) { + dp[i][j] = i; // If second string is empty, remove all characters of first string + } else if (str1[i - 1] == str2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1]; + } else { + dp[i][j] = 1 + min({dp[i - 1][j], // Remove + dp[i][j - 1], // Insert + dp[i - 1][j - 1]}); // Replace + } + } + } + + return dp[m][n]; +} + +int main() { + string str1 = "kitten"; + string str2 = "sitting"; + cout << "Minimum edit distance is: " << editDistance(str1, str2) << endl; + return 0; +} + +``` + +### JavaScript Implementation + +```javascript +function editDistance(str1, str2) { + let m = str1.length; + let n = str2.length; + let dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); // DP table initialization + + for (let i = 0; i <= m; i++) { + for (let j = 0; j <= n; j++) { + if (i === 0) { + dp[i][j] = j; // If first string is empty, insert all characters of second string + } else if (j === 0) { + dp[i][j] = i; // If second string is empty, remove all characters of first string + } else if (str1[i - 1] === str2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1]; + } else { + dp[i][j] = 1 + Math.min(dp[i - 1][j], // Remove + dp[i][j - 1], // Insert + dp[i - 1][j - 1]); // Replace + } + } + } + + return dp[m][n]; +} + +let str1 = "kitten"; +let str2 = "sitting"; +console.log("Minimum edit distance is:", editDistance(str1, str2)); + +``` + +## Complexity Analysis + +- Time Complexity: $O(m \times n)$, where m and n are the lengths of the two strings. +- Space Complexity: $O(m \times n)$, for storing the DP table. + +## Conclusion + +Dynamic programming provides an efficient solution for the Edit Distance problem by breaking it into subproblems and storing intermediate results. This technique can be extended to solve other problems with overlapping subproblems and optimal substructure properties. \ No newline at end of file diff --git a/docs/Algorithms/Dynamic Programming/10-Partition.md b/docs/Algorithms/Dynamic Programming/10-Partition.md new file mode 100644 index 0000000..978c72d --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/10-Partition.md @@ -0,0 +1,183 @@ +--- +id: partition-problem +title: Partition Problem using Dynamic Programming +sidebar_label: Partition Problem +tags: [python, java, c++, javascript, programming, algorithms, dynamic programming, tutorial, in-depth] +description: In this tutorial, we will learn about the Partition Problem and its solution using Dynamic Programming in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +# Partition Problem using Dynamic Programming + +The Partition Problem is a classic problem in computer science where the goal is to determine if a given set can be partitioned into two subsets with equal sum. + +## Problem Statement + +Given a set of integers, determine if it can be partitioned into two subsets such that the sum of elements in both subsets is the same. + +### Intuition + +The problem can be solved efficiently using dynamic programming by breaking it down into subproblems. The idea is to use a boolean DP table where `dp[i][j]` indicates whether a subset of the first `i` numbers can sum up to `j`. + +## Dynamic Programming Approach + +Using dynamic programming, we fill the table based on the recurrence relation: +- If including the current element in the subset is possible, update the DP table accordingly. + +## Pseudocode for Partition Problem using DP + +#### Initialize: + +```markdown +sum = sum of all elements +if sum is odd, return false + +target = sum / 2 +dp = [False] * (target + 1) +dp[0] = True + +for num in nums: + for j in range(target, num - 1, -1): + dp[j] = dp[j] or dp[j - num] + +return dp[target] +``` + +### Example Output: + +Given the set: +- `nums = [1, 5, 11, 5]` + +The set can be partitioned into two subsets with equal sum. + +### Output Explanation: + +The subsets `{1, 5, 5}` and `{11}` both sum up to `11`. + +Therefore, the output is: `The set can be partitioned into two subsets with equal sum.` + +## Implementing Partition using DP + +### Python Implementation + +```python +def can_partition(nums): + total_sum = sum(nums) + if total_sum % 2 != 0: + return False + + target = total_sum // 2 + dp = [False] * (target + 1) + dp[0] = True + + for num in nums: + for j in range(target, num - 1, -1): + dp[j] = dp[j] or dp[j - num] + + return dp[target] + +nums = [1, 5, 11, 5] +print("The set can be partitioned into two subsets with equal sum." if can_partition(nums) else "The set cannot be partitioned into two subsets with equal sum.") +``` + +### Java Implementation + +```java +public class PartitionProblem { + public static boolean canPartition(int[] nums) { + int totalSum = 0; + for (int num : nums) { + totalSum += num; + } + if (totalSum % 2 != 0) { + return false; + } + + int target = totalSum / 2; + boolean[] dp = new boolean[target + 1]; + dp[0] = true; + + for (int num : nums) { + for (int j = target; j >= num; j--) { + dp[j] = dp[j] || dp[j - num]; + } + } + + return dp[target]; + } + + public static void main(String[] args) { + int[] nums = {1, 5, 11, 5}; + System.out.println("The set can be partitioned into two subsets with equal sum." if canPartition(nums) else "The set cannot be partitioned into two subsets with equal sum."); + } +} +``` +### C++ Implementation + +```cpp +#include +#include +using namespace std; + +bool canPartition(vector& nums) { + int totalSum = 0; + for (int num : nums) { + totalSum += num; + } + if (totalSum % 2 != 0) { + return false; + } + + int target = totalSum / 2; + vector dp(target + 1, false); + dp[0] = true; + + for (int num : nums) { + for (int j = target; j >= num; j--) { + dp[j] = dp[j] || dp[j - num]; + } + } + + return dp[target]; +} + +int main() { + vector nums = {1, 5, 11, 5}; + cout << (canPartition(nums) ? "The set can be partitioned into two subsets with equal sum." : "The set cannot be partitioned into two subsets with equal sum.") << endl; + return 0; +} +``` + +### JavaScript Implementation + +```javascript +function canPartition(nums) { + let totalSum = nums.reduce((a, b) => a + b, 0); + if (totalSum % 2 !== 0) { + return false; + } + + let target = totalSum / 2; + let dp = new Array(target + 1).fill(false); + dp[0] = true; + + for (let num of nums) { + for (let j = target; j >= num; j--) { + dp[j] = dp[j] || dp[j - num]; + } + } + + return dp[target]; +} + +let nums = [1, 5, 11, 5]; +console.log(canPartition(nums) ? "The set can be partitioned into two subsets with equal sum." : "The set cannot be partitioned into two subsets with equal sum."); +``` + +## Complexity Analysis + +- Time Complexity: $O(n \times \text{sum})$, where n is the number of elements in the set and sum is the total sum of the elements. +- Space Complexity: $O(\text{sum})$, for storing the DP table. + +## Conclusion + +Dynamic programming provides an efficient solution for the Partition Problem by breaking it into subproblems and storing intermediate results. This technique can be extended to solve other problems with overlapping subproblems and optimal substructure properties. \ No newline at end of file diff --git a/docs/Algorithms/Dynamic Programming/11-Bellman-Ford-Algorithm.md b/docs/Algorithms/Dynamic Programming/11-Bellman-Ford-Algorithm.md new file mode 100644 index 0000000..2605645 --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/11-Bellman-Ford-Algorithm.md @@ -0,0 +1,277 @@ +--- +id: bellman-ford-algorithm +title: Bellman-Ford Algorithm +sidebar_label: Bellman-Ford Algorithm +tags: [python, java, c++, programming, algorithms, dynamic programming, graph, tutorial, in-depth] +description: In this tutorial, we will learn about the Bellman-Ford Algorithm and its solution using Dynamic Programming in Python, Java, and C++ with detailed explanations and examples. +--- + +# Bellman-Ford Algorithm + +The Bellman-Ford algorithm is a classic algorithm for finding the shortest paths in a weighted graph with negative weights. It is capable of handling graphs with negative edge weights and can also detect negative weight cycles. + +## Problem Statement + +Given a graph and a source vertex, find the shortest paths from the source vertex to all other vertices in the graph. + +### Intuition + +The algorithm iteratively relaxes the edges of the graph. The idea is to improve the estimate of the shortest path step by step. It takes up to `|V| - 1` iterations, where `|V|` is the number of vertices, to ensure that the shortest paths are found. If we perform one more iteration and still find a shorter path, it indicates the presence of a negative weight cycle. + +## Dynamic Programming Approach + +Using dynamic programming, we maintain an array `dist` where `dist[i]` holds the shortest distance from the source vertex to vertex `i`. + +## Pseudocode for Bellman-Ford Algorithm using DP + +#### Initialize: + +```markdown +dist[source] = 0 +for i from 1 to |V| - 1: + for each edge (u, v) with weight w: + if dist[u] + w < dist[v]: + dist[v] = dist[u] + w + +for each edge (u, v) with weight w: + if dist[u] + w < dist[v]: + print("Graph contains a negative weight cycle") + return +``` + +### Example Output: + +Given the graph: + +- `Vertices: {0, 1, 2, 3}` +- `Edges: {(0, 1, 1), (1, 2, 3), (2, 3, 2), (3, 1, -6)}` + +The set can be partitioned into two subsets with equal sum. + +### Output Explanation: + +The shortest distances from the source vertex 0 to all other vertices are: + +- `0 -> 1: 1` +- `0 -> 2: 4` +- `0 -> 3: 6` + +By following the Bellman-Ford algorithm, the shortest path distances from the source vertex 0 to vertices 1, 2, and 3 are found to be 1, 4, and 6 respectively. + +## Implementing Bellman-Ford Algorithm using DP + +### Python Implementation + +```python +class Graph: + def __init__(self, vertices): + self.V = vertices + self.graph = [] + + def add_edge(self, u, v, w): + self.graph.append([u, v, w]) + + def bellman_ford(self, src): + dist = [float("Inf")] * self.V + dist[src] = 0 + + for _ in range(self.V - 1): + for u, v, w in self.graph: + if dist[u] != float("Inf") and dist[u] + w < dist[v]: + dist[v] = dist[u] + w + + for u, v, w in self.graph: + if dist[u] != float("Inf") and dist[u] + w < dist[v]: + print("Graph contains a negative weight cycle") + return + + print("Vertex Distance from Source") + for i in range(self.V): + print(f"{i}\t\t{dist[i]}") + +g = Graph(4) +g.add_edge(0, 1, 1) +g.add_edge(1, 2, 3) +g.add_edge(2, 3, 2) +g.add_edge(3, 1, -6) + +g.bellman_ford(0) +``` + +### Java Implementation + +```java +import java.util.*; + +class Graph { + class Edge { + int src, dest, weight; + Edge() { + src = dest = weight = 0; + } + }; + + int V, E; + Edge edge[]; + + Graph(int v, int e) { + V = v; + E = e; + edge = new Edge[e]; + for (int i = 0; i < e; ++i) + edge[i] = new Edge(); + } + + void BellmanFord(Graph graph, int src) { + int V = graph.V, E = graph.E; + int dist[] = new int[V]; + + Arrays.fill(dist, Integer.MAX_VALUE); + dist[src] = 0; + + for (int i = 1; i < V; ++i) { + for (int j = 0; j < E; ++j) { + int u = graph.edge[j].src; + int v = graph.edge[j].dest; + int weight = graph.edge[j].weight; + if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) + dist[v] = dist[u] + weight; + } + } + + for (int j = 0; j < E; ++j) { + int u = graph.edge[j].src; + int v = graph.edge[j].dest; + int weight = graph.edge[j].weight; + if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) + System.out.println("Graph contains a negative weight cycle"); + } + + printArr(dist, V); + } + + void printArr(int dist[], int V) { + System.out.println("Vertex Distance from Source"); + for (int i = 0; i < V; ++i) + System.out.println(i + "\t\t" + dist[i]); + } + + public static void main(String[] args) { + Graph graph = new Graph(4, 4); + + graph.edge[0].src = 0; + graph.edge[0].dest = 1; + graph.edge[0].weight = 1; + + graph.edge[1].src = 1; + graph.edge[1].dest = 2; + graph.edge[1].weight = 3; + + graph.edge[2].src = 2; + graph.edge[2].dest = 3; + graph.edge[2].weight = 2; + + graph.edge[3].src = 3; + graph.edge[3].dest = 1; + graph.edge[3].weight = -6; + + graph.BellmanFord(graph, 0); + } +} +``` +### C++ Implementation + +```cpp +#include +using namespace std; + +struct Edge { + int src, dest, weight; +}; + +struct Graph { + int V, E; + struct Edge* edge; +}; + +struct Graph* createGraph(int V, int E) { + struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph)); + graph->V = V; + graph->E = E; + graph->edge = (struct Edge*) malloc(graph->E * sizeof(struct Edge)); + return graph; +} + +void printArr(int dist[], int n) { + cout << "Vertex Distance from Source" << endl; + for (int i = 0; i < n; ++i) + cout << i << "\t\t" << dist[i] << endl; +} + +void BellmanFord(struct Graph* graph, int src) { + int V = graph->V; + int E = graph->E; + int dist[V]; + + for (int i = 0; i < V; i++) + dist[i] = INT_MAX; + dist[src] = 0; + + for (int i = 1; i <= V - 1; i++) { + for (int j = 0; j < E; j++) { + int u = graph->edge[j].src; + int v = graph->edge[j].dest; + int weight = graph->edge[j].weight; + if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) + dist[v] = dist[u] + weight; + } + } + + for (int i = 0; i < E; i++) { + int u = graph->edge[i].src; + int v = graph->edge[i].dest; + int weight = graph->edge[i].weight; + if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { + cout << "Graph contains a negative weight cycle" << endl; + return; + } + } + + printArr(dist, V); +} + +int main() { + int V = 4; + int E = 4; + struct Graph* graph = createGraph(V, E); + + graph->edge[0].src = 0; + graph->edge[0].dest = 1; + graph->edge[0].weight = 1; + + graph->edge[1].src = 1; + graph->edge[1].dest = 2; + graph->edge[1].weight = 3; + + graph->edge[2].src = 2; + graph->edge[2].dest = 3; + graph->edge[2].weight = 2; + + graph->edge[3].src = 3; + graph->edge[3].dest = 1; + graph->edge[3].weight = -6; + + BellmanFord(graph, 0); + + return 0; +} +``` + +## Complexity Analysis + +- Time Complexity: $O(V \times E)$, where V is the number of vertices and E is the number of edges. +- Space Complexity: $O(V)$, for storing the distance array. + +## Conclusion + +The Bellman-Ford algorithm provides an efficient solution for finding the shortest paths in a graph with negative weights and can also detect negative weight cycles. This technique is useful in various applications, including network routing and financial modeling. \ No newline at end of file diff --git a/docs/Algorithms/Dynamic Programming/12-Wildcards-Matching.md b/docs/Algorithms/Dynamic Programming/12-Wildcards-Matching.md new file mode 100644 index 0000000..8c7fecd --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/12-Wildcards-Matching.md @@ -0,0 +1,177 @@ +--- +id: wildcards-matching +title: Wildcards Matching using Dynamic Programming +sidebar_label: Wildcards Matching +tags: [python, java, c++, programming, algorithms, dynamic programming, strings, tutorial, in-depth] +description: In this tutorial, we will learn about Wildcards Matching and its solution using Dynamic Programming in Python, Java, and C++ with detailed explanations and examples. +--- + +# Wildcards Matching using Dynamic Programming + +Wildcards Matching is a problem where we determine if a given text matches a pattern that includes wildcard characters. The two common wildcards are `?` which matches any single character, and `*` which matches any sequence of characters (including an empty sequence). + +## Problem Statement + +Given a text and a pattern with wildcards, determine if the text matches the pattern. + +### Intuition + +The problem can be efficiently solved using dynamic programming by breaking it down into subproblems. We use a DP table where `dp[i][j]` indicates if the first `i` characters of the text match the first `j` characters of the pattern. + +## Dynamic Programming Approach + +Using dynamic programming, we fill the table based on the recurrence relations: +- If the pattern character is `*`, it can match zero or more characters. +- If the pattern character is `?` or matches the current text character, update the DP table accordingly. + +## Pseudocode for Wildcards Matching using DP + +#### Initialize: + +```markdown +dp[0][0] = True +for j from 1 to len(pattern): + if pattern[j-1] == '*': + dp[0][j] = dp[0][j-1] + +for i from 1 to len(text): + for j from 1 to len(pattern): + if pattern[j-1] == '*': + dp[i][j] = dp[i][j-1] or dp[i-1][j] + elif pattern[j-1] == '?' or pattern[j-1] == text[i-1]: + dp[i][j] = dp[i-1][j-1] + +return dp[len(text)][len(pattern)] +``` + + +### Example Output: + +Given the graph: + +- `Vertices: {0, 1, 2, 3}` +- `Edges: {(0, 1, 1), (1, 2, 3), (2, 3, 2), (3, 1, -6)}` + +The set can be partitioned into two subsets with equal sum. + +### Output Explanation: + +The shortest distances from the source vertex 0 to all other vertices are: + +- `0 -> 1: 1` +- `0 -> 2: 4` +- `0 -> 3: 6` + +By following the Bellman-Ford algorithm, the shortest path distances from the source vertex 0 to vertices 1, 2, and 3 are found to be 1, 4, and 6 respectively. + +## Implementing Bellman-Ford Algorithm using DP + +### Python Implementation + +```python +def is_match(text, pattern): + m, n = len(text), len(pattern) + dp = [[False] * (n + 1) for _ in range(m + 1)] + dp[0][0] = True + + for j in range(1, n + 1): + if pattern[j - 1] == '*': + dp[0][j] = dp[0][j - 1] + + for i in range(1, m + 1): + for j in range(1, n + 1): + if pattern[j - 1] == '*': + dp[i][j] = dp[i][j - 1] or dp[i - 1][j] + elif pattern[j - 1] == '?' or pattern[j - 1] == text[i - 1]: + dp[i][j] = dp[i - 1][j - 1] + + return dp[m][n] + +text = "abcd" +pattern = "a*d" +print("The text matches the pattern." if is_match(text, pattern) else "The text does not match the pattern.") +``` + +### Java Implementation + +```java +public class WildcardMatching { + public static boolean isMatch(String text, String pattern) { + int m = text.length(), n = pattern.length(); + boolean[][] dp = new boolean[m + 1][n + 1]; + dp[0][0] = true; + + for (int j = 1; j <= n; j++) { + if (pattern.charAt(j - 1) == '*') { + dp[0][j] = dp[0][j - 1]; + } + } + + for (int i = 1; i <= m; i++) { + for (int j = 1; j <= n; j++) { + if (pattern.charAt(j - 1) == '*') { + dp[i][j] = dp[i][j - 1] || dp[i - 1][j]; + } else if (pattern.charAt(j - 1) == '?' || pattern.charAt(j - 1) == text.charAt(i - 1)) { + dp[i][j] = dp[i - 1][j - 1]; + } + } + } + + return dp[m][n]; + } + + public static void main(String[] args) { + String text = "abcd"; + String pattern = "a*d"; + System.out.println("The text matches the pattern." if isMatch(text, pattern) else "The text does not match the pattern."); + } +} +``` +### C++ Implementation + +```cpp +#include +#include +#include +using namespace std; + +bool isMatch(const string& text, const string& pattern) { + int m = text.size(), n = pattern.size(); + vector> dp(m + 1, vector(n + 1, false)); + dp[0][0] = true; + + for (int j = 1; j <= n; j++) { + if (pattern[j - 1] == '*') { + dp[0][j] = dp[0][j - 1]; + } + } + + for (int i = 1; i <= m; i++) { + for (int j = 1; j <= n; j++) { + if (pattern[j - 1] == '*') { + dp[i][j] = dp[i][j - 1] || dp[i - 1][j]; + } else if (pattern[j - 1] == '?' || pattern[j - 1] == text[i - 1]) { + dp[i][j] = dp[i - 1][j - 1]; + } + } + } + + return dp[m][n]; +} + +int main() { + string text = "abcd"; + string pattern = "a*d"; + cout << (isMatch(text, pattern) ? "The text matches the pattern." : "The text does not match the pattern.") << endl; + return 0; +} +``` + +## Complexity Analysis + +- Time Complexity: $O(m \times n)$, where m is the length of the text and n is the length of the pattern. +- Space Complexity: $O(m \times n)$, for storing the DP table. + +## Conclusion + +Dynamic programming provides an efficient solution for Wildcards Matching by breaking it into subproblems and storing intermediate results. This technique can be extended to solve other pattern matching problems with overlapping subproblems and optimal substructure properties. \ No newline at end of file diff --git a/docs/Algorithms/Dynamic Programming/13-Palindrome-Partitioning.md b/docs/Algorithms/Dynamic Programming/13-Palindrome-Partitioning.md new file mode 100644 index 0000000..b0a2059 --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/13-Palindrome-Partitioning.md @@ -0,0 +1,155 @@ +--- +id: palindrome-partitioning +title: Palindrome Partitioning +sidebar_label: Palindrome Partitioning +tags: [python, java, c++, programming, algorithms, dynamic programming, strings, tutorial, in-depth] +description: In this tutorial, we will learn about the Palindrome Partitioning problem and its solution using Dynamic Programming in Python, Java, and C++ with detailed explanations and examples. +--- + +# Palindrome Partitioning + +The Palindrome Partitioning problem involves partitioning a given string such that every substring of the partition is a palindrome. We aim to find the minimum number of cuts needed for a palindrome partitioning of the string. + +## Problem Statement + +Given a string `s`, partition `s` such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of `s`. + +### Intuition + +To solve this problem, we use dynamic programming. We maintain an array `dp` where `dp[i]` represents the minimum number of cuts needed for a palindrome partitioning of the substring `s[0:i+1]`. + +## Dynamic Programming Approach + +We use a 2D boolean array `isPalindrome` to keep track of whether a substring `s[i:j+1]` is a palindrome. Then we build the `dp` array using the `isPalindrome` array. + +## Pseudocode for Palindrome Partitioning using DP + +#### Initialize: + +```markdown +dp = [0] * len(s) +for i in range(len(s)): + min_cut = i + for j in range(i + 1): + if s[j:i+1] is a palindrome: + min_cut = 0 if j == 0 else min(min_cut, dp[j-1] + 1) + dp[i] = min_cut +return dp[-1] +``` + +### Example Output: + +Given the string: + +- `s = "aab"` + +The minimum cuts needed for a palindrome partitioning is `1`. + +### Output Explanation: + +We can partition the string as `"aa" | "b"`, which requires `1` cut. + +## Implementing Palindrome Partitioning using DP + +### Python Implementation + +```python +class Solution: + def minCut(self, s: str) -> int: + n = len(s) + dp = [0] * n + is_palindrome = [[False] * n for _ in range(n)] + + for i in range(n): + min_cut = i + for j in range(i + 1): + if s[j] == s[i] and (i - j <= 2 or is_palindrome[j + 1][i - 1]): + is_palindrome[j][i] = True + min_cut = 0 if j == 0 else min(min_cut, dp[j - 1] + 1) + dp[i] = min_cut + + return dp[-1] + +s = "aab" +solution = Solution() +print(solution.minCut(s)) # Output: 1 +``` + +### Java Implementation + +```java +class Solution { + public int minCut(String s) { + int n = s.length(); + int[] dp = new int[n]; + boolean[][] isPalindrome = new boolean[n][n]; + + for (int i = 0; i < n; i++) { + int minCut = i; + for (int j = 0; j <= i; j++) { + if (s.charAt(j) == s.charAt(i) && (i - j <= 2 || isPalindrome[j + 1][i - 1])) { + isPalindrome[j][i] = true; + minCut = j == 0 ? 0 : Math.min(minCut, dp[j - 1] + 1); + } + } + dp[i] = minCut; + } + + return dp[n - 1]; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + String s = "aab"; + System.out.println(solution.minCut(s)); // Output: 1 + } +} +``` +### C++ Implementation + +```cpp +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + int minCut(string s) { + int n = s.length(); + vector dp(n, 0); + vector> isPalindrome(n, vector(n, false)); + + for (int i = 0; i < n; i++) { + int minCut = i; + for (int j = 0; j <= i; j++) { + if (s[j] == s[i] && (i - j <= 2 || isPalindrome[j + 1][i - 1])) { + isPalindrome[j][i] = true; + minCut = j == 0 ? 0 : min(minCut, dp[j - 1] + 1); + } + } + dp[i] = minCut; + } + + return dp[n - 1]; + } +}; + +int main() { + Solution solution; + string s = "aab"; + cout << solution.minCut(s) << endl; // Output: 1 + return 0; +} +``` + +## Complexity Analysis + +- Time Complexity: $O(n^2)$, where n is the length of the string. +- Space Complexity: $O(n^2)$, for storing the isPalindrome array. + +## Conclusion + +The Palindrome Partitioning problem can be efficiently solved using dynamic programming. The provided implementations in Python, Java, and C++ demonstrate how to find the minimum cuts needed for a palindrome partitioning of a given string. \ No newline at end of file diff --git a/docs/Algorithms/Dynamic Programming/14-Travelling-Sales-Person.md b/docs/Algorithms/Dynamic Programming/14-Travelling-Sales-Person.md new file mode 100644 index 0000000..456d373 --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/14-Travelling-Sales-Person.md @@ -0,0 +1,336 @@ +--- +id: travelling-sales-person +title: Travelling Sales Person Algorithm +sidebar_label: Travelling Sales Person Algorithm +tags: [python, java, c++, programming, algorithms, dynamic programming, graph, tutorial, in-depth] +description: In this tutorial, we will learn about the Travelling Sales Person Algorithm and its solution using Dynamic Programming in Python, Java, and C++ with detailed explanations and examples. +--- + +# Travelling Sales Person Algorithm + +Given a set of cities and the distance between every pair of cities, the problem is to find the shortest possible route that visits every city exactly once and returns to the starting point. Note the difference between Hamiltonian Cycle and TSP. The Hamiltonian cycle problem is to find if there exists a tour that visits every city exactly once. Here we know that Hamiltonian Tour exists (because the graph is complete) and in fact, many such tours exist, the problem is to find a minimum weight Hamiltonian Cycle. + +## Problem Statement + +For example, consider the graph shown in the figure. A TSP tour in the graph is 1-2-4-3-1. The cost of the tour is 10+25+30+15 which is 80. The problem is a famous NP-hard problem. There is no polynomial-time know solution for this problem. The following are different solutions for the traveling salesman problem. + +![Example](../../../assets/tsp.png) + +### Intuition + +1) Consider city 1 as the starting and ending point. + +2) Generate all (n-1)! Permutations of cities. + +3) Calculate the cost of every permutation and keep track of the minimum cost permutation. + +4) Return the permutation with minimum cost. + +Time Complexity: T(n!) + +## Dynamic Programming Approach + +Let the given set of vertices be 1, 2, 3, 4,….n. Let us consider 1 as starting and ending point of output. For every other vertex I (other than 1), we find the minimum cost path with 1 as the starting point, I as the ending point, and all vertices appearing exactly once. Let the cost of this path cost (i), and the cost of the corresponding Cycle would cost (i) + dist(i, 1) where dist(i, 1) is the distance from I to 1. Finally, we return the minimum of all [cost(i) + dist(i, 1)] values. This looks simple so far. + +Now the question is how to get cost(i)? To calculate the cost(i) using Dynamic Programming, we need to have some recursive relation in terms of sub-problems. + +Let us define a term C(S, i) be the cost of the minimum cost path visiting each vertex in set S exactly once, starting at 1 and ending at i. We start with all subsets of size 2 and calculate C(S, i) for all subsets where S is the subset, then we calculate C(S, i) for all subsets S of size 3 and so on. Note that 1 must be present in every subset. +``` +If size of S is 2, then S must be {1, i}, + C(S, i) = dist(1, i) +Else if size of S is greater than 2. + C(S, i) = min { C(S-{i}, j) + dis(j, i)} where j belongs to S, j != i and j != 1. +``` + +## Code for Travelling Sales Person Algorithm using DP + + + + + ``` Python showLineNumbers +n = 4 # there are four nodes in example graph (graph is 1-based) + +# dist[i][j] represents shortest distance to go from i to j +# this matrix can be calculated for any given graph using +# all-pair shortest path algorithms +dist = [[0, 0, 0, 0, 0], [0, 0, 10, 15, 20], [ + 0, 10, 0, 25, 25], [0, 15, 25, 0, 30], [0, 20, 25, 30, 0]] + +# memoization for top down recursion +memo = [[-1]*(1 << (n+1)) for _ in range(n+1)] + + +def fun(i, mask): + # base case + # if only ith bit and 1st bit is set in our mask, + # it implies we have visited all other nodes already + if mask == ((1 << i) | 3): + return dist[1][i] + + # memoization + if memo[i][mask] != -1: + return memo[i][mask] + + res = 10**9 # result of this sub-problem + + # we have to travel all nodes j in mask and end the path at ith node + # so for every node j in mask, recursively calculate cost of + # travelling all nodes in mask + # except i and then travel back from node j to node i taking + # the shortest path take the minimum of all possible j nodes + for j in range(1, n+1): + if (mask & (1 << j)) != 0 and j != i and j != 1: + res = min(res, fun(j, mask & (~(1 << i))) + dist[j][i]) + memo[i][mask] = res # storing the minimum value + return res + + +# Driver program to test above logic +ans = 10**9 +for i in range(1, n+1): + # try to go from node 1 visiting all nodes in between to i + # then return from i taking the shortest route to 1 + ans = min(ans, fun(i, (1 << (n+1))-1) + dist[i][1]) + +print("The cost of most efficient tour = " + str(ans)) + + +``` + + + + +``` jsx showLineNumbers +import java.io.*; +import java.util.*; + +public class TSE { + // there are four nodes in example graph (graph is + // 1-based) + + static int n = 4; + // give appropriate maximum to avoid overflow + + static int MAX = 1000000; + + // dist[i][j] represents shortest distance to go from i + // to j this matrix can be calculated for any given + // graph using all-pair shortest path algorithms + static int[][] dist = { + { 0, 0, 0, 0, 0 }, { 0, 0, 10, 15, 20 }, + { 0, 10, 0, 25, 25 }, { 0, 15, 25, 0, 30 }, + { 0, 20, 25, 30, 0 }, + }; + + // memoization for top down recursion + + static int[][] memo = new int[n + 1][1 << (n + 1)]; + + static int fun(int i, int mask) + { + // base case + // if only ith bit and 1st bit is set in our mask, + // it implies we have visited all other nodes + // already + if (mask == ((1 << i) | 3)) + return dist[1][i]; + // memoization + if (memo[i][mask] != 0) + return memo[i][mask]; + + int res = MAX; // result of this sub-problem + + // we have to travel all nodes j in mask and end the + // path at ith node so for every node j in mask, + // recursively calculate cost of travelling all + // nodes in mask + // except i and then travel back from node j to node + // i taking the shortest path take the minimum of + // all possible j nodes + + for (int j = 1; j <= n; j++) + if ((mask & (1 << j)) != 0 && j != i && j != 1) + res = Math.min(res, + fun(j, mask & (~(1 << i))) + + dist[j][i]); + return memo[i][mask] = res; + } + + // Driver program to test above logic + public static void main(String[] args) + { + int ans = MAX; + for (int i = 1; i <= n; i++) + // try to go from node 1 visiting all nodes in + // between to i then return from i taking the + // shortest route to 1 + ans = Math.min(ans, fun(i, (1 << (n + 1)) - 1) + + dist[i][1]); + + System.out.println( + "The cost of most efficient tour = " + ans); + } +} + + +``` + + + +```cpp showLineNumbers +#include + +using namespace std; + +// there are four nodes in example graph (graph is 1-based) +const int n = 4; +// give appropriate maximum to avoid overflow +const int MAX = 1000000; + +// dist[i][j] represents shortest distance to go from i to j +// this matrix can be calculated for any given graph using +// all-pair shortest path algorithms +int dist[n + 1][n + 1] = { + { 0, 0, 0, 0, 0 }, { 0, 0, 10, 15, 20 }, + { 0, 10, 0, 25, 25 }, { 0, 15, 25, 0, 30 }, + { 0, 20, 25, 30, 0 }, +}; + +// memoization for top down recursion +int memo[n + 1][1 << (n + 1)]; + +int fun(int i, int mask) +{ + // base case + // if only ith bit and 1st bit is set in our mask, + // it implies we have visited all other nodes already + if (mask == ((1 << i) | 3)) + return dist[1][i]; + // memoization + if (memo[i][mask] != 0) + return memo[i][mask]; + + int res = MAX; // result of this sub-problem + + // we have to travel all nodes j in mask and end the + // path at ith node so for every node j in mask, + // recursively calculate cost of travelling all nodes in + // mask except i and then travel back from node j to + // node i taking the shortest path take the minimum of + // all possible j nodes + + for (int j = 1; j <= n; j++) + if ((mask & (1 << j)) && j != i && j != 1) + res = std::min(res, fun(j, mask & (~(1 << i))) + + dist[j][i]); + return memo[i][mask] = res; +} +// Driver program to test above logic +int main() +{ + int ans = MAX; + for (int i = 1; i <= n; i++) + // try to go from node 1 visiting all nodes in + // between to i then return from i taking the + // shortest route to 1 + ans = std::min(ans, fun(i, (1 << (n + 1)) - 1) + + dist[i][1]); + + printf("The cost of most efficient tour = %d", ans); + + return 0; +} + + +``` + + + +```jsx showLineNumbers +// JavaScript code for the above approach + +// there are four nodes in example graph (graph is 1-based) +let n = 4; + +// give appropriate maximum to avoid overflow +let MAX = 1000000; + +// dist[i][j] represents shortest distance to go from i to j +// this matrix can be calculated for any given graph using +// all-pair shortest path algorithms +let dist = [ + [0, 0, 0, 0, 0], [0, 0, 10, 15, 20], + [0, 10, 0, 25, 25], [0, 15, 25, 0, 30], + [0, 20, 25, 30, 0], +]; + +// memoization for top down recursion +let memo = new Array(n + 1); + +for (let i = 0; i < memo.length; i++) { + memo[i] = new Array(1 << (n + 1)).fill(0) +} + +function fun(i, mask) +{ + + // base case + // if only ith bit and 1st bit is set in our mask, + // it implies we have visited all other nodes already + if (mask == ((1 << i) | 3)) + return dist[1][i]; + + // memoization + if (memo[i][mask] != 0) + return memo[i][mask]; + + let res = MAX; // result of this sub-problem + + // we have to travel all nodes j in mask and end the + // path at ith node so for every node j in mask, + // recursively calculate cost of travelling all nodes in + // mask except i and then travel back from node j to + // node i taking the shortest path take the minimum of + // all possible j nodes + + for (let j = 1; j <= n; j++) + if ((mask & (1 << j)) && j != i && j != 1) + res = Math.min(res, fun(j, mask & (~(1 << i))) + + dist[j][i]); + return memo[i][mask] = res; +} + +// Driver program to test above logic +let ans = MAX; +for (let i = 1; i <= n; i++) + + // try to go from node 1 visiting all nodes in + // between to i then return from i taking the + // shortest route to 1 + ans = Math.min(ans, fun(i, (1 << (n + 1)) - 1) + + dist[i][1]); + +console.log("The cost of most efficient tour " + ans); + +``` + + + + +## Output + +``` +The cost of most efficient tour = 80 +``` + +## Time Complexity : + +O(n2*2n) where O(n* 2n) are maximum number of unique subproblems/states and O(n) for transition (through for loop as in code) in every states. + +## Auxiliary Space: + +O(n*2n), where n is number of Nodes/Cities here. + +## Conclusion + +For a set of size n, we consider n-2 subsets each of size n-1 such that all subsets don’t have nth in them. Using the above recurrence relation, we can write a dynamic programming-based solution. There are at most O(n*2n) subproblems, and each one takes linear time to solve. The total running time is therefore O(n2*2n). The time complexity is much less than O(n!) but still exponential. The space required is also exponential. So this approach is also infeasible even for a slightly higher number of vertices. We will soon be discussing approximate algorithms for the traveling salesman problem. \ No newline at end of file diff --git a/docs/Algorithms/Dynamic Programming/15-Z-Algorithm.md b/docs/Algorithms/Dynamic Programming/15-Z-Algorithm.md new file mode 100644 index 0000000..7fcf604 --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/15-Z-Algorithm.md @@ -0,0 +1,172 @@ +--- +id: z-algorithm +title: Z-Algorithm +sidebar_label: Z-Algorithm +tags: [python, java, c++, programming, algorithms, dynamic programming, tutorial, in-depth] +description: In this tutorial, we will learn about the Z-Algorithm and its implementation in Python, Java, and C++ with detailed explanations and examples. +--- + +# Z-Algorithm + +The Z-Algorithm is a linear time algorithm used for pattern matching within a string. It is commonly used to compute the Z-array, which provides information about the occurrences of a substring within a string. The Z-array for a string `S` is an array where the `i-th` position represents the length of the longest substring starting from `S[i]` that matches a prefix of `S`. + +## Problem Statement + +Given a string `S` of length `n`, the Z-array of `S` is an array `Z` of length `n` where `Z[i]` is the length of the longest substring starting from `S[i]` which is also a prefix of `S`. + +## Example + +For the string `S = "aabcaabxaaaz"`, the Z-array would be `[0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 0]`. + +## Algorithm + +1. Initialize `L` and `R` to 0. These will define the interval `[L, R]` which is the rightmost segment of `S` that matches the prefix of `S`. +2. Iterate over each character in the string and compute the Z-values based on the interval `[L, R]`. +3. If the current index `i` is outside of `[L, R]`, calculate the Z-value directly. +4. If `i` is within `[L, R]`, use previously computed Z-values to determine the Z-value at `i`. + +## Code for Z-Algorithm + +## Z-Algorithm + +The Z-Algorithm is used for string pattern matching and finding the Z-array, which represents the lengths of the longest substrings starting from each position in a string that match the prefix of the string. + +### Python Implementation + +```python +def compute_z(s): + n = len(s) + z = [0] * n + l, r, k = 0, 0, 0 + for i in range(1, n): + if i > r: + l, r = i, i + while r < n and s[r] == s[r - l]: + r += 1 + z[i] = r - l + r -= 1 + else: + k = i - l + if z[k] < r - i + 1: + z[i] = z[k] + else: + l = i + while r < n and s[r] == s[r - l]: + r += 1 + z[i] = r - l + r -= 1 + return z +s = "aabcaabxaaaz" +print("Z-array:", compute_z(s)) +``` + +### Java Implementation + +```java +public class ZAlgorithm { + public static int[] computeZ(String s) { + int n = s.length(); + int[] z = new int[n]; + int l = 0, r = 0, k; + for (int i = 1; i < n; i++) { + if (i > r) { + l = r = i; + while (r < n && s.charAt(r) == s.charAt(r - l)) { + r++; + } + z[i] = r - l; + r--; + } else { + k = i - l; + if (z[k] < r - i + 1) { + z[i] = z[k]; + } else { + l = i; + while (r < n && s.charAt(r) == s.charAt(r - l)) { + r++; + } + z[i] = r - l; + r--; + } + } + } + return z; + } + + public static void main(String[] args) { + String s = "aabcaabxaaaz"; + int[] z = computeZ(s); + System.out.print("Z-array: "); + for (int value : z) { + System.out.print(value + " "); + } + } +} +``` + +### Cpp Implementation + +```cpp +#include +#include +#include + +using namespace std; + +vector computeZ(const string& s) { + int n = s.length(); + vector z(n, 0); + int l = 0, r = 0, k; + for (int i = 1; i < n; i++) { + if (i > r) { + l = r = i; + while (r < n && s[r] == s[r - l]) { + r++; + } + z[i] = r - l; + r--; + } else { + k = i - l; + if (z[k] < r - i + 1) { + z[i] = z[k]; + } else { + l = i; + while (r < n && s[r] == s[r - l]) { + r++; + } + z[i] = r - l; + r--; + } + } + } + return z; +} + +int main() { + string s = "aabcaabxaaaz"; + vector z = computeZ(s); + cout << "Z-array: "; + for (int value : z) { + cout << value << " "; + } + cout << endl; + return 0; +} +``` + +## Output + +`Z-array: 0 1 0 3 0 1 0 2 0 1 0 0` + + +## Time Complexity + +The Z-Algorithm runs in $O(n)$ time complexity where `n` is the length of the string. This is due to the linear scan of the string and the efficient handling of previously computed Z-values. + +## Space Complexity + +The space complexity is $O(n)$ for storing the Z-array. + +## Conclusion + +The Z-Algorithm is an efficient method for pattern matching and string analysis, providing the Z-array in linear time. This algorithm is widely used in various applications such as substring search and pattern matching. diff --git a/docs/Algorithms/Dynamic Programming/16-Word-Break.md b/docs/Algorithms/Dynamic Programming/16-Word-Break.md new file mode 100644 index 0000000..653b9bd --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/16-Word-Break.md @@ -0,0 +1,124 @@ +--- +id: word-break-problem +title: Word Break Problem +sidebar_label: Word Break Problem +tags: [python, java, c++, programming, algorithms, dynamic programming, tutorial, in-depth] +description: In this tutorial, we will learn about the Word Break Problem and its implementation in Python, Java, and C++ with detailed explanations and examples. +--- + +# Word Break Problem + +The Word Break Problem is a dynamic programming problem that involves determining if a given string can be segmented into a space-separated sequence of one or more dictionary words. It is commonly used in natural language processing and text analysis. + +## Problem Statement + +Given a string `s` and a dictionary of words `dict`, determine if `s` can be segmented into a space-separated sequence of one or more dictionary words. + +## Example + +For the string `s = "leetcode"` and dictionary `dict = ["leet", "code"]`, the output would be `True` because the string can be segmented into "leet code". + +## Algorithm + +1. Initialize a boolean array `dp` of length `n+1` where `n` is the length of the string `s`. The array `dp[i]` will be `True` if the substring `s[0:i]` can be segmented. +2. Set `dp[0]` to `True` because an empty string can always be segmented. +3. Iterate over the string `s` and update the `dp` array based on whether the substring ending at the current position can be segmented. + +## Code for Word Break Problem + +### Python Implementation + +```python +def word_break(s, word_dict): + n = len(s) + dp = [False] * (n + 1) + dp[0] = True + for i in range(1, n + 1): + for j in range(i): + if dp[j] and s[j:i] in word_dict: + dp[i] = True + break + return dp[n] + +s = "leetcode" +word_dict = {"leet", "code"} +print("Can the string be segmented:", word_break(s, word_dict)) +``` + +### Java Implementation + +```java +import java.util.*; +public class WordBreak { + public static boolean wordBreak(String s, Set wordDict) { + int n = s.length(); + boolean[] dp = new boolean[n + 1]; + dp[0] = true; + for (int i = 1; i <= n; i++) { + for (int j = 0; j < i; j++) { + if (dp[j] && wordDict.contains(s.substring(j, i))) { + dp[i] = true; + break; + } + } + } + return dp[n]; + } + + public static void main(String[] args) { + String s = "leetcode"; + Set wordDict = new HashSet<>(Arrays.asList("leet", "code")); + System.out.println("Can the string be segmented: " + wordBreak(s, wordDict)); + } +} +``` + +### Cpp Implementation + +```cpp +#include +#include +#include +#include + +using namespace std; + +bool wordBreak(const string& s, const unordered_set& wordDict) { + int n = s.length(); + vector dp(n + 1, false); + dp[0] = true; + for (int i = 1; i <= n; i++) { + for (int j = 0; j < i; j++) { + if (dp[j] && wordDict.find(s.substr(j, i - j)) != wordDict.end()) { + dp[i] = true; + break; + } + } + } + return dp[n]; +} + +int main() { + string s = "leetcode"; + unordered_set wordDict = {"leet", "code"}; + cout << "Can the string be segmented: " << (wordBreak(s, wordDict) ? "True" : "False") << endl; + return 0; +} +``` + +## Output + +`Can the string be segmented: True` + + +## Time Complexity + +The time complexity of the Word Break Problem is $O(n^2 * k)$ where n is the length of the string and k is the average length of the words in the dictionary. This is due to the nested loops and substring checks. + +## Space Complexity + +The space complexity is $O(n)$ for storing the boolean array dp. + +## Conclusion + +The Word Break Problem is a classic dynamic programming problem that demonstrates the power of dynamic programming in solving string segmentation and text analysis problems. This algorithm efficiently determines if a string can be segmented into dictionary words. \ No newline at end of file diff --git a/docs/Algorithms/Dynamic Programming/_category_.json b/docs/Algorithms/Dynamic Programming/_category_.json new file mode 100644 index 0000000..7eaf597 --- /dev/null +++ b/docs/Algorithms/Dynamic Programming/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Dynamic Programming Algorithms", + "position": 11, + "link": { + "type": "generated-index", + "description": "You can find the most useful Dynamic Programming Algorithms in this section" + } + } \ No newline at end of file diff --git a/docs/Algorithms/Graph Algorithms/01-Dijkstra's Algorithm.md b/docs/Algorithms/Graph Algorithms/01-Dijkstra's Algorithm.md new file mode 100644 index 0000000..1e94aef --- /dev/null +++ b/docs/Algorithms/Graph Algorithms/01-Dijkstra's Algorithm.md @@ -0,0 +1,324 @@ +--- +id: dijkstras-algorithm +title: Dijkstra's Algorithm +sidebar_label: 01 - Dijkstra's Algorithm +tags: + - Graph Algorithms + - Shortest Path + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains Dijkstra's Algorithm for finding the shortest path in a graph, with code implementations and resources for further learning." +--- + +# Dijkstra's Algorithm + +## 1. What is Dijkstra's Algorithm? + +Dijkstra's Algorithm is a famous algorithm used for finding the shortest paths between nodes in a graph. It is widely used in routing and navigation systems. The algorithm works on both directed and undirected graphs with non-negative edge weights. + +Dijkstra’s algorithm is a popular algorithms for solving many single-source shortest path problems having non-negative edge weight in the graphs i.e., it is to find the shortest distance between two vertices on a graph. It was conceived by Dutch computer scientist Edsger W. Dijkstra in 1956. + +## 2. Algorithm for Dijkstra's Algorithm + +1. Initialize the distance to the start node as 0 and to all other nodes as infinity. +2. Push the start node into a priority queue (min-heap) with distance 0. +3. While the priority queue is not empty: + - Pop the node with the smallest distance from the queue. + - For each adjacent node, calculate the distance to it through the current node. + - If this distance is less than the known distance, update the shortest distance and push the node into the queue. +4. Continue the process until all nodes have been processed. + +## 3. How Does Dijkstra's Algorithm Work? + +1. Start with the initial node, setting its distance to 0 and all others to infinity. +2. Use a priority queue to explore the nearest unvisited node. +3. Update the distances to all adjacent nodes, pushing nodes with updated distances into the queue. +4. Repeat until all nodes are processed, ensuring the shortest paths from the start node to all other nodes. + +**Consider the below graph:** +![Example from GFG](https://media.geeksforgeeks.org/wp-content/uploads/20230303115424/d1-(1).png) + +**Step 1**: Start from Node 0 and mark Node as visited as you can check in below image visited Node is marked red. + +![Example from GFG](https://media.geeksforgeeks.org/wp-content/uploads/20230303124731/d2-(1).png) + +**Step 2**: Check for adjacent Nodes, Now we have to choices (Either choose Node1 with distance 2 or either choose Node 2 with distance 6 ) and choose Node with minimum distance. In this step Node 1 is Minimum distance adjacent Node, so marked it as visited and add up the distance. + +Distance: Node 0 -> Node 1 = 2 +![Example from GFG](https://media.geeksforgeeks.org/wp-content/uploads/20230303125338/d3-(1).png) + +**Step 3**: Then Move Forward and check for adjacent Node which is Node 3, so marked it as visited and add up the distance, Now the distance will be: + +Distance: Node 0 -> Node 1 -> Node 3 = 2 + 5 = 7 +![Example from GFG](https://media.geeksforgeeks.org/wp-content/uploads/20240102151831/Dijkstra-Algorithm--step-3-768.jpg) + +**Step 4**: Again we have two choices for adjacent Nodes (Either we can choose Node 4 with distance 10 or either we can choose Node 5 with distance 15) so choose Node with minimum distance. In this step Node 4 is Minimum distance adjacent Node, so marked it as visited and add up the distance. + +Distance: Node 0 -> Node 1 -> Node 3 -> Node 4 = 2 + 5 + 10 = 17 +![Example from GFG](https://media.geeksforgeeks.org/wp-content/uploads/20230303133722/d5-(1).png) + +**Step 5**: Again, Move Forward and check for adjacent Node which is Node 6, so marked it as visited and add up the distance, Now the distance will be: + +Distance: Node 0 -> Node 1 -> Node 3 -> Node 4 -> Node 6 = 2 + 5 + 10 + 2 = 19 +![Example from GFG](https://media.geeksforgeeks.org/wp-content/uploads/20230303134335/d6.png) +So, the Shortest Distance from the Source Vertex is 19 which is optimal one + +## 4. Problem Description + +Given a graph with vertices and weighted edges, find the shortest path from a starting vertex to all other vertices. + +## 5. Examples + +### Example 1: + +``` +Input: +Graph: {A: [(B, 1), (C, 4)], B: [(A, 1), (C, 2), (D, 5)], C: [(A, 4), (B, 2), (D, 1)], D: [(B, 5), (C, 1)]} +Start node: A + +Output: +Shortest distances: {A: 0, B: 1, C: 3, D: 4} +``` + +### Example 2: + +``` +Input: +Graph: {1: [(2, 2), (3, 4)], 2: [(1, 2), (3, 1)], 3: [(1, 4), (2, 1)]} +Start node: 1 + +Output: +Shortest distances: {1: 0, 2: 2, 3: 3} +``` + +## 6. Constraints + +- The graph must have non-negative edge weights. +- The graph can be directed or undirected. + +## 7. Implementation + +### Python + +```python +import heapq + +def dijkstra(graph, start): + pq = [(0, start)] + distances = {vertex: float('infinity') for vertex in graph} + distances[start] = 0 + + while pq: + current_distance, current_vertex = heapq.heappop(pq) + + if current_distance > distances[current_vertex]: + continue + + for neighbor, weight in graph[current_vertex]: + distance = current_distance + weight + + if distance < distances[neighbor]: + distances[neighbor] = distance + heapq.heappush(pq, (distance, neighbor)) + + return distances +``` + +### C++ + +```cpp +#include +#include +#include +#include +#include +using namespace std; + +typedef pair pii; + +unordered_map dijkstra(unordered_map>& graph, int start) { + priority_queue, greater> pq; + unordered_map distances; + + for (auto& node : graph) { + distances[node.first] = INT_MAX; + } + + distances[start] = 0; + pq.push({0, start}); + + while (!pq.empty()) { + int current_distance = pq.top().first; + int current_vertex = pq.top().second; + pq.pop(); + + if (current_distance > distances[current_vertex]) continue; + + for (auto& neighbor : graph[current_vertex]) { + int weight = neighbor.second; + int next_vertex = neighbor.first; + int distance = current_distance + weight; + + if (distance < distances[next_vertex]) { + distances[next_vertex] = distance; + pq.push({distance, next_vertex}); + } + } + } + + return distances; +} + +void shortDijkstra(int src, int n, vector>& adjList) { + vector dist(n, INT_MAX); + set st; + + dist[src] = 0; + st.insert({0, src}); + + while (!st.empty()) { + auto mini = *st.begin(); + + int nodedistance = mini.first; + int node = mini.second; + + st.erase(st.begin()); + + for (auto nbr : adjList[node]) { + int dis = nodedistance + nbr.second; + if (dis < dist[nbr.first]) { + auto result = st.find(make_pair(dist[nbr.first], nbr.first)); + if (result != st.end()) { + st.erase(result); + } + dist[nbr.first] = dis; + st.insert(make_pair(dist[nbr.first], nbr.first)); + } + } + } + cout << "Printing ans" << endl; + for (auto i : dist) { + cout << i << " "; + } +} + +``` + +### Java + +```java +import java.util.*; + +class Graph { + private Map> graph = new HashMap<>(); + + public void addEdge(int source, int destination, int weight) { + graph.computeIfAbsent(source, k -> new ArrayList<>()).add(new int[]{destination, weight}); + graph.computeIfAbsent(destination, k -> new ArrayList<>()).add(new int[]{source, weight}); + } + + public Map dijkstra(int start) { + PriorityQueue pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1])); + Map distances = new HashMap<>(); + for (int node : graph.keySet()) distances.put(node, Integer.MAX_VALUE); + + distances.put(start, 0); + pq.add(new int[]{start, 0}); + + while (!pq.isEmpty()) { + int[] current = pq.poll(); + int currentNode = current[0]; + int currentDistance = current[1]; + + if (currentDistance > distances.get(currentNode)) continue; + + for (int[] neighbor : graph.get(currentNode)) { + int nextNode = neighbor[0]; + int weight = neighbor[1]; + int distance = currentDistance + weight; + + if (distance < distances.get(nextNode)) { + distances.put(nextNode, distance); + pq.add(new int[]{nextNode, distance}); + } + } + } + + return distances; + } +} +``` + +### JavaScript + +```javascript +class PriorityQueue { + constructor() { + this.values = []; + } + enqueue(val, priority) { + this.values.push({val, priority}); + this.sort(); + } + dequeue() { + return this.values.shift(); + } + sort() { + this.values.sort((a, b) => a.priority - b.priority); + } +} + +function dijkstra(graph, start) { + const pq = new PriorityQueue(); + const distances = {}; + for (let vertex in graph) { + distances[vertex] = Infinity; + } + distances[start] = 0; + pq.enqueue(start, 0); + + while (pq.values.length) { + let {val: currentVertex, priority: currentDistance} = pq.dequeue(); + + if (currentDistance > distances[currentVertex]) continue; + + for (let [neighbor, weight] of graph[currentVertex]) { + let distance = currentDistance + weight; + + if (distance < distances[neighbor]) { + distances[neighbor] = distance; + pq.enqueue(neighbor, distance); + } + } + } + + return distances; +} +``` + +## 8. Complexity Analysis + +- **Time Complexity:** $O(E log V)$, where $E$ is the number of edges and $V$ is the number of vertices. This is due to the priority queue operations. +- **Space Complexity:** $O(V)$, for storing distances and the priority queue. + +## 9. Advantages and Disadvantages + +### Advantages: +- Efficient for graphs with non-negative weights. +- Provides the shortest path from a single source to all other vertices. + +### Disadvantages: +- Cannot handle graphs with negative weight edges. +- More complex to implement compared to simpler algorithms like BFS for unweighted graphs. + +## 10. Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/dijkstrashortreach/problem) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) +- **Video Explanation:** + - [Dijkstra's Algorithm | GeeksforGeeks](https://www.youtube.com/watch?v=V6H1UChTtA4) + - [Shortest Path Algorithms | Computer Science](https://www.youtube.com/watch?v=pVfj6mxhdMw) \ No newline at end of file diff --git a/docs/Algorithms/Graph Algorithms/02-Bellman-Ford.md b/docs/Algorithms/Graph Algorithms/02-Bellman-Ford.md new file mode 100644 index 0000000..5c33779 --- /dev/null +++ b/docs/Algorithms/Graph Algorithms/02-Bellman-Ford.md @@ -0,0 +1,211 @@ +--- +id: bellman-ford-algorithm +title: Bellman-Ford Algorithm +sidebar_label: 02 - Bellman-Ford Algorithm +tags: + - Graph Algorithms + - Shortest Path + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains the Bellman-Ford Algorithm for finding the shortest path in a graph with negative weight edges." +--- + +# Bellman-Ford Algorithm + +## 1. What is the Bellman-Ford Algorithm? + +The Bellman-Ford Algorithm is used to find the shortest paths from a single source vertex to all other vertices in a weighted graph, even in the presence of negative weight edges. It can detect negative weight cycles in a graph. + +## 2. Algorithm for Bellman-Ford Algorithm + +1. Initialize the distances to all vertices as infinity, except the source vertex, which is 0. +2. Relax all edges $|V| - 1$ times, where $|V|$ is the number of vertices. +3. Repeat one more time to detect negative weight cycles. If a shorter path is found, then a negative weight cycle exists. + +## 3. How Does Bellman-Ford Algorithm Work? + +1. Start with the source vertex and initialize the distances to all other vertices as infinity. +2. Relax all edges $|V| - 1$ times, where $|V|$ is the number of vertices. Relaxation means updating the distance if a shorter path is found. +3. Repeat the process one more time. If a shorter path is found during this additional relaxation step, then a negative weight cycle exists. + +## 4. Problem Description + +Given a weighted graph and a source vertex, the Bellman-Ford Algorithm aims to find the shortest paths from the source vertex to all other vertices in the graph. + +## 5. Examples + +Example graph: +``` + 0 1 2 3 + -------------------- + 0 | 0 4 0 0 + 1 | 0 0 -1 0 + 2 | 0 0 0 2 + 3 | 0 3 0 0 +``` + +Starting from vertex 0, we want to find the shortest paths to all other vertices. + +## 6. Constraints + +- The graph can have negative weight edges. +- The graph may not contain any negative weight cycles reachable from the source vertex. + +## 7. Implementation + + + + ```python + def bellman_ford(graph, start): + vertices = list(graph.keys()) + distances = {v: float('inf') for v in vertices} + distances[start] = 0 + + for _ in range(len(vertices) - 1): + for u in vertices: + for v, weight in graph[u]: + if distances[u] != float('inf') and distances[u] + weight < distances[v]: + distances[v] = distances[u] + weight + + for u in vertices: + for v, weight in graph[u]: + if distances[u] != float('inf') and distances[u] + weight < distances[v]: + print("Graph contains negative weight cycle") + return + + return distances + ``` + + + + ```cpp + #include + #include + #include + using namespace std; + + typedef pair pii; + + vector bellmanFord(vector>& graph, int start) { + int V = graph.size(); + vector dist(V, numeric_limits::max()); + dist[start] = 0; + + for (int i = 0; i < V - 1; ++i) { + for (int u = 0; u < V; ++u) { + for (auto& [v, weight] : graph[u]) { + if (dist[u] != numeric_limits::max() && dist[u] + weight < dist[v]) { + dist[v] = dist[u] + weight; + } + } + } + } + + for (int u = 0; u < V; ++u) { + for (auto& [v, weight] : graph[u]) { + if (dist[u] != numeric_limits::max() && dist[u] + weight < dist[v]) { + cout << "Graph contains negative weight cycle\n"; + return {}; + } + } + } + + return dist; + } + ``` + + + + ```java + import java.util.*; + + class BellmanFord { + public static int[] bellmanFord(List> graph, int start) { + int V = graph.size(); + int[] dist = new int[V]; + Arrays.fill(dist, Integer.MAX_VALUE); + dist[start] = 0; + + for (int i = 0; i < V - 1; ++i) { + for (int u = 0; u < V; ++u) { + for (int[] edge : graph.get(u)) { + int v = edge[0]; + int weight = edge[1]; + if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) { + dist[v] = dist[u] + weight; + } + } + } + } + + for (int u = 0; u < V; ++u) { + for (int[] edge : graph.get(u)) { + int v = edge[0]; + int weight = edge[1]; + if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) { + System.out.println("Graph contains negative weight cycle"); + return new int[]{}; + } + } + } + + return dist; + } + } + ``` + + + + ```javascript + function bellmanFord(graph, start) { + const vertices = Object.keys(graph); + const distances = {}; + vertices.forEach(vertex => distances[vertex] = Infinity); + distances[start] = 0; + + for (let i = 0; i < vertices.length - 1; i++) { + for (let u of vertices) { + for (let [v, weight] of graph[u]) { + if (distances[u] !== Infinity && distances[u] + weight < distances[v]) { + distances[v] = distances[u] + weight; + } + } + } + } + + for (let u of vertices) { + for (let [v, weight] of graph[u]) { + if (distances[u] !== Infinity && distances[u] + weight < distances[v]) { + console.log("Graph contains negative weight cycle"); + return {}; + } + } + } + + return distances; + } + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity:** $O(V * E)$, where $V$ is the number of vertices and $E$ is the number of edges. +- **Space Complexity:** $O(V)$, for storing distances. + +## 9. Advantages and Disadvantages + +### Advantages: +- Can handle graphs with negative weight edges. +- Can detect negative weight cycles. + +### Disadvantages: +- Less efficient than Dijkstra's Algorithm for graphs with non-negative weights. +- Slower on large graphs due to the need for multiple relaxation steps. + +## 10. Reference + +- [GeeksforGeeks - Bellman-Ford Algorithm](https://www.geeksforgeeks.org/bellman-ford-algorithm-dp-23/) \ No newline at end of file diff --git a/docs/Algorithms/Graph Algorithms/03-Floyd-Warshall Algorithm.md b/docs/Algorithms/Graph Algorithms/03-Floyd-Warshall Algorithm.md new file mode 100644 index 0000000..c222bb3 --- /dev/null +++ b/docs/Algorithms/Graph Algorithms/03-Floyd-Warshall Algorithm.md @@ -0,0 +1,173 @@ +--- +id: floyd-warshall-algorithm +title: Floyd-Warshall Algorithm +sidebar_label: 03 - Floyd-Warshall Algorithm +tags: + - Graph Algorithms + - Shortest Path + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains the Floyd-Warshall Algorithm for finding the shortest paths between all pairs of vertices in a weighted graph." +--- + +# Floyd-Warshall Algorithm + +## 1. What is the Floyd-Warshall Algorithm? + +The Floyd-Warshall Algorithm is used to find the shortest paths between all pairs of vertices in a weighted graph. It works for both directed and undirected graphs and can handle graphs with negative weight edges, but not negative weight cycles. + +## 2. Algorithm for Floyd-Warshall Algorithm + +1. Initialize the distance matrix with the weights of the edges between vertices. +2. For each pair of vertices $(i, j)$, update the distance matrix by considering the possibility of going through a third vertex $(k)$ to get a shorter path from $i$ to $j$. +3. The final distance matrix will contain the shortest distances between all pairs of vertices. + +## 3. How Does Floyd-Warshall Algorithm Work? + +1. Start with a distance matrix representing the weights of the edges between vertices. +2. Update the matrix by considering all possible intermediate vertices for each pair of vertices. +3. Repeat this process until all pairs of vertices have been considered, and the matrix stabilizes. + +## 4. Problem Description + +Given a weighted graph, the Floyd-Warshall Algorithm aims to find the shortest paths between all pairs of vertices in the graph. + +## 5. Examples + +Example graph: +``` + 0 1 2 3 + -------------------- + 0 | 0 3 ∞ 7 + 1 | 8 0 2 ∞ + 2 | 5 ∞ 0 1 + 3 | 2 ∞ ∞ 0 +``` + +## 6. Constraints + +- The graph can have negative weight edges, but not negative weight cycles. + +## 7. Implementation + + + + ```python + def floyd_warshall(graph): + V = len(graph) + dist = [[float('inf') for _ in range(V)] for _ in range(V)] + for i in range(V): + dist[i][i] = 0 + for u in range(V): + for v in range(V): + if graph[u][v] != 0: + dist[u][v] = graph[u][v] + for k in range(V): + for i in range(V): + for j in range(V): + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) + return dist + ``` + + + + ```cpp + #include + #include + #include + using namespace std; + + vector> floydWarshall(vector>& graph) { + int V = graph.size(); + vector> dist(graph); + + for (int k = 0; k < V; ++k) { + for (int i = 0; i < V; ++i) { + for (int j = 0; j < V; ++j) { + if (dist[i][k] != numeric_limits::max() && dist[k][j] != numeric_limits::max()) { + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); + } + } + } + } + + return dist; + } + ``` + + + + ```java + import java.util.*; + + class FloydWarshall { + public static int[][] floydWarshall(int[][] graph) { + int V = graph.length; + int[][] dist = new int[V][V]; + + for (int i = 0; i < V; ++i) { + for (int j = 0; j < V; ++j) { + dist[i][j] = graph[i][j]; + } + } + + for (int k = 0; k < V; ++k) { + for (int i = 0; i < V; ++i) { + for (int j = 0; j < V; ++j) { + if (dist[i][k] != Integer.MAX_VALUE && dist[k][j] != Integer.MAX_VALUE) { + dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); + } + } + } + } + + return dist; + } + } + ``` + + + + ```javascript + function floydWarshall(graph) { + const V = graph.length; + const dist = [...graph]; + + for (let k = 0; k < V; ++k) { + for (let i = 0; i < V; ++i) { + for (let j = 0; j < V; ++j) { + if (dist[i][k] !== Infinity && dist[k][j] !== Infinity) { + dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); + } + } + } + } + + return dist; + } + ``` + + + + +## 8. Complexity Analysis + +- **Time Complexity:** $O(V^3)$, where $V$ is the number of vertices. +- **Space Complexity:** $O(V^2)$, for storing the distance matrix. + +## 9. Advantages and Disadvantages + +### Advantages: +- Finds the shortest paths between all pairs of vertices. +- Can handle graphs with negative weight edges. + +### Disadvantages: +- Inefficient for large graphs due to its cubic time complexity. +- Requires additional space to store the distance matrix. + +## 10. Reference + +- [GeeksforGeeks - Floyd-Warshall Algorithm](https://www.geeksforgeeks.org/floyd-warshall-algorithm/) \ No newline at end of file diff --git a/docs/Algorithms/Graph Algorithms/04-Kruskal's Algorithm.md b/docs/Algorithms/Graph Algorithms/04-Kruskal's Algorithm.md new file mode 100644 index 0000000..45ba58b --- /dev/null +++ b/docs/Algorithms/Graph Algorithms/04-Kruskal's Algorithm.md @@ -0,0 +1,301 @@ +--- +id: kruskals-algorithm +title: Kruskal's Algorithm +sidebar_label: 04 - Kruskal's Algorithm +tags: + - Graph Algorithms + - Minimum Spanning Tree + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains Kruskal's Algorithm for finding the minimum spanning tree in a graph." +--- + +# Kruskal's Algorithm + +## 1. What is Kruskal's Algorithm? + +Kruskal's Algorithm is used to find the minimum spanning tree (MST) of a connected, undirected graph. It greedily selects edges with the lowest weight that do not form cycles, gradually building the MST. + +## 2. Algorithm for Kruskal's Algorithm + +1. Sort all the edges of the graph in non-decreasing order of their weight. +2. Initialize an empty set to store the MST. +3. Iterate through the sorted edges, adding each edge to the MST if it doesn't create a cycle. +4. Repeat until all vertices are connected or the MST contains $(V-1)$ edges, where $V$ is the number of vertices. + +## 3. How Does Kruskal's Algorithm Work? + +- Kruskal's Algorithm greedily selects edges with the lowest weight that do not form cycles, gradually building the MST. + +## 4. Problem Description + +Given a weighted, connected graph, Kruskal's Algorithm aims to find the minimum spanning tree (MST) of the graph. + +## 5. Examples + +Example graph: + +``` + 0 1 2 3 + -------------------- + 0 | 0 2 0 6 + 1 | 2 0 3 8 + 2 | 0 3 0 0 + 3 | 6 8 0 0 +``` + +## 6. Constraints + +- The graph must be connected and undirected. +- The weights of the edges can be positive or negative. + +## 7. Implementation + +### Kruskal's Algorithm + + + + ```python + def find(parent, i): + if parent[i] == i: + return i + return find(parent, parent[i]) + + def union(parent, rank, x, y): + xroot = find(parent, x) + yroot = find(parent, y) + + if rank[xroot] < rank[yroot]: + parent[xroot] = yroot + elif rank[xroot] > rank[yroot]: + parent[yroot] = xroot + else: + parent[yroot] = xroot + rank[xroot] += 1 + + def kruskal(graph): + V = len(graph) + result = [] + i = 0 + e = 0 + graph = sorted(graph, key=lambda item: item[2]) + parent = [i for i in range(V)] + rank = [0] * V + + while e < V - 1: + u, v, w = graph[i] + i = i + 1 + x = find(parent, u) + y = find(parent, v) + if x != y: + e = e + 1 + result.append([u, v, w]) + union(parent, rank, x, y) + + return result + ``` + + + + ```cpp + #include + #include + #include + using namespace std; + + struct Edge { + int src, dest, weight; + }; + + struct DisjointSet { + vector parent, rank; + DisjointSet(int n) { + parent.resize(n); + rank.resize(n); + for (int i = 0; i < n; ++i) + parent[i] = i; + } + int find(int i) { + if (parent[i] != i) + parent[i] = find(parent[i]); + return parent[i]; + } + void Union(int x, int y) { + int xRoot = find(x); + int yRoot = find(y); + if (xRoot == yRoot) return; + if (rank[xRoot] < rank[yRoot]) + parent[xRoot] = yRoot; + else if (rank[yRoot] < rank[xRoot]) + parent[yRoot] = xRoot; + else { + parent[yRoot] = xRoot; + rank[xRoot] += 1; + } + } + }; + + bool compare(const Edge& a, const Edge& b) { + return a.weight < b.weight; + } + + vector kruskal(vector& edges, int V) { + sort(edges.begin(), edges.end(), compare); + vector MST; + DisjointSet ds(V); + int i = 0; + while (MST.size() < V - 1) { + Edge nextEdge = edges[i++]; + int x = ds.find(nextEdge.src); + int y = ds.find(nextEdge.dest); + if (x != y) { + MST.push_back(nextEdge); + ds.Union(x, y); + } + } + return MST; + } + ``` + + + + ```java + import java.util.*; + + class KruskalAlgorithm { + static class Edge { + int src, dest, weight; + Edge(int src, int dest, int weight) { + this.src = src; + this.dest = dest; + this.weight = weight; + } + } + + static class Disjoint + private int[] parent; + private int[] rank; + + Disjoint(int n) { + parent = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; i++) { + parent[i] = i; + rank[i] = 0; + } + } + + int find(int x) { + if (parent[x] != x) { + parent[x] = find(parent[x]); + } + return parent[x]; + } + + void union(int x, int y) { + int xRoot = find(x); + int yRoot = find(y); + if (xRoot == yRoot) return; + if (rank[xRoot] < rank[yRoot]) { + parent[xRoot] = yRoot; + } else if (rank[yRoot] < rank[xRoot]) { + parent[yRoot] = xRoot; + } else { + parent[yRoot] = xRoot; + rank[xRoot]++; + } + } + } + + static List kruskalAlgorithm(List edges, int V) { + Collections.sort(edges, Comparator.comparingInt(e -> e.weight)); + List MST = new ArrayList<>(); + Disjoint disjointSet = new Disjoint(V); + int i = 0; + while (MST.size() < V - 1) { + Edge nextEdge = edges.get(i++); + int x = disjointSet.find(nextEdge.src); + int y = disjointSet.find(nextEdge.dest); + if (x != y) { + MST.add(nextEdge); + disjointSet.union(x, y); + } + } + return MST; + } + } + ``` + + + + + ```javascript + class DisjointSet { + constructor(size) { + this.parent = [...Array(size).keys()]; + this.rank = Array(size).fill(0); + } + + find(x) { + if (this.parent[x] !== x) { + this.parent[x] = this.find(this.parent[x]); + } + return this.parent[x]; + } + + union(x, y) { + const xRoot = this.find(x); + const yRoot = this.find(y); + if (xRoot === yRoot) return; + if (this.rank[xRoot] < this.rank[yRoot]) { + this.parent[xRoot] = yRoot; + } else if (this.rank[yRoot] < this.rank[xRoot]) { + this.parent[yRoot] = xRoot; + } else { + this.parent[yRoot] = xRoot; + this.rank[xRoot]++; + } + } + } + + function kruskal(edges, V) { + edges.sort((a, b) => a.weight - b.weight); + const MST = []; + const ds = new DisjointSet(V); + let i = 0; + while (MST.length < V - 1) { + const { src, dest } = edges[i++]; + const x = ds.find(src); + const y = ds.find(dest); + if (x !== y) { + MST.push({ src, dest }); + ds.union(x, y); + } + } + return MST; + } + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity:** $O(E log E)$ for sorting the edges, where $E$ is the number of edges, and $O(E log V)$ for finding the minimum spanning tree, where $V$ is the number of vertices. +- **Space Complexity:** $O(V + E)$, for storing the edges and disjoint set. + +## 9. Advantages and Disadvantages + +### Advantages: +- Finds the minimum spanning tree of a graph efficiently. +- Works well with both dense and sparse graphs. + +### Disadvantages: +- Requires sorting of edges, which can be computationally expensive. +- Not suitable for graphs with negative edge weights. + +## 10. References + +- [GeeksforGeeks - Kruskal's Algorithm](https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/) diff --git "a/docs/Algorithms/Graph Algorithms/05-Prim\342\200\231s Algorithm.md" "b/docs/Algorithms/Graph Algorithms/05-Prim\342\200\231s Algorithm.md" new file mode 100644 index 0000000..1c55425 --- /dev/null +++ "b/docs/Algorithms/Graph Algorithms/05-Prim\342\200\231s Algorithm.md" @@ -0,0 +1,229 @@ +--- +id: prims-algorithm +title: Prim's Algorithm +sidebar_label: 05 - Prim's Algorithm +tags: + - Graph Algorithms + - Minimum Spanning Tree + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains Prim's Algorithm for finding the minimum spanning tree in a graph." +--- + +# Prim's Algorithm + +## 1. What is Prim's Algorithm? + +Prim's Algorithm is used to find the minimum spanning tree (MST) of a connected, undirected graph. It greedily selects vertices with the lowest distance to the current MST, adding them to the MST one by one. + +## 2. Algorithm for Prim's Algorithm + +1. Start with an empty set to store the MST and a priority queue (min-heap) to store the vertices. +2. Initialize a distance array to track the minimum weight edge connecting each vertex to the MST. +3. Initialize all distances to infinity and set the distance of the starting vertex to 0. +4. Repeat until all vertices are added to the MST: + - Extract the vertex with the minimum distance from the priority queue. + - Add the vertex to the MST. + - Update the distances of adjacent vertices if they are not already in the MST. +5. The MST is formed by the edges connecting the vertices in the priority queue. + +## 3. How Does Prim's Algorithm Work? + +- Prim's Algorithm greedily selects vertices with the lowest distance to the current MST, adding them to the MST one by one. + +## 4. Problem Description + +Given a weighted, connected graph, Prim's Algorithm aims to find the minimum spanning tree (MST) of the graph. + +## 5. Examples + +Example graph: + +``` + 0 1 2 3 + -------------------- + 0 | 0 2 0 6 + 1 | 2 0 3 8 + 2 | 0 3 0 0 + 3 | 6 8 0 0 +``` + +## 6. Constraints + +- The graph must be connected and undirected. +- The weights of the edges can be positive or negative. + +## 7. Implementation + +### Prim's Algorithm + + + + ```python + import heapq + + def prim(graph): + min_heap = [] + visited = set() + MST = [] + start_vertex = list(graph.keys())[0] + visited.add(start_vertex) + for neighbor, weight in graph[start_vertex]: + heapq.heappush(min_heap, (weight, start_vertex, neighbor)) + while min_heap: + weight, src, dest = heapq.heappop(min_heap) + if dest not in visited: + visited.add(dest) + MST.append((src, dest, weight)) + for neighbor, weight in graph[dest]: + if neighbor not in visited: + heapq.heappush(min_heap, (weight, dest, neighbor)) + return MST + ``` + + + + ```cpp + #include + #include + #include + #include + #include + using namespace std; + + typedef pair pii; + + vector prim(vector>& graph) { + int V = graph.size(); + vector MST; + priority_queue, greater> min_heap; + unordered_set visited; + visited.insert(0); // Starting from vertex 0 + for (auto& edge : graph[0]) + min_heap.push({edge.second, edge.first, 0}); + while (!min_heap.empty()) { + auto [weight, src, dest] = min_heap.top(); + min_heap.pop(); + if (visited.find(dest) == visited.end()) { + visited.insert(dest); + MST.push_back({src, dest}); + for (auto& edge : graph[dest]) { + if (visited.find(edge.first) == visited.end()) + min_heap.push({edge.second, dest, edge.first}); + } + } + } + return MST; + } + ``` + + + + ```java + import java.util.*; + + class PrimAlgorithm { + static class Edge { + int dest, weight; + Edge(int dest, int weight) { + this.dest = dest; + this.weight = weight; + } + } + + static List primAlgorithm(List> graph) { + int V = graph.size(); + List MST = new ArrayList<>(); + PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a.weight - b.weight); + Set visited = new HashSet<>(); + visited.add(0); // Starting from vertex 0 + for (Edge edge : graph.get(0)) + minHeap.offer(edge); + while (!minHeap.isEmpty()) { + Edge edge = minHeap.poll(); + int src = edge.dest; + int weight = edge.weight; + if (!visited.contains(src)) { + visited.add(src); + MST.add(edge); + for (Edge nextEdge : graph.get(src)) { + if (!visited.contains(nextEdge.dest)) + minHeap.offer(nextEdge); + } + } + } + return MST; + } + } + ``` + + + + ```javascript + class PriorityQueue { + constructor() { + this.heap = []; + } + + push(item) { + this.heap.push(item); + this.heap.sort((a, b) => a[0] - b[0]); + } + + pop() { + return this.heap.shift(); + } + + isEmpty() { + return this.heap.length === 0; + } + } + + function prim(graph) { + const minHeap = new PriorityQueue(); + const MST = []; + const visited = new Set(); + const startVertex = Object.keys(graph)[0]; + visited.add(startVertex); + for (const [neighbor, weight] of graph[startVertex]) { + minHeap.push([weight, startVertex, neighbor]); + } + while (!minHeap.isEmpty()) { + const [weight, src, dest] = minHeap.pop(); + if (!visited.has(dest)) { + visited.add(dest); + MST.push([src, dest, weight]); + for (const [neighbor, weight] of graph[dest]) { + if (!visited.has(neighbor)) { + minHeap.push([weight, dest, neighbor]); + } + } + } + } + return MST; + } + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity:** $O(E + V log V)$ for a binary heap implementation, where $E$ is the number of edges and $V$ is the number of vertices. +- **Space Complexity:** $O(V + E)$ for storing the graph and priority queue. + +## 9. Advantages and Disadvantages + +### Advantages: +- Finds the minimum spanning tree of a graph efficiently. +- Works well with dense graphs. + +### Disadvantages: +- Requires a priority queue, which can be expensive in terms of space and time. +- Not suitable for graphs with negative edge weights. + +## 10. References + +- [GeeksforGeeks - Prim's Algorithm](https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/) \ No newline at end of file diff --git a/docs/Algorithms/Graph Algorithms/06-Kosaraju's-Algorithm.md b/docs/Algorithms/Graph Algorithms/06-Kosaraju's-Algorithm.md new file mode 100644 index 0000000..4666cbe --- /dev/null +++ b/docs/Algorithms/Graph Algorithms/06-Kosaraju's-Algorithm.md @@ -0,0 +1,291 @@ +--- +id: kosaraju-algorithm +title: Kosaraju's Algorithm +sidebar_label: 06 - Kosaraju's Algorithm +tags: + - Graph Algorithms + - Strongly Connected Components + - DSA + - Python + - C++ + - Java +description: "This page explains Kosaraju's Algorithm for finding the no of strongly connected component in a graph." +--- + +# Kosaraju's Algorithm + +## 1.Strongly Connected Component(SCC)? + +A component is called a Strongly Connected Component(SCC) only if for every possible pair of vertices (u, v) inside that component, u is reachable from v and v is reachable from u. + +## What is Kosaraju's Algorithm? + +To find the strongly connected components of a given directed graph, we are going to use Kosaraju’s Algorithm. + +Before understanding the algorithm, we are going to discuss the thought process behind it. If we start DFS from node 0 for the following graph, we will end up visiting all the nodes. So, it is impossible to differentiate between different SCCs. +Now, we need to think in a different way. We can convert the above graph into the following illustration: + +By definition, within each SCC, every node is reachable. So, if we start DFS from a node of SCC1 we can visit all the nodes in SCC1 and via edge e1 we can reach SCC2. Similarly, we can travel from SCC2 to SCC3 via e2 and SCC3 to SCC4 via e3. Thus all the nodes of the graph become reachable. + +But if we reverse the edges e1, e2, and e3, the graph will look like the following: + +Now in this graph, if we start DFS from node 0 it will visit only the nodes of SCC1. Similarly, if we start from node 3 it will visit only the nodes of SCC2. Thus, by reversing the SCC-connecting edges, the adjacent SCCs become unreachable. Now, the DFS will work in such a way, that in one DFS call we can only visit the nodes of a particular SCC. So, the number of DFS calls will represent the number of SCCs. + +Until now, we have successfully found out the process of getting the number of SCCs. But here, comes a new problem i.e. if we do not know the SCCs, how the edges will be reversed? To solve this problem, we will simply try to reverse all the edges of the graph like the following: + +If we carefully observe, the nodes within an SCC are reachable from each one to everyone even if we reverse the edges of the SCC. So, the SCCs will have no effect on reversing the edges. Thus we can fulfill our intention of reversing the SCC-connecting edge without affecting the SCCs. + +Now, the question might be like, if node 0 is located in SCC4 and we start DFS from node 0, again we will visit all the SCCs at once even after reversing the edges. This is where the starting time and the finishing time concept will come in. + +Now, we have a clear intuition about reversing edges before we move on to the starting and the finishing time concept in the algorithm part. + +## 2. Algorithm for Kosaraju's Algorithm + +- Sort all the nodes according to their finishing time: +- To sort all the nodes according to their finishing time, we will start DFS from node 0 and while backtracking in the DFS call we will store the nodes in a stack data structure. The nodes in the last SCC will finish first and will be stored in the last of the stack. After the DFS gets completed for all the nodes, the stack will be storing all the nodes in the sorted order of their finishing time. +- Reverse all the edges of the entire graph: +- Now, we will create another adjacency list and store the information of the graph in a reversed manner. +- Perform the DFS and count the no. of different DFS calls to get the no. of SCC: + - Now, we will start DFS from the node which is on the top of the stack and continue until the stack becomes empty. For each individual DFS call, we will increment the counter variable by 1. + - We will get the number of SCCs by just counting the number of individual DFS calls as in each individual DFS call, all the nodes of a particular SCC get visited. +- Finally, we will get the number of SCCs in the counter variable. If we want to store the SCCs as + well, we need to store the nodes in some array during each individual DFS call in step 3. + + + +## 4. Problem Description + + Given a Directed Graph with V vertices `(Numbered from 0 to V-1)` and E edges, Find the number of strongly connected components in the graph. + +## 5. Examples + +Example graph: + +``` + 0 1 2 3 4 + --------------------- + 0 | 0 0 1 1 0 + 1 | 1 0 0 0 0 + 2 | 0 1 0 0 0 + 3 | 0 0 0 0 1 + 4 | 0 0 0 0 0 + + Result: 3 +``` + +## 6. Constraints + +- The graph must be connected and directed. + +## 7. Implementation + +### Prim's Algorithm + + + + ```python + import heapq + + def prim(graph): + min_heap = [] + visited = set() + MST = [] + start_vertex = list(graph.keys())[0] + visited.add(start_vertex) + for neighbor, weight in graph[start_vertex]: + heapq.heappush(min_heap, (weight, start_vertex, neighbor)) + while min_heap: + weight, src, dest = heapq.heappop(min_heap) + if dest not in visited: + visited.add(dest) + MST.append((src, dest, weight)) + for neighbor, weight in graph[dest]: + if neighbor not in visited: + heapq.heappush(min_heap, (weight, dest, neighbor)) + return MST + ``` + + + + ```java + import java.io.*; +import java.util.*; + + + +//User function Template for Java + + +class Solution { + private void dfs(int node, int []vis, ArrayList> adj, + Stack st) { + vis[node] = 1; + for (Integer it : adj.get(node)) { + if (vis[it] == 0) { + dfs(it, vis, adj, st); + } + } + st.push(node); + } + private void dfs3(int node, int[] vis, ArrayList> adjT) { + vis[node] = 1; + for (Integer it : adjT.get(node)) { + if (vis[it] == 0) { + dfs3(it, vis, adjT); + } + } + } + //Function to find number of strongly connected components in the graph. + public int kosaraju(int V, ArrayList> adj) { + int[] vis = new int[V]; + Stack st = new Stack(); + for (int i = 0; i < V; i++) { + if (vis[i] == 0) { + dfs(i, vis, adj, st); + } + } + + ArrayList> adjT = new ArrayList>(); + for (int i = 0; i < V; i++) { + adjT.add(new ArrayList()); + } + for (int i = 0; i < V; i++) { + vis[i] = 0; + for (Integer it : adj.get(i)) { + // i -> it + // it -> i + adjT.get(it).add(i); + } + } + int scc = 0; + while (!st.isEmpty()) { + int node = st.peek(); + st.pop(); + if (vis[node] == 0) { + scc++; + dfs3(node, vis, adjT); + } + } + return scc; + } +} + +class Main { + public static void main (String[] args) { + int n = 5; + int[][] edges = { + {1, 0}, {0, 2}, + {2, 1}, {0, 3}, + {3, 4} + }; + ArrayList> adj = new ArrayList<>(); + for (int i = 0; i < n; i++) { + adj.add(new ArrayList()); + } + for (int i = 0; i < n; i++) { + adj.get(edges[i][0]).add(edges[i][1]); + } + Solution obj = new Solution(); + int ans = obj.kosaraju(n, adj); + System.out.println("The number of strongly connected components is: " + ans); + } +} + ``` + + + + ```cpp + #include +using namespace std; + + + + +class Solution +{ +private: + void dfs(int node, vector &vis, vector adj[], + stack &st) { + vis[node] = 1; + for (auto it : adj[node]) { + if (!vis[it]) { + dfs(it, vis, adj, st); + } + } + + st.push(node); + } +private: + void dfs3(int node, vector &vis, vector adjT[]) { + vis[node] = 1; + for (auto it : adjT[node]) { + if (!vis[it]) { + dfs3(it, vis, adjT); + } + } + } +public: + //Function to find number of strongly connected components in the graph. + int kosaraju(int V, vector adj[]) + { + vector vis(V, 0); + stack st; + for (int i = 0; i < V; i++) { + if (!vis[i]) { + dfs(i, vis, adj, st); + } + } + + vector adjT[V]; + for (int i = 0; i < V; i++) { + vis[i] = 0; + for (auto it : adj[i]) { + // i -> it + // it -> i + adjT[it].push_back(i); + } + } + int scc = 0; + while (!st.empty()) { + int node = st.top(); + st.pop(); + if (!vis[node]) { + scc++; + dfs3(node, vis, adjT); + } + } + return scc; + } +}; + +int main() { + + int n = 5; + int edges[5][2] = { + {1, 0}, {0, 2}, + {2, 1}, {0, 3}, + {3, 4} + }; + vector adj[n]; + for (int i = 0; i < n; i++) { + adj[edges[i][0]].push_back(edges[i][1]); + } + Solution obj; + int ans = obj.kosaraju(n, adj); + cout << "The number of strongly connected components is: " << ans << endl; + return 0; +} + ``` + + + + +## 8. Complexity Analysis + +- **Time Complexity:** `O(V+E) + $O(V+E) + O(V+E) ~ O(V+E)` , where `V = no. of vertices`, `E = no. of edges`. The first step is a simple DFS, so the first term is `O(V+E)`. The second step of reversing the graph and the third step, containing DFS again, will take $O(V+E)$ each. +- **Space Complexity:** $O(V)$+$O(V)$+$O(V+E)$, where `V = no. of vertices`, `E = no. of edges`. Two $O(V)$ for the visited array and the stack we have used. $O(V+E)$ space for the reversed adjacent list. + + +## 10. References + +- [GeeksforGeeks - Prim's Algorithm](https://takeuforward.org/graph/strongly-connected-components-kosarajus-algorithm-g-54/) \ No newline at end of file diff --git a/docs/Algorithms/Graph Algorithms/07-Ford Fulkerson's Algorithm.md b/docs/Algorithms/Graph Algorithms/07-Ford Fulkerson's Algorithm.md new file mode 100644 index 0000000..4fa34db --- /dev/null +++ b/docs/Algorithms/Graph Algorithms/07-Ford Fulkerson's Algorithm.md @@ -0,0 +1,590 @@ +--- +id: Ford Fulkerson's Algorithm +title: Ford Fulkerson's Algorithm +sidebar_label: 07 - Ford Fulkerson's Algorithm +tags: + - Graph Algorithms + - Network flow + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains the Ford Fulkerson's Algorithm for finding the maximum flow,residual flowin a network flow graph." +--- + +# Ford Fulkerson's Algorithm + +## 1. What is the Ford Fulkerson's Algorithm? + +The Ford-Fulkerson algorithm is a widely used algorithm to solve the maximum flow problem in a flow network. The maximum flow problem involves determining the maximum amount of flow that can be sent from a source vertex to a sink vertex in a directed weighted graph, subject to capacity constraints on the edges. + +## 2. Algorithm for Ford Fulkerson's Algorithm + +The following is simple idea of Ford-Fulkerson algorithm: + +1. Start with initial flow as 0. +2. While there exists an augmenting path from the source to the sink: + + - Find an augmenting path using any path-finding algorithm, such as breadth-first search or depth-first search. + + - Determine the amount of flow that can be sent along the augmenting path, which is the minimum residual capacity along the edges of the path. + + - Increase the flow along the augmenting path by the determined amount. + +3. Return the maximum flow. + +## 3. How Does Ford Fulkerson's Algorithm Work? + +The algorithm works by iteratively finding an augmenting path, which is a path from the source to the sink in the residual graph, i.e., the graph obtained by subtracting the current flow from the capacity of each edge. The algorithm then increases the flow along this path by the maximum possible amount, which is the minimum capacity of the edges along the path. + +## 4. Problem Description + +Given a graph which represents a flow network where every edge has a capacity. Also, given two vertices source β€˜s’ and sink β€˜t’ in the graph, find the maximum possible flow from s to t with the following constraints: + +Flow on an edge doesn’t exceed the given capacity of the edge. +Incoming flow is equal to outgoing flow for every vertex except s and t. + +## 5. Examples + +![Example network](../../../assets/ford.png) + +The maximum possible flow in the above graph is 23. + +![Solved network](../../../assets/ford2.png) + +## 6. Manual Run Through + +There is no flow in the graph to start with. + +To find the maximum flow, the Ford-Fulkerson algorithm must increase flow, but first it needs to find out where the flow can be increased: it must find an augmented path. + +The Ford-Fulkerson algorithm actually does not specify how such an augmented path is found (that is why it is often described as a method instead of an algorithm), but we will use Depth First Search (DFS) to find the augmented paths for the Ford-Fulkerson algorithm in this tutorial. + +## 7. Implementation + + + + ```python + # Python program for implementation +# of Ford Fulkerson algorithm +from collections import defaultdict + +# This class represents a directed graph +# using adjacency matrix representation +class Graph: + + def __init__(self, graph): + self.graph = graph # residual graph + self. ROW = len(graph) + # self.COL = len(gr[0]) + + '''Returns true if there is a path from source 's' to sink 't' in + residual graph. Also fills parent[] to store the path ''' + + def BFS(self, s, t, parent): + + # Mark all the vertices as not visited + visited = [False]*(self.ROW) + + # Create a queue for BFS + queue = [] + + # Mark the source node as visited and enqueue it + queue.append(s) + visited[s] = True + + # Standard BFS Loop + while queue: + + # Dequeue a vertex from queue and print it + u = queue.pop(0) + + # Get all adjacent vertices of the dequeued vertex u + # If a adjacent has not been visited, then mark it + # visited and enqueue it + for ind, val in enumerate(self.graph[u]): + if visited[ind] == False and val > 0: + # If we find a connection to the sink node, + # then there is no point in BFS anymore + # We just have to set its parent and can return true + queue.append(ind) + visited[ind] = True + parent[ind] = u + if ind == t: + return True + + # We didn't reach sink in BFS starting + # from source, so return false + return False + + + # Returns the maximum flow from s to t in the given graph + def FordFulkerson(self, source, sink): + + # This array is filled by BFS and to store path + parent = [-1]*(self.ROW) + + max_flow = 0 # There is no flow initially + + # Augment the flow while there is path from source to sink + while self.BFS(source, sink, parent) : + + # Find minimum residual capacity of the edges along the + # path filled by BFS. Or we can say find the maximum flow + # through the path found. + path_flow = float("Inf") + s = sink + while(s != source): + path_flow = min (path_flow, self.graph[parent[s]][s]) + s = parent[s] + + # Add path flow to overall flow + max_flow += path_flow + + # update residual capacities of the edges and reverse edges + # along the path + v = sink + while(v != source): + u = parent[v] + self.graph[u][v] -= path_flow + self.graph[v][u] += path_flow + v = parent[v] + + return max_flow + + +# Create a graph given in the above diagram + +graph = [[0, 16, 13, 0, 0, 0], + [0, 0, 10, 12, 0, 0], + [0, 4, 0, 0, 14, 0], + [0, 0, 9, 0, 0, 20], + [0, 0, 0, 7, 0, 4], + [0, 0, 0, 0, 0, 0]] + +g = Graph(graph) + +source = 0; sink = 5 + +print ("The maximum possible flow is %d " % g.FordFulkerson(source, sink)) + ``` + + + + ```cpp + // C++ program for implementation of Ford Fulkerson +// algorithm +#include +#include +#include +#include +using namespace std; + +// Number of vertices in given graph +#define V 6 + +/* Returns true if there is a path from source 's' to sink +'t' in residual graph. Also fills parent[] to store the +path */ +bool bfs(int rGraph[V][V], int s, int t, int parent[]) +{ + // Create a visited array and mark all vertices as not + // visited + bool visited[V]; + memset(visited, 0, sizeof(visited)); + + // Create a queue, enqueue source vertex and mark source + // vertex as visited + queue q; + q.push(s); + visited[s] = true; + parent[s] = -1; + + // Standard BFS Loop + while (!q.empty()) { + int u = q.front(); + q.pop(); + + for (int v = 0; v < V; v++) { + if (visited[v] == false && rGraph[u][v] > 0) { + // If we find a connection to the sink node, + // then there is no point in BFS anymore We + // just have to set its parent and can return + // true + if (v == t) { + parent[v] = u; + return true; + } + q.push(v); + parent[v] = u; + visited[v] = true; + } + } + } + + // We didn't reach sink in BFS starting from source, so + // return false + return false; +} + +// Returns the maximum flow from s to t in the given graph +int fordFulkerson(int graph[V][V], int s, int t) +{ + int u, v; + + // Create a residual graph and fill the residual graph + // with given capacities in the original graph as + // residual capacities in residual graph + int rGraph[V] + [V]; // Residual graph where rGraph[i][j] + // indicates residual capacity of edge + // from i to j (if there is an edge. If + // rGraph[i][j] is 0, then there is not) + for (u = 0; u < V; u++) + for (v = 0; v < V; v++) + rGraph[u][v] = graph[u][v]; + + int parent[V]; // This array is filled by BFS and to + // store path + + int max_flow = 0; // There is no flow initially + + // Augment the flow while there is path from source to + // sink + while (bfs(rGraph, s, t, parent)) { + // Find minimum residual capacity of the edges along + // the path filled by BFS. Or we can say find the + // maximum flow through the path found. + int path_flow = INT_MAX; + for (v = t; v != s; v = parent[v]) { + u = parent[v]; + path_flow = min(path_flow, rGraph[u][v]); + } + + // update residual capacities of the edges and + // reverse edges along the path + for (v = t; v != s; v = parent[v]) { + u = parent[v]; + rGraph[u][v] -= path_flow; + rGraph[v][u] += path_flow; + } + + // Add path flow to overall flow + max_flow += path_flow; + } + + // Return the overall flow + return max_flow; +} + +// Driver program to test above functions +int main() +{ + // Let us create a graph shown in the above example + int graph[V][V] + = { { 0, 16, 13, 0, 0, 0 }, { 0, 0, 10, 12, 0, 0 }, + { 0, 4, 0, 0, 14, 0 }, { 0, 0, 9, 0, 0, 20 }, + { 0, 0, 0, 7, 0, 4 }, { 0, 0, 0, 0, 0, 0 } }; + + cout << "The maximum possible flow is " + << fordFulkerson(graph, 0, 5); + + return 0; +} + + ``` + + + + ```java + // Java program for implementation of Ford Fulkerson +// algorithm +import java.io.*; +import java.lang.*; +import java.util.*; +import java.util.LinkedList; + +class MaxFlow { + static final int V = 6; // Number of vertices in graph + + /* Returns true if there is a path from source 's' to + sink 't' in residual graph. Also fills parent[] to + store the path */ + boolean bfs(int rGraph[][], int s, int t, int parent[]) + { + // Create a visited array and mark all vertices as + // not visited + boolean visited[] = new boolean[V]; + for (int i = 0; i < V; ++i) + visited[i] = false; + + // Create a queue, enqueue source vertex and mark + // source vertex as visited + LinkedList queue + = new LinkedList(); + queue.add(s); + visited[s] = true; + parent[s] = -1; + + // Standard BFS Loop + while (queue.size() != 0) { + int u = queue.poll(); + + for (int v = 0; v < V; v++) { + if (visited[v] == false + && rGraph[u][v] > 0) { + // If we find a connection to the sink + // node, then there is no point in BFS + // anymore We just have to set its parent + // and can return true + if (v == t) { + parent[v] = u; + return true; + } + queue.add(v); + parent[v] = u; + visited[v] = true; + } + } + } + + // We didn't reach sink in BFS starting from source, + // so return false + return false; + } + + // Returns the maximum flow from s to t in the given + // graph + int fordFulkerson(int graph[][], int s, int t) + { + int u, v; + + // Create a residual graph and fill the residual + // graph with given capacities in the original graph + // as residual capacities in residual graph + + // Residual graph where rGraph[i][j] indicates + // residual capacity of edge from i to j (if there + // is an edge. If rGraph[i][j] is 0, then there is + // not) + int rGraph[][] = new int[V][V]; + + for (u = 0; u < V; u++) + for (v = 0; v < V; v++) + rGraph[u][v] = graph[u][v]; + + // This array is filled by BFS and to store path + int parent[] = new int[V]; + + int max_flow = 0; // There is no flow initially + + // Augment the flow while there is path from source + // to sink + while (bfs(rGraph, s, t, parent)) { + // Find minimum residual capacity of the edges + // along the path filled by BFS. Or we can say + // find the maximum flow through the path found. + int path_flow = Integer.MAX_VALUE; + for (v = t; v != s; v = parent[v]) { + u = parent[v]; + path_flow + = Math.min(path_flow, rGraph[u][v]); + } + + // update residual capacities of the edges and + // reverse edges along the path + for (v = t; v != s; v = parent[v]) { + u = parent[v]; + rGraph[u][v] -= path_flow; + rGraph[v][u] += path_flow; + } + + // Add path flow to overall flow + max_flow += path_flow; + } + + // Return the overall flow + return max_flow; + } + + // Driver program to test above functions + public static void main(String[] args) + throws java.lang.Exception + { + // Let us create a graph shown in the above example + int graph[][] = new int[][] { + { 0, 16, 13, 0, 0, 0 }, { 0, 0, 10, 12, 0, 0 }, + { 0, 4, 0, 0, 14, 0 }, { 0, 0, 9, 0, 0, 20 }, + { 0, 0, 0, 7, 0, 4 }, { 0, 0, 0, 0, 0, 0 } + }; + MaxFlow m = new MaxFlow(); + + System.out.println("The maximum possible flow is " + + m.fordFulkerson(graph, 0, 5)); + } +} + + ``` + + + + ```javascript + + + ``` + + + + +## 8. Complexity Analysis + +Time complexity of the above algorithm is O(max_flow * E). We run a loop while there is an augmenting path. In worst case, we may add 1 unit flow in every iteration. Therefore the time complexity becomes O(max_flow * E). + +Space Complexity :O(V) , as we created queue. + +## 9. Residual Network in Ford-Fulkerson + +The Ford-Fulkerson algorithm actually works by creating and using something called a residual network, which is a representation of the original graph. + +In the residual network, every edge has a residual capacity, which is the original capacity of the edge, minus the the flow in that edge. The residual capacity can be seen as the leftover capacity in an edge with some flow. + +## 10. Reversed Edges in Ford-Fulkerson + +The Ford-Fulkerson algorithm also uses something called reversed edges to send flow back. This is useful to increase the total flow.To send flow back, in the opposite direction of the edge, a reverse edge is created for each original edge in the network. The Ford-Fulkerson algorithm can then use these reverse edges to send flow in the reverse direction.The idea of a residual network with residual capacity on edges, and the idea of reversed edges, are central to how the Ford-Fulkerson algorithm works, and we will go into more detail about this when we implement the algorithm further down on this page. diff --git a/docs/Algorithms/Graph Algorithms/08-Depth-First-Search.md b/docs/Algorithms/Graph Algorithms/08-Depth-First-Search.md new file mode 100644 index 0000000..68b4f3f --- /dev/null +++ b/docs/Algorithms/Graph Algorithms/08-Depth-First-Search.md @@ -0,0 +1,228 @@ +--- +id: depth-first-search +title: Depth-First Search +sidebar_label: 08 - Depth-First Search +tags: + - Graph Algorithms + - Traversal + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains Depth-First Search for traversing or searching tree or graph data structures." +--- + +# Depth-First Search + +## 1. What is Depth-First Search? + +Depth-First Search (DFS) is a fundamental graph traversal algorithm used to explore nodes and edges of a graph. Starting from a source node, DFS explores as far as possible along each branch before backtracking. + +## 2. Algorithm for Depth-First Search + +1. Start at the root node (or any arbitrary node). +2. Mark the starting node as visited and push it to a stack. +3. While the stack is not empty: + - Pop a node from the stack. + - If the node has any unvisited adjacent nodes: + - Mark the adjacent node as visited. + - Push the adjacent node onto the stack. +4. Repeat the process until the stack is empty. + +## 3. How Does Depth-First Search Work? + +- DFS explores nodes by going as deep as possible down each branch before backtracking to explore other branches. + +## 4. Problem Description + +Given a graph, DFS aims to traverse the graph, visiting all the vertices and edges exactly once in a depthward motion. + +## 5. Examples + +Example graph: + +``` + 0 - 1 - 2 + | | | + 3 - 4 - 5 +``` + +## 6. Constraints + +- The graph can be directed or undirected. +- The graph may contain cycles. + +## 7. Implementation + +### Depth-First Search + + + + + ```python + def dfs(graph, start): + visited = set() + stack = [start] + + while stack: + vertex = stack.pop() + if vertex not in visited: + visited.add(vertex) + stack.extend(set(graph[vertex]) - visited) + + return visited + + graph = { + 0: [1, 3], + 1: [0, 2, 4], + 2: [1, 5], + 3: [0, 4], + 4: [1, 3, 5], + 5: [2, 4] + } + + print(dfs(graph, 0)) + ``` + + + + + ```cpp + + #include + #include + #include + #include + using namespace std; + + void dfs(vector>& graph, int start) { + unordered_set visited; + stack s; + s.push(start); + + while (!s.empty()) { + int vertex = s.top(); + s.pop(); + if (visited.find(vertex) == visited.end()) { + visited.insert(vertex); + cout << vertex << " "; + for (auto neighbor : graph[vertex]) { + if (visited.find(neighbor) == visited.end()) { + s.push(neighbor); + } + } + } + } + } + + int main() { + vector> graph = { + {1, 3}, + {0, 2, 4}, + {1, 5}, + {0, 4}, + {1, 3, 5}, + {2, 4} + }; + + dfs(graph, 0); + return 0; + } +``` + + + + +```java + + import java.util.*; + public class DFS { + public static void dfs(Map> graph, int start) { + Set visited = new HashSet<>(); + Stack stack = new Stack<>(); + stack.push(start); + + while (!stack.isEmpty()) { + int vertex = stack.pop(); + if (!visited.contains(vertex)) { + visited.add(vertex); + System.out.print(vertex + " "); + for (int neighbor : graph.get(vertex)) { + if (!visited.contains(neighbor)) { + stack.push(neighbor); + } + } + } + } + } + + public static void main(String[] args) { + Map> graph = new HashMap<>(); + graph.put(0, Arrays.asList(1, 3)); + graph.put(1, Arrays.asList(0, 2, 4)); + graph.put(2, Arrays.asList(1, 5)); + graph.put(3, Arrays.asList(0, 4)); + graph.put(4, Arrays.asList(1, 3, 5)); + graph.put(5, Arrays.asList(2, 4)); + + dfs(graph, 0); + } + } + ``` + + + + +```javascript + function dfs(graph, start) { + const visited = new Set(); + const stack = [start]; + + while (stack.length) { + const vertex = stack.pop(); + if (!visited.has(vertex)) { + visited.add(vertex); + console.log(vertex); + for (const neighbor of graph[vertex]) { + if (!visited.has(neighbor)) { + stack.push(neighbor); + } + } + } + } + } + + const graph = { + 0: [1, 3], + 1: [0, 2, 4], + 2: [1, 5], + 3: [0, 4], + 4: [1, 3, 5], + 5: [2, 4] + }; + + dfs(graph, 0); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity:** $O(V + E)$ where $V$ is the number of vertices and $E$ is the number of edges. +- **Space Complexity:** $O(V)$ due to the stack and visited set. + +## 9. Advantages and Disadvantages + +### Advantages: +- Simple and easy to implement. +- Can be used to detect cycles in a graph. +- Useful for solving problems like topological sorting, pathfinding, and connectivity. + +### Disadvantages: +- May get stuck in an infinite loop if the graph contains cycles and the implementation does not account for visited nodes. +- Not optimal for finding the shortest path in unweighted graphs. + +## 10. References + +- [GeeksforGeeks - Depth First Search or DFS for a Graph](https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/) diff --git a/docs/Algorithms/Graph Algorithms/09-Breadth-First-Search.md b/docs/Algorithms/Graph Algorithms/09-Breadth-First-Search.md new file mode 100644 index 0000000..2fb2d47 --- /dev/null +++ b/docs/Algorithms/Graph Algorithms/09-Breadth-First-Search.md @@ -0,0 +1,230 @@ +--- +id: breadth-first-search +title: Breadth-First Search +sidebar_label: 09 - Breadth-First Search +tags: + - Graph Algorithms + - Traversal + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains Breadth-First Search for traversing or searching tree or graph data structures." +--- + +# Breadth-First Search + +## 1. What is Breadth-First Search? + +Breadth-First Search (BFS) is a fundamental graph traversal algorithm used to explore nodes and edges of a graph level by level. Starting from a source node, BFS explores all the neighboring nodes at the present depth before moving on to nodes at the next depth level. + +## 2. Algorithm for Breadth-First Search + +1. Start at the root node (or any arbitrary node). +2. Mark the starting node as visited and enqueue it. +3. While the queue is not empty: + - Dequeue a node from the front of the queue. + - If the node has any unvisited adjacent nodes: + - Mark the adjacent node as visited. + - Enqueue the adjacent node. +4. Repeat the process until the queue is empty. + +## 3. How Does Breadth-First Search Work? + +- BFS explores nodes level by level, ensuring that all nodes at the current level are explored before moving on to the next level. + +## 4. Problem Description + +Given a graph, BFS aims to traverse the graph, visiting all the vertices and edges exactly once in a breadthward motion. + +## 5. Examples + +Example graph: + +``` + 0 - 1 - 2 + | | | + 3 - 4 - 5 +``` + +## 6. Constraints + +- The graph can be directed or undirected. +- The graph may contain cycles. + +## 7. Implementation + +### Breadth-First Search + + + + + ```python + from collections import deque + + def bfs(graph, start): + visited = set() + queue = deque([start]) + visited.add(start) + + while queue: + vertex = queue.popleft() + print(vertex, end=" ") + + for neighbor in graph[vertex]: + if neighbor not in visited: + visited.add(neighbor) + queue.append(neighbor) + + graph = { + 0: [1, 3], + 1: [0, 2, 4], + 2: [1, 5], + 3: [0, 4], + 4: [1, 3, 5], + 5: [2, 4] + } + + bfs(graph, 0) + ``` + + + + + ```cpp + #include + #include + #include + #include + using namespace std; + + void bfs(vector>& graph, int start) { + unordered_set visited; + queue q; + q.push(start); + visited.insert(start); + + while (!q.empty()) { + int vertex = q.front(); + q.pop(); + cout << vertex << " "; + + for (auto neighbor : graph[vertex]) { + if (visited.find(neighbor) == visited.end()) { + visited.insert(neighbor); + q.push(neighbor); + } + } + } + } + + int main() { + vector> graph = { + {1, 3}, + {0, 2, 4}, + {1, 5}, + {0, 4}, + {1, 3, 5}, + {2, 4} + }; + + bfs(graph, 0); + return 0; + } + ``` + + + + + ```java + import java.util.*; + + public class BFS { + public static void bfs(Map> graph, int start) { + Set visited = new HashSet<>(); + Queue queue = new LinkedList<>(); + queue.add(start); + visited.add(start); + + while (!queue.isEmpty()) { + int vertex = queue.poll(); + System.out.print(vertex + " "); + + for (int neighbor : graph.get(vertex)) { + if (!visited.contains(neighbor)) { + visited.add(neighbor); + queue.add(neighbor); + } + } + } + } + + public static void main(String[] args) { + Map> graph = new HashMap<>(); + graph.put(0, Arrays.asList(1, 3)); + graph.put(1, Arrays.asList(0, 2, 4)); + graph.put(2, Arrays.asList(1, 5)); + graph.put(3, Arrays.asList(0, 4)); + graph.put(4, Arrays.asList(1, 3, 5)); + graph.put(5, Arrays.asList(2, 4)); + + bfs(graph, 0); + } + } + ``` + + + + + ```javascript + function bfs(graph, start) { + const visited = new Set(); + const queue = [start]; + visited.add(start); + + while (queue.length) { + const vertex = queue.shift(); + console.log(vertex); + + for (const neighbor of graph[vertex]) { + if (!visited.has(neighbor)) { + visited.add(neighbor); + queue.push(neighbor); + } + } + } + } + + const graph = { + 0: [1, 3], + 1: [0, 2, 4], + 2: [1, 5], + 3: [0, 4], + 4: [1, 3, 5], + 5: [2, 4] + }; + + bfs(graph, 0); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity:** $O(V + E)$ where $V$ is the number of vertices and $E$ is the number of edges. +- **Space Complexity:** $O(V)$ due to the queue and visited set. + +## 9. Advantages and Disadvantages + +### Advantages: +- Guarantees finding the shortest path in unweighted graphs. +- Simple and easy to implement. + +### Disadvantages: +- Requires more memory compared to DFS due to the queue. +- May be slower than DFS for deep and densely connected graphs. + +## 10. References + +- [GeeksforGeeks - Breadth First Search or BFS for a Graph](https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/) diff --git a/docs/Algorithms/Graph Algorithms/10-A-Star-Algorithm.md b/docs/Algorithms/Graph Algorithms/10-A-Star-Algorithm.md new file mode 100644 index 0000000..066c488 --- /dev/null +++ b/docs/Algorithms/Graph Algorithms/10-A-Star-Algorithm.md @@ -0,0 +1,409 @@ +--- +id: a-star-algorithm +title: A* Algorithm +sidebar_label: 10 - A* Algorithm +tags: + - Graph Algorithms + - Pathfinding + - Heuristic + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains the A* Algorithm for finding the shortest path in a graph using heuristics." +--- + +# A* Algorithm + +## 1. What is A* Algorithm? + +The A* Algorithm is a popular pathfinding and graph traversal algorithm known for its efficiency and accuracy. It is used to find the shortest path from a start node to a goal node by combining the strengths of Dijkstra's Algorithm and Greedy Best-First Search. + +## 2. Algorithm for A* Algorithm + +1. Initialize the open list with the start node. +2. Initialize the closed list as empty. +3. While the open list is not empty: + - Extract the node with the lowest f-cost from the open list (f-cost = g-cost + h-cost). + - If this node is the goal node, return the path. + - Move the node to the closed list. + - For each neighbor of the current node: + - If the neighbor is in the closed list, skip it. + - Calculate the g-cost (distance from start) and h-cost (heuristic estimate to goal). + - If the neighbor is not in the open list, add it. + - If the neighbor is in the open list with a higher f-cost, update its f-cost and parent. +4. If the open list is empty and the goal is not reached, return that no path exists. + +## 3. How Does A* Algorithm Work? + +- A* uses a priority queue to explore nodes with the lowest f-cost (estimated total cost). +- The g-cost represents the actual distance from the start node to the current node. +- The h-cost represents the heuristic estimate from the current node to the goal node. + +## 4. Problem Description + +Given a graph with weighted edges, A* aims to find the shortest path from the start node to the goal node using heuristic estimates. + +## 5. Examples + +Example graph: + +``` + A ---1--- B + | / | \ + 4 2 5 12 + | / | \ + C ---1--- D ---1--- E +``` + +## 6. Constraints + +- The graph can be directed or undirected. +- The graph may contain cycles. +- The heuristic function (h-cost) should be admissible (not overestimating the actual cost). + +## 7. Implementation + +### A* Algorithm + + + + + ```python + import heapq + + def heuristic(a, b): + return abs(a - b) + + def a_star(graph, start, goal): + open_list = [] + heapq.heappush(open_list, (0, start)) + came_from = {} + g_cost = {start: 0} + f_cost = {start: heuristic(start, goal)} + + while open_list: + _, current = heapq.heappop(open_list) + + if current == goal: + path = [] + while current in came_from: + path.append(current) + current = came_from[current] + path.append(start) + return path[::-1] + + for neighbor, weight in graph[current]: + tentative_g_cost = g_cost[current] + weight + if neighbor not in g_cost or tentative_g_cost < g_cost[neighbor]: + came_from[neighbor] = current + g_cost[neighbor] = tentative_g_cost + f_cost[neighbor] = g_cost[neighbor] + heuristic(neighbor, goal) + heapq.heappush(open_list, (f_cost[neighbor], neighbor)) + + return [] + + graph = { + 'A': [('B', 1), ('C', 4)], + 'B': [('A', 1), ('D', 5), ('E', 12)], + 'C': [('A', 4), ('D', 1)], + 'D': [('B', 5), ('C', 1), ('E', 1)], + 'E': [('B', 12), ('D', 1)] + } + + print(a_star(graph, 'A', 'E')) + ``` + + + + + ```cpp + #include + #include + #include + #include + #include + using namespace std; + + typedef pair pis; + + double heuristic(const string& a, const string& b) { + return abs(a[0] - b[0]); + } + + vector a_star(unordered_map>& graph, const string& start, const string& goal) { + priority_queue, greater> open_list; + open_list.push({0, start}); + unordered_map came_from; + unordered_map g_cost; + unordered_map f_cost; + + g_cost[start] = 0; + f_cost[start] = heuristic(start, goal); + + while (!open_list.empty()) { + auto [_, current] = open_list.top(); + open_list.pop(); + + if (current == goal) { + vector path; + while (current != start) { + path.push_back(current); + current = came_from[current]; + } + path.push_back(start); + reverse(path.begin(), path.end()); + return path; + } + + for (auto& [neighbor, weight] : graph[current]) { + double tentative_g_cost = g_cost[current] + weight; + if (!g_cost.count(neighbor) || tentative_g_cost < g_cost[neighbor]) { + came_from[neighbor] = current; + g_cost[neighbor] = tentative_g_cost; + f_cost[neighbor] = g_cost[neighbor] + heuristic(neighbor, goal); + open_list.push({f_cost[neighbor], neighbor}); + } + } + } + + return {}; + } + + int main() { + unordered_map> graph = { + {"A", {{"B", 1}, {"C", 4}}}, + {"B", {{"A", 1}, {"D", 5}, {"E", 12}}}, + {"C", {{"A", 4}, {"D", 1}}}, + {"D", {{"B", 5}, {"C", 1}, {"E", 1}}}, + {"E", {{"B", 12}, {"D", 1}}} + }; + + vector result = a_star(graph, "A", "E"); + for (const auto& node : result) { + cout << node << " "; + } + return 0; + } + ``` + + + + + ```java + import java.util.*; + + public class AStar { + static class Node implements Comparable { + String name; + double gCost, fCost; + + Node(String name, double gCost, double fCost) { + this.name = name; + this.gCost = gCost; + this.fCost = fCost; + } + + @Override + public int compareTo(Node other) { + return Double.compare(this.fCost, other.fCost); + } + } + + static double heuristic(String a, String b) { + return Math.abs(a.charAt(0) - b.charAt(0)); + } + + static List aStar(Map> graph, String start, String goal) { + PriorityQueue openList = new PriorityQueue<>(); + Map cameFrom = new HashMap<>(); + Map gCost = new HashMap<>(); + Map fCost = new HashMap<>(); + + openList.add(new Node(start, 0, heuristic(start, goal))); + gCost.put(start, 0.0); + fCost.put(start, heuristic(start, goal)); + + while (!openList.isEmpty()) { + Node current = openList.poll(); + if (current.name.equals(goal)) { + List path = new ArrayList<>(); + while (current.name != null) { + path.add(current.name); + current = new Node(cameFrom.get(current.name), 0, 0); + } + Collections.reverse(path); + return path; + } + + for (Node neighbor : graph.get(current.name)) { + double tentativeGCost = gCost.get(current.name) + neighbor.gCost; + if (!gCost.containsKey(neighbor.name) || tentativeGCost < gCost.get(neighbor.name)) { + cameFrom.put(neighbor.name, current.name); + gCost.put(neighbor.name, tentativeGCost); + fCost.put(neighbor.name, tentativeGCost + heuristic(neighbor.name, goal)); + openList.add(new Node(neighbor.name, tentativeGCost, fCost.get(neighbor.name))); + } + } + } + + return Collections.emptyList(); + } + + public static void main(String[] args) { + Map> graph = new HashMap<>(); + graph.put("A", Arrays.asList(new Node("B", 1, 0), new Node("C", 4, 0))); + graph.put("B", Arrays.asList(new Node("A", 1, 0), new Node("D", 5, 0), new Node("E", 12, 0 + +))); + graph.put("C", Arrays.asList(new Node("A", 4, 0), new Node("D", 1, 0))); + graph.put("D", Arrays.asList(new Node("B", 5, 0), new Node("C", 1, 0), new Node("E", 1, 0))); + graph.put("E", Arrays.asList(new Node("B", 12, 0), new Node("D", 1, 0))); + + List result = aStar(graph, "A", "E"); + result.forEach(node -> System.out.print(node + " ")); + } + } + ``` + + + + + ```javascript + class Node { + constructor(name, gCost, fCost) { + this.name = name; + this.gCost = gCost; + this.fCost = fCost; + } + } + + function heuristic(a, b) { + return Math.abs(a.charCodeAt(0) - b.charCodeAt(0)); + } + + function aStar(graph, start, goal) { + const openList = new PriorityQueue((a, b) => a.fCost < b.fCost); + openList.enqueue(new Node(start, 0, heuristic(start, goal))); + const cameFrom = new Map(); + const gCost = new Map([[start, 0]]); + const fCost = new Map([[start, heuristic(start, goal)]]); + + while (!openList.isEmpty()) { + const current = openList.dequeue(); + if (current.name === goal) { + const path = []; + let temp = current.name; + while (temp) { + path.push(temp); + temp = cameFrom.get(temp); + } + return path.reverse(); + } + + for (const [neighbor, weight] of graph[current.name]) { + const tentativeGCost = gCost.get(current.name) + weight; + if (!gCost.has(neighbor) || tentativeGCost < gCost.get(neighbor)) { + cameFrom.set(neighbor, current.name); + gCost.set(neighbor, tentativeGCost); + const newFCost = tentativeGCost + heuristic(neighbor, goal); + fCost.set(neighbor, newFCost); + openList.enqueue(new Node(neighbor, tentativeGCost, newFCost)); + } + } + } + + return []; + } + + const graph = { + 'A': [['B', 1], ['C', 4]], + 'B': [['A', 1], ['D', 5], ['E', 12]], + 'C': [['A', 4], ['D', 1]], + 'D': [['B', 5], ['C', 1], ['E', 1]], + 'E': [['B', 12], ['D', 1]] + }; + + const PriorityQueue = class { + constructor(comparator = (a, b) => a > b) { + this._heap = []; + this._comparator = comparator; + } + size() { + return this._heap.length; + } + isEmpty() { + return this.size() === 0; + } + peek() { + return this._heap[0]; + } + enqueue(value) { + this._heap.push(value); + this._siftUp(); + return this.size(); + } + dequeue() { + const poppedValue = this.peek(); + const bottom = this.size() - 1; + if (bottom > 0) { + this._swap(0, bottom); + } + this._heap.pop(); + this._siftDown(); + return poppedValue; + } + _greater(i, j) { + return this._comparator(this._heap[i], this._heap[j]); + } + _swap(i, j) { + [this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]]; + } + _siftUp() { + let node = this.size() - 1; + while (node > 0 && this._greater(node, (node - 1) >>> 1)) { + this._swap(node, (node - 1) >>> 1); + node = (node - 1) >>> 1; + } + } + _siftDown() { + let node = 0; + while ( + (node << 1) + 1 < this.size() && + (this._greater((node << 1) + 1, node) || + (node << 1) + 2 < this.size() && this._greater((node << 1) + 2, node)) + ) { + let maxChild = (node << 1) + 2 < this.size() && this._greater((node << 1) + 2, (node << 1) + 1) + ? (node << 1) + 2 + : (node << 1) + 1; + this._swap(node, maxChild); + node = maxChild; + } + } + }; + + console.log(aStar(graph, 'A', 'E')); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity:** $O(E \log V)$ where $E$ is the number of edges and $V$ is the number of vertices. +- **Space Complexity:** $O(V)$ due to the priority queue and the g-cost and f-cost dictionaries. + +## 9. Advantages and Disadvantages + +### Advantages: +- Guarantees finding the shortest path. +- Efficient with an admissible heuristic. + +### Disadvantages: +- Requires a good heuristic to be efficient. +- Memory intensive due to maintaining multiple lists and cost dictionaries. + +## 10. References + +- [GeeksforGeeks - A* Search Algorithm](https://www.geeksforgeeks.org/a-search-algorithm/) + diff --git a/docs/Algorithms/Graph Algorithms/11-Topological-Sorting.md b/docs/Algorithms/Graph Algorithms/11-Topological-Sorting.md new file mode 100644 index 0000000..c899a9c --- /dev/null +++ b/docs/Algorithms/Graph Algorithms/11-Topological-Sorting.md @@ -0,0 +1,248 @@ +--- +id: topological-sorting +title: Topological Sorting +sidebar_label: 11 - Topological Sorting +tags: + - Graph Algorithms + - Sorting + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains Topological Sorting, an algorithm for ordering vertices in a directed acyclic graph (DAG)." +--- + +# Topological Sorting + +## 1. What is Topological Sorting? + +Topological Sorting is a linear ordering of vertices in a directed acyclic graph (DAG) such that for every directed edge u β†’ v, vertex u comes before vertex v. It is used in scenarios where there is a dependency between tasks. + +## 2. Algorithm for Topological Sorting + +1. Initialize an empty stack to store the result (topologically sorted order). +2. Mark all vertices as not visited. +3. For each vertex, if it is not visited, call the recursive helper function: + - Mark the current vertex as visited. + - For each adjacent vertex, if it is not visited, recursively call the helper function. + - Push the current vertex to the stack. +4. Reverse the stack to get the topological order. + +## 3. How Does Topological Sorting Work? + +- Topological sorting sorts vertices such that for any directed edge u β†’ v, vertex u appears before vertex v in the ordering. +- It uses depth-first search (DFS) to explore the graph and a stack to store the vertices in the topologically sorted order. + +## 4. Problem Description + +Given a directed acyclic graph (DAG), find a topological ordering of its vertices. + +## 5. Examples + +Example graph: + +``` + 5 β†’ 0 ← 4 + ↓ ↓ + 2 β†’ 3 β†’ 1 +``` + +Topological Sort: 4, 5, 0, 2, 3, 1 or 5, 4, 2, 3, 0, 1 (one of the valid topological orders) + +## 6. Constraints + +- The graph must be directed and acyclic. + +## 7. Implementation + +### Topological Sorting + + + + + ```python + def topological_sort_util(v, visited, stack, graph): + visited[v] = True + for neighbor in graph[v]: + if not visited[neighbor]: + topological_sort_util(neighbor, visited, stack, graph) + stack.append(v) + + def topological_sort(graph): + visited = {v: False for v in graph} + stack = [] + + for v in graph: + if not visited[v]: + topological_sort_util(v, visited, stack, graph) + + stack.reverse() + return stack + + graph = { + 5: [0, 2], + 4: [0, 1], + 2: [3], + 3: [1], + 1: [], + 0: [] + } + + print(topological_sort(graph)) + ``` + + + + + ```cpp + #include + #include + #include + using namespace std; + + void topologicalSortUtil(int v, vector& visited, stack& Stack, vector>& graph) { + visited[v] = true; + for (int i : graph[v]) + if (!visited[i]) + topologicalSortUtil(i, visited, Stack, graph); + Stack.push(v); + } + + vector topologicalSort(vector>& graph) { + stack Stack; + vector visited(graph.size(), false); + + for (int i = 0; i < graph.size(); i++) + if (visited[i] == false) + topologicalSortUtil(i, visited, Stack, graph); + + vector result; + while (!Stack.empty()) { + result.push_back(Stack.top()); + Stack.pop(); + } + return result; + } + + int main() { + vector> graph = { + {}, // 0 + {0}, // 1 + {1}, // 2 + {0, 1}, // 3 + {1}, // 4 + {0, 2} // 5 + }; + + vector result = topologicalSort(graph); + for (int v : result) + cout << v << " "; + return 0; + } + ``` + + + + + ```java + import java.util.*; + + public class TopologicalSort { + private static void topologicalSortUtil(int v, boolean[] visited, Stack stack, Map> graph) { + visited[v] = true; + for (int neighbor : graph.get(v)) + if (!visited[neighbor]) + topologicalSortUtil(neighbor, visited, stack, graph); + stack.push(v); + } + + public static List topologicalSort(Map> graph) { + Stack stack = new Stack<>(); + boolean[] visited = new boolean[graph.size()]; + + for (int v : graph.keySet()) + if (!visited[v]) + topologicalSortUtil(v, visited, stack, graph); + + List result = new ArrayList<>(); + while (!stack.isEmpty()) + result.add(stack.pop()); + return result; + } + + public static void main(String[] args) { + Map> graph = new HashMap<>(); + graph.put(5, Arrays.asList(0, 2)); + graph.put(4, Arrays.asList(0, 1)); + graph.put(2, Arrays.asList(3)); + graph.put(3, Arrays.asList(1)); + graph.put(1, new ArrayList<>()); + graph.put(0, new ArrayList<>()); + + List result = topologicalSort(graph); + result.forEach(v -> System.out.print(v + " ")); + } + } + ``` + + + + + ```javascript + function topologicalSortUtil(v, visited, stack, graph) { + visited[v] = true; + for (const neighbor of graph[v]) { + if (!visited[neighbor]) { + topologicalSortUtil(neighbor, visited, stack, graph); + } + } + stack.push(v); + } + + function topologicalSort(graph) { + const visited = new Array(Object.keys(graph).length).fill(false); + const stack = []; + + for (const v in graph) { + if (!visited[v]) { + topologicalSortUtil(v, visited, stack, graph); + } + } + + stack.reverse(); + return stack; + } + + const graph = { + 0: [], + 1: [0], + 2: [1], + 3: [0, 1], + 4: [1], + 5: [0, 2] + }; + + console.log(topologicalSort(graph)); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity:** $O(V + E)$ where $V$ is the number of vertices and $E$ is the number of edges. +- **Space Complexity:** $O(V)$ due to the stack and visited array. + +## 9. Advantages and Disadvantages + +### Advantages: +- Efficient and straightforward for DAGs. +- Useful for scheduling tasks, resolving symbol dependencies in linkers, etc. + +### Disadvantages: +- Only applicable to directed acyclic graphs (DAGs). +- Does not handle graphs with cycles. + +## 10. References + +- [GeeksforGeeks - Topological Sorting](https://www.geeksforgeeks.org/topological-sorting/) diff --git a/docs/Algorithms/Graph Algorithms/12-Johnsons-Algorithm.md b/docs/Algorithms/Graph Algorithms/12-Johnsons-Algorithm.md new file mode 100644 index 0000000..0f8cd67 --- /dev/null +++ b/docs/Algorithms/Graph Algorithms/12-Johnsons-Algorithm.md @@ -0,0 +1,482 @@ +--- +id: johnsons-algorithm +title: Johnson's Algorithm +sidebar_label: 12 - Johnson's Algorithm +tags: + - Graph Algorithms + - Shortest Path + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains Johnson's Algorithm, an algorithm for finding shortest paths between all pairs of vertices in a weighted, directed graph." +--- + +# Johnson's Algorithm + +## 1. What is Johnson's Algorithm? + +Johnson's Algorithm is used to find the shortest paths between all pairs of vertices in a weighted, directed graph. It combines both Dijkstra's and the Bellman-Ford algorithm to efficiently handle graphs with both positive and negative edge weights, provided there are no negative weight cycles. + +## 2. Algorithm for Johnson's Algorithm + +1. **Add a New Vertex**: Add a new vertex to the graph and connect it to every other vertex with an edge of weight 0. +2. **Bellman-Ford Algorithm**: Use the Bellman-Ford algorithm to find the shortest path from the new vertex to every other vertex. If a negative weight cycle is detected, the algorithm terminates. +3. **Reweighting**: Reweight all edges in the original graph to ensure all edges have non-negative weights. +4. **Dijkstra's Algorithm**: Use Dijkstra's algorithm to find the shortest paths between all pairs of vertices in the reweighted graph. +5. **Adjust Weights**: Adjust the weights of the paths found by removing the effects of reweighting. + +## 3. How Does Johnson's Algorithm Work? + +- **Bellman-Ford Algorithm**: Used to find shortest paths from the new vertex, detecting any negative weight cycles. +- **Reweighting**: Transforms the edge weights to non-negative, allowing Dijkstra's algorithm to be used. +- **Dijkstra's Algorithm**: Finds shortest paths between all pairs of vertices in the reweighted graph. +- **Adjusting Weights**: Converts the shortest paths in the reweighted graph back to the original weights. + +## 4. Problem Description + +Given a weighted, directed graph, find the shortest paths between all pairs of vertices, ensuring the graph has no negative weight cycles. + +## 5. Examples + +Example graph: + +``` + 4 β†’ 5 + ↑ ↓ + 1 β†’ 3 β†’ 2 + ↓ ↓ + 0 ← 1 +``` + +Shortest Path Matrix: +``` + 0 1 2 3 4 5 +0[0, 1, 2, 1, 3, 3] +1[1, 0, 1, 2, 2, 2] +2[2, 1, 0, 1, 1, 1] +3[1, 2, 1, 0, 2, 2] +4[3, 2, 1, 2, 0, 1] +5[3, 2, 1, 2, 1, 0] +``` + +## 6. Constraints + +- The graph must not contain any negative weight cycles. + +## 7. Implementation + +### Johnson's Algorithm + + + + + ```python + import heapq + + def bellman_ford(graph, source): + distance = {v: float('inf') for v in graph} + distance[source] = 0 + + for _ in range(len(graph) - 1): + for u in graph: + for v, weight in graph[u]: + if distance[u] + weight < distance[v]: + distance[v] = distance[u] + weight + + for u in graph: + for v, weight in graph[u]: + if distance[u] + weight < distance[v]: + return None # Negative weight cycle detected + + return distance + + def dijkstra(graph, source): + pq = [(0, source)] + distance = {v: float('inf') for v in graph} + distance[source] = 0 + + while pq: + dist, u = heapq.heappop(pq) + if dist > distance[u]: + continue + for v, weight in graph[u]: + if distance[u] + weight < distance[v]: + distance[v] = distance[u] + weight + heapq.heappush(pq, (distance[v], v)) + + return distance + + def johnson(graph): + new_vertex = 'q' + graph[new_vertex] = [(v, 0) for v in graph] + + h = bellman_ford(graph, new_vertex) + if h is None: + return None # Negative weight cycle detected + + del graph[new_vertex] + reweighted_graph = {} + for u in graph: + reweighted_graph[u] = [] + for v, weight in graph[u]: + reweighted_graph[u].append((v, weight + h[u] - h[v])) + + distance = {} + for u in graph: + distance[u] = dijkstra(reweighted_graph, u) + for v in distance[u]: + distance[u][v] += h[v] - h[u] + + return distance + + graph = { + 0: [(1, 1), (3, 1)], + 1: [(2, 1)], + 2: [(4, 1)], + 3: [(2, 1)], + 4: [(0, 1), (5, 1)], + 5: [(2, 1)] + } + + print(johnson(graph)) + ``` + + + + + ```cpp + #include + #include + #include + #include + using namespace std; + + struct Edge { + int v, weight; + }; + + vector bellmanFord(vector>& graph, int source) { + int V = graph.size(); + vector distance(V, INT_MAX); + distance[source] = 0; + + for (int i = 1; i < V; ++i) { + for (int u = 0; u < V; ++u) { + for (Edge e : graph[u]) { + if (distance[u] != INT_MAX && distance[u] + e.weight < distance[e.v]) { + distance[e.v] = distance[u] + e.weight; + } + } + } + } + + for (int u = 0; u < V; ++u) { + for (Edge e : graph[u]) { + if (distance[u] != INT_MAX && distance[u] + e.weight < distance[e.v]) { + return {}; // Negative weight cycle detected + } + } + } + + return distance; + } + + vector dijkstra(vector>& graph, int source) { + int V = graph.size(); + vector distance(V, INT_MAX); + distance[source] = 0; + priority_queue, vector>, greater<>> pq; + pq.push({0, source}); + + while (!pq.empty()) { + int u = pq.top().second; + pq.pop(); + + for (Edge e : graph[u]) { + if (distance[u] != INT_MAX && distance[u] + e.weight < distance[e.v]) { + distance[e.v] = distance[u] + e.weight; + pq.push({distance[e.v], e.v}); + } + } + } + + return distance; + } + + vector> johnson(vector>& graph) { + int V = graph.size(); + vector new_edges(V, {0, 0}); + graph.push_back(new_edges); + + vector h = bellmanFord(graph, V); + graph.pop_back(); + + if (h.empty()) { + return {}; // Negative weight cycle detected + } + + vector> reweighted_graph(V); + for (int u = 0; u < V; ++u) { + for (Edge e : graph[u]) { + reweighted_graph[u].push_back({e.v, e.weight + h[u] - h[e.v]}); + } + } + + vector> distance(V, vector(V)); + for (int u = 0; u < V; ++u) { + vector dist = dijkstra(reweighted_graph, u); + for (int v = 0; v < V; ++v) { + distance[u][v] = dist[v] + h[v] - h[u]; + } + } + + return distance; + } + + int main() { + vector> graph = { + {{1, 1}, {3, 1}}, // 0 + {{2, 1}}, // 1 + {{4, 1}}, // 2 + {{2, 1}}, // 3 + {{0, 1}, {5, 1}}, // 4 + {{2, 1}} // 5 + }; + + vector> distance = johnson(graph); + for (const auto& row : distance) { + for (int dist : row) { + cout << dist << " "; + } + cout << endl; + } + + return 0; + } + ``` + + + + + ```java + import java.util.*; + + class Edge { + int v, weight; + + Edge(int v, int weight) { + this.v = + + v; + this.weight = weight; + } + } + + public class JohnsonsAlgorithm { + private static int[] bellmanFord(Map> graph, int source) { + int V = graph.size(); + int[] distance = new int[V]; + Arrays.fill(distance, Integer.MAX_VALUE); + distance[source] = 0; + + for (int i = 1; i < V; ++i) { + for (int u : graph.keySet()) { + for (Edge e : graph.get(u)) { + if (distance[u] != Integer.MAX_VALUE && distance[u] + e.weight < distance[e.v]) { + distance[e.v] = distance[u] + e.weight; + } + } + } + } + + for (int u : graph.keySet()) { + for (Edge e : graph.get(u)) { + if (distance[u] != Integer.MAX_VALUE && distance[u] + e.weight < distance[e.v]) { + return null; // Negative weight cycle detected + } + } + } + + return distance; + } + + private static int[] dijkstra(Map> graph, int source) { + int V = graph.size(); + int[] distance = new int[V]; + Arrays.fill(distance, Integer.MAX_VALUE); + distance[source] = 0; + + PriorityQueue pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1])); + pq.add(new int[]{source, 0}); + + while (!pq.isEmpty()) { + int[] current = pq.poll(); + int u = current[0]; + + for (Edge e : graph.get(u)) { + if (distance[u] != Integer.MAX_VALUE && distance[u] + e.weight < distance[e.v]) { + distance[e.v] = distance[u] + e.weight; + pq.add(new int[]{e.v, distance[e.v]}); + } + } + } + + return distance; + } + + public static int[][] johnson(Map> graph) { + int V = graph.size(); + graph.put(V, new ArrayList<>()); + for (int u = 0; u < V; ++u) { + graph.get(V).add(new Edge(u, 0)); + } + + int[] h = bellmanFord(graph, V); + graph.remove(V); + + if (h == null) { + return null; // Negative weight cycle detected + } + + Map> reweightedGraph = new HashMap<>(); + for (int u : graph.keySet()) { + reweightedGraph.put(u, new ArrayList<>()); + for (Edge e : graph.get(u)) { + reweightedGraph.get(u).add(new Edge(e.v, e.weight + h[u] - h[e.v])); + } + } + + int[][] distance = new int[V][V]; + for (int u = 0; u < V; ++u) { + int[] dist = dijkstra(reweightedGraph, u); + for (int v = 0; v < V; ++v) { + distance[u][v] = dist[v] + h[v] - h[u]; + } + } + + return distance; + } + + public static void main(String[] args) { + Map> graph = new HashMap<>(); + graph.put(0, Arrays.asList(new Edge(1, 1), new Edge(3, 1))); + graph.put(1, Arrays.asList(new Edge(2, 1))); + graph.put(2, Arrays.asList(new Edge(4, 1))); + graph.put(3, Arrays.asList(new Edge(2, 1))); + graph.put(4, Arrays.asList(new Edge(0, 1), new Edge(5, 1))); + graph.put(5, Arrays.asList(new Edge(2, 1))); + + int[][] distance = johnson(graph); + for (int[] row : distance) { + System.out.println(Arrays.toString(row)); + } + } + } + ``` + + + + + ```javascript + function bellmanFord(graph, source) { + const distance = Array(graph.length).fill(Infinity); + distance[source] = 0; + + for (let i = 1; i < graph.length; ++i) { + for (let u = 0; u < graph.length; ++u) { + for (const [v, weight] of graph[u]) { + if (distance[u] + weight < distance[v]) { + distance[v] = distance[u] + weight; + } + } + } + } + + for (let u = 0; u < graph.length; ++u) { + for (const [v, weight] of graph[u]) { + if (distance[u] + weight < distance[v]) { + return null; // Negative weight cycle detected + } + } + } + + return distance; + } + + function dijkstra(graph, source) { + const distance = Array(graph.length).fill(Infinity); + distance[source] = 0; + const pq = new MinPriorityQueue(); + + pq.enqueue([source, 0]); + + while (!pq.isEmpty()) { + const [u, dist] = pq.dequeue(); + if (dist > distance[u]) continue; + + for (const [v, weight] of graph[u]) { + if (distance[u] + weight < distance[v]) { + distance[v] = distance[u] + weight; + pq.enqueue([v, distance[v]]); + } + } + } + + return distance; + } + + function johnson(graph) { + const newVertex = graph.length; + graph.push(graph.map((_, i) => [i, 0])); + + const h = bellmanFord(graph, newVertex); + graph.pop(); + + if (!h) return null; // Negative weight cycle detected + + const reweightedGraph = graph.map((edges, u) => + edges.map(([v, weight]) => [v, weight + h[u] - h[v]]) + ); + + const distance = Array(graph.length) + .fill(null) + .map((_, u) => dijkstra(reweightedGraph, u).map((dist, v) => dist + h[v] - h[u])); + + return distance; + } + + const graph = [ + [[1, 1], [3, 1]], + [[2, 1]], + [[4, 1]], + [[2, 1]], + [[0, 1], [5, 1]], + [[2, 1]], + ]; + + console.log(johnson(graph)); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity:** $O(V^2 \log V + VE)$ where $V$ is the number of vertices and $E$ is the number of edges. +- **Space Complexity:** $O(V^2)$ due to the distance matrix and reweighted graph. + +## 9. Advantages and Disadvantages + +### Advantages: +- Handles graphs with negative weights. +- Efficient for sparse graphs. + +### Disadvantages: +- Cannot handle graphs with negative weight cycles. +- More complex to implement compared to other shortest path algorithms. + +## 10. References + +- [GeeksforGeeks - Johnson's Algorithm](https://www.geeksforgeeks.org/johnsons-algorithm/) + diff --git a/docs/Algorithms/Graph Algorithms/13-Edmonds-Karp-Algorithm.md b/docs/Algorithms/Graph Algorithms/13-Edmonds-Karp-Algorithm.md new file mode 100644 index 0000000..ec45fd0 --- /dev/null +++ b/docs/Algorithms/Graph Algorithms/13-Edmonds-Karp-Algorithm.md @@ -0,0 +1,343 @@ +--- +id: edmonds-karp-algorithm +title: Edmonds-Karp Algorithm +sidebar_label: 13 - Edmonds-Karp Algorithm +tags: + - Graph Algorithms + - Maximum Flow + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains the Edmonds-Karp Algorithm, an implementation of the Ford-Fulkerson method for computing the maximum flow in a flow network." +--- + +# Edmonds-Karp Algorithm + +## 1. What is the Edmonds-Karp Algorithm? + +The Edmonds-Karp Algorithm is an implementation of the Ford-Fulkerson method for computing the maximum flow in a flow network. It uses Breadth-First Search (BFS) to find augmenting paths, making it a specific and efficient version of the Ford-Fulkerson method. + +## 2. Algorithm for Edmonds-Karp + +1. **Initialize Flow**: Start with zero flow. +2. **Find Augmenting Path**: Use BFS to find the shortest augmenting path from the source to the sink in terms of the number of edges. +3. **Augment Flow**: Increase the flow along the path found in step 2 by the minimum residual capacity of the edges along the path. +4. **Update Residual Capacities**: Adjust the residual capacities of the edges and reverse edges along the path. +5. **Repeat**: Repeat steps 2-4 until no more augmenting paths can be found. + +## 3. How Does the Edmonds-Karp Algorithm Work? + +- **Breadth-First Search (BFS)**: Finds the shortest augmenting path in terms of the number of edges. +- **Residual Capacity**: The capacity left in an edge after considering the current flow. +- **Augmenting Path**: A path from the source to the sink where every edge has residual capacity greater than zero. + +## 4. Problem Description + +Given a flow network represented by a directed graph with capacities on the edges, find the maximum flow from a source vertex to a sink vertex. + +## 5. Examples + +Example graph: + +``` + 10 + A -----> B + /| |\ + | | \ + |6 |4 \10 + | | \ + v v v + C -----> D ----> E + 10 10 +``` + +Maximum Flow: 20 + +## 6. Constraints + +- The graph should be a directed graph with non-negative edge capacities. +- There must be a source and a sink vertex. + +## 7. Implementation + +### Edmonds-Karp Algorithm + + + + + ```python + from collections import deque + + def bfs(C, F, source, sink): + queue = deque([source]) + paths = {source: []} + if source == sink: + return paths[source] + while queue: + u = queue.popleft() + for v in range(len(C)): + if C[u][v] - F[u][v] > 0 and v not in paths: + paths[v] = paths[u] + [(u, v)] + if v == sink: + return paths[v] + queue.append(v) + return None + + def edmonds_karp(C, source, sink): + n = len(C) + F = [[0] * n for _ in range(n)] + path = bfs(C, F, source, sink) + while path: + flow = min(C[u][v] - F[u][v] for u, v in path) + for u, v in path: + F[u][v] += flow + F[v][u] -= flow + path = bfs(C, F, source, sink) + return sum(F[source][i] for i in range(n)) + + capacity = [ + [0, 10, 6, 0, 0], + [0, 0, 0, 4, 10], + [0, 0, 0, 10, 0], + [0, 0, 0, 0, 10], + [0, 0, 0, 0, 0] + ] + + source = 0 + sink = 4 + print("Max Flow:", edmonds_karp(capacity, source, sink)) + ``` + + + + + ```cpp + #include + #include + #include + #include + using namespace std; + + bool bfs(vector>& capacity, vector>& flow, int source, int sink, vector& parent) { + int n = capacity.size(); + vector visited(n, false); + queue q; + q.push(source); + visited[source] = true; + parent[source] = -1; + + while (!q.empty()) { + int u = q.front(); + q.pop(); + + for (int v = 0; v < n; ++v) { + if (!visited[v] && capacity[u][v] - flow[u][v] > 0) { + q.push(v); + parent[v] = u; + visited[v] = true; + if (v == sink) { + return true; + } + } + } + } + return false; + } + + int edmondsKarp(vector>& capacity, int source, int sink) { + int n = capacity.size(); + vector> flow(n, vector(n, 0)); + vector parent(n); + int maxFlow = 0; + + while (bfs(capacity, flow, source, sink, parent)) { + int pathFlow = INT_MAX; + for (int v = sink; v != source; v = parent[v]) { + int u = parent[v]; + pathFlow = min(pathFlow, capacity[u][v] - flow[u][v]); + } + + for (int v = sink; v != source; v = parent[v]) { + int u = parent[v]; + flow[u][v] += pathFlow; + flow[v][u] -= pathFlow; + } + + maxFlow += pathFlow; + } + return maxFlow; + } + + int main() { + vector> capacity = { + {0, 10, 6, 0, 0}, + {0, 0, 0, 4, 10}, + {0, 0, 0, 10, 0}, + {0, 0, 0, 0, 10}, + {0, 0, 0, 0, 0} + }; + + int source = 0; + int sink = 4; + cout << "Max Flow: " << edmondsKarp(capacity, source, sink) << endl; + return 0; + } + ``` + + + + + ```java + import java.util.*; + + public class EdmondsKarp { + private static boolean bfs(int[][] capacity, int[][] flow, int source, int sink, int[] parent) { + int n = capacity.length; + boolean[] visited = new boolean[n]; + Queue queue = new LinkedList<>(); + queue.add(source); + visited[source] = true; + parent[source] = -1; + + while (!queue.isEmpty()) { + int u = queue.poll(); + for (int v = 0; v < n; v++) { + if (!visited[v] && capacity[u][v] - flow[u][v] > 0) { + queue.add(v); + parent[v] = u; + visited[v] = true; + if (v == sink) { + return true; + } + } + } + } + return false; + } + + public static int edmondsKarp(int[][] capacity, int source, int sink) { + int n = capacity.length; + int[][] flow = new int[n][n]; + int[] parent = new int[n]; + int maxFlow = 0; + + while (bfs(capacity, flow, source, sink, parent)) { + int pathFlow = Integer.MAX_VALUE; + for (int v = sink; v != source; v = parent[v]) { + int u = parent[v]; + pathFlow = Math.min(pathFlow, capacity[u][v] - flow[u][v]); + } + + for (int v = sink; v != source; v = parent[v]) { + int u = parent[v]; + flow[u][v] += pathFlow; + flow[v][u] -= pathFlow; + } + + maxFlow += pathFlow; + } + return maxFlow; + } + + public static void main(String[] args) { + int[][] capacity = { + {0, 10, 6, 0, 0}, + {0, 0, 0, 4, 10}, + {0, 0, 0, 10, 0}, + {0, 0, 0, 0, 10}, + {0, 0, 0, 0, 0} + }; + + int source = 0; + int sink = 4; + System.out.println("Max Flow: " + edmondsKarp(capacity, source, sink)); + } + } + ``` + + + + + ```javascript + function bfs(capacity, flow, source, sink, parent) { + const visited = new Array(capacity.length).fill(false); + const queue = [source]; + visited[source] = true; + parent[source] = -1; + + while (queue.length) { + const u = queue.shift(); + for (let v = 0; v < capacity.length; v++) { + if (!visited[v] && capacity[u][v] - flow[u][v] > 0) { + queue.push(v); + parent[v] = u; + visited[v] = true; + if (v === sink) { + return true; + } + } + } + } + return false; + } + + function edmondsKarp(capacity, source, sink) { + const n = capacity.length; + const flow = Array.from({ length: n }, () => Array(n).fill(0)); + const parent = new Array(n); + let maxFlow = 0; + + while (bfs(capacity, flow, source, sink, parent)) { + let pathFlow = Infinity; + for (let v = sink; v !== source; v = parent[v]) { + const u = parent[v]; + pathFlow = Math.min(pathFlow, capacity[u][v] - flow[u][v]); + } + + for (let v = sink; v !== source; v = parent[v]) { + const u = parent[v]; + flow[u][v] += pathFlow; + flow[v][u] -= pathFlow; + } + + maxFlow += pathFlow; + } + return maxFlow; + } + + const capacity = [ + [0, 10, 6, 0, 0], + [0, 0, 0, 4, 10], + [0, 0, 0, 10, 0], + [0, 0, 0, 0, 10], + [0, 0, 0, 0, 0] + ]; + + const source = 0; + const sink = 4; + console.log("Max Flow:", edmondsKarp(capacity, source, sink)); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity:** $O(VE^2)$ where $V$ is the number of vertices and $E$ is the number of edges. +- **Space Complexity:** $O(V^2)$ due to the storage required for the capacity and flow matrices. + +## 9. Advantages and Disadvantages + +### Advantages: +- Provides an exact solution to the maximum flow problem. +- Uses BFS, making it simpler and ensuring the shortest augmenting path is found. + +### Disadvantages: +- Inefficient for dense graphs with large capacities. +- Higher time complexity compared to some other flow algorithms for large graphs. + +## 10. References + +- [GeeksforGeeks - Edmonds-Karp Algorithm](https://www.geeksforgeeks.org/edmonds-karp-algorithm-for-maximum-flow-problem/) + diff --git a/docs/Algorithms/Graph Algorithms/14-Kahns-Algorithm.md b/docs/Algorithms/Graph Algorithms/14-Kahns-Algorithm.md new file mode 100644 index 0000000..b0f913f --- /dev/null +++ b/docs/Algorithms/Graph Algorithms/14-Kahns-Algorithm.md @@ -0,0 +1,302 @@ +--- +id: kahns-algorithm +title: Kahn's Algorithm +sidebar_label: 14 - Kahn's Algorithm +tags: + - Graph Algorithms + - Topological Sorting + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains Kahn's Algorithm, an algorithm for topological sorting of a directed acyclic graph (DAG)." +--- + +# Kahn's Algorithm + +## 1. What is Kahn's Algorithm? + +Kahn's Algorithm is an algorithm for topological sorting of a directed acyclic graph (DAG). It uses an iterative approach to remove nodes with no incoming edges and forms a topological order of the vertices. + +## 2. Algorithm for Kahn's Algorithm + +1. **Initialize In-Degree**: Compute the in-degree (number of incoming edges) for each vertex. +2. **Initialize Queue**: Collect all vertices with an in-degree of 0 in a queue. +3. **Process Vertices**: + - Remove a vertex from the queue and add it to the topological order. + - Decrease the in-degree of all its neighboring vertices by 1. + - If any neighboring vertex's in-degree becomes 0, add it to the queue. +4. **Check for Cycles**: If the number of vertices in the topological order is less than the total number of vertices, the graph has a cycle. + +## 3. How Does Kahn's Algorithm Work? + +- **In-Degree Calculation**: Helps identify vertices with no dependencies (in-degree 0). +- **Queue Processing**: Ensures vertices are processed in the order of their dependencies being resolved. +- **Cycle Detection**: If all vertices are not included in the topological order, the graph contains a cycle. + +## 4. Problem Description + +Given a directed acyclic graph (DAG), perform a topological sort of its vertices. + +## 5. Examples + +Example graph: + +``` + 5 β†’ 0 ← 4 + ↓ ↓ + 2 β†’ 3 β†’ 1 +``` + +Topological Sort: 4, 5, 0, 2, 3, 1 or 5, 4, 2, 3, 0, 1 (one of the valid topological orders) + +## 6. Constraints + +- The graph must be directed and acyclic. + +## 7. Implementation + +### Kahn's Algorithm + + + + + ```python + from collections import deque, defaultdict + + def kahns_algorithm(graph): + in_degree = {u: 0 for u in graph} + for u in graph: + for v in graph[u]: + in_degree[v] += 1 + + queue = deque([u for u in graph if in_degree[u] == 0]) + topo_order = [] + + while queue: + u = queue.popleft() + topo_order.append(u) + + for v in graph[u]: + in_degree[v] -= 1 + if in_degree[v] == 0: + queue.append(v) + + if len(topo_order) == len(graph): + return topo_order + else: + return [] # The graph has a cycle + + graph = { + 5: [0, 2], + 4: [0, 1], + 2: [3], + 3: [1], + 1: [], + 0: [] + } + + print(kahns_algorithm(graph)) + ``` + + + + + ```cpp + #include + #include + #include + using namespace std; + + vector kahnsAlgorithm(vector>& graph) { + int n = graph.size(); + vector in_degree(n, 0); + for (int u = 0; u < n; ++u) { + for (int v : graph[u]) { + in_degree[v]++; + } + } + + queue q; + for (int i = 0; i < n; ++i) { + if (in_degree[i] == 0) { + q.push(i); + } + } + + vector topo_order; + while (!q.empty()) { + int u = q.front(); + q.pop(); + topo_order.push_back(u); + + for (int v : graph[u]) { + if (--in_degree[v] == 0) { + q.push(v); + } + } + } + + if (topo_order.size() == n) { + return topo_order; + } else { + return {}; // The graph has a cycle + } + } + + int main() { + vector> graph = { + {}, // 0 + {}, // 1 + {3}, // 2 + {1}, // 3 + {0, 1}, // 4 + {0, 2} // 5 + }; + + vector result = kahnsAlgorithm(graph); + for (int v : result) { + cout << v << " "; + } + cout << endl; + return 0; + } + ``` + + + + + ```java + import java.util.*; + + public class KahnsAlgorithm { + public static List kahnsAlgorithm(Map> graph) { + Map inDegree = new HashMap<>(); + for (int u : graph.keySet()) { + inDegree.put(u, 0); + } + for (int u : graph.keySet()) { + for (int v : graph.get(u)) { + inDegree.put(v, inDegree.get(v) + 1); + } + } + + Queue queue = new LinkedList<>(); + for (int u : inDegree.keySet()) { + if (inDegree.get(u) == 0) { + queue.add(u); + } + } + + List topoOrder = new ArrayList<>(); + while (!queue.isEmpty()) { + int u = queue.poll(); + topoOrder.add(u); + + for (int v : graph.get(u)) { + inDegree.put(v, inDegree.get(v) - 1); + if (inDegree.get(v) == 0) { + queue.add(v); + } + } + } + + if (topoOrder.size() == graph.size()) { + return topoOrder; + } else { + return new ArrayList<>(); // The graph has a cycle + } + } + + public static void main(String[] args) { + Map> graph = new HashMap<>(); + graph.put(0, new ArrayList<>()); + graph.put(1, new ArrayList<>()); + graph.put(2, Arrays.asList(3)); + graph.put(3, Arrays.asList(1)); + graph.put(4, Arrays.asList(0, 1)); + graph.put(5, Arrays.asList(0, 2)); + + List result = kahnsAlgorithm(graph); + result.forEach(v -> System.out.print(v + " ")); + System.out.println(); + } + } + ``` + + + + + ```javascript + function kahnsAlgorithm(graph) { + const inDegree = {}; + for (const u in graph) { + inDegree[u] = 0; + } + for (const u in graph) { + for (const v of graph[u]) { + inDegree[v] = (inDegree[v] || 0) + 1; + } + } + + const queue = []; + for (const u in inDegree) { + if (inDegree[u] === 0) { + queue.push(u); + } + } + + const topoOrder = []; + while (queue.length > 0) { + const u = queue.shift(); + topoOrder.push(u); + + for (const v of graph[u]) { + inDegree[v]--; + if (inDegree[v] === 0) { + queue.push(v); + } + } + } + + if (topoOrder.length === Object.keys(graph).length) { + return topoOrder; + } else { + return []; // The graph has a cycle + } + } + + const graph = { + 0: [], + 1: [], + 2: [3], + 3: [1], + 4: [0, 1], + 5: [0, 2] + }; + + console.log(kahnsAlgorithm(graph)); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity:** $O(V + E)$ where $V$ is the number of vertices and $E$ is the number of edges. +- **Space Complexity:** $O(V)$ due to the storage required for the in-degree array and the queue. + +## 9. Advantages and Disadvantages + +### Advantages: +- Efficient and straightforward for DAGs. +- Useful for scheduling tasks, resolving symbol dependencies in linkers, etc. + +### Disadvantages: +- Only applicable to directed acyclic graphs (DAGs). +- Does not handle graphs with cycles. + +## 10. References + +- [GeeksforGeeks - Kahn's Algorithm](https://www.geeksforgeeks.org/topological-sorting-indegree-based-solution/) + diff --git "a/docs/Algorithms/Graph Algorithms/15-Bor\305\257vkas-Algorithm.md" "b/docs/Algorithms/Graph Algorithms/15-Bor\305\257vkas-Algorithm.md" new file mode 100644 index 0000000..e5c0183 --- /dev/null +++ "b/docs/Algorithms/Graph Algorithms/15-Bor\305\257vkas-Algorithm.md" @@ -0,0 +1,485 @@ +--- +id: boruvkas-algorithm +title: BorΕ―vka's Algorithm +sidebar_label: 15 - BorΕ―vka's Algorithm +tags: + - Graph Algorithms + - Minimum Spanning Tree + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains BorΕ―vka's Algorithm, an algorithm for finding the minimum spanning tree (MST) of a graph." +--- + +# BorΕ―vka's Algorithm + +## 1. What is BorΕ―vka's Algorithm? + +BorΕ―vka's Algorithm is an algorithm for finding the Minimum Spanning Tree (MST) of a connected, weighted, undirected graph. It is one of the oldest MST algorithms and works by repeatedly adding the shortest edge from each component to another component until all components are connected. + +## 2. Algorithm for BorΕ―vka's Algorithm + +1. **Initialize Components**: Start with each vertex as a separate component. +2. **Find Minimum Edge**: For each component, find the minimum weight edge that connects it to a vertex in another component. +3. **Add Minimum Edge**: Add all such edges to the MST and merge the corresponding components. +4. **Repeat**: Repeat the process until there is only one component left, which represents the MST. + +## 3. How Does BorΕ―vka's Algorithm Work? + +- **Component Initialization**: Initially, every vertex is its own component. +- **Minimum Edge Selection**: For each component, select the edge with the smallest weight that connects to a different component. +- **Component Merging**: Add these edges to the MST and merge the components they connect. +- **Iteration**: Repeat the process until all vertices are in a single component. + +## 4. Problem Description + +Given a connected, weighted, undirected graph, find the Minimum Spanning Tree (MST) using BorΕ―vka's Algorithm. + +## 5. Examples + +Example graph: + +``` + 2 3 +(0)---(1)---(2) + | \ | / | + 6 8 5 7 4 + | |/ | +(3)----(4)---(5) + 9 10 +``` + +Minimum Spanning Tree: Edges (0-1, 0-3, 1-2, 1-4, 2-5) + +## 6. Constraints + +- The graph must be connected and undirected. +- The edges must have non-negative weights. + +## 7. Implementation + +### BorΕ―vka's Algorithm + + + + + ```python + class Graph: + def __init__(self, vertices): + self.V = vertices + self.graph = [] + + def add_edge(self, u, v, w): + self.graph.append([u, v, w]) + + def find(self, parent, i): + if parent[i] == i: + return i + return self.find(parent, parent[i]) + + def union(self, parent, rank, x, y): + xroot = self.find(parent, x) + yroot = self.find(parent, y) + if rank[xroot] < rank[yroot]: + parent[xroot] = yroot + elif rank[xroot] > rank[yroot]: + parent[yroot] = xroot + else: + parent[yroot] = xroot + rank[xroot] += 1 + + def boruvka_mst(self): + parent = [] + rank = [] + cheapest = [] + + num_trees = self.V + mst_weight = 0 + + for node in range(self.V): + parent.append(node) + rank.append(0) + cheapest = [-1] * self.V + + while num_trees > 1: + for i in range(len(self.graph)): + u, v, w = self.graph[i] + set1 = self.find(parent, u) + set2 = self.find(parent, v) + if set1 != set2: + if cheapest[set1] == -1 or cheapest[set1][2] > w: + cheapest[set1] = [u, v, w] + if cheapest[set2] == -1 or cheapest[set2][2] > w: + cheapest[set2] = [u, v, w] + + for node in range(self.V): + if cheapest[node] != -1: + u, v, w = cheapest[node] + set1 = self.find(parent, u) + set2 = self.find(parent, v) + if set1 != set2: + mst_weight += w + self.union(parent, rank, set1, set2) + num_trees -= 1 + + cheapest = [-1] * self.V + + return mst_weight + + g = Graph(6) + g.add_edge(0, 1, 2) + g.add_edge(0, 3, 6) + g.add_edge(1, 2, 3) + g.add_edge(1, 3, 8) + g.add_edge(1, 4, 5) + g.add_edge(2, 4, 7) + g.add_edge(2, 5, 4) + g.add_edge(3, 4, 9) + g.add_edge(4, 5, 10) + + print("Weight of MST is", g.boruvka_mst()) + ``` + + + + + ```cpp + #include + #include + #include + using namespace std; + + class Graph { + int V, E; + vector> edges; + + public: + Graph(int V) : V(V), E(0) {} + + void addEdge(int u, int v, int w) { + edges.push_back({w, u, v}); + E++; + } + + int find(vector& parent, int i) { + if (parent[i] == i) + return i; + return find(parent, parent[i]); + } + + void Union(vector& parent, vector& rank, int x, int y) { + int xroot = find(parent, x); + int yroot = find(parent, y); + if (rank[xroot] < rank[yroot]) + parent[xroot] = yroot; + else if (rank[xroot] > rank[yroot]) + parent[yroot] = xroot; + else { + parent[yroot] = xroot; + rank[xroot]++; + } + } + + int boruvkaMST() { + vector parent(V), rank(V, 0), cheapest(V, -1); + iota(parent.begin(), parent.end(), 0); + + int numTrees = V, MSTweight = 0; + + while (numTrees > 1) { + for (int i = 0; i < E; ++i) { + int u = edges[i][1], v = edges[i][2], w = edges[i][0]; + int set1 = find(parent, u), set2 = find(parent, v); + if (set1 != set2) { + if (cheapest[set1] == -1 || edges[cheapest[set1]][0] > w) + cheapest[set1] = i; + if (cheapest[set2] == -1 || edges[cheapest[set2]][0] > w) + cheapest[set2] = i; + } + } + + for (int i = 0; i < V; ++i) { + if (cheapest[i] != -1) { + int u = edges[cheapest[i]][1], v = edges[cheapest[i]][2], w = edges[cheapest[i]][0]; + int set1 = find(parent, u), set2 = find(parent, v); + if (set1 != set2) { + MSTweight += w; + Union(parent, rank, set1, set2); + numTrees--; + } + } + } + + fill(cheapest.begin(), cheapest.end(), -1); + } + + return MSTweight; + } + }; + + int main() { + Graph g(6); + g.addEdge(0, 1, 2); + g.addEdge(0, 3, 6); + g.addEdge(1, 2, 3); + g.addEdge(1, 3, 8); + g.addEdge(1, 4, 5); + g.addEdge(2, 4, 7); + g.addEdge(2, 5, 4); + g.addEdge(3, 4, 9); + g.addEdge(4, 5, 10); + + cout << "Weight of MST is " << g.boruvkaMST() << endl; + return 0; + } + ``` + + + + + ```java + import java.util.*; + + class Graph { + class Edge { + int src, dest, weight; + Edge() { src = dest = weight = 0; } + } + + int V, E; + Edge edge[]; + + Graph(int v, int e) { + V = v; + E = e; + edge = new Edge[E]; + for (int i = 0; i < e; ++i) + edge[i] = new Edge(); + } + + + + int find(int parent[], int i) { + if (parent[i] == i) + return i; + return find(parent, parent[i]); + } + + void union(int parent[], int rank[], int x, int y) { + int xroot = find(parent, x); + int yroot = find(parent, y); + if (rank[xroot] < rank[yroot]) + parent[xroot] = yroot; + else if (rank[xroot] > rank[yroot]) + parent[yroot] = xroot; + else { + parent[yroot] = xroot; + rank[xroot]++; + } + } + + void boruvkaMST() { + int parent[] = new int[V]; + int rank[] = new int[V]; + int cheapest[] = new int[V]; + + for (int v = 0; v < V; ++v) { + parent[v] = v; + rank[v] = 0; + cheapest[v] = -1; + } + + int numTrees = V; + int MSTweight = 0; + + while (numTrees > 1) { + for (int i = 0; i < E; ++i) { + int u = edge[i].src, v = edge[i].dest, w = edge[i].weight; + int set1 = find(parent, u), set2 = find(parent, v); + if (set1 != set2) { + if (cheapest[set1] == -1 || edge[cheapest[set1]].weight > w) + cheapest[set1] = i; + if (cheapest[set2] == -1 || edge[cheapest[set2]].weight > w) + cheapest[set2] = i; + } + } + + for (int i = 0; i < V; ++i) { + if (cheapest[i] != -1) { + int u = edge[cheapest[i]].src, v = edge[cheapest[i]].dest, w = edge[cheapest[i]].weight; + int set1 = find(parent, u), set2 = find(parent, v); + if (set1 != set2) { + MSTweight += w; + union(parent, rank, set1, set2); + numTrees--; + } + } + } + + Arrays.fill(cheapest, -1); + } + + System.out.println("Weight of MST is " + MSTweight); + } + + public static void main(String[] args) { + int V = 6, E = 9; + Graph graph = new Graph(V, E); + + graph.edge[0].src = 0; + graph.edge[0].dest = 1; + graph.edge[0].weight = 2; + + graph.edge[1].src = 0; + graph.edge[1].dest = 3; + graph.edge[1].weight = 6; + + graph.edge[2].src = 1; + graph.edge[2].dest = 2; + graph.edge[2].weight = 3; + + graph.edge[3].src = 1; + graph.edge[3].dest = 3; + graph.edge[3].weight = 8; + + graph.edge[4].src = 1; + graph.edge[4].dest = 4; + graph.edge[4].weight = 5; + + graph.edge[5].src = 2; + graph.edge[5].dest = 4; + graph.edge[5].weight = 7; + + graph.edge[6].src = 2; + graph.edge[6].dest = 5; + graph.edge[6].weight = 4; + + graph.edge[7].src = 3; + graph.edge[7].dest = 4; + graph.edge[7].weight = 9; + + graph.edge[8].src = 4; + graph.edge[8].dest = 5; + graph.edge[8].weight = 10; + + graph.boruvkaMST(); + } + } + ``` + + + + + ```javascript + class Graph { + constructor(vertices) { + this.V = vertices; + this.edges = []; + } + + addEdge(u, v, w) { + this.edges.push([u, v, w]); + } + + find(parent, i) { + if (parent[i] === i) + return i; + return this.find(parent, parent[i]); + } + + union(parent, rank, x, y) { + let xroot = this.find(parent, x); + let yroot = this.find(parent, y); + if (rank[xroot] < rank[yroot]) + parent[xroot] = yroot; + else if (rank[xroot] > rank[yroot]) + parent[yroot] = xroot; + else { + parent[yroot] = xroot; + rank[xroot]++; + } + } + + boruvkaMST() { + let parent = []; + let rank = []; + let cheapest = []; + + let numTrees = this.V; + let MSTweight = 0; + + for (let node = 0; node < this.V; ++node) { + parent[node] = node; + rank[node] = 0; + cheapest[node] = -1; + } + + while (numTrees > 1) { + this.edges.forEach(edge => { + let [u, v, w] = edge; + let set1 = this.find(parent, u); + let set2 = this.find(parent, v); + if (set1 !== set2) { + if (cheapest[set1] === -1 || this.edges[cheapest[set1]][2] > w) + cheapest[set1] = this.edges.indexOf(edge); + if (cheapest[set2] === -1 || this.edges[cheapest[set2]][2] > w) + cheapest[set2] = this.edges.indexOf(edge); + } + }); + + for (let node = 0; node < this.V; ++node) { + if (cheapest[node] !== -1) { + let [u, v, w] = this.edges[cheapest[node]]; + let set1 = this.find(parent, u); + let set2 = this.find(parent, v); + if (set1 !== set2) { + MSTweight += w; + this.union(parent, rank, set1, set2); + numTrees--; + } + } + } + + cheapest.fill(-1); + } + + return MSTweight; + } + } + + const g = new Graph(6); + g.addEdge(0, 1, 2); + g.addEdge(0, 3, 6); + g.addEdge(1, 2, 3); + g.addEdge(1, 3, 8); + g.addEdge(1, 4, 5); + g.addEdge(2, 4, 7); + g.addEdge(2, 5, 4); + g.addEdge(3, 4, 9); + g.addEdge(4, 5, 10); + + console.log("Weight of MST is", g.boruvkaMST()); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity:** $O(E \log V)$, where $E$ is the number of edges and $V$ is the number of vertices. +- **Space Complexity:** $O(V + E)$ due to the storage required for the parent, rank, and cheapest arrays. + +## 9. Advantages and Disadvantages + +### Advantages: +- Suitable for parallel computation. +- Efficient for dense graphs. + +### Disadvantages: +- Not as straightforward to implement as other MST algorithms like Kruskal's or Prim's. + +## 10. References + +- [GeeksforGeeks - BorΕ―vka’s Algorithm](https://www.geeksforgeeks.org/boruvkas-algorithm-greedy-algo-9/) + diff --git a/docs/Algorithms/Graph Algorithms/_category_.json b/docs/Algorithms/Graph Algorithms/_category_.json new file mode 100644 index 0000000..03b28cd --- /dev/null +++ b/docs/Algorithms/Graph Algorithms/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Graph Algorithms", + "position": 11, + "link": { + "type": "generated-index", + "description": "You can find The most useful Graph Algorithms in this section" + } + } \ No newline at end of file diff --git a/docs/Algorithms/Graph Algorithms/tarjan.md b/docs/Algorithms/Graph Algorithms/tarjan.md new file mode 100644 index 0000000..2f32d38 --- /dev/null +++ b/docs/Algorithms/Graph Algorithms/tarjan.md @@ -0,0 +1,100 @@ +# Tarjan's Algorithm + +Tarjan's Algorithm is an efficient method for finding all Strongly Connected Components (SCCs) in a directed graph. An SCC is a maximal subgraph where each vertex is reachable from every other vertex in the subgraph. + +## Algorithm Description + +Tarjan's Algorithm uses Depth-First Search (DFS) to identify SCCs in a graph. It maintains a stack to keep track of the vertices in the current path and uses two arrays (or dictionaries) to store the discovery times and the lowest points reachable for each vertex. + +## Steps + +1. Perform a DFS traversal of the graph. +2. For each vertex, track the discovery time and the lowest discovery time reachable from that vertex. +3. Use a stack to keep vertices of the current DFS path. +4. When a vertex completes its DFS, check if it's the root of an SCC. If so, pop vertices from the stack to form the SCC. +5. Continue until all vertices have been processed. + +## Time Complexity + +The time complexity of Tarjan's Algorithm is O(V + E), where V is the number of vertices and E is the number of edges in the graph. + +## Python Implementation + +Here is a Python implementation of Tarjan's Algorithm: + +```python +from collections import defaultdict + +class TarjanSCC: + def __init__(self, graph): + self.graph = graph + self.V = len(graph) + self.index = 0 + self.stack = [] + self.in_stack = [False] * self.V + self.indices = [-1] * self.V + self.low_links = [-1] * self.V + self.sccs = [] + + def find_sccs(self): + for v in range(self.V): + if self.indices[v] == -1: + self._strong_connect(v) + return self.sccs + + def _strong_connect(self, v): + self.indices[v] = self.index + self.low_links[v] = self.index + self.index += 1 + self.stack.append(v) + self.in_stack[v] = True + + for w in self.graph[v]: + if self.indices[w] == -1: + self._strong_connect(w) + self.low_links[v] = min(self.low_links[v], self.low_links[w]) + elif self.in_stack[w]: + self.low_links[v] = min(self.low_links[v], self.indices[w]) + + if self.low_links[v] == self.indices[v]: + scc = [] + while True: + w = self.stack.pop() + self.in_stack[w] = False + scc.append(w) + if w == v: + break + self.sccs.append(scc) +``` +# Example usage +if __name__ == "__main__": + # Define the graph as an adjacency list + graph = defaultdict(list) + graph[0].extend([1]) + graph[1].extend([2]) + graph[2].extend([0, 3]) + graph[3].extend([4]) + graph[4].extend([5, 7]) + graph[5].extend([6]) + graph[6].extend([4]) + graph[7].extend([8]) + graph[8].extend([7]) + + # Find SCCs + tarjan = TarjanSCC(graph) + sccs = tarjan.find_sccs() + + # Print the SCCs + print("Strongly Connected Components:") + for scc in sccs: + print(scc) + +## Explanation +The TarjanSCC class initializes the graph and necessary variables. +The find_sccs method starts the DFS traversal and returns the list of SCCs. +The _strong_connect method performs the DFS, updates discovery times and low links, and identifies SCCs. +The example usage demonstrates how to define a graph, find SCCs using Tarjan's Algorithm, and print the results + +## Conclusion +Tarjan's Algorithm is an efficient and elegant solution for finding all SCCs in a directed graph. Its linear time complexity makes it suitable for large graphs, and it is widely used in applications like compiler optimization, social network analysis, and more. + diff --git a/docs/Algorithms/String-Algorithms/01-Knuth-Morris-Pratt (KMP).md b/docs/Algorithms/String-Algorithms/01-Knuth-Morris-Pratt (KMP).md new file mode 100644 index 0000000..580957e --- /dev/null +++ b/docs/Algorithms/String-Algorithms/01-Knuth-Morris-Pratt (KMP).md @@ -0,0 +1,326 @@ +--- +id: Knuth-Morris-Pratt +title: Knuth-Morris-Pratt (KMP) Algorithm (Geeks for Geeks) +sidebar_label: Knuth-Morris-Pratt (KMP) +tags: + - Intermediate + - String Matching Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Knuth-Morris-Pratt (KMP) algorithm problem on Geeks for Geeks." +--- + +## 1. What is the Knuth-Morris-Pratt (KMP) Algorithm? + +The Knuth-Morris-Pratt (KMP) algorithm is an efficient pattern matching algorithm that searches for occurrences of a $word$ $W$ within a main $text string$ $T$ by employing the observation that when a mismatch occurs, the word itself embodies sufficient information to determine where the next match could begin, thus bypassing re-examination of previously matched characters. + +## 2. Algorithm for Knuth-Morris-Pratt (KMP) + +1. Preprocess the pattern to create an array (LPS array) that stores the length of the longest prefix which is also a suffix. +2. Use the $LPS array$ to skip characters while matching. + +## 3. How does the Knuth-Morris-Pratt (KMP) Algorithm work? + +- The KMP algorithm preprocesses the pattern to determine the longest prefix which is also a suffix in the pattern itself. +- This preprocessing is used to avoid unnecessary re-evaluation of the characters in the text, making the search process more efficient. + +## 4. Problem Description + +Given a text string and a pattern string, implement the $Knuth-Morris-Pratt (KMP)$ algorithm to find all occurrences of the pattern in the text. + +## 5. Examples + +**Example 1:** +``` +Input: text = "ABABDABACDABABCABAB", pattern = "ABABCABAB" +Output: Pattern found at index 10 +``` + +**Example 2:** +``` +Input: text = "AABAACAADAABAABA", pattern = "AABA" +Output: Pattern found at index 0, Pattern found at index 9, Pattern found at index 12 +``` + +**Explanation of Example 1:** +- The pattern "ABABCABAB" is found in the text "ABABDABACDABABCABAB" starting from index 10. + +## Visual Example + +![Visual Example of KMP](../../../assets/KMP_algo.png) + +## 6. Constraints + +- The text and pattern can contain any number of characters. +- All characters are $ASCII$ characters. + +## 7. Implementation + + + + + ```python + def KMPSearch(pat, txt): + M = len(pat) + N = len(txt) + + lps = [0] * M + j = 0 + + computeLPSArray(pat, M, lps) + + i = 0 + while i < N: + if pat[j] == txt[i]: + i += 1 + j += 1 + + if j == M: + print("Found pattern at index " + str(i - j)) + j = lps[j - 1] + elif i < N and pat[j] != txt[i]: + if j != 0: + j = lps[j - 1] + else: + i += 1 + + def computeLPSArray(pat, M, lps): + length = 0 + lps[0] = 0 + i = 1 + + while i < M: + if pat[i] == pat[length]: + length += 1 + lps[i] = length + i += 1 + else: + if length != 0: + length = lps[length - 1] + else: + lps[i] = 0 + i += 1 + + # Example usage: + text = "ABABDABACDABABCABAB" + pattern = "ABABCABAB" + KMPSearch(pattern, text) + ``` + + + + + ```cpp + #include + #include + using namespace std; + + void computeLPSArray(string pat, int M, vector& lps) { + int length = 0; + lps[0] = 0; + int i = 1; + + while (i < M) { + if (pat[i] == pat[length]) { + length++; + lps[i] = length; + i++; + } else { + if (length != 0) { + length = lps[length - 1]; + } else { + lps[i] = 0; + i++; + } + } + } + } + + void KMPSearch(string pat, string txt) { + int M = pat.size(); + int N = txt.size(); + + vector lps(M); + computeLPSArray(pat, M, lps); + + int i = 0; + int j = 0; + while (i < N) { + if (pat[j] == txt[i]) { + i++; + j++; + } + + if (j == M) { + cout << "Found pattern at index " << (i - j) << endl; + j = lps[j - 1]; + } else if (i < N && pat[j] != txt[i]) { + if (j != 0) { + j = lps[j - 1]; + } else { + i++; + } + } + } + } + + int main() { + string txt = "ABABDABACDABABCABAB"; + string pat = "ABABCABAB"; + KMPSearch(pat, txt); + return 0; + } + ``` + + + + + ```java + public class KMPAlgorithm { + void KMPSearch(String pat, String txt) { + int M = pat.length(); + int N = txt.length(); + + int lps[] = new int[M]; + int j = 0; + + computeLPSArray(pat, M, lps); + + int i = 0; + while (i < N) { + if (pat.charAt(j) == txt.charAt(i)) { + i++; + j++; + } + if (j == M) { + System.out.println("Found pattern at index " + (i - j)); + j = lps[j - 1]; + } else if (i < N && pat.charAt(j) != txt.charAt(i)) { + if (j != 0) + j = lps[j - 1]; + else + i++; + } + } + } + + void computeLPSArray(String pat, int M, int lps[]) { + int len = 0; + int i = 1; + lps[0] = 0; + + while (i < M) { + if (pat.charAt(i) == pat.charAt(len)) { + len++; + lps[i] = len; + i++; + } else { + if (len != 0) { + len = lps[len - 1]; + } else { + lps[i] = 0; + i++; + } + } + } + } + + public static void main(String args[]) { + String txt = "ABABDABACDABABCABAB"; + String pat = "ABABCABAB"; + new KMPAlgorithm().KMPSearch(pat, txt); + } + } + ``` + + + + + ```javascript + function KMPSearch(pat, txt) { + const M = pat.length; + const N = txt.length; + + const lps = new Array(M).fill(0); + computeLPSArray(pat, M, lps); + + let i = 0; + let j = 0; + while (i < N) { + if (pat[j] === txt[i]) { + i++; + j++; + } + if (j === M) { + console.log("Found pattern at index " + (i - j)); + j = lps[j - 1]; + } else if (i < N && pat[j] !== txt[i]) { + if (j !== 0) { + j = lps[j - 1]; + } else { + i++; + } + } + } + } + + function computeLPSArray(pat, M, lps) { + let length = 0; + let i = 1; + + lps[0] = 0; + + while (i < M) { + if (pat[i] === pat[length]) { + length++; + lps[i] = length; + i++; + } else { + if (length !== 0) { + length = lps[length - 1]; + } else { + lps[i] = 0; + i++; + } + } + } + } + + // Example usage: + const text = "ABABDABACDABABCABAB"; + const + + pattern = "ABABCABAB"; + KMPSearch(pattern, text); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: + - Preprocessing the LPS array: $O(M)$ + - Searching the pattern in the text: $O(N)$ + - Overall: $O(M + N)$ + +- **Space Complexity**: $O(M)$ for the LPS array. + +## 9. Advantages and Disadvantages + +**Advantages:** +- More efficient than the naive pattern matching algorithm, especially for large texts. +- Avoids redundant comparisons. + +**Disadvantages:** +- Slightly more complex to implement than naive algorithms. +- Requires additional space for the LPS array. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/kmp-algorithm/problem) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) \ No newline at end of file diff --git a/docs/Algorithms/String-Algorithms/02-Rabin-Karp Algorithm.md b/docs/Algorithms/String-Algorithms/02-Rabin-Karp Algorithm.md new file mode 100644 index 0000000..e374f14 --- /dev/null +++ b/docs/Algorithms/String-Algorithms/02-Rabin-Karp Algorithm.md @@ -0,0 +1,294 @@ +--- +id: Rabin-Karp +title: Rabin-Karp Algorithm (Geeks for Geeks) +sidebar_label: Rabin-Karp +tags: + - Intermediate + - String Matching Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Rabin-Karp algorithm problem on Geeks for Geeks." +--- + +## 1. What is the Rabin-Karp Algorithm? + +The Rabin-Karp algorithm is a string-searching algorithm that uses hashing to find an exact match of a pattern string within a text string. It is particularly effective when dealing with multiple pattern searches in the same text. + +## 2. Algorithm for Rabin-Karp + +1. Compute the hash value of the pattern. +2. Compute the hash value of the first window of text. +3. Slide the pattern over the text one character at a time, updating the hash value. +4. Compare the hash values, and if they match, check the actual substring to ensure there is no hash collision. + +## 3. How does the Rabin-Karp Algorithm work? + +- The algorithm uses a hash function to convert the current substring of text and the pattern into numerical values. +- By sliding the pattern over the text, the hash value of the current substring is updated efficiently using a rolling hash technique. +- When the hash values of the pattern and the current substring match, a detailed comparison is done to confirm the match. + +## Difference Between KMP and Rabin-Karp + +Table format for the differences between KMP and Rabin-Karp algorithms: + +| **Criteria** | **KMP Algorithm** | **Rabin-Karp Algorithm** | +|---------------------|-----------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------| +| **Approach** | Uses the LPS (Longest Prefix Suffix) array to skip comparisons. | Uses hashing to compare the pattern with substrings of the text. | +| **Time Complexity** | O(N + M): Preprocessing O(M), Searching O(N). | Average: O(N + M), Worst: O(N * M) due to hash collisions. | +| **Space Complexity**| O(M) for the LPS array. | O(1) for rolling hash calculation. | +| **Use Case** | Best for patterns and texts with many repeated sub-patterns. | Suitable for multiple pattern searches in a single text. | +| **Advantages** | No hash collisions; guarantees linear time complexity. | Efficient average performance; good for multiple patterns. | +| **Disadvantages** | Complex to implement due to the LPS array construction. | Performance can degrade to O(N * M) due to hash collisions. | + + + +## 4. Problem Description + +Given a text string and a pattern string, implement the Rabin-Karp algorithm to find all occurrences of the pattern in the text. + +## 5. Examples + +**Example 1:** +``` +Input: text = "GEEKS FOR GEEKS", pattern = "GEEK" +Output: Pattern found at index 0, Pattern found at index 10 +``` + +**Example 2:** +``` +Input: text = "ABABDABACDABABCABAB", pattern = "ABAB" +Output: Pattern found at index 0, Pattern found at index 10, Pattern found at index 12 +``` + +**Explanation of Example 1:** +- The pattern "GEEK" is found in the text "GEEKS FOR GEEKS" starting from index 0 and index 10. + +## 6. Constraints + +- $The text and pattern can contain any number of characters.$ +- $All characters are ASCII characters.$ + +## 7. Implementation + + + + + ```python + d = 256 + q = 101 + + def search(pat, txt): + M = len(pat) + N = len(txt) + i = 0 + j = 0 + p = 0 + t = 0 + h = 1 + + for i in range(M-1): + h = (h * d) % q + + for i in range(M): + p = (d * p + ord(pat[i])) % q + t = (d * t + ord(txt[i])) % q + + for i in range(N - M + 1): + if p == t: + for j in range(M): + if txt[i + j] != pat[j]: + break + + j += 1 + if j == M: + print("Pattern found at index " + str(i)) + + if i < N - M: + t = (d * (t - ord(txt[i]) * h) + ord(txt[i + M])) % q + if t < 0: + t = t + q + + # Example usage: + text = "GEEKS FOR GEEKS" + pattern = "GEEK" + search(pattern, text) + ``` + + + + + ```cpp + #include + #include + using namespace std; + + #define d 256 + + void search(string pat, string txt, int q) { + int M = pat.size(); + int N = txt.size(); + int i, j; + int p = 0; + int t = 0; + int h = 1; + + for (i = 0; i < M - 1; i++) + h = (h * d) % q; + + for (i = 0; i < M; i++) { + p = (d * p + pat[i]) % q; + t = (d * t + txt[i]) % q; + } + + for (i = 0; i <= N - M; i++) { + if (p == t) { + for (j = 0; j < M; j++) { + if (txt[i + j] != pat[j]) + break; + } + if (j == M) + cout << "Pattern found at index " << i << endl; + } + if (i < N - M) { + t = (d * (t - txt[i] * h) + txt[i + M]) % q; + if ( t < 0) + t = (t + q); + } + } + } + + int main() { + string txt = "GEEKS FOR GEEKS"; + string pat = "GEEK"; + int q = 101; + search(pat, txt, q); + return 0; + } + ``` + + + + + ```java + public class RabinKarp { + public final static int d = 256; + + static void search(String pat, String txt, int q) { + int M = pat.length(); + int N = txt.length(); + int i, j; + int p = 0; + int t = 0; + int h = 1; + + for (i = 0; i < M - 1; i++) + h = (h * d) % q; + + for (i = 0; i < M; i++) { + p = (d * p + pat.charAt(i)) % q; + t = (d * t + txt.charAt(i)) % q; + } + + for (i = 0; i <= N - M; i++) { + if (p == t) { + for (j = 0; j < M; j++) { + if (txt.charAt(i + j) != pat.charAt(j)) + break; + } + if (j == M) + System.out.println("Pattern found at index " + i); + } + if (i < N - M) { + t = (d * (t - txt.charAt(i) * h) + txt.charAt(i + M)) % q; + if (t < 0) + t = (t + q); + } + } + } + + public static void main(String[] args) { + String txt = "GEEKS FOR GEEKS"; + String pat = "GEEK"; + int q = 101; + search(pat, txt, q); + } + } + ``` + + + + + ```javascript + const d = 256; + const q = 101; + + function search(pat, txt) { + let M = pat.length; + let N = txt.length; + let i, j; + let p = 0; + let t = 0; + let h = 1; + + for (i = 0; i < M - 1; i++) + h = (h * d) % q; + + for (i = 0; i < M; i++) { + p = (d * p + pat.charCodeAt(i)) % q; + t = (d * t + txt.charCodeAt(i)) % q; + } + + for (i = 0; i <= N - M; i++) { + if (p == t) { + for (j = 0; j < M; j++) { + if (txt.charAt(i + j) !== pat.charAt(j)) + break; + } + if (j == M) + console.log("Pattern found at index " + i); + } + if (i < N - M) { + t = (d * (t - txt.charCodeAt(i) * h) + txt.charCodeAt(i + M)) % q; + if (t < 0) + t = (t + q); + } + } + } + + // Example usage: + const text = "GEEKS FOR GEEKS"; + const pattern = "GEEK"; + search(pattern, text); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: + - Average and Best Case: $O(N + M)$ + - Worst Case: $O(N * M)$ (due to hash collisions) + +- **Space Complexity**: $O(1)$ for the rolling hash calculation. + +## 9. Advantages and Disadvantages + +**Advantages:** +- Efficient on average with good hash functions. +- Suitable for multiple pattern searches in a single text. + +**Disadvantages + +:** +- Hash collisions can degrade performance to $O(N * M)$. +- Requires a good hash function to minimize collisions. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/rabin-karp-algorithm-for-pattern-searching/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/rabin-karp/problem) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) \ No newline at end of file diff --git a/docs/Algorithms/String-Algorithms/03-Z-Algorithm.md b/docs/Algorithms/String-Algorithms/03-Z-Algorithm.md new file mode 100644 index 0000000..3092170 --- /dev/null +++ b/docs/Algorithms/String-Algorithms/03-Z-Algorithm.md @@ -0,0 +1,392 @@ +--- +id: Z Algorithm +title: Z Algorithm +sidebar_label: Z-Algorithm +tags: + - Intermediate + - String Matching Algorithms + - CPP + - Python + - Java + - DSA +description: "This is a solution for the string matching in linear time using Z algorithm." +--- + +## 1. What is the Z Algorithm? + +This algorithm finds all occurrences of a pattern in a text in linear time. Let length of text be n and of pattern be m, then total time taken is `O(m + n)` with linear space complexity. Now we can see that both time and space complexity is same as KMP algorithm but this algorithm is Simpler to understand. +In this algorithm, we construct a Z array. + +## 2. What is Z Array? + +For a string `str[0..n-1]`, Z array is of same length as string. An element Z[i] of Z array stores length of the longest substring starting from `str[i]` which is also a prefix of `str[0..n-1]`. The first entry of Z array is meaning less as complete string is always prefix of itself. + +#### Examples +``` +Index 0 1 2 3 4 5 6 7 8 9 10 11 +Text a a b c a a b x a a a z +Z values X 1 0 0 3 1 0 0 2 2 1 0 +``` +## 3. How to construct Z array? + +A Simple Solution is to run two nested loops, the outer loop goes to every index and the inner loop finds length of the longest prefix that matches the substring starting at the current index. The time complexity of this solution is $O(n2)$. + We can construct Z array in linear time. + +``` +The idea is to maintain an interval [L, R] which is the interval with max R +such that [L,R] is prefix substring (substring which is also prefix). + +Steps for maintaining this interval are as follows – + +1) If i > R then there is no prefix substring that starts before i and + ends after i, so we reset L and R and compute new [L,R] by comparing + str[0..] to str[i..] and get Z[i] (= R-L+1). + +2) If i <= R then let K = i-L, now Z[i] >= min(Z[K], R-i+1) because + str[i..] matches with str[K..] for atleast R-i+1 characters (they are in + [L,R] interval which we know is a prefix substring). + Now two sub cases arise – + a) If Z[K] < R-i+1 then there is no prefix substring starting at + str[i] (otherwise Z[K] would be larger) so Z[i] = Z[K] and + interval [L,R] remains same. + b) If Z[K] >= R-i+1 then it is possible to extend the [L,R] interval + thus we will set L as i and start matching from str[R] onwards and + get new R then we will update interval [L,R] and calculate Z[i] (=R-L+1). + +``` + + + + +## 4. Problem Description + +Given a text string and a pattern string, implement the Z algorithm to find all occurrences of the pattern in the text. + +## 5. Examples + +**Example 1:** +``` +Input: text = "GEEKS FOR GEEKS", pattern = "GEEK" +Output: Pattern found at index 0, Pattern found at index 10 +``` + +**Example 2:** +``` +Input: text = "ABABDABACDABABCABAB", pattern = "ABAB" +Output: Pattern found at index 0, Pattern found at index 10, Pattern found at index 12 +``` + +**Explanation of Example 1:** +- The pattern "GEEK" is found in the text "GEEKS FOR GEEKS" starting from index 0 and index 10. + +## 6. Constraints + +- $The text and pattern can contain any number of characters.$ +- $All characters are ASCII characters.$ + +## 7. Implementation + + + + ```python + def getZarr(string, z): + n = len(string) + + # [L,R] make a window which matches + # with prefix of s + l, r, k = 0, 0, 0 + for i in range(1, n): + + # if i>R nothing matches so we will calculate. + # Z[i] using naive way. + if i > r: + l, r = i, i + + # R-L = 0 in starting, so it will start + # checking from 0'th index. For example, + # for "ababab" and i = 1, the value of R + # remains 0 and Z[i] becomes 0. For string + # "aaaaaa" and i = 1, Z[i] and R become 5 + while r < n and string[r - l] == string[r]: + r += 1 + z[i] = r - l + r -= 1 + else: + + # k = i-L so k corresponds to number which + # matches in [L,R] interval. + k = i - l + + # if Z[k] is less than remaining interval + # then Z[i] will be equal to Z[k]. + # For example, str = "ababab", i = 3, R = 5 + # and L = 2 + if z[k] < r - i + 1: + z[i] = z[k] + + # For example str = "aaaaaa" and i = 2, + # R is 5, L is 0 + else: + + # else start from R and check manually + l = i + while r < n and string[r - l] == string[r]: + r += 1 + z[i] = r - l + r -= 1 + +# prints all occurrences of pattern +# in text using Z algo +def search(text, pattern): + + # Create concatenated string "P$T" + concat = pattern + "$" + text + l = len(concat) + + # Construct Z array + z = [0] * l + getZarr(concat, z) + + # now looping through Z array for matching condition + for i in range(l): + + # if Z[i] (matched region) is equal to pattern + # length we got the pattern + if z[i] == len(pattern): + print("Pattern found at index", + i - len(pattern) - 1) + + + if __name__ == "__main__": + text = "GEEKS FOR GEEKS" + pattern = "GEEK" + search(text, pattern) + + +``` + + + + ```cpp +#include +using namespace std; + +void getZarr(string str, int Z[]); + +// prints all occurrences of pattern in text using Z algo +void search(string text, string pattern) +{ + // Create concatenated string "P$T" + string concat = pattern + "$" + text; + int l = concat.length(); + + // Construct Z array + int Z[l]; + getZarr(concat, Z); + + // now looping through Z array for matching condition + for (int i = 0; i < l; ++i) + { + // if Z[i] (matched region) is equal to pattern + // length we got the pattern + if (Z[i] == pattern.length()) + cout << "Pattern found at index " + << i - pattern.length() -1 << endl; + } +} + +// Fills Z array for given string str[] +void getZarr(string str, int Z[]) +{ + int n = str.length(); + int L, R, k; + + // [L,R] make a window which matches with prefix of s + L = R = 0; + for (int i = 1; i < n; ++i) + { + // if i>R nothing matches so we will calculate. + // Z[i] using naive way. + if (i > R) + { + L = R = i; + + // R-L = 0 in starting, so it will start + // checking from 0'th index. For example, + // for "ababab" and i = 1, the value of R + // remains 0 and Z[i] becomes 0. For string + // "aaaaaa" and i = 1, Z[i] and R become 5 + while (R + + + ```java + +class GFG { + + // prints all occurrences of pattern in text using + // Z algo + public static void search(String text, String pattern) + { + + // Create concatenated string "P$T" + String concat = pattern + "$" + text; + + int l = concat.length(); + + int Z[] = new int[l]; + + // Construct Z array + getZarr(concat, Z); + + // now looping through Z array for matching condition + for(int i = 0; i < l; ++i){ + + // if Z[i] (matched region) is equal to pattern + // length we got the pattern + + if(Z[i] == pattern.length()){ + System.out.println("Pattern found at index " + + (i - pattern.length() - 1)); + } + } + } + + // Fills Z array for given string str[] + private static void getZarr(String str, int[] Z) { + + int n = str.length(); + + // [L,R] make a window which matches with + // prefix of s + int L = 0, R = 0; + + for(int i = 1; i < n; ++i) { + + // if i>R nothing matches so we will calculate. + // Z[i] using naive way. + if(i > R){ + + L = R = i; + + // R-L = 0 in starting, so it will start + // checking from 0'th index. For example, + // for "ababab" and i = 1, the value of R + // remains 0 and Z[i] becomes 0. For string + // "aaaaaa" and i = 1, Z[i] and R become 5 + + while(R < n && str.charAt(R - L) == str.charAt(R)) + R++; + + Z[i] = R - L; + R--; + + } + else{ + + // k = i-L so k corresponds to number which + // matches in [L,R] interval. + int k = i - L; + + // if Z[k] is less than remaining interval + // then Z[i] will be equal to Z[k]. + // For example, str = "ababab", i = 3, R = 5 + // and L = 2 + if(Z[k] < R - i + 1) + Z[i] = Z[k]; + + // For example str = "aaaaaa" and i = 2, R is 5, + // L is 0 + else{ + + + // else start from R and check manually + L = i; + while(R < n && str.charAt(R - L) == str.charAt(R)) + R++; + + Z[i] = R - L; + R--; + } + } + } + } + + // Driver program + public static void main(String[] args) + { + String text = "GEEKS FOR GEEKS"; + String pattern = "GEEK"; + + search(text, pattern); + } +} + + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: + - Average and Best Case: $O(N + M)$ + +- **Space Complexity**: $O(N)$ . + +## 9. Advantages and Disadvantages + +**Advantages:** +- Efficient on average with good hash functions. +- Suitable for multiple pattern searches in a single text. + +**Disadvantages + +:** +- Hash collisions can degrade performance to $O(N * M)$. +- Requires a good hash function to minimize collisions. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/z-algorithm-linear-time-pattern-searching-algorithm/) diff --git a/docs/Algorithms/String-Algorithms/04-Boyer-Moore-Algorithm.md b/docs/Algorithms/String-Algorithms/04-Boyer-Moore-Algorithm.md new file mode 100644 index 0000000..28e31a0 --- /dev/null +++ b/docs/Algorithms/String-Algorithms/04-Boyer-Moore-Algorithm.md @@ -0,0 +1,251 @@ +--- +id: Boyer-Moore +title: Boyer-Moore Algorithm (Geeks for Geeks) +sidebar_label: Boyer-Moore +tags: + - Advanced + - String Matching Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Boyer-Moore algorithm problem on Geeks for Geeks." +--- + +## 1. What is the Boyer-Moore Algorithm? + +The Boyer-Moore algorithm is an efficient string searching algorithm that skips sections of the text to find the pattern, making it faster than many other algorithms. It uses two main heuristics: the Bad Character Rule and the Good Suffix Rule, which allow it to skip over sections of the text that do not need to be checked. + +## 2. Algorithm for Boyer-Moore + +1. Preprocess the pattern to create two arrays (Bad Character and Good Suffix). +2. Use these arrays to skip characters while matching the pattern with the text. + +## 3. How does the Boyer-Moore Algorithm work? + +- **Bad Character Rule**: When a mismatch occurs, the character in the text causing the mismatch is used to shift the pattern. +- **Good Suffix Rule**: When a mismatch occurs, the pattern is shifted to align with the next possible match of the good suffix (the portion of the pattern that matched just before the mismatch). + +## 4. Problem Description + +Given a text string and a pattern string, implement the $Boyer-Moore$ algorithm to find all occurrences of the pattern in the text. + +## 5. Examples + +**Example 1:** +``` +Input: text = "ABABDABACDABABCABAB", pattern = "ABABCABAB" +Output: Pattern found at index 10 +``` + +**Example 2:** +``` +Input: text = "AABAACAADAABAABA", pattern = "AABA" +Output: Pattern found at index 0, Pattern found at index 9, Pattern found at index 12 +``` + +**Explanation of Example 1:** +- The pattern "ABABCABAB" is found in the text "ABABDABACDABABCABAB" starting from index 10. + +## Visual Example + +![Visual Example of Boyer-Moore](../../../assets/Boyer_Moore_algo.png) + +## 6. Constraints + +- The text and pattern can contain any number of characters. +- All characters are $ASCII$ characters. + +## 7. Implementation + + + + + +```python + def bad_char_heuristic(pattern): + bad_char = [-1] * 256 + for i in range(len(pattern)): + bad_char[ord(pattern[i])] = i + return bad_char + + def boyer_moore_search(text, pattern): + m = len(pattern) + n = len(text) + bad_char = bad_char_heuristic(pattern) + + s = 0 + while s <= n - m: + j = m - 1 + while j >= 0 and pattern[j] == text[s + j]: + j -= 1 + if j < 0: + print("Pattern found at index " + str(s)) + s += (m - bad_char[ord(text[s + m])] if s + m < n else 1) + else: + s += max(1, j - bad_char[ord(text[s + j])]) + + + # Example usage + text = "ABABDABACDABABCABAB" + pattern = "ABABCABAB" + boyer_moore_search(text, pattern) + +``` + + + + + + +```cpp + #include + #include + using namespace std; + + void badCharHeuristic(string str, int size, int badchar[256]) { + for (int i = 0; i < 256; i++) + badchar[i] = -1; + for (int i = 0; i < size; i++) + badchar[(int) str[i]] = i; + } + + void boyerMooreSearch(string txt, string pat) { + int m = pat.size(); + int n = txt.size(); + + int badchar[256]; + badCharHeuristic(pat, m, badchar); + + int s = 0; + while (s <= (n - m)) { + int j = m - 1; + while (j >= 0 && pat[j] == txt[s + j]) + j--; + if (j < 0) { + cout << "Pattern found at index " << s << endl; + s += (s + m < n) ? m - badchar[txt[s + m]] : 1; + } else + s += max(1, j - badchar[txt[s + j]]); + } + } + + int main() { + string txt = "ABABDABACDABABCABAB"; + string pat = "ABABCABAB"; + boyerMooreSearch(txt, pat); + return 0; + } + ``` + + + + + + ```java + + public class BoyerMooreAlgorithm { + void badCharHeuristic(char[] str, int size, int badchar[]) { + for (int i = 0; i < 256; i++) + badchar[i] = -1; + for (int i = 0; i < size; i++) + badchar[(int) str[i]] = i; + } + + void boyerMooreSearch(char txt[], char pat[]) { + int m = pat.length; + int n = txt.length; + + int badchar[] = new int[256]; + badCharHeuristic(pat, m, badchar); + + int s = 0; + while (s <= (n - m)) { + int j = m - 1; + while (j >= 0 && pat[j] == txt[s + j]) + j--; + if (j < 0) { + System.out.println("Pattern found at index " + s); + s += (s + m < n) ? m - badchar[txt[s + m]] : 1; + } else + s += Math.max(1, j - badchar[txt[s + j]]); + } + } + + public static void main(String[] args) { + BoyerMooreAlgorithm bm = new BoyerMooreAlgorithm(); + String txt = "ABABDABACDABABCABAB"; + String pat = "ABABCABAB"; + bm.boyerMooreSearch(txt.toCharArray(), pat.toCharArray()); + } + } + +``` + + + + + + ```javascript + + function badCharHeuristic(str, size) { + const badChar = new Array(256).fill(-1); + for (let i = 0; i < size; i++) { + badChar[str.charCodeAt(i)] = i; + } + return badChar; + } + + function boyerMooreSearch(txt, pat) { + const m = pat.length; + const n = txt.length; + const badChar = badCharHeuristic(pat, m); + + let s = 0; + while (s <= (n - m)) { + let j = m - 1; + while (j >= 0 && pat[j] === txt[s + j]) + j--; + if (j < 0) { + console.log("Pattern found at index " + s); + s += (s + m < n) ? m - badChar[txt.charCodeAt(s + m)] : 1; + } else + s += Math.max(1, j - badChar[txt.charCodeAt(s + j)]); + } + } + + // Example usage: + const text = "ABABDABACDABABCABAB"; + const pattern = "ABABCABAB"; + boyerMooreSearch(text, pattern); + +``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: + - Preprocessing the Bad Character and Good Suffix tables: $O(m + |Ξ£|)$, where $m$ is the length of the pattern and $|Ξ£|$ is the size of the alphabet. + - Searching the pattern in the text: $O(n)$ in the best case and $O(mn)$ in the worst case, where $n$ is the length of the text. + - Overall: Efficient in practice with average time complexity $O(n/m)$. + +- **Space Complexity**: $O(m + |Ξ£|)$ for the Bad Character and Good Suffix tables. + +## 9. Advantages and Disadvantages + +**Advantages:** +- Very efficient for large texts with small patterns. +- Uses heuristics to skip sections of the text, making it faster than many other algorithms. + +**Disadvantages:** +- More complex to implement compared to simpler algorithms like the Naive Pattern Matching algorithm. +- The worst-case time complexity can be higher for certain patterns and texts. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/boyer-moore-algorithm-for-pattern-searching/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/save-humanity/problem) +- **Author's Geeks for Geeks Profile:** Aarti_Rathi diff --git a/docs/Algorithms/String-Algorithms/05-Naive-Pattern-Matching.md b/docs/Algorithms/String-Algorithms/05-Naive-Pattern-Matching.md new file mode 100644 index 0000000..b7dcfe4 --- /dev/null +++ b/docs/Algorithms/String-Algorithms/05-Naive-Pattern-Matching.md @@ -0,0 +1,216 @@ +--- +id: Naive-Pattern-Matching +title: Naive Pattern Matching Algorithm (Geeks for Geeks) +sidebar_label: Naive Pattern Matching +tags: + - Basic + - String Matching Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Naive Pattern Matching algorithm problem on Geeks for Geeks." +--- + +## 1. What is the Naive Pattern Matching Algorithm? + +The Naive Pattern Matching algorithm is a straightforward approach for finding occurrences of a pattern string within a text string. It compares the pattern to each substring of the text and checks for a match. + +## 2. Algorithm for Naive Pattern Matching + +1. Loop through the text, and for each position in the text, check if the pattern matches the substring starting at that position. +2. If a match is found, record the starting index of the match. + +## 3. How does the Naive Pattern Matching Algorithm work? + +- For each position in the text, compare the substring of the text starting at that position with the pattern. +- If the pattern matches the substring, record the starting index. +- Continue this process until the end of the text is reached. + +## 4. Problem Description + +Given a text string and a pattern string, implement the Naive Pattern Matching algorithm to find all occurrences of the pattern in the text. + +## 5. Examples + +**Example 1:** +``` +Input: text = "THIS IS A TEST TEXT", pattern = "TEST" +Output: Pattern found at index 10 +``` + +**Example 2:** +``` +Input: text = "AABAACAADAABAABA", pattern = "AABA" +Output: Pattern found at index 0, Pattern found at index 9, Pattern found at index 12 +``` + +**Explanation of Example 1:** +- The pattern "TEST" is found in the text "THIS IS A TEST TEXT" at index 10. + +## Visual Example + +![Visual Example of Naive Pattern Matching](../../../assets/Naive_Pattern_Matching_algo.png) + +## 6. Constraints + +- The text and pattern can contain any number of characters. +- All characters are $ASCII$ characters. + +## 7. Implementation + + + + + +```python +def naive_pattern_search(text, pattern): + n = len(text) + m = len(pattern) + + for i in range(n - m + 1): + j = 0 + while j < m and text[i + j] == pattern[j]: + j += 1 + if j == m: + print(f"Pattern found at index {i}") + +# Example usage +text = "THIS IS A TEST TEXT" +pattern = "TEST" +naive_pattern_search(text, pattern) + +text = "AABAACAADAABAABA" +pattern = "AABA" +naive_pattern_search(text, pattern) +``` + + + + + + +```cpp +#include +#include +using namespace std; + +void naivePatternSearch(string txt, string pat) { + int n = txt.size(); + int m = pat.size(); + + for (int i = 0; i <= n - m; i++) { + int j; + for (j = 0; j < m; j++) + if (txt[i + j] != pat[j]) + break; + + if (j == m) + cout << "Pattern found at index " << i << endl; + } +} + +int main() { + string txt = "THIS IS A TEST TEXT"; + string pat = "TEST"; + naivePatternSearch(txt, pat); + + txt = "AABAACAADAABAABA"; + pat = "AABA"; + naivePatternSearch(txt, pat); + return 0; +} +``` + + + + + +```java +public class NaivePatternMatching { + static void naivePatternSearch(String txt, String pat) { + int n = txt.length(); + int m = pat.length(); + + for (int i = 0; i <= n - m; i++) { + int j; + for (j = 0; j < m; j++) + if (txt.charAt(i + j) != pat.charAt(j)) + break; + + if (j == m) + System.out.println("Pattern found at index " + i); + } + } + + public static void main(String[] args) { + String txt = "THIS IS A TEST TEXT"; + String pat = "TEST"; + naivePatternSearch(txt, pat); + + txt = "AABAACAADAABAABA"; + pat = "AABA"; + naivePatternSearch(txt, pat); + } +} +``` + + + + + +```javascript +function naivePatternSearch(txt, pat) { + const n = txt.length; + const m = pat.length; + + for (let i = 0; i <= n - m; i++) { + let j; + for (j = 0; j < m; j++) { + if (txt[i + j] !== pat[j]) { + break; + } + } + if (j === m) { + console.log(`Pattern found at index ${i}`); + } + } +} + +// Example usage: +let text = "THIS IS A TEST TEXT"; +let pattern = "TEST"; +naivePatternSearch(text, pattern); + +text = "AABAACAADAABAABA"; +pattern = "AABA"; +naivePatternSearch(text, pattern); +``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: + - Worst-case: $O((n-m+1) \cdot m)$, where $n$ is the length of the text and $m$ is the length of the pattern. + - Best-case: $O(n - m + 1)$ when all characters of the pattern are different. + +- **Space Complexity**: $O(1)$ as it uses a constant amount of extra space. + +## 9. Advantages and Disadvantages + +**Advantages:** +- Simple and easy to understand and implement. +- No preprocessing required. + +**Disadvantages:** +- Inefficient for large texts and patterns with many repeated characters. +- Higher time complexity compared to more advanced algorithms like Boyer-Moore and KMP. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/naive-algorithm-for-pattern-searching/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/kmp-fp/problem) +- **Author's Geeks for Geeks Profile:** GeeksforGeeks diff --git a/docs/Algorithms/String-Algorithms/06-Aho-Corasick-Algorithm.md b/docs/Algorithms/String-Algorithms/06-Aho-Corasick-Algorithm.md new file mode 100644 index 0000000..cc9f6be --- /dev/null +++ b/docs/Algorithms/String-Algorithms/06-Aho-Corasick-Algorithm.md @@ -0,0 +1,407 @@ +--- +id: Aho-Corasick +title: Aho-Corasick Algorithm (Geeks for Geeks) +sidebar_label: Aho-Corasick +tags: + - Advanced + - String Matching Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Aho-Corasick algorithm problem on Geeks for Geeks." +--- + +## 1. What is the Aho-Corasick Algorithm? + +The Aho-Corasick algorithm is a powerful and efficient string searching algorithm that can locate multiple patterns in a text simultaneously. It constructs a finite state machine that resembles a digital tree with additional links between nodes to allow fast transitions between different patterns. + +## 2. Algorithm for Aho-Corasick + +1. Build a Trie from the set of patterns. +2. Construct failure links to allow the algorithm to skip unnecessary comparisons. +3. Traverse the text using the Trie and the failure links to find all occurrences of the patterns. + +## 3. How does the Aho-Corasick Algorithm work? + +- **Trie Construction**: Insert all the patterns into a Trie. +- **Failure Links**: Create links that enable skipping sections of the Trie that do not match the current character in the text. +- **Search**: Traverse the text using the Trie, following the failure links whenever a mismatch occurs. + +## 4. Problem Description + +Given a text string and multiple pattern strings, implement the $Aho-Corasick$ algorithm to find all occurrences of the patterns in the text. + +## 5. Examples + +**Example 1:** +``` +Input: text = "THIS IS A TEST TEXT", patterns = ["TEST", "TEXT"] +Output: Pattern 'TEST' found at index 10 + Pattern 'TEXT' found at index 15 +``` + +**Example 2:** +``` +Input: text = "AABAACAADAABAABA", patterns = ["AABA", "CAAD"] +Output: Pattern 'AABA' found at index 0 + Pattern 'AABA' found at index 9 + Pattern 'AABA' found at index 12 + Pattern 'CAAD' found at index 5 +``` + +**Explanation of Example 1:** +- The patterns "TEST" and "TEXT" are found in the text "THIS IS A TEST TEXT" starting from index 10 and 15, respectively. + +## Visual Example + +![Visual Example of Aho-Corasick](../../../assets/Aho_Corasick_algo.png) + +## 6. Constraints + +- The text and patterns can contain any number of characters. +- All characters are $ASCII$ characters. + +## 7. Implementation + + + + + +```python +from collections import deque, defaultdict + +class AhoCorasick: + def __init__(self, keywords): + self.trie = {} + self.out = defaultdict(list) + self.fail = {} + self.build_trie(keywords) + self.build_automaton() + + def build_trie(self, keywords): + for keyword in keywords: + node = self.trie + for char in keyword: + node = node.setdefault(char, {}) + node['#'] = keyword + + def build_automaton(self): + queue = deque() + for key in self.trie: + self.fail[key] = self.trie + queue.append(key) + while queue: + current = queue.popleft() + for key in self.trie[current]: + if key == '#': + continue + fail_node = self.fail[current] + while key not in fail_node and fail_node is not self.trie: + fail_node = self.fail[fail_node] + self.fail[key] = fail_node.get(key, self.trie) + queue.append(key) + self.out[current].extend(self.out[self.fail[current]]) + if '#' in self.trie[current]: + self.out[current].append(self.trie[current]['#']) + + def search(self, text): + node = self.trie + for i, char in enumerate(text): + while char not in node and node is not self.trie: + node = self.fail[node] + node = node.get(char, self.trie) + if '#' in node: + print(f"Pattern '{node['#']}' found at index {i - len(node['#']) + 1}") + +# Example usage: +text = "THIS IS A TEST TEXT" +patterns = ["TEST", "TEXT"] +ac = AhoCorasick(patterns) +ac.search(text) +``` + + + + + + +```cpp +#include +#include +#include +#include +using namespace std; + +class AhoCorasick { + struct TrieNode { + unordered_map children; + TrieNode* fail; + vector output; + }; + TrieNode* root; + +public: + AhoCorasick(const vector& keywords) { + root = new TrieNode(); + buildTrie(keywords); + buildAutomaton(); + } + + void buildTrie(const vector& keywords) { + for (const auto& keyword : keywords) { + TrieNode* node = root; + for (char c : keyword) { + if (node->children.find(c) == node->children.end()) { + node->children[c] = new TrieNode(); + } + node = node->children[c]; + } + node->output.push_back(keyword); + } + } + + void buildAutomaton() { + queue q; + root->fail = root; + for (auto& pair : root->children) { + pair.second->fail = root; + q.push(pair.second); + } + while (!q.empty()) { + TrieNode* current = q.front(); + q.pop(); + for (auto& pair : current->children) { + char c = pair.first; + TrieNode* child = pair.second; + TrieNode* fail = current->fail; + while (fail != root && fail->children.find(c) == fail->children.end()) { + fail = fail->fail; + } + if (fail->children.find(c) != fail->children.end()) { + child->fail = fail->children[c]; + } else { + child->fail = root; + } + child->output.insert(child->output.end(), child->fail->output.begin(), child->fail->output.end()); + q.push(child); + } + } + } + + void search(const string& text) { + TrieNode* node = root; + for (int i = 0; i < text.size(); i++) { + while (node != root && node->children.find(text[i]) == node->children.end()) { + node = node->fail; + } + if (node->children.find(text[i]) != node->children.end()) { + node = node->children[text[i]]; + } else { + node = root; + } + if (!node->output.empty()) { + for (const string& pattern : node->output) { + cout << "Pattern '" << pattern << "' found at index " << i - pattern.size() + 1 << endl; + } + } + } + } +}; + +// Example usage: +int main() { + string text = "THIS IS A TEST TEXT"; + vector patterns = {"TEST", "TEXT"}; + AhoCorasick ac(patterns); + ac.search(text); + return 0; +} +``` + + + + + +```java +import java.util.*; + +public class AhoCorasick { + private static class TrieNode { + Map children = new HashMap<>(); + TrieNode fail; + List output = new ArrayList<>(); + } + + private TrieNode root; + + public AhoCorasick(List keywords) { + root = new TrieNode(); + buildTrie(keywords); + buildAutomaton(); + } + + private void buildTrie(List keywords) { + for (String keyword : keywords) { + TrieNode node = root; + for (char c : keyword.toCharArray()) { + node = node.children.computeIfAbsent(c, k -> new TrieNode()); + } + node.output.add(keyword); + } + } + + private void buildAutomaton() { + Queue queue = new LinkedList<>(); + root.fail = root; + for (TrieNode node : root.children.values()) { + node.fail = root; + queue.add(node); + } + while (!queue.isEmpty()) { + TrieNode current = queue.poll(); + for (Map.Entry entry : current.children.entrySet()) { + char c = entry.getKey(); + TrieNode child = entry.getValue(); + TrieNode fail = current.fail; + while (fail != root && !fail.children.containsKey(c)) { + fail = fail.fail; + } + if (fail.children.containsKey(c)) { + child.fail = fail.children.get(c); + } else { + child.fail = root; + } + child.output.addAll(child.fail.output); + queue.add(child); + } + } + } + + public void search(String text) { + TrieNode node = root; + for (int i = 0; i < text.length(); i++) { + while (node != root && !node.children.containsKey(text.charAt(i))) { + node = node.fail; + + + } + if (node.children.containsKey(text.charAt(i))) { + node = node.children.get(text.charAt(i)); + } else { + node = root; + } + if (!node.output.isEmpty()) { + for (String pattern : node.output) { + System.out.println("Pattern '" + pattern + "' found at index " + (i - pattern.length() + 1)); + } + } + } + } + + public static void main(String[] args) { + String text = "THIS IS A TEST TEXT"; + List patterns = Arrays.asList("TEST", "TEXT"); + AhoCorasick ac = new AhoCorasick(patterns); + ac.search(text); + } +} +``` + + + + + +```javascript +class AhoCorasick { + constructor(keywords) { + this.trie = {}; + this.out = {}; + this.fail = {}; + this.buildTrie(keywords); + this.buildAutomaton(); + } + + buildTrie(keywords) { + for (const keyword of keywords) { + let node = this.trie; + for (const char of keyword) { + if (!(char in node)) { + node[char] = {}; + } + node = node[char]; + } + node['#'] = keyword; + } + } + + buildAutomaton() { + const queue = []; + for (const key in this.trie) { + this.fail[key] = this.trie; + queue.push(this.trie[key]); + } + + while (queue.length > 0) { + const current = queue.shift(); + for (const key in current) { + if (key === '#') continue; + let failNode = this.fail[current] || this.trie; + while (failNode !== this.trie && !(key in failNode)) { + failNode = this.fail[failNode]; + } + this.fail[current[key]] = failNode[key] || this.trie; + queue.push(current[key]); + } + } + } + + search(text) { + let node = this.trie; + for (let i = 0; i < text.length; i++) { + const char = text[i]; + while (!(char in node) && node !== this.trie) { + node = this.fail[node]; + } + node = node[char] || this.trie; + if ('#' in node) { + console.log(`Pattern '${node['#']}' found at index ${i - node['#'].length + 1}`); + } + } + } +} + +// Example usage: +const text = "THIS IS A TEST TEXT"; +const patterns = ["TEST", "TEXT"]; +const ac = new AhoCorasick(patterns); +ac.search(text); +``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: + - Preprocessing (building Trie and failure links): $O(m)$ where $m$ is the total length of all patterns. + - Searching: $O(n + z)$ where $n$ is the length of the text and $z$ is the number of occurrences of the patterns. + - Overall: Efficient for multiple pattern matching. + +- **Space Complexity**: $O(m)$ for the Trie and failure links. + +## 9. Advantages and Disadvantages + +**Advantages:** +- Efficient for searching multiple patterns simultaneously. +- Uses Trie and failure links to minimize unnecessary comparisons. + +**Disadvantages:** +- More complex to implement compared to simpler algorithms. +- Higher space complexity due to the construction of the Trie and failure links. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/aho-corasick-algorithm-pattern-searching/) +- **Author's Geeks for Geeks Profile:** Ayush Govil diff --git a/docs/Algorithms/String-Algorithms/07-Burrows-Wheeler-Transform.md b/docs/Algorithms/String-Algorithms/07-Burrows-Wheeler-Transform.md new file mode 100644 index 0000000..e060bd8 --- /dev/null +++ b/docs/Algorithms/String-Algorithms/07-Burrows-Wheeler-Transform.md @@ -0,0 +1,216 @@ +--- +id: Burrows-Wheeler-Transform +title: Burrows-Wheeler Transform (Geeks for Geeks) +sidebar_label: Burrows-Wheeler Transform +tags: + - Advanced + - String Matching Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Burrows-Wheeler Transform (BWT) algorithm problem on Geeks for Geeks." +--- + +## 1. What is the Burrows-Wheeler Transform (BWT)? + +The Burrows-Wheeler Transform (BWT) is an algorithm used to transform a string into a form that is more amenable to compression. The BWT reorganizes the input string into runs of similar characters, which can then be more effectively compressed by other algorithms. It is particularly useful in data compression techniques and bioinformatics for sequence analysis. + +## 2. Algorithm for Burrows-Wheeler Transform + +1. Generate all rotations of the input string. +2. Sort the rotations lexicographically. +3. Take the last column of the sorted rotations to form the BWT output. + +## 3. How does the Burrows-Wheeler Transform work? + +- **Generate Rotations**: Create all possible rotations of the input string. +- **Sort Rotations**: Sort the generated rotations in lexicographical order. +- **Last Column**: Extract the last column from the sorted rotations to form the transformed string. + +## 4. Problem Description + +Given a text string, implement the Burrows-Wheeler Transform (BWT) to obtain the transformed string. + +## 5. Examples + +**Example 1:** +``` +Input: text = "BANANA" +Output: BWT = "ANNBAA" +``` + +**Example 2:** +``` +Input: text = "GEEKSFORGEEKS" +Output: BWT = "SKREEEGKESOF" +``` + +**Explanation of Example 1:** +- The rotations of "BANANA" are: + ``` + BANANA + ANANAB + NANABA + ANABAN + NABANA + ABANAN + ``` +- Sorting the rotations lexicographically: + ``` + ABANAN + ANABAN + ANANAB + BANANA + NABANA + NANABA + ``` +- The last column of the sorted rotations is "ANNBAA", which is the BWT of "BANANA". + +## Visual Example + +![Visual Example of Burrows-Wheeler Transform](../../../assets/Burrows_Wheeler_Transform.png) + +## 6. Constraints + +- The text can contain any number of characters. +- All characters are $ASCII$ characters. + +## 7. Implementation + + + + + +```python +def burrows_wheeler_transform(text): + n = len(text) + rotations = [text[i:] + text[:i] for i in range(n)] + rotations.sort() + bwt = ''.join(rotation[-1] for rotation in rotations) + return bwt + +# Example usage: +text = "BANANA" +bwt = burrows_wheeler_transform(text) +print("BWT =", bwt) +``` + + + + + + +```cpp +#include +#include +#include +using namespace std; + +string burrows_wheeler_transform(const string &text) { + int n = text.size(); + vector rotations(n); + for (int i = 0; i < n; i++) { + rotations[i] = text.substr(i) + text.substr(0, i); + } + sort(rotations.begin(), rotations.end()); + string bwt; + for (const auto &rotation : rotations) { + bwt += rotation.back(); + } + return bwt; +} + +// Example usage: +int main() { + string text = "BANANA"; + string bwt = burrows_wheeler_transform(text); + cout << "BWT = " << bwt << endl; + return 0; +} +``` + + + + + +```java +import java.util.Arrays; + +public class BurrowsWheelerTransform { + + public static String burrowsWheelerTransform(String text) { + int n = text.length(); + String[] rotations = new String[n]; + for (int i = 0; i < n; i++) { + rotations[i] = text.substring(i) + text.substring(0, i); + } + Arrays.sort(rotations); + StringBuilder bwt = new StringBuilder(); + for (String rotation : rotations) { + bwt.append(rotation.charAt(n - 1)); + } + return bwt.toString(); + } + + // Example usage: + public static void main(String[] args) { + String text = "BANANA"; + String bwt = burrowsWheelerTransform(text); + System.out.println("BWT = " + bwt); + } +} +``` + + + + + +```javascript +function burrowsWheelerTransform(text) { + const n = text.length; + const rotations = []; + for (let i = 0; i < n; i++) { + rotations.push(text.slice(i) + text.slice(0, i)); + } + rotations.sort(); + let bwt = ''; + for (const rotation of rotations) { + bwt += rotation.charAt(n - 1); + } + return bwt; +} + +// Example usage: +const text = "BANANA"; +const bwt = burrowsWheelerTransform(text); +console.log("BWT =", bwt); +``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: + - Generating rotations: $O(n^2)$ where $n$ is the length of the text. + - Sorting rotations: $O(n \log n)$. + - Overall: $O(n^2)$ due to the rotations generation step. + +- **Space Complexity**: $O(n^2)$ for storing all rotations. + +## 9. Advantages and Disadvantages + +**Advantages:** +- Makes the input string more compressible. +- Useful in various applications, including data compression and bioinformatics. + +**Disadvantages:** +- High space complexity due to storing all rotations. +- Higher time complexity compared to some other string transformation algorithms. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/burrows-wheeler-data-transform-algorithm/) +- **Author's Geeks for Geeks Profile:** GeeksforGeeks diff --git a/docs/Algorithms/String-Algorithms/08-Manachers-Algorithm.md b/docs/Algorithms/String-Algorithms/08-Manachers-Algorithm.md new file mode 100644 index 0000000..33cad3f --- /dev/null +++ b/docs/Algorithms/String-Algorithms/08-Manachers-Algorithm.md @@ -0,0 +1,273 @@ +--- +id: Manachers-Algorithm +title: Manacher's Algorithm (Geeks for Geeks) +sidebar_label: Manacher's Algorithm +tags: + - Advanced + - String Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Manacher's Algorithm problem on Geeks for Geeks." +--- + +## 1. What is Manacher's Algorithm? + +Manacher's Algorithm is an efficient algorithm used to find the longest palindromic substring in a given string. It operates in linear time, making it significantly faster than the traditional approach which operates in quadratic time. + +## 2. Algorithm for Manacher's Algorithm + +1. Preprocess the string to handle even-length palindromes by inserting a unique character (e.g., `#`) between every character and at the boundaries. +2. Use the preprocessed string to compute the length of the palindromes centered at each character using a palindrome expansion approach. +3. Track the maximum length palindrome and its center to determine the longest palindromic substring. + +## 3. How does Manacher's Algorithm work? + +- **Preprocessing**: Convert the string `s` to a new string `t` by inserting a unique character `#` between each character of `s` and adding boundary characters at the start and end. +- **Palindrome Expansion**: Use the preprocessed string `t` to compute an array `p` where `p[i]` gives the length of the palindrome centered at `t[i]`. +- **Longest Palindromic Substring**: Find the maximum value in the array `p` to get the longest palindromic substring in the original string `s`. + +## 4. Problem Description + +Given a text string, implement Manacher's Algorithm to find the longest palindromic substring. + +## 5. Examples + +**Example 1:** +``` +Input: text = "babad" +Output: "bab" (or "aba") +``` + +**Example 2:** +``` +Input: text = "cbbd" +Output: "bb" +``` + +**Explanation of Example 1:** +- The longest palindromic substring in "babad" is "bab" or "aba". + +## Visual Example + +![Visual Example of Manacher's Algorithm](../../../assets/Manachers_Algorithm.png) + +## 6. Constraints + +- The text can contain any number of characters. +- All characters are $ASCII$ characters. + +## 7. Implementation + + + + + +```python +def preprocess(s): + return '#' + '#'.join(s) + '#' + +def manachers_algorithm(s): + t = preprocess(s) + n = len(t) + p = [0] * n + c = 0 + r = 0 + for i in range(n): + mirr = 2 * c - i + if i < r: + p[i] = min(r - i, p[mirr]) + while i + p[i] + 1 < n and i - p[i] - 1 >= 0 and t[i + p[i] + 1] == t[i - p[i] - 1]: + p[i] += 1 + if i + p[i] > r: + c = i + r = i + p[i] + max_len = max(p) + center_index = p.index(max_len) + start = (center_index - max_len) // 2 + return s[start:start + max_len] + +# Example usage: +text = "babad" +result = manachers_algorithm(text) +print("Longest Palindromic Substring:", result) +``` + + + + + + +```cpp +#include +#include +using namespace std; + +string preprocess(const string &s) { + string t = "#"; + for (char c : s) { + t += c; + t += "#"; + } + return t; +} + +string manachers_algorithm(const string &s) { + string t = preprocess(s); + int n = t.size(); + vector p(n, 0); + int c = 0, r = 0; + for (int i = 0; i < n; i++) { + int mirr = 2 * c - i; + if (i < r) + p[i] = min(r - i, p[mirr]); + while (i + p[i] + 1 < n && i - p[i] - 1 >= 0 && t[i + p[i] + 1] == t[i - p[i] - 1]) + p[i]++; + if (i + p[i] > r) { + c = i; + r = i + p[i]; + } + } + int max_len = 0, center_index = 0; + for (int i = 0; i < n; i++) { + if (p[i] > max_len) { + max_len = p[i]; + center_index = i; + } + } + int start = (center_index - max_len) / 2; + return s.substr(start, max_len); +} + +// Example usage: +int main() { + string text = "babad"; + string result = manachers_algorithm(text); + cout << "Longest Palindromic Substring: " << result << endl; + return 0; +} +``` + + + + + +```java +public class ManachersAlgorithm { + + private static String preprocess(String s) { + StringBuilder t = new StringBuilder("#"); + for (char c : s.toCharArray()) { + t.append(c).append("#"); + } + return t.toString(); + } + + public static String manachersAlgorithm(String s) { + String t = preprocess(s); + int n = t.length(); + int[] p = new int[n]; + int c = 0, r = 0; + for (int i = 0; i < n; i++) { + int mirr = 2 * c - i; + if (i < r) { + p[i] = Math.min(r - i, p[mirr]); + } + while (i + p[i] + 1 < n && i - p[i] - 1 >= 0 && t.charAt(i + p[i] + 1) == t.charAt(i - p[i] - 1)) { + p[i]++; + } + if (i + p[i] > r) { + c = i; + r = i + p[i]; + } + } + int max_len = 0, center_index = 0; + for (int i = 0; i < n; i++) { + if (p[i] > max_len) { + max_len = p[i]; + center_index = i; + } + } + int start = (center_index - max_len) / 2; + return s.substring(start, start + max_len); + } + + // Example usage: + public static void main(String[] args) { + String text = "babad"; + String result = manachersAlgorithm(text); + System.out.println("Longest Palindromic Substring: " + result); + } +} +``` + + + + + +```javascript +function preprocess(s) { + return '#' + s.split('').join('#') + '#'; +} + +function manachersAlgorithm(s) { + const t = preprocess(s); + const n = t.length; + const p = new Array(n).fill(0); + let c = 0, r = 0; + for (let i = 0; i < n; i++) { + const mirr = 2 * c - i; + if (i < r) { + p[i] = Math.min(r - i, p[mirr]); + } + while (i + p[i] + 1 < n && i - p[i] - 1 >= 0 && t[i + p[i] + 1] === t[i - p[i] - 1]) { + p[i]++; + } + if (i + p[i] > r) { + c = i; + r = i + p[i]; + } + } + let maxLen = 0; + let centerIndex = 0; + for (let i = 0; i < n; i++) { + if (p[i] > maxLen) { + maxLen = p[i]; + centerIndex = i; + } + } + const start = (centerIndex - maxLen) / 2; + return s.substring(start, start + maxLen); +} + +// Example usage: +const text = "babad"; +const result = manachersAlgorithm(text); +console.log("Longest Palindromic Substring:", result); +``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: $O(n)$, where $n$ is the length of the preprocessed string. +- **Space Complexity**: $O(n)$ for the arrays used. + +## 9. Advantages and Disadvantages + +**Advantages:** +- Linear time complexity. +- Efficient for finding the longest palindromic + + substring. + +**Disadvantages:** +- Requires preprocessing which increases the space complexity. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/manachers-algorithm-linear-time-longest-palindromic-substring-part-1/) +- **Author's Geeks for Geeks Profile:** Anurag Singh diff --git a/docs/Algorithms/String-Algorithms/09-Rolling-Hash.md b/docs/Algorithms/String-Algorithms/09-Rolling-Hash.md new file mode 100644 index 0000000..46b15fc --- /dev/null +++ b/docs/Algorithms/String-Algorithms/09-Rolling-Hash.md @@ -0,0 +1,277 @@ +--- +id: Rolling-Hash +title: Rolling Hash Algorithm (Geeks for Geeks) +sidebar_label: Rolling Hash +tags: + - Advanced + - String Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Rolling Hash algorithm problem on Geeks for Geeks." +--- + +## 1. What is the Rolling Hash Algorithm? + +The Rolling Hash algorithm is an efficient string searching algorithm used for detecting substring matches in a given text. It is a key component of the Rabin-Karp algorithm. The rolling hash function allows the hash of a substring to be quickly updated as the window slides over the text. + +## 2. Algorithm for Rolling Hash + +1. Calculate the hash value of the initial substring of the text that has the same length as the pattern. +2. Slide the window over the text one character at a time, updating the hash value using the rolling hash formula. +3. Compare the hash values of the pattern and the current substring of the text. If they match, compare the actual strings to confirm a match. + +## 3. How does the Rolling Hash Algorithm work? + +- **Initial Hash Calculation**: Compute the hash value for the first substring of the text that matches the length of the pattern. +- **Rolling Hash Update**: Update the hash value for the next substring by subtracting the hash value of the outgoing character, adding the hash value of the incoming character, and applying a modulus operation to avoid overflow. +- **Match Verification**: If the hash values match, compare the actual strings to confirm the match. + +## 4. Problem Description + +Given a text string and a pattern string, implement the Rolling Hash algorithm to find all occurrences of the pattern in the text. + +## 5. Examples + +**Example 1:** +``` +Input: text = "THIS IS A TEST TEXT", pattern = "TEST" +Output: Pattern found at index 10 +``` + +**Example 2:** +``` +Input: text = "AABAACAADAABAABA", pattern = "AABA" +Output: Pattern found at index 0, Pattern found at index 9, Pattern found at index 12 +``` + +**Explanation of Example 1:** +- The pattern "TEST" is found in the text "THIS IS A TEST TEXT" starting from index 10. + + +## 6. Constraints + +- The text and pattern can contain any number of characters. +- All characters are $ASCII$ characters. + +## 7. Implementation + + + + + +```python +d = 256 # Number of characters in the input alphabet +q = 101 # A prime number + +def search(pattern, text): + m = len(pattern) + n = len(text) + p = 0 # Hash value for pattern + t = 0 # Hash value for text + h = 1 + + # The value of h would be "pow(d, m-1)%q" + for i in range(m-1): + h = (h * d) % q + + # Calculate the hash value of pattern and first window of text + for i in range(m): + p = (d * p + ord(pattern[i])) % q + t = (d * t + ord(text[i])) % q + + # Slide the pattern over text one by one + for i in range(n - m + 1): + # Check the hash values of current window of text and pattern + if p == t: + # Check for characters one by one + if text[i:i+m] == pattern: + print("Pattern found at index " + str(i)) + + # Calculate hash value for next window of text + if i < n - m: + t = (d * (t - ord(text[i]) * h) + ord(text[i + m])) % q + if t < 0: + t = t + q + +# Example usage +text = "THIS IS A TEST TEXT" +pattern = "TEST" +search(pattern, text) +``` + + + + + + +```cpp +#include +#include +using namespace std; + +#define d 256 +#define q 101 + +void search(string pattern, string text) { + int m = pattern.size(); + int n = text.size(); + int p = 0; // Hash value for pattern + int t = 0; // Hash value for text + int h = 1; + + // The value of h would be "pow(d, m-1)%q" + for (int i = 0; i < m - 1; i++) + h = (h * d) % q; + + // Calculate the hash value of pattern and first window of text + for (int i = 0; i < m; i++) { + p = (d * p + pattern[i]) % q; + t = (d * t + text[i]) % q; + } + + // Slide the pattern over text one by one + for (int i = 0; i <= n - m; i++) { + // Check the hash values of current window of text and pattern + if (p == t) { + // Check for characters one by one + if (text.substr(i, m) == pattern) + cout << "Pattern found at index " << i << endl; + } + + // Calculate hash value for next window of text + if (i < n - m) { + t = (d * (t - text[i] * h) + text[i + m]) % q; + if (t < 0) + t = t + q; + } + } +} + +// Example usage +int main() { + string text = "THIS IS A TEST TEXT"; + string pattern = "TEST"; + search(pattern, text); + return 0; +} +``` + + + + + +```java +public class RollingHash { + + static final int d = 256; + static final int q = 101; + + static void search(String pattern, String text) { + int m = pattern.length(); + int n = text.length(); + int p = 0; // hash value for pattern + int t = 0; // hash value for text + int h = 1; + + for (int i = 0; i < m - 1; i++) + h = (h * d) % q; + + for (int i = 0; i < m; i++) { + p = (d * p + pattern.charAt(i)) % q; + t = (d * t + text.charAt(i)) % q; + } + + for (int i = 0; i <= n - m; i++) { + if (p == t) { + if (text.substring(i, i + m).equals(pattern)) + System.out.println("Pattern found at index " + i); + } + + if (i < n - m) { + t = (d * (t - text.charAt(i) * h) + text.charAt(i + m)) % q; + if (t < 0) + t = (t + q); + } + } + } + + // Example usage + public static void main(String[] args) { + String text = "THIS IS A TEST TEXT"; + String pattern = "TEST"; + search(pattern, text); + } +} +``` + + + + + +```javascript +const d = 256; +const q = 101; + +function search(pattern, text) { + const m = pattern.length; + const n = text.length; + let p = 0; // hash value for pattern + let t = 0; // hash value for text + let h = 1; + + for (let i = 0; i < m - 1; i++) + h = (h * d) % q; + + for (let i = 0; i < m; i++) { + p = (d * p + pattern.charCodeAt(i)) % q; + t = (d * t + text.charCodeAt(i)) % q; + } + + for (let i = 0; i <= n - m; i++) { + if (p === t) { + if (text.substring(i, i + m) === pattern) + console.log("Pattern found at index " + i); + } + + if (i < n - m) { + t = (d * (t - text.charCodeAt(i) * h) + text.charCodeAt(i + m)) % q; + if (t < 0) + t = (t + q); + } + } +} + +// Example usage +const text = "THIS IS A TEST TEXT"; +const pattern = "TEST"; +search(pattern, text); +``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: $O(n + m)$, where $n$ is the length of the text and $m$ is the length of the pattern. +- **Space Complexity**: $O(1)$, since it uses a constant amount + + of extra space. + +## 9. Advantages and Disadvantages + +**Advantages:** +- Efficient for searching multiple patterns in a text. +- Uses a simple hash function for pattern matching. + +**Disadvantages:** +- Hash collisions can lead to false positives. +- Requires preprocessing which increases the space complexity. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/introduction-to-rolling-hash-data-structures-and-algorithms/) +- **Author's Geeks for Geeks Profile:** akashjha2671 + diff --git a/docs/Algorithms/String-Algorithms/_category_.json b/docs/Algorithms/String-Algorithms/_category_.json new file mode 100644 index 0000000..93c3206 --- /dev/null +++ b/docs/Algorithms/String-Algorithms/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "String Algorithms", + "position": 8, + "link": { + "type": "generated-index", + "description": "In This section Two String Algorithms are defined in DSA for Searching are meant to be added" + } + } \ No newline at end of file diff --git a/docs/Algorithms/Tree/in-order-traversal.md b/docs/Algorithms/Tree/in-order-traversal.md new file mode 100644 index 0000000..6d22ab7 --- /dev/null +++ b/docs/Algorithms/Tree/in-order-traversal.md @@ -0,0 +1,199 @@ +--- +id: in-order-traversal +title: in-order-traversal +sidebar_label: In Order Traversal +tags: +- Tree +- Depth-First Search +- Binary Tree +description: "This is a solution to the Binary Tree In Order Traversal problem on LeetCode." +--- + +## Problem Description +Given the root of a binary tree, return the inorder traversal of its nodes' values. + +### Examples + +**Example 1:** +![alt text](inorder_1-1.jpg) +``` +Input: root = [1,null,2,3] +Output: [1,2,3] +``` + +**Example 2:** +``` +Input: root = [] +Output: [] +``` + +**Example 3:** +``` +Input: root = [1] +Output: [1] +``` + + + +### Constraints +- The number of nodes in the tree is in the range [0, 100]. +- `-1000 <= Node.val <= 1000` + +## Solution for Binary Tree Pre Order Traversal + +### Intuition +- Recursive is very easy try with iterative way + +### Code in Different Languages + + + + + + + ```python +//python + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + + def InOrder(root,arr): + + if root is None: + return + + else: + InOrder(root.left,arr) + arr.append(root.val) + InOrder(root.right,arr) + + return arr + + return InOrder(root,[]) + + +``` + + + + + ```java +//java + + +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List inorderTraversal(TreeNode root) { + + List ans = new ArrayList<>(); + ArrayDeque stack = new ArrayDeque<>(); + + TreeNode cur = root; + + while(cur != null || !stack.isEmpty()) { + + while(cur != null) { + + stack.push(cur); + cur = cur.left; + } + + TreeNode pop = stack.pop(); + ans.add(pop.val); + + cur = pop.right; + } + return ans; + } +} + + + + +``` + + + + + ```cpp +//cpp + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + vector ans ; + void inorder (TreeNode* root) { + + // inorder(LNR) + + if(!root) + return ; + + + + inorder(root->left) ; + + + ans.push_back(root->val); + + + inorder(root->right) ; + + +} + vector inorderTraversal(TreeNode* root) { + + inorder(root) ; + + return ans ; + + } +}; + +``` + + + + + + + + +## References + +- **LeetCode Problem:** [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) +- **Solution Link:** [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/submissions/) +- **Authors GeeksforGeeks Profile:** [parikhit kurmi](https://www.geeksforgeeks.org/user/sololeveler673/) +- **Authors Leetcode:** [parikhit kurmi](https://leetcode.com/u/parikhitkurmi14/) + diff --git a/docs/Algorithms/Tree/inorder_1-1.jpg b/docs/Algorithms/Tree/inorder_1-1.jpg new file mode 100644 index 0000000..34b9d70 Binary files /dev/null and b/docs/Algorithms/Tree/inorder_1-1.jpg differ diff --git a/docs/Algorithms/Tree/inorder_1.jpg b/docs/Algorithms/Tree/inorder_1.jpg new file mode 100644 index 0000000..34b9d70 Binary files /dev/null and b/docs/Algorithms/Tree/inorder_1.jpg differ diff --git a/docs/Algorithms/Tree/level-order-traversal.md b/docs/Algorithms/Tree/level-order-traversal.md new file mode 100644 index 0000000..98d083f --- /dev/null +++ b/docs/Algorithms/Tree/level-order-traversal.md @@ -0,0 +1,321 @@ +--- +id: level-order-traversal +title: Level Order Traversal +sidebar_label: Level Order Traversal +tags: +- Tree +- Breadth-First Search +- Binary Tree +description: "This is a solution to the Binary Tree Level Order Traversal problem on LeetCode." +--- + +## Problem Description +Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). + +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg) +``` +Input: root = [3,9,20,null,null,15,7] +Output: [[3],[9,20],[15,7]] +``` + +**Example 2:** +``` +Input: root = [1] +Output: [[1]] +``` + + +### Constraints +- The number of nodes in the tree is in the range [0, 2000]. +- `-1000 <= Node.val <= 1000` + +## Solution for Binary Tree Level Order Traversal + +### Intuition +- To perform a level-order traversal on a binary tree and store the nodes’ values in a 2D vector representing each level, start by initialising an empty queue to hold the level by level nodes.Enqueue the root node into the queue and traverse until the queue is empty. For each level, track the number of nodes in that level, creating a temporary vector to deque and store them. At each node, store its value in the temporary vector and enqueue its left and right children if they exist.Once all the nodes at a level are processed add this 1D temporary vector to the final 2D vector, representing that level. This process repeats until all levels are traversed. Finally, return this 2D vector containing the level order traversal of the binary tree. + + +#### Implementation + +```jsx live +function Solution() { +function TreeNode(val = 0, left = null, right = null) { + this.val = val; + this.left = left; + this.right = right; +} +function constructTreeFromArray(array) { + if (!array.length) return null; + + let root = new TreeNode(array[0]); + let queue = [root]; + let i = 1; + + while (i < array.length) { + let currentNode = queue.shift(); + + if (array[i] !== null) { + currentNode.left = new TreeNode(array[i]); + queue.push(currentNode.left); + } + i++; + + if (i < array.length && array[i] !== null) { + currentNode.right = new TreeNode(array[i]); + queue.push(currentNode.right); + } + i++; + } + return root; +} +function levelOrder(root) { + if (!root) return []; + + const queue = [root]; + const ans = []; + + while (queue.length > 0) { + const size = queue.length; + const temp = []; + + for (let i = 0; i < size; i++) { + const curr = queue.shift(); + + if (curr.left) queue.push(curr.left); + if (curr.right) queue.push(curr.right); + + temp.push(curr.val); + } + + ans.push(temp); + } + + return ans; +} + + +const array = [3,9,20,null,null,15,7] +const input = constructTreeFromArray(array) +const output = levelOrder(input) + return ( +
+

+ Input: {JSON.stringify(array)} +

+

+ Output: {output.toString()} +

+
+ ); +} +``` + +### Code in Different Languages + + + + + ```javascript + } +function levelOrder(root) { + if (!root) return []; + + const queue = [root]; + const ans = []; + + while (queue.length > 0) { + const size = queue.length; + const temp = []; + + for (let i = 0; i < size; i++) { + const curr = queue.shift(); + + if (curr.left) queue.push(curr.left); + if (curr.right) queue.push(curr.right); + + temp.push(curr.val); + } + + ans.push(temp); + } + + return ans; +} +``` + + + + ```typescript + class TreeNode { + val: number; + left: TreeNode | null; + right: TreeNode | null; + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = (val === undefined ? 0 : val); + this.left = (left === undefined ? null : left); + this.right = (right === undefined ? null : right); + } +} + +function levelOrder(root: TreeNode | null): number[][] { + if (!root) return []; + + const queue: TreeNode[] = [root]; + const ans: number[][] = []; + + while (queue.length > 0) { + const size = queue.length; + const temp: number[] = []; + + for (let i = 0; i < size; i++) { + const curr = queue.shift()!; + + if (curr.left) queue.push(curr.left); + if (curr.right) queue.push(curr.right); + + temp.push(curr.val); + } + + ans.push(temp); + } + + return ans; +} + ``` + + + + ```python +from collections import deque +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def levelOrder(self, root: TreeNode) -> List[List[int]]: + if not root: + return [] + + q = deque([root]) + ans = [] + + while q: + size = len(q) + temp = [] + + for _ in range(size): + curr = q.popleft() + + if curr.left: + q.append(curr.left) + if curr.right: + q.append(curr.right) + + temp.append(curr.val) + + ans.append(temp) + + return ans + ``` + + + +```java +import java.util.*; + +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +class Solution { + public List> levelOrder(TreeNode root) { + Queue q = new LinkedList<>(); + List> ans = new ArrayList<>(); + + if (root == null) return ans; + + q.offer(root); + + while (!q.isEmpty()) { + int size = q.size(); + List temp = new ArrayList<>(); + + for (int i = 0; i < size; i++) { + TreeNode curr = q.poll(); + + if (curr.left != null) q.offer(curr.left); + if (curr.right != null) q.offer(curr.right); + + temp.add(curr.val); + } + + ans.add(temp); + } + + return ans; + } +} + +``` + + + +```cpp +class Solution { +public: + vector> levelOrder(TreeNode* root) { + queue q; + vector> ans; + + if(!root) return ans; + + q.push(root); + + while(!q.empty()){ + int size = q.size(); + vector temp; + + while(size--){ + TreeNode *curr = q.front(); + q.pop(); + + if(curr->left) q.push(curr->left); + if(curr->right) q.push(curr->right); + + temp.push_back(curr->val); + } + + ans.push_back(temp); + } + + return ans; + } +}; +``` + + + +#### Complexity Analysis + ##### Time Complexity: + - $O(N)$ where N is the number of nodes in the binary tree. Each node of the binary tree is enqueued and dequeued exactly once, hence all nodes need to be processed and visited. Processing each node takes constant time operations which contributes to the overall linear time complexity. + + ##### Space Complexity: + - $O(N)$ where N is the number of nodes in the binary tree. In the worst case, the queue has to hold all the nodes of the last level of the binary tree, the last level could at most hold N/2 nodes hence the space complexity of the queue is proportional to $O(N)$.The resultant vector answer also stores the values of the nodes level by level and hence contains all the nodes of the tree contributing to O(N) space as well. + +
+
+ +## References + +- **LeetCode Problem**: [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/) + +- **Solution Link**: [LeetCode Solution](hhttps://leetcode.com/problems/binary-tree-level-order-traversal/solutions) + diff --git a/docs/Algorithms/Tree/post-order-traversal.md b/docs/Algorithms/Tree/post-order-traversal.md new file mode 100644 index 0000000..a4f76a1 --- /dev/null +++ b/docs/Algorithms/Tree/post-order-traversal.md @@ -0,0 +1,179 @@ +--- +id: post-order-traversal +title: post-order-traversal +sidebar_label: Post Order Traversal +tags: +- Tree +- Depth-First Search +- Binary Tree +description: "This is a solution to the Binary Tree Post Order Traversal problem on LeetCode." +--- + +## Problem Description +Given the root of a binary tree, return the postorder traversal of its nodes' values. + +### Examples + +**Example 1:** +![alt text](inorder_1-1.jpg) +``` +Input: root = [1,null,2,3] +Output: [1,2,3] +``` + +**Example 2:** +``` +Input: root = [] +Output: [] +``` + +**Example 3:** +``` +Input: root = [1] +Output: [1] +``` + + + +### Constraints +- The number of nodes in the tree is in the range [0, 100]. +- `-1000 <= Node.val <= 1000` + +## Solution for Binary Tree Post Order Traversal + +### Intuition +- Recursive is very easy try with iterative way + +### Code in Different Languages + + + + + + + ```python +//python +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def postorderTraversal(self, root): + """ + :type root: TreeNode + :rtype: List[int] + """ + stack=[] + def dfs(root): + if root: + dfs(root.left) + dfs(root.right) + stack.append(root.val) + dfs(root) + return stack + + +``` + + + + + ```java +//java + +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + ArrayList res = new ArrayList<>(); + public List postorderTraversal(TreeNode root) { + postOrder(root); + return res; + } + + private void postOrder(TreeNode root){ + if(root == null){ + return; + } + postOrder(root.left); + postOrder(root.right); + res.add(root.val); + } +} + + + + +``` + + + + + ```cpp +//cpp + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + vector ans ; + void postorder(TreeNode* root) + { + if(!root) + return ; + + postorder(root->left) ; + postorder(root->right) ; + + ans.push_back(root->val) ; + + + } + vector postorderTraversal(TreeNode* root) { + + postorder(root) ; + return ans ; + + } +}; + +``` + + + + + + + + +## References + +- **LeetCode Problem:** [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) +- **Solution Link:** [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/submissions/) +- **Authors GeeksforGeeks Profile:** [parikhit kurmi](https://www.geeksforgeeks.org/user/sololeveler673/) +- **Authors Leetcode:** [parikhit kurmi](https://leetcode.com/u/parikhitkurmi14/) + diff --git a/docs/Algorithms/Tree/pre-order-traversal.md b/docs/Algorithms/Tree/pre-order-traversal.md new file mode 100644 index 0000000..1807cc7 --- /dev/null +++ b/docs/Algorithms/Tree/pre-order-traversal.md @@ -0,0 +1,175 @@ +--- +id: pre-order-traversal +title: pre-order-traversal +sidebar_label: Pre Order Traversal +tags: +- Tree +- Depth-First Search +- Binary Tree +description: "This is a solution to the Binary Tree Pre Order Traversal problem on LeetCode." +--- + +## Problem Description +Given the root of a binary tree, return the preorder traversal of its nodes' values. + +### Examples + +**Example 1:** +![alt text](inorder_1.jpg) +``` +Input: root = [1,null,2,3] +Output: [1,2,3] +``` + +**Example 2:** +``` +Input: root = [] +Output: [] +``` + +**Example 3:** +``` +Input: root = [1] +Output: [1] +``` + + + +### Constraints +- The number of nodes in the tree is in the range [0, 100]. +- `-1000 <= Node.val <= 1000` + +## Solution for Binary Tree Pre Order Traversal + +### Intuition +- Recursive is very easy try with iterative way + +### Code in Different Languages + + + + + + + ```python +//python + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + L=[] + def pot(node): + if node is None: + return + L.append(node.val) + pot(node.left) + pot(node.right) + return L + return pot(root) + +``` + + + + + ```java +//java + + +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + List result = new ArrayList<>(); + public List preorderTraversal(TreeNode root) { + preOrder(root); + return result; + } + + private void preOrder(TreeNode node){ + if(node == null){ + return; + } + + result.add(node.val); + preOrder(node.left); + preOrder(node.right); + } +} + + +``` + + + + + ```cpp +//cpp + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + +vectorans ; +void Preorder(TreeNode* root) { + if(!root) + return ; + + // NLR + ans.push_back(root->val) ; + Preorder(root->left); + Preorder(root->right) ; + +} + vector preorderTraversal(TreeNode* root) { + + Preorder(root) ; + return ans ; + + } +}; + +``` + + + + + + + + +## References + +- **LeetCode Problem:** [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) +- **Solution Link:** [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/submissions/) +- **Authors GeeksforGeeks Profile:** [parikhit kurmi](https://www.geeksforgeeks.org/user/sololeveler673/) +- **Authors Leetcode:** [parikhit kurmi](https://leetcode.com/u/parikhitkurmi14/) + diff --git a/docs/Algorithms/_category_.json b/docs/Algorithms/_category_.json new file mode 100644 index 0000000..ac476a3 --- /dev/null +++ b/docs/Algorithms/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Algorithms", + "position": 7, + "link": { + "type": "generated-index", + "description": "In This section all the Algorithms are defined in DSA for graphs,trees,DP are meant to be added" + } + } \ No newline at end of file diff --git a/docs/Algorithms/a-star.md b/docs/Algorithms/a-star.md new file mode 100644 index 0000000..9a3ccf6 --- /dev/null +++ b/docs/Algorithms/a-star.md @@ -0,0 +1,263 @@ +--- +id: a-star +title: A* Algorithm +sidebar_label: A* Algorithm +tags: [python, c++, programming, algorithms, A*, graph, shortest-path, data structures, tutorial, in-depth] +description: In this tutorial, we will learn about A* Algorithm and its implementation in Python, and C++ with detailed explanations and examples. +--- + +# A* Algorithm + +The A* Algorithm is an informed search algorithm used for finding the shortest path between two nodes in a graph. It is widely used in various applications such as pathfinding for games, AI, and robotics due to its efficiency and accuracy. + +## How A* Algorithm Works + +The A* Algorithm combines the advantages of Dijkstra's Algorithm and Greedy Best-First Search. It uses a priority queue to explore nodes based on the cost function: + +𝑓(𝑛)=𝑔(𝑛)+β„Ž(𝑛) + +Where: +g(n) is the cost from the start node to the current node. +h(n) is the heuristic function that estimates the cost from the current node n to the goal node. + +## Heuristics in A* Algorithm +The choice of the heuristic function h(n) is crucial for the efficiency of the A* Algorithm. Common heuristics include: + +1. **Manhattan Distance:** Used for grid-based maps. +2. **Euclidean Distance:** Used for geometric spaces. +3. **Chebyshev Distance:** Used when diagonal movement is allowed. +The heuristic function should be admissible, meaning it never overestimates the actual cost to reach the goal. + +## Complexity Analysis +The time complexity of the A* Algorithm is +𝑂(𝑏𝑑) + +WHERE: +b is the branching factor (the average number of successors per state) and +d is the depth of the goal. The space complexity is also +𝑂(𝑏𝑑) as it needs to store all generated nodes in the worst case. + +## Comparison with Other Algorithms + +1. **Dijkstra's Algorithm:** A* is generally faster because it uses heuristics to guide its search, while Dijkstra's explores all possible paths. +2. **Greedy Best-First Search:** A* is more accurate because it takes into account both the actual cost from the start and the estimated cost to the goal, while Greedy Best-First only considers the latter. + +## Common Applications + +1. **Game Development:** For pathfinding characters in video games. +2. **Robotics:** For navigating robots through environments. +3. **Geographic Information Systems (GIS):** For finding the shortest route in maps. + +## Pseudocode +Here is the pseudocode for the A* Algorithm: + + ```pseudo + function A*(start, goal) + openSet := {start} + cameFrom := empty map + gScore := map with default value of Infinity + gScore[start] := 0 + fScore := map with default value of Infinity + fScore[start] := heuristic(start, goal) + + while openSet is not empty + current := node in openSet with lowest fScore[] value + if current == goal + return reconstruct_path(cameFrom, current) + + openSet.Remove(current) + for each neighbor of current + tentative_gScore := gScore[current] + d(current, neighbor) + if tentative_gScore < gScore[neighbor] + cameFrom[neighbor] := current + gScore[neighbor] := tentative_gScore + fScore[neighbor] := gScore[neighbor] + heuristic(neighbor, goal) + if neighbor not in openSet + openSet.Add(neighbor) + + return failure + + function reconstruct_path(cameFrom, current) + total_path := {current} + while current in cameFrom.Keys + current := cameFrom[current] + total_path.Prepend(current) + return total_path + ```` + +## Implementation in Python + ```python + import heapq + + def heuristic(a, b): + return abs(a[0] - b[0]) + abs(a[1] - b[1]) + + def a_star(graph, start, goal): + open_set = [] + heapq.heappush(open_set, (0, start)) + came_from = {} + g_score = {start: 0} + f_score = {start: heuristic(start, goal)} + + while open_set: + _, current = heapq.heappop(open_set) + + if current == goal: + return reconstruct_path(came_from, current) + + for neighbor in graph[current]: + tentative_g_score = g_score[current] + graph[current][neighbor] + if tentative_g_score < g_score.get(neighbor, float('inf')): + came_from[neighbor] = current + g_score[neighbor] = tentative_g_score + f_score[neighbor] = g_score[neighbor] + heuristic(neighbor, goal) + heapq.heappush(open_set, (f_score[neighbor], neighbor)) + + return None + + def reconstruct_path(came_from, current): + path = [current] + while current in came_from: + current = came_from[current] + path.append(current) + return path[::-1] + + + # Example usage + graph = { + (0, 0): {(0, 1): 1, (1, 0): 1}, + (0, 1): {(0, 0): 1, (1, 1): 1, (0, 2): 1}, + (1, 0): {(0, 0): 1, (1, 1): 1, (2, 0): 1}, + (1, 1): {(1, 0): 1, (0, 1): 1, (1, 2): 1, (2, 1): 1}, + (2, 0): {(1, 0): 1, (2, 1): 1}, + (2, 1): {(2, 0): 1, (1, 1): 1, (2, 2): 1}, + (0, 2): {(0, 1): 1, (1, 2): 1}, + (1, 2): {(1, 1): 1, (0, 2): 1, (2, 2): 1}, + (2, 2): {(2, 1): 1, (1, 2): 1}, + } + + start = (0, 0) + goal = (2, 2) + print(a_star(graph, start, goal)) + ``` + + +## Implementation in C++ + ```cpp + #include + #include + #include + #include + #include + + using namespace std; + + struct Node { + int x, y, f, g, h; + Node* parent; + + Node(int x, int y) : x(x), y(y), f(0), g(0), h(0), parent(nullptr) {} + + bool operator==(const Node& other) const { + return x == other.x && y == other.y; + } + + struct HashFunction { + size_t operator()(const Node& node) const { + return hash()(node.x) ^ hash()(node.y); + } + }; + }; + + int heuristic(Node* a, Node* b) { + return abs(a->x - b->x) + abs(a->y - b->y); + } + + vector reconstructPath(unordered_map& cameFrom, Node* current) { + vector path; + while (current != nullptr) { + path.push_back(current); + current = cameFrom[current]; + } + reverse(path.begin(), path.end()); + return path; + } + + vector aStar(Node* start, Node* goal, unordered_map, Node::HashFunction>& graph) { + auto cmp = [](Node* left, Node* right) { return left->f > right->f; }; + priority_queue, decltype(cmp)> openSet(cmp); + unordered_map cameFrom; + unordered_map gScore; + gScore[start] = 0; + start->f = heuristic(start, goal); + openSet.push(start); + + while (!openSet.empty()) { + Node* current = openSet.top(); + openSet.pop(); + + if (*current == *goal) { + return reconstructPath(cameFrom, current); + } + + for (Node* neighbor : graph[current]) { + int tentativeGScore = gScore[current] + 1; + if (tentativeGScore < gScore[neighbor]) { + cameFrom[neighbor] = current; + gScore[neighbor] = tentativeGScore; + neighbor->f = tentativeGScore + heuristic(neighbor, goal); + openSet.push(neighbor); + } + } + } + return {}; + } + + int main() { + Node* start = new Node(0, 0); + Node* goal = new Node(2, 2); + + unordered_map, Node::HashFunction> graph; + graph[start] = {new Node(0, 1), new Node(1, 0)}; + graph[new Node(0, 1)] = {start, new Node(1, 1), new Node(0, 2)}; + graph[new Node(1, 0)] = {start, new Node(1, 1), new Node(2, 0)}; + graph[new Node(1, 1)] = {new Node(1, 0), new Node(0, 1), new Node(1, 2), new Node(2, 1)}; + graph[new Node(2, 0)] = {new Node(1, 0), new Node(2, 1)}; + graph[new Node(2, 1)] = {new Node(2, 0), new Node(1, 1), new Node(2, 2)}; + graph[new Node(0, 2)] = {new Node(0, 1), new Node(1, 2)}; + graph[new Node(1, 2)] = {new Node(1, 1), new Node(0, 2), new Node(2, 2)}; + graph[new Node(2, 2)] = {new Node(2, 1), new Node(1, 2)}; + + vector path = aStar(start, goal, graph); + for (Node* node : path) { + cout << "(" << node->x << ", " << node->y << ")" << endl; + } + + // Clean up dynamically allocated nodes + for (auto& pair : graph) { + delete pair.first; + for (Node* node : pair.second) { + delete node; + } + } + + return 0; + } + ``` + +## Optimizations and Variations + +1. **Bidirectional A*** **:** Runs two simultaneous searchesβ€”one forward from the start and one backward from the goal. +2. **Weighted A*** **:** Modifies the heuristic function to allow faster, though potentially suboptimal, solutions. +3. **Iterative Deepening A*** **:** Combines the benefits of depth-first and breadth-first search, useful for memory-constrained environments. + +## Visualization Tools + +1. **Pathfinding.js:** A library for visualizing pathfinding algorithms in JavaScript. +2. **Graphhopper:** An open-source routing library and server, ideal for map-based applications. +3. **Mazewar:** A web-based tool to visualize and understand different pathfinding algorithms. + +## Conclusion +The A* Algorithm is a powerful and efficient pathfinding algorithm that can be implemented in various programming languages. By understanding its principles and applying the appropriate heuristic functions, you can leverage A* for a wide range of applications. + +In this tutorial, we have covered the theoretical background, provided pseudocode, and demonstrated implementations in Python, Java, C++, and JavaScript. With this knowledge, you should be well-equipped to utilize the A* Algorithm in your projects. diff --git a/docs/Algorithms/bin-packing.md b/docs/Algorithms/bin-packing.md new file mode 100644 index 0000000..95d35d2 --- /dev/null +++ b/docs/Algorithms/bin-packing.md @@ -0,0 +1,647 @@ +--- +id: bin-packing +title: Bin Packing Algorithm +sidebar_label: Bin Packing Algorithm +tags: [python, java, c++, javascript, programming, algorithms, bin packing, data structures, tutorial, in-depth] +description: In this , we will learn about Bin Packing Algorithm and its implementation in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +# Bin Packing Algorithm + +In case of given m elements of different weights and bins each of capacity C, assign each element to a bin so that number of total implemented bins is minimized. Assumption should be that all elements have weights less than bin capacity. + +## Introduction to Bin Packing Algorithm + +Given n items of different weights and bins each of capacity c, assign each item to a bin such that number of total used bins is minimized. It may be assumed that all items have weights smaller than bin capacity. + +## Example + +``` +Input: weight = 4, 8, 1, 4, 2, 1 + + Bin Capacity c = 10 + +Output: 2 + +We need minimum 2 bins to accommodate all items +First bin contains 4, 4, 2 and second bin 8, 1, 1 + +Input: weight = 9, 8, 2, 2, 5, 4 + + Bin Capacity c = 10 + +Output: 4 + +We need minimum 4 bins to accommodate all items. + +Input: weight = 2, 5, 4, 7, 1, 3, 8 + + Bin Capacity c = 10 + +Output: 3 +``` + +## Lower Bound + +We can always find a lower bound on minimum number of bins required. The lower bound can be given as : + + ``` + Min no. of bins >= Ceil ((Total Weight) / (Bin Capacity)) + ``` + +In the above examples, lower bound for first example is β€œceil(4 + 8 + 1 + 4 + 2 + 1)/10” = 2 and lower bound in second example is β€œceil(9 + 8 + 2 + 2 + 5 + 4)/10” = 3. + +This problem is a NP Hard problem and finding an exact minimum number of bins takes exponential time. Following are approximate algorithms for this problem. + +## Online Algorithms + +These algorithms are for Bin Packing problems where items arrive one at a time (in unknown order), each must be put in a bin, before considering the next item. + +### Next Fit: +When processing next item, check if it fits in the same bin as the last item. Use a new bin only if it does not. + +### Implementation of Algorithm + + + + ``` Python showLineNumbers +# Python3 implementation for above approach +def nextfit(weight, c): + res = 0 + rem = c + for _ in range(len(weight)): + if rem >= weight[_]: + rem = rem - weight[_] + else: + res += 1 + rem = c - weight[_] + return res + +# Driver Code +weight = [2, 5, 4, 7, 1, 3, 8] +c = 10 + +print("Number of bins required in Next Fit :", + nextfit(weight, c)) + + +``` + + + + +``` jsx showLineNumbers +// Java program to find number +// of bins required using +// next fit algorithm. +class GFG { + + // Returns number of bins required + // using next fit online algorithm + static int nextFit(int weight[], int n, int c) + { + + // Initialize result (Count of bins) and remaining + // capacity in current bin. + int res = 0, bin_rem = c; + + // Place items one by one + for (int i = 0; i < n; i++) { + // If this item can't fit in current bin + if (weight[i] > bin_rem) { + res++; // Use a new bin + bin_rem = c - weight[i]; + } + else + bin_rem -= weight[i]; + } + return res; + } + + // Driver program + public static void main(String[] args) + { + int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; + int c = 10; + int n = weight.length; + System.out.println("Number of bins required in Next Fit : " + nextFit(weight, n, c)); + } +} + +``` + + + +```cpp showLineNumbers +// C++ program to find number of bins required using +// next fit algorithm. +#include +using namespace std; + +// Returns number of bins required using next fit +// online algorithm +int nextFit(int weight[], int n, int c) +{ + // Initialize result (Count of bins) and remaining + // capacity in current bin. + int res = 0, bin_rem = c; + + // Place items one by one + for (int i = 0; i < n; i++) { + // If this item can't fit in current bin + if (weight[i] > bin_rem) { + res++; // Use a new bin + bin_rem = c - weight[i]; + } + else + bin_rem -= weight[i]; + } + return res; +} + +// Driver program +int main() +{ + int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; + int c = 10; + int n = sizeof(weight) / sizeof(weight[0]); + cout << "Number of bins required in Next Fit : " + << nextFit(weight, n, c); + return 0; +} + + +``` + + + +```jsx showLineNumbers + + +``` + + + +Output: + +``` +Number of bins required in Next Fit : 4 +``` + +Next Fit is a simple algorithm. It requires only O(n) time and O(1) extra space to process n items. +Next Fit is 2 approximate, i.e., the number of bins used by this algorithm is bounded by twice of optimal. Consider any two adjacent bins. The sum of items in these two bins must be > c; otherwise, NextFit would have put all the items of second bin into the first. The same holds for all other bins. Thus, at most half the space is wasted, and so Next Fit uses at most 2M bins if M is optimal. + +### First Fit: + +When processing the next item, scan the previous bins in order and place the item in the first bin that fits. Start a new bin only if it does not fit in any of the existing bins. + +### Implementation of Algorithm + + + + ``` Python showLineNumbers +# Python program to find number of bins required using +# First Fit algorithm. + +# Returns number of bins required using first fit +# online algorithm +def firstFit(weight, n, c): + + # Initialize result (Count of bins) + res = 0 + + # Create an array to store remaining space in bins + # there can be at most n bins + bin_rem = [0]*n + + # Place items one by one + for i in range(n): + + # Find the first bin that can accommodate + # weight[i] + j = 0 + while( j < res): + if (bin_rem[j] >= weight[i]): + bin_rem[j] = bin_rem[j] - weight[i] + break + j+=1 + + # If no bin could accommodate weight[i] + if (j == res): + bin_rem[res] = c - weight[i] + res= res+1 + return res + +# Driver program +weight = [2, 5, 4, 7, 1, 3, 8] +c = 10 +n = len(weight) +print("Number of bins required in First Fit : ",firstFit(weight, n, c)) + + +``` + + + + +``` jsx showLineNumbers +// Java program to find number of bins required using +// First Fit algorithm. +class GFG +{ + +// Returns number of bins required using first fit +// online algorithm +static int firstFit(int weight[], int n, int c) +{ + // Initialize result (Count of bins) + int res = 0; + + // Create an array to store remaining space in bins + // there can be at most n bins + int []bin_rem = new int[n]; + + // Place items one by one + for (int i = 0; i < n; i++) + { + // Find the first bin that can accommodate + // weight[i] + int j; + for (j = 0; j < res; j++) + { + if (bin_rem[j] >= weight[i]) + { + bin_rem[j] = bin_rem[j] - weight[i]; + break; + } + } + + // If no bin could accommodate weight[i] + if (j == res) + { + bin_rem[res] = c - weight[i]; + res++; + } + } + return res; +} + +// Driver program +public static void main(String[] args) +{ + int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; + int c = 10; + int n = weight.length; + System.out.print("Number of bins required in First Fit : " + + firstFit(weight, n, c)); +} +} + + +``` + + + +```cpp showLineNumbers +// C++ program to find number of bins required using +// First Fit algorithm. +#include +using namespace std; + +// Returns number of bins required using first fit +// online algorithm +int firstFit(int weight[], int n, int c) +{ + // Initialize result (Count of bins) + int res = 0; + + // Create an array to store remaining space in bins + // there can be at most n bins + int bin_rem[n]; + + // Place items one by one + for (int i = 0; i < n; i++) { + // Find the first bin that can accommodate + // weight[i] + int j; + for (j = 0; j < res; j++) { + if (bin_rem[j] >= weight[i]) { + bin_rem[j] = bin_rem[j] - weight[i]; + + break; + } + } + + // If no bin could accommodate weight[i] + if (j == res) { + bin_rem[res] = c - weight[i]; + res++; + } + + } + return res; +} + +// Driver program +int main() +{ + int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; + int c = 10; + int n = sizeof(weight) / sizeof(weight[0]); + cout << "Number of bins required in First Fit : " + << firstFit(weight, n, c); + return 0; +} + + +``` + + + +```jsx showLineNumbers + + +``` + + + +Output: +``` +Number of bins required in First Fit : 4 +``` + +The above implementation of First Fit requires O(n2) time, but First Fit can be implemented in O(n Log n) time using Self-Balancing Binary Search Trees. +If M is the optimal number of bins, then First Fit never uses more than 1.7M bins. So First-Fit is better than Next Fit in terms of upper bound on number of bins. + +Auxiliary Space: O(n) + +## Offline Algorithms + +In the offline version, we have all items upfront. Unfortunately offline version is also NP Complete, but we have a better approximate algorithm for it. First Fit Decreasing uses at most (4M + 1)/3 bins if the optimal is M. + +### First Fit Decreasing: + +A trouble with online algorithms is that packing large items is difficult, especially if they occur late in the sequence. We can circumvent this by *sorting* the input sequence, and placing the large items first. With sorting, we get First Fit Decreasing and Best Fit Decreasing, as offline analogues of online First Fit and Best Fit. + +### Implementation of Algorithm + + + + ``` Python showLineNumbers +# Python program to find number of bins required using +# First Fit Decreasing algorithm. + +# Returns number of bins required using first fit +# online algorithm +def firstFit(weight, n, c): + + # Initialize result (Count of bins) + res = 0 + + # Create an array to store remaining space in bins + # there can be at most n bins + bin_rem = [0]*n + + # Place items one by one + for i in range(n): + + # Find the first bin that can accommodate + # weight[i] + j = 0 + while( j < res): + if (bin_rem[j] >= weight[i]): + bin_rem[j] = bin_rem[j] - weight[i] + break + j+=1 + + # If no bin could accommodate weight[i] + if (j == res): + bin_rem[res] = c - weight[i] + res= res+1 + return res + +# Returns number of bins required using first fit +# decreasing offline algorithm +def firstFitDec(weight, n, c): + + # First sort all weights in decreasing order + weight.sort(reverse = True) + + # Now call first fit for sorted items + return firstFit(weight, n, c) + +# Driver program +weight = [ 2, 5, 4, 7, 1, 3, 8 ] +c = 10 +n = len(weight) +print("Number of bins required in First Fit Decreasing : ",str(firstFitDec(weight, n, c))) + +``` + + + + +``` jsx showLineNumbers +// Java program to find number of bins required using +// First Fit Decreasing algorithm. +import java.util.*; + +class GFG +{ + + /* Copy firstFit() from above */ + + // Returns number of bins required using first fit + // decreasing offline algorithm + static int firstFitDec(Integer weight[], int n, int c) + { + + // First sort all weights in decreasing order + Arrays.sort(weight, Collections.reverseOrder()); + + // Now call first fit for sorted items + return firstFit(weight, n, c); + } + + // Driver code + public static void main(String[] args) + { + Integer weight[] = { 2, 5, 4, 7, 1, 3, 8 }; + int c = 10; + int n = weight.length; + System.out.print("Number of bins required in First Fit " + "Decreasing : " + + firstFitDec(weight, n, c)); + } +} + + + +``` + + + +```cpp showLineNumbers +// C++ program to find number of bins required using +// First Fit Decreasing algorithm. +#include +using namespace std; + +/* Copy firstFit() from above */ + +// Returns number of bins required using first fit +// decreasing offline algorithm +int firstFitDec(int weight[], int n, int c) +{ + // First sort all weights in decreasing order + sort(weight, weight + n, std::greater()); + + // Now call first fit for sorted items + return firstFit(weight, n, c); +} + +// Driver program +int main() +{ + int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; + int c = 10; + int n = sizeof(weight) / sizeof(weight[0]); + cout << "Number of bins required in First Fit " + << "Decreasing : " << firstFitDec(weight, n, c); + return 0; +} + +``` + + + +```jsx showLineNumbers +function firstFit(weight, n, c) { + // Implement firstFit() function here +} + +function firstFitDec(weight, n, c) { + // Sort all weights in decreasing order + weight.sort((a, b) => b - a); + + // Now call firstFit() for sorted items + return 3; +} + +let weight = [2, 5, 4, 7, 1, 3, 8]; +let c = 10; +let n = weight.length; +console.log(`Number of bins required in First Fit Decreasing: ${firstFitDec(weight, n, c)}`); + + + +``` + + + +Output: + +``` +Number of bins required in First Fit Decreasing : 3 +``` + +First Fit decreasing produces the best result for the sample input because items are sorted first. +First Fit Decreasing can also be implemented in O(n Log n) time using Self-Balancing Binary Search Trees. + +Auxiliary Space: O(1) + +## Applications + +- Loading of containers like trucks. +- Placing data on multiple disks. +- Job scheduling. +- Packing advertisements in fixed length radio/TV station breaks. +- Storing a large collection of music onto tapes/CD’s, etc. + + diff --git a/docs/Algorithms/bubble-sort.md b/docs/Algorithms/bubble-sort.md new file mode 100644 index 0000000..29c8140 --- /dev/null +++ b/docs/Algorithms/bubble-sort.md @@ -0,0 +1,58 @@ +# Bubble Sort Algorithm + +Bubble Sort is a simple comparison-based sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing adjacent items and swapping them if they are in the wrong order. The process is repeated until the list is sorted. + +## Algorithm Description + +1. Start at the beginning of the list. +2. Compare the first two elements. If the first element is greater than the second, swap them. +3. Move to the next pair of elements and repeat the comparison and swap if necessary. +4. Continue this process for each pair of adjacent elements to the end of the list. This completes one pass. +5. Repeat the above steps for all elements, reducing the range of comparison each time by one as the last elements will already be sorted. +6. The algorithm stops when no swaps are needed on a new pass, indicating that the list is sorted. + +## Time Complexity + +- **Best Case:** O(n) when the list is already sorted. +- **Average Case:** O(n^2). +- **Worst Case:** O(n^2) when the list is sorted in reverse order. + +## Python Implementation + +Here is a Python implementation of the Bubble Sort algorithm: + +```python +def bubble_sort(arr): + """ + Function to perform Bubble Sort on a list. + + :param arr: List of elements to be sorted. + """ + n = len(arr) + for i in range(n): + swapped = False + for j in range(0, n - i - 1): + if arr[j] > arr[j + 1]: + arr[j], arr[j + 1] = arr[j + 1], arr[j] + swapped = True + # If no elements were swapped in the inner loop, break + if not swapped: + break +``` +# Example usage +if __name__ == "__main__": + arr = [64, 34, 25, 12, 22, 11, 90] + print("Original array:", arr) + bubble_sort(arr) + print("Sorted array:", arr) + +## Explanation +The bubble_sort function takes a list arr as input and sorts it in ascending order using the Bubble Sort algorithm. +The outer loop runs n times, where n is the length of the list. +The inner loop performs the comparison and swapping of adjacent elements. +The swapped flag is used to optimize the algorithm by stopping early if the list is already sorted. +The example usage demonstrates how to use the function and print the original and sorted arrays. + +## Conclusion +Bubble Sort is an easy-to-understand sorting algorithm that is suitable for small datasets or educational purposes. However, due to its O(n^2) time complexity, it is inefficient for large datasets compared to more advanced sorting algorithms like Quick Sort or Merge Sort. + diff --git a/docs/Algorithms/dijkstra.md b/docs/Algorithms/dijkstra.md new file mode 100644 index 0000000..2533663 --- /dev/null +++ b/docs/Algorithms/dijkstra.md @@ -0,0 +1,370 @@ +--- +id: dijkstra +title: Dijkstra's Algorithm +sidebar_label: Dijkstra's Algorithm +tags: [python, java, c++, javascript, programming, algorithms, dijkstra, graph, shortest-path, data structures, tutorial, in-depth] +description: In this tutorial, we will learn about Dijkstra's Algorithm and its implementation in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +# Dijkstra's Algorithm + +Dijkstra's Algorithm is a popular algorithm used for finding the shortest paths between nodes in a graph. This tutorial will cover the basics of Dijkstra's Algorithm, its applications, and how to implement it in Python, Java, C++, and JavaScript. We will also delve into various optimizations and advanced use cases. + +## Introduction to Dijkstra's Algorithm + +Dijkstra's Algorithm was conceived by computer scientist Edsger W. Dijkstra in 1956. It is used to find the shortest path from a starting node to all other nodes in a weighted graph, where the weights represent the cost to traverse from one node to another. + +## How Dijkstra's Algorithm Works + +- **Initialization**: Start with a set of nodes. Assign a tentative distance value to every node: set it to zero for the initial node and to infinity for all other nodes. Set the initial node as the current node. +- **Visit Neighbors**: For the current node, consider all its unvisited neighbors and calculate their tentative distances. Compare the newly calculated tentative distance to the current assigned value and assign the smaller one. +- **Mark Visited**: Once all neighbors are visited, mark the current node as visited. A visited node will not be checked again. +- **Select Next Node**: Select the unvisited node that is marked with the smallest tentative distance and set it as the new current node. +- **Repeat**: Continue the process until all nodes have been visited. + +![image](https://cdn.hashnode.com/res/hashnode/image/upload/v1671745151505/5488136c-81a8-4a65-9d52-fa966d645b3f.png) + +## Pseudocode for Dijkstra's Algorithm + +Here is the pseudocode for Dijkstra's Algorithm: + +``` +function Dijkstra(Graph, source): + create vertex set Q + + for each vertex v in Graph: + dist[v] ← INFINITY + prev[v] ← UNDEFINED + add v to Q + dist[source] ← 0 + + while Q is not empty: + u ← vertex in Q with min dist[u] + remove u from Q + + for each neighbor v of u: + alt ← dist[u] + length(u, v) + if alt < dist[v]: + dist[v] ← alt + prev[v] ← u + + return dist[], prev[] +``` + +## Implementing Dijkstra's Algorithm + + + + ``` Python showLineNumbers +import heapq + +def dijkstra(graph, start): + priority_queue = [(0, start)] + distances = {vertex: float('infinity') for vertex in graph} + distances[start] = 0 + previous_nodes = {vertex: None for vertex in graph} + + while priority_queue: + current_distance, current_vertex = heapq.heappop(priority_queue) + + if current_distance > distances[current_vertex]: + continue + + for neighbor, weight in graph[current_vertex].items(): + distance = current_distance + weight + + if distance < distances[neighbor]: + distances[neighbor] = distance + previous_nodes[neighbor] = current_vertex + heapq.heappush(priority_queue, (distance, neighbor)) + + return distances, previous_nodes + +def shortest_path(graph, start, goal): + distances, previous_nodes = dijkstra(graph, start) + path = [] + while goal: + path.append(goal) + goal = previous_nodes[goal] + return path[::-1] + +graph = { + 'A': {'B': 1, 'C': 4}, + 'B': {'A': 1, 'C': 2, 'D': 5}, + 'C': {'A': 4, 'B': 2, 'D': 1}, + 'D': {'B': 5, 'C': 1} +} + +print(shortest_path(graph, 'A', 'D')) + +``` + + + + +``` jsx showLineNumbers +import java.util.*; + +public class Dijkstra { + + public static void dijkstra(Map> graph, String start) { + PriorityQueue priorityQueue = new PriorityQueue<>(Comparator.comparingInt(node -> node.distance)); + Map distances = new HashMap<>(); + Map previousNodes = new HashMap<>(); + + for (String vertex : graph.keySet()) { + distances.put(vertex, Integer.MAX_VALUE); + previousNodes.put(vertex, null); + } + distances.put(start, 0); + priorityQueue.add(new Node(start, 0)); + + while (!priorityQueue.isEmpty()) { + Node current = priorityQueue.poll(); + + if (current.distance > distances.get(current.name)) { + continue; + } + + for (Map.Entry neighbor : graph.get(current.name).entrySet()) { + int distance = current.distance + neighbor.getValue(); + + if (distance < distances.get(neighbor.getKey())) { + distances.put(neighbor.getKey(), distance); + previousNodes.put(neighbor.getKey(), current.name); + priorityQueue.add(new Node(neighbor.getKey(), distance)); + } + } + } + + for (Map.Entry entry : distances.entrySet()) { + System.out.println(entry.getKey() + " : " + entry.getValue()); + } + } + + public static List shortestPath(Map> graph, String start, String goal) { + dijkstra(graph, start); + List path = new ArrayList<>(); + for (String at = goal; at != null; at = previousNodes.get(at)) { + path.add(at); + } + Collections.reverse(path); + return path; + } + + public static void main(String[] args) { + Map> graph = new HashMap<>(); + graph.put("A", Map.of("B", 1, "C", 4)); + graph.put("B", Map.of("A", 1, "C", 2, "D", 5)); + graph.put("C", Map.of("A", 4, "B", 2, "D", 1)); + graph.put("D", Map.of("B", 5, "C", 1)); + + System.out.println(shortestPath(graph, "A", "D")); + } + + static class Node { + String name; + int distance; + + Node(String name, int distance) { + this.name = name; + this.distance = distance; + } + } +} + +``` + + + +```cpp showLineNumbers +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +typedef pair Node; +typedef unordered_map> Graph; + +unordered_map dijkstra(const Graph& graph, const string& start, unordered_map& previousNodes) { + unordered_map distances; + for (const auto& node : graph) { + distances[node.first] = numeric_limits::max(); + } + distances[start] = 0; + + auto cmp = [](Node left, Node right) { return left.second > right.second; }; + priority_queue, decltype(cmp)> priorityQueue(cmp); + priorityQueue.push({start, 0}); + + while (!priorityQueue.empty()) { + string current = priorityQueue.top().first; + int currentDistance = priorityQueue.top().second; + priorityQueue.pop(); + + if (currentDistance > distances[current]) { + continue; + } + + for (const auto& neighbor : graph.at(current)) { + int distance = currentDistance + neighbor.second; + if (distance < distances[neighbor.first]) { + distances[neighbor.first] = distance; + previousNodes[neighbor.first] = current; + priorityQueue.push({neighbor.first, distance}); + } + } + } + + return distances; +} + +vector shortestPath(const Graph& graph, const string& start, const string& goal) { + unordered_map previousNodes; + dijkstra(graph, start, previousNodes); + + vector path; + for (string at = goal; !at.empty(); at = previousNodes[at]) { + path.push_back(at); + } + reverse(path.begin(), path.end()); + return path; +} + +int main() { + Graph graph = { + {"A", {{"B", 1}, {"C", 4}}}, + {"B", {{"A", 1}, {"C", 2}, {"D", 5}}}, + {"C", {{"A", 4}, {"B", 2}, {"D", 1}}}, + {"D", {{"B", 5}, {"C", 1}}} + }; + + vector path = shortestPath(graph, "A", "D"); + for (const string& node : path) { + cout << node << " "; + } + cout << endl; + return 0; +} + +``` + + + +```jsx showLineNumbers +function dijkstra(graph, start) { + let distances = {}; + let previousNodes = {}; + let priorityQueue = new PriorityQueue(); + + for (let vertex in graph) { + if (vertex === start) { + distances[vertex] = 0; + priorityQueue.enqueue(vertex, 0); + } else { + + + distances[vertex] = Infinity; + priorityQueue.enqueue(vertex, Infinity); + } + previousNodes[vertex] = null; + } + + while (!priorityQueue.isEmpty()) { + let currentVertex = priorityQueue.dequeue().element; + + for (let neighbor in graph[currentVertex]) { + let distance = distances[currentVertex] + graph[currentVertex][neighbor]; + if (distance < distances[neighbor]) { + distances[neighbor] = distance; + previousNodes[neighbor] = currentVertex; + priorityQueue.enqueue(neighbor, distance); + } + } + } + + return { distances, previousNodes }; +} + +function shortestPath(graph, start, goal) { + let { distances, previousNodes } = dijkstra(graph, start); + let path = []; + while (goal) { + path.push(goal); + goal = previousNodes[goal]; + } + return path.reverse(); +} + +class PriorityQueue { + constructor() { + this.values = []; + } + + enqueue(element, priority) { + this.values.push({ element, priority }); + this.sort(); + } + + dequeue() { + return this.values.shift(); + } + + isEmpty() { + return this.values.length === 0; + } + + sort() { + this.values.sort((a, b) => a.priority - b.priority); + } +} + +let graph = { + 'A': { 'B': 1, 'C': 4 }, + 'B': { 'A': 1, 'C': 2, 'D': 5 }, + 'C': { 'A': 4, 'B': 2, 'D': 1 }, + 'D': { 'B': 5, 'C': 1 } +}; + +console.log(shortestPath(graph, 'A', 'D')); + +``` + + + +## Applications of Dijkstra's Algorithm + +- **Network Routing**: Finding the shortest path in network routing protocols such as OSPF. +- **Map Services**: Computing the shortest routes in map services like Google Maps. +- **Robotics**: Pathfinding in autonomous robots to navigate through environments. +- **Game Development**: Pathfinding for game AI to navigate through game worlds. + +## Advanced Topics and Optimizations + +### Bidirectional Dijkstra + +Bidirectional Dijkstra runs two simultaneous searches: one forward from the source and one backward from the target. This can significantly speed up the search in large graphs. + +### Time Complexity + +The time complexity of Dijkstra's Algorithm depends on the data structures used: +- Using a simple list: $O(V^2)$ +- Using a binary heap (priority queue): $O((V + E) log V)$ +- Using a Fibonacci heap: $O(V log V + E)$ + +### Handling Negative Weights + +Dijkstra's Algorithm does not work with graphs that have negative weights. For such graphs, the Bellman-Ford Algorithm or Johnson's Algorithm can be used. + +### Path Reconstruction + +To reconstruct the shortest path from the source to a target node, we can backtrack from the target node using the `previous_nodes` dictionary. + +## Conclusion + +In this tutorial, we covered the fundamentals of Dijkstra's Algorithm, its implementation in Python, Java, C++, and JavaScript, and various optimizations and applications. Dijkstra's Algorithm is a powerful tool for finding the shortest path in graphs and is widely used in numerous domains. By mastering this algorithm, you can effectively solve a variety of shortest path problems in your projects. diff --git a/docs/Algorithms/floyd-warshall.md b/docs/Algorithms/floyd-warshall.md new file mode 100644 index 0000000..abfc93e --- /dev/null +++ b/docs/Algorithms/floyd-warshall.md @@ -0,0 +1,75 @@ +# Floyd-Warshall Algorithm + +The Floyd-Warshall algorithm is an all-pairs shortest path algorithm that finds the shortest paths between all pairs of vertices in a weighted graph. It is particularly useful for dense graphs or when you need to calculate the shortest path between every pair of vertices. + +## Algorithm Description + +The Floyd-Warshall algorithm works by iteratively improving the shortest path between any two vertices (i, j) by considering an intermediate vertex k. The algorithm updates the shortest path matrix with the shortest distance found so far. + +The algorithm uses a matrix `dist` to store the shortest distances between pairs of vertices. The key idea is to update this matrix by checking if a path through an intermediate vertex offers a shorter route than the direct path. + +## Steps + +1. Initialize the distance matrix `dist` with direct distances between vertices. If there is no direct edge between vertices, initialize it with infinity. +2. Set the distance from a vertex to itself as 0. +3. Iterate over all pairs of vertices (i, j) for each intermediate vertex k. +4. Update the distance matrix `dist[i][j]` if a shorter path is found through vertex k. + +## Time Complexity + +The time complexity of the Floyd-Warshall algorithm is O(V^3), where V is the number of vertices in the graph. + +## Python Implementation + +Here is a Python implementation of the Floyd-Warshall algorithm: + +```python +def floyd_warshall(graph): + """ + Floyd-Warshall algorithm to find the shortest paths between all pairs of vertices. + + :param graph: 2D list representing the adjacency matrix of the graph + :return: 2D list representing the shortest distance matrix + """ + # Number of vertices in the graph + V = len(graph) + + # Initialize the distance matrix with the input graph matrix + dist = [list(row) for row in graph] + + # Iterate over all intermediate vertices + for k in range(V): + # Iterate over all pairs of vertices + for i in range(V): + for j in range(V): + # Update the distance matrix if a shorter path is found + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) + + return dist +``` +# Example usage +if __name__ == "__main__": + # Define the adjacency matrix of the graph + # Infinity represents no direct path between vertices + INF = float('inf') + graph = [ + [0, 3, INF, 5], + [2, 0, INF, 4], + [INF, 1, 0, INF], + [INF, INF, 2, 0] + ] + + # Find the shortest paths between all pairs of vertices + shortest_paths = floyd_warshall(graph) + + # Print the shortest distance matrix + for row in shortest_paths: + print(row) +## Explanation +The floyd_warshall function takes a graph represented as an adjacency matrix and returns the shortest distance matrix. +The outer loop iterates over all possible intermediate vertices k. +The nested loops iterate over all pairs of vertices (i, j) and update the distance dist[i][j] if a shorter path is found through vertex k. +The example usage demonstrates how to use the function and print the shortest distance matrix. + +## Conclusion +The Floyd-Warshall algorithm is a powerful and simple algorithm for finding shortest paths in weighted graphs. Its cubic time complexity makes it suitable for smaller graphs, but it can handle dense graphs effectively. diff --git a/docs/Algorithms/hashing.md b/docs/Algorithms/hashing.md new file mode 100644 index 0000000..0e9e95e --- /dev/null +++ b/docs/Algorithms/hashing.md @@ -0,0 +1,323 @@ +--- +id: hashing +title: Hashing +sidebar_label: Hashing +tags: [python, java, c++, javascript, programming, algorithms, data structures, tutorial, in-depth] +description: In this tutorial, we will learn about Hash Tables, their uses, how they work, and hashing in general with detailed explanations and examples. +--- + +# Hash Tables + +Hash tables are a fundamental data structure in computer science used for fast data retrieval. This tutorial will cover the basics of hash tables, their uses, how they work, and the concept of hashing in general. + +## Introduction to Hash Tables + +A hash table, also known as a hash map, is a data structure that stores key-value pairs. It provides efficient insertion, deletion, and lookup operations, typically in constant average time complexity, $O(1)$. + +## Uses of Hash Tables + +Hash tables are widely used in various applications due to their efficiency and versatility. Some common uses include: + +- **Databases**: Implementing indexes to speed up data retrieval. +- **Caching**: Storing recently accessed data to quickly serve future requests. +- **Dictionaries**: Implementing associative arrays or dictionaries, where each key is associated with a value. +- **Symbol Tables**: Managing variable names in interpreters and compilers. +- **Sets**: Implementing sets, which allow for fast membership testing. + +## Working of Hash Tables + +A hash table works by mapping keys to indices in an array. This mapping is achieved using a hash function. The hash function takes a key and returns an integer, which is used as an index to store the corresponding value in the array. + +### Components of a Hash Table + +1. **Hash Function**: Converts keys into valid array indices. +2. **Buckets**: Array elements where key-value pairs are stored. +3. **Collision Resolution**: Strategy to handle cases where multiple keys map to the same index. + +![hashing](https://khalilstemmler.com/img/blog/data-structures/hash-tables/hash-table.png) +### Hash Function + +The hash function is crucial for the performance of a hash table. It should be fast to compute and distribute keys uniformly across the array. A common hash function for integers is `h(key) = key % N`, where `N` is the size of the array. + +### Collision Resolution + +Collisions occur when multiple keys hash to the same index. There are several strategies to resolve collisions: + +- **Chaining**: Store multiple key-value pairs in a list at each index. +- **Open Addressing**: Find another index within the array using methods like linear probing, quadratic probing, or double hashing. + +## Hashing in General + +Hashing is the process of converting input data (keys) into a fixed-size integer, which serves as an index for data storage and retrieval. Hashing is widely used beyond hash tables in various fields such as cryptography, data structures, and databases. + +### Properties of a Good Hash Function + +1. **Deterministic**: The hash function must consistently return the same hash value for the same input. +2. **Uniform Distribution**: It should distribute hash values uniformly across the hash table to minimize collisions. +3. **Efficient Computation**: The hash function should be quick to compute. +4. **Minimally Correlated**: Hash values should be independent of each other to avoid clustering. + +### Common Hash Functions + +- **Division Method**: `h(key) = key % N` +- **Multiplication Method**: `h(key) = floor(N * (key * A % 1))`, where `A` is a constant between 0 and 1. +- **Universal Hashing**: Uses a class of hash functions and selects one at random to minimize the chance of collisions. + +## Implementing Hash Tables + + + +```Python showLineNumbers +class HashTable: + def __init__(self, size): + self.size = size + self.table = [[] for _ in range(size)] + + def hash_function(self, key): + return hash(key) % self.size + + def insert(self, key, value): + index = self.hash_function(key) + for i, kv in enumerate(self.table[index]): + if kv[0] == key: + self.table[index][i] = (key, value) + return + self.table[index].append((key, value)) + + def lookup(self, key): + index = self.hash_function(key) + for kv in self.table[index]: + if kv[0] == key: + return kv[1] + return None + + def delete(self, key): + index = self.hash_function(key) + for i, kv in enumerate(self.table[index]): + if kv[0] == key: + del self.table[index][i] + return + +# Example usage +ht = HashTable(10) +ht.insert("apple", 1) +ht.insert("banana", 2) +print(ht.lookup("apple")) # Output: 1 +ht.delete("apple") +print(ht.lookup("apple")) # Output: None + +``` + + + +```jsx showLineNumbers +import java.util.LinkedList; + +class HashTable { + private class Entry { + K key; + V value; + Entry(K key, V value) { + this.key = key; + this.value = value; + } + } + + private LinkedList>[] table; + private int size; + + @SuppressWarnings("unchecked") + public HashTable(int size) { + this.size = size; + table = new LinkedList[size]; + for (int i = 0; i < size; i++) { + table[i] = new LinkedList<>(); + } + } + + private int hashFunction(K key) { + return key.hashCode() % size; + } + + public void insert(K key, V value) { + int index = hashFunction(key); + for (Entry entry : table[index]) { + if (entry.key.equals(key)) { + entry.value = value; + return; + } + } + table[index].add(new Entry<>(key, value)); + } + + public V lookup(K key) { + int index = hashFunction(key); + for (Entry entry : table[index]) { + if (entry.key.equals(key)) { + return entry.value; + } + } + return null; + } + + public void delete(K key) { + int index = hashFunction(key); + table[index].removeIf(entry -> entry.key.equals(key)); + } + + public static void main(String[] args) { + HashTable ht = new HashTable<>(10); + ht.insert("apple", 1); + ht.insert("banana", 2); + System.out.println(ht.lookup("apple")); // Output: 1 + ht.delete("apple"); + System.out.println(ht.lookup("apple")); // Output: null + } +} + +``` + + +```cpp showLineNumbers +#include +#include +#include +#include + +using namespace std; + +class HashTable { +private: + int size; + vector>> table; + + int hashFunction(const string &key) { + return hash{}(key) % size; + } + +public: + HashTable(int size) : size(size), table(size) {} + + void insert(const string &key, int value) { + int index = hashFunction(key); + for (auto &kv : table[index]) { + if (kv.first == key) { + kv.second = value; + return; + } + } + table[index].emplace_back(key, value); + } + + int lookup(const string &key) { + int index = hashFunction(key); + for (const auto &kv : table[index]) { + if (kv.first == key) { + return kv.second; + } + } + return -1; // Return -1 if key not found + } + + void delete_key(const string &key) { + int index = hashFunction(key); + table[index].remove_if([&key](const pair &kv) { return kv.first == key; }); + } +}; + +int main() { + HashTable ht(10); + ht.insert("apple", 1); + ht.insert("banana", 2); + cout << ht.lookup("apple") << endl; // Output: 1 + ht.delete_key("apple"); + cout << ht.lookup("apple") << endl; // Output: -1 + return 0; +} + +``` + + + +```jsx showLineNumbers +class HashTable { + constructor(size) { + this.size = size; + this.table = new Array(size).fill(null).map(() => []); + } + + hashFunction(key) { + let hash = 0; + for (let char of key) { + hash += char.charCodeAt(0); + } + return hash % this.size; + } + + insert(key, value) { + const index = this.hashFunction(key); + for (let [k, v] of this.table[index]) { + if (k === key) { + v = value; + return; + } + } + this.table[index].push([key, value]); + } + + lookup(key) { + const index = this.hashFunction(key); + for (let [k, v] of this.table[index]) { + if (k === key) { + return v; + } + } + return null; + } + + delete(key) { + const index = this.hashFunction(key); + this.table[index] = this.table[index].filter(([k, v]) => k !== key); + } +} + +const ht = new HashTable(10); +ht.insert("apple", 1); +ht.insert("banana", 2); +console.log(ht.lookup("apple")); // Output: 1 +ht.delete("apple"); +console.log(ht.lookup("apple")); + + // Output: null + +``` + + + +## Time Complexity Analysis + +- **Insertion**: $O(1)$ on average +- **Deletion**: $O(1)$ on average +- **Lookup**: $O(1)$ on average + +## Space Complexity Analysis + +- **Space Complexity**: $O(n)$ where n is the number of key-value pairs + +## Advanced Topics + +### Dynamic Resizing + +When the load factor (number of elements/size of table) exceeds a threshold, the hash table can be resized to maintain performance. This involves creating a new table with a larger size and rehashing all existing elements. + +### Cryptographic Hash Functions + +In cryptography, hash functions are used to secure data. These hash functions are designed to be irreversible and produce a fixed-size hash value for any input. + +### Bloom Filters + +A Bloom filter is a space-efficient probabilistic data structure used to test whether an element is a member of a set. It uses multiple hash functions to map elements to a bit array. + +## Conclusion + +In this tutorial, we covered the fundamentals of hash tables, their uses, how they work, and the concept of hashing in general. We also provided implementations in Python, Java, C++, and JavaScript. Hash tables are a powerful and efficient data structure that play a crucial role in various applications. Understanding how they work and how to implement them will greatly enhance your programming skills and ability to solve complex problems efficiently. \ No newline at end of file diff --git a/docs/Algorithms/kruskal's.md b/docs/Algorithms/kruskal's.md new file mode 100644 index 0000000..306f595 --- /dev/null +++ b/docs/Algorithms/kruskal's.md @@ -0,0 +1,345 @@ +--- +id: kruskal's +title: Kruskal's Graph Algorithm +sidebar_label: Kruskal's Algorithm +tags: + - dsa + - data-structures + - graph + - graph-traversal + - algorithm + - javascript + - python + - c++ + - java + - Minimum Spanning Tree + - programming + - tutorial +sidebar_position: 3 +--- +Kruskal's algorithm is a popular method used to find the minimum spanning tree (MST) of a connected, undirected graph. A minimum spanning tree is a subset of the edges in a graph that connects all the vertices together, wihout any cycles, and with minimum possible total edge weight. +### Key Concepts: +* Edge Selection: The algorithm picks the smallest weight edge first and uses a greedy approach to ensure the overall minimum weight for the spanning tree. +* Cycle Detection: To check efficiently if adding a new edge forms a cycle, the algorithm uses union-find (Disjoint set union) function for that. +### To find MST using Kruskal's algorithm +Following steps are used to find the MST: +1. Sort the edges in ascending order of their weight. +2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If the cycle is not formed, include this edge. Else, discard it. +3. Repeat step 2 until there are (V-1) edges in the spanning tree. +### Implementation: +![image](https://wat-images.s3.ap-south-1.amazonaws.com/images/ps/minimum-spanning-tree-using-kruskals-algorithm.svg) + +Program for the Kruskal's algorithm: + + + + ```Cpp showLineNumbers + //kruskals algorithm +#include +#include +#define I INT32_MAX +using namespace std; +void Union(int u, int v,vector&s)// here u and v are the head of two sets +{ + // the one with more child will become the ultimate head + if (s[u]&s)// u is the element whose parent we need to find +{ + int x=u; + int v=0; + while(s[x]>0) + { + x=s[x]; + } + + return x; +} +vector> kruskals_algo(vector>&G,int n,int a) +{ + vectorset(a,-1); + vectorincluded(n,0); + vector>sol(2,vector(a-1)); + int i=0,j,k,min,u,v; + while(i>n; + cout<<"Enter the number of vertexes: "; + cin>>a; + vector>G(3,vector(n)); + for (int i=0;i<3;i++) + { + for (int j=0;j>G[i][j]; + } + vector>res=kruskals_algo(G,n,a); + cout<<"Kruskals path is: "< + + +```Python showLineNumbers +import sys + +def union(u, v, s): + if s[u] < s[v]: + s[u] += s[v] + s[v] = u + else: + s[v] += s[u] + s[u] = v + +def find(u, s): + x = u + while s[x] > 0: + x = s[x] + return x + +def kruskals_algo(G, n, a): + set = [-1] * a + included = [0] * n + sol = [[0] * (a - 1) for _ in range(2)] + i = 0 + while i < a - 1: + min = sys.maxsize + for j in range(n): + if included[j] == 0 and G[2][j] < min: + min = G[2][j] + k = j + u = G[0][j] + v = G[1][j] + x = find(u, set) + y = find(v, set) + if x != y: + sol[0][i] = u + sol[1][i] = v + union(x, y, set) + i += 1 + included[k] = 1 + return sol + +if __name__ == "__main__": + n = int(input("Enter the number of edges: ")) + a = int(input("Enter the number of vertices: ")) + G = [list(map(int, input().split())) for _ in range(3)] + res = kruskals_algo(G, n, a) + print("Kruskal's path is: ") + for i in range(2): + print(" ".join(map(str, res[i]))) + +``` + + + +``` jsx showLineNumbers +import java.util.*; + +public class KruskalsAlgorithm { + static void union(int u, int v, int[] s) { + if (s[u] < s[v]) { + s[u] += s[v]; + s[v] = u; + } else { + s[v] += s[u]; + s[u] = v; + } + } + + static int find(int u, int[] s) { + int x = u; + while (s[x] > 0) { + x = s[x]; + } + return x; + } + + static int[][] kruskals_algo(int[][] G, int n, int a) { + int[] set = new int[a]; + Arrays.fill(set, -1); + int[] included = new int[n]; + int[][] sol = new int[2][a - 1]; + int i = 0; + while (i < a - 1) { + int min = Integer.MAX_VALUE; + int u = 0, v = 0, k = 0; + for (int j = 0; j < n; j++) { + if (included[j] == 0 && G[2][j] < min) { + min = G[2][j]; + k = j; + u = G[0][j]; + v = G[1][j]; + } + } + int x = find(u, set); + int y = find(v, set); + if (x != y) { + sol[0][i] = u; + sol[1][i] = v; + union(x, y, set); + i++; + } + included[k] = 1; + } + return sol; + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.print("Enter the number of edges: "); + int n = scanner.nextInt(); + System.out.print("Enter the number of vertices: "); + int a = scanner.nextInt(); + int[][] G = new int[3][n]; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < n; j++) { + G[i][j] = scanner.nextInt(); + } + } + int[][] res = kruskals_algo(G, n, a); + System.out.println("Kruskal's path is: "); + for (int i = 0; i < 2; i++) { + for (int j = 0; j < a - 1; j++) { + System.out.print(res[i][j] + " "); + } + System.out.println(); + } + scanner.close(); + } +} +``` + + + +``` jsx showLineNumbers +function union(u, v, s) { + if (s[u] < s[v]) { + s[u] += s[v]; + s[v] = u; + } else { + s[v] += s[u]; + s[u] = v; + } +} + +function find(u, s) { + let x = u; + while (s[x] > 0) { + x = s[x]; + } + return x; +} + +function kruskalsAlgo(G, n, a) { + let set = new Array(a).fill(-1); + let included = new Array(n).fill(0); + let sol = [new Array(a - 1), new Array(a - 1)]; + let i = 0; + while (i < a - 1) { + let min = Number.MAX_SAFE_INTEGER; + let u, v, k; + for (let j = 0; j < n; j++) { + if (included[j] === 0 && G[2][j] < min) { + min = G[2][j]; + k = j; + u = G[0][j]; + v = G[1][j]; + } + } + let x = find(u, set); + let y = find(v, set); + if (x !== y) { + sol[0][i] = u; + sol[1][i] = v; + union(x, y, set); + i++; + } + included[k] = 1; + } + return sol; +} + +function main() { + const n = parseInt(prompt("Enter the number of edges: ")); + const a = parseInt(prompt("Enter the number of vertices: ")); + let G = []; + for (let i = 0; i < 3; i++) { + G.push(prompt(`Enter row ${i} of graph:`).split(' ').map(Number)); + } + let res = kruskalsAlgo(G, n, a); + console.log("Kruskal's path is: "); + for (let i = 0; i < 2; i++) { + console.log(res[i].join(' ')); + } +} + +main(); +``` + + + +Output:
+ +``` +/*input is in the format row one u, row two v and row three weight between u and v*/ +Enter the number of edges: 8 +Enter the number of vertexes: 7 +0 0 0 1 1 3 6 4 +1 3 6 2 4 4 4 5 +2 3 4 3 2 5 6 7 +Kruskals path is: +0 1 0 1 0 4 +1 4 3 2 6 5 + +``` +### Time and Space Complexity: +* Time complexity: The time complexity of kruskal's algorithm depends on two operations i.e. sorting of all edges and union-find operation.Thus, the overall time complexity is: $O(ElogV)$ +* Space complexity: The space complexity of kruskal's algorithm includes storage for edges, union-find data structure and storage for the MST. Thus the overall space complexity is: $O(E+V)$ diff --git a/docs/Algorithms/moores-voting-algorithm.md b/docs/Algorithms/moores-voting-algorithm.md new file mode 100644 index 0000000..9e7db89 --- /dev/null +++ b/docs/Algorithms/moores-voting-algorithm.md @@ -0,0 +1,250 @@ +--- +id: moores-voting-algorithm +title: Moore's Voting Algorithm +sidebar_label: Moore's Voting Algorithm +tags: [python, java, c++, javascript, programming, algorithms, subarray, array, tutorial, in-depth , Hash Table,Divide and Conquer,Sorting ,Counting] +description: In this tutorial, we will learn about Moore's Voting Algorithm and its implementation in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +# Moore's Voting Algorithm +The Boyer-Moore voting algorithm is one of the popular optimal algorithms which is used to find the majority element among the given elements that have more than `N/ 2` occurrences. This works perfectly fine for finding the majority element which takes 2 traversals over the given elements, which works in $O(N)$ time complexity and $O(1)$ space complexity. + +## Problem Statement +Given an array nums of size n, return the majority element. +The majority element is the element that appears more than `n / 2` times. You may assume that the majority element always exists in the array. + +### Intuition + - We will run a loop that will select the elements of the array one by one. + - Now, for each element, we will run another loop and count its occurrence in the given array. + - If any element occurs more than the floor of $(N/2)$, we will simply return it. + +## Brute Force Approach +```c++ +int majorityElement(vector v) { + //size of the given array: + int n = v.size(); + + for (int i = 0; i < n; i++) { + //selected element is v[i] + int cnt = 0; + for (int j = 0; j < n; j++) { + // counting the frequency of v[i] + if (v[j] == v[i]) { + cnt++; + } + } + + // check if frquency is greater than n/2: + if (cnt > (n / 2)) + return v[i]; + } + + return -1; +} +``` +#### Time Complexity : $O(n^2)$ +#### Spcae Complexity : $O(1)$ +## Better Approach - Hashmap +#### Intuition + - Use a hashmap and store as (key, value) pairs. (Can also use frequency array based on the size of nums) + - Here the key will be the element of the array and the value will be the number of times it occurs. + - Traverse the array and update the value of the key. Simultaneously check if the value is greater than the floor of N/2. + - If yes, return the key + - Else iterate forward. + + +```c++ +int majorityElement(vector v) { + + //size of the given array: + int n = v.size(); + + //declaring a map: + map mpp; + + //storing the elements with its occurnce: + for (int i = 0; i < n; i++) { + mpp[v[i]]++; + } + + //searching for the majority element: + for (auto it : mpp) { + if (it.second > (n / 2)) { + return it.first; + } + } + + return -1; +} +``` +#### Time Complexity : $O(nlogn)$ +#### Spcae Complexity : $O(n)$ + +## Optimized Approach - Moore's Voting Algorithm +#### Intuition +If the array contains a majority element, its occurrence must be greater than the floor(N/2). Now, we can say that the count of minority elements and majority elements is equal up to a certain point in the array. So when we traverse through the array we try to keep track of the count of elements and the element itself for which we are tracking the count. + +After traversing the whole array, we will check the element stored in the variable. If the question states that the array must contain a majority element, the stored element will be that one but if the question does not state so, then we need to check if the stored element is the majority element or not. If not, then the array does not contain any majority element. + +#### Steps +- Initialize 2 variables: + Count – for tracking the count of element + Element – for which element we are counting +- Traverse through the given array. + If Count is 0 then store the current element of the array as Element. + If the current element and Element are the same increase the Count by 1. + If they are different decrease the Count by 1. +- The integer present in Element should be the result we are expecting + +## Implementing Moore's Voting Algorithm + +### Python Implementation + +```python +def majorityElement(arr): + # Size of the given array + n = len(arr) + cnt = 0 # Count + el = None # Element + + # Applying the algorithm + for i in range(n): + if cnt == 0: + cnt = 1 + el = arr[i] + elif el == arr[i]: + cnt += 1 + else: + cnt -= 1 + + # Checking if the stored element is the majority element + cnt1 = 0 + for i in range(n): + if arr[i] == el: + cnt1 += 1 + + if cnt1 > (n / 2): + return el + return -1 +``` + +### Java Implementation + +```java +import java.util.*; + +public class tUf { + public static int majorityElement(int []v) { + //size of the given array: + int n = v.length; + int cnt = 0; // count + int el = 0; // Element + + //applying the algorithm: + for (int i = 0; i < n; i++) { + if (cnt == 0) { + cnt = 1; + el = v[i]; + } else if (el == v[i]) cnt++; + else cnt--; + } + + //checking if the stored element + // is the majority element: + int cnt1 = 0; + for (int i = 0; i < n; i++) { + if (v[i] == el) cnt1++; + } + + if (cnt1 > (n / 2)) return el; + return -1; + } + + public static void main(String args[]) { + int[] arr = {2, 2, 1, 1, 1, 2, 2}; + int ans = majorityElement(arr); + System.out.println("The majority element is: " + ans); + + } + +} +``` + +### C++ Implementation + +```cpp +int majorityElement(vector v) { + + //size of the given array: + int n = v.size(); + int cnt = 0; // count + int el; // Element + + //applying the algorithm: + for (int i = 0; i < n; i++) { + if (cnt == 0) { + cnt = 1; + el = v[i]; + } + else if (el == v[i]) cnt++; + else cnt--; + } + + //checking if the stored element + // is the majority element: + int cnt1 = 0; + for (int i = 0; i < n; i++) { + if (v[i] == el) cnt1++; + } + + if (cnt1 > (n / 2)) return el; + return -1; +} +``` + +### JavaScript Implementation + +```javascript +function majorityElement(arr) { + // Size of the given array + let n = arr.length; + let cnt = 0; // Count + let el; // Element + + // Applying the algorithm + for (let i = 0; i < n; i++) { + if (cnt === 0) { + cnt = 1; + el = arr[i]; + } else if (el === arr[i]) { + cnt++; + } else { + cnt--; + } + } + + // Checking if the stored element is the majority element + let cnt1 = 0; + for (let i = 0; i < n; i++) { + if (arr[i] === el) { + cnt1++; + } + } + + if (cnt1 > Math.floor(n / 2)) { + return el; + } + return -1; +} + +``` + +## Complexity Analysis + #### Time Complexity : $O(n)$ + #### Space Complexity : $O(1)$ + +## Conclusion +- Moore's Voting Algorithm concludes by returning the majority element, if it exists, otherwise, -1. + + + diff --git a/docs/Algorithms/prim.md b/docs/Algorithms/prim.md new file mode 100644 index 0000000..ef6fff4 --- /dev/null +++ b/docs/Algorithms/prim.md @@ -0,0 +1,407 @@ +--- +id: prim +title: Prim's Algorithm +sidebar_label: Prim's Algorithm +tags: [python, java, c++, javascript, programming, algorithms, dijkstra, graph, shortest-path, data structures, tutorial, in-depth] +description: In this tutorial, we will learn about Prim's Algorithm and its implementation in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +# Prim's Algorithm + +Prim's Algorithm is a greedy algorithm that is used to find the minimum spanning tree from a graph. Prim's algorithm finds the subset of edges that includes every vertex of the graph such that the sum of the weights of the edges can be minimized. + +## Introduction to Prim's Algorithm + +Prim's algorithm starts with the single node and explores all the adjacent nodes with all the connecting edges at every step. The edges with the minimal weights causing no cycles in the graph got selected. + +## How Prim's Algorithm Works + +Prim's algorithm is a greedy algorithm that starts from one vertex and continue to add the edges with the smallest weight until the goal is reached. The steps to implement the prim's algorithm are given as follows - + +First, we have to initialize an MST with the randomly chosen vertex. +Now, we have to find all the edges that connect the tree in the above step with the new vertices. From the edges found, select the minimum edge and add it to the tree. +Repeat step 2 until the minimum spanning tree is formed. + +![image](https://cdn.hashnode.com/res/hashnode/image/upload/v1671745151505/5488136c-81a8-4a65-9d52-fa966d645b3f.png) + +## Pseudocode for Prim's Algorithm + +Here is the pseudocode for Prim's Algorithm: + +``` +prim(graph): + # Initialize an empty set to hold the vertices in the minimum spanning tree + mst = empty set + + # Select the first vertex to start the tree + startVertex = first vertex in graph + mst.add(startVertex) + + # Initialize the set of edges to consider + edges = edges connected to startVertex + + # Iterate until all vertices are in the minimum spanning tree + while mst has fewer vertices than graph: + # Find the minimum edge in the set of edges + minEdge, minWeight = findMinEdge(edges) + + # Add the vertex to the minimum spanning tree + mst.add(minEdge) + + # Add the edges connected to the vertex to the set of edges to consider + for edge in edges connected to minEdge: + if edge is not in mst: + edges.add(edge) + + # Remove the minimum edge from the set of edges to consider + edges.remove(minEdge) + + # Return the minimum spanning tree as an array + return mst as an array +``` + +## Implementing Prim's Algorithm + +### Python Implementation + +```python +import heapq + +def prim(graph, start_vertex): + mst = [] + visited = set() + min_heap = [(0, start_vertex, None)] # (weight, vertex, from_vertex) + + while min_heap: + weight, vertex, from_vertex = heapq.heappop(min_heap) + + if vertex not in visited: + visited.add(vertex) + if from_vertex is not None: + mst.append((from_vertex, vertex, weight)) + + for neighbor, edge_weight in graph[vertex]: + if neighbor not in visited: + heapq.heappush(min_heap, (edge_weight, neighbor, vertex)) + + return mst + +# Example usage +graph = { + 'A': [('B', 2), ('D', 6)], + 'B': [('A', 2), ('C', 3), ('D', 8)], + 'C': [('B', 3), ('D', 5), ('E', 7)], + 'D': [('A', 6), ('B', 8), ('C', 5), ('E', 9)], + 'E': [('C', 7), ('D', 9)] +} + +start_vertex = 'A' +mst = prim(graph, start_vertex) + +print("Edges in the Minimum Spanning Tree:") +for edge in mst: + print(edge) + +``` + +### Java Implementation + +```java +import java.util.*; + +class Edge implements Comparable { + int weight; + int vertex; + + Edge(int weight, int vertex) { + this.weight = weight; + this.vertex = vertex; + } + + public int compareTo(Edge other) { + return Integer.compare(this.weight, other.weight); + } +} + +public class PrimAlgorithm { + + public static void prim(List> graph, int startVertex) { + int n = graph.size(); + boolean[] visited = new boolean[n]; + PriorityQueue minHeap = new PriorityQueue<>(); + List mst = new ArrayList<>(); + + // Initialize the min-heap with the starting vertex + minHeap.add(new Edge(0, startVertex)); + + while (!minHeap.isEmpty()) { + Edge edge = minHeap.poll(); + int weight = edge.weight; + int vertex = edge.vertex; + + if (visited[vertex]) continue; + + visited[vertex] = true; + + if (vertex != startVertex) { + mst.add(edge); + } + + for (Edge neighbor : graph.get(vertex)) { + if (!visited[neighbor.vertex]) { + minHeap.add(neighbor); + } + } + } + + // Output the MST edges and their weights + System.out.println("Edges in the Minimum Spanning Tree:"); + for (Edge e : mst) { + System.out.println("Vertex: " + e.vertex + ", Weight: " + e.weight); + } + } + + public static void main(String[] args) { + int n = 5; // Number of vertices + List> graph = new ArrayList<>(); + + for (int i = 0; i < n; i++) { + graph.add(new ArrayList<>()); + } + + // Add edges to the graph + graph.get(0).add(new Edge(2, 1)); // A - B + graph.get(0).add(new Edge(6, 3)); // A - D + graph.get(1).add(new Edge(2, 0)); // B - A + graph.get(1).add(new Edge(3, 2)); // B - C + graph.get(1).add(new Edge(8, 3)); // B - D + graph.get(2).add(new Edge(3, 1)); // C - B + graph.get(2).add(new Edge(5, 3)); // C - D + graph.get(2).add(new Edge(7, 4)); // C - E + graph.get(3).add(new Edge(6, 0)); // D - A + graph.get(3).add(new Edge(8, 1)); // D - B + graph.get(3).add(new Edge(5, 2)); // D - C + graph.get(3).add(new Edge(9, 4)); // D - E + graph.get(4).add(new Edge(7, 2)); // E - C + graph.get(4).add(new Edge(9, 3)); // E - D + + int startVertex = 0; // Starting from vertex A (0) + + prim(graph, startVertex); + } +} + +``` + +### C++ Implementation + +```cpp +#include +#include +#include +#include + +using namespace std; + +typedef pair Edge; // (weight, vertex) + +void prim(const vector>& graph, int startVertex) { + int n = graph.size(); + vector visited(n, false); + priority_queue, greater> minHeap; + vector mst; + + // Initialize the min-heap with the starting vertex + minHeap.push({0, startVertex}); + + while (!minHeap.empty()) { + int weight = minHeap.top().first; + int vertex = minHeap.top().second; + minHeap.pop(); + + if (visited[vertex]) continue; + + visited[vertex] = true; + + if (vertex != startVertex) { + mst.push_back({weight, vertex}); + } + + for (const auto& neighbor : graph[vertex]) { + if (!visited[neighbor.second]) { + minHeap.push(neighbor); + } + } + } + + // Output the MST edges and their weights + cout << "Edges in the Minimum Spanning Tree:" << endl; + for (const auto& edge : mst) { + cout << "Vertex: " << edge.second << ", Weight: " << edge.first << endl; + } +} + +int main() { + int n = 5; // Number of vertices + vector> graph(n); + + // Add edges to the graph + graph[0].push_back({2, 1}); // A - B + graph[0].push_back({6, 3}); // A - D + graph[1].push_back({2, 0}); // B - A + graph[1].push_back({3, 2}); // B - C + graph[1].push_back({8, 3}); // B - D + graph[2].push_back({3, 1}); // C - B + graph[2].push_back({5, 3}); // C - D + graph[2].push_back({7, 4}); // C - E + graph[3].push_back({6, 0}); // D - A + graph[3].push_back({8, 1}); // D - B + graph[3].push_back({5, 2}); // D - C + graph[3].push_back({9, 4}); // D - E + graph[4].push_back({7, 2}); // E - C + graph[4].push_back({9, 3}); // E - D + + int startVertex = 0; // Starting from vertex A (0) + + prim(graph, startVertex); + + return 0; +} + +``` + +### JavaScript Implementation + +```javascript +class MinHeap { + constructor() { + this.heap = []; + } + + insert(value) { + this.heap.push(value); + this.bubbleUp(this.heap.length - 1); + } + + extractMin() { + if (this.heap.length === 1) { + return this.heap.pop(); + } + const min = this.heap[0]; + this.heap[0] = this.heap.pop(); + this.bubbleDown(0); + return min; + } + + bubbleUp(index) { + while (index > 0) { + const parentIndex = Math.floor((index - 1) / 2); + if (this.heap[parentIndex][0] <= this.heap[index][0]) { + break; + } + [this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]]; + index = parentIndex; + } + } + + bubbleDown(index) { + const length = this.heap.length; + while (true) { + const leftChildIndex = 2 * index + 1; + const rightChildIndex = 2 * index + 2; + let smallest = index; + + if (leftChildIndex < length && this.heap[leftChildIndex][0] < this.heap[smallest][0]) { + smallest = leftChildIndex; + } + if (rightChildIndex < length && this.heap[rightChildIndex][0] < this.heap[smallest][0]) { + smallest = rightChildIndex; + } + if (smallest === index) break; + + [this.heap[smallest], this.heap[index]] = [this.heap[index], this.heap[smallest]]; + index = smallest; + } + } + + isEmpty() { + return this.heap.length === 0; + } +} + +function prim(graph, startVertex) { + const mst = []; + const visited = new Set(); + const minHeap = new MinHeap(); + minHeap.insert([0, startVertex, null]); + + while (!minHeap.isEmpty()) { + const [weight, vertex, fromVertex] = minHeap.extractMin(); + + if (!visited.has(vertex)) { + visited.add(vertex); + if (fromVertex !== null) { + mst.push([fromVertex, vertex, weight]); + } + + graph[vertex].forEach(([neighbor, edgeWeight]) => { + if (!visited.has(neighbor)) { + minHeap.insert([edgeWeight, neighbor, vertex]); + } + }); + } + } + + return mst; +} + +// Example usage +const graph = { + 'A': [['B', 2], ['D', 6]], + 'B': [['A', 2], ['C', 3], ['D', 8]], + 'C': [['B', 3], ['D', 5], ['E', 7]], + 'D': [['A', 6], ['B', 8], ['C', 5], [' + +``` + +## Applications of Prim's Algorithm + +- **Network Design**: Prim's algorithm helps in designing efficient communication networks by minimizing the cost of laying cables or fiber optics to connect various nodes (e.g., telephone lines, internet connections). +- **Transportation Networks**: Helps in planning the construction of roads, highways, and railways to connect various cities or locations with the minimum total distance or cost. +- **Computer Networks**: Helps in determining the optimal routing paths in networks to ensure data is transmitted efficiently with minimal delay and cost. + +- **Cluster Analysis**: In machine learning and data mining, Prim's algorithm can be used to cluster data points by constructing a Minimum Spanning Tree and then cutting the most expensive edges to form clusters. + +## Advanced Topics and Optimizations + +Parallel and Distributed Implementations: + +### Parallel Prim's Algorithm: +Implementing Prim's algorithm in a parallel computing environment can significantly reduce computation time by distributing the workload across multiple processors. Parallel algorithms often involve dividing the graph into subgraphs, computing local MSTs, and then merging them. + +### Distributed Prim's Algorithm: + In distributed systems, where the graph is too large to fit into a single machine's memory, Prim's algorithm can be adapted to run across multiple machines, each handling a portion of the graph. +External Memory Algorithms: + +For very large graphs that cannot fit into the main memory, external memory algorithms are used. These algorithms are designed to efficiently manage the transfer of data between the external storage (e.g., disk) and the main memory, minimizing I/O operations. +Dynamic Graphs: + +### Incremental MST: +If edges are added to the graph dynamically, the MST can be updated without recomputing it from scratch. This involves maintaining the MST and efficiently incorporating the new edges. +Decremental MST: If edges are removed from the graph, the MST can be adjusted accordingly. This requires techniques to efficiently update the MST when edges are deleted. + +## Optimizations: + +### Fibonacci Heap: +Using a Fibonacci heap for the priority queue operations in Prim's algorithm reduces the time complexity to +O(VlogV+E), making it more efficient for dense graphs. + +### Pairing Heap: +Another alternative is the pairing heap, which provides a good balance between theoretical complexity and practical performance. + +### Edge Filtering: +Before running Prim's algorithm, irrelevant edges (e.g., edges that are obviously too heavy) can be filtered out. This preprocessing step reduces the number of edges that the algorithm needs to process. + +### Early Termination: + +If the graph is already known to be connected and certain properties are met (e.g., the graph is sparse), Prim's algorithm can be optimized to terminate early once the MST is guaranteed to be found. \ No newline at end of file diff --git a/docs/Algorithms/prims.md b/docs/Algorithms/prims.md new file mode 100644 index 0000000..abb099b --- /dev/null +++ b/docs/Algorithms/prims.md @@ -0,0 +1,330 @@ +--- + +id: prims +title: Prim's Algorithm +sidebar_label: Prim's Algorithm +tags: [python, java, c++, javascript, programming, algorithms, prim, graph, minimum-spanning-tree, data structures, tutorial, in-depth] +description: In this tutorial, we will learn about Prim's Algorithm and its implementation in Python, Java, C++, and JavaScript with detailed explanations and examples. + +--- + +# Prim's Algorithm for Minimum Spanning Tree + +## Introduction + +Prim's Algorithm is a greedy algorithm used for finding the Minimum Spanning Tree (MST) of a weighted undirected graph. The MST is a subset of the graph's edges that connects all vertices together without cycles and with the minimum possible total edge weight. + +## Key Concepts + +- **Minimum Spanning Tree (MST)**: A tree that spans all the vertices of the graph with the minimum total edge weight. +- **Greedy Algorithm**: At each step, the algorithm selects the edge with the smallest weight that connects a vertex in the MST to a vertex outside the MST. + +## Steps + +1. Initialize a tree with a single vertex, chosen arbitrarily from the graph. +2. Grow the tree by one edge: select the edge with the smallest weight that connects a vertex in the tree to a vertex outside the tree. +3. Repeat step 2 until all vertices are included in the tree. + +## Pseudocode + +Here’s the pseudocode for Prim's Algorithm: + +```python +function prim(graph, start): + initialize a priority queue (min-heap) and a list for the MST + add start vertex to the MST + for each edge from the start vertex, add edge to the priority queue + + while the priority queue is not empty: + edge = extract-min from the priority queue + if the edge connects a vertex in the MST to a vertex outside the MST: + add edge to the MST + add the new vertex to the MST + for each edge from the new vertex, add edge to the priority queue + + return MST +``` + + + + +```python showLineNubmers +import heapq + +def prim(graph, start): + mst = [] + visited = set([start]) + edges = [(cost, start, to) for to, cost in graph[start].items()] + heapq.heapify(edges) + + while edges: + cost, frm, to = heapq.heappop(edges) + if to not in visited: + visited.add(to) + mst.append((frm, to, cost)) + for to_next, cost in graph[to].items(): + if to_next not in visited: + heapq.heappush(edges, (cost, to, to_next)) + + return mst + +# Example usage +graph = { + 'A': {'B': 1, 'C': 4}, + 'B': {'A': 1, 'C': 3, 'D': 2}, + 'C': {'A': 4, 'B': 3, 'D': 5}, + 'D': {'B': 2, 'C': 5} +} + +mst = prim(graph, 'A') +print(mst) # Output: [('A', 'B', 1), ('B', 'D', 2), ('B', 'C', 3)] + +``` + + + + +```jsx showLineNumbers +import java.util.*; + +public class Prim { + static class Edge { + int to, cost; + Edge(int to, int cost) { + this.to = to; + this.cost = cost; + } + } + + public static List prim(Map> graph, int start) { + List mst = new ArrayList<>(); + Set visited = new HashSet<>(); + PriorityQueue pq = new PriorityQueue<>(Comparator.comparingInt(e -> e.cost)); + + visited.add(start); + pq.addAll(graph.get(start)); + + while (!pq.isEmpty()) { + Edge edge = pq.poll(); + if (!visited.contains(edge.to)) { + visited.add(edge.to); + mst.add(new int[]{start, edge.to, edge.cost}); + for (Edge nextEdge : graph.get(edge.to)) { + if (!visited.contains(nextEdge.to)) { + pq.add(nextEdge); + } + } + } + } + return mst; + } + + public static void main(String[] args) { + Map> graph = new HashMap<>(); + graph.put(0, Arrays.asList(new Edge(1, 1), new Edge(2, 4))); + graph.put(1, Arrays.asList(new Edge(0, 1), new Edge(2, 3), new Edge(3, 2))); + graph.put(2, Arrays.asList(new Edge(0, 4), new Edge(1, 3), new Edge(3, 5))); + graph.put(3, Arrays.asList(new Edge(1, 2), new Edge(2, 5))); + + List mst = prim(graph, 0); + for (int[] edge : mst) { + System.out.println(Arrays.toString(edge)); // Output: [0, 1, 1], [1, 3, 2], [1, 2, 3] + } + } +} + +``` + + + +```cpp showLineNumbers +#include +#include +#include +#include +#include + +using namespace std; + +class Edge { +public: + int to, cost; + Edge(int to, int cost) : to(to), cost(cost) {} +}; + +vector> prim(unordered_map> &graph, int start) { + vector> mst; + unordered_set visited; + auto cmp = [](Edge &a, Edge &b) { return a.cost > b.cost; }; + priority_queue, decltype(cmp)> pq(cmp); + + visited.insert(start); + for (const Edge &edge : graph[start]) { + pq.push(edge); + } + + while (!pq.empty()) { + Edge edge = pq.top(); + pq.pop(); + + if (visited.find(edge.to) == visited.end()) { + visited.insert(edge.to); + mst.push_back({start, edge.to, edge.cost}); + + for (const Edge &nextEdge : graph[edge.to]) { + if (visited.find(nextEdge.to) == visited.end()) { + pq.push(nextEdge); + } + } + } + } + return mst; +} + +int main() { + unordered_map> graph; + graph[0] = {Edge(1, 1), Edge(2, 4)}; + graph[1] = {Edge(0, 1), Edge(2, 3), Edge(3, 2)}; + graph[2] = {Edge(0, 4), Edge(1, 3), Edge(3, 5)}; + graph[3] = {Edge(1, 2), Edge(2, 5)}; + + vector> mst = prim(graph, 0); + for (const vector &edge : mst) { + cout << "[" << edge[0] << ", " << edge[1] << ", " << edge[2] << "]" << endl; // Output: [0, 1, 1], [1, 3, 2], [1, 2, 3] + } +} + +``` + + + +```jsx showLineNumbers +class MinHeap { + constructor() { + this.heap = []; + } + + insert(edge) { + this.heap.push(edge); + this.bubbleUp(); + } + + extractMin() { + if (this.heap.length < 2) return this.heap.pop(); + const min = this.heap[0]; + this.heap[0] = this.heap.pop(); + this.bubbleDown(); + return min; + } + + bubbleUp() { + let index = this.heap.length - 1; + while (index > 0) { + const element = this.heap[index]; + const parentIndex = Math.floor((index - 1) / 2); + const parent = this.heap[parentIndex]; + if (parent.cost <= element.cost) break; + this.heap[index] = parent; + this.heap[parentIndex] = element; + index = parentIndex; + } + } + + bubbleDown() { + let index = 0; + const length = this.heap.length; + const element = this.heap[0]; + while (true) { + const leftChildIndex = 2 * index + 1; + const rightChildIndex = 2 * index + 2; + let leftChild, rightChild; + let swap = null; + + if (leftChildIndex < length) { + leftChild = this.heap[leftChildIndex]; + if (leftChild.cost < element.cost) { + swap = leftChildIndex; + } + } + + if (rightChildIndex < length) { + rightChild = this.heap[rightChildIndex]; + if ((swap === null && rightChild.cost < element.cost) || + (swap !== null && rightChild.cost < leftChild.cost)) { + swap = rightChildIndex; + } + } + + if (swap === null) break; + this.heap[index] = this.heap[swap]; + this.heap[swap] = element; + index = swap; + } + } +} + +function prim(graph, start) { + const mst = []; + const visited = new Set(); + const minHeap = new MinHeap(); + + visited.add(start); + for (const [to, cost] of Object.entries(graph[start])) { + minHeap.insert({ from: start + +, to: to, cost: cost }); + } + + while (minHeap.heap.length > 0) { + const { from, to, cost } = minHeap.extractMin(); + if (!visited.has(to)) { + visited.add(to); + mst.push([from, to, cost]); + for (const [nextTo, nextCost] of Object.entries(graph[to])) { + if (!visited.has(nextTo)) { + minHeap.insert({ from: to, to: nextTo, cost: nextCost }); + } + } + } + } + return mst; +} + +// Example usage +const graph = { + 'A': { 'B': 1, 'C': 4 }, + 'B': { 'A': 1, 'C': 3, 'D': 2 }, + 'C': { 'A': 4, 'B': 3, 'D': 5 }, + 'D': { 'B': 2, 'C': 5 } +}; + +const mst = prim(graph, 'A'); +console.log(mst); // Output: [['A', 'B', 1], ['B', 'D', 2], ['B', 'C', 3]] + +``` + + + +## Example + +Consider a weighted undirected graph with vertices and edges: + +```plaintext +graph = { + 'A': {'B': 1, 'C': 4}, + 'B': {'A': 1, 'C': 3, 'D': 2}, + 'C': {'A': 4, 'B': 3, 'D': 5}, + 'D': {'B': 2, 'C': 5} +} +``` + +1. Start with vertex 'A'. +2. The edge with the smallest weight from 'A' is ('A', 'B', 1), add it to the MST. +3. The next smallest edge is ('B', 'D', 2), add it to the MST. +4. Finally, add edge ('B', 'C', 3) to the MST. + +The MST contains the edges: [('A', 'B', 1), ('B', 'D', 2), ('B', 'C', 3)]. + +## Conclusion + +Prim's Algorithm is an efficient method for finding the Minimum Spanning Tree of a weighted undirected graph. It operates in $O(E log V)$ time complexity using a priority queue, making it suitable for large graphs. Understanding and implementing this algorithm is fundamental for solving various network design problems and optimizing connectivity. diff --git a/docs/Algorithms/searching.md b/docs/Algorithms/searching.md new file mode 100644 index 0000000..f539fd2 --- /dev/null +++ b/docs/Algorithms/searching.md @@ -0,0 +1,233 @@ +--- +id: searching +title: Linear Search and Binary Search Algorithms +sidebar_label: Linear Search and Binary Search +tags: [python, java, c++, javascript, algorithms, search-algorithms, tutorial, in-depth] +description: In this tutorial, we will explore linear search and binary search algorithms and their implementations in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +# Linear Search and Binary Search Algorithms + +In this tutorial, we will delve into two fundamental search algorithms: linear search and binary search. We'll discuss their concepts, implementations, time complexities, and applications in different programming languages including Python, Java, C++, and JavaScript. + +## 1. Linear Search + +Linear search, also known as sequential search, is a simple search algorithm that checks every element in a list or array until the target element is found or the end of the list is reached. It is straightforward but may be inefficient for large datasets. + +![linear search](https://miro.medium.com/v2/resize:fit:1200/1*eTQoIHGdG58sy-iMwcp97w.png) + + + +```python showLineNumbers +def linear_search(arr, target): + for i in range(len(arr)): + if arr[i] == target: + return i + return -1 + +arr = [10, 20, 30, 40, 50] +target = 30 +print(linear_search(arr, target)) # Output: 2 + +``` + + +```jsx showLineNumbers +public class LinearSearch { + + public static int linearSearch(int[] arr, int target) { + for (int i = 0; i < arr.length; i++) { + if (arr[i] == target) { + return i; + } + } + return -1; + } + + public static void main(String[] args) { + int[] arr = {10, 20, 30, 40, 50}; + int target = 30; + System.out.println(linearSearch(arr, target)); // Output: 2 + } +} + +``` + + + +```cpp showLineNumbers +#include +#include + +int linearSearch(const std::vector& arr, int target) { + for (int i = 0; i < arr.size(); i++) { + if (arr[i] == target) { + return i; + } + } + return -1; +} + +int main() { + std::vector arr = {10, 20, 30, 40, 50}; + int target = 30; + std::cout << linearSearch(arr, target) << std::endl; // Output: 2 + return 0; +} + +``` + + +```jsx showLineNumbers +function linearSearch(arr, target) { + for (let i = 0; i < arr.length; i++) { + if (arr[i] === target) { + return i; + } + } + return -1; +} + +let arr = [10, 20, 30, 40, 50]; +let target = 30; +console.log(linearSearch(arr, target)); // Output: 2 + +``` + + + +## 2. Binary Search + +Binary search is a more efficient search algorithm for sorted arrays. It works by repeatedly dividing the search interval in half until the target element is found or the interval is empty. + +![binary search](https://data-flair.training/blogs/wp-content/uploads/sites/2/2023/09/binary-search-in-c-1.webp) + + + +```python showLineNumbers +def binary_search(arr, target): + low = 0 + high = len(arr) - 1 + + while low <= high: + mid = (low + high) // 2 + if arr[mid] == target: + return mid + elif arr[mid] < target: + low = mid + 1 + else: + high = mid - 1 + return -1 + +arr = [10, 20, 30, 40, 50] +target = 30 +print(binary_search(arr, target)) # Output: 2 + +``` + + +```jsx showLineNumbers +public class BinarySearch { + + public static int binarySearch(int[] arr, int target) { + int low = 0; + int high = arr.length - 1; + + while (low <= high) { + int mid = (low + high) / 2; + if (arr[mid] == target) { + return mid; + } else if (arr[mid] < target) { + low = mid + 1; + } else { + high = mid - 1; + } + } + return -1; + } + + public static void main(String[] args) { + int[] arr = {10, 20, 30, 40, 50}; + int target = 30; + System.out.println(binarySearch(arr, target)); // Output: 2 + } +} + +``` + + +```cpp showLineNumbers +#include +#include + +int binarySearch(const std::vector& arr, int target) { + int low = 0; + int high = arr.size() - 1; + + while (low <= high) { + int mid = (low + high) / 2; + if (arr[mid] == target) { + return mid; + } else if (arr[mid] < target) { + low = mid + 1; + } else { + high = mid - 1; + } + } + return -1; +} + +int main() { + std::vector arr = {10, 20, 30, 40, 50}; + int target = 30; + std::cout << binarySearch(arr, target) << std::endl; // Output: 2 + return 0; +} + +``` + + + +```jsx showLineNumbers +function binarySearch(arr, target) { + let low = 0; + let high = arr.length - 1; + + while (low <= high) { + let mid = Math.floor((low + high) / 2); + if (arr[mid] === target) { + return mid; + } else if (arr[mid] < target) { + low = mid + 1; + } else { + high = mid - 1; + } + } + return -1; +} + +let arr = [10, 20, 30, 40, 50]; +let target = 30; +console.log(binarySearch(arr, target)); // Output: 2 + +``` + + + +## Time Complexity Analysis + +- **Linear Search**: + - Best Case: $O(1)$ (when the target is found at the first position) + - Worst Case: $O(n)$ (when the target is not present in the array or at the last position) +- **Binary Search**: + - Best Case: $O(1)$ (when the target is found at the middle position) + - Worst Case: $O(log n)$ (when the target is not present in the array or at the last position) + +## Applications of Linear Search and Binary Search + +- **Linear Search**: Used in scenarios where the data is unsorted or small in size. +- **Binary Search**: Ideal for searching in large sorted datasets, such as searching in databases or sorted arrays. + +## Conclusion + +In this tutorial, we explored linear search and binary search algorithms along with their implementations in Python, Java, C++, and JavaScript. Understanding these fundamental search algorithms is essential for solving various problems efficiently. \ No newline at end of file diff --git a/docs/Algorithms/tarjan.md b/docs/Algorithms/tarjan.md new file mode 100644 index 0000000..984d6e3 --- /dev/null +++ b/docs/Algorithms/tarjan.md @@ -0,0 +1,401 @@ +--- + +id: tarjan +title: Tarjan's Algorithm +sidebar_label: Tarjan's Algorithm +tags: [python, java, c++, javascript, programming, algorithms, tarjan, graph, strongly-connected-components, data structures, tutorial, in-depth] +description: In this tutorial, we will learn about Tarjan's Algorithm and its implementation in Python, Java, C++, and JavaScript with detailed explanations and examples. + +--- + +# Tarjan's Algorithm for Strongly Connected Components + +## Introduction + +Tarjan's Algorithm is a depth-first search (DFS) based algorithm for finding all strongly connected components (SCCs) in a directed graph. A strongly connected component is a maximal subgraph where every pair of vertices is mutually reachable. This algorithm is efficient, operating in O(V + E) time, where V is the number of vertices and E is the number of edges. + +## Key Concepts + +- **DFS Number**: Each node is assigned a unique integer in the order it is first visited. +- **Low Link Value**: The smallest DFS number reachable from the node, including itself and its descendants. +- **Stack**: A stack is used to keep track of the nodes currently being explored. + +## Steps + +1. Perform a Depth-First Search (DFS) traversal of the graph. +2. Assign a DFS number to each node. +3. Calculate the low link value for each node. +4. Identify nodes that form SCCs based on their low link values. +5. Extract SCCs when a node’s low link value is equal to its DFS number. + +## Pseudocode + +Here’s the pseudocode for Tarjan's Algorithm: + +```python +function tarjanSCC(graph): + initialize index to 0 + initialize an empty stack + initialize an empty list for SCCs + for each vertex v in graph: + if v is not visited: + strongConnect(v) + +function strongConnect(v): + set v.index to index + set v.lowlink to index + increment index by 1 + push v onto stack + set v.onStack to true + + for each neighbor w of v: + if w is not visited: + strongConnect(w) + v.lowlink = min(v.lowlink, w.lowlink) + else if w is on stack: + v.lowlink = min(v.lowlink, w.index) + + if v.lowlink is equal to v.index: + start a new SCC + repeat + w = stack.pop() + set w.onStack to false + add w to current SCC + until w is v + add current SCC to list of SCCs +``` + +## Implementation in Various Languages + +### Python + +```python +class TarjanSCC: + def __init__(self, graph): + self.graph = graph + self.index = 0 + self.stack = [] + self.indices = {} + self.lowlinks = {} + self.on_stack = {} + self.sccs = [] + + def run(self): + for node in self.graph: + if node not in self.indices: + self.strong_connect(node) + return self.sccs + + def strong_connect(self, node): + self.indices[node] = self.index + self.lowlinks[node] = self.index + self.index += 1 + self.stack.append(node) + self.on_stack[node] = True + + for neighbor in self.graph[node]: + if neighbor not in self.indices: + self.strong_connect(neighbor) + self.lowlinks[node] = min(self.lowlinks[node], self.lowlinks[neighbor]) + elif self.on_stack[neighbor]: + self.lowlinks[node] = min(self.lowlinks[node], self.indices[neighbor]) + + if self.lowlinks[node] == self.indices[node]: + scc = [] + while True: + w = self.stack.pop() + self.on_stack[w] = False + scc.append(w) + if w == node: + break + self.sccs.append(scc) + +# Example usage +graph = { + 0: [1], + 1: [2], + 2: [0, 3], + 3: [4], + 4: [5, 7], + 5: [6], + 6: [4], + 7: [8], + 8: [9], + 9: [7] +} + +tarjan = TarjanSCC(graph) +sccs = tarjan.run() +print(sccs) # Output: [[0, 2, 1], [3], [4, 6, 5], [7, 9, 8]] +``` + +### Java + +```java +import java.util.*; + +public class TarjanSCC { + private Map> graph; + private int index; + private Stack stack; + private Map indices; + private Map lowlinks; + private Set onStack; + private List> sccs; + + public TarjanSCC(Map> graph) { + this.graph = graph; + this.index = 0; + this.stack = new Stack<>(); + this.indices = new HashMap<>(); + this.lowlinks = new HashMap<>(); + this.onStack = new HashSet<>(); + this.sccs = new ArrayList<>(); + } + + public List> run() { + for (Integer node : graph.keySet()) { + if (!indices.containsKey(node)) { + strongConnect(node); + } + } + return sccs; + } + + private void strongConnect(Integer node) { + indices.put(node, index); + lowlinks.put(node, index); + index++; + stack.push(node); + onStack.add(node); + + for (Integer neighbor : graph.get(node)) { + if (!indices.containsKey(neighbor)) { + strongConnect(neighbor); + lowlinks.put(node, Math.min(lowlinks.get(node), lowlinks.get(neighbor))); + } else if (onStack.contains(neighbor)) { + lowlinks.put(node, Math.min(lowlinks.get(node), indices.get(neighbor))); + } + } + + if (lowlinks.get(node).equals(indices.get(node))) { + List scc = new ArrayList<>(); + Integer w; + do { + w = stack.pop(); + onStack.remove(w); + scc.add(w); + } while (!w.equals(node)); + sccs.add(scc); + } + } + + public static void main(String[] args) { + Map> graph = new HashMap<>(); + graph.put(0, Arrays.asList(1)); + graph.put(1, Arrays.asList(2)); + graph.put(2, Arrays.asList(0, 3)); + graph.put(3, Arrays.asList(4)); + graph.put(4, Arrays.asList(5, 7)); + graph.put(5, Arrays.asList(6)); + graph.put(6, Arrays.asList(4)); + graph.put(7, Arrays.asList(8)); + graph.put(8, Arrays.asList(9)); + graph.put(9, Arrays.asList(7)); + + TarjanSCC tarjan = new TarjanSCC(graph); + List> sccs = tarjan.run(); + System.out.println(sccs); // Output: [[0, 2, 1], [3], [4, 6, 5], [7, 9, 8]] + } +} +``` + +### C++ + +```cpp +#include +#include +#include +#include +#include + +class TarjanSCC { +private: + std::unordered_map> graph; + int index; + std::stack stack; + std::unordered_map indices; + std::unordered_map lowlinks; + std::unordered_map onStack; + std::vector> sccs; + + void strongConnect(int node) { + indices[node] = index; + lowlinks[node] = index; + index++; + stack.push(node); + onStack[node] = true; + + for (int neighbor : graph[node]) { + if (indices.find(neighbor) == indices.end()) { + strongConnect(neighbor); + lowlinks[node] = std::min(lowlinks[node], lowlinks[neighbor]); + } else if (onStack[neighbor]) { + lowlinks[node] = std::min(lowlinks[node], indices[neighbor]); + } + } + + if (lowlinks[node] == indices[node]) { + std::vector scc; + int w; + do { + w = stack.top(); + stack.pop(); + onStack[w] = false; + scc.push_back(w); + } while (w != node); + sccs.push_back(scc); + } + } + +public: + TarjanSCC(const std::unordered_map>& graph) : graph(graph), index(0) {} + + std::vector> run() { + for (const auto& [node, _] : graph) { + if (indices.find(node) == indices.end()) { + strongConnect(node); + } + } + return sccs; + } +}; + +int main() { + std::unordered_map> graph = { + {0, {1}}, + {1, {2}}, + {2, {0, 3}}, + {3, {4}}, + {4, {5, 7}}, + {5, { + +6}}, + {6, {4}}, + {7, {8}}, + {8, {9}}, + {9, {7}} + }; + + TarjanSCC tarjan(graph); + std::vector> sccs = tarjan.run(); + for (const auto& scc : sccs) { + for (int node : scc) { + std::cout << node << " "; + } + std::cout << std::endl; + } + // Output: [[0, 2, 1], [3], [4, 6, 5], [7, 9, 8]] +} +``` + +### JavaScript + +```javascript +class TarjanSCC { + constructor(graph) { + this.graph = graph; + this.index = 0; + this.stack = []; + this.indices = {}; + this.lowlinks = {}; + this.onStack = {}; + this.sccs = []; + } + + run() { + for (const node in this.graph) { + if (!(node in this.indices)) { + this.strongConnect(node); + } + } + return this.sccs; + } + + strongConnect(node) { + this.indices[node] = this.index; + this.lowlinks[node] = this.index; + this.index++; + this.stack.push(node); + this.onStack[node] = true; + + for (const neighbor of this.graph[node]) { + if (!(neighbor in this.indices)) { + this.strongConnect(neighbor); + this.lowlinks[node] = Math.min(this.lowlinks[node], this.lowlinks[neighbor]); + } else if (this.onStack[neighbor]) { + this.lowlinks[node] = Math.min(this.lowlinks[node], this.indices[neighbor]); + } + } + + if (this.lowlinks[node] === this.indices[node]) { + const scc = []; + let w; + do { + w = this.stack.pop(); + this.onStack[w] = false; + scc.push(w); + } while (w !== node); + this.sccs.push(scc); + } + } +} + +// Example usage +const graph = { + 0: [1], + 1: [2], + 2: [0, 3], + 3: [4], + 4: [5, 7], + 5: [6], + 6: [4], + 7: [8], + 8: [9], + 9: [7] +}; + +const tarjan = new TarjanSCC(graph); +const sccs = tarjan.run(); +console.log(sccs); // Output: [[0, 2, 1], [3], [4, 6, 5], [7, 9, 8]] +``` + +## Example + +Consider a directed graph with vertices and edges: + +```plaintext +graph = { + 0: [1], + 1: [2], + 2: [0, 3], + 3: [4], + 4: [5, 7], + 5: [6], + 6: [4], + 7: [8], + 8: [9], + 9: [7] +} +``` + +1. The algorithm starts at vertex 0, and the DFS traverses the graph assigning DFS numbers and calculating low link values. +2. The nodes 0, 1, and 2 form one SCC as they can all reach each other. +3. Node 3 is an SCC by itself as it doesn't have any back edges to earlier nodes. +4. Nodes 4, 5, and 6 form another SCC. +5. Finally, nodes 7, 8, and 9 form the last SCC. + +## Conclusion + +Tarjan's Algorithm is a powerful method for finding strongly connected components in a directed graph. It efficiently handles the problem in linear time relative to the number of vertices and edges, making it suitable for large graphs. By understanding and implementing this algorithm, you can solve various problems related to graph connectivity and component analysis. + diff --git a/docs/arrays/01-Easy-Problems.md b/docs/arrays/01-Easy-Problems.md new file mode 100644 index 0000000..2ab90f1 --- /dev/null +++ b/docs/arrays/01-Easy-Problems.md @@ -0,0 +1,19 @@ +| Problem | Difficulty | Solution Link | +|-----------------------------------------------------------------------------------------------------------------|------------|-----------------------------------------------------------------------------------------------------------------------------| +| [Largest Element in an Array](https://www.geeksforgeeks.org/c-program-find-largest-element-array/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/largest-element-in-array4009/1) | +| [Second Largest Element in an Array without sorting](https://www.geeksforgeeks.org/find-second-largest-element-array/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/second-largest3735/1) | +| [Check if the array is sorted](https://www.geeksforgeeks.org/array-sorted-not-iterative-recursive/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/check-if-an-array-is-sorted0701/1) | +| [Remove duplicates from Sorted array](https://www.geeksforgeeks.org/remove-duplicates-sorted-array/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/remove-duplicate-elements-from-sorted-array/1) | +| [Left Rotate an array by one place](https://www.geeksforgeeks.org/array-rotation/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/reversal-algorithm5340/1) | +| [Left rotate an array by D places](https://www.geeksforgeeks.org/array-rotation/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/rotate-array-by-n-elements/0) | +| [Move Zeros to end](https://www.geeksforgeeks.org/move-zeroes-end-array/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/move-all-zeroes-to-end-of-array0751/1) | +| [Linear Search](https://www.geeksforgeeks.org/linear-search/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/searching-a-number0324/1) | +| [Find missing number in an array](https://www.geeksforgeeks.org/find-the-missing-number/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/missing-number-in-array1416/1) | +| [Maximum Consecutive Ones](https://www.geeksforgeeks.org/maximum-consecutive-ones-or-zeros-in-a-binary-array/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/max-consecutive-ones/1) | +| [Majority Element (>n/2 times)](https://www.geeksforgeeks.org/majority-element/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/majority-element-1587115620/1) | +| [Kadane's Algorithm, maximum subarray sum](https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1) | +| [Stock Buy and Sell](https://www.geeksforgeeks.org/stock-buy-sell/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/stock-buy-and-sell-1587115621/1) | +| [Leaders in an Array problem](https://www.geeksforgeeks.org/leaders-in-an-array/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/leaders-in-an-array-1587115620/1) | +| [Count subarrays with given sum](https://www.geeksforgeeks.org/number-subarrays-sum-exactly-equal-k/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/number-of-subarrays-with-given-sum/1) | +| [Maximum Product Subarray](https://www.geeksforgeeks.org/maximum-product-subarray/) | Easy | [Solution](https://practice.geeksforgeeks.org/problems/maximum-product-subarray3604/1) | + diff --git a/docs/arrays/02-Medium-Problems.md b/docs/arrays/02-Medium-Problems.md new file mode 100644 index 0000000..ccd1e41 --- /dev/null +++ b/docs/arrays/02-Medium-Problems.md @@ -0,0 +1,23 @@ +| Problem | Difficulty | Solution Link | +|---------------------------------------------------------------------------------------------------------------------------------|------------|-----------------------------------------------------------------------------------------------------------------------------| +| [2Sum Problem](https://www.geeksforgeeks.org/two-sum-problem/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/two-sum-problem/0) | +| [Sort an array of 0's 1's and 2's](https://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s-1587115621/1) | +| [Find the Union](https://www.geeksforgeeks.org/find-union-and-intersection-of-two-unsorted-arrays/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/union-of-two-arrays3538/1) | +| [Print subarray with maximum subarray sum (extended version of above problem)](https://www.geeksforgeeks.org/print-subarray-with-maximum-subarray-sum/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/maximum-sum-subarray2630/1) | +| [Find the number that appears once, and other numbers twice](https://www.geeksforgeeks.org/find-the-element-that-appears-once-in-a-sorted-array/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/element-appears-once/0) | +| [Rearrange the array in alternating positive and negative items](https://www.geeksforgeeks.org/rearrange-array-alternating-positive-negative-items-o1-extra-space/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/array-of-alternate-ve-and-ve-nos/0) | +| [Next Permutation](https://www.geeksforgeeks.org/find-the-next-lexicographically-greater-word-than-a-given-word/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/next-permutation5226/1) | +| [Longest subarray with given sum K(positives)](https://www.geeksforgeeks.org/longest-subarray-with-sum-k/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/longest-sub-array-with-sum-k0809/1) | +| [Longest subarray with sum K (Positives + Negatives)](https://www.geeksforgeeks.org/find-the-largest-subarray-with-0-sum/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/largest-subarray-with-0-sum/1) | +| [Longest Consecutive Sequence in an Array](https://www.geeksforgeeks.org/longest-consecutive-subsequence/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/longest-consecutive-subsequence2449/1) | +| [Set Matrix Zeros](https://www.geeksforgeeks.org/a-boolean-matrix-question/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/set-matrix-zeroes-1587115621/1) | +| [Rotate Matrix by 90 degrees](https://www.geeksforgeeks.org/inplace-rotate-square-matrix-by-90-degrees/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/rotate-by-90-degree0356/1) | +| [Print the matrix in spiral manner](https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/spirally-traversing-a-matrix-1587115621/1) | +| [Pascal's Triangle](https://www.geeksforgeeks.org/pascal-triangle/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/pascals-triangle/1) | +| [Majority Element (n/3 times)](https://www.geeksforgeeks.org/n3-repeated-number-array-o1-space/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/majority-element-1587115620/1) | +| [3-Sum Problem](https://www.geeksforgeeks.org/find-a-triplet-that-sum-to-a-given-value/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/triplet-sum-in-array-1587115621/1) | +| [Largest Subarray with 0 Sum](https://www.geeksforgeeks.org/find-the-largest-subarray-with-0-sum/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/largest-subarray-with-0-sum/1) | +| [Merge Overlapping Subintervals](https://www.geeksforgeeks.org/merging-intervals/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/merge-intervals/1) | +| [Merge two sorted arrays without extra space](https://www.geeksforgeeks.org/merge-two-sorted-arrays-o1-extra-space/) | Medium | [Solution](https://practice.geeksforgeeks.org/problems/merge-two-sorted-arrays-1587115620/1) | + + diff --git a/docs/arrays/03-Hard-Problems.md b/docs/arrays/03-Hard-Problems.md new file mode 100644 index 0000000..24ddf31 --- /dev/null +++ b/docs/arrays/03-Hard-Problems.md @@ -0,0 +1,8 @@ +| Problem | Difficulty | Solution Link | +|---------------------------------------------------------------------------------------------------------------------------------|------------|-----------------------------------------------------------------------------------------------------------------------------| +| [4-Sum Problem](https://www.geeksforgeeks.org/4-sum-problem/) | Hard | [Solution](https://practice.geeksforgeeks.org/problems/4-sum-problem/1) | +| [Count number of subarrays with given xor K](https://www.geeksforgeeks.org/count-number-of-subarrays-with-given-xor/) | Hard | [Solution](https://practice.geeksforgeeks.org/problems/count-number-of-subarrays-with-given-xor/1) | +| [Find the repeating and missing number](https://www.geeksforgeeks.org/find-a-repeating-and-a-missing-number/) | Hard | [Solution](https://practice.geeksforgeeks.org/problems/find-missing-and-repeating2512/1) | +| [Count Inversions](https://www.geeksforgeeks.org/counting-inversions/) | Hard | [Solution](https://practice.geeksforgeeks.org/problems/inversion-of-array-1587115620/1) | +| [Reverse Pairs](https://www.geeksforgeeks.org/count-reverse-pairs-in-an-array/) | Hard | [Solution](https://practice.geeksforgeeks.org/problems/reverse-pairs/1) | + diff --git a/docs/arrays/Boyer-Moore Majority Voting Algorithm.md b/docs/arrays/Boyer-Moore Majority Voting Algorithm.md new file mode 100644 index 0000000..fdd3348 --- /dev/null +++ b/docs/arrays/Boyer-Moore Majority Voting Algorithm.md @@ -0,0 +1,399 @@ +--- +id: boyer-moore-majority-voting-algorithm +title: Boyer Moore Majority voting algorithm +sidebar_label: Boyer Majority voting algorithm +tags: [python, java, c++, algorithms, array, counting] +description: In this tutorial, we will learn about Moore's Voting Algorithm and its implementation in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +# Moore's Voting Algorithm +The Boyer-Moore Majority Voting Algorithm is a well-known and efficient algorithm used to find the majority element in an array, i.e., an element that appears more than `n/2` times. This algorithm, initially designed by Robert S. Boyer and J Strother Moore in `1981`, is widely used in various applications, including data analysis and stream processing. However, in some scenarios, we may need to find elements that occur more than `n/k` times, where k is a positive integer. In this article, we explore the generalization of the Boyer-Moore Majority Voting Algorithm to solve this problem efficiently + +## Problem Statement +Given an array of `N` integers. Find the elements that appear more than `N/3` times in the array. If no such element exists, return an empty vector. + +### Examples + +**Example 1:** + +``` +Input: N = 5, array[] = {1,2,2,3,2} +Output: 2 +Explanation: Here we can see that the Count(1) = 1, Count(2) = 3 and Count(3) = 1.Therefore, the count of 2 is greater than N/3 times. Hence, 2 is the answer. + +``` + +**Example 2:** + +``` +Input: N = 6, array[] = {11,33,33,11,33,11} +Output: 11 33 +Explanation: Here we can see that the Count(11) = 3 and Count(33) = 3. Therefore, the count of both 11 and 33 is greater than N/3 times. Hence, 11 and 33 is the answer. + +``` +## Brute Force Approach + +#### Intuition + +If we closely observe, in the given array, there can be a maximum of two integers that can occur more than `floor(N/3)` times. Let’s understand it using the following scenario: +Assume there are `8` elements in the given array. Now, if there is any majority element, it should occur more than `floor(8/3) = 2` times. So, the majority of elements should occur at least 3 times. Now, if we imagine there are 3 majority elements, then the total occurrence of them will be `3X3 = 9` i.e. greater than the size of the array. But this should not happen. That is why there can be a maximum of 2 majority elements. + +#### Approach +- We will run a loop that will select the elements of the array one by one. +- Now, for each unique element, we will run another loop and count its occurrence in the given array. +- If any element occurs more than the floor of (N/3), we will include it in our answer. +- While traversing if we find any element that is already included in our answer, we will just skip it. + +```c++ +vector majorityElement(vector v) { + int n = v.size(); //size of the array + vector ls; // list of answers + + for (int i = 0; i < n; i++) { + //selected element is v[i]: + // Checking if v[i] is not already + // a part of the answer: + if (ls.size() == 0 || ls[0] != v[i]) { + int cnt = 0; + for (int j = 0; j < n; j++) { + // counting the frequency of v[i] + if (v[j] == v[i]) { + cnt++; + } + } + + // check if frquency is greater than n/3: + if (cnt > (n / 3)) + ls.push_back(v[i]); + } + + if (ls.size() == 2) break; + } + + return ls; +} + +``` +```java +public static List majorityElement(int []v) { + int n = v.length; //size of the array + List ls = new ArrayList<>(); // list of answers + + for (int i = 0; i < n; i++) { + //selected element is v[i]: + // Checking if v[i] is not already + // a part of the answer: + if (ls.size() == 0 || ls.get(0) != v[i]) { + int cnt = 0; + for (int j = 0; j < n; j++) { + // counting the frequency of v[i] + if (v[j] == v[i]) { + cnt++; + } + } + + // check if frquency is greater than n/3: + if (cnt > (n / 3)) + ls.add(v[i]); + } + + if (ls.size() == 2) break; + } + + return ls; + } + +``` +```python +from typing import List + +def majorityElement(v: List[int]) -> List[int]: + n = len(v) # size of the list + ls = [] # list of answers + + for i in range(n): + # selected element is v[i]: + # Checking if v[i] is not already + # a part of the answer: + if len(ls) == 0 or ls[0] != v[i]: + cnt = 0 + for j in range(n): + # counting the frequency of v[i] + if v[j] == v[i]: + cnt += 1 + + # check if frquency is greater than n/3: + if cnt > (n // 3): + ls.append(v[i]) + + if len(ls) == 2: + break + + return ls +``` +#### Time Complexity : $O(n^2)$ +#### Spcae Complexity : $O(1)$ + +## Better Approach - Hashmap +#### Intuition +Use a better data structure to reduce the number of look-up operations and hence the time complexity. Moreover, we have been calculating the count of the same element again and again – so we have to reduce that also. + +#### Approach + - Use a hashmap and store the elements as ` ` + pairs. (Can also use frequency array based on the size of nums). +- Here the key will be the element of the array and the + value will be the number of times it occurs. +- Traverse the whole array and update the occurrence of + each element. +- After that, check the map if the value for any element + is greater than the floor of N/3. + - If yes, include it in the list. + - Else iterate forward. +- Finally, return the list. + +```c++ +vector majorityElement(vector v) { + int n = v.size(); //size of the array + vector ls; // list of answers + + //declaring a map: + map mpp; + + // least occurrence of the majority element: + int mini = int(n / 3) + 1; + + //storing the elements with its occurnce: + for (int i = 0; i < n; i++) { + mpp[v[i]]++; + + //checking if v[i] is + // the majority element: + if (mpp[v[i]] == mini) { + ls.push_back(v[i]); + } + if (ls.size() == 2) break; + } + + return ls; +} + +``` +```java +public static List majorityElement(int []v) { + int n = v.length; //size of the array + List ls = new ArrayList<>(); // list of answers + + //declaring a map: + HashMap mpp = new HashMap<>(); + + // least occurrence of the majority element: + int mini = (int)(n / 3) + 1; + + //storing the elements with its occurnce: + for (int i = 0; i < n; i++) { + int value = mpp.getOrDefault(v[i], 0); + mpp.put(v[i], value + 1); + + //checking if v[i] is + // the majority element: + if (mpp.get(v[i]) == mini) { + ls.add(v[i]); + } + if (ls.size() == 2) break; + } + + return ls; + } +``` +```python +def majorityElement(arr): + # Size of the given array + n = len(arr) + + # Count the occurrences of each element using Counter + counter = Counter(arr) + + # Searching for the majority element + for num, count in counter.items(): + if count > (n // 2): + return num + + return -1 +``` +#### Time Complexity : $O(nlogn)$ +#### Spcae Complexity : $O(n)$ + +## Optimal Approach (Extended Boyer Moore’s Voting Algorithm): +#### Intuition +If the array contains the majority of elements, their occurrence must be greater than the `floor(N/3)`. Now, we can say that the count of minority elements and majority elements is equal up to a certain point in the array. So when we traverse through the array we try to keep track of the counts of elements and the elements themselves for which we are tracking the counts. + +After traversing the whole array, we will check the elements stored in the variables. Then we need to check if the stored elements are the majority elements or not by manually checking their counts. + +#### Steps +- Initialize 4 variables: + cnt1 & cnt2 – for tracking the counts of elements + el1 & el2 – for storing the majority of elements. +- Traverse through the given array. + - If cnt1 is 0 and the current element is not el2 then store the current element of the array as el1 along with increasing the cnt1 value by 1. + - If cnt2 is 0 and the current element is not el1 then store the current element of the array as el2 along with increasing the cnt2 value by 1. + - If the current element and el1 are the same increase the cnt1 by 1. + - If the current element and el2 are the same increase the cnt2 by 1. +- Other than all the above cases: decrease cnt1 and cnt2 by 1. +- The integers present in el1 & el2 should be the result we are expecting. So, using another loop, we will manually check their counts if they are greater than the floor(N/3). + +## Implementing Extended Boyer Moore’s Voting Algorithm + +### Python Implementation + +```python +def majorityElement(v: List[int]) -> List[int]: + n = len(v) # size of the array + + cnt1, cnt2 = 0, 0 # counts + el1, el2 = float('-inf'), float('-inf') # element 1 and element 2 + + # applying the Extended Boyer Moore’s Voting Algorithm: + for i in range(n): + if cnt1 == 0 and el2 != v[i]: + cnt1 = 1 + el1 = v[i] + elif cnt2 == 0 and el1 != v[i]: + cnt2 = 1 + el2 = v[i] + elif v[i] == el1: + cnt1 += 1 + elif v[i] == el2: + cnt2 += 1 + else: + cnt1 -= 1 + cnt2 -= 1 + + ls = [] # list of answers + + # Manually check if the stored elements in + # el1 and el2 are the majority elements: + cnt1, cnt2 = 0, 0 + for i in range(n): + if v[i] == el1: + cnt1 += 1 + if v[i] == el2: + cnt2 += 1 + + mini = int(n / 3) + 1 + if cnt1 >= mini: + ls.append(el1) + if cnt2 >= mini: + ls.append(el2) + + # Uncomment the following line + # if it is told to sort the answer array: + #ls.sort() #TC --> O(2*log2) ~ O(1); + + return ls +``` + +### Java Implementation + +```java +public static List majorityElement(int []v) { + int n = v.length; //size of the array + + int cnt1 = 0, cnt2 = 0; // counts + int el1 = Integer.MIN_VALUE; // element 1 + int el2 = Integer.MIN_VALUE; // element 2 + + // applying the Extended Boyer Moore's Voting Algorithm: + for (int i = 0; i < n; i++) { + if (cnt1 == 0 && el2 != v[i]) { + cnt1 = 1; + el1 = v[i]; + } else if (cnt2 == 0 && el1 != v[i]) { + cnt2 = 1; + el2 = v[i]; + } else if (v[i] == el1) cnt1++; + else if (v[i] == el2) cnt2++; + else { + cnt1--; cnt2--; + } + } + + List ls = new ArrayList<>(); // list of answers + + // Manually check if the stored elements in + // el1 and el2 are the majority elements: + cnt1 = 0; cnt2 = 0; + for (int i = 0; i < n; i++) { + if (v[i] == el1) cnt1++; + if (v[i] == el2) cnt2++; + } + + int mini = (int)(n / 3) + 1; + if (cnt1 >= mini) ls.add(el1); + if (cnt2 >= mini) ls.add(el2); + + // Uncomment the following line + // if it is told to sort the answer array: + //Collections.sort(ls); //TC --> O(2*log2) ~ O(1); + + return ls; + } +``` + +### C++ Implementation + +```cpp +vector majorityElement(vector v) { + int n = v.size(); //size of the array + + int cnt1 = 0, cnt2 = 0; // counts + int el1 = INT_MIN; // element 1 + int el2 = INT_MIN; // element 2 + + // applying the Extended Boyer Moore's Voting Algorithm: + for (int i = 0; i < n; i++) { + if (cnt1 == 0 && el2 != v[i]) { + cnt1 = 1; + el1 = v[i]; + } + else if (cnt2 == 0 && el1 != v[i]) { + cnt2 = 1; + el2 = v[i]; + } + else if (v[i] == el1) cnt1++; + else if (v[i] == el2) cnt2++; + else { + cnt1--, cnt2--; + } + } + + vector ls; // list of answers + + // Manually check if the stored elements in + // el1 and el2 are the majority elements: + cnt1 = 0, cnt2 = 0; + for (int i = 0; i < n; i++) { + if (v[i] == el1) cnt1++; + if (v[i] == el2) cnt2++; + } + + int mini = int(n / 3) + 1; + if (cnt1 >= mini) ls.push_back(el1); + if (cnt2 >= mini) ls.push_back(el2); + + // Uncomment the following line + // if it is told to sort the answer array: + // sort(ls.begin(), ls.end()); //TC --> O(2*log2) ~ O(1); + + return ls; +} +``` + +## Complexity Analysis + #### Time Complexity : $O(n)$ + #### Space Complexity : $O(1)$ + +## Conclusion +- Extended Boyer Moore's Voting Algorithm concludes by returning the array of element which have occurance more than $(n/3)$, if it exists, otherwise, -1. + + + diff --git a/docs/arrays/Dutch-National-Flag-Algorithm.md b/docs/arrays/Dutch-National-Flag-Algorithm.md new file mode 100644 index 0000000..4c64194 --- /dev/null +++ b/docs/arrays/Dutch-National-Flag-Algorithm.md @@ -0,0 +1,322 @@ +--- +id: dutch-national-flag-algorithm +title: Dutch National Flag Algorithm +sidebar_label: Dutch National Flag Algorithm +tags: [python, java, c++, algorithms, array] +description: In this tutorial, we will learn about the Dutch National Flag Algorithm and its implementation in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +## Problem Statement +Given an array `A[]` consisting of only 0s, 1s, and 2s. The task is to sort the array, i.e., put all 0s first, then all 1s, and all 2s last. + +This problem is the same as the famous β€œDutch National Flag problem” proposed by Edsger Dijkstra. The problem is as follows: + +Given `N` balls of color red, white, or blue arranged in a line in random order, you have to arrange all the balls such that the balls with the same colors are adjacent with the order of the balls being red, white, and blue (i.e., all red colored balls come first, then the white colored balls, and then the blue colored balls). + +### Examples + +**Example 1:** + +``` +Input: {0, 1, 2, 0, 1, 2} +Output: {0, 0, 1, 1, 2, 2} +Explanation: {0, 0, 1, 1, 2, 2} has all 0s first, then all 1s, and all 2s last. +``` + +**Example 2:** + +``` +Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1} +Output: {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2} +Explanation: {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2} has all 0s first, then all 1s, and all 2s last. +``` + +## Brute Force Approach + +### Intuition +The naive solution is to simply sort the array using a standard sorting algorithm or sort library function. This will simply place all the 0s first, then all 1s, and 2s at last. This approach requires `O(N * log(N))` time and `O(1)` space. + + + + +```python +# Brute Force Approach in Python +def sort012(arr): + arr.sort() + +# Sample Input +arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1] +sort012(arr) +print(arr) +``` + + + + +```java +import java.util.Arrays; + +// Brute Force Approach in Java +public class Main { + public static void sort012(int[] arr) { + Arrays.sort(arr); + } + + public static void main(String[] args) { + int[] arr = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; + sort012(arr); + System.out.println(Arrays.toString(arr)); + } +} +``` + + + + +```cpp +#include +#include +using namespace std; + +// Brute Force Approach in C++ +void sort012(int arr[], int n) { + sort(arr, arr + n); +} + +int main() { + int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; + int n = sizeof(arr) / sizeof(arr[0]); + sort012(arr, n); + for (int i = 0; i < n; i++) { + cout << arr[i] << " "; + } + return 0; +} +``` + + + + +### Time Complexity: $O(n \cdot \log(n))$ +### Space Complexity: $O(1)$ + +## Better Approach + +### Intuition +A better solution is to traverse the array once and count the number of 0s, 1s, and 2s. Let these counts be `c0`, `c1`, and `c2`. Now traverse the array again, put `c0` (count of 0s) 0s first, then `c1` 1s, and finally `c2` 2s. This solution works in `O(n)` time but is not stable and requires two traversals of the array. This approach requires `O(N)` time and `O(1)` space. + + + + +```python +# Better Approach in Python +def sort012(arr): + c0 = c1 = c2 = 0 + for num in arr: + if num == 0: + c0 += 1 + elif num == 1: + c1 += 1 + else: + c2 += 1 + + idx = 0 + for _ in range(c0): + arr[idx] = 0 + idx += 1 + for _ in range(c1): + arr[idx] = 1 + idx += 1 + for _ in range(c2): + arr[idx] = 2 + idx += 1 + +# Sample Input +arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1] +sort012(arr) +print(arr) +``` + + + + +```java +// Better Approach in Java +public class Main { + public static void sort012(int[] arr) { + int c0 = 0, c1 = 0, c2 = 0; + for (int num : arr) { + if (num == 0) c0++; + else if (num == 1) c1++; + else c2++; + } + + int idx = 0; + for (int i = 0; i < c0; i++) arr[idx++] = 0; + for (int i = 0; i < c1; i++) arr[idx++] = 1; + for (int i = 0; i < c2; i++) arr[idx++] = 2; + } + + public static void main(String[] args) { + int[] arr = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; + sort012(arr); + System.out.println(Arrays.toString(arr)); + } +} +``` + + + + +```cpp +#include +using namespace std; + +// Better Approach in C++ +void sort012(int arr[], int n) { + int c0 = 0, c1 = 0, c2 = 0; + for (int i = 0; i < n; i++) { + if (arr[i] == 0) c0++; + else if (arr[i] == 1) c1++; + else c2++; + } + + int idx = 0; + for (int i = 0; i < c0; i++) arr[idx++] = 0; + for (int i = 0; i < c1; i++) arr[idx++] = 1; + for (int i = 0; i < c2; i++) arr[idx++] = 2; +} + +int main() { + int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; + int n = sizeof(arr) / sizeof(arr[0]); + sort012(arr, n); + for (int i = 0; i < n; i++) { + cout << arr[i] << " "; + } + return 0; +} +``` + + + + +### Time Complexity: $O(2n)$ +### Space Complexity: $O(1)$ + +## Optimal Approach (Dutch National Flag Algorithm) + +### Intuition +The idea is to sort the array of size `N` using three pointers: `lo = 0`, `mid = 0`, and `hi = N – 1` such that the array is divided into three parts: + +- `arr[0]` to `arr[lo – 1]`: This part will have all the zeros. +- `arr[lo]` to `arr[mid – 1]`: This part will have all the ones. +- `arr[hi + 1]` to `arr[N – 1]`: This part will have all the twos. + +### Steps +Traverse over the array till `mid <= hi`. According to the value of `arr[mid]`, we can have three cases: + +- If `arr[mid]` is 0, swap `arr[lo]` and `arr[mid]` and increment both `lo` and `mid`. +- If `arr[mid]` is 1, increment `mid`. +- If `arr[mid]` is 2, swap `arr[mid]` and `arr[hi]` and decrement `hi`. + + + + +```python +# Optimal Approach in Python +def sort012(arr): + lo = mid = 0 + hi = len(arr) - 1 + while mid <= hi: + if arr[mid] == 0: + arr[lo], arr[mid] = arr[mid], arr[lo] + lo += 1 + mid += 1 + elif arr[mid] == 1: + mid += 1 + else: + arr[mid], arr[hi] = arr[hi], arr[mid] + hi -= 1 + +# Sample Input +arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1] +sort012(arr) +print(arr) +``` + + + + +```java +// Optimal Approach in Java +public class Main { + public static void sort012(int[] arr) { + int lo = 0, mid = 0, hi = arr.length - 1; + while (mid <= hi) { + if (arr[mid] == 0) { + int temp = arr[lo]; + arr[lo] = arr[mid]; + arr[mid] = temp; + lo++; + mid++; + } else if (arr[mid] == 1) { + mid++; + } else { + int temp = arr[mid]; + arr[mid] = arr[hi]; + arr[hi] = temp; + hi--; + } + } + } + + public static void main(String[] args) { + int[] arr = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; + sort012(arr); + System.out.println(Arrays.toString(arr)); + } +} +``` + + + + +```cpp +#include +using namespace std; + +// Optimal Approach in C++ +void sort012(int arr[], int n) { + int lo = 0, mid = 0, hi = n - 1; + while (mid <= hi) { + switch (arr[mid]) { + case 0: + swap(arr[lo++], arr[mid++]); + break; + case 1: + mid++; + break; + case 2: + swap(arr[mid], arr[hi--]); + break; + } + } +} + +int main() { + int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; + int n = sizeof(arr) / sizeof(arr[0]); + sort012(arr, n); + for (int i = 0; i < n; i++) { + cout << arr[i] << " "; + } + return 0; +} +``` + + + + +### Time Complexity: $O(n)$ +### Space Complexity: $O(1)$ diff --git a/docs/arrays/Kadane's-Algorithm.md b/docs/arrays/Kadane's-Algorithm.md new file mode 100644 index 0000000..0a0c657 --- /dev/null +++ b/docs/arrays/Kadane's-Algorithm.md @@ -0,0 +1,402 @@ +--- +id: kadaney's-algorithm +title: Kadaney's Algorithm +sidebar_label: Kadane's-Algorithm +tags: [python, java, c++, algorithms, array] +description: In this tutorial, we will learn about Kadane's Algorithm and its implementation in Python, Java, C++, and JavaScript with detailed explanations and examples. +--- + +### Kadane's Algorithm +The idea of Kadane’s algorithm is to maintain a variable max_ending_here that stores the maximum sum contiguous subarray ending at current index and a variable max_so_far stores the maximum sum of contiguous subarray found so far, Everytime there is a positive-sum value in max_ending_here compare it with max_so_far and update max_so_far if it is greater than max_so_far. + +So the main Intuition behind Kadane’s Algorithm is, + +The subarray with negative sum is discarded (by assigning max_ending_here = 0 in code). +We carry subarray till it gives positive sum. + +## Problem Statement +Given an array `arr[]` of size `N`. The task is to find the sum of the contiguous subarray within a `arr[]` with the largest sum. + +### Examples + +**Example 1:** + +``` +Input: arr = {-2,-3,4,-1,-2,1,5,-3} +Output: 7 +Explanation: The subarray {4,-1, -2, 1, 5} has the largest sum 7. + +``` + +**Example 2:** + +``` +Input: arr = {2} +Output: 2 +Explanation: The subarray {2} has the largest sum 2. + +``` +## Brute Force Approach + +#### Intuition + +To print the subarray with the maximum sum the idea is to maintain start index of maximum_sum_ending_here at current index so that whenever maximum_sum_so_far is updated with maximum_sum_ending_here then start index and end index of subarray can be updated with start and current index. + +#### Approach +- Initialize the variables s, start, and end with 0 and max_so_far = INT_MIN and max_ending_here = 0 +- Run a for loop from 0 to N-1 and for each index i: +- Add the arr[i] to max_ending_here. +- If max_so_far is less than max_ending_here then update max_so_far to max_ending_here and update start to s and end to i . +- If max_ending_here < 0 then update max_ending_here = 0 and s with i+1. +Print values from index start to end. + +```c++ +// C++ program to print largest contiguous array sum + +#include +#include +using namespace std; + +void maxSubArraySum(int a[], int size) +{ + int max_so_far = INT_MIN, max_ending_here = 0, + start = 0, end = 0, s = 0; + + for (int i = 0; i < size; i++) { + max_ending_here += a[i]; + + if (max_so_far < max_ending_here) { + max_so_far = max_ending_here; + start = s; + end = i; + } + + if (max_ending_here < 0) { + max_ending_here = 0; + s = i + 1; + } + } + cout << "Maximum contiguous sum is " << max_so_far + << endl; + cout << "Starting index " << start << endl + << "Ending index " << end << endl; +} + +/*Driver program to test maxSubArraySum*/ +int main() +{ + int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; + int n = sizeof(a) / sizeof(a[0]); + maxSubArraySum(a, n); + return 0; +} + + +``` +```java +// Java program to print largest +// contiguous array sum +import java.io.*; +import java.util.*; +class GFG { + + static void maxSubArraySum(int a[], int size) + { + int max_so_far = Integer.MIN_VALUE, + max_ending_here = 0, start = 0, end = 0, s = 0; + + for (int i = 0; i < size; i++) { + max_ending_here += a[i]; + + if (max_so_far < max_ending_here) { + max_so_far = max_ending_here; + start = s; + end = i; + } + + if (max_ending_here < 0) { + max_ending_here = 0; + s = i + 1; + } + } + System.out.println("Maximum contiguous sum is " + + max_so_far); + System.out.println("Starting index " + start); + System.out.println("Ending index " + end); + } + + // Driver code + public static void main(String[] args) + { + int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; + int n = a.length; + maxSubArraySum(a, n); + } +} + + + + +``` +```python +// Java program to print largest +// contiguous array sum +import java.io.*; +import java.util.*; +class GFG { + + static void maxSubArraySum(int a[], int size) + { + int max_so_far = Integer.MIN_VALUE, + max_ending_here = 0, start = 0, end = 0, s = 0; + + for (int i = 0; i < size; i++) { + max_ending_here += a[i]; + + if (max_so_far < max_ending_here) { + max_so_far = max_ending_here; + start = s; + end = i; + } + + if (max_ending_here < 0) { + max_ending_here = 0; + s = i + 1; + } + } + System.out.println("Maximum contiguous sum is " + + max_so_far); + System.out.println("Starting index " + start); + System.out.println("Ending index " + end); + } + + + public static void main(String[] args) + { + int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; + int n = a.length; + maxSubArraySum(a, n); + } +} + + +``` +#### Time Complexity : $O(n)$ +#### Spcae Complexity : $O(1)$ + +## Better Approach - Dynamic Programming + +#### Approach +For each index `i`, `DP[i]` stores the maximum possible Largest Sum Contiguous Subarray ending at index `i`, and therefore we can calculate `DP[i]` using the mentioned state transition: + +`DP[i] = max(DP[i-1] + arr[i] , arr[i] )` + +```c++ +// C++ program to print largest contiguous array sum +#include +using namespace std; + +void maxSubArraySum(int a[], int size) +{ + vector dp(size, 0); + dp[0] = a[0]; + int ans = dp[0]; + for (int i = 1; i < size; i++) { + dp[i] = max(a[i], a[i] + dp[i - 1]); + ans = max(ans, dp[i]); + } + cout << ans; +} + +/*Driver program to test maxSubArraySum*/ +int main() +{ + int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; + int n = sizeof(a) / sizeof(a[0]); + maxSubArraySum(a, n); + return 0; +} + + +``` +```java +import java.util.Arrays; + +public class Main { + // Function to find the largest contiguous array sum + public static void maxSubArraySum(int[] a) { + int size = a.length; + int[] dp = new int[size]; // Create an array to store intermediate results + dp[0] = a[0]; // Initialize the first element of the intermediate array with the first element of the input array + int ans = dp[0]; // Initialize the answer with the first element of the intermediate array + for (int i = 1; i < size; i++) { + // Calculate the maximum of the current element and the sum of the current element and the previous result + dp[i] = Math.max(a[i], a[i] + dp[i - 1]); + // Update the answer with the maximum value encountered so far + ans = Math.max(ans, dp[i]); + } + // Print the maximum contiguous array sum + System.out.println(ans); + } + + public static void main(String[] args) { + int[] a = { -2, -3, 4, -1, -2, 1, 5, -3 }; + maxSubArraySum(a); // Call the function to find and print the maximum contiguous array sum + } +} + +``` +```python +# Python program for the above approach + +def max_sub_array_sum(a, size): + # Create a list to store intermediate results + dp = [0] * size + + # Initialize the first element of the list with the first element of the array + dp[0] = a[0] + + # Initialize the answer with the first element of the array + ans = dp[0] + + # Loop through the array starting from the second element + for i in range(1, size): + # Choose the maximum value between the current element and the sum of the current element + # and the previous maximum sum (stored in dp[i - 1]) + dp[i] = max(a[i], a[i] + dp[i - 1]) + + # Update the overall maximum sum + ans = max(ans, dp[i]) + + # Print the maximum contiguous subarray sum + print(ans) + +# Driver program to test max_sub_array_sum +if __name__ == "__main__": + # Sample array + a = [-2, -3, 4, -1, -2, 1, 5, -3] + + # Get the length of the array + n = len(a) + + # Call the function to find the maximum contiguous subarray sum + max_sub_array_sum(a, n) + +``` +#### Time Complexity : $O(n)$ +#### Spcae Complexity : $O(1)$ + +## Optimal Approach (Kadane's Algorithm): +#### Intuition +The idea of Kadane’s algorithm is to maintain a variable max_ending_here that stores the maximum sum contiguous subarray ending at current index and a variable max_so_far stores the maximum sum of contiguous subarray found so far, Everytime there is a positive-sum value in max_ending_here compare it with max_so_far and update max_so_far if it is greater than max_so_far. + +#### Steps +Follow the below steps to Implement the idea: + +- Initialize the variables max_so_far = INT_MIN and max_ending_here = 0 +- Run a for loop from 0 to N-1 and for each index i: +- Add the arr[i] to max_ending_here. +- If max_so_far is less than max_ending_here then update max_so_far to max_ending_here. +- If max_ending_here < 0 then update max_ending_here = 0 +- Return max_so_far + +## Implementing Kadane's Algorithm + +### Python Implementation + +```python +def GFG(a, size): + max_so_far = float('-inf') + # Use float('-inf') instead of maxint + max_ending_here = 0 + for i in range(0, size): + max_ending_here = max_ending_here + a[i] + if max_so_far < max_ending_here: + max_so_far = max_ending_here + if max_ending_here < 0: + max_ending_here = 0 + return max_so_far +# Driver function to check the above function +a = [-2, -3, 4, -1, -2, 1, 5, -3] +print("Maximum contiguous sum is", GFG(a, len(a))) + +``` + +### Java Implementation + +```java +// Java program to print largest contiguous array sum +import java.io.*; +import java.util.*; + +class Kadane { + // Driver Code + public static void main(String[] args) + { + int[] a = { -2, -3, 4, -1, -2, 1, 5, -3 }; + System.out.println("Maximum contiguous sum is " + + maxSubArraySum(a)); + } + + // Function Call + static int maxSubArraySum(int a[]) + { + int size = a.length; + int max_so_far = Integer.MIN_VALUE, max_ending_here + = 0; + + for (int i = 0; i < size; i++) { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; + } +} + +``` + +### C++ Implementation + +```cpp +// C++ program to print largest contiguous array sum +#include +using namespace std; + +int maxSubArraySum(int a[], int size) +{ + int max_so_far = INT_MIN, max_ending_here = 0; + + for (int i = 0; i < size; i++) { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; +} + +// Driver Code +int main() +{ + int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; + int n = sizeof(a) / sizeof(a[0]); + + // Function Call + int max_sum = maxSubArraySum(a, n); + cout << "Maximum contiguous sum is " << max_sum; + return 0; +} + +``` + +## Complexity Analysis + #### Time Complexity : $O(n)$ + #### Space Complexity : $O(1)$ + +## Conclusion +- Extended Kadane's Algorithm concludes by returning element of maximum contiguous. \ No newline at end of file diff --git a/docs/arrays/_category_.json b/docs/arrays/_category_.json new file mode 100644 index 0000000..6b7a0d6 --- /dev/null +++ b/docs/arrays/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Arrays", + "position": 7, + "link": { + "type": "generated-index", + "description": "In Data Structures, an array is a data structure consisting of a collection of elements, each identified by at least one array index or key. An array is stored such that the position of each element can be computed from its index tuple by a mathematical formula. The simplest type of data structure is a linear array, also called one-dimensional array." + } + } \ No newline at end of file diff --git a/docs/arrays/arrays-dsa.md b/docs/arrays/arrays-dsa.md new file mode 100644 index 0000000..2b4e3c7 --- /dev/null +++ b/docs/arrays/arrays-dsa.md @@ -0,0 +1,16 @@ +--- +id: arrays-in-dsa +title: All Problems on Arrays in DSA +sidebar_label: Arrays All Problems +sidebar_position: 1 +description: "Arrays are the most basic data structure in computer science. They are used to store a collection of elements of the same type. In this article, we will learn about arrays, their properties, and the problems related to arrays in Data Structures and Algorithms. We will also discuss the problems for practice." +tags: [dsa, arrays, data-structures, algorithms, programming-skills, leetcode, interview-questions, problems, practice, collection] +--- + +import collections from './collections'; + +In this page we will shared all the problems related to Arrays in Data Structures and Algorithms. We will also discuss the problems for practice. So, let's get started. + +## Study Materials / Resources + + \ No newline at end of file diff --git a/docs/arrays/collections.js b/docs/arrays/collections.js new file mode 100644 index 0000000..e7a2333 --- /dev/null +++ b/docs/arrays/collections.js @@ -0,0 +1,12 @@ +const collections = [ + { label: "LeetCode Study Plan", url:"https://leetcode.com/study-plan/programming-skills" }, + { label: "GFG Study Resource", url: "https://www.geeksforgeeks.org/array-data-structure/" }, + { label: "GFG - Problems For Interviews", url: "https://www.geeksforgeeks.org/top-50-array-coding-problems-for-interviews/" }, + { label: "workat Study Plan", url: "https://workat.tech/problem-solving/topics/arrays/practice" }, + { label: "IgotanOffer Study Plan", url: "https://igotanoffer.com/blogs/tech/array-interview-questions"}, + { label: "Coding Ninjas Study Plan", url: "https://www.codingninjas.com/studio/problem-lists/top-array-coding-interview-questions"}, + { label: "InterviewBit Study Plan", url: "https://www.interviewbit.com/array-interview-questions/"}, + { label: "Educative Study Plan", url: "https://www.educative.io/blog/array-interview-questions"}, +]; + +export default collections; diff --git a/docs/beginner/001-Time-Complexity.md b/docs/beginner/001-Time-Complexity.md new file mode 100644 index 0000000..9f832f1 --- /dev/null +++ b/docs/beginner/001-Time-Complexity.md @@ -0,0 +1,277 @@ +--- +id: 001-time-complexity +title: Time Complexity +sidebar_label: Time Complexity +tags: + - dsa + - data-structures + - algorithms + - introduction + - basics + - beginner + - programming + - time-complexity + - data structure + - algorithm +sidebar_position: 2 +--- +# Introduction to Time Complexity + +## What is Time Complexity? +Time complexity is a way to measure how the runtime of an algorithm changes as the size of the input changes. It helps us understand and compare the efficiency of different algorithms. + +## Big O Notation +Big O notation is a mathematical notation used to describe the upper bound of an algorithm's runtime. It provides a worst-case scenario for the time complexity of an algorithm. + +## Example + +Q. Imagine a classroom of 100 students in which you gave your pen to one person. You have to find that pen without knowing to whom you gave it. + +Here are some ways to find the pen and what the $O$ order is. + +1. $O(n2)$: You go and ask the first person in the class if he has the pen. Also, you ask this person about the other 99 people in the classroom if they have that pen and so on, +This is what we call $O(n2)$. +2. $O(n)$: Going and asking each student individually is $O(N)$. +3. $O(log n)$: Now I divide the class into two groups, then ask: β€œIs it on the left side, or the right side of the classroom?” Then I take that group and divide it into two and ask again, and so on. Repeat the process till you are left with one student who has your pen. This is what you mean by $O(log n)$ + +- The $O(n2)$ searches if only one student knows on which student the pen is hidden. +- The $O(n)$ if one student had the pen and only they knew it. +- The $O(log n)$ search if all the students knew, but would only tell me if I guessed the right side. + +## Use Cases + +| Input Length | Worst Accepted Time Complexity | Usually Type of Solutions | +|--------------|--------------------------------|---------------------------------------------| +| 10-12 | O(N!) | Recursion and backtracking | +| 15-18 | O(2^N * N) | Recursion, backtracking, and bit manipulation| +| 18-22 | O(2^N * N) | Recursion, backtracking, and bit manipulation| +| 30-40 | O(2^(N/2) * N) | Meet in the middle, Divide and Conquer | +| 100 | O(N^4) | Dynamic programming, Constructive | +| 400 | O(N^3) | Dynamic programming, Constructive | +| 2K | O(N^2 * log N) | Dynamic programming, Binary Search, Sorting, Divide and Conquer | +| 10K | O(N^2) | Dynamic programming, Graph, Trees, Constructive | +| 1M | O(N * log N) | Sorting, Binary Search, Divide and Conquer | +| 100M | O(N), O(log N), O(1) | Constructive, Mathematical, Greedy Algorithms| + + +### Common Time Complexities + +#### a) O(1) - Constant Time Complexity +The runtime does not change with the input size. + +```python +def get_first_element(arr): + return arr[0] +``` +The time it takes to get the first element is constant, regardless of the size of the array. + +#### b) O(log n) - Logarithmic Time Complexity +The runtime grows logarithmically with the input size. + +```python +def binary_search(arr, target): + low = 0 + high = len(arr) - 1 + while low <= high: + mid = (low + high) // 2 + if arr[mid] == target: + return mid + elif arr[mid] < target: + low = mid + 1 + else: + high = mid - 1 + return -1 +``` +The time it takes to find the target grows logarithmically with the size of the array. + +#### c) O(n) - Linear Time Complexity +The runtime grows linearly with the input size. + +```python +def print_elements(arr): + for element in arr: + print(element) +``` +The time it takes to print all elements grows linearly with the size of the array. + +#### d) O(n^2) - Quadratic Time Complexity +The runtime grows quadratically with the input size. + +```python +def bubble_sort(arr): + n = len(arr) + for i in range(n): + for j in range(0, n-i-1): + if arr[j] > arr[j+1]: + arr[j], arr[j+1] = arr[j+1], arr[j] +``` +The time it takes to sort the array grows quadratically with the size of the array. + +#### e) O(2^n) - Exponential Time Complexity +The runtime doubles with each additional element in the input. + +```python +def fibonacci(n): + if n <= 1: + return n + else: + return fibonacci(n-1) + fibonacci(n-2) +``` +The time it takes to calculate the nth Fibonacci number doubles with each additional element. + +#### f) O(n!) - Factorial Time Complexity +The runtime grows factorially with the input size. + +```python +def permutations(arr, l, r): + if l == r: + print(''.join(arr)) + else: + for i in range(l, r+1): + arr[l], arr[i] = arr[i], arr[l] + permutations(arr, l+1, r) + arr[l], arr[i] = arr[i], arr[l] +``` +The time it takes to generate all permutations of the array grows factorially with the size of the array. + +## How to Calculate Time Complexity? + +1. **Identify the basic operations** in your algorithm (e.g., comparisons, assignments). +2. **Count the number of times these operations are executed** in terms of the input size $N$. +3. **Express this count using Big O notation** to simplify and generalize the complexity. + +## Time Complexity of Different Data Structures + +- **Array**: + - Access: $O(1)$ + - Search: $O(N)$ + - Insertion: $O(N)$ + - Deletion: $O(N)$ + +- **Linked List**: + - Access: $O(N)$ + - Search: $O(N)$ + - Insertion: $O(1)$ + - Deletion: $O(1)$ + +- **Hash Table**: + - Access: $O(1)$ + - Search: $O(1)$ + - Insertion: $O(1)$ + - Deletion: $O(1)$ + +- **Binary Search Tree**: + - Access: $O(log N)$ + - Search: $O(log N)$ + - Insertion: $O(log N)$ + - Deletion: $O(log N)$ + +## Analyzing Algorithms with Time Complexity + +1. **Linear Search**: + ```python + def linear_search(arr, target): + for i in range(len(arr)): + if arr[i] == target: + return i + return -1 + ``` + Time Complexity: $O(N)$ + +2. **Binary Search**: + ```python + def binary_search(arr, target): + low = 0 + high = len(arr) - 1 + while low <= high: + mid = (low + high) // 2 + if arr[mid] == target: + return mid + elif arr[mid] < target: + low = mid + 1 + else: + high = mid - 1 + return -1 + ``` + Time Complexity: $O(log N)$ + +3. **Bubble Sort**: + ```python + def bubble_sort(arr): + n = len(arr) + for i in range(n): + for j in range(0, n-i-1): + if arr[j] > arr[j+1]: + arr[j], arr[j+1] = arr[j+1], arr[j] + ``` + Time Complexity: $O(N^2)$ + +4. **Merge Sort**: + ```python + def merge_sort(arr): + if len(arr) > 1: + mid = len(arr) // 2 + left_half = arr[:mid] + right_half = arr[mid:] + + merge_sort(left_half) + merge_sort(right_half) + + i = j = k = 0 + + while i < len(left_half) and j < len(right_half): + if left_half[i] < right_half[j]: + arr[k] = left_half[i] + i += 1 + else: + arr[k] = right_half[j] + j += 1 + k += 1 + + while i < len(left_half): + arr[k] = left_half[i] + i += 1 + k += 1 + + while j < len(right_half): + arr[k] = right_half[j] + j += 1 + k += 1 + ``` + Time Complexity: $O(N log N)$ + +5. **Fibonacci (Recursive)**: + ```python + def fibonacci(n): + if n <= 1: + return n + else: + return fibonacci(n-1) + fibonacci(n-2) + ``` + Time Complexity: $O(2^N)$ + +## Practical Tips + +- **Optimize Your Code**: Aim to reduce the time complexity for better performance, especially for large inputs. +- **Consider Both Time and Space Complexity**: While time complexity is important, space complexity (the amount of memory used) is also crucial. +- **Know Your Problem Domain**: Some problems inherently require higher time complexity. Understanding the problem domain helps in choosing the right algorithm. + +## Resources to Learn More + +1. **Books**: + - *Introduction to Algorithms* by Cormen, Leiserson, Rivest, and Stein + - *Algorithm Design Manual* by Steven S. Skiena + +2. **Online Courses**: + - [Coursera Algorithms Specialization](https://www.coursera.org/specializations/algorithms) + - [edX Data Structures and Algorithm](https://www.edx.org/course/data-structures-and-algorithms) + +3. **Websites**: + - [GeeksforGeeks Time Complexity](https://www.geeksforgeeks.org/analysis-of-algorithms-set-1-asymptotic-analysis/) + - [Khan Academy Algorithms](https://www.khanacademy.org/computing/computer-science/algorithms) + +4. **Interactive Tools**: + - [VisuAlgo](https://visualgo.net/en) + - [Big O Cheat Sheet](https://www.bigocheatsheet.com/) + +Understanding time complexity is essential for writing efficient algorithms and is a fundamental skill in computer science and software development. By analyzing and optimizing time complexity, you can ensure your programs run efficiently, even with large inputs. diff --git a/docs/beginner/002-Recursion.md b/docs/beginner/002-Recursion.md new file mode 100644 index 0000000..5507531 --- /dev/null +++ b/docs/beginner/002-Recursion.md @@ -0,0 +1,202 @@ +--- +id: 0002-recursion +title: Recursion +sidebar_label: Recursion +tags: + - Basics + - Algorithms + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains the concept of Recursion with detailed explanations, examples, and code implementations." +--- + +## 1. What is Recursion? + +Recursion is a programming technique where a function calls itself in order to solve a problem. This technique divides the problem into smaller, more manageable sub-problems. A recursive function has two main parts: +- **Base Case:** The condition under which the function stops calling itself. +- **Recursive Case:** The part where the function calls itself with a smaller or simpler sub-problem. + +## 2. How Does Recursion Work? + +Recursion works by breaking down a problem into smaller instances of the same problem until a base case is reached. The base case is the simplest form of the problem, which can be solved directly without further recursion. Once the base case is reached, the function returns a value, and the recursive calls start to resolve in reverse order, ultimately solving the entire problem. + +### Example: Factorial of a Number + +The factorial of a number `n` (denoted as `n!`) is the product of all positive integers less than or equal to `n`. + +- **Factorial of 5:** `5! = 5 * 4 * 3 * 2 * 1 = 120` + +Here is the recursive definition of factorial: +- **Base Case:** `0! = 1` +- **Recursive Case:** `n! = n * (n - 1)!` + +## Algorithmic Approach + +#### The algorithmic steps for implementing recursion in a function are as follows: + +- Step1 - Define a base case: Identify the simplest case for which the solution is known or trivial. This is the stopping condition for the recursion, as it prevents the function from infinitely calling itself. + +- Step2 - Define a recursive case: Define the problem in terms of smaller subproblems. Break the problem down into smaller versions of itself, and call the function recursively to solve each subproblem. + +- Step3 - Ensure the recursion terminates: Make sure that the recursive function eventually reaches the base case, and does not enter an infinite loop. + +- Step4 - Combine the solutions: Combine the solutions of the subproblems to solve the original problem. + +## How are recursive functions stored in memory? + +Recursion uses more memory, because the recursive function adds to the stack with each recursive call, and keeps the values there until the call is finished. The recursive function uses LIFO (LAST IN FIRST OUT) Structure just like the stack data structure. ![Recursive memore](https://www.geeksforgeeks.org/stack-data-structure/) + +### What is the base condition in recursion? +- In the recursive program, the solution to the base case is provided and the solution to the bigger problem is expressed in terms of smaller problems. + +``` +int fact(int n) +{ + if (n < = 1) // base case + return 1; + else + return n*fact(n-1); +} +``` + +In the above example, the base case for n < = 1 is defined and the larger value of a number can be solved by converting to a smaller one till the base case is reached. + +### Why Stack Overflow error occurs in recursion? +If the base case is not reached or not defined, then the stack overflow problem may arise. Let us take an example to understand this. + +``` +int fact(int n) +{ + // wrong base case (it may cause + // stack overflow). + if (n == 100) + return 1; + + else + return n*fact(n-1); +} +``` + +If $fact(10)$ is called, it will call $fact(9)$, $fact(8)$, $fact(7)$, and so on but the number will never reach 100. So, the base case is not reached. If the memory is exhausted by these functions on the stack, it will cause a stack overflow error. + +## 3. Problem Description + +Compute the factorial of a given number using recursion. + +## 4. Examples + +### Example 1: +**Input:** `n = 5` +**Output:** `120` + +### Example 2: +**Input:** `n = 0` +**Output:** `1` + +## 5. Constraints + +- $0 \leq n \leq 12$ (for reasonable output) + +## 6. Algorithm for Recursion + +1. Define the base case for the smallest problem. +2. Define the recursive case that breaks the problem into smaller sub-problems. +3. Ensure the problem size decreases with each recursive call to reach the base case. + +## 7. Implementation (Code for 4 Languages) + + + + ```python + def factorial(n): + if n == 0: + return 1 + else: + return n * factorial(n - 1) + + # Example usage: + print(factorial(5)) # Output: 120 + ``` + + + + ```cpp + #include + using namespace std; + + int factorial(int n) { + if (n == 0) + return 1; + else + return n * factorial(n - 1); + } + + int main() { + cout << factorial(5) << endl; // Output: 120 + return 0; + } + ``` + + + + ```java + public class Recursion { + public static int factorial(int n) { + if (n == 0) + return 1; + else + return n * factorial(n - 1); + } + + public static void main(String[] args) { + System.out.println(factorial(5)); // Output: 120 + } + } + ``` + + + + ```javascript + function factorial(n) { + if (n === 0) { + return 1; + } else { + return n * factorial(n - 1); + } + } + + // Example usage: + console.log(factorial(5)); // Output: 120 + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity:** $O(n)$, where $n$ is the number of recursive calls. +- **Space Complexity:** $O(n)$, due to the call stack. + +## 9. Advantages and Disadvantages + +### Advantages: +- Simplifies code for problems that can be broken into similar sub-problems. +- Natural fit for problems that have a recursive structure, such as tree traversals. + +### Disadvantages: +- May lead to high memory usage due to the call stack, especially for deep recursions. +- Can be slower due to the overhead of multiple function calls. + +## 10. Examples of Recursion in Practice + +- **Fibonacci Series:** Computing Fibonacci numbers. +- **Tree Traversals:** Pre-order, in-order, and post-order traversals. +- **Backtracking Algorithms:** Solving puzzles like Sudoku or the N-Queens problem. +- **Divide and Conquer Algorithms:** Merge sort, quicksort, etc. + +## 11. References + +- [GeeksforGeeks - Recursion](https://www.geeksforgeeks.org/recursion/) +- [Wikipedia - Recursion](https://en.wikipedia.org/wiki/Recursion_(computer_science)) diff --git a/docs/beginner/01-introduction.md b/docs/beginner/01-introduction.md new file mode 100644 index 0000000..6b07777 --- /dev/null +++ b/docs/beginner/01-introduction.md @@ -0,0 +1,41 @@ +--- +id: 01-introduction-to-dsa +title: Introduction to Data Structures and Algorithms +sidebar_label: Introduction +tags: + - dsa + - data-structures + - algorithms + - introduction + - basics + - beginner + - programming + - computer-science + - data structure + - algorithm +sidebar_position: 1 +--- + +Data Structures and Algorithms (DSA) are the building blocks of computer programming. They are essential tools for any programmer to have in their toolkit. They help in writing efficient code and solving complex problems. + +## What are Data Structures? + +Data Structures are a way of organizing and storing data in a computer so that it can be accessed and modified efficiently. They define the relationship between the data and the operations that can be performed on the data. + +Data Structures are used to store and manage data in an efficient and organized way. They are used to represent data in a way that is easy to understand and manipulate. + +## What are Algorithms? + +Algorithms are a set of instructions or rules that are used to solve a problem. They define the steps that need to be followed to solve a problem. Algorithms are used to solve problems in an efficient and systematic way. + +Algorithms are used to perform operations on data structures. They define the steps that need to be followed to perform a specific operation on a data structure. + +## Why Learn Data Structures and Algorithms? + +Data Structures and Algorithms are essential tools for any programmer. They help in writing efficient code and solving complex problems. They are used in a wide range of applications, from simple programs to complex systems. + +Learning Data Structures and Algorithms will help you become a better programmer. It will help you write efficient code, solve complex problems, and understand how computer programs work. + +## Conclusion + +Data Structures and Algorithms are the building blocks of computer programming. They are essential tools for any programmer to have in their toolkit. They help in writing efficient code and solving complex problems. Learning Data Structures and Algorithms will help you become a better programmer and understand how computer programs work. \ No newline at end of file diff --git a/docs/beginner/02-basics-of-programming.md b/docs/beginner/02-basics-of-programming.md new file mode 100644 index 0000000..b662c35 --- /dev/null +++ b/docs/beginner/02-basics-of-programming.md @@ -0,0 +1,140 @@ +--- +id: 02-basics-of-programming +title: Basics of Programming +sidebar_label: Basics of Programming +tags: + - dsa + - data-structures + - algorithms + - introduction + - basics + - beginner + - programming + - computer-science + - data structure + - algorithm +sidebar_position: 2 +--- + +Programming is the process of writing instructions for a computer to perform a specific task. It involves writing code in a programming language that the computer can understand and execute. Programming is an essential skill for any software developer or computer scientist. In this tutorial, we will cover the basics of programming, including the following topics: + +- What is Programming? +- Why Learn Programming? +- How to Write a Program? +- Programming Languages +- Basic Programming Concepts +- Common Programming Constructs +- Programming Tools and Environments +- Best Practices in Programming +- Conclusion + +## What is Programming? + +Programming is the process of writing instructions for a computer to perform a specific task. These instructions are written in a programming language, which is a formal language that specifies a set of rules and syntax for writing code. The code is then translated into machine code by a compiler or interpreter, which the computer can understand and execute. + +Programming involves designing algorithms, writing code, testing and debugging programs, and maintaining and updating software. It requires logical thinking, problem-solving skills, and attention to detail. + +## Why Learn Programming? + +Learning programming is essential for anyone interested in computer science, software development, or technology in general. Programming allows you to create software applications, websites, games, and other digital products. It enables you to automate tasks, analyze data, and solve complex problems. + +Programming is a valuable skill in today's digital world. It opens up a wide range of career opportunities in software development, data science, artificial intelligence, cybersecurity, and more. It also helps you develop critical thinking, creativity, and problem-solving skills. + +## How to Write a Program? + +To write a program, you need to follow these steps: + +**1. Define the problem:** Understand the problem you want to solve and identify the requirements and constraints. Break down the problem into smaller subproblems if necessary. +**2. Design the algorithm:** Develop a step-by-step plan or algorithm to solve the problem. +**3. Write the code:** Implement the algorithm in a programming language by writing code. +**4. Test and debug:** Test the program to ensure it works correctly and fix any errors or bugs. +**5. Run and maintain:** Run the program and maintain it by updating and improving it as needed. + +## Programming Languages + +Programming languages are formal languages that specify a set of rules and syntax for writing code. They allow programmers to communicate instructions to a computer and develop software applications. There are thousands of programming languages, each with its own syntax, features, and use cases. Some popular programming languages include: + +- **Python:** A versatile and beginner-friendly language used for web development, data analysis, artificial intelligence, and more. +- **Java:** A widely-used language for building enterprise applications, mobile apps, and web services. +- **JavaScript:** A language used for front-end and back-end web development, including interactive websites and web applications. +- **C++:** A powerful language used for system programming, game development, and high-performance applications. +- **C#:** A language developed by Microsoft for building Windows applications, games, and enterprise software. +- **Ruby:** A language known for its simplicity and productivity, used for web development and automation. +- **PHP:** A server-side language used for building dynamic websites and web applications. +- **Swift:** A language developed by Apple for building iOS and macOS applications. +- **Kotlin:** A modern language used for Android app development and building cross-platform applications. +- **R:** A language used for statistical computing, data analysis, and machine learning. +- **SQL:** A language used for managing and querying databases. +- **HTML/CSS:** Markup and styling languages used for creating web pages and web applications. +- **Assembly:** A low-level language used for system programming and embedded systems. +- **Go:** A language developed by Google for building scalable and efficient software. +- **TypeScript:** A superset of JavaScript that adds static typing and other features for large-scale applications. + +## Basic Programming Concepts + +Programming involves several fundamental concepts that are common to most programming languages. These concepts include: + +- **Variables:** Named storage locations used to store data values. +- **Data Types:** Categories of data values, such as integers, floating-point numbers, strings, and booleans. +- **Operators:** Symbols used to perform operations on data values, such as arithmetic, comparison, and logical operations. +- **Control Structures:** Statements that control the flow of a program, such as loops and conditional statements. +- **Functions:** Named blocks of code that perform a specific task or operation. +- **Classes and Objects:** Blueprints for creating objects with properties and methods. +- **Arrays and Collections:** Data structures used to store multiple values in a single variable. +- **Input and Output:** Reading data from and writing data to external sources, such as files or the console. +- **Error Handling:** Dealing with errors and exceptions that occur during program execution. +- **Comments:** Annotations in the code that provide additional information and improve readability. +- **Testing and Debugging:** Techniques for testing and fixing errors in programs. + +## Common Programming Constructs + +Programming languages provide constructs that allow you to perform common tasks and solve problems efficiently. Some common programming constructs include: + +- **Loops:** Repeating a block of code multiple times until a condition is met. +- **Conditional Statements:** Executing different blocks of code based on a condition. +- **Functions and Methods:** Encapsulating code into reusable blocks that can be called multiple times. +- **Recursion:** A technique where a function calls itself to solve a problem. +- **Data Structures:** Collections of data values organized in a specific way, such as arrays, lists, stacks, queues, trees, and graphs. +- **Algorithms:** Step-by-step procedures for solving a problem, such as searching, sorting, and graph traversal algorithms. +- **Object-Oriented Programming:** A programming paradigm based on objects and classes, emphasizing encapsulation, inheritance, and polymorphism. +- **Functional Programming:** A programming paradigm based on functions and immutability, emphasizing pure functions and higher-order functions. +- **Event-Driven Programming:** A programming paradigm based on events and event handlers, used in graphical user interfaces and asynchronous programming. +- **Parallel and Concurrent Programming:** Techniques for executing multiple tasks simultaneously, such as multithreading and multiprocessing. +- **Error Handling:** Dealing with errors and exceptions that occur during program execution. +- **Input and Output:** Reading data from and writing data to external sources, such as files, databases, or the network. +- **Testing and Debugging:** Techniques for testing and fixing errors in programs. +- **Optimization:** Improving the performance and efficiency of programs by reducing resource usage and execution time. + +## Programming Tools and Environments + +Programmers use a variety of tools and environments to write, test, and debug programs. Some common programming tools and environments include: + +- **Integrated Development Environments (IDEs):** Software applications that provide a comprehensive set of tools for writing, testing, and debugging code, such as Visual Studio, Eclipse, IntelliJ IDEA, and PyCharm. + +- **Text Editors:** Lightweight tools for writing and editing code, such as Visual Studio Code, Sublime Text, Atom, and Notepad++. + +- **Compilers and Interpreters:** Software that translates code written in a high-level language into machine code that the computer can execute, such as GCC, Clang, Python, and Node.js. + +- **Version Control Systems:** Tools for managing changes to code and collaborating with other developers, such as Git, SVN, and Mercurial. + +- **Debuggers:** Tools for finding and fixing errors in code, such as breakpoints, watch windows, and call stacks. + +- **Testing Frameworks:** Tools for writing and running automated tests to ensure code quality and reliability, such as JUnit, NUnit, PyTest, and Jasmine. + +- **Package Managers:** Tools for managing dependencies and libraries used in a project, such as npm, pip, Maven, and NuGet. + +## Best Practices in Programming + +To write clean, efficient, and maintainable code, programmers follow best practices and coding standards. Some common best practices in programming include: + +- **Use Meaningful Names:** Choose descriptive names for variables, functions, classes, and other elements in the code. +- **Write Readable Code:** Use consistent formatting, indentation, and comments to improve code readability. +- **Follow Coding Conventions:** Adhere to coding standards and style guides for the programming language or framework you are using. +- **Avoid Code Duplication:** Refactor duplicate code into reusable functions or classes to improve code maintainability. +- **Write Modular Code:** Break down complex problems into smaller modules or functions that perform specific tasks. +- **Test Early and Often:** Write automated tests to verify the correctness of the code and catch errors early in the development process. +- **Document Your Code:** Add comments, documentation, and inline annotations to explain the purpose and functionality of the code. + +## Conclusion + +Programming is an essential skill for anyone interested in computer science, software development, or technology. It allows you to create software applications, automate tasks, analyze data, and solve complex problems. By learning programming, you can open up a wide range of career opportunities and develop valuable skills that are in high demand in today's digital world. Whether you are a beginner or an experienced programmer, mastering the basics of programming will help you become a more effective and efficient developer. \ No newline at end of file diff --git a/docs/beginner/03-arrays-and-strings.md b/docs/beginner/03-arrays-and-strings.md new file mode 100644 index 0000000..a6f2ad8 --- /dev/null +++ b/docs/beginner/03-arrays-and-strings.md @@ -0,0 +1,263 @@ +--- +id: 03-arrays-and-strings +title: Arrays and Strings +sidebar_label: Arrays and Strings +tags: + - dsa + - data-structures + - arrays + - strings + - beginner + - javascript + - python + - c++ + - java + - programming + - tutorial + - typescript +sidebar_position: 3 +--- + +In this tutorial, we will learn about arrays and strings in programming. We will discuss what arrays and strings are, how they are used, and how they are different from each other. + +## Arrays in Programming + +An array is a data structure that stores a collection of elements. These elements can be of any data type, such as integers, strings, or objects. An array is a fixed-size data structure, which means that the number of elements it can store is determined when it is created. + +In most programming languages, arrays are zero-indexed, which means that the first element of the array is at index 0, the second element is at index 1, and so on. The size of an array is the number of elements it can store. + +Arrays are used to store a collection of elements that are related to each other in some way. For example, an array can be used to store the grades of students in a class, the temperatures recorded over a period of time, or the names of employees in a company. + +Here is an example of an array in some programming languages: + + + + ```javascript + // Creating an array in JavaScript + let numbers = [1, 2, 3, 4, 5]; + + // Accessing elements of an array + console.log(numbers[0]); // Output: 1 + console.log(numbers[1]); // Output: 2 + console.log(numbers[2]); // Output: 3 + ``` + + + + ```python + # Creating an array in Python + numbers = [1, 2, 3, 4, 5] + + # Accessing elements of an array + print(numbers[0]) # Output: 1 + print(numbers[1]) # Output: 2 + print(numbers[2]) # Output: 3 + ``` + + + + ```typescript + // Creating an array in TypeScript + let numbers: number[] = [1, 2, 3, 4, 5]; + + // Accessing elements of an array + console.log(numbers[0]); // Output: 1 + console.log(numbers[1]); // Output: 2 + console.log(numbers[2]); // Output: 3 + ``` + + + + ```cpp + #include + using namespace std; + + int main() { + // Creating an array in C++ + int numbers[] = {1, 2, 3, 4, 5}; + + // Accessing elements of an array + cout << numbers[0] << endl; // Output: 1 + cout << numbers[1] << endl; // Output: 2 + cout << numbers[2] << endl; // Output: 3 + + return 0; + } + ``` + + + + ```java + public class Main { + public static void main(String[] args) { + // Creating an array in Java + int[] numbers = {1, 2, 3, 4, 5}; + + // Accessing elements of an array + System.out.println(numbers[0]); // Output: 1 + System.out.println(numbers[1]); // Output: 2 + System.out.println(numbers[2]); // Output: 3 + } + } + ``` + + + + +## Strings in Programming + +A string is a sequence of characters, such as letters, digits, or symbols. Strings are used to represent text in programming. Strings are a fundamental data type in most programming languages, and they are used to store and manipulate text data. + +Strings can be created using single quotes (`'`) or double quotes (`"`). In some programming languages, strings are immutable, which means that once a string is created, it cannot be changed. However, in other programming languages, strings are mutable, which means that they can be modified after they are created. + +Here is an example of a string in some programming languages: + + + + ```javascript + // Creating a string in JavaScript + let name = 'Alice'; + + // Accessing characters of a string + console.log(name[0]); // Output: 'A' + console.log(name[1]); // Output: 'l' + console.log(name[2]); // Output: 'i' + ``` + + + + ```python + # Creating a string in Python + name = 'Alice' + + # Accessing characters of a string + print(name[0]) # Output: 'A' + print(name[1]) # Output: 'l' + print(name[2]) # Output: 'i' + ``` + + + + ```typescript + // Creating a string in TypeScript + let name: string = 'Alice'; + + // Accessing characters of a string + console.log(name[0]); // Output: 'A' + console.log(name[1]); // Output: 'l' + console.log(name[2]); // Output: 'i' + ``` + + + + ```cpp + #include + using namespace std; + + int main() { + // Creating a string in C++ + string name = "Alice"; + + // Accessing characters of a string + cout << name[0] << endl; // Output: 'A' + cout << name[1] << endl; // Output: 'l' + cout << name[2] << endl; // Output: 'i' + + return 0; + } + ``` + + + + ```java + public class Main { + public static void main(String[] args) { + // Creating a string in Java + String name = "Alice"; + + // Accessing characters of a string + System.out.println(name.charAt(0)); // Output: 'A' + System.out.println(name.charAt(1)); // Output: 'l' + System.out.println(name.charAt(2)); // Output: 'i' + } + } + ``` + + + + +## Differences Between Arrays and Strings + +While arrays and strings are both used to store collections of elements, there are some key differences between them: + +| No. | Arrays | Strings | +| --- | -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | +| 1. | An array is a collection of elements of any data type. | A string is a sequence of characters. | +| 2. | The elements of an array can be of different data types. | The characters of a string are of the same data type (usually characters). | +| 3. | Arrays are mutable, which means that the elements of an array can be modified after it is created. | Strings are immutable in some programming languages, which means that a string cannot be changed after it is created. | +| 4. | Arrays are zero-indexed, which means that the first element of an array is at index 0. | Strings are indexed by position, which means that the first character of a string is at position 1. | +| 5. | Arrays are used to store a collection of elements that are related to each other in some way. | Strings are used to represent text data. | + +:::tip for better understanding + +## Live Example + +You can run the following code snippet to see the output of the examples provided above: + +```jsx live +function Example() { + // Creating an array + let numbers = [1, 2, 3, 4, 5]; + + // Creating a string + let name = "Alice"; + + return ( +
+
+

Array Example

+

Accessing elements of an array:

+

{numbers[0]}

+

{numbers[1]}

+

{numbers[2]}

+
+
+

String Example

+

Accessing characters of a string:

+

{name[0]}

+

{name[1]}

+

{name[2]}

+
+
+ ); +} +``` + +In the above example, we have created an array `numbers` and a string `name`. We have accessed the elements of the array and the characters of the string and displayed them on the screen. +::: + +## Conclusion + +In this tutorial, we learned about arrays and strings in programming. We discussed what arrays and strings are, how they are used, and how they are different from each other. We also saw examples of arrays and strings in different programming languages. diff --git a/docs/beginner/04-stacks-and-queues.md b/docs/beginner/04-stacks-and-queues.md new file mode 100644 index 0000000..4a9b48c --- /dev/null +++ b/docs/beginner/04-stacks-and-queues.md @@ -0,0 +1,840 @@ +--- +id: 04-stacks-and-queues +title: Stacks and Queues in Data Structures and Algorithms +sidebar_label: Stacks and Queues +tags: + - dsa + - data-structures + - stacks + - queues + - beginner + - javascript + - python + - c++ + - java + - programming + - tutorial + - typescript +sidebar_position: 4 +--- + +In this tutorial, we will learn about stacks and queues in Data Structures and Algorithms. We will discuss what stacks and queues are, how they are used, and how they are different from each other. + +## Stacks in Data Structures and Algorithms + +A stack is a data structure that stores a collection of elements. The elements in a stack are stored in a Last-In-First-Out (LIFO) order, which means that the last element added to the stack is the first one to be removed. Stacks are used to store elements that need to be accessed in a specific order, such as undo operations in a text editor, function calls in a program, or backtracking in a maze-solving algorithm. + +A stack has two main operations: + +1. **Push**: Adds an element to the top of the stack. +2. **Pop**: Removes and returns the element at the top of the stack. + +In addition to these operations, stacks may also support other operations such as: + +- **Peek**: Returns the element at the top of the stack without removing it. +- **isEmpty**: Checks if the stack is empty. +- **Size**: Returns the number of elements in the stack. +- **Clear**: Removes all elements from the stack. +- **Search**: Searches for an element in the stack. +- **Copy**: Creates a copy of the stack. +- **Iterate**: Iterates over the elements of the stack. +- **Merge**: Merges two stacks into one. +- **Reverse**: Reverses the order of elements in the stack. +- **Sort**: Sorts the elements of the stack. +- **Map**: Applies a function to each element of the stack. + +Here is an example of a stack in some programming languages: + + + + ```javascript + // Creating a stack in JavaScript + class Stack { + constructor() { + this.items = []; + } + + // Push operation + push(element) { + this.items.push(element); + } + + // Pop operation + pop() { + if (this.isEmpty()) { + return "Underflow"; + } + return this.items.pop(); + } + + // Peek operation + peek() { + return this.items[this.items.length - 1]; + } + + // isEmpty operation + isEmpty() { + return this.items.length === 0; + } + + // Size operation + size() { + return this.items.length; + } + + // Clear operation + clear() { + this.items = []; + } + + // Print operation + print() { + console.log(this.items); + } + } + + // Using the stack + let stack = new Stack(); + stack.push(1); + stack.push(2); + stack.push(3); + stack.print(); // Output: [1, 2, 3] + stack.pop(); + stack.print(); // Output: [1, 2] + console.log(stack.peek()); // Output: 2 + console.log(stack.isEmpty()); // Output: false + console.log(stack.size()); // Output: 2 + stack.clear(); + stack.print(); // Output: [] + ``` + + + + ```python + # Creating a stack in Python + class Stack: + def __init__(self): + self.items = [] + + # Push operation + def push(self, element): + self.items.append(element) + + # Pop operation + def pop(self): + if self.is_empty(): + return "Underflow" + return self.items.pop() + + # Peek operation + def peek(self): + return self.items[-1] + + # isEmpty operation + def is_empty(self): + return len(self.items) == 0 + + # Size operation + def size(self): + return len(self.items) + + # Clear operation + def clear(self): + self.items = [] + + # Print operation + def print(self): + print(self.items) + + # Using the stack + stack = Stack() + stack.push(1) + stack.push(2) + stack.push(3) + stack.print() # Output: [1, 2, 3] + stack.pop() + stack.print() # Output: [1, 2] + print(stack.peek()) # Output: 2 + print(stack.is_empty()) # Output: False + print(stack.size()) # Output: 2 + stack.clear() + stack.print() # Output: [] + ``` + + + + ```typescript + // Creating a stack in TypeScript + class Stack { + private items: T[] = []; + + // Push operation + push(element: T): void { + this.items.push(element); + } + + // Pop operation + pop(): T | string { + if (this.isEmpty()) { + return "Underflow"; + } + return this.items.pop(); + } + + // Peek operation + peek(): T | undefined { + return this.items[this.items.length - 1]; + } + + // isEmpty operation + isEmpty(): boolean { + return this.items.length === 0; + } + + // Size operation + size(): number { + return this.items.length; + } + + // Clear operation + clear(): void { + this.items = []; + } + + // Print operation + print(): void { + console.log(this.items); + } + } + + // Using the stack + let stack = new Stack(); + stack.push(1); + stack.push(2); + stack.push(3); + stack.print(); // Output: [1, 2, 3] + stack.pop(); + stack.print(); // Output: [1, 2] + console.log(stack.peek()); // Output: 2 + console.log(stack.isEmpty()); // Output: false + console.log(stack.size()); // Output: 2 + stack.clear(); + stack.print(); // Output: [] + ``` + + + + ```cpp + #include + #include + using namespace std; + + // Creating a stack in C++ + template + class Stack { + private: + vector items; + + public: + // Push operation + void push(T element) { + items.push_back(element); + } + + // Pop operation + T pop() { + if (isEmpty()) { + throw "Underflow"; + } + T element = items.back(); + items.pop_back(); + return element; + } + + // Peek operation + T peek() { + if (isEmpty()) { + throw "Stack is empty"; + } + return items.back(); + } + + // isEmpty operation + bool isEmpty() { + return items.empty(); + } + + // Size operation + int size() { + return items.size(); + } + + // Clear operation + void clear() { + items.clear(); + } + + // Print operation + void print() { + for (T element : items) { + cout << element << " "; + } + cout << endl; + } + }; + + int main() { + // Using the stack + Stack stack; + stack.push(1); + stack.push(2); + stack.push(3); + stack.print(); // Output: 1 2 3 + stack.pop(); + stack.print(); // Output: 1 2 + cout << stack.peek() << endl; // Output: 2 + cout << stack.isEmpty() << endl; // Output: 0 + cout << stack.size() << endl; // Output: 2 + stack.clear(); + stack.print(); // Output: + + return 0; + } + ``` + + + + ```java + import java.util.Stack; + + public class Main { + public static void main(String[] args) { + // Creating a stack in Java + Stack stack = new Stack<>(); + + // Push operation + stack.push(1); + stack.push(2); + stack.push(3); + + // Print operation + System.out.println(stack); // Output: [1, 2, 3] + + // Pop operation + stack.pop(); + System.out.println(stack); // Output: [1, 2] + + // Peek operation + System.out.println(stack.peek()); // Output: 2 + + // isEmpty operation + System.out.println(stack.isEmpty()); // Output: false + + // Size operation + System.out.println(stack.size()); // Output: 2 + + // Clear operation + stack.clear(); + System.out.println(stack); // Output: [] + } + } + ``` + + + + +## Queues in Data Structures and Algorithms + +A queue is a data structure that stores a collection of elements. The elements in a queue are stored in a First-In-First-Out (FIFO) order, which means that the first element added to the queue is the first one to be removed. Queues are used to store elements that need to be processed in a specific order, such as tasks in a job queue, messages in a message queue, or requests in a web server. + +A queue has two main operations: + +1. **Enqueue**: Adds an element to the back of the queue. +2. **Dequeue**: Removes and returns the element at the front of the queue. + +In addition to these operations, queues may also support other operations such as: + +- **Peek**: Returns the element at the front of the queue without removing it. +- **isEmpty**: Checks if the queue is empty. +- **Size**: Returns the number of elements in the queue. +- **Clear**: Removes all elements from the queue. +- **Search**: Searches for an element in the queue. +- **Copy**: Creates a copy of the queue. +- **Iterate**: Iterates over the elements of the queue. +- **Merge**: Merges two queues into one. +- **Reverse**: Reverses the order of elements in the queue. +- **Sort**: Sorts the elements of the queue. +- **Map**: Applies a function to each element of the queue. + +Here is an example of a queue in some programming languages: + + + + ```javascript + // Creating a queue in JavaScript + class Queue { + constructor() { + this.items = []; + } + + // Enqueue operation + enqueue(element) { + this.items.push(element); + } + + // Dequeue operation + dequeue() { + if (this.isEmpty()) { + return "Underflow"; + } + return this.items.shift(); + } + + // Peek operation + peek() { + return this.items[0]; + } + + // isEmpty operation + isEmpty() { + return this.items.length === 0; + } + + // Size operation + size() { + return this.items.length; + } + + // Clear operation + clear() { + this.items = []; + } + + // Print operation + print() { + console.log(this.items); + } + } + + // Using the queue + let queue = new Queue(); + queue.enqueue(1); + queue.enqueue(2); + queue.enqueue(3); + queue.print(); // Output: [1, 2, 3] + queue.dequeue(); + queue.print(); // Output: [2, 3] + console.log(queue.peek()); // Output: 2 + console.log(queue.isEmpty()); // Output: false + console.log(queue.size()); // Output: 2 + queue.clear(); + queue.print(); // Output: [] + ``` + + + + ```python + # Creating a queue in Python + class Queue: + def __init__(self): + self.items = [] + + # Enqueue operation + def enqueue(self, element): + self.items.append(element) + + # Dequeue operation + def dequeue(self): + if self.is_empty(): + return "Underflow" + return self.items.pop(0) + + # Peek operation + def peek(self): + return self.items[0] + + # isEmpty operation + def is_empty(self): + return len(self.items) == 0 + + # Size operation + def size(self): + return len(self.items) + + # Clear operation + def clear(self): + self.items = [] + + # Print operation + def print(self): + print(self.items) + + # Using the queue + queue = Queue() + queue.enqueue(1) + queue.enqueue + queue.enqueue(2) + queue.enqueue(3) + queue.print() # Output: [1, 2, 3] + queue.dequeue() + queue.print() # Output: [2, 3] + print(queue.peek()) # Output: 2 + print(queue.is_empty()) # Output: False + print(queue.size()) # Output: 2 + queue.clear() + queue.print() # Output: [] + ``` + + + + ```typescript + // Creating a queue in TypeScript + class Queue { + private items: T[] = []; + + // Enqueue operation + enqueue(element: T): void { + this.items.push(element); + } + + // Dequeue operation + dequeue(): T | string { + if (this.isEmpty()) { + return "Underflow"; + } + return this.items.shift(); + } + + // Peek operation + peek(): T | undefined { + return this.items[0]; + } + + // isEmpty operation + isEmpty(): boolean { + return this.items.length === 0; + } + + // Size operation + size(): number { + return this.items.length; + } + + // Clear operation + clear(): void { + this.items = []; + } + + // Print operation + print(): void { + console.log(this.items); + } + } + + // Using the queue + let queue = new Queue(); + queue.enqueue(1); + queue.enqueue(2); + queue.enqueue(3); + queue.print(); // Output: [1, 2, 3] + queue.dequeue(); + queue.print(); // Output: [2, 3] + console.log(queue.peek()); // Output: 2 + console.log(queue.isEmpty()); // Output: false + console.log(queue.size()); // Output: 2 + queue.clear(); + queue.print(); // Output: [] + ``` + + + + ```cpp + #include + #include + using namespace std; + + // Creating a queue in C++ + template + class Queue { + private: + vector items; + + public: + // Enqueue operation + void enqueue(T element) { + items.push_back(element); + } + + // Dequeue operation + T dequeue() { + if (isEmpty()) { + throw underflow_error("Underflow"); + } + T element = items.front(); + items.erase(items.begin()); + return element; + } + + // Peek operation + T peek() { + if (isEmpty()) { + throw underflow_error("Queue is empty"); + } + return items.front(); + } + + // isEmpty operation + bool isEmpty() { + return items.empty(); + } + + // Size operation + int size() { + return items.size(); + } + + // Clear operation + void clear() { + items.clear(); + } + + // Print operation + void print() { + for (T element : items) { + cout << element << " "; + } + cout << endl; + } + }; + + int main() { + Queue queue; + queue.enqueue(1); + queue.enqueue(2); + queue.enqueue(3); + queue.print(); // Output: 1 2 3 + queue.dequeue(); + queue.print(); // Output: 2 3 + cout << queue.peek() << endl; // Output: 2 + cout << queue.isEmpty() << endl; // Output: 0 + cout << queue.size() << endl; // Output: 2 + queue.clear(); + queue.print(); // Output: + + return 0; + } + ``` + + + + ```java + import java.util.LinkedList; + import java.util.Queue; + + public class Main { + public static void main(String[] args) { + // Creating a queue in Java + Queue queue = new LinkedList<>(); + + // Enqueue operation + queue.add(1); + queue.add(2); + queue.add(3); + + // Print operation + System.out.println(queue); // Output: [1, 2, 3] + + // Dequeue operation + queue.poll(); + System.out.println(queue); // Output: [2, 3] + + // Peek operation + System.out.println(queue.peek()); // Output: 2 + + // isEmpty operation + System.out.println(queue.isEmpty()); // Output: false + + // Size operation + System.out.println(queue.size()); // Output: 2 + + // Clear operation + queue.clear(); + System.out.println(queue); // Output: [] + } + } + ``` + + + + +## Differences Between Stacks and Queues + +Stacks and queues are both data structures that store a collection of elements, but they differ in how the elements are accessed and removed. The main differences between stacks and queues are: + +| No. | Feature | Stack | Queue | +| --- | :----------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| 1. | Access Order | Elements are accessed in a Last-In-First-Out (LIFO) order. | Elements are accessed in a First-In-First-Out (FIFO) order. | +| 2. | Insertion | Elements are inserted and removed from the top of the stack. | Elements are inserted at the back and removed from the front of the queue. | +| 3. | Removal | The last element added to the stack is the first one to be removed. | The first element added to the queue is the first one to be removed. | +| 4. | Operations | Stacks support push, pop, peek, isEmpty, size, clear, and other operations. | Queues support enqueue, dequeue, peek, isEmpty, size, clear, and other operations. | +| 5. | Applications | Stacks are used for undo operations, function calls, backtracking, and other applications. | Queues are used for job queues, message queues, web servers, and other applications. | + +:::tip for better understanding πŸ€“ + +## Live Example + +You can try running the following code snippet to see the output of the examples provided above: + +```jsx live +function Example() { + // Stack class + class Stack { + constructor() { + this.items = []; + } + + push(element) { + this.items.push(element); + } + + pop() { + if (this.isEmpty()) { + return "Underflow"; + } + return this.items.pop(); + } + + peek() { + return this.items[this.items.length - 1]; + } + + isEmpty() { + return this.items.length === 0; + } + + size() { + return this.items.length; + } + + clear() { + this.items = []; + } + + print() { + return this.items.join(" "); + } + } + + // Queue class + class Queue { + constructor() { + this.items = []; + } + + enqueue(element) { + this.items.push(element); + } + + dequeue() { + if (this.isEmpty()) { + return "Underflow"; + } + return this.items.shift(); + } + + peek() { + return this.items[0]; + } + + isEmpty() { + return this.items.length === 0; + } + + size() { + return this.items.length; + } + + clear() { + this.items = []; + } + + print() { + return this.items.join(" "); + } + } + + // Creating a stack + let stack = new Stack(); + + // Creating a queue + let queue = new Queue(); + + return ( +
+
+

Stack Example

+
+

Using the stack:

+

{stack.push(1)}

+

{stack.push(2)}

+

{stack.push(3)}

+

{stack.print()}

+

{stack.pop()}

+

{stack.print()}

+

{stack.peek()}

+

{stack.isEmpty().toString()}

+

{stack.size()}

+

{stack.clear()}

+

{stack.print()}

+
+
+ +
+

Queue Example

+
+

Using the queue:

+

{queue.enqueue(1)}

+

{queue.enqueue(2)}

+

{queue.enqueue(3)}

+

{queue.print()}

+

{queue.dequeue()}

+

{queue.print()}

+

{queue.peek()}

+

{queue.isEmpty().toString()}

+

{queue.size()}

+

{queue.clear()}

+

{queue.print()}

+
+
+
+ ); +} +``` + +::: + +## Conclusion + +In this tutorial, we learned about stacks and queues in Data Structures and Algorithms. We discussed what stacks and queues are, how they are used, and how they are different from each other. We also saw examples of stacks and queues in JavaScript, Python, TypeScript, C++, and Java. diff --git a/docs/beginner/05-linked-lists.md b/docs/beginner/05-linked-lists.md new file mode 100644 index 0000000..a09d170 --- /dev/null +++ b/docs/beginner/05-linked-lists.md @@ -0,0 +1,433 @@ +--- +id: 05-linked-lists +title: Linked Lists in Data Structures +sidebar_label: Linked Lists +tags: + - dsa + - data-structures + - linked-lists + - beginner + - javascript + - python + - c++ + - java + - programming + - tutorial + - typescript +sidebar_position: 5 +--- + +In this tutorial, we will learn about linked lists in Data Structures and Algorithms. We will discuss what linked lists are, how they are used, and how they are different from arrays. + +## Linked Lists in Programming + +A linked list is a data structure that consists of a sequence of elements, where each element points to the next element in the sequence. Each element in a linked list is called a node, and it contains two parts: the data and a reference (or pointer) to the next node in the sequence. + +Linked lists are dynamic data structures, which means that the size of a linked list can change during the execution of a program. Unlike arrays, linked lists do not have a fixed size, and elements can be added or removed from a linked list at any time. + +Linked lists are used to store a collection of elements that are related to each other in some way. For example, a linked list can be used to store the nodes of a graph, the tasks in a to-do list, or the songs in a playlist. + +Here is an example of a linked list in some programming languages: + + + + ```javascript + // Creating a linked list in JavaScript + class Node { + constructor(data) { + this.data = data; + this.next = null; + } + } + + class LinkedList { + constructor() { + this.head = null; + } + + addNode(data) { + const newNode = new Node(data); + + if (this.head === null) { + this.head = newNode; + } else { + let current = this.head; + while (current.next !== null) { + current = current.next; + } + current.next = newNode; + } + } + + printList() { + let current = this.head; + while (current !== null) { + console.log(current.data); + current = current.next; + } + } + } + + // Creating a linked list + const linkedList = new LinkedList(); + linkedList.addNode(1); + linkedList.addNode(2); + linkedList.addNode(3); + + // Printing the linked list + linkedList.printList(); + ``` + + + ```python + # Creating a linked list in Python + class Node: + def __init__(self, data): + self.data = data + self.next = None + + class LinkedList: + def __init__(self): + self.head = None + + def add_node(self, data): + new_node = Node(data) + + if self.head is None: + self.head = new_node + else: + current = self.head + while current.next is not None: + current = current.next + current.next = new_node + + def print_list(self): + current = self.head + while current is not None: + print(current.data) + current = current.next + + # Creating a linked list + linked_list = LinkedList() + linked_list.add_node(1) + linked_list.add_node(2) + linked_list.add_node(3) + + # Printing the linked list + linked_list.print_list() + ``` + + + ```typescript + // Creating a linked list in TypeScript + class Node { + data: number; + next: Node | null; + + constructor(data: number) { + this.data = data; + this.next = null; + } + } + + class LinkedList { + head: Node | null; + + constructor() { + this.head = null; + } + + addNode(data: number) { + const newNode = new Node(data); + + if (this.head === null) { + this.head = newNode; + } else { + let current = this.head; + while (current.next !== null) { + current = current.next; + } + current.next = newNode; + } + } + + printList() { + let current = this.head; + while (current !== null) { + console.log(current.data); + current = current.next; + } + } + } + + // Creating a linked list + const linkedList = new LinkedList(); + linkedList.addNode(1); + linkedList.addNode(2); + linkedList.addNode(3); + + // Printing the linked list + linkedList.printList(); + ``` + + + ```cpp + #include + using namespace std; + + // Creating a linked list in C++ + class Node { + public: + int data; + Node* next; + + Node(int data) { + this->data = data; + this->next = nullptr; + } + }; + + class LinkedList { + public: + Node* head; + + LinkedList() { + this->head = nullptr; + } + + void addNode(int data) { + Node* newNode = new Node(data); + + if (this->head == nullptr) { + this->head = newNode; + } else { + Node* current = this->head; + while (current->next != nullptr) { + current = current->next; + } + current->next = newNode; + } + } + + void printList() { + Node* current = this->head; + while (current != nullptr) { + cout << current->data << endl; + current = current->next; + } + } + }; + + int main() { + // Creating a linked list + LinkedList linkedList; + linkedList.addNode(1); + linkedList.addNode(2); + linkedList.addNode(3); + + // Printing the linked list + linkedList.printList(); + + return 0; + } + ``` + + + ```java + // Creating a linked list in Java + class Node { + int data; + Node next; + + Node(int data) { + this.data = data; + this.next = null; + } + } + + class LinkedList { + Node head; + + LinkedList() { + this.head = null; + } + + void addNode(int data) { + Node newNode = new Node(data); + + if (this.head == null) { + this.head = newNode; + } else { + Node current = this.head; + while (current.next != null) { + current = current.next; + } + current.next = newNode; + } + } + + void printList() { + Node current = this.head; + while (current != null) { + System.out.println(current.data); + current = current.next; + } + } + } + + public class Main { + public static void main(String[] args) { + // Creating a linked list + LinkedList linkedList = new LinkedList(); + linkedList.addNode(1); + linkedList.addNode(2); + linkedList.addNode(3); + + // Printing the linked list + linkedList.printList(); + } + } + ``` + + + +In the example above, we have created a linked list in JavaScript, Python, TypeScript, C++, and Java. We have defined a `Node` class to represent a node in the linked list and a `LinkedList` class to represent the linked list itself. We have implemented methods to add nodes to the linked list and print the elements of the linked list. + +## Types of Linked Lists + +There are several types of linked lists, each with its own characteristics and use cases. Some common types of linked lists include: + +1. **Singly Linked List**: In a singly linked list, each node points to the next node in the sequence. The last node in the list points to `null`, indicating the end of the list. +2. **Doubly Linked List**: In a doubly linked list, each node points to both the next node and the previous node in the sequence. This allows for bidirectional traversal of the list. +3. **Circular Linked List**: In a circular linked list, the last node in the list points back to the first node, forming a circular structure. This allows for efficient traversal of the list without the need to check for `null` pointers. +4. **Sorted Linked List**: In a sorted linked list, the nodes are arranged in ascending or descending order based on the value of the data in each node. This allows for efficient searching and insertion of elements in the list. +5. **Sparse Linked List**: In a sparse linked list, the nodes only store non-default values, reducing the memory usage of the list. This is useful for representing sparse data structures, such as matrices. +6. **Circular Doubly Linked List**: In a circular doubly linked list, each node points to both the next node and the previous node, and the last node points back to the first node, forming a circular structure. This allows for bidirectional traversal of the list without the need to check for `null` pointers. +7. **Self-organizing Linked List**: In a self-organizing linked list, the order of the nodes is adjusted based on the frequency of access to each node. This allows for faster access to frequently accessed nodes. + +Each type of linked list has its own advantages and disadvantages, and the choice of which type to use depends on the specific requirements of the application. + +:::tip for better understanding πŸ€“ + +## Live Example + +Let's create a singly linked list in jsx using JavaScript. We will define a `Node` class to represent a node in the linked list and a `LinkedList` class to represent the linked list itself. We will implement methods to add nodes to the linked list and print the elements of the linked list. + +```jsx live +function Example() { + // Node class for the linked list + class Node { + constructor(data) { + this.data = data; + this.next = null; + } + } + + // LinkedList class + class LinkedList { + constructor() { + this.head = null; + } + + // Inserting a new node at the end of the linked list + append(data) { + let newNode = new Node(data); + if (!this.head) { + this.head = newNode; + return; + } + let current = this.head; + while (current.next) { + current = current.next; + } + current.next = newNode; + } + + // Inserting a new node at the beginning of the linked list + prepend(data) { + let newNode = new Node(data); + newNode.next = this.head; + this.head = newNode; + } + + // Deleting a node by its value + delete(data) { + if (!this.head) return; + + if (this.head.data === data) { + this.head = this.head.next; + return; + } + + let current = this.head; + while (current.next) { + if (current.next.data === data) { + current.next = current.next.next; + return; + } + current = current.next; + } + } + + // Printing the linked list + print() { + let current = this.head; + let result = []; + while (current) { + result.push(current.data); + current = current.next; + } + return result.join(' -> '); + } + } + + // Creating a linked list + let linkedList = new LinkedList(); + + // Inserting elements into the linked list + linkedList.append(1); + linkedList.append(2); + linkedList.append(3); + linkedList.prepend(0); + + return ( +
+
+

Linked List Example

+
+

Linked List: {linkedList.print()}

+

Deleting 2...

+ {linkedList.delete(2)} +

Updated Linked List: {linkedList.print()}

+
+
+
+ ); +} +``` + +In the above example, we have created a singly linked list in JavaScript. We have defined a `Node` class to represent a node in the linked list and a `LinkedList` class to represent the linked list itself. We have implemented methods to add nodes to the linked list, print the elements of the linked list, prepend a node at the beginning of the list, and delete a node by its value. + +::: + +## Conclusion + +In this tutorial, we have learned about linked lists in Data Structures and Algorithms. We have discussed what linked lists are, how they are used, and how they are different from arrays. We have also explored the different types of linked lists and their characteristics. \ No newline at end of file diff --git a/docs/beginner/06-deque.md b/docs/beginner/06-deque.md new file mode 100644 index 0000000..1e08ce3 --- /dev/null +++ b/docs/beginner/06-deque.md @@ -0,0 +1,289 @@ +--- +id: 06-deque +title: Deque in Data Structures and Algorithms +sidebar_label: Deque +tags: + - dsa + - data-structures + - deque + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial + - typescript +sidebar_position: 5 +--- + +In this tutorial, we will delve into deque (double-ended queue) in Data Structures and Algorithms. We'll explore what deque is, how it's used, and its implementation in various programming languages. + + +A deque, short for double-ended queue, is a versatile data structure that allows insertion and deletion of elements from both ends. This makes it suitable for scenarios requiring efficient manipulation at both the front and back, such as implementing a queue where elements need to be added and removed from both ends. + +A deque supports the following operations: + +1. **Insertion at Front**: Adds an element to the front of the deque. +2. **Insertion at Back**: Adds an element to the back of the deque. +3. **Deletion at Front**: Removes and returns the element at the front of the deque. +4. **Deletion at Back**: Removes and returns the element at the back of the deque. +5. **Peek at Front**: Returns the element at the front of the deque without removing it. +6. **Peek at Back**: Returns the element at the back of the deque without removing it. +7. **isEmpty**: Checks if the deque is empty. +8. **Size**: Returns the number of elements in the deque. +9. **Clear**: Removes all elements from the deque. + +Additionally, deques may support other operations such as searching, copying, iterating, merging, reversing, sorting, and mapping. + +![dequeue image](https://media.dev.to/cdn-cgi/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm7ak5h7mlz8ox6ut5dja.png) + +Here's an example of a deque in some programming languages: + + + + ```javascript + class Deque { + constructor() { + this.items = []; + } + + // Insertion at Front + addFront(element) { + this.items.unshift(element); + } + + // Insertion at Back + addBack(element) { + this.items.push(element); + } + + // Deletion at Front + removeFront() { + if (this.isEmpty()) { + return "Underflow"; + } + return this.items.shift(); + } + + // Deletion at Back + removeBack() { + if (this.isEmpty()) { + return "Underflow"; + } + return this.items.pop(); + } + + // Peek at Front + peekFront() { + return this.items[0]; + } + + // Peek at Back + peekBack() { + return this.items[this.items.length - 1]; + } + + // isEmpty operation + isEmpty() { + return this.items.length === 0; + } + + // Size operation + size() { + return this.items.length; + } + + // Clear operation + clear() { + this.items = []; + } + + // Print operation + print() { + console.log(this.items); + } + } + + // Using the deque + let deque = new Deque(); + deque.addFront(1); + deque.addBack(2); + deque.addFront(3); + deque.print(); // Output: [3, 1, 2] + deque.removeFront(); + deque.print(); // Output: [1, 2] + console.log(deque.peekBack()); // Output: 2 + console.log(deque.isEmpty()); // Output: false + console.log(deque.size()); // Output: 2 + deque.clear(); + deque.print(); // Output: [] + ``` + + + + ```python + from collections import deque + + # Using the deque + deque = deque() + deque.appendleft(1) + deque.append(2) + deque.appendleft(3) + print(deque) # Output: deque([3, 1, 2]) + deque.popleft() + print(deque) # Output: deque([1, 2]) + print(deque[-1]) # Output: 2 + print(len(deque) == 0) # Output: False + print(len(deque)) # Output: 2 + deque.clear() + print(deque) # Output: deque([]) + ``` + + + + ```typescript + class Deque { + private items: T[] = []; + + // Insertion at Front + addFront(element: T): void { + this.items.unshift(element); + } + + // Insertion at Back + addBack(element: T): void { + this.items.push(element); + } + + // Deletion at Front + removeFront(): T | string { + if (this.isEmpty()) { + return "Underflow"; + } + return this.items.shift(); + } + + // Deletion at Back + removeBack(): T | string { + if (this.isEmpty()) { + return "Underflow"; + } + return this.items.pop(); + } + + // Peek at Front + peekFront(): T | undefined { + return this.items[0]; + } + + // Peek at Back + peekBack(): T | undefined { + return this.items[this.items.length - 1]; + } + + // isEmpty operation + isEmpty(): boolean { + return this.items.length === 0; + } + + // Size operation + size(): number { + return this.items.length; + } + + // Clear operation + clear(): void { + this.items = []; + } + + // Print operation + print(): void { + console.log(this.items); + } + } + + // Using the deque + let deque = new Deque(); + deque.addFront(1); + deque.addBack(2); + deque.addFront(3); + deque.print(); // Output: [3, 1, 2] + deque.removeFront(); + deque.print(); // Output: [1, 2] + console.log(deque.peekBack()); // Output: 2 + console.log(deque.isEmpty()); // Output: false + console.log(deque.size()); // Output: 2 + deque.clear(); + deque.print(); // Output: [] + ``` + + + + ```cpp + #include + #include + using namespace std; + + // Using the deque + deque deque; + deque.push_front(1); + deque.push_back(2); + deque.push_front(3); + for (int element : deque) { + cout << element << " "; + } + cout << endl; // Output: 3 1 2 + deque.pop_front(); + for (int element : deque) { + cout << element << " "; + } + cout << endl; // Output: 1 2 + cout <<```cpp + deque.back() << endl; // Output: 2 + cout << (deque.empty() ? "true" : "false") << endl; // Output: false + cout << deque.size() << endl; // Output: 2 + deque.clear(); + for (int element : deque) { + cout << element << " "; + } + cout << endl; // Output: + ``` + + + + ```java + import java.util.ArrayDeque; + import java.util.Deque; + + public class Main { + public static void main(String[] args) { + // Creating a deque in Java + Deque deque = new ArrayDeque<>(); + + // Using the deque + deque.addFirst(1); + deque.addLast(2); + deque.addFirst(3); + System.out.println(deque); // Output: [3, 1, 2] + deque.removeFirst(); + System.out.println(deque); // Output: [1, 2] + System.out.println(deque.peekLast()); // Output: 2 + System.out.println(deque.isEmpty()); // Output: false + System.out.println(deque.size()); // Output: 2 + deque.clear(); + System.out.println(deque); // Output: [] + } + } + ``` + + + + +## Conclusion + +In this tutorial, we explored deque (double-ended queue) in Data Structures and Algorithms. We discussed its features, operations, and provided implementations in JavaScript, Python, TypeScript, C++, and Java. Deque is a powerful data structure that offers efficient insertion and deletion at both ends, making it suitable for various applications where elements need to be manipulated dynamically. + +Now, armed with the knowledge of deque, you can enhance your understanding of data structures and algorithms and apply them to solve complex problems effectively. + +This tutorial provides a detailed overview of deque, including its operations and implementations in different programming languages. It should serve as a valuable resource for anyone looking to understand and utilize deque in their projects. \ No newline at end of file diff --git a/docs/beginner/06-graphs.md b/docs/beginner/06-graphs.md new file mode 100644 index 0000000..090f2d1 --- /dev/null +++ b/docs/beginner/06-graphs.md @@ -0,0 +1,514 @@ +--- +id: 06-graphs +title: Graphs +sidebar_label: Graphs +tags: + - dsa + - data-structures + - graphs + - beginner + - javascript + - python + - c++ + - java + - programming + - tutorial + - typescript +sidebar_position: 6 +--- + +In this tutorial, we will learn about graphs in Data Structures and Algorithms. We will discuss what graphs are, how they are used, and why they are important. + +## Graphs in Programming + +Graph Data Structure is a collection of nodes connected by edges. It’s used to represent relationships between different entities. Graph algorithms are methods used to manipulate and analyze graphs, solving various problems like finding the shortest path or detecting cycles. + +Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is denoted by G(V, E). + +## Components of a Graph + +- Vertices: Vertices are the fundamental units of the graph. Sometimes, vertices are also known as vertex or nodes. Every node/vertex can be labeled or unlabeled. +- Edges: Edges are drawn or used to connect two nodes of the graph. It can be ordered pair of nodes in a directed graph. Edges can connect any two nodes in any possible way. There are no rules. Sometimes, edges are also known as arcs. Every edge can be labelled/unlabelled. + +## Graph Representation + +### Adjacency Matrix Graph Representation + +The Adjacency Matrix is a 2D array (matrix) where each cell on index (i,j) stores information about the edge from vertex i to vertex j. + +Below is a Graph with the Adjacency Matrix representation next to it. + +![Adj Matrix](./images/graphs1.png) + +The adjacency matrix above represents an undirected Graph, so the values '1' only tells us where the edges are. Also, the values in the adjacency matrix is symmetrical because the edges go both ways (undirected Graph). + +To create a directed Graph with an adjacency matrix, we must decide which vertices the edges go from and to, by inserting the value at the correct indexes (i,j). To represent a weighted Graph we can put other values than '1' inside the adjacency matrix. + +Below is a directed and weighted Graph with the Adjacency Matrix representation next to it. + +![Adj Matrix](./images/graphs2.png) + +In the adjacency matrix above, the value 3 on index (0,1) tells us there is an edge from vertex A to vertex B, and the weight for that edge is 3. + +As you can see, the weights are placed directly into the adjacency matrix for the correct edge, and for a directed Graph, the adjacency matrix does not have to be symmetric. + +### Adjacency List Graph Representation + +In case we have a 'sparse' Graph with many vertices, we can save space by using an Adjacency List compared to using an Adjacency Matrix, because an Adjacency Matrix would reserve a lot of memory on empty Array elements for edges that don't exist. + +A 'sparse' Graph is a Graph where each vertex only has edges to a small portion of the other vertices in the Graph. + +An Adjacency List has an array that contains all the vertices in the Graph, and each vertex has a Linked List (or Array) with the vertex's edges. + +![Adj List](./images/graphs3.png) + +In the adjacency list above, the vertices A to D are placed in an Array, and each vertex in the array has its index written right next to it. + +Each vertex in the Array has a pointer to a Linked List that represents that vertex's edges. More specifically, the Linked List contains the indexes to the adjacent (neighbor) vertices. + +So for example, vertex A has a link to a Linked List with values 3, 1, and 2. These values are the indexes to A's adjacent vertices D, B, and C. + +An Adjacency List can also represent a directed and weighted Graph, like this: + +![Adj List](./images/graphs4.png) + +In the Adjacency List above, vertices are stored in an Array. Each vertex has a pointer to a Linked List with edges stored as i,w, where i is the index of the vertex the edge goes to, and w is the weight of that edge. + +Node D for example, has a pointer to a Linked List with an edge to vertex A. The values 0,4 means that vertex D has an edge to vertex on index 0 (vertex A), and the weight of that edge is 4. + + +Here is an example of a basic graph in some programming languages: + + + + ```javascript + class Graph { + constructor(size) { + this.size = size; + this.adjMatrix = Array.from({ length: size }, () => Array(size).fill(0)); + this.vertexData = Array(size).fill(''); + } + + addEdge(u, v) { + if (u >= 0 && u < this.size && v >= 0 && v < this.size) { + this.adjMatrix[u][v] = 1; + this.adjMatrix[v][u] = 1; + } + } + + addVertexData(vertex, data) { + if (vertex >= 0 && vertex < this.size) { + this.vertexData[vertex] = data; + } + } + + printGraph() { + console.log("Adjacency Matrix:"); + for (let i = 0; i < this.size; i++) { + console.log(this.adjMatrix[i].join(' ')); + } + + console.log("\nVertex Data:"); + for (let i = 0; i < this.size; i++) { + console.log(`Vertex ${i}: ${this.vertexData[i]}`); + } + } +} + +// Example usage: +const g = new Graph(4); +g.addVertexData(0, 'A'); +g.addVertexData(1, 'B'); +g.addVertexData(2, 'C'); +g.addVertexData(3, 'D'); +g.addEdge(0, 1); // A - B +g.addEdge(0, 2); // A - C +g.addEdge(0, 3); // A - D +g.addEdge(1, 2); // B - C + +g.printGraph(); + ``` + + + ```python + class Graph: + def __init__(self, size): + self.adj_matrix = [[0] * size for _ in range(size)] + self.size = size + self.vertex_data = [''] * size + + def add_edge(self, u, v): + if 0 <= u < self.size and 0 <= v < self.size: + self.adj_matrix[u][v] = 1 + self.adj_matrix[v][u] = 1 + + def add_vertex_data(self, vertex, data): + if 0 <= vertex < self.size: + self.vertex_data[vertex] = data + + def print_graph(self): + print("Adjacency Matrix:") + for row in self.adj_matrix: + print(' '.join(map(str, row))) + print("\nVertex Data:") + for vertex, data in enumerate(self.vertex_data): + print(f"Vertex {vertex}: {data}") + + g = Graph(4) + g.add_vertex_data(0, 'A') + g.add_vertex_data(1, 'B') + g.add_vertex_data(2, 'C') + g.add_vertex_data(3, 'D') + g.add_edge(0, 1) # A - B + g.add_edge(0, 2) # A - C + g.add_edge(0, 3) # A - D + g.add_edge(1, 2) # B - C + + g.print_graph() + ``` + + + ```typescript + class Graph { + private adjMatrix: number[][]; + private vertexData: string[]; + private size: number; + + constructor(size: number) { + this.size = size; + this.adjMatrix = Array.from({ length: size }, () => Array(size).fill(0)); + this.vertexData = Array(size).fill(''); + } + + public addEdge(u: number, v: number): void { + if (u >= 0 && u < this.size && v >= 0 && v < this.size) { + this.adjMatrix[u][v] = 1; + this.adjMatrix[v][u] = 1; + } + } + + public addVertexData(vertex: number, data: string): void { + if (vertex >= 0 && vertex < this.size) { + this.vertexData[vertex] = data; + } + } + + public printGraph(): void { + console.log("Adjacency Matrix:"); + for (let i = 0; i < this.size; i++) { + console.log(this.adjMatrix[i].join(' ')); + } + + console.log("\nVertex Data:"); + for (let i = 0; i < this.size; i++) { + console.log(`Vertex ${i}: ${this.vertexData[i]}`); + } + } +} + +// Example usage: +const g = new Graph(4); +g.addVertexData(0, 'A'); +g.addVertexData(1, 'B'); +g.addVertexData(2, 'C'); +g.addVertexData(3, 'D'); +g.addEdge(0, 1); // A - B +g.addEdge(0, 2); // A - C +g.addEdge(0, 3); // A - D +g.addEdge(1, 2); // B - C + +g.printGraph(); + + ``` + + + ```cpp + #include +#include +#include + +class Graph { +private: + std::vector> adjMatrix; + std::vector vertexData; + int size; + +public: + Graph(int size) { + this->size = size; + adjMatrix.resize(size, std::vector(size, 0)); + vertexData.resize(size, ""); + } + + void addEdge(int u, int v) { + if (u >= 0 && u < size && v >= 0 && v < size) { + adjMatrix[u][v] = 1; + adjMatrix[v][u] = 1; + } + } + + void addVertexData(int vertex, const std::string& data) { + if (vertex >= 0 && vertex < size) { + vertexData[vertex] = data; + } + } + + void printGraph() { + std::cout << "Adjacency Matrix:" << std::endl; + for (int i = 0; i < size; ++i) { + for (int j = 0; j < size; ++j) { + std::cout << adjMatrix[i][j] << " "; + } + std::cout << std::endl; + } + + std::cout << "\nVertex Data:" << std::endl; + for (int i = 0; i < size; ++i) { + std::cout << "Vertex " << i << ": " << vertexData[i] << std::endl; + } + } +}; + +int main() { + Graph g(4); + g.addVertexData(0, "A"); + g.addVertexData(1, "B"); + g.addVertexData(2, "C"); + g.addVertexData(3, "D"); + g.addEdge(0, 1); // A - B + g.addEdge(0, 2); // A - C + g.addEdge(0, 3); // A - D + g.addEdge(1, 2); // B - C + + g.printGraph(); + return 0; +} + + ``` + + + ```java + class Graph { + private int[][] adjMatrix; + private int size; + private String[] vertexData; + + public Graph(int size) { + this.size = size; + this.adjMatrix = new int[size][size]; + this.vertexData = new String[size]; + for (int i = 0; i < size; i++) { + this.vertexData[i] = ""; + } + } + + public void addEdge(int u, int v) { + if (u >= 0 && u < size && v >= 0 && v < size) { + this.adjMatrix[u][v] = 1; + this.adjMatrix[v][u] = 1; + } + } + + public void addVertexData(int vertex, String data) { + if (vertex >= 0 && vertex < size) { + this.vertexData[vertex] = data; + } + } + + public void printGraph() { + System.out.println("Adjacency Matrix:"); + for (int i = 0; i < size; i++) { + for (int j = 0; j < size; j++) { + System.out.print(this.adjMatrix[i][j] + " "); + } + System.out.println(); + } + + System.out.println("\nVertex Data:"); + for (int i = 0; i < size; i++) { + System.out.println("Vertex " + i + ": " + this.vertexData[i]); + } + } + + public static void main(String[] args) { + Graph g = new Graph(4); + g.addVertexData(0, "A"); + g.addVertexData(1, "B"); + g.addVertexData(2, "C"); + g.addVertexData(3, "D"); + g.addEdge(0, 1); // A - B + g.addEdge(0, 2); // A - C + g.addEdge(0, 3); // A - D + g.addEdge(1, 2); // B - C + + g.printGraph(); + } +} + + ``` + + + +In the example above, we have created a graph in JavaScript, Python, TypeScript, C++, and Java. We have defined a `Graph` class to represent a vertex and its associated edge in the graph. We have implemented methods to add these to the graph and print the elements of it. + +## Types of Graph + +There are several types of graphs, each with its own characteristics and use cases. Some common types of these include: + +1. **Null Graph**: A graph is known as a null graph if there are no edges in the graph.. +2. **Trivial Graph**: Graph having only a single vertex, it is also the smallest graph possible. . +3. **Undirected Graph**: A graph in which edges do not have any direction. That is the nodes are unordered pairs in the definition of every edge. +4. **Directed Graph**: A graph in which edge has direction. That is the nodes are ordered pairs in the definition of every edge. +5. **Connected Graph**: The graph in which from one node we can visit any other node in the graph is known as a connected graph. +6. **Disconnected Graph**: The graph in which at least one node is not reachable from a node is known as a disconnected graph. +7. **Regular Graph**: The graph in which the degree of every vertex is equal to K is called K regular graph. +8. **Complete Graph**: The graph in which from each node there is an edge to each other node. + + +:::tip for better understanding πŸ€“ + +## Live Example + +Let's create a graph in jsx using JavaScript. We will define a `Graph` class to represent a adjacnecy list in the graph. We will implement methods to add vertices and edges to the list and print the elements of it. + +```jsx live + function GraphExample() { + // Graph class + class Graph { + constructor() { + this.adjacencyList = {}; + } + + // Add a vertex to the graph + addVertex(vertex) { + if (!this.adjacencyList[vertex]) { + this.adjacencyList[vertex] = []; + } + } + + // Add an edge between two vertices + addEdge(vertex1, vertex2) { + if (this.adjacencyList[vertex1] && this.adjacencyList[vertex2]) { + this.adjacencyList[vertex1].push(vertex2); + this.adjacencyList[vertex2].push(vertex1); + } + } + + // Remove an edge between two vertices + removeEdge(vertex1, vertex2) { + this.adjacencyList[vertex1] = this.adjacencyList[vertex1].filter( + v => v !== vertex2 + ); + this.adjacencyList[vertex2] = this.adjacencyList[vertex2].filter( + v => v !== vertex1 + ); + } + + // Remove a vertex and all connected edges + removeVertex(vertex) { + while (this.adjacencyList[vertex].length) { + const adjacentVertex = this.adjacencyList[vertex].pop(); + this.removeEdge(vertex, adjacentVertex); + } + delete this.adjacencyList[vertex]; + } + + // Print the adjacency list of the graph + printGraph() { + let result = []; + for (let vertex in this.adjacencyList) { + result.push(`${vertex} -> ${this.adjacencyList[vertex].join(", ")}`); + } + return result.join(' | '); + } + } + + // Creating a graph + let graph = new Graph(); + + // Adding vertices + graph.addVertex('A'); + graph.addVertex('B'); + graph.addVertex('C'); + graph.addVertex('D'); + + // Adding edges + graph.addEdge('A', 'B'); + graph.addEdge('A', 'C'); + graph.addEdge('B', 'D'); + graph.addEdge('C', 'D'); + + // Graph before removing an edge + const graphBefore = graph.printGraph(); + + // Removing an edge + graph.removeEdge('A', 'B'); + + // Graph after removing an edge + const graphAfterRemovingEdge = graph.printGraph(); + + // Removing a vertex + graph.removeVertex('D'); + + // Graph after removing a vertex + const graphAfterRemovingVertex = graph.printGraph(); + + return ( +
+
+

Graph Example

+
+

Graph: {graphBefore}

+

Deleting edge A-B...

+

Updated Graph: {graphAfterRemovingEdge}

+

Deleting vertex D...

+

Updated Graph: {graphAfterRemovingVertex}

+
+
+
+ ); +} + +``` + +In the above example: +- A graph instance graph is created. +- Vertices A, B, C, and D are added. +- Edges are added between these vertices. +- The graph's adjacency list is printed. +- An edge is removed, and the updated graph is printed. +- A vertex is removed, and the updated graph is printed. + +::: + +## Applications + +- Graph data structures can be used to represent the interactions between players on a team, such as passes, shots, and tackles. Analyzing these interactions can provide insights into team dynamics and areas for improvement. +- Commonly used to represent social networks, such as networks of friends on social media. +- Graphs can be used to represent the topology of computer networks, such as the connections between routers and switches. +- Graphs are used to represent the connections between different places in a transportation network, such as roads and airports. +- Graphs are used in Neural Networks where vertices represent neurons and edges represent the synapses between them. Neural networks are used to understand how our brain works and how connections change when we learn. The human brain has about 10^11 neurons and close to 10^15 synapses. + +## Conclusion + +In this tutorial, we have learned about graphs in Data Structures and Algorithms. We have discussed what graphs are, how they are used, and why they are important. \ No newline at end of file diff --git a/docs/beginner/07-linked-list-implementation-in-Java.md b/docs/beginner/07-linked-list-implementation-in-Java.md new file mode 100644 index 0000000..eab505f --- /dev/null +++ b/docs/beginner/07-linked-list-implementation-in-Java.md @@ -0,0 +1,376 @@ +--- +id: 07-linked-lists-in-Java +title: Linked List implementation in Java +sidebar_label: Linked Lists in Java +tags: + - dsa + - data-structures + - linked-lists + - beginner + - java + - programming + - tutorial +sidebar_position: 7 +--- + +## Introduction: +In this tutorial, we will learn how to implement Linked List data structure in Java without using built-in data structures. We will cover operations such as creation, insertion, deletion and display. + +## Arrays v/s Linked List +Why do we need linked list, even though we can use arrays? + +- Arrays are contiguous in memory (elements are stored sequentially) whereas linked lists are not. +- Arrays are static data structure i.e. they have a fixed size. Linked lists, on the other hand are dynamic in nature; they can grow and shrink, making them memory efficient. +- Arrays are preffered for operations such as searching as they allow direct access to elements. +- Linked list are preffered for operations like insertion and deletion and when memory is a concern. + +## Uses of Linked List +- Music playlist. +- Web Browsers. +- For implementing other data structures. + +## Implementation: + +Now, we'll implement a singly linked list in Java from scratch.
You may wonder, why should we implement it from scratch instead of using the in built data structure? Well,this way we can customise the data structure! We can add new operations to suit our specific requirements.It also helps us to develop a deeper understanding of how the data structure works. + +## **Code:** + +```java +package ll; +import java.util.*; + +class node{ + +int data; +node next; + +node(int data){ +this.data=data; +next=null; +} +} + +class linkedlist{ + Scanner sc=new Scanner(System.in); + node head; + node ptr; + + linkedlist(){ + //initially linked list is null + head=null; + } + + public void add_nodes() { + //adds 'n' number of nodes + int flag=0; + do{ + System.out.println("Enter data: "); + int data=sc.nextInt(); + node newnode=new node(data); + if(head==null) { + head=newnode; + } + else { + ptr=head; + while(ptr.next!=null) { + ptr=ptr.next; + } + ptr.next=newnode; + } + int temp=0; + do { + System.out.println("Do you want to add another node?\n 1.Yes\n 2.No"); + int ans=sc.nextInt(); + if(ans!=1 && ans!=2) { + System.out.println("Enter valid option!"); + } + else { + if(ans==2) { + flag=1; + } + temp=1; + } + }while(temp==0); + }while(flag==0); + } + + public void display() { + //displays the content of linked list + if(head==null) { + System.out.println("Linked List is empty !"); + return; + } + ptr=head; + while(ptr!=null) { + if(ptr==head) { + System.out.print(ptr.data); + } + else { + System.out.print(" -> "+ptr.data); + } + ptr=ptr.next; + } + + } + + int calculate_length() { + //returns length of linked list + int count=0; + if(head==null) { + return count; + } + ptr=head; + while(ptr!=null) { + ptr=ptr.next; + count++; + } + return count; + } + + + public void insert() { + //accept data for new node + System.out.println("Enter data: "); + int data=sc.nextInt(); + node newnode=new node(data); + + //accept position to insert new node + System.out.println("Enter position to insert the new node:"); + int pos=sc.nextInt(); + int len=calculate_length(); + if(pos<1 || pos>(len+1)) { + //negative index or position greater that size of linked list + //if pos==(len+1), attach to end of linkedlist + System.out.println("Cannot insert at position "+pos); + return; + } + + if(head==null && pos==1) { + //1st node + head=newnode; + System.out.println("Inserted node sucessfully!"); + return; + } + + if(pos==(len+1)) { + //insert at last node + ptr=head; + while(ptr.next!=null) { + ptr=ptr.next; + } + ptr.next=newnode; + System.out.println("Inserted node sucessfully!"); + return; + } + + ptr=head; + node prev=ptr; + for(int i=1;i 2 -> 3 +Enter option: + 1.Add nodes + 2.Display Linked List + 3.Insert node + 4.Delete node + 5.Exit +3 +Enter data: +5 +Enter position to insert the new node: +4 +Inserted node sucessfully! + +Enter option: + 1.Add nodes + 2.Display Linked List + 3.Insert node + 4.Delete node + 5.Exit +3 +Enter data: +4 +Enter position to insert the new node: +4 +Inserted node sucessfully! + +Enter option: + 1.Add nodes + 2.Display Linked List + 3.Insert node + 4.Delete node + 5.Exit +2 +1 -> 2 -> 3 -> 4 -> 5 +Enter option: + 1.Add nodes + 2.Display Linked List + 3.Insert node + 4.Delete node + 5.Exit +4 +Enter data to be deleted +25 +Data not found! + +Enter option: + 1.Add nodes + 2.Display Linked List + 3.Insert node + 4.Delete node + 5.Exit +4 +Enter data to be deleted +4 +Deleted node successfully! + +Enter option: + 1.Add nodes + 2.Display Linked List + 3.Insert node + 4.Delete node + 5.Exit +2 +1 -> 2 -> 3 -> 5 +Enter option: + 1.Add nodes + 2.Display Linked List + 3.Insert node + 4.Delete node + 5.Exit +8 +Enter valid option! + +Enter option: + 1.Add nodes + 2.Display Linked List + 3.Insert node + 4.Delete node + 5.Exit +5 +``` +## Conclusion: +In this tutorial, we learnt about the use of the linked list data structure.We also learnt how to implement it from scratch in Java programming language and how doing so can be beneficial. + diff --git a/docs/beginner/Binary_Search.md b/docs/beginner/Binary_Search.md new file mode 100644 index 0000000..2a5a8e9 --- /dev/null +++ b/docs/beginner/Binary_Search.md @@ -0,0 +1,191 @@ +# Binary search + +Binary search is a classic algorithm for finding an element in a sorted array. It repeatedly divides the search interval in half and compares the middle element of the interval to the target value. If the target value matches the middle element, the search is successful. Otherwise, the search continues in the half of the array that may contain the target value. + +### Why is Binary Search preferred over Linear Search? + +1. **Time Complexity**: + - **Binary Search**: O(log n) + - **Linear Search**: O(n) + + Binary search divides the search space in half each time, making it much faster for large datasets. + +2. **Efficiency with Large Datasets**: + - Binary search is efficient for large datasets, requiring around 20 comparisons for a million elements. + - Linear search would require, on average, 500,000 comparisons for the same dataset. + +3. **Data Requirements**: + - **Binary Search**: Requires sorted data. + - **Linear Search**: Works with unsorted data but is slower for large datasets. + +4. **Predictability**: + - Binary search offers consistent performance. + - Linear search performance varies based on the target element's position. + +5. **Use Cases**: + - **Binary Search**: Ideal for static, sorted data with frequent searches (e.g., database indexing, dictionary lookups). + - **Linear Search**: Suitable for small datasets or frequently changing data where sorting is impractical. + +### Algorithm + +1. **Sort**: Ensure the array is sorted in ascending order. +2. **Initialize**: Set two pointers, `low` and `high`, to the beginning and end of the array, respectively. +3. **Iterate**: While `low` is less than or equal to `high`: + - Calculate the middle index: `mid = (low + high) / 2`. + - Compare the middle element with the target value. + - If the middle element is the target, return the index. + - If the middle element is greater than the target, search the left half by setting `high = mid - 1`. + - If the middle element is less than the target, search the right half by setting `low = mid + 1`. +4. **End**: If the target is not found, return an indication (e.g., `-1`). + +### Explanation + +#### Recursive Approach + +```python +def binary_search_recursive(arr, low, high, target): + if low > high: + return -1 # Target not found + + mid = (low + high) // 2 + + if arr[mid] == target: + return mid + elif arr[mid] > target: + return binary_search_recursive(arr, low, mid - 1, target) + else: + return binary_search_recursive(arr, mid + 1, high, target) +``` + +#### Iterative Approach + +```python +def binary_search_iterative(arr, target): + low = 0 + high = len(arr) - 1 + + while low <= high: + mid = (low + high) // 2 + + if arr[mid] == target: + return mid + elif arr[mid] > target: + high = mid - 1 + else: + low = mid + 1 + + return -1 # Target not found +``` + +### Time Complexity Analysis + +1. **Recurrence Relation**: + - Each step of the algorithm reduces the search space by half. + - If `T(n)` is the time complexity for an array of size `n`, then: + `T(n) = T(n/2) + O(1)`. + +2. **Master's Theorem**: + - The recurrence relation `T(n) = T(n/2) + O(1)` fits the form `T(n) = aT(n/b) + f(n)`, where `a = 1`, `b = 2`, and `f(n) = O(1)`. + - According to Master's Theorem: + `T(n) = O(\log n)` + +3. **Substitution Method**: + - Assume `T(n) = O(\log n)`. + - Substitute into the recurrence relation: + ` T(n) = T(n/2) + O(1) = O(\log n) + O(1) = O(\log n)` + +### Space Complexity + +- The space complexity for the iterative approach is `O(1)` since it uses a constant amount of extra space. +- The space complexity for the recursive approach is `O(\log n)` due to the recursive call stack. + +### Applications + +- **Searching in a Sorted Array**: Efficiently find an element in a sorted array. +- **Database Indexing**: Quickly locate records in a sorted database. +- **Debugging**: Find the source of an error in a range of code or data. + +### Illustration + +#### Initial State + +``` +Array: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] +Target: 7 +low = 0, high = 9 +``` + +#### Step 1 + +``` +mid = (0 + 9) // 2 = 4 +Array[mid] = 9 +9 > 7, so high = mid - 1 = 3 +``` + +#### Step 2 + +``` +low = 0, high = 3 +mid = (0 + 3) // 2 = 1 +Array[mid] = 3 +3 < 7, so low = mid + 1 = 2 +``` + +#### Step 3 + +``` +low = 2, high = 3 +mid = (2 + 3) // 2 = 2 +Array[mid] = 5 +5 < 7, so low = mid + 1 = 3 +``` + +#### Step 4 + +``` +low = 3, high = 3 +mid = (3 + 3) // 2 = 3 +Array[mid] = 7 +7 == 7, target found at index 3 +``` + +### Pictorial Representation + +![Binary Search](https://upload.wikimedia.org/wikipedia/commons/8/83/Binary_Search_Depiction.svg) + +### Let us have a pictorial representation of the binary search algorithm to understand it better. + +1. The array in which searching is to be performed is: + ![Step1](https://cdn.programiz.com/sites/tutorial2program/files/binary-search-initial-array.png) +
Initial array
+ + Let `x = 4` be the element to be searched. + +2. Set two pointers low and high at the lowest and the highest positions respectively. + ![Step2](https://cdn.programiz.com/sites/tutorial2program/files/binary-search-set-pointers.png) +
Setting pointers
+ +3. Find the middle element `mid` of the array i.e. `arr[(low + high)/2] = 6`. + ![Step3](https://cdn.programiz.com/sites/tutorial2program/files/binary-search-mid.png) +
Mid element
+ + +4. If x == mid, then return mid. Else, compare the element to be searched with mid. + +5. If `x > mid`, compare `x` with the middle element of the elements on the right side of `mid`. This is done by setting `low` to `low = mid + 1`. + +6. Else, compare `x` with the middle element of the elements on the left side of `mid`. This is done by setting `high` to `high = mid - 1`. + ![Step6](https://cdn.programiz.com/sites/tutorial2program/files/binary-search-find-mid.png) +
Finding mid element
+ +7. Repeat steps 3 to 6 until low meets high. + ![Step7](https://cdn.programiz.com/sites/tutorial2program/files/binary-search-mid-again.png) +
Mid element
+ +8. `x = 4` is found. + ![Step8](https://cdn.programiz.com/sites/tutorial2program/files/binary-search-found.png) +
Found
+ + +Binary search is a fundamental algorithm with wide-ranging applications, especially in scenarios requiring fast data retrieval from sorted datasets. diff --git a/docs/beginner/doubly_linked_list.md b/docs/beginner/doubly_linked_list.md new file mode 100644 index 0000000..b9eb157 --- /dev/null +++ b/docs/beginner/doubly_linked_list.md @@ -0,0 +1,869 @@ +# Doubly Linked List + +A doubly linked list is similar to a singly linked list, with the primary difference being the addition of an extra pointer called prev, which stores the address of the previous node. Therefore, a node in a doubly linked list contains the prev pointer (address of the previous node), data, and next pointer (address of the next node). The last node would have the next attribute set to null, and the head node would have the prev attribute set to null. + +## Real-life Applications of Doubly Linked List + +- **Tree Implementation:** Doubly linked lists are used to implement tree data structure where the prev and next attributes are used to refer to the children of a node. +- **Web Browsers:** Web browsers use doubly linked lists for forward and backward page navigations. +- **Undo/Redo:** The redo and undo functions of various applications are implemented using a doubly linked list +- **Games:** It is used in various games like the classical deck of cards + +## Implementation +### Python +```python +class Node: + def __init__(self,data): + self.data = data + self.next = None + self.prev = None + +class doubly_linked_list: + def __init__(self): + self.head = None + + def insert_end(self,data): + new_node = Node(data) + if self.head is None: + self.head = new_node + else: + temp = self.head + while temp.next is not None: + temp = temp.next + temp.next = new_node + new_node.prev = temp + + def insert_begin(self, data): + new_node = Node(data) + if self.head is None: + self.head = new_node + else: + new_node.next = self.head + self.head = new_node + + def insert_pos(self,data,pos): + new_node = Node(data) + if self.head is None: + self.head = new_node + else: + if pos==1: + self.insert_begin(data) + else: + temp = self.head + for i in range(1, pos-1): + temp = temp.next + new_node.next = temp.next + new_node.prev = temp + temp.next.prev = new_node + temp.next = new_node + + def delete_end(self): + if self.head is None: + print("Linked list is empty") + return + else: + temp = self.head + while temp.next.next is not None: + temp = temp.next + temp.next = None + + def delete_begin(self): + if self.head is None: + print("Linked list is empty") + return + else: + self.head = self.head.next + self.head.prev = None + + def delete_pos(self,pos): + if self.head is None: + print("Linked list is empty") + return + else: + if pos==1: + self.delete_begin() + else: + temp = self.head + for i in range(1, pos-1): + temp = temp.next + temp.next = temp.next.next + temp.next.prev = temp + + def count(self): + count = 0 + temp = self.head + while temp is not None: + count+=1 + temp = temp.next + return count + + def search(self,data): + temp = self.head + while temp is not None: + if temp.data==data: + return True + temp = temp.next + return False + + def display(self): + if self.head is None: + print("Linked list is empty") + return + else: + temp = self.head + while temp is not None: + print(temp.data, end="-->") + temp = temp.next + print("None") + + def display_reverse(self): + if self.head is None: + print("Linked list is empty") + return + else: + temp = self.head + while temp.next is not None: + temp = temp.next + while temp is not None: + print(temp.data, end="-->") + temp = temp.prev + print("None") + +dll = doubly_linked_list() +dll.insert_end(1) +dll.insert_end(2) +dll.insert_end(3) +dll.insert_end(4) +dll.insert_end(5) +print("Original linked list: ", end="") +dll.display() +dll.insert_begin(11) +print("After insertion at beginning: ", end="") +dll.display() +dll.insert_pos(8,3) +print("After insertion at given postition: ", end="") +dll.display() +dll.delete_begin() +print("After deletion from beginning: ", end="") +dll.display() +dll.delete_end() +print("After deletion from end: ", end="") +dll.display() +dll.delete_pos(2) +print("After deletion from given position: ", end="") +dll.display() +c = dll.count() +print("Number of nodes in the linked list:", c) +s = dll.search(10) +print("Is the value present in the linked list?", s) +print("Linked list in reverse order:", end="") +dll.display_reverse() + + +''' +OUTPUT: +Original linked list: 1-->2-->3-->4-->5-->None +After insertion at beginning: 11-->1-->2-->3-->4-->5-->None +After insertion at given postition: 11-->1-->8-->2-->3-->4-->5-->None +After deletion from beginning: 1-->8-->2-->3-->4-->5-->None +After deletion from end: 1-->8-->2-->3-->4-->None +After deletion from given position: 1-->2-->3-->4-->None +Number of nodes in the linked list: 4 +Is the value present in the linked list? False +Linked list in reverse order:4-->3-->2-->1-->None +''' +``` + +### Java +```java +class Node { + int data; + Node next; + Node prev; + + public Node(int data) { + this.data = data; + this.next = null; + this.prev = null; + } +} + +class DoublyLinkedList { + Node head; + + public DoublyLinkedList() { + this.head = null; + } + + void insertEnd(int data) { + Node newNode = new Node(data); + if (head == null) { + head = newNode; + } + else { + Node temp = head; + while (temp.next != null) { + temp = temp.next; + } + temp.next = newNode; + newNode.prev = temp; + } + } + + void insertBegin(int data) { + Node newNode = new Node(data); + if (head == null) { + head = newNode; + } + else { + newNode.next = head; + head.prev = newNode; + head = newNode; + } + } + + void insertPos(int data, int pos) { + Node newNode = new Node(data); + if (head == null) { + head = newNode; + } + else { + if (pos == 1) { + insertBegin(data); + } + else { + Node temp = head; + for (int i = 1; i < pos - 1; i++) { + temp = temp.next; + } + newNode.next = temp.next; + if (temp.next != null) { + temp.next.prev = newNode; + } + temp.next = newNode; + newNode.prev = temp; + } + } + } + + void deleteEnd() { + if (head == null) { + System.out.println("Linked list is empty"); + return; + } + else { + Node temp = head; + while (temp.next.next != null) { + temp = temp.next; + } + temp.next = null; + } + } + + void deleteBegin() { + if (head == null) { + System.out.println("Linked list is empty"); + return; + } + else { + head = head.next; + if (head != null) { + head.prev = null; + } + } + } + + void deletePos(int pos) { + if (head == null) { + System.out.println("Linked list is empty"); + return; + } + else { + if (pos == 1) { + deleteBegin(); + } + else { + Node temp = head; + for (int i = 1; i < pos - 1; i++) { + temp = temp.next; + } + temp.next = temp.next.next; + if (temp.next != null) { + temp.next.prev = temp; + } + } + } + } + + int count() { + int count = 0; + Node temp = head; + while (temp != null) { + count++; + temp = temp.next; + } + return count; + } + + boolean search(int data) { + Node temp = head; + while (temp != null) { + if (temp.data == data) { + return true; + } + temp = temp.next; + } + return false; + } + + void display() { + if (head == null) { + System.out.println("Linked list is empty"); + return; + } + else { + Node temp = head; + while (temp != null) { + System.out.print(temp.data + "-->"); + temp = temp.next; + } + System.out.println("None"); + } + } + + void displayReverse() { + if (head == null) { + System.out.println("Linked list is empty"); + return; + } + else { + Node temp = head; + while (temp.next != null) { + temp = temp.next; + } + while (temp != null) { + System.out.print(temp.data + "-->"); + temp = temp.prev; + } + System.out.println("None"); + } + } +} + +public class Main { + public static void main(String[] args) { + DoublyLinkedList dll = new DoublyLinkedList(); + dll.insertEnd(1); + dll.insertEnd(2); + dll.insertEnd(3); + dll.insertEnd(4); + dll.insertEnd(5); + System.out.print("Original linked list: "); + dll.display(); + dll.insertBegin(11); + System.out.print("After insertion at beginning: "); + dll.display(); + dll.insertPos(8, 3); + System.out.print("After insertion at given position: "); + dll.display(); + dll.deleteBegin(); + System.out.print("After deletion from beginning: "); + dll.display(); + dll.deleteEnd(); + System.out.print("After deletion from end: "); + dll.display(); + dll.deletePos(2); + System.out.print("After deletion from given position: "); + dll.display(); + int c = dll.count(); + System.out.println("Number of nodes in the linked list: " + c); + boolean s = dll.search(10); + System.out.println("Is the value present in the linked list? " + s); + System.out.print("Linked list in reverse order: "); + dll.displayReverse(); + } +} + + +/* +OUTPUT: +Original linked list: 1-->2-->3-->4-->5-->None +After insertion at beginning: 11-->1-->2-->3-->4-->5-->None +After insertion at given position: 11-->1-->8-->2-->3-->4-->5-->None +After deletion from beginning: 1-->8-->2-->3-->4-->5-->None +After deletion from end: 1-->8-->2-->3-->4-->None +After deletion from given position: 1-->2-->3-->4-->None +Number of nodes in the linked list: 4 +Is the value present in the linked list? false +Linked list in reverse order: 4-->3-->2-->1-->None +*/ +``` + +### C++ +```cpp +#include + +using namespace std; + +class Node { +public: + int data; + Node* next; + Node* prev; + + Node(int data) { + this->data = data; + this->next = nullptr; + this->prev = nullptr; + } +}; + +class DoublyLinkedList { +public: + Node* head; + + DoublyLinkedList() { + this->head = nullptr; + } + + void insertEnd(int data) { + Node* newNode = new Node(data); + if (head == nullptr) { + head = newNode; + } + else { + Node* temp = head; + while (temp->next != nullptr) { + temp = temp->next; + } + temp->next = newNode; + newNode->prev = temp; + } + } + + void insertBegin(int data) { + Node* newNode = new Node(data); + if (head == nullptr) { + head = newNode; + } + else { + newNode->next = head; + head->prev = newNode; + head = newNode; + } + } + + void insertPos(int data, int pos) { + Node* newNode = new Node(data); + if (head == nullptr) { + head = newNode; + } + else { + if (pos == 1) { + insertBegin(data); + } + else { + Node* temp = head; + for (int i = 1; i < pos - 1; i++) { + temp = temp->next; + } + newNode->next = temp->next; + if (temp->next != nullptr) { + temp->next->prev = newNode; + } + temp->next = newNode; + newNode->prev = temp; + } + } + } + + void deleteEnd() { + if (head == nullptr) { + cout << "Linked list is empty" << endl; + return; + } + else { + Node* temp = head; + while (temp->next->next != nullptr) { + temp = temp->next; + } + temp->next = nullptr; + } + } + + void deleteBegin() { + if (head == nullptr) { + cout << "Linked list is empty" << endl; + return; + } + else { + head = head->next; + if (head != nullptr) { + head->prev = nullptr; + } + } + } + + void deletePos(int pos) { + if (head == nullptr) { + cout << "Linked list is empty" << endl; + return; + } + else { + if (pos == 1) { + deleteBegin(); + } + else { + Node* temp = head; + for (int i = 1; i < pos - 1; i++) { + temp = temp->next; + } + temp->next = temp->next->next; + if (temp->next != nullptr) { + temp->next->prev = temp; + } + } + } + } + + int count() { + int count = 0; + Node* temp = head; + while (temp != nullptr) { + count++; + temp = temp->next; + } + return count; + } + + bool search(int data) { + Node* temp = head; + while (temp != nullptr) { + if (temp->data == data) { + return true; + } + temp = temp->next; + } + return false; + } + + void display() { + if (head == nullptr) { + cout << "Linked list is empty" << endl; + return; + } + else { + Node* temp = head; + while (temp != nullptr) { + cout << temp->data << "-->"; + temp = temp->next; + } + cout << "None" << endl; + } + } + + void displayReverse() { + if (head == nullptr) { + cout << "Linked list is empty" << endl; + return; + } + else { + Node* temp = head; + while (temp->next != nullptr) { + temp = temp->next; + } + while (temp != nullptr) { + cout << temp->data << "-->"; + temp = temp->prev; + } + cout << "None" << endl; + } + } +}; + +int main() { + DoublyLinkedList dll; + dll.insertEnd(1); + dll.insertEnd(2); + dll.insertEnd(3); + dll.insertEnd(4); + dll.insertEnd(5); + cout << "Original linked list: "; + dll.display(); + dll.insertBegin(11); + cout << "After insertion at beginning: "; + dll.display(); + dll.insertPos(8, 3); + cout << "After insertion at given position: "; + dll.display(); + dll.deleteBegin(); + cout << "After deletion from beginning: "; + dll.display(); + dll.deleteEnd(); + cout << "After deletion from end: "; + dll.display(); + dll.deletePos(2); + cout << "After deletion from given position: "; + dll.display(); + int c = dll.count(); + cout << "Number of nodes in the linked list: " << c << endl; + bool s = dll.search(10); + cout << "Is the value present in the linked list? " << boolalpha << s << endl; + cout << "Linked list in reverse order: "; + dll.displayReverse(); + return 0; +} + + +''' +OUTPUT: +Original linked list: 1-->2-->3-->4-->5-->None +After insertion at beginning: 11-->1-->2-->3-->4-->5-->None +After insertion at given position: 11-->1-->8-->2-->3-->4-->5-->None +After deletion from beginning: 1-->8-->2-->3-->4-->5-->None +After deletion from end: 1-->8-->2-->3-->4-->None +After deletion from given position: 1-->2-->3-->4-->None +Number of nodes in the linked list: 4 +Is the value present in the linked list? false +Linked list in reverse order: 4-->3-->2-->1-->None +''' +``` + +### C +```c +#include +#include + +struct Node { + int data; + struct Node* next; + struct Node* prev; +}; + +struct DoublyLinkedList { + struct Node* head; +}; + +struct Node* createNode(int data) { + struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); + if (newNode == NULL) { + printf("Memory allocation failed\n"); + exit(1); + } + newNode->data = data; + newNode->next = NULL; + newNode->prev = NULL; + return newNode; +} + +struct DoublyLinkedList* initializeList() { + struct DoublyLinkedList* dll = (struct DoublyLinkedList*)malloc(sizeof(struct DoublyLinkedList)); + if (dll == NULL) { + printf("Memory allocation failed\n"); + exit(1); + } + dll->head = NULL; + return dll; +} + +void insertEnd(struct DoublyLinkedList* dll, int data) { + struct Node* newNode = createNode(data); + if (dll->head == NULL) { + dll->head = newNode; + } + else { + struct Node* temp = dll->head; + while (temp->next != NULL) { + temp = temp->next; + } + temp->next = newNode; + newNode->prev = temp; + } +} + +void insertBegin(struct DoublyLinkedList* dll, int data) { + struct Node* newNode = createNode(data); + if (dll->head == NULL) { + dll->head = newNode; + } + else { + newNode->next = dll->head; + dll->head->prev = newNode; + dll->head = newNode; + } +} + +void insertPos(struct DoublyLinkedList* dll, int data, int pos) { + struct Node* newNode = createNode(data); + if (dll->head == NULL) { + dll->head = newNode; + } + else { + if (pos == 1) { + insertBegin(dll, data); + } + else { + struct Node* temp = dll->head; + for (int i = 1; i < pos - 1; i++) { + temp = temp->next; + } + newNode->next = temp->next; + if (temp->next != NULL) { + temp->next->prev = newNode; + } + temp->next = newNode; + newNode->prev = temp; + } + } +} + +void deleteEnd(struct DoublyLinkedList* dll) { + if (dll->head == NULL) { + printf("Linked list is empty\n"); + return; + } + else { + struct Node* temp = dll->head; + while (temp->next->next != NULL) { + temp = temp->next; + } + temp->next = NULL; + } +} + +void deleteBegin(struct DoublyLinkedList* dll) { + if (dll->head == NULL) { + printf("Linked list is empty\n"); + return; + } + else { + dll->head = dll->head->next; + if (dll->head != NULL) { + dll->head->prev = NULL; + } + } +} + +void deletePos(struct DoublyLinkedList* dll, int pos) { + if (dll->head == NULL) { + printf("Linked list is empty\n"); + return; + } + else { + if (pos == 1) { + deleteBegin(dll); + } + else { + struct Node* temp = dll->head; + for (int i = 1; i < pos - 1; i++) { + temp = temp->next; + } + temp->next = temp->next->next; + if (temp->next != NULL) { + temp->next->prev = temp; + } + } + } +} + +int count(struct DoublyLinkedList* dll) { + int count = 0; + struct Node* temp = dll->head; + while (temp != NULL) { + count++; + temp = temp->next; + } + return count; +} + +int search(struct DoublyLinkedList* dll, int data) { + struct Node* temp = dll->head; + while (temp != NULL) { + if (temp->data == data) { + return 1; + } + temp = temp->next; + } + return 0; +} + +void display(struct DoublyLinkedList* dll) { + if (dll->head == NULL) { + printf("Linked list is empty\n"); + return; + } + else { + struct Node* temp = dll->head; + while (temp != NULL) { + printf("%d-->", temp->data); + temp = temp->next; + } + printf("None\n"); + } +} + +void displayReverse(struct DoublyLinkedList* dll) { + if (dll->head == NULL) { + printf("Linked list is empty\n"); + return; + } + else { + struct Node* temp = dll->head; + while (temp->next != NULL) { + temp = temp->next; + } + while (temp != NULL) { + printf("%d-->", temp->data); + temp = temp->prev; + } + printf("None\n"); + } +} + +int main() { + struct DoublyLinkedList* dll = initializeList(); + insertEnd(dll, 1); + insertEnd(dll, 2); + insertEnd(dll, 3); + insertEnd(dll, 4); + insertEnd(dll, 5); + printf("Original linked list: "); + display(dll); + insertBegin(dll, 11); + printf("After insertion at beginning: "); + display(dll); + insertPos(dll, 8, 3); + printf("After insertion at given position: "); + display(dll); + deleteBegin(dll); + printf("After deletion from beginning: "); + display(dll); + deleteEnd(dll); + printf("After deletion from end: "); + display(dll); + deletePos(dll, 2); + printf("After deletion from given position: "); + display(dll); + int c = count(dll); + printf("Number of nodes in the linked list: %d\n", c); + int s = search(dll, 10); + printf("Is the value present in the linked list? %s\n", s ? "true" : "false"); + printf("Linked list in reverse order: "); + displayReverse(dll); + return 0; +} + + +''' +OUTPUT: +Original linked list: 1-->2-->3-->4-->5-->None +After insertion at beginning: 11-->1-->2-->3-->4-->5-->None +After insertion at given position: 11-->1-->8-->2-->3-->4-->5-->None +After deletion from beginning: 1-->8-->2-->3-->4-->5-->None +After deletion from end: 1-->8-->2-->3-->4-->None +After deletion from given position: 1-->2-->3-->4-->None +Number of nodes in the linked list: 4 +Is the value present in the linked list? false +Linked list in reverse order: 4-->3-->2-->1-->None +''' +``` diff --git a/docs/beginner/images/graphs1.png b/docs/beginner/images/graphs1.png new file mode 100644 index 0000000..11f8f98 Binary files /dev/null and b/docs/beginner/images/graphs1.png differ diff --git a/docs/beginner/images/graphs2.png b/docs/beginner/images/graphs2.png new file mode 100644 index 0000000..f21cd8b Binary files /dev/null and b/docs/beginner/images/graphs2.png differ diff --git a/docs/beginner/images/graphs3.png b/docs/beginner/images/graphs3.png new file mode 100644 index 0000000..7ac4fdf Binary files /dev/null and b/docs/beginner/images/graphs3.png differ diff --git a/docs/beginner/images/graphs4.png b/docs/beginner/images/graphs4.png new file mode 100644 index 0000000..a888561 Binary files /dev/null and b/docs/beginner/images/graphs4.png differ diff --git a/docs/beginner/searching-techniques.md b/docs/beginner/searching-techniques.md new file mode 100644 index 0000000..bf2bf7f --- /dev/null +++ b/docs/beginner/searching-techniques.md @@ -0,0 +1,175 @@ +# Searching Techniques: + +Searching is a technique that which helps to find the place of a given element. Any Search is said to be unsuccessful or successful depending upon whether the element being searched is found or not. + +Majorly, Searching techniques are of two types: + + - Linear Search + - Binary Search + +# Linear Search: +Linear search is a very simple search algorithm.In this type of search, a sequential search is made over all elements one by one.Every item is checked and if match is found then it will be returned true otherwise, the search continues till the end of the data. + +It has a time complexity of O(N) + +## Algorithm: +Linear search(array A, value x) + +`>`Step1 : Set an integer i to 1 + +`>`Step2: If i>n then , go to step7 (where n is the size of array) + +`>`Step3: If A[i]==x then go to step6 + +`>`Step4: Set i to i+1 + +`>`Step5: go to step2 + +`>`Step6: Print value found at index i and go to step8 + +`>`Step7: Print value not found + +`>`Step8: Exit + +## Program: + +```c +void linear_search(int a[],int n, int value){ + int i; + for(i = 0; i < n; i++) { + if(a[i] == value) { // compares each element of the array + printf("The element is found at %d position\n", i+1); + } + printf("The element is not present in the array\n"); + } + } +``` + +**Example:** +```c + + #include + + int search(int array[], int n, int x) { + + // Going through array sequencially + for (int i = 0; i < n; i++) + if (array[i] == x) + return i; + return -1; + } + + int main() { + int array[] = {2, 4, 0, 1, 9}; + int x = 1; + int n = sizeof(array) / sizeof(array[0]); + + int result = search(array, n, x); + + (result == -1) ? printf("Element not found") : printf("Element found at index: %d", result); + } + + Output: + Element found at index 3 + +``` + +## Apllications of Linear Search: + +- Unsorted List Search: Linear search is useful when the data is not sorted. It sequentially checks each element in the list until a match is found. +- Simple Database Search: In small databases or unsorted lists, linear search can be used to find specific records. +- Linear Data Structures: Linear search is often used with linear data structures like arrays, linked lists, etc., to find a specific element. +- Debugging: Linear search can be used in debugging scenarios to find a specific value in a collection for troubleshooting purposes. + +# Binary Search: + +- Binary search is a search algorithm used to find the position of a target value within a sorted array. +- It works by repeatedly dividing the search interval in half until the target value is found or the interval is empty. +- The search interval is halved by comparing the target element with the middle value of the search space. + +## Algorithm: + +`>`Step1: Divide the searchspace into two halves by finding the middle index +``` +where , mid= (low+high)/2 +low= starting index of the array +high= last index of the array +``` + +`>`Step2: Compare the middle element of the search space with the value + +`>`Step3: If the key is found at middle element, the process is terminated + +`>`Step4: If the key is not found at middle element, choose which half will be used as the next search space +``` +If the key is smaller than the middle element, then the left side is used for next search +If the key is larger than the middle element, then the right side is used for next search +``` + +`>`Step5: This process is continued until the key is found or the total search space is exhausted. + +## Program: +```c + int binary_search(int arr[], int left, int right, int target) { + while (left <= right) { + int mid = left + (right - left) / 2; + + if (arr[mid] == target) { + return mid; + } else if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return -1; // Target not found + } +``` +**Example** +```c + #include + + int binary_search(int arr[], int left, int right, int target) { + while (left <= right) { + int mid = left + (right - left) / 2; + + if (arr[mid] == target) { + return mid; + } else if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return -1; // Target not found + } + + int main() { + int arr[] = {1, 3, 5, 7, 9}; + int n = sizeof(arr) / sizeof(arr[0]); + int target = 5; + + int index = binary_search(arr, 0, n - 1, target); + + if (index == -1) { + printf("Target not found\n"); + } else { + printf("Target found at index %d\n", index); + } + + return 0; + } + + + Output: + Target found at index 2 +``` + + +## Applications of Binary Search: +- Sorted List Search: Binary search is efficient for searching in sorted arrays or lists. It relies on the property that the elements are in sorted order. +- Searching in Databases: Binary search is commonly used in databases for searching indexes or sorted data sets. +- Searching in Trees: Binary search can be applied to binary search trees for efficient searching of elements. +- Performance-Critical Applications: Binary search is preferred in performance-critical applications due to its time complexity of O(log n), where n is the number of elements in the collection. \ No newline at end of file diff --git a/docs/beginner/stacks-and-queue-using-linkedlist.md b/docs/beginner/stacks-and-queue-using-linkedlist.md new file mode 100644 index 0000000..61eb051 --- /dev/null +++ b/docs/beginner/stacks-and-queue-using-linkedlist.md @@ -0,0 +1,674 @@ +# Stack + +Stack is a linear data structure that follows the **Last In First Out (LIFO)** order, meaning that the last element to be added is the first one to be removed, or alternatively the **First In Last Out (FILO)** order. + +In a stack, insertion and deletion is done from one end, refered to as the top of the stack + +Working with a stack is similar to managing a pile of plates where each plate is placed on top of another. Similarly, in a stack insertion of a new element occurs on top of the existing element and deletion occurs from the top as well. This behavior of stacks mimicks the physical stack of plates, where a new plate is added to the top or the topmost plate is removed. + +## Real-Life Applications Of Stack + +- **Function Call:** In programming languages, whenever a function is called, it's parameters and local variables are pushed onto a stack. When the function is completed, they are popped off. +- **Browser History:** The most recently visited website is at the top whereas older websites are listed below. +- **Expression Evaluation:** Stacks are used to convert mathematical expressions from infix to postfix or prefix and calculate the result. These are very common in calculator applications. +- **Syntax Checking:** In programming languages, stacks are used to check if the opening and closing symbols such as the parentheses, braces and brackets are matched properly or not. For example, in HTML, a stack is used to check whether each opening tag has a corresponding closing tag. + +## Basic Operations Of A Stack + +- **Push:** Inserting a new element in the stack. +- **Pop:** Removing/deleting the top most element in the stack. +- **Peek:** Viewing the top element of the stack but not deleting it. +- **isFull:** Checking if the stack is full. +- **isEmpty:** Checking if the stack is empty. + +## Linked List Implementation A Stack + +### Python +```python +class Node: + def __init__(self, data): + self.data = data + self.next = None + +class Stack: + def __init__(self): + self.head = None + + # Inserting a new element at the top + def push(self, data): + new_node = Node(data) + if self.head is None: + self.head = new_node + else: + new_node.next = self.head + self.head = new_node + + # Deleting the top element + def pop(self): + if self.head==None: + print("Stack Underflow") + else: + data = self.head.data + print("Popped element:", data) + self.head = self.head.next + + # Displaying top element + def peek(self): + if self.head==None: + print("Stack Underflow") + else: + print("Top element:", self.head.data) + + # Checking if the stack is empty + def isempty(self): + return self.head==None + + # Displaying the stack from top to bottom + def display(self): + temp = self.head + while temp is not None: + print(temp.data, "->", end="") + temp = temp.next + print("None") + +s = Stack() +s.push(1) +s.push(2) +s.push(3) +s.push(4) +s.push(5) +print("Original stack: ", end="") +s.display() +s.pop() +print("After pop() operation: ", end="") +s.display() +s.peek() +s.pop() +s.pop() +s.pop() +s.pop() +s.display() +print("Is the stack empty?", s.isempty()) +s.pop() + +''' +OUTPUT: +Original stack: 5 ->4 ->3 ->2 ->1 ->None +Popped element: 5 +After pop() operation: 4 ->3 ->2 ->1 ->None +Top element: 4 +Popped element: 4 +Popped element: 3 +Popped element: 2 +Popped element: 1 +None +Is the stack empty? True +Stack Underflow +''' +``` + +### Java +```java +class Node { + int data; + Node next; + + public Node(int data) { + this.data = data; + this.next = null; + } +} + +class Stack { + Node head; + + // Constructor + public Stack() { + this.head = null; + } + + // Inserting a new element at the top + public void push(int data) { + Node newNode = new Node(data); + if (head == null) { + head = newNode; + } + else { + newNode.next = head; + head = newNode; + } + } + + // Deleting the top element + public void pop() { + if (head == null) { + System.out.println("Stack Underflow"); + } + else { + int data = head.data; + System.out.println("Popped element: " + data); + head = head.next; + } + } + + // Displaying top element + public void peek() { + if (head == null) { + System.out.println("Stack Underflow"); + } + else { + System.out.println("Top element: " + head.data); + } + } + + // Checking if the stack is empty + public boolean isEmpty() { + return head == null; + } + + // Displaying the stack from top to bottom + public void display() { + Node temp = head; + while (temp != null) { + System.out.print(temp.data + " -> "); + temp = temp.next; + } + System.out.println("None"); + } +} + +public class Main { + public static void main(String[] args) { + Stack s = new Stack(); + s.push(1); + s.push(2); + s.push(3); + s.push(4); + s.push(5); + System.out.print("Original stack: "); + s.display(); + s.pop(); + System.out.print("After pop() operation: "); + s.display(); + s.peek(); + s.pop(); + s.pop(); + s.pop(); + s.pop(); + s.display(); + System.out.println("Is the stack empty? " + s.isEmpty()); + s.pop(); + } +} + + +/* +OUTPUT: +Original stack: 5 -> 4 -> 3 -> 2 -> 1 -> None +Popped element: 5 +After pop() operation: 4 -> 3 -> 2 -> 1 -> None +Top element: 4 +Popped element: 4 +Popped element: 3 +Popped element: 2 +Popped element: 1 +None +Is the stack empty? true +Stack Underflow +*/ +``` + +### C++ +```cpp +#include +using namespace std; + +class Node { +public: + int data; + Node* next; + + Node(int data) { + this->data = data; + this->next = nullptr; + } +}; + +class Stack { +private: + Node* head; + +public: + Stack() { + this->head = nullptr; + } + + // Inserting a new element in the stack + void push(int data) { + Node* newNode = new Node(data); + if (head == nullptr) { + head = newNode; + } + else { + newNode->next = head; + head = newNode; + } + } + + // Deleting the top element + void pop() { + if (head == nullptr) { + cout << "Stack Underflow" << endl; + } + else { + int data = head->data; + cout << "Popped element: " << data << endl; + Node* temp = head; + head = head->next; + delete temp; + } + } + + // Displaying the top element of stack + void peek() { + if (head == nullptr) { + cout << "Stack Underflow" << endl; + } + else { + cout << "Top element: " << head->data << endl; + } + } + + // Checking if the stack is empty + bool isEmpty() { + return head == nullptr; + } + + // Displaying the stack from top to bottom + void display() { + Node* temp = head; + while (temp != nullptr) { + cout << temp->data << " -> "; + temp = temp->next; + } + cout << "None" << endl; + } +}; + +int main() { + Stack s; + s.push(1); + s.push(2); + s.push(3); + s.push(4); + s.push(5); + cout << "Original stack: "; + s.display(); + s.pop(); + cout << "After pop() operation: "; + s.display(); + s.peek(); + s.pop(); + s.pop(); + s.pop(); + s.pop(); + s.display(); + cout << "Is the stack empty? " << (s.isEmpty() ? "true" : "false") << endl; + s.pop(); + + return 0; +} + + +/* +OUTPUT: +Original stack: 5 -> 4 -> 3 -> 2 -> 1 -> None +Popped element: 5 +After pop() operation: 4 -> 3 -> 2 -> 1 -> None +Top element: 4 +Popped element: 4 +Popped element: 3 +Popped element: 2 +Popped element: 1 +None +Is the stack empty? true +Stack Underflow +*/ +``` + +# Queue + +A queue is a linear data structure that follows the **First In, First Out (FIFO)** principle where the first element inserted is the first one to be removed. + +In a queue, insertion is done at the end, called the **rear** and deletion is done from the beginning called the **front**. + +The functioning of a queue is similar to a group of people standing in a line: new individuals join at the rear of the line, and those who have been waiting the longest leave from the front. + +## Real-Life Applications of Queue + +- **Operating Systems:** OS use queue for scheduling task. For example, OS maintains a ready queue, having processes that are ready to be executed and are waiting for CPU time. +- **Networking Devices:** Queues are used for packet management in networking devices such as routers and switches. They use queues to temporaily store packets if the outgoing links are too busy. +- **Printer Queues:** Queues are used to manage the order of printing jobs. As the jobs are submitted, they are added to the queue. The first added job is printed first, the second job is printed second and so on. +- **Breadth First Search Algorithm:** The BFS algorithm is used for level-by-level traversal of a graph. It starts at a particular node, adds its neighbour to the queue and then visits each neighbour. + +## Basic Operations in a Queue + +- **Enqueue:** Inserting an element at the rear end of a queue +- **Dequeue:** Deleting at element from the front end of a queue +- **Peek:** Displaying the element at the front +- **isFull:** Checking if the queue is full +- **isEmpty:** Checking if the queue is empty + +## Linked List Implementation of a Queue + +### Python +```python +class Node: + def __init__(self, data): + self.data = data + self.next = None + +class Queue: + def __init__(self): + self.head = None + + # Inserting an element in the queue + def enqueue(self, data): + new_node = Node(data) + if self.head is None: + self.head = new_node + else: + temp = self.head + while temp.next is not None: + temp = temp.next + temp.next = new_node + + # Deleting the an element in the queue + def dequeue(self): + if self.head is None: + print("Queue Underflow") + return None + else: + data = self.head.data + self.head = self.head.next + return data + + # Displaying the front element of the queue + def peek(self): + if self.head is None: + print("Queue Underflow") + return None + return self.head.data + + # Checking if the queue is empty + def isEmpty(self): + return self.head is None + + # Displaying the entire queue + def display(self): + if self.head is None: + print("Queue Underflow") + return + else: + temp = self.head + while temp is not None: + print(temp.data, end="->") + temp = temp.next + print("None") + +q = Queue() +q.enqueue(1) +q.enqueue(2) +q.enqueue(3) +q.enqueue(4) +q.enqueue(5) +print("Original Queue: ", end="") +q.display() +print("Removed element:", q.dequeue()) +print("Queue after removal: ", end="") +q.display() +print("Front Element:", q.peek()) +q.dequeue() +q.dequeue() +q.dequeue() +q.dequeue() +print("Is the queue empty?", q.isEmpty()) + + +''' +OUTPUT: +Original Queue: 1->2->3->4->5->None +Removed element: 1 +Queue after removal: 2->3->4->5->None +Front Element: 2 +Is the queue empty? True +''' +``` + +### Java +```java +class Node { + int data; + Node next; + + public Node(int data) { + this.data = data; + this.next = null; + } +} + +class Queue { + Node head; + + public Queue() { + this.head = null; + } + + // Inserting an element in the queue + public void enqueue(int data) { + Node newNode = new Node(data); + if (this.head == null) { + this.head = newNode; + } + else { + Node temp = this.head; + while (temp.next != null) { + temp = temp.next; + } + temp.next = newNode; + } + } + + // Deleting an element in the queue + public int dequeue() { + if (this.head == null) { + System.out.println("Queue Underflow"); + return -1; + } + else { + int data = this.head.data; + this.head = this.head.next; + return data; + } + } + + // Displaying the front element of the queue + public int peek() { + if (this.head == null) { + System.out.println("Queue Underflow"); + return -1; + } + return this.head.data; + } + + // Checking if the queue is empty + public boolean isEmpty() { + return this.head == null; + } + + // Displaying the entire queue + public void display() { + if (this.head == null) { + System.out.println("Queue Underflow"); + } + else { + Node temp = this.head; + while (temp != null) { + System.out.print(temp.data + "->"); + temp = temp.next; + } + System.out.println("None"); + } + } +} + +public class Main { + public static void main(String[] args) { + Queue q = new Queue(); + q.enqueue(1); + q.enqueue(2); + q.enqueue(3); + q.enqueue(4); + q.enqueue(5); + System.out.print("Original Queue: "); + q.display(); + System.out.println("Removed element: " + q.dequeue()); + System.out.print("Queue after removal: "); + q.display(); + System.out.println("Front Element: " + q.peek()); + q.dequeue(); + q.dequeue(); + q.dequeue(); + q.dequeue(); + System.out.println("Is the queue empty? " + q.isEmpty()); + } +} + + +/* +OUTPUT: +Original Queue: 1->2->3->4->5->None +Removed element: 1 +Queue after removal: 2->3->4->5->None +Front Element: 2 +Is the queue empty? true +*/ +``` + +### C++ +```cpp +#include +using namespace std; + +class Node { +public: + int data; + Node* next; + + // Constructor + Node(int data) { + this->data = data; + this->next = nullptr; + } +}; + +class Queue { +private: + Node* head; + +public: + Queue() { + this->head = nullptr; + } + + // Inserting an element in the queue + void enqueue(int data) { + Node* newNode = new Node(data); + if (this->head == nullptr) { + this->head = newNode; + } + else { + Node* temp = this->head; + while (temp->next != nullptr) { + temp = temp->next; + } + temp->next = newNode; + } + } + + // Deleting an element in the queue + int dequeue() { + if (this->head == nullptr) { + cout << "Queue Underflow" << endl; + return -1; + } + else { + int data = this->head->data; + Node* temp = this->head; + this->head = this->head->next; + delete temp; + return data; + } + } + + // Displaying the front element of the queue + int peek() { + if (this->head == nullptr) { + cout << "Queue Underflow" << endl; + return -1; + } + return this->head->data; + } + + // Checking if the queue is empty + bool isEmpty() { + return this->head == nullptr; + } + + // Displaying the entire queue + void display() { + if (this->head == nullptr) { + cout << "Queue Underflow" << endl; + } + else { + Node* temp = this->head; + while (temp != nullptr) { + cout << temp->data << "->"; + temp = temp->next; + } + cout << "None" << endl; + } + } +}; + +int main() { + Queue q; + q.enqueue(1); + q.enqueue(2); + q.enqueue(3); + q.enqueue(4); + q.enqueue(5); + cout << "Original Queue: "; + q.display(); + cout << "Removed element: " << q.dequeue() << endl; + cout << "Queue after removal: "; + q.display(); + cout << "Front Element: " << q.peek() << endl; + q.dequeue(); + q.dequeue(); + q.dequeue(); + q.dequeue(); + cout << "Is the queue empty? " << (q.isEmpty() ? "true" : "false") << endl; + return 0; +} + + +/* +OUTPUT: +Original Queue: 1->2->3->4->5->None +Removed element: 1 +Queue after removal: 2->3->4->5->None +Front Element: 2 +Is the queue empty? true +*/ +``` diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..43ea8df --- /dev/null +++ b/docs/index.md @@ -0,0 +1,234 @@ +--- +id: dsa +title: Data Structures and Algorithms +sidebar_label: Data Structures and Algorithms +sidebar_position: 1 +slug: / +tags: [data-structures, algorithms, dsa, resources, books, courses, websites, blogs, youtube, podcasts, interview-preparation, competitive-programming, practice-problems, mock-interviews, interview-experiences, interview-questions, interview-tips, interview-cheat-sheets, interview-preparation-misc] +description: 'A comprehensive guide to Data Structures and Algorithms (DSA) including resources, books, courses, websites, blogs, YouTube channels, podcasts, interview preparation, competitive programming, practice problems, mock interviews, interview experiences, interview questions, interview tips, interview cheat sheets, and interview preparation misc.' +--- + +> Data Structures and Algorithms are the building blocks of computer science. They are the tools you'll use to build software systems. This section is a collection of resources to help you understand and master Data Structures and Algorithms. + +If you're new to Data Structures and Algorithms, start with the [Introduction to Data Structures and Algorithms](/docs/dsa/) guide. + +```mermaid +graph TD; + A[Data Structures & Algorithms] --> B(Data Structures); + A --> C(Algorithms); + +``` + +I'd be glad to create a comprehensive response for your Data Structures and Algorithms (DSA) roadmap, incorporating the best aspects of previous suggestions and addressing potential shortcomings: + +### Data Structures + +Data Structures are the fundamental building blocks used to organize and store data efficiently. Here are some common data structures you should be familiar with: + +```mermaid +graph TD; + A[Data Structures] --> B(Array); + A --> C(String); + A --> D(Linked List); + A --> E(Stack); + A --> F(Queue); + A --> G(Tree); + A --> H(Graph); + A --> I(Hashing); + A --> J(Heap); + A --> K(Trie); +``` + +- **Array**: A collection of elements of the same type stored in contiguous memory locations. +- **String**: A sequence of characters. +- **Linked List**: A linear data structure where elements are not stored in contiguous memory locations. +- **Stack**: A linear data structure that follows the Last In First Out (LIFO) principle. +- **Queue**: A linear data structure that follows the First In First Out (FIFO) principle. +- **Tree**: A non-linear data structure used to store data hierarchically. +- **Graph**: A non-linear data structure consisting of vertices and edges. +- **Hashing**: A technique used to uniquely identify objects. +- **Heap**: A complete binary tree that satisfies the heap property. +- **Trie**: A tree-like data structure used to store a dynamic set of strings. + +### Algorithms + +Algorithms are step-by-step procedures used to solve problems or perform computations. Here are some common algorithms you should be familiar with: + +```mermaid +graph TD; + A[Algorithms] --> B(Sorting); + A --> C(Searching); + A --> D(Recursion); + A --> E(Dynamic Programming); + A --> F(Greedy Algorithms); + A --> G(Divide and Conquer); + A --> H(Brute Force); + A --> I(Bit Manipulation); + A --> J(Graph Algorithms); + A --> K(String Matching); +``` + +- **Sorting**: Arranging elements in a specific order. +- **Searching**: Finding a specific element in a collection of elements. +- **Recursion**: A technique where a function calls itself to solve a smaller instance of the same problem. +- **Dynamic Programming**: Solving problems by breaking them down into smaller subproblems. +- **Greedy Algorithms**: Making locally optimal choices at each step. +- **Divide and Conquer**: Solving problems by breaking them down into smaller subproblems. +- **Brute Force**: Solving problems by trying all possible solutions. +- **Bit Manipulation**: Algorithmically manipulating bits or binary digits. +- **Graph Algorithms**: Solving problems on graphs. +- **String Matching**: Finding a substring within a string. + +## Resources + +When it comes to learning Data Structures and Algorithms, there are numerous resources available, including books, courses, websites, blogs, YouTube channels, podcasts, Interview Preparation, Competitive Programming, Practice Problems, Mock Interviews, Interview Experiences, Interview Questions, Interview Tips, Interview Cheat Sheets and Interview Preparation Misc. + +**Here are some of the most popular and highly recommended resources for mastering DSA:** + +### Books + +| Book Title | Description | Link (if available) | +|:---|:---|:---| +| Introduction to Algorithms (Cormen et al.) | The classic, in-depth guide to algorithms, covering a wide range of topics and complexities. | [mitpress.mit.edu](http://mitpress.mit.edu/9780262046305/introduction-to-algorithms/) | +| Grokking Algorithms (Bhargava) | A more approachable introduction with clear explanations and visualizations. | [edu.anarcho-copy.org](https://edu.anarcho-copy.org/Algorithm/grokking-algorithms-illustrated-programmers-curious.pdf) | +| Cracking the Coding Interview (Gallott) | A practical guide geared towards interview preparation, with problem-solving strategies and solutions. | [amazon.com](https://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional-ebook/dp/B000SEIBB8) | +| Elements of Programming Interviews in Python/Java/C++ (Langdon) | Language-specific resources that delve into commonly asked interview questions and solutions. | [amazon.com](https://www.amazon.com/Elements-Programming-Interviews-Python-Insiders/dp/1537713949) | + +### Courses + +| Platform | Course Title | Description | Link (if available) | +|:---|:---|:---|:---| +| Coursera | Algorithms, Part 1 & 2 (Stanford University) | A well-structured series by Stanford professors, covering fundamental algorithms and data structures. | [coursera.org](https://www.coursera.org/specializations/algorithms) | +| edX | Introduction to Algorithms (MIT) | Another excellent series from MIT, offering a comprehensive exploration of algorithms and complexities. | [edx.org/learn/algorithms](https://www.edx.org/learn/algorithms) | +| Udacity | Nanodegree Programs (Various) | Comprehensive programs focused on specific aspects of DSA, like data structures and algorithms or interview preparation. | [udacity.com](https://www.udacity.com/) | +| Udemy | Various DSA Courses | A vast selection of courses from different instructors, catering to beginner, intermediate, and advanced learners. | [udemy.com](https://www.udemy.com/) | + + +### Websites + +| Website | Description | Link | +|:---|:---|:---| +| GeeksforGeeks | A popular resource with tutorials, practice problems, interview preparation materials, and competitive programming insights. | [geeksforgeeks.org](https://www.geeksforgeeks.org/) | +| LeetCode | A platform with a large collection of coding problems, categorized by difficulty level, company tags, and problem types. | [leetcode.com](https://leetcode.com/) | +| HackerRank | Similar to LeetCode, HackerRank provides coding challenges, practice problems, and interview preparation features. | [hackerrank.com](https://www.hackerrank.com/) | +| Programiz | A website offering clear explanations, visualizations, and interactive coding exercises for various DSA concepts. | [programiz.com](https://www.programiz.com/) | +| Code Chef | Similar to LeetCode, HackerRank provides coding challenges, weekly contests, practice problems, and interview preparation features. | [codechef.com](https://www.codechef.com/)| + +### Blogs + +| Blog | Description | Link (if available) | +|:---|:---|:---| +| InterviewCake | Articles and videos focused on interview preparation, problem-solving strategies, and common DSA topics. | [interviewcake.com](https://www.interviewcake.com/) | +| AlgoExpert | A blog with in-depth articles on algorithms, data structures, and system design, along with video explanations. | [algoexpert.io/product](https://www.algoexpert.io/product) | +| Back to Back SWE | A blog by a former Facebook engineer, offering insights into the tech interview process and practical DSA tips. | [youtube.com/c/BackToBackSWE](https://www.youtube.com/c/BackToBackSWE) | +| MIT OpenCourseware | Access written materials from MIT's renowned algorithms courses, including problem sets and solutions. | [ocw.mit.edu](https://ocw.mit.edu/courses/mathematics/) | +| Take u Forward | Take u forward organization provides all materials for the DSA topics with clear explanation and example code in three languages C++,Python and JAVA | [takeuforward.org](https://takeuforward.org/blogs) | + +### YouTube Channels + +| Channel | Description | Link (if available) | +|:---|:---|:---| +| freeCodeCamp.org | Offers tutorials, problem-solving walkthroughs, and interview preparation advice on DSA concepts. | [youtube.com/c/...](https://www.youtube.com/c/Freecodecamp) | +| The Coding Train | Creates engaging and creative videos that explain data structures and algorithms in a visually appealing way. | [youtube.com/c/...](https://www.youtube.com/channel/UCvjgXvBlbQiydffZU7m1_aw) | +| Computer Science Dojo | Another channel with clear explanations and helpful visualizations for core DSA concepts. | [youtube.com/c/...](https://m.youtube.com/c/CSDojo) | +| take U forward | One more channel with clear explanations and helpful visualizations for core DSA concepts. | [youtube.com/c/...](https://www.youtube.com/@takeUforward) | +| CodeWithHarry | One more channel with clear explanations and helpful visualizations for core DSA concepts and with teach varies technologies as well. | [youtube.com/c/...](https://www.youtube.com/@CodeWithHarry) | +| Apna College | One more channel with clear explanations and helpful visualizations for core DSA concepts and with teach varies technologies as well. | [youtube.com/c/...](https://www.youtube.com/@ApnaCollegeOfficial) | + + + + +### Podcasts + +| Podcast | Description | Link (if available) | +|:---|:---|:---| +| Software Engineering Daily | Interviews with software engineers, often covering DSA topics and interview experiences. | [softwareengineeringdaily.com](https://softwareengineeringdaily.com/) | +| Coding Blocks | A podcast geared towards Indian students, offering guidance on technical interviews and DSA preparation. | [codingblocks.com](https://www.codingblocks.net/) | + +### Interview Preparation + +| Resource | Description | Link (if available) | +|:---|:---|:---| +| Pramp | A platform for conducting mock interviews with other programmers, providing valuable practice. | [pramp.com](https://www.pramp.com/) | +| Exponent | Connects you with experienced software engineers for mock interviews and personalized feedback. | [tryexponent.com](https://www.tryexponent.com/practice/) | | +| Interviewing.io | Similar to Exponent, Interviewing.io allows you to connect with experienced engineers for mock interviews. | [interviewing.io](https://www.interviewing.io/) | +| Blind | An anonymous forum where users share interview experiences and insights from various companies. | N/A | + +### Competitive Programming + +| Platform | Description | Link (if available) | +|:---|:---|:---| +| LeetCode Contests | Regularly held coding challenges on LeetCode, promoting problem-solving skills and competitive spirit. | [https://leetcode.com/contest/](https://leetcode.com/contest/) | +| HackerRank Contests | Similar to LeetCode Contests, HackerRank offers regular challenges for competitive programmers. | [https://www.hackerrank.com/contests](https://www.hackerrank.com/contests) | +| Codeforces | A popular platform for competitive programming with contests, problems, and tutorials. | [https://codeforces.com/](https://codeforces.com/) | +| Topcoder | Another platform hosting coding challenges, marathons, and tutorials for competitive programmers. | [https://www.topcoder.com/](https://www.topcoder.com/) | +| Codechef Contests | Regularly held coding challenges on Codechef, promoting problem-solving skills and competitive spirit. | [https://codechef.com/contest/](https://www.codechef.com/contests) | +| Coding Ninjas | Regularly held coding challenges on Coding ninjas, promoting problem-solving skills and competitive spirit. | [https://www.naukri.com/code360/contests](https://www.naukri.com/code360/contests) | + + +### Practice Problems + +| Platform | Description | Link (if available) | +|:---|:---|:---| +| (See Websites section) | Websites like GeeksforGeeks, LeetCode, and HackerRank offer a vast collection of practice problems with varying difficulty levels. | [GFG](https://www.geeksforgeeks.org/), [LeetCode](https://leetcode.com/), [HackerRank](https://www.hackerrank.com/), [W3Schools](https://www.w3schools.com/),[codechef](https://codechef.com/), [Programiz](https://www.programiz.com/) | +| Project Euler | A website with a series of challenging mathematical and computational problems. | [projecteuler.net](https://projecteuler.net/) | +| HackerRank 100 Days of Code | A structured challenge from HackerRank with daily programming exercises, including DSA problems. | [hackerrank.com/100-days-of-code](https://www.hackerrank.com/100-days-of-code) | +| Take u Forward A2Z sheet | A structured challenge from take u forward organization with programming exercises, including DSA problems. | [Strivers A2Z DSA Course/Sheet](https://takeuforward.org/strivers-a2z-dsa-course/strivers-a2z-dsa-course-sheet-2) | +| Coding Ninjas | Regularly held coding challenges on coding ninjas, promoting problem-solving skills and competitive spirit. | [https://www.naukri.com/code360/problems](https://www.naukri.com/code360/problems) | +| Love babbar | It is the combination of lectures notes, codes of the playlisst depolyed in the github written in C++ language(cpp) | [https://github.com/loveBabbar/CodeHelp-DSA-Busted-Series](https://github.com/loveBabbar/CodeHelp-DSA-Busted-Series) | + + + +### Mock Interviews + +| Resource | Description (mentioned previously) | Link (if available) | +|:---|:---|:---| +| Pramp | Connect with other programmers for mock interviews. | [pramp.com](https://www.pramp.com/) | +| Exponent | Get mock interviews and feedback from experienced engineers. | N/A | +| Interviewing.io | Conduct mock interviews with experienced engineers. | [interviewing.io](https://www.interviewing.io/) | + +### Interview Experiences + +| Platform | Description (mentioned previously) | Link (if available) | +|:---|:---|:---| +| Blind | Share and read interview experiences from various companies. | N/A | +| LeetCode Discuss | The LeetCode discussion forum often includes threads where users share interview experiences. | [leetcode.com/discuss/](https://leetcode.com/discuss/) | +| Glassdoor | Read interview reviews and experiences for various companies. | [glassdoor.com](https://www.glassdoor.com/) | + +### Interview Questions + +| Platform | Description (mentioned previously) | Link (if available) | +|:---|:---|:---| +| (See Websites section) | Websites like GeeksforGeeks, LeetCode, and HackerRank provide categorized interview questions. | [GFG](https://www.geeksforgeeks.org/), [LeetCode](https://leetcode.com/),[codechef](https://www.codechef.com/practice#interview), [HackerRank](https://www.hackerrank.com/), [W3Schools](https://www.w3schools.com/), [Programiz](https://www.programiz.com/) | +| Interview Cake | Articles and tutorials focusing on common interview questions and problem-solving techniques. | [interviewcake.com](https://www.interviewcake.com/) | +| AlgoExpert | Offers in-depth explanations of frequently asked interview questions. | [algoexpert.io](https://www.algoexpert.io/product) | + +### Interview Tips + +| Resource | Description | Link (if available) | +|:---|:---|:---| +| Interview Cake | Articles with practical tips on communication, problem-solving, and approaching technical interviews. | [interviewcake.com](https://www.interviewcake.com/) | +| Pramp | Mock interviews provide valuable experience in handling interview pressure and communication. | [pramp.com](https://www.pramp.com/) | +| Exponent | Feedback from experienced engineers can help identify areas for improvement in your interview approach. | N/A | +| Interviewing.io | Mock interviews allow you to practice your communication skills and technical problem-solving under interview-like conditions. | [interviewing.io](https://www.interviewing.io/) | +| Blogs (mentioned previously) | Blogs like InterviewCake and Back to Back SWE offer valuable advice on interview preparation and communication. | N/A | + +### Interview Cheat Sheets + +| Resource | Description | Link (if available) | +|:---|:---|:---| +| Tech Interview Handbook | A comprehensive online guide with cheat sheets for various DSA topics, big O notation, and system design. | [techinterviewhandbook.org](https://www.techinterviewhandbook.org/) | +| AlgoExpert | Cheat sheets summarizing key concepts and problem-solving approaches for common interview questions. | [algoexpert.io](https://www.algoexpert.io/product) | +| LeetCode Cheat Sheet | A community-created cheat sheet with summaries of various DSA concepts and algorithms. | [leetcode.com](https://leetcode.com/explore/interview/card/cheatsheets/) | + +### Interview Preparation Misc + +| Resource | Description | Link (if available) | +|:---|:---|:---| +| LeetCode Blind Questions | A curated list of interview questions frequently asked at top tech companies, based on user reports on Blind. | [https://leetcode.com/discuss/](https://leetcode.com/discuss/general-discussion/460599/blind-75-leetcode-questions) | +| System Design Interview | A website dedicated to system design interview preparation, offering resources and practice problems. | N/A | +| Educative.io | Offers interactive courses and practice problems for DSA, system design, and interview preparation. | [https://www.educative.io/](https://www.educative.io/) | + +Remember, this roadmap is a starting point. Tailor it to your specific learning style, goals, and the types of roles you're targeting. Be consistent in your practice, and don't hesitate to seek help from online communities or mentors when needed. + +***Good luck on your journey to mastering Data Structures and Algorithms!*** \ No newline at end of file diff --git a/docs/intermediate/Graph_traversal.md b/docs/intermediate/Graph_traversal.md new file mode 100644 index 0000000..f868c8a --- /dev/null +++ b/docs/intermediate/Graph_traversal.md @@ -0,0 +1,418 @@ +--- +id: 02-graph-traversal +title: Graph Data Structure Traversal Methods +sidebar_label: Graph Traversal methods +tags: + - dsa + - data-structures + - graph + - graph-traversal + - bfs + - dfs + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial +sidebar_position: 3 +--- +## What is Graph Data Structure +Graph Data Structure is a collection of vertices connected by edges. The vertices(V) are also referred as nodes and lines connecting any two nodes are called edges(E). A graph is denoted by G(V,E). + +![Local Image](graph.png) +## Traversal Methods in Graph +Two very popular traversal methods in Graph are: +* BFS (Breadth First Search) +* DFS (Depth First Search) + +## BFS (Breadth First Search) +Breadth First Search traversal algorithm in graph is similar to level order traversal of tree. It starts at a specified vertex and visits all its neighbors before moving on to the next level of neighbors. BFS is commonly used in algorithms for pathfinding, connected components, and shortest path problems in graphs. +### Algorithm: +1. Use adjacency list or adjacency matrix to store the graph, queue and a visiting array to keep the track of the visited vertex. +2. Strat traversal from any vertex. +3. Drop that vertex into queue +4. Take out the vertex from queue and explore it. +5. While exploring, go to all the adjacent vertices and add them to queue. +6. Repeat step 4 and 5 unitl queue is not empty. + +### BFS Program + + + ```Cpp showLineNumbers + /*write a cpp program to implement bfs algorithm*/ +#include +#include +#include +using namespace std; +void bfs(int source, vector>&graph,int vertex) +{ + queuequ; + vectorvisited(vertex,0); + qu.push(source); + visited[source]=1; + cout<>adjlis(vertex); //using adjacent list method to represent graph + //there are 9 edges in the graph + adjlis[0].push_back(2); + adjlis[0].push_back(1); + adjlis[0].push_back(3); + adjlis[1].push_back(3); + adjlis[2].push_back(3); + adjlis[2].push_back(4); + adjlis[3].push_back(4); + adjlis[4].push_back(5); + adjlis[4].push_back(6); + + bfs(0,adjlis,vertex); + return 0; +} + ``` + + + + ```Python showLineNumbers + from collections import deque + def bfs(source, graph, vertex): + qu = deque() + visited = [0] * vertex + qu.append(source) + visited[source] = 1 + print(source, end=" ") + + while qu: + u = qu.popleft() + for it in graph[u]: + if visited[it] == 0: + print(it, end=" ") + visited[it] = 1 + qu.append(it) + + def main(): + vertex = 7 + adjlis = [[] for _ in range(vertex)] # using adjacency list method to represent graph + # there are 9 edges in the graph + adjlis[0].extend([2, 1, 3]) + adjlis[1].append(3) + adjlis[2].extend([3, 4]) + adjlis[3].append(4) + adjlis[4].extend([5, 6]) + + bfs(0, adjlis, vertex) + + if __name__ == "__main__": + main() + + ``` + + + +```jsx showLineNumbers +import java.util.*; + +public class Main { + public static void bfs(int source, List> graph, int vertex) { + Queue qu = new LinkedList<>(); + boolean[] visited = new boolean[vertex]; + qu.add(source); + visited[source] = true; + System.out.print(source + " "); + + while (!qu.isEmpty()) { + int u = qu.poll(); + for (int it : graph.get(u)) { + if (!visited[it]) { + System.out.print(it + " "); + visited[it] = true; + qu.add(it); + } + } + } + } + + public static void main(String[] args) { + int vertex = 7; + List> adjlis = new ArrayList<>(vertex); + + for (int i = 0; i < vertex; i++) { + adjlis.add(new ArrayList<>()); + } + + // There are 9 edges in the graph + adjlis.get(0).addAll(Arrays.asList(2, 1, 3)); + adjlis.get(1).add(3); + adjlis.get(2).addAll(Arrays.asList(3, 4)); + adjlis.get(3).add(4); + adjlis.get(4).addAll(Arrays.asList(5, 6)); + + bfs(0, adjlis, vertex); + } +} + +``` + + + +```JavaScript showLineNumbers +class Graph { + constructor(vertex) { + this.vertex = vertex; + this.adjList = new Array(vertex).fill(null).map(() => []); + } + + addEdge(src, dest) { + this.adjList[src].push(dest); + } + + bfs(source) { + const visited = new Array(this.vertex).fill(false); + const queue = []; + visited[source] = true; + queue.push(source); + + while (queue.length !== 0) { + const u = queue.shift(); + console.log(u); + + for (const it of this.adjList[u]) { + if (!visited[it]) { + visited[it] = true; + queue.push(it); + } + } + } + } +} + +const main = () => { + const vertex = 7; + const graph = new Graph(vertex); + + // There are 9 edges in the graph + graph.addEdge(0, 2); + graph.addEdge(0, 1); + graph.addEdge(0, 3); + graph.addEdge(1, 3); + graph.addEdge(2, 3); + graph.addEdge(2, 4); + graph.addEdge(3, 4); + graph.addEdge(4, 5); + graph.addEdge(4, 6); + + graph.bfs(0); +}; + +main(); +``` + + +Output:
+ +``` +0 2 1 3 4 5 6 +``` + +## DFS (Depth First Search) +Depth First Search traversal algorithm is similar to Pre-order traversal in binary tree. DFS use stack data structure here (or recursion as stack).he algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. + +### Algorithm: +1. Use adjacency list or adjacency matrix to store the graph, queue and a visiting array to keep the track of the visited vertex. +2. Start with any vertex and start exploring. +3. After getting first element suspend the previous one in the stack and now start exploring this vertex. +4. If cannot explore more go back to previous vertex (backtraking) from stack and explore that +5. Repeat 3 and 4 until stack is empty. + +### DFS Program + + + ```Cpp showLineNumbers + #include +#include +using namespace std; + +// Function for DFS traversal +void DFS(int u, vector>& G, vector& visited) { + cout << u << " "; + visited[u] = 1; + + for (int v = 0; v < G.size(); ++v) { + if (G[u][v] == 1 && visited[v] == 0) { + DFS(v, G, visited); + } + } +} + +int main() { + int vertex=7; + + //using adjacent matrix method to represent graph + vector> G{{0,1,1,1,0,0,0}, + {1,0,0,1,1,0,0}, + {1,0,0,1,0,0,0}, + {1,1,1,0,1,0,0}, + {0,1,0,1,0,1,1}, + {0,0,0,0,1,0,0}, + {0,0,0,0,1,0,0}}; + + + vector visited(vertex, 0); // Initialize visited array to 0 + + cout << "DFS traversal starting from vertex 0: "; + DFS(0, G, visited); + + return 0; +} + ``` + + + + ```Python showLineNumbers + def dfs(u, graph, visited): + print(u, end=" ") + visited[u] = 1 + + for v in range(len(graph)): + if graph[u][v] == 1 and not visited[v]: + dfs(v, graph, visited) + +def main(): + vertex = 7 + + graph = [ + [0, 1, 1, 1, 0, 0, 0], + [1, 0, 0, 1, 1, 0, 0], + [1, 0, 0, 1, 0, 0, 0], + [1, 1, 1, 0, 1, 0, 0], + [0, 1, 0, 1, 0, 1, 1], + [0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 1, 0, 0] + ] + + visited = [0] * vertex # Initialize visited array to 0 + + print("DFS traversal starting from vertex 0: ", end="") + dfs(0, graph, visited) + +if __name__ == "__main__": + main() + + ``` + + + + ```jsx showLineNumbers + import java.util.*; + +public class DFS { + // Function for DFS traversal + public static void dfs(int u, int[][] graph, boolean[] visited) { + System.out.print(u + " "); + visited[u] = true; + + for (int v = 0; v < graph.length; v++) { + if (graph[u][v] == 1 && !visited[v]) { + dfs(v, graph, visited); + } + } + } + + public static void main(String[] args) { + int vertex = 7; + + int[][] graph = { + {0, 1, 1, 1, 0, 0, 0}, + {1, 0, 0, 1, 1, 0, 0}, + {1, 0, 0, 1, 0, 0, 0}, + {1, 1, 1, 0, 1, 0, 0}, + {0, 1, 0, 1, 0, 1, 1}, + {0, 0, 0, 0, 1, 0, 0}, + {0, 0, 0, 0, 1, 0, 0} + }; + + boolean[] visited = new boolean[vertex]; // Initialize visited array to false + + System.out.print("DFS traversal starting from vertex 0: "); + dfs(0, graph, visited); + } +} + + ``` + + + + ```JavaScript showLineNumbers + class Graph { + constructor(vertex) { + this.vertex = vertex; + this.adjList = new Array(vertex).fill(null).map(() => []); + } + + addEdge(src, dest) { + this.adjList[src].push(dest); + } + + dfsUtil(v, visited) { + visited[v] = true; + console.log(v + " "); + + this.adjList[v].forEach(neighbour => { + if (!visited[neighbour]) { + this.dfsUtil(neighbour, visited); + } + }); + } + + dfs(v) { + let visited = new Array(this.vertex).fill(false); + this.dfsUtil(v, visited); + } +} + +const main = () => { + const vertex = 7; + const graph = new Graph(vertex); + + graph.addEdge(0, 1); + graph.addEdge(0, 2); + graph.addEdge(0, 3); + graph.addEdge(1, 3); + graph.addEdge(1, 4); + graph.addEdge(2, 3); + graph.addEdge(3, 4); + graph.addEdge(4, 5); + graph.addEdge(4, 6); + + console.log("DFS traversal starting from vertex 0: "); + graph.dfs(0); +}; + +main(); + + ``` + + +Output:
+ +``` +DFS traversal starting from vertex 0: 0 1 3 2 4 5 6 +``` diff --git a/docs/intermediate/Hash-table.md b/docs/intermediate/Hash-table.md new file mode 100644 index 0000000..29bbb5d --- /dev/null +++ b/docs/intermediate/Hash-table.md @@ -0,0 +1,131 @@ +# Hash Table + +A hash table (or hash map) is a fundamental data structure in computer science, used for fast data retrieval. Here’s an in-depth look at hash tables: + +## Overview +A hash table is a collection of key-value pairs, where each key is mapped to a value. The key is transformed into an index in an array through a process called hashing. This index is used to quickly locate the value associated with the key. + +## Key Concepts +1. *Hash Function:* This function takes an input (the key) and returns an integer (the hash code), which is used as an index to store the corresponding value in the array. A good hash function distributes keys uniformly across the array. +2. *Buckets:* Each index in the array is referred to as a bucket. In cases where multiple keys hash to the same index, these keys are stored in the same bucket. +3. *Collision Handling:* Collisions occur when multiple keys hash to the same index. Common collision handling techniques include: + - Chaining: Each bucket points to a linked list of entries that map to the same index. + - Open Addressing: When a collision occurs, the algorithm searches for the next open bucket using a probing sequence (linear probing, quadratic probing, or double hashing). + +## Operations +**Insertion:** + +Compute the hash code of the key using the hash function. +Map the hash code to an index in the array. +Store the key-value pair in the corresponding bucket. Handle collisions appropriately. + +**Search:** + +Compute the hash code of the key. +Map the hash code to an index. +Check the corresponding bucket. If using chaining, search the linked list. If using open addressing, follow the probing sequence until the key is found or an empty bucket is reached. + +**Deletion:** + +Compute the hash code of the key. +Map the hash code to an index. +Locate the key in the bucket and remove the key-value pair. Adjust the structure to maintain efficiency (e.g., rehash elements if necessary). + +## Complexity +Average Time Complexity: $O(1)$ for insert, delete, and search operations in a well-implemented hash table with a good hash function and a load factor that avoids excessive collisions. + +Worst-Case Time Complexity: $O(n)$ for insert, delete, and search operations if all keys hash to the same index (highly unlikely with a good hash function). + +## Load Factor +The load factor $(Ξ±)$ is the ratio of the number of entries to the number of buckets in the hash table. A high load factor can lead to more collisions, affecting performance. A common practice is to resize the hash table (rehash) when the load factor exceeds a certain threshold. + + +$$​Load Factor = No. of entries / No. of Buckets$$ + + +**Rehashing** + +When the load factor exceeds a threshold, the hash table is resized (usually doubled) and all existing keys are rehashed to the new array. This operation ensures that the hash table maintains efficient performance. + +## Practical Considerations +*Choosing a Hash Function:* A good hash function minimizes collisions and uniformly distributes keys. Common hash functions include division-remainder, multiplication, and universal hashing. + +*Dynamic Resizing:* To maintain efficient operations, hash tables are dynamically resized (rehashing) when the load factor becomes too high. + +*Memory Usage:* Hash tables can be memory-inefficient if they are sparsely populated. A balance between memory usage and performance needs to be struck. + +## Applications + +1. Database Indexing: Hash tables are used for indexing databases to allow quick retrieval of records. +2. Caches: Hash tables underpin the implementation of caches. +3. Symbol Tables in Compilers: Used for fast lookup of identifiers (variables, functions, etc.) during compilation. +4. Sets: Hash tables can be used to implement set data structures for efficient membership checking. + +## Implementation in CPP + +```cpp +#include +#include +#include +#include + +class HashTable { +private: + int size; + std::vector>> table; + + int hashFunction(const std::string& key) const { + std::hash hashFunc; + return hashFunc(key) % size; + } + +public: + HashTable(int s) : size(s), table(s) {} + + void insert(const std::string& key, const std::string& value) { + int index = hashFunction(key); + for (auto& kvp : table[index]) { + if (kvp.first == key) { + kvp.second = value; + return; + } + } + table[index].emplace_back(key, value); + } + + std::string search(const std::string& key) const { + int index = hashFunction(key); + for (const auto& kvp : table[index]) { + if (kvp.first == key) { + return kvp.second; + } + } + return "Not Found"; + } + + bool remove(const std::string& key) { + int index = hashFunction(key); + for (auto it = table[index].begin(); it != table[index].end(); ++it) { + if (it->first == key) { + table[index].erase(it); + return true; + } + } + return false; + } +}; + +int main() { + HashTable ht(10); + ht.insert("key1", "value1"); + ht.insert("key2", "value2"); + + std::cout << "Search key1: " << ht.search("key1") << std::endl; // Output: value1 + std::cout << "Search key2: " << ht.search("key2") << std::endl; // Output: value2 + + ht.remove("key1"); + std::cout << "Search key1: " << ht.search("key1") << std::endl; // Output: Not Found + + return 0; +} +``` diff --git a/docs/intermediate/binary_tree.md b/docs/intermediate/binary_tree.md new file mode 100644 index 0000000..acb3b56 --- /dev/null +++ b/docs/intermediate/binary_tree.md @@ -0,0 +1,597 @@ +--- +id: 01-binary-tree +title: Introduction to Binary Tree +sidebar_label: Binary Tree +tags: + - dsa + - data-structures + - binary-tree + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial +sidebar_position: 2 +--- +In this tutorial we will explore one of the fundamental data structure in computer science: Binary Tree +# What is a Binary Tree? +A binary tree is a hierarchical data structure composed of nodes, where each node has at most two children: a left child and a right child. The topmost node of the tree is called the root node. Each child node can have its own left and right children, forming sub-trees. + + + +## Representation of a Node Binary Tree +Binary Tree is made up of nodes, where each node except leaf nodes have children. Each node in the tree consist of three parts i.e., data, left pointer, right pointer. To create a node we can follow the below structure of code: + + + + ```Cpp showLineNumbers + //Creating a node in C++ using structure + + typedef struct treetype + { + struct treetype *left; + int data; + struct treetype *right; + }node; + + //Creating a node in C++ using class + class Node{ + public: + Node *left; + int data; + Node *right; + }; + ``` + + + + ```Python showLineNumbers + #Creating a node in Python + + class Node: + def __init__(self, val): + self.left = None + self.data = val + self.right = None + ``` + + + + ```jsx showLineNumbers + //Creating a node in Java + + class Node{ + int data; + Node left,right; + public Node(int val) + { + left=null; + data=val; + right=null; + } + } + ``` + + + + ```JavaScript showLineNumbers + //Creating a node in JavaScript + + class Node + { + constructor(val) + { + this.left=null; + this.data=val; + this.right=null; + } + } + ``` + + + +## Operation in Binary Tree +### 1. Insert Operation: +We can add a node in the Binary Tree as a left child or right child of any node. +
+**Algorithm or steps to insert in a binary tree**
+* First check if the root is null or not if root is null means this is the first node of the tree, make it as a root and return it else move to next step +* Now as we have already studient queue data strucuture, we will use that to add nodes to the binary tree +* Insert a node as the left or right child of the parent node if the parent node points to null +* Return root to main function. + +### 2. Traversal of Binary Tree: +Traversal means visiting all nodes of the binary tree. Three famous binary tree traversal methods are:
+* **Preorder Traversal (NLR) :** In this traversal method we have to visit the current node before visiting its left or right subtree. The traversal is Node-left-right means first node (root node) is traveresed then left child and then right child +* **Inorder Traversal (LNR) :** In this traversal method we have to visit all the nodes inside the left subtree first then visit the current node and then the nodes in the right subtree. The traversal is Left-Node-right. +* **Postorder Traversal (LRN) :** In this traversal method we visit the current node after visiting all the nodes in left and right subtree. The traversal is in the order left-right-node. + +### 3. Search in Binary Tree: +We can search any element in the Binary Tree using the same algorithm as insertion just with some difference
+**Algorithm or steps to insert in a binary tree**
+*First check if the root is null or not if root is null return false to main else move to next step.
+*Store the root in a queue, start a loop which ends when queue is empty.
+*Take the front node (as temp) from queue check the temp value with the search value given if same return true to main else move to next step.
+*Check if the temp left or temp right child are NULL or not , if null continue the loop, else push the left then right child in the queue.
+*If the queue comes empty and element is not found return false to main.
+ +## Programming implementation of operation in Binary Tree + + + ```Cpp showLineNumbers + #include + #include + using namespace std; + class Node + { + public: + Node *left,*right; + int data; + Node(int val) + { + left=NULL; + data=val; + right=NULL; + } + }; + //insert function for binary search + Node* insert(Node* root, int data) + { + if (root==NULL){ + root=new Node(data); + return root; + } + //using queue data structure to find the position to insert the node + queuestore; + store.push(root); + while(!store.empty()) + { + Node *temp=store.front(); + store.pop(); + //check for left and right child + if (temp->left==NULL) + { + temp->left=new Node(data); + break; + } + else + store.push(temp->left); + if (temp->right==NULL) + { + temp->right=new Node(data); + break; + } + else + store.push(temp->right); + } + return root; + } + //now traversals methods of binary tree + //PRE-ORDER traversal + void pre_traversal(Node* root) + { + if (root==NULL) + return; + cout<data<<" "; + pre_traversal(root->left); + pre_traversal(root->right); + } + //IN-ORDER traversal + void in_traversal(Node *root) + { + if(root==NULL) + return ; + in_traversal(root->left); + cout<data<<" "; + in_traversal(root->right); + } + //POST-ORDER traversal + void post_traversal(Node *root) + { + if (root==NULL) + return ; + post_traversal(root->left); + post_traversal(root->right); + cout<data<<" "; + } + //search function for binary tree + bool search(Node *root, int value) + { + if (root==NULL) + return false; + queuestore; + store.push(root); + while(!store.empty()) + { + Node *temp=store.front(); + store.pop(); + if (temp->data==value) + return true; + if (temp->left!=NULL) + { + store.push(temp->left); + } + if (temp->right!=NULL) + { + store.push(temp->right); + } + } + return false; + } + int main() + { + Node *root=NULL; + //insertion operation in binary tree + root=insert(root,1); + root=insert(root,2); + root=insert(root,3); + root=insert(root,4); + root=insert(root,5); + //traversal + //preorder traversal + cout<<"Preorder Traversal: "; + pre_traversal(root); + //inorder traversal + cout< + + + ```Python showLineNumbers + from collections import deque + + class Node: + def __init__(self, val): + self.left = None + self.data = val + self.right = None + + # Insert function for binary search + def insert(root, data): + if root is None: + root = Node(data) + return root + # Using queue data structure to find the position to insert the node + store = deque([root]) + while store: + temp = store.popleft() + # Check for left and right child + if temp.left is None: + temp.left = Node(data) + break + else: + store.append(temp.left) + if temp.right is None: + temp.right = Node(data) + break + else: + store.append(temp.right) + return root + + # Now traversal methods of binary tree + # PRE-ORDER traversal + def pre_traversal(root): + if root is None: + return + print(root.data, end=" ") + pre_traversal(root.left) + pre_traversal(root.right) + + # IN-ORDER traversal + def in_traversal(root): + if root is None: + return + in_traversal(root.left) + print(root.data, end=" ") + in_traversal(root.right) + + # POST-ORDER traversal + def post_traversal(root): + if root is None: + return + post_traversal(root.left) + post_traversal(root.right) + print(root.data, end=" ") + + # Search function for binary tree + def search(root, value): + if root is None: + return False + store = deque([root]) + while store: + temp = store.popleft() + if temp.data == value: + return True + if temp.left is not None: + store.append(temp.left) + if temp.right is not None: + store.append(temp.right) + return False + + # Main function + def main(): + root = None + # Insertion operation in binary tree + root = insert(root, 1) + root = insert(root, 2) + root = insert(root, 3) + root = insert(root, 4) + root = insert(root, 5) + + # Traversal + # Preorder traversal + print("Preorder Traversal:", end=" ") + pre_traversal(root) + # Inorder traversal + print("\nInorder Traversal:", end=" ") + in_traversal(root) + # Postorder traversal + print("\nPost-order Traversal:", end=" ") + post_traversal(root) + + # Searching a node in the binary tree + if search(root, 4): + print("\nNode found in the binary tree") + else: + print("\nNode not found in the binary tree") + + if __name__ == "__main__": + main() + + ``` + + + + ```jsx showLineNumbers + import java.util.LinkedList; + import java.util.Queue; + + class Node { + Node left, right; + int data; + + Node(int val) { + left = null; + data = val; + right = null; + } + } + + public class BinaryTree { + // Insert function for binary search + static Node insert(Node root, int data) { + if (root == null) { + root = new Node(data); + return root; + } + // Using queue data structure to find the position to insert the node + Queue store = new LinkedList<>(); + store.add(root); + while (!store.isEmpty()) { + Node temp = store.poll(); + // Check for left and right child + if (temp.left == null) { + temp.left = new Node(data); + break; + } else + store.add(temp.left); + if (temp.right == null) { + temp.right = new Node(data); + break; + } else + store.add(temp.right); + } + return root; + } + + // Now traversal methods of binary tree + // PRE-ORDER traversal + static void preTraversal(Node root) { + if (root == null) + return; + System.out.print(root.data + " "); + preTraversal(root.left); + preTraversal(root.right); + } + + // IN-ORDER traversal + static void inTraversal(Node root) { + if (root == null) + return; + inTraversal(root.left); + System.out.print(root.data + " "); + inTraversal(root.right); + } + + // POST-ORDER traversal + static void postTraversal(Node root) { + if (root == null) + return; + postTraversal(root.left); + postTraversal(root.right); + System.out.print(root.data + " "); + } + + // Search function for binary tree + static boolean search(Node root, int value) { + if (root == null) + return false; + Queue store = new LinkedList<>(); + store.add(root); + while (!store.isEmpty()) { + Node temp = store.poll(); + if (temp.data == value) + return true; + if (temp.left != null) + store.add(temp.left); + if (temp.right != null) + store.add(temp.right); + } + return false; + } + + public static void main(String[] args) { + Node root = null; + // Insertion operation in binary tree + root = insert(root, 1); + root = insert(root, 2); + root = insert(root, 3); + root = insert(root, 4); + root = insert(root, 5); + + // Traversal + // Preorder traversal + System.out.print("Preorder Traversal: "); + preTraversal(root); + // Inorder traversal + System.out.print("\nInorder Traversal: "); + inTraversal(root); + // Postorder traversal + System.out.print("\nPost-order Traversal: "); + postTraversal(root); + + // Searching a node in the binary tree + if (search(root, 4)) + System.out.println("\nNode found in the binary tree"); + else + System.out.println("\nNode not found in the binary tree"); + } + } + + ``` + + + + ```javaScript showLineNumbers + class Node { + constructor(val) { + this.left = null; + this.data = val; + this.right = null; + } + } + + // Insert function for binary search + function insert(root, data) { + if (root === null) { + root = new Node(data); + return root; + } + // Using queue data structure to find the position to insert the node + let store = [root]; + while (store.length > 0) { + let temp = store.shift(); + // Check for left and right child + if (temp.left === null) { + temp.left = new Node(data); + break; + } else + store.push(temp.left); + if (temp.right === null) { + temp.right = new Node(data); + break; + } else + store.push(temp.right); + } + return root; + } + + // Now traversal methods of binary tree + // PRE-ORDER traversal + function preTraversal(root) { + if (root === null) + return; + process.stdout.write(root.data + " "); + preTraversal(root.left); + preTraversal(root.right); + } + + // IN-ORDER traversal + function inTraversal(root) { + if (root === null) + return; + inTraversal(root.left); + process.stdout.write(root.data + " "); + inTraversal(root.right); + } + + // POST-ORDER traversal + function postTraversal(root) { + if (root === null) + return; + postTraversal(root.left); + postTraversal(root.right); + process.stdout.write(root.data + " "); + } + + // Search function for binary tree + function search(root, value) { + if (root === null) + return false; + let store = [root]; + while (store.length > 0) { + let temp = store.shift(); + if (temp.data === value) + return true; + if (temp.left !== null) + store.push(temp.left); + if (temp.right !== null) + store.push(temp.right); + } + return false; + } + + // Main function + function main() { + let root = null; + // Insertion operation in binary tree + root = insert(root, 1); + root = insert(root, 2); + root = insert(root, 3); + root = insert(root, 4); + root = insert(root, 5); + + // Traversal + // Preorder traversal + process.stdout.write("Preorder Traversal: "); + preTraversal(root); + // Inorder traversal + process.stdout.write("\nInorder Traversal: "); + inTraversal(root); + // Postorder traversal + process.stdout.write("\nPost-order Traversal: "); + postTraversal(root); + + // Searching a node in the binary tree + if (search(root, 4)) + console.log("\nNode found in the binary tree"); + else + console.log("\nNode not found in the binary tree"); + } + + main(); + ``` + + + +Output:
+ +``` +Preorder Traversal: 1 2 4 5 3 +Inorder Traversal: 4 2 5 1 3 +Post-order Traversal: 4 5 2 3 1 +Node found in the binary tree +``` diff --git a/docs/intermediate/cpp_deques.md b/docs/intermediate/cpp_deques.md new file mode 100644 index 0000000..121a7c4 --- /dev/null +++ b/docs/intermediate/cpp_deques.md @@ -0,0 +1,107 @@ +# cpp_deques.md: Explanation and Usage of Deque (Double-Ended Queue) in STL + +## Introduction + +The `deque` (double-ended queue) is a sequence container in the C++ Standard Library (STL) that allows fast insertion and deletion of elements at both the beginning and the end. Unlike vectors, deques are not guaranteed to store all elements in contiguous memory, but they provide similar functionality with efficient insertions and deletions at both ends. + +## Syntax + +To use `deque`, you need to include the `` header: + +```cpp +#include +``` +## Declaration +You can declare a deque as follows: + +```cpp +std::deque myDeque; +``` + +# Basic Operations +## Adding Elements +push_back: Adds an element to the end of the deque. +push_front: Adds an element to the front of the deque. + + +```cpp +myDeque.push_back(10); // Adds 10 to the end +myDeque.push_front(5); // Adds 5 to the front +``` + +# Removing Elements +pop_back: Removes an element from the end of the deque. +pop_front: Removes an element from the front of the deque. + +```cpp +myDeque.pop_back(); // Removes the last element +myDeque.pop_front(); // Removes the first element +``` + +# Accessing Elements +operator[]: Provides random access to elements. +at: Provides bounds-checked access to elements. +front: Accesses the first element. +back: Accesses the last element. + +```cpp +int firstElement = myDeque.front(); +int lastElement = myDeque.back(); +int elementAt2 = myDeque[2]; +int elementAt3 = myDeque.at(3); // Throws an exception if out of range +``` + +# Iterators +begin: Returns an iterator to the first element. +end: Returns an iterator to one past the last element. + +```cpp +for (auto it = myDeque.begin(); it != myDeque.end(); ++it) { + std::cout << *it << " "; +} +``` + +# Example Code +Here is an example demonstrating the usage of deque: + +```cpp +#include +#include + +int main() { + std::deque myDeque; + + // Adding elements + myDeque.push_back(10); + myDeque.push_front(5); + myDeque.push_back(15); + myDeque.push_front(1); + + // Display elements + std::cout << "Deque elements: "; + for (int num : myDeque) { + std::cout << num << " "; + } + std::cout << std::endl; + + // Accessing elements + std::cout << "Front element: " << myDeque.front() << std::endl; + std::cout << "Back element: " << myDeque.back() << std::endl; + std::cout << "Element at index 2: " << myDeque[2] << std::endl; + + // Removing elements + myDeque.pop_front(); + myDeque.pop_back(); + + // Display elements after removal + std::cout << "Deque elements after pop operations: "; + for (int num : myDeque) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` +# Conclusion +The deque container in the C++ STL is a versatile sequence container that allows efficient insertion and deletion of elements at both ends. It combines the strengths of both vectors and lists, making it a suitable choice for scenarios where you need quick access to both ends of a sequence. diff --git a/docs/intermediate/cpp_stl/_category_.json b/docs/intermediate/cpp_stl/_category_.json new file mode 100644 index 0000000..3253f78 --- /dev/null +++ b/docs/intermediate/cpp_stl/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "cpp-stl", + "position": 2, + "link": { + "type": "generated-index", + "description": "Learn everything from the basics to the advanced topics that make up the C++ Standard Template Library." + } +} \ No newline at end of file diff --git a/docs/intermediate/cpp_stl/cpp_find.md b/docs/intermediate/cpp_stl/cpp_find.md new file mode 100644 index 0000000..6cd4372 --- /dev/null +++ b/docs/intermediate/cpp_stl/cpp_find.md @@ -0,0 +1,285 @@ +--- +id: cpp-find +title: The Find Algorithm in C++ +sidebar_label: CPP STL +tags: + - dsa + - data-structures + - cpp + - intermediate + - stl + - standard template library + - cpp stl + - programming + - tutorial + - find algorithm + - cpp find +sidebar_position: 7 +--- + +# Mastering the `find` Algorithm in C++: A Comprehensive Guide + +Hello, C++ enthusiasts! Today, we’re diving into one of the most fundamental and versatile components of the C++ Standard Library: the `find` algorithm. If you're looking to enhance your understanding and utilization of searching in C++, you're in the right place. This guide will cover everything you need to know about the `find` algorithm, from basic usage to advanced features, complete with examples and practical applications. + +## What is the `find` Algorithm? + +The `find` algorithm is a built-in function in the C++ Standard Library that allows you to search for a specific element in a range, typically specified by two iterators. It is part of the `` header and provides a straightforward way to locate elements within containers like vectors, lists, and arrays. + +### Why Use the `find` Algorithm? + +1. **Efficiency**: The find algorithm is optimized for performance and typically runs in O(n) time complexity. +2. **Convenience**: It simplifies the search process and reduces the amount of boilerplate code needed to implement searching. +3. **Flexibility**: The find algorithm can be used with various types of containers and custom comparison functions. + +## Basics of the `find` Algorithm + +Let’s start with the basics of using the `find` algorithm in C++. + +### Including the Header + +To use the `find` algorithm, you need to include the `` header. + +```cpp +#include +#include +#include +``` + +### Basic Usage + +The `find` algorithm requires three parameters: two iterators specifying the range to search within and the value to search for. + +```cpp +#include +#include +#include + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + auto it = std::find(numbers.begin(), numbers.end(), 3); + + if (it != numbers.end()) { + std::cout << "Element found: " << *it << std::endl; + } else { + std::cout << "Element not found." << std::endl; + } + + return 0; +} +``` + +### Searching in Different Containers + +You can use the `find` algorithm with various types of containers, such as vectors, lists, and arrays. + +Example with a List: + +```cpp +#include +#include +#include + +int main() { + std::list numbers = {1, 2, 3, 4, 5}; + auto it = std::find(numbers.begin(), numbers.end(), 3); + + if (it != numbers.end()) { + std::cout << "Element found: " << *it << std::endl; + } else { + std::cout << "Element not found." << std::endl; + } + + return 0; +} +``` + +## Advanced Features + +Now that we've covered the basics, let's explore some advanced features and techniques for using the `find` algorithm in C++. + +### Using `find` with Custom Data Types + +You can use the `find` algorithm to search for elements in containers of custom data types by providing a suitable comparison function. + +Example with a Custom Data Type: + +```cpp +#include +#include +#include +#include + +struct Person { + std::string name; + int age; + + bool operator==(const Person &other) const { + return name == other.name && age == other.age; + } +}; + +int main() { + std::vector people = {{"Alice", 30}, {"Bob", 25}, {"Charlie", 35}}; + Person target = {"Bob", 25}; + auto it = std::find(people.begin(), people.end(), target); + + if (it != people.end()) { + std::cout << "Person found: " << it->name << ", " << it->age << std::endl; + } else { + std::cout << "Person not found." << std::endl; + } + + return 0; +} +``` + +### Using `find_if` for More Complex Searches + +When you need more complex search criteria, you can use the `find_if` algorithm, which allows you to specify a predicate function. + +Example with `find_if`: + +```cpp +#include +#include +#include + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + auto it = std::find_if(numbers.begin(), numbers.end(), [](int x) { + return x > 3; + }); + + if (it != numbers.end()) { + std::cout << "First element greater than 3: " << *it << std::endl; + } else { + std::cout << "No elements greater than 3 found." << std::endl; + } + + return 0; +} +``` + +### Using `find_if_not` for Negative Searches + +The `find_if_not` algorithm finds the first element that does not satisfy a given predicate. + +```cpp +#include +#include +#include + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + auto it = std::find_if_not(numbers.begin(), numbers.end(), [](int x) { + return x < 3; + }); + + if (it != numbers.end()) { + std::cout << "First element not less than 3: " << *it << std::endl; + } else { + std::cout << "All elements are less than 3." << std::endl; + } + + return 0; +} +``` + +## Practical Applications of the find Algorithm + +The `find` algorithm is not just a theoretical construct; it is immensely practical and can be used in various scenarios to solve real-world problems. + +### Problem 1: Finding an Element in a Vector + +You have a vector of integers, and you want to find a specific element. + +```cpp +#include +#include +#include + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + int target = 4; + auto it = std::find(numbers.begin(), numbers.end(), target); + + if (it != numbers.end()) { + std::cout << "Element " << target << " found at index " << std::distance(numbers.begin(), it) << std::endl; + } else { + std::cout << "Element " << target << " not found." << std::endl; + } + + return 0; +} +``` + +### Problem 2: Finding a String in a List + +You have a list of strings, and you want to find a specific string. + +```cpp +#include +#include +#include +#include + +int main() { + std::list names = {"Alice", "Bob", "Charlie"}; + std::string target = "Bob"; + auto it = std::find(names.begin(), names.end(), target); + + if (it != names.end()) { + std::cout << "Name " << target << " found." << std::endl; + } else { + std::cout << "Name " << target << " not found." << std::endl; + } + + return 0; +} +``` + +### Problem 3: Finding a Custom Object in a Set + +You have a set of custom objects, and you want to find a specific object based on a member variable. + +```cpp +#include +#include +#include +#include + +struct Book { + std::string title; + int year; + + bool operator<(const Book &other) const { + return title < other.title; + } +}; + +bool compareByTitle(const Book &a, const Book &b) { + return a.title == b.title; +} + +int main() { + std::set books = {{"C++ Primer", 2012}, {"Effective C++", 2005}, {"The C++ Programming Language", 2013}}; + Book target = {"Effective C++", 2005}; + auto it = std::find_if(books.begin(), books.end(), [&](const Book &b) { + return compareByTitle(b, target); + }); + + if (it != books.end()) { + std::cout << "Book found: " << it->title << ", " << it->year << std::endl; + } else { + std::cout << "Book not found." << std::endl; + } + + return 0; +} +``` + +## In Conclusion + +The `find` algorithm is a powerful and versatile tool in the C++ Standard Library, offering efficient and flexible searching capabilities. By mastering the `find` algorithm, you can write more efficient, readable, and maintainable code. Whether you're searching for simple data types, complex objects, or using custom comparison functions, the `find` algorithm is the go-to solution.
+ +So, dive into the world of searching, experiment with the `find` algorithm, and unlock the full potential of your C++ programming skills. Happy coding, and may your searches always be successful! \ No newline at end of file diff --git a/docs/intermediate/cpp_stl/cpp_functor.md b/docs/intermediate/cpp_stl/cpp_functor.md new file mode 100644 index 0000000..dab81df --- /dev/null +++ b/docs/intermediate/cpp_stl/cpp_functor.md @@ -0,0 +1,308 @@ +--- +id: cpp-functor +title: Functors in C++ +sidebar_label: CPP STL +tags: + - dsa + - data-structures + - cpp + - intermediate + - stl + - standard template library + - cpp stl + - programming + - tutorial + - functors + - cpp functor +sidebar_position: 8 +--- + +Greetings, C++ enthusiasts! Today, we’re going to dive into the world of functors, also known as function objects. If you’re eager to enhance your C++ skills and learn how to create flexible, reusable functions, you’ve come to the right place. This comprehensive guide will cover everything you need to know about functors, from basic usage to advanced features, complete with practical examples. + +## What are Functors? + +A functor, short for function object, is an object that can be used as though it were a function. It achieves this by overloading the function call operator operator(). Functors are more than just functions; they can maintain state, be customized, and provide more flexible and reusable code. + +### Why Use Functors? + +1. **Flexibility**: Functors can maintain state between function calls, allowing for more complex behavior. +2. **Customization**: They provide a way to parameterize behavior, making code more adaptable. +3. **Reusability**: Functors can be reused across different contexts, promoting code modularity. + +## Basics of Functors + +Let’s start with the basics of creating and using functors in C++. + +### Creating a Functor + +To create a functor, define a class and overload the function call operator `operator()`. + +```cpp +#include + +class MyFunctor { +public: + void operator()(int x) const { + std::cout << "Functor called with argument: " << x << std::endl; + } +}; + +int main() { + MyFunctor functor; + functor(42); // Using the functor like a function + return 0; +} +``` + +### Using Functors + +Functors can be used wherever functions are expected, such as in algorithms, as function pointers, and with standard library containers. + +```cpp +#include +#include +#include + +class Square { +public: + int operator()(int x) const { + return x * x; + } +}; + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + Square square; + std::transform(numbers.begin(), numbers.end(), numbers.begin(), square); + + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +## Advanced Functors + +Now that we’ve covered the basics, let’s explore some advanced features and techniques for using functors in C++. + +### Functors with State + +Functors can maintain internal state between function calls, enabling more complex behavior. + +```cpp +#include + +class Counter { + int count = 0; +public: + int operator()() { + return ++count; + } +}; + +int main() { + Counter counter; + std::cout << "First call: " << counter() << std::endl; + std::cout << "Second call: " << counter() << std::endl; + std::cout << "Third call: " << counter() << std::endl; + + return 0; +} +``` + +### Parameterized Functors + +Functors can accept constructor parameters, allowing for customized behavior. + +```cpp +#include + +class Multiplier { + int factor; +public: + Multiplier(int f) : factor(f) {} + int operator()(int x) const { + return x * factor; + } +}; + +int main() { + Multiplier multiplyByTwo(2); + std::cout << "5 multiplied by 2: " << multiplyByTwo(5) << std::endl; + + Multiplier multiplyByThree(3); + std::cout << "5 multiplied by 3: " << multiplyByThree(5) << std::endl; + + return 0; +} +``` + +### Functors as Function Objects + +Functors can act as function objects, providing a way to encapsulate and parameterize behavior. + +```cpp +#include +#include +#include + +class ThresholdChecker { + int threshold; +public: + ThresholdChecker(int t) : threshold(t) {} + bool operator()(int x) const { + return x > threshold; + } +}; + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + int threshold = 2; + ThresholdChecker isAboveThreshold(threshold); + auto it = std::find_if(numbers.begin(), numbers.end(), isAboveThreshold); + + if (it != numbers.end()) { + std::cout << "First element above threshold " << threshold << ": " << *it << std::endl; + } else { + std::cout << "No elements above threshold " << threshold << " found." << std::endl; + } + + return 0; +} +``` + +### Combining Functors with Standard Library Algorithms + +Functors can be combined with standard library algorithms to perform complex operations efficiently. + +```cpp +#include +#include +#include + +class Increment { + int increment_value; +public: + Increment(int inc) : increment_value(inc) {} + int operator()(int x) const { + return x + increment_value; + } +}; + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + Increment incrementBy(3); + std::transform(numbers.begin(), numbers.end(), numbers.begin(), incrementBy); + + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +## Practical Applications of Functors + +Functors are not just theoretical constructs; they are immensely practical and can be used in various scenarios to solve real-world problems. + +### Problem 1: Sorting with Custom Criteria + +You have a list of items, and you want to sort them using custom criteria. + +```cpp +#include +#include +#include +#include + +struct Person { + std::string name; + int age; + + Person(std::string n, int a) : name(n), age(a) {} +}; + +class CompareByAge { +public: + bool operator()(const Person &a, const Person &b) const { + return a.age < b.age; + } +}; + +int main() { + std::vector people = {{"Alice", 30}, {"Bob", 25}, {"Charlie", 35}}; + std::sort(people.begin(), people.end(), CompareByAge()); + + for (const auto &person : people) { + std::cout << person.name << ": " << person.age << std::endl; + } + + return 0; +} +``` + +### Problem 2: Filtering Elements in a Container + +You need to filter elements in a container based on a specific condition. + +```cpp +#include +#include +#include + +class IsEven { +public: + bool operator()(int x) const { + return x % 2 == 0; + } +}; + +int main() { + std::vector numbers = {1, 2, 3, 4, 5, 6}; + auto end = std::remove_if(numbers.begin(), numbers.end(), IsEven()); + numbers.erase(end, numbers.end()); + + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Problem 3: Accumulating Values with Custom Behavior + +You want to accumulate values in a container using custom behavior. + +```cpp +#include +#include +#include + +class Multiply { +public: + int operator()(int a, int b) const { + return a * b; + } +}; + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + int result = std::accumulate(numbers.begin(), numbers.end(), 1, Multiply()); + + std::cout << "Product of all elements: " << result << std::endl; + return 0; +} +``` + +## In Conclusion + +Functors, or function objects, are powerful tools in C++ that enable more flexible and reusable code. By mastering functors, you can encapsulate complex behavior, maintain state, and create customizable functions that integrate seamlessly with the standard library algorithms.
+ +Functors, or function objects, are powerful tools in C++ that enable more flexible and reusable code. By mastering functors, you can encapsulate complex behavior, maintain state, and create customizable functions that integrate seamlessly with the standard library algorithms. \ No newline at end of file diff --git a/docs/intermediate/cpp_stl/cpp_iterators.md b/docs/intermediate/cpp_stl/cpp_iterators.md new file mode 100644 index 0000000..3ef9627 --- /dev/null +++ b/docs/intermediate/cpp_stl/cpp_iterators.md @@ -0,0 +1,298 @@ +--- +id: cpp-iterators +title: C++ Iterators +sidebar_label: CPP STL +tags: + - dsa + - data-structures + - cpp + - intermediate + - stl + - standard template library + - cpp stl + - programming + - tutorial + - iterators + - cpp iterator +sidebar_position: 5 +--- + +# Exploring Iterators in C++: The Ultimate Guide + +Hello, C++ enthusiasts! Today, we’re diving into one of the most essential and versatile components of the C++ Standard Template Library (STL): the iterator. If you’re looking to enhance your understanding and utilization of iterators in C++, you’re in the right place. This guide will cover everything you need to know about iterators, from basic usage to advanced features, complete with examples and practical applications. + +## What is an Iterator? + +An iterator is an object that allows a programmer to traverse a container, particularly lists, vectors, and other sequence containers. Think of it as a pointer-like object that can increment and point to elements in a container. + +### Why Use Iterators? + +1. **Abstraction**: Iterators provide an abstraction over pointer arithmetic, making the code cleaner and more readable. +2. **Flexibility**: They can be used to traverse different types of containers uniformly. +3. **Safety**: Iterators help avoid common errors associated with raw pointers, such as accessing invalid memory. + +## Basics of Iterators + +Let’s start with the basics of creating and using iterators in C++. + +### Types of Iterators + +The STL provides several types of iterators, each with specific capabilities: + +1. **Input Iterators**: Read from the container. +2. **Output Iterators**: Write to the container. +3. **Forward Iterators**: Read/write and traverse in one direction. +4. **Bidirectional Iterators**: Read/write and traverse in both directions. +5. **Random Access Iterators**: Provide access to any element in constant time. + +### Creating and Using Iterators + +To use iterators, you need to include the appropriate header for your container (e.g., ``, ``). + +```cpp +#include +#include + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + std::vector::iterator it; // Declare an iterator for a vector of integers + + for (it = numbers.begin(); it != numbers.end(); ++it) { + std::cout << *it << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Iterating Over Containers + +You can use iterators to traverse different types of containers, such as vectors, lists, and sets. + +```cpp +#include +#include + +int main() { + std::list numbers = {1, 2, 3, 4, 5}; + std::list::iterator it; + + for (it = numbers.begin(); it != numbers.end(); ++it) { + std::cout << *it << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +## Advanced Iterator Features + +Now that we've covered the basics, let's explore some advanced features and techniques for using iterators in C++. + +### Const Iterators + +Const iterators are used when you want to traverse a container without modifying its elements. + +```cpp +#include +#include + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + std::vector::const_iterator it; + + for (it = numbers.cbegin(); it != numbers.cend(); ++it) { + std::cout << *it << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Reverse Iterators + +Reverse iterators allow you to traverse a container in the reverse direction. + +```cpp +#include +#include + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + std::vector::reverse_iterator rit; + + for (rit = numbers.rbegin(); rit != numbers.rend(); ++rit) { + std::cout << *rit << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Using Iterators with Algorithms + +Iterators can be used with STL algorithms for operations such as sorting, finding, and copying elements. + +Example with `std::find`: + +```cpp +#include +#include +#include + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + auto it = std::find(numbers.begin(), numbers.end(), 3); + + if (it != numbers.end()) { + std::cout << "Element found: " << *it << std::endl; + } else { + std::cout << "Element not found." << std::endl; + } + + return 0; +} +``` + +Example with `std::sort`: + +```cpp +#include +#include +#include + +int main() { + std::vector numbers = {5, 3, 1, 4, 2}; + std::sort(numbers.begin(), numbers.end()); + + std::cout << "Sorted elements:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Custom Iterators + +You can create custom iterators by defining your own iterator class, which can be useful for custom data structures. + +```cpp +#include +#include +#include + +template +class CustomIterator : public std::iterator { + T* p; +public: + CustomIterator(T* x) : p(x) {} + CustomIterator(const CustomIterator& it) : p(it.p) {} + CustomIterator& operator++() { ++p; return *this; } + CustomIterator operator++(int) { CustomIterator tmp(*this); ++p; return tmp; } + bool operator==(const CustomIterator& rhs) const { return p == rhs.p; } + bool operator!=(const CustomIterator& rhs) const { return p != rhs.p; } + T& operator*() { return *p; } +}; + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + CustomIterator begin(numbers.data()); + CustomIterator end(numbers.data() + numbers.size()); + + std::cout << "Elements in the vector using custom iterator:" << std::endl; + for (auto it = begin; it != end; ++it) { + std::cout << *it << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +## Practical Applications of Iterators + +Iterators are not just theoretical constructs; they are immensely practical and can be used in various scenarios to solve real-world problems. + +### Problem 1: Traversing Containers + +When working with different containers, iterators provide a uniform way to traverse them without worrying about their underlying implementation. + +```cpp +#include +#include + +int main() { + std::set numbers = {1, 2, 3, 4, 5}; + std::set::iterator it; + + for (it = numbers.begin(); it != numbers.end(); ++it) { + std::cout << *it << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Problem 2: Modifying Elements + +You can use iterators to traverse and modify elements in a container. + +```cpp +#include +#include + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + for (auto it = numbers.begin(); it != numbers.end(); ++it) { + *it *= 2; // Double each element + } + + std::cout << "Modified elements:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Problem 3: Combining Iterators with Algorithms + +Using iterators with STL algorithms allows you to perform complex operations concisely. + +```cpp +#include +#include +#include +#include + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + std::vector copied_numbers; + + std::copy(numbers.begin(), numbers.end(), std::back_inserter(copied_numbers)); + + std::cout << "Copied elements:" << std::endl; + for (int num : copied_numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +## In Conclusion + +Iterators are a powerful and versatile component of the C++ Standard Template Library, offering an abstraction over raw pointers that makes code cleaner, safer, and more flexible. By mastering iterators, you can write more efficient, readable, and maintainable code. Whether you’re traversing containers, modifying elements, or combining iterators with STL algorithms, iterators are the go-to solution.
+ +So, dive into the world of iterators, experiment with their features, and unlock the full potential of your C++ programming skills. Happy coding, and may your iterators always point to success! \ No newline at end of file diff --git a/docs/intermediate/cpp_stl/cpp_lists.md b/docs/intermediate/cpp_stl/cpp_lists.md new file mode 100644 index 0000000..d066a68 --- /dev/null +++ b/docs/intermediate/cpp_stl/cpp_lists.md @@ -0,0 +1,338 @@ +--- +id: cpp-list +title: C++ Lists +sidebar_label: CPP STL +tags: + - dsa + - data-structures + - cpp + - intermediate + - stl + - standard template library + - cpp stl + - programming + - tutorial + - lists + - cpp list +sidebar_position: 3 +--- + +# Exploring Lists in C++: The Ultimate Guide + +Hello, C++ aficionados! Today, we're diving into one of the most fundamental and flexible components of the C++ Standard Template Library (STL): the list. If you're looking to enhance your understanding and utilization of lists in C++, you're in the right place. This guide will cover everything you need to know about lists, from basic usage to advanced features, complete with examples and practical applications. + +## What is a List? + +In C++, a `list` is a sequence container that allows non-contiguous memory allocation. Specifically, it is a doubly linked list, which means each element points to both its previous and next elements. This structure allows efficient insertion and deletion of elements, especially in the middle of the list. + +### Why Use Lists? + +1. **Efficient Insertions/Deletions**: Lists allow fast insertions and deletions compared to vectors, particularly when dealing with elements in the middle of the sequence. +2. **Dynamic Sizing**: Like vectors, lists can grow and shrink dynamically. +3. **Bidirectional Traversal**: The doubly linked nature of lists enables easy traversal in both forward and backward directions. + +## Basics of Lists + +Let's start with the basics of creating and using lists in C++. + +### Creating a List + +To use lists, you need to include the `` header. + +```cpp +#include +#include + +int main() { + std::list numbers; // Creates an empty list of integers + std::list numbers_with_initial_size(10); // Creates a list with 10 elements initialized to 0 + std::list numbers_with_initial_values(10, 5); // Creates a list with 10 elements initialized to 5 + + return 0; +} +``` + +### Adding and Accessing Elements + +You can add elements to a list using `push_back` and `push_front`, and access elements using iterators. + +```cpp +#include +#include + +int main() { + std::list numbers; + numbers.push_back(1); // Adds 1 to the end of the list + numbers.push_front(2); // Adds 2 to the beginning of the list + + std::cout << "Elements in the list:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Iterating Over a List + +You can iterate over the elements of a list using a range-based for loop or iterators. + +```cpp +#include +#include + +int main() { + std::list numbers = {1, 2, 3, 4, 5}; + + std::cout << "Using range-based for loop:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + std::cout << "Using iterators:" << std::endl; + for (auto it = numbers.begin(); it != numbers.end(); ++it) { + std::cout << *it << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +## Advanced List Features + +Now that we've covered the basics, let's explore some advanced features and techniques for using lists in C++. + +### Inserting and Erasing Elements + +You can insert and erase elements at any position using the `insert` and `erase` methods. + +```cpp +#include +#include + +int main() { + std::list numbers = {1, 2, 4, 5}; + auto it = numbers.begin(); + std::advance(it, 2); // Move iterator to the third position + numbers.insert(it, 3); // Inserts 3 at the third position + + std::cout << "List after insertion:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + numbers.erase(it); // Erases the element at the third position + + std::cout << "List after erasing:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Merging and Splicing Lists + +Lists provide powerful methods like `merge` and `splice` for combining and manipulating lists. + +```cpp +#include +#include + +int main() { + std::list list1 = {1, 3, 5}; + std::list list2 = {2, 4, 6}; + + list1.merge(list2); // Merges list2 into list1 + + std::cout << "Merged list:" << std::endl; + for (int num : list1) { + std::cout << num << " "; + } + std::cout << std::endl; + + std::list list3 = {7, 8, 9}; + auto it = list1.begin(); + std::advance(it, 3); + list1.splice(it, list3); // Splices list3 into list1 at the fourth position + + std::cout << "List after splicing:" << std::endl; + for (int num : list1) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Sorting and Removing Elements + +You can sort and remove elements using the `sort` and `remove` methods. + +```cpp +#include +#include + +int main() { + std::list numbers = {3, 1, 4, 1, 5, 9, 2}; + + numbers.sort(); // Sorts the list in ascending order + + std::cout << "Sorted list:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + numbers.remove(1); // Removes all elements with value 1 + + std::cout << "List after removing 1:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Capacity and Size + +Lists provide methods to manage and query their size. + +```cpp +#include +#include + +int main() { + std::list numbers = {1, 2, 3, 4, 5}; + + std::cout << "Size: " << numbers.size() << std::endl; // Number of elements + std::cout << "Is empty: " << (numbers.empty() ? "Yes" : "No") << std::endl; // Check if list is empty + + numbers.clear(); // Clears all elements from the list + + std::cout << "Size after clear: " << numbers.size() << std::endl; + + return 0; +} +``` + +### Swapping Lists + +You can swap the contents of two lists using the `swap` method. + +```cpp +#include +#include + +int main() { + std::list list1 = {1, 2, 3}; + std::list list2 = {4, 5, 6}; + + list1.swap(list2); + + std::cout << "list1 after swap:" << std::endl; + for (int num : list1) { + std::cout << num << " "; + } + std::cout << std::endl; + + std::cout << "list2 after swap:" << std::endl; + for (int num : list2) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +## Practical Applications of Lists + +Lists are not just theoretical constructs; they are immensely practical and can be used in various scenarios to solve real-world problems. + +### Problem 1: Implementing a To-Do List + +Imagine you are developing a simple to-do list application where tasks need to be added, removed, and displayed in order. Lists are ideal for this scenario due to their dynamic nature and efficient insertion and deletion. + +```cpp +#include +#include +#include + +int main() { + std::list to_do_list; + to_do_list.push_back("Buy groceries"); + to_do_list.push_back("Clean the house"); + to_do_list.push_back("Finish homework"); + + std::cout << "Current to-do list:" << std::endl; + for (const auto& task : to_do_list) { + std::cout << "- " << task << std::endl; + } + + to_do_list.remove("Clean the house"); + + std::cout << "To-do list after removal:" << std::endl; + for (const auto& task : to_do_list) { + std::cout << "- " << task << std::endl; + } + + return 0; +} +``` + +### Problem 2: Managing a Playlist + +Suppose you need to manage a music playlist where songs can be added, removed, and rearranged. Lists are perfect for this due to their ability to efficiently handle such operations. + +```cpp +#include +#include +#include + +int main() { + std::list playlist; + playlist.push_back("Song A"); + playlist.push_back("Song B"); + playlist.push_back("Song C"); + + std::cout << "Current playlist:" << std::endl; + for (const auto& song : playlist) { + std::cout << song << std::endl; + } + + auto it = playlist.begin(); + std::advance(it, 1); // Move iterator to the second position + playlist.insert(it, "Song D"); // Inserts "Song D" at the second position + + std::cout << "Playlist after insertion:" << std::endl; + for (const auto& song : playlist) { + std::cout << song << std::endl; + } + + playlist.erase(it); // Erases the second song + + std::cout << "Playlist after erasing:" << std::endl; + for (const auto& song : playlist) { + std::cout << song << std::endl; + } + + return 0; +} +``` + +## In Conclusion + +Lists are a powerful and flexible component of the C++ Standard Template Library, offering dynamic sizing and efficient insertion and deletion. By mastering lists, you can write more efficient, readable, and maintainable code. Whether you're managing a to-do list, a playlist, or any other dynamic collection, lists are the go-to solution.
+ +So, dive into the world of lists, experiment with their features, and unlock the full potential of your C++ programming skills. Happy coding, and may your lists always be efficiently managed and dynamically sized!
\ No newline at end of file diff --git a/docs/intermediate/cpp_stl/cpp_sets.md b/docs/intermediate/cpp_stl/cpp_sets.md new file mode 100644 index 0000000..3a254d7 --- /dev/null +++ b/docs/intermediate/cpp_stl/cpp_sets.md @@ -0,0 +1,317 @@ +--- +id: cpp-set +title: C++ Sets +sidebar_label: CPP STL +tags: + - dsa + - data-structures + - cpp + - intermediate + - stl + - standard template library + - cpp stl + - programming + - tutorial + - sets + - cpp set +sidebar_position: 4 +--- + +# Exploring Sets in C++: The Ultimate Guide + +Hello, C++ enthusiasts! Today, we're diving into one of the most powerful and unique components of the C++ Standard Template Library (STL): the `set`. If you're looking to enhance your understanding and utilization of sets in C++, you're in the right place. This guide will cover everything you need to know about sets, from basic usage to advanced features, complete with examples and practical applications. + +## What is a Set? + +In C++, a `set` is a container that stores unique elements in a specific order. The elements are stored in a balanced binary search tree, which allows sets to offer fast search, insertion, and deletion operations. + +### Why Use Sets? + +1. **Unique Elements**: Sets automatically ensure that all elements are unique, which can be useful for preventing duplicates. +2. **Automatic Ordering**: Elements in a set are stored in a specific order, usually ascending. +3. **Efficient Operations**: Sets provide efficient search, insertion, and deletion operations, typically in O(log n) time complexity. + +## Basics of Sets + +Let’s start with the basics of creating and using sets in C++. + +### Creating a Set + +To use sets, you need to include the `` header. + +```cpp +#include +#include + +int main() { + std::set numbers; // Creates an empty set of integers + std::set numbers_with_initial_values = {1, 2, 3, 4, 5}; // Creates a set with initial values + + return 0; +} +``` + +### Adding and Accessing Elements + +You can add elements to a set using the `insert` method. Sets do not support direct access by index, but you can use iterators. + +```cpp +#include +#include + +int main() { + std::set numbers; + numbers.insert(1); // Adds 1 to the set + numbers.insert(2); // Adds 2 to the set + numbers.insert(2); // Adding 2 again has no effect because sets store unique elements + + std::cout << "Elements in the set:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Iterating Over a Set + +You can iterate over the elements of a set using a range-based for loop or iterators. + +```cpp +#include +#include + +int main() { + std::set numbers = {1, 2, 3, 4, 5}; + + std::cout << "Using range-based for loop:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + std::cout << "Using iterators:" << std::endl; + for (auto it = numbers.begin(); it != numbers.end(); ++it) { + std::cout << *it << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +## Advanced Set Features + +Now that we've covered the basics, let's explore some advanced features and techniques for using sets in C++. + +### Checking for Elements + +You can check if an element exists in a set using the `find` method or the `count` method. + +```cpp +#include +#include + +int main() { + std::set numbers = {1, 2, 3, 4, 5}; + + int element = 3; + if (numbers.find(element) != numbers.end()) { + std::cout << element << " is in the set." << std::endl; + } else { + std::cout << element << " is not in the set." << std::endl; + } + + element = 6; + if (numbers.count(element) > 0) { + std::cout << element << " is in the set." << std::endl; + } else { + std::cout << element << " is not in the set." << std::endl; + } + + return 0; +} +``` + +### Erasing Elements + +You can remove elements from a set using the `erase` method. + +```cpp +#include +#include + +int main() { + std::set numbers = {1, 2, 3, 4, 5}; + numbers.erase(3); // Removes the element 3 + + std::cout << "Set after erasing 3:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Using Custom Comparison Functions + +You can define a set with a custom comparison function to change the ordering of elements. + +```cpp +#include +#include + +struct DescendingOrder { + bool operator()(int a, int b) const { + return a > b; + } +}; + +int main() { + std::set numbers = {1, 2, 3, 4, 5}; + + std::cout << "Elements in the set (descending order):" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Union, Intersection, and Difference of Sets + +You can perform set operations like union, intersection, and difference using standard algorithms. + +```cpp +#include +#include +#include +#include + +int main() { + std::set set1 = {1, 2, 3, 4, 5}; + std::set set2 = {4, 5, 6, 7, 8}; + + // Union of sets + std::set union_set; + std::set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(union_set, union_set.begin())); + + std::cout << "Union of sets:" << std::endl; + for (int num : union_set) { + std::cout << num << " "; + } + std::cout << std::endl; + + // Intersection of sets + std::set intersection_set; + std::set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(intersection_set, intersection_set.begin())); + + std::cout << "Intersection of sets:" << std::endl; + for (int num : intersection_set) { + std::cout << num << " "; + } + std::cout << std::endl; + + // Difference of sets + std::set difference_set; + std::set_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(difference_set, difference_set.begin())); + + std::cout << "Difference of sets:" << std::endl; + for (int num : difference_set) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +## Practical Applications of Sets + +Sets are not just theoretical constructs; they are immensely practical and can be used in various scenarios to solve real-world problems. + +### Problem 1: Removing Duplicates + +Imagine you have a list of numbers with duplicates, and you want to remove the duplicates while preserving the order. Sets are ideal for this scenario because they store unique elements. + +```cpp +#include +#include +#include + +int main() { + std::vector numbers = {1, 2, 2, 3, 4, 4, 5}; + std::set unique_numbers(numbers.begin(), numbers.end()); + + std::cout << "Unique numbers:" << std::endl; + for (int num : unique_numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Problem 2: Finding Common Elements + +Suppose you have two lists of numbers, and you want to find the common elements between them. Sets are perfect for this due to their efficient search operations. + +```cpp +#include +#include +#include + +int main() { + std::vector list1 = {1, 2, 3, 4, 5}; + std::vector list2 = {4, 5, 6, 7, 8}; + + std::set set1(list1.begin(), list1.end()); + std::set set2(list2.begin(), list2.end()); + + std::vector common_elements; + std::set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), std::back_inserter(common_elements)); + + std::cout << "Common elements:" << std::endl; + for (int num : common_elements) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Problem 3: Fast Lookups + +If you need to perform frequent lookups to check the existence of elements, sets provide an efficient solution due to their logarithmic time complexity for search operations. + +```cpp +#include +#include + +int main() { + std::set numbers = {1, 2, 3, 4, 5}; + + int element_to_find = 3; + if (numbers.find(element_to_find) != numbers.end()) { + std::cout << element_to_find << " is in the set." << std::endl; + } else { + std::cout << element_to_find << " is not in the set." << std::endl; + } + + return 0; +} +``` + +## In Conclusion + +Sets are a powerful and flexible component of the C++ Standard Template Library, offering efficient search, insertion, and deletion operations while ensuring unique elements and automatic ordering. By mastering sets, you can write more efficient, readable, and maintainable code. Whether you're removing duplicates, finding common elements, or performing fast lookups, sets are the go-to solution.
+ +So, dive into the world of sets, experiment with their features, and unlock the full potential of your C++ programming skills. Happy coding, and may your sets always be uniquely ordered and efficiently managed! \ No newline at end of file diff --git a/docs/intermediate/cpp_stl/cpp_sort.md b/docs/intermediate/cpp_stl/cpp_sort.md new file mode 100644 index 0000000..69e8e87 --- /dev/null +++ b/docs/intermediate/cpp_stl/cpp_sort.md @@ -0,0 +1,334 @@ +--- +id: cpp-sort +title: The Sort Algorithm in C++ +sidebar_label: CPP STL +tags: + - dsa + - data-structures + - cpp + - intermediate + - stl + - standard template library + - cpp stl + - programming + - tutorial + - sort algorithm + - cpp sort +sidebar_position: 6 +--- + +# Mastering the sort Algorithm in C++: A Comprehensive Guide + +Hello, C++ enthusiasts! Today, we’re diving into one of the most fundamental and powerful components of the C++ Standard Library: the `sort` algorithm. If you're looking to enhance your understanding and utilization of sorting in C++, you're in the right place. This guide will cover everything you need to know about the `sort` algorithm, from basic usage to advanced features, complete with examples and practical applications. + +## What is the `sort` Algorithm? + +The `sort` algorithm is a built-in function in the C++ Standard Library that allows you to sort elements in a range, typically specified by two iterators. It is part of the `` header and uses a highly efficient sorting algorithm, typically an introspective sort, which is a hybrid of quicksort, heapsort, and insertion sort. + +### Why Use the `sort` Algorithm? + +1. **Efficiency**: The `sort` algorithm is optimized for performance and typically runs in O(n log n) time complexity. +2. **Convenience**: It is easy to use and reduces the amount of boilerplate code needed to implement sorting. +3. **Flexibility**: The `sort` algorithm can be customized with comparison functions to define custom sorting orders. + +## Basics of the `sort` Algorithm + +Let’s start with the basics of using the `sort` algorithm in C++. + +### Including the Header + +To use the `sort` algorithm, you need to include the `` header. + +```cpp +#include +#include +#include +``` + +### Basic Usage + +The `sort` algorithm requires two iterators: one pointing to the beginning of the range and the other pointing to the end. + +```cpp +#include +#include +#include + +int main() { + std::vector numbers = {5, 3, 1, 4, 2}; + std::sort(numbers.begin(), numbers.end()); + + std::cout << "Sorted elements:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Custom Comparison Function + +You can customize the sorting order by providing a comparison function. + +```cpp +#include +#include +#include + +bool descending(int a, int b) { + return a > b; +} + +int main() { + std::vector numbers = {5, 3, 1, 4, 2}; + std::sort(numbers.begin(), numbers.end(), descending); + + std::cout << "Sorted elements in descending order:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +## Advanced Features + +Now that we've covered the basics, let's explore some advanced features and techniques for using the `sort` algorithm in C++. + +### Sorting Structures + +You can sort a vector of structures or classes by defining a custom comparison function or by overloading the comparison operators. + +Example with Custom Comparison Function: + +```cpp +#include +#include +#include + +struct Person { + std::string name; + int age; +}; + +bool compareByAge(const Person &a, const Person &b) { + return a.age < b.age; +} + +int main() { + std::vector people = {{"Alice", 30}, {"Bob", 25}, {"Charlie", 35}}; + std::sort(people.begin(), people.end(), compareByAge); + + std::cout << "People sorted by age:" << std::endl; + for (const Person &p : people) { + std::cout << p.name << ": " << p.age << std::endl; + } + + return 0; +} +``` + +Example with Overloaded Operators: + +```cpp +#include +#include +#include + +struct Person { + std::string name; + int age; + + bool operator<(const Person &other) const { + return age < other.age; + } +}; + +int main() { + std::vector people = {{"Alice", 30}, {"Bob", 25}, {"Charlie", 35}}; + std::sort(people.begin(), people.end()); + + std::cout << "People sorted by age:" << std::endl; + for (const Person &p : people) { + std::cout << p.name << ": " << p.age << std::endl; + } + + return 0; +} +``` + +### Sorting with Lambdas + +Lambdas provide a concise way to define custom comparison functions. + +```cpp +#include +#include +#include + +int main() { + std::vector numbers = {5, 3, 1, 4, 2}; + std::sort(numbers.begin(), numbers.end(), [](int a, int b) { + return a > b; // Sort in descending order + }); + + std::cout << "Sorted elements in descending order using lambda:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Partial Sorting + +If you only need the top N elements sorted, you can use `std::partial_sort`. + +```cpp +#include +#include +#include + +int main() { + std::vector numbers = {5, 3, 1, 4, 2}; + std::partial_sort(numbers.begin(), numbers.begin() + 3, numbers.end()); + + std::cout << "Top 3 sorted elements:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Sorting Specific Ranges + +You can sort only a part of a container by specifying the range with iterators. + +```cpp +#include +#include +#include + +int main() { + std::vector numbers = {5, 3, 1, 4, 2, 6, 8, 7}; + std::sort(numbers.begin() + 2, numbers.begin() + 6); + + std::cout << "Partially sorted elements (index 2 to 5):" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +## Practical Applications of the `sort` Algorithm + +The `sort` algorithm is not just a theoretical construct; it is immensely practical and can be used in various scenarios to solve real-world problems. + +### Problem 1: Sorting a List of Names + +You have a list of names, and you want to sort them alphabetically. + +```cpp +#include +#include +#include +#include + +int main() { + std::vector names = {"Charlie", "Alice", "Bob"}; + std::sort(names.begin(), names.end()); + + std::cout << "Sorted names:" << std::endl; + for (const std::string &name : names) { + std::cout << name << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Problem 2: Sorting by Multiple Criteria + +You have a list of students with names and grades, and you want to sort them first by grade, then by name. + +```cpp +#include +#include +#include +#include + +struct Student { + std::string name; + int grade; +}; + +bool compareStudents(const Student &a, const Student &b) { + if (a.grade == b.grade) { + return a.name < b.name; + } + return a.grade > b.grade; // Higher grades first +} + +int main() { + std::vector students = {{"Charlie", 85}, {"Alice", 95}, {"Bob", 85}, {"Dave", 70}}; + std::sort(students.begin(), students.end(), compareStudents); + + std::cout << "Sorted students:" << std::endl; + for (const Student &student : students) { + std::cout << student.name << ": " << student.grade << std::endl; + } + + return 0; +} +``` + +### Problem 3: Sorting a Custom Data Structure + +You have a custom data structure, and you want to sort it based on a specific member variable. + +```cpp +#include +#include +#include +#include + +struct Book { + std::string title; + int year; +}; + +bool compareByYear(const Book &a, const Book &b) { + return a.year < b.year; +} + +int main() { + std::vector books = {{"C++ Primer", 2012}, {"Effective C++", 2005}, {"The C++ Programming Language", 2013}}; + std::sort(books.begin(), books.end(), compareByYear); + + std::cout << "Books sorted by year:" << std::endl; + for (const Book &book : books) { + std::cout << book.title << ": " << book.year << std::endl; + } + + return 0; +} +``` + +# In Conclusion + +The sort algorithm is a powerful and versatile tool in the C++ Standard Library, offering efficient and flexible sorting capabilities. By mastering the sort algorithm, you can write more efficient, readable, and maintainable code. Whether you're sorting simple arrays, complex data structures, or using custom comparison functions, the sort algorithm is the go-to solution.
+ +So, dive into the world of sorting, experiment with the sort algorithm, and unlock the full potential of your C++ programming skills. Happy coding, and may your sorted arrays always be in the right order! \ No newline at end of file diff --git a/docs/intermediate/cpp_stl/cpp_stl_basics.md b/docs/intermediate/cpp_stl/cpp_stl_basics.md new file mode 100644 index 0000000..66460d1 --- /dev/null +++ b/docs/intermediate/cpp_stl/cpp_stl_basics.md @@ -0,0 +1,224 @@ +--- +id: cpp-stl-basics +title: The Basics of C++ STL +sidebar_label: CPP STL +tags: + - dsa + - data-structures + - cpp + - intermediate + - stl + - standard template library + - cpp stl + - programming + - tutorial +sidebar_position: 1 +--- + +# Unlocking the Power of C++: A Journey Through the Standard Template Library (STL) + +Greetings, aspiring C++ wizards and seasoned coders alike! Today, we embark on an exciting journey through the magical realm of the C++ Standard Template Library, or STL. This powerful toolkit is the secret weapon in every C++ programmer's arsenal, offering a treasure trove of pre-written code that can make solving data structure and algorithm problems a breeze. So, grab your wand (or keyboard), and let’s dive into the world of STL, where efficiency meets elegance in C++ programming. + +## What is the C++ Standard Template Library (STL)? + +The C++ Standard Template Library (STL) is a powerful library of generic classes and functions that greatly enhances the capabilities of C++. It provides standardized ways to manipulate data, offering a wide array of algorithms, iterators, and containers that can be used to solve complex problems with ease. + +### Why is STL Important? + +1. **Efficiency**: STL provides highly optimized implementations of common data structures and algorithms, saving you time and effort. +2. **Reusability**: By using STL, you can avoid reinventing the wheel, allowing you to focus on solving the problem at hand rather than coding basic functionalities. +3. **Portability**: STL is part of the C++ standard, ensuring that your code is portable and can run on any platform with a standard-compliant compiler. + +## The Building Blocks of STL + +STL is composed of several key components: containers, iterators, algorithms, and functors. Let’s explore each of these elements and see how they can be used to simplify your coding life. + +### 1. Containers + +Containers are data structures that store collections of objects. STL offers several types of containers, each designed for specific use cases. + +#### a. Vector + +A `vector` is a dynamic array that can grow and shrink in size. It provides fast random access and is ideal for situations where you need a resizable array. + +```cpp +#include +#include + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + numbers.push_back(6); // Add an element at the end + for (int num : numbers) { + std::cout << num << " "; + } + return 0; +} +``` + +#### b. List + +A `list` is a doubly linked list that allows fast insertions and deletions from anywhere in the sequence. + +```cpp +#include +#include + +int main() { + std::list numbers = {1, 2, 3, 4, 5}; + numbers.push_back(6); // Add an element at the end + numbers.push_front(0); // Add an element at the beginning + for (int num : numbers) { + std::cout << num << " "; + } + return 0; +} +``` + +#### c. Set + +A `set` is a collection of unique elements, sorted by default. + +```cpp +#include +#include + +int main() { + std::set numbers = {4, 1, 3, 2, 5}; + numbers.insert(6); // Add an element + for (int num : numbers) { + std::cout << num << " "; + } + return 0; +} +``` + +### 2. Iterators + +Iterators are objects that point to elements within a container. They provide a way to access and traverse container elements. + +```cpp +#include +#include + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + for (auto it = numbers.begin(); it != numbers.end(); ++it) { + std::cout << *it << " "; + } + return 0; +} +``` + +### 3. Algorithms + +STL provides a plethora of algorithms for performing operations on containers, such as searching, sorting, and manipulating elements. + +#### a. Sort + +```cpp +#include +#include +#include + +int main() { + std::vector numbers = {5, 3, 1, 4, 2}; + std::sort(numbers.begin(), numbers.end()); // Sort in ascending order + for (int num : numbers) { + std::cout << num << " "; + } + return 0; +} +``` + +#### b. Find + +```cpp +#include +#include +#include + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + auto it = std::find(numbers.begin(), numbers.end(), 3); + if (it != numbers.end()) { + std::cout << "Found: " << *it << std::endl; + } else { + std::cout << "Not found" << std::endl; + } + return 0; +} +``` + +### 4. Functors + +Functors, or function objects, are objects that can be called as though they are functions. They are used to pass behavior to algorithms. + +```cpp +#include +#include +#include + +struct MultiplyByTwo { + void operator()(int &n) { n *= 2; } +}; + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + std::for_each(numbers.begin(), numbers.end(), MultiplyByTwo()); + for (int num : numbers) { + std::cout << num << " "; + } + return 0; +} +``` + +## Practical Applications of STL + +### Problem 1: Sorting a List of Names + +Imagine you have a list of names that you need to sort alphabetically. Using STL, this task is straightforward. + +```cpp +#include +#include +#include + +int main() { + std::vector names = {"Alice", "Bob", "Charlie", "Dave"}; + std::sort(names.begin(), names.end()); + for (const auto& name : names) { + std::cout << name << " "; + } + return 0; +} +``` + +### Problem 2: Finding the Frequency of Elements + +Suppose you need to find out how many times each element appears in a list. This can be efficiently done using `map`. + +```cpp +#include +#include +#include + +int main() { + std::vector numbers = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4}; + std::map frequency; + for (int num : numbers) { + frequency[num]++; + } + for (const auto& pair : frequency) { + std::cout << pair.first << ": " << pair.second << " times" << std::endl; + } + return 0; +} +``` + +## In Conclusion + +The C++ Standard Template Library is an invaluable resource for any C++ programmer. By providing a rich set of containers, iterators, algorithms, and functors, STL allows you to write efficient and concise code, making your development process smoother and more enjoyable.
+ +Whether you are sorting a list, searching for an element, or performing complex operations on data, STL has got you covered. So, dive in, explore the wonders of STL, and let your C++ coding experience be as magical and powerful as a wizard's spellbook.
+ +Happy coding, and may your algorithms always be efficient!
\ No newline at end of file diff --git a/docs/intermediate/cpp_stl/cpp_vectors.md b/docs/intermediate/cpp_stl/cpp_vectors.md new file mode 100644 index 0000000..8c59919 --- /dev/null +++ b/docs/intermediate/cpp_stl/cpp_vectors.md @@ -0,0 +1,275 @@ +--- +id: cpp-vector +title: C++ Vectors +sidebar_label: CPP STL +tags: + - dsa + - data-structures + - cpp + - intermediate + - stl + - standard template library + - cpp stl + - programming + - tutorial + - vectors +sidebar_position: 2 +--- + +# Exploring Vectors in C++: The Ultimate Guide + +Welcome back, C++ enthusiasts! Today, we're going to take a deep dive into one of the most versatile and widely used components of the C++ Standard Template Library (STL): the `vector`. If you’re looking to enhance your understanding and utilization of vectors in C++, you’re in the right place. This guide will cover everything you need to know about vectors, from basic usage to advanced features, complete with examples and practical applications. + +## What is a Vector? + +In C++, a `vector` is a dynamic array that can resize itself automatically when an element is added or removed. Unlike standard arrays, vectors provide flexibility and a host of functionalities that make managing collections of data more efficient. + +### Why Use Vectors? + +1. **Dynamic Sizing**: Vectors can grow and shrink dynamically, which makes them more versatile than arrays. +2. **Ease of Use**: Vectors come with built-in functions for common operations like insertion, deletion, and access. +3. **Efficiency**: Vectors are optimized for performance, offering constant-time complexity for element access and amortized constant time for insertion at the end. + +## Basics of Vectors + +Let’s start with the basics of creating and using vectors in C++. + +### Creating a Vector + +To use vectors, you need to include the `` header. + +```cpp +#include +#include + +int main() { + std::vector numbers; // Creates an empty vector of integers + std::vector numbers_with_initial_size(10); // Creates a vector with 10 elements initialized to 0 + std::vector numbers_with_initial_values(10, 5); // Creates a vector with 10 elements initialized to 5 + + return 0; +} +``` + +### Adding and Accessing Elements + +You can add elements to a vector using `push_back`, and access them using the `[]` operator or the `at` method. + +```cpp +#include +#include + +int main() { + std::vector numbers; + numbers.push_back(1); // Adds 1 to the vector + numbers.push_back(2); // Adds 2 to the vector + + std::cout << "First element: " << numbers[0] << std::endl; // Accesses the first element + std::cout << "Second element: " << numbers.at(1) << std::endl; // Accesses the second element using at() + + return 0; +} +``` + +### Iterating Over a Vector + +You can iterate over the elements of a vector using a range-based for loop or iterators. + +```cpp +#include +#include + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + + std::cout << "Using range-based for loop:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + std::cout << "Using iterators:" << std::endl; + for (auto it = numbers.begin(); it != numbers.end(); ++it) { + std::cout << *it << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +## Advanced Vector Features + +Now that we've covered the basics, let's explore some advanced features and techniques for using vectors in C++. + +### Resizing a Vector + +You can resize a vector using the `resize` method, which adjusts the size of the vector. + +```cpp +#include +#include + +int main() { + std::vector numbers = {1, 2, 3}; + numbers.resize(5); // Resizes the vector to contain 5 elements + + std::cout << "Vector after resizing:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Inserting and Erasing Elements + +You can insert and erase elements at any position using the `insert` and `erase` methods. + +```cpp +#include +#include + +int main() { + std::vector numbers = {1, 2, 4, 5}; + auto it = numbers.begin() + 2; + numbers.insert(it, 3); // Inserts 3 at the third position + + std::cout << "Vector after insertion:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + numbers.erase(it); // Erases the element at the third position + + std::cout << "Vector after erasing:" << std::endl; + for (int num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Capacity and Size + +Vectors provide several methods to manage and query their capacity and size. + +```cpp +#include +#include + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + + std::cout << "Size: " << numbers.size() << std::endl; // Number of elements + std::cout << "Capacity: " << numbers.capacity() << std::endl; // Capacity of the vector + std::cout << "Is empty: " << (numbers.empty() ? "Yes" : "No") << std::endl; // Check if vector is empty + + numbers.reserve(10); // Increase the capacity of the vector to at least 10 + + std::cout << "Capacity after reserve: " << numbers.capacity() << std::endl; + + return 0; +} +``` + +### Swapping Vectors + +You can `swap` the contents of two vectors using the swap method, which is useful for optimizing performance. + +```cpp +#include +#include + +int main() { + std::vector numbers1 = {1, 2, 3}; + std::vector numbers2 = {4, 5, 6}; + + numbers1.swap(numbers2); + + std::cout << "numbers1 after swap:" << std::endl; + for (int num : numbers1) { + std::cout << num << " "; + } + std::cout << std::endl; + + std::cout << "numbers2 after swap:" << std::endl; + for (int num : numbers2) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +## Practical Applications of Vectors + +Vectors are not just theoretical constructs; they are immensely practical and can be used in various scenarios to solve real-world problems. + +### Problem 1: Storing Dynamic User Input + +Imagine you are developing a program that collects an unknown number of user inputs. Vectors are ideal for this scenario because they can dynamically grow as needed. + +```cpp +#include +#include + +int main() { + std::vector inputs; + int input; + + std::cout << "Enter numbers (enter -1 to stop):" << std::endl; + while (std::cin >> input && input != -1) { + inputs.push_back(input); + } + + std::cout << "You entered:" << std::endl; + for (int num : inputs) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +### Problem 2: Performing Operations on a List of Numbers + +Vectors are perfect for storing and manipulating lists of numbers, such as calculating the average or finding the maximum value. + +```cpp +#include +#include +#include // For std::accumulate + +int main() { + std::vector numbers = {1, 2, 3, 4, 5}; + + // Calculate the sum + int sum = std::accumulate(numbers.begin(), numbers.end(), 0); + + // Calculate the average + double average = static_cast(sum) / numbers.size(); + + // Find the maximum value + int max_value = *std::max_element(numbers.begin(), numbers.end()); + + std::cout << "Sum: " << sum << std::endl; + std::cout << "Average: " << average << std::endl; + std::cout << "Max value: " << max_value << std::endl; + + return 0; +} +``` + +## In Conclusion + +Vectors are a cornerstone of the C++ Standard Template Library, providing a dynamic and flexible way to handle collections of data. By mastering vectors, you can write more efficient, readable, and maintainable code. Whether you're dealing with dynamic user input, performing complex calculations, or simply managing a list of items, vectors are the go-to solution.
+ +So, dive into the world of vectors, experiment with their features, and unlock the full potential of your C++ programming skills. Happy coding, and may your vectors always be well-sized and efficiently managed! \ No newline at end of file diff --git a/docs/intermediate/graph.png b/docs/intermediate/graph.png new file mode 100644 index 0000000..817c20f Binary files /dev/null and b/docs/intermediate/graph.png differ diff --git a/docs/intermediate/image-1.png b/docs/intermediate/image-1.png new file mode 100644 index 0000000..3588938 Binary files /dev/null and b/docs/intermediate/image-1.png differ diff --git a/docs/intermediate/image-2.png b/docs/intermediate/image-2.png new file mode 100644 index 0000000..acbbe2d Binary files /dev/null and b/docs/intermediate/image-2.png differ diff --git a/docs/intermediate/image-3.png b/docs/intermediate/image-3.png new file mode 100644 index 0000000..1d60329 Binary files /dev/null and b/docs/intermediate/image-3.png differ diff --git a/docs/intermediate/image-4.png b/docs/intermediate/image-4.png new file mode 100644 index 0000000..ac7c7e6 Binary files /dev/null and b/docs/intermediate/image-4.png differ diff --git a/docs/intermediate/image.png b/docs/intermediate/image.png new file mode 100644 index 0000000..ed3a3bd Binary files /dev/null and b/docs/intermediate/image.png differ diff --git a/docs/intermediate/monotonic-stack.md b/docs/intermediate/monotonic-stack.md new file mode 100644 index 0000000..78d9fe1 --- /dev/null +++ b/docs/intermediate/monotonic-stack.md @@ -0,0 +1,202 @@ +--- +id: monotonic-stack +title: Monotonic Stack in Data Structures and Algorithms +sidebar_label: Monotonic Stack +tags: + - dsa + - data-structures + - stack + - monotonic-stack + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial + - typescript +sidebar_position: 5 +--- + +In this tutorial, we will delve into the concept of a monotonic stack in Data Structures and Algorithms. We'll explore what a monotonic stack is, how it works, and its applications. + +## Monotonic Stack in Data Structures and Algorithms + +A monotonic stack, also known as a monotone stack or an increasing/decreasing stack, is a variation of the stack data structure that maintains either monotonic increasing or monotonic decreasing order of its elements. + +### Characteristics + +- **Monotonicity**: The key characteristic of a monotonic stack is that the elements are either monotonically increasing or monotonically decreasing. +- **Single Direction**: Unlike a regular stack, where elements can be pushed and popped in any order, a monotonic stack enforces a single direction of monotonicity. +- **Optimization**: Monotonic stacks are often used to optimize certain problems by efficiently identifying elements that are greater (or smaller) than the current element. + +![monotonic stack](https://storage.googleapis.com/download/storage/v1/b/designgurus-prod.appspot.com/o/docImages%2F64beb1e31a5d38cdee24dfde%2Fimg:c7f05bb-0214-28ff-ec31-a04c2270158e.svg?generation=1690366276715884&alt=media) +### Operations + +A monotonic stack typically supports the following operations: + +- **Push**: Adds an element to the stack while maintaining monotonicity. +- **Pop**: Removes and returns the top element of the stack. +- **Peek**: Returns the top element of the stack without removing it. +- **isEmpty**: Checks if the stack is empty. +- **Size**: Returns the number of elements in the stack. + +### Applications + +Monotonic stacks find applications in various algorithms and problems, including but not limited to: + +- **Finding Next Greater/Smaller Element**: Monotonic stacks can efficiently find the next greater or smaller element for each element in an array. +- **Largest Rectangle in Histogram**: They are used to solve the problem of finding the largest rectangle in a histogram efficiently. +- **Finding the Nearest Smaller Element**: Monotonic stacks can determine the nearest smaller element for each element in an array. +- **Maximal Rectangles in Binary Matrix**: Used in algorithms to find the maximal rectangles in a binary matrix. + +Now, let's see an example implementation of a monotonic stack in various programming languages. + + + + ```javascript + function monotonicStack(arr) { + const stack = []; + const result = []; + + for (let i = 0; i < arr.length; i++) { + while (stack.length && arr[i] < arr[stack[stack.length - 1]]) { + result[stack.pop()] = arr[i]; + } + stack.push(i); + } + + while (stack.length) { + result[stack.pop()] = -1; + } + + return result; + } + + // Example usage + const arr = [2, 1, 4, 3, 6, 5, 8, 7]; + const nextSmallerElements = monotonicStack(arr); + console.log("Next Smaller Elements:", nextSmallerElements); + ``` + + + + ```python + def monotonic_stack(arr): + stack = [] + result = [-1] * len(arr) + + for i in range(len(arr)): + while stack and arr[i] < arr[stack[-1]]: + result[stack.pop()] = arr[i] + stack.append(i) + + return result + + # Example usage + arr = [2, 1, 4, 3, 6, 5, 8, 7] + next_smaller_elements = monotonic_stack(arr) + print("Next Smaller Elements:", next_smaller_elements) + ``` + + + + ```typescript + function monotonicStack(arr: number[]): number[] { + const stack: number[] = []; + const result: number[] = new Array(arr.length).fill(-1); + + for (let i = 0; i < arr.length; i++) { + while (stack.length && arr[i] < arr[stack[stack.length - 1]]) { + result[stack.pop()!] = arr[i]; + } + stack.push(i); + } + + return result; + } + + // Example usage + const arr: number[] = [2, 1, 4, 3, 6, 5, 8, 7]; + const nextSmallerElements: number[] = monotonicStack(arr); + console.log("Next Smaller Elements:", nextSmallerElements); + ``` + + + + ```cpp + #include + #include + #include + using namespace std; + + vector monotonicStack(vector& arr) { + stack st; + vector result(arr.size(), -1); + + for (int i = 0; i < arr.size(); i++) { + while (!st.empty() && arr[i] < arr[st.top()]) { + result[st.top()] = arr[i]; + st.pop(); + } + st.push(i); + } + + return result; + } + + int main() { + // Example usage + vector arr = {2, 1, 4, 3, 6, 5, 8, 7}; + vector nextSmallerElements = monotonicStack(arr); + cout << "Next Smaller Elements: "; + for (int num : nextSmallerElements) { + cout << num << " "; + } + cout << endl; + return 0; + } + ``` + + + + ```java + import java.util.*; + + public class Main { + // Implementing a monotonic stack in Java + public static int[] monotonicStack(int[] arr) { + Stack stack = new Stack<>(); + int[] result = new int[arr.length]; + Arrays.fill(result, -1); + + for (int i = 0; i < arr.length; i++) { + while (!stack.isEmpty() && arr[i] < arr[stack.peek()]) { + result[stack.pop()] = arr[i]; + } + stack.push(i); + } + + return result; + } + + public static void main(String[] args) { + // Example usage + int[] arr = {2, 1, 4, 3, 6, 5, 8, 7}; + int[] nextSmallerElements = monotonicStack(arr); + System.out.print("Next Smaller Elements: "); + for (int num : nextSmallerElements) { + System.out.print(num + " "); + } + System.out.println(); + } + } + ``` + + + + +## Conclusion + +In this tutorial, we explored the concept of a monotonic stack in Data Structures and Algorithms. We discussed its characteristics, operations, and applications. Additionally, we provided example implementations of a monotonic stack in JavaScript, Python, TypeScript, C++, and Java. Monotonic stacks offer a powerful tool for solving various algorithmic problems efficiently by maintaining monotonicity of elements. +``` \ No newline at end of file diff --git a/docs/intermediate/priority-queue.md b/docs/intermediate/priority-queue.md new file mode 100644 index 0000000..6909855 --- /dev/null +++ b/docs/intermediate/priority-queue.md @@ -0,0 +1,330 @@ +--- +id: priority-queue +title: Priority Queue in Data Structures and Algorithms +sidebar_label: Priority Queue +tags: + - dsa + - data-structures + - priority-queue + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial + - typescript +sidebar_position: 2 +--- +In this tutorial, we'll explore priority queues in Data Structures and Algorithms. We'll discuss what priority queues are, how they're used, and how to implement them in various programming languages. + +## Priority Queue in Data Structures and Algorithms +![Priority Queue](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDIjnd49L65sMTGqPmBiVyau1KmDuYe4po_Q&s) + +A priority queue is a data structure similar to a regular queue or stack, but each element has an associated priority. Elements with higher priorities are dequeued before elements with lower priorities. Priority queues are commonly used in scenarios where elements need to be processed based on their importance or urgency. + +A priority queue supports the following operations: + +1. **Insertion**: Adds an element to the priority queue with its associated priority. +2. **Deletion**: Removes and returns the element with the highest priority from the priority queue. +3. **Peek**: Returns the element with the highest priority without removing it. +4. **isEmpty**: Checks if the priority queue is empty. +5. **Size**: Returns the number of elements in the priority queue. +6. **Clear**: Removes all elements from the priority queue. + +Additionally, priority queues may support other operations such as searching, updating priorities, merging, and iterating. + +Here's an example of a priority queue in some programming languages: + + + + ```javascript + + class PriorityQueue { + constructor() { + this.items = []; + } + + // Insertion operation + enqueue(element, priority) { + const queueElement = { element, priority }; + let added = false; + for (let i = 0; i < this.items.length; i++) { + if (queueElement.priority < this.items[i].priority) { + this.items.splice(i, 0, queueElement); + added = true; + break; + } + } + if (!added) { + this.items.push(queueElement); + } + } + + // Deletion operation + dequeue() { + if (this.isEmpty()) { + return "Underflow"; + } + return this.items.shift().element; + } + + // Peek operation + peek() { + if (this.isEmpty()) { + return "Queue is empty"; + } + return this.items[0].element; + } + + // isEmpty operation + isEmpty() { + return this.items.length === 0; + } + + // Size operation + size() { + return this.items.length; + } + + // Clear operation + clear() { + this.items = []; + } + + // Print operation + print() { + console.log(this.items); + } + } + + let priorityQueue = new PriorityQueue(); + priorityQueue.enqueue("Task 1", 2); + priorityQueue.enqueue("Task 2", 1); + priorityQueue.enqueue("Task 3", 3); + priorityQueue.print(); // Output: [{ element: 'Task 2', priority: 1 }, { element: 'Task 1', priority: 2 }, { element: 'Task 3', priority: 3 }] + console.log(priorityQueue.dequeue()); // Output: Task 2 + console.log(priorityQueue.peek()); // Output: Task 1 + console.log(priorityQueue.isEmpty()); // Output: false + console.log(priorityQueue.size()); // Output: 2 + priorityQueue.clear(); + priorityQueue.print(); // Output: [] + ``` + + + + ```python + from queue import PriorityQueue + + # Using the priority queue + priorityQueue = PriorityQueue() + priorityQueue.put((2, "Task 1")) + priorityQueue.put((1, "Task 2")) + priorityQueue.put((3, "Task 3")) + while not priorityQueue.empty(): + print(priorityQueue.get()[1], end=' ') # Output: Task 2 Task 1 Task 3 + ``` + + + + ```typescript + interface QueueElement { + element: T; + priority: number; + } + + class PriorityQueue { + private items: QueueElement[] = []; + + enqueue(element: T, priority: number): void { + const queueElement: QueueElement = { element, priority }; + let added = false; + for (let i = 0; i < this.items.length; i++) { + if (queueElement.priority < this.items[i].priority) { + this.items.splice(i, 0, queueElement); + added = true; + break; + } + if (!added) { + this.items.push(queueElement); + } + } + + // Deletion operation + dequeue(): T | string { + if (this.isEmpty()) { + return "Underflow"; + } + return this.items.shift()?.element; + } + + // Peek operation + peek(): T | string { + if (this.isEmpty()) { + return "Queue is empty"; + } + return this.items[0].element; + } + + // isEmpty operation + isEmpty(): boolean { + return this.items.length === 0; + } + + // Size operation + size(): number { + return this.items.length; + } + + // Clear operation + clear(): void { + this.items = []; + } + + // Print operation + print(): void { + console.log(this.items); + } + } + + // Using the priority queue + let priorityQueue = new PriorityQueue(); + priorityQueue.enqueue("Task 1", 2); + priorityQueue.enqueue("Task 2", 1); + priorityQueue.enqueue("Task 3", 3); + priorityQueue.print(); // Output: [{ element: 'Task 2', priority: 1 }, { element: 'Task 1', priority: 2 }, { element: 'Task 3', priority: 3 }] + console.log(priorityQueue.dequeue()); // Output: Task 2 + console.log(priorityQueue.peek()); // Output: Task 1 + console.log(priorityQueue.isEmpty()); // Output: false + console.log(priorityQueue.size()); // Output: 2 + priorityQueue.clear(); + priorityQueue.print(); // Output: [] + ``` + + + + ```cpp + #include + #include + #include + using namespace std; + + class PriorityQueue { + private: + priority_queue, vector>, greater>> pq; + + public: + // Insertion operation + void enqueue(string element, int priority) { + pq.push({priority, element}); + } + + // Deletion operation + string dequeue() { + if (isEmpty()) { + return "Underflow"; + } + string element = pq.top().second; + pq.pop(); + return element; + } + + // Peek operation + string peek() { + if (isEmpty()) { + return "Queue is empty"; + } + return pq.top().second; + } + + // isEmpty operation + bool isEmpty() { + return pq.empty(); + } + + // Size operation + int size() { + return pq.size(); + } + + // Clear operation + void clear() { + while (!pq.empty()) { + pq.pop(); + } + } + + // Print operation + void print() { + priority_queue, vector>, greater>> temp = pq; + while (!temp.empty()) { + cout << temp.top().second << " "; + temp.pop(); + } + cout << endl; + } + }; + + int main() { + PriorityQueue pq; + pq.enqueue("Task 1", 2); + pq.enqueue("Task 2", 1); + pq.enqueue("Task 3", 3); + pq.print(); // Output: Task 2 Task 1 Task 3 + cout << pq.dequeue() << endl; // Output: Task 2 + cout << pq.peek() << endl; // Output: Task 1 + cout << (pq.isEmpty() ? "true" : "false") << endl; // Output: false + cout << pq.size() << endl; // Output: 2 + pq.clear(); + pq.print(); // Output: + return 0; + } + ``` + + + + ```java + import java.util.PriorityQueue; + + public class Main { + public static void main(String[] args) { + // Creating a priority queue in Java + PriorityQueue priorityQueue = new PriorityQueue<>(); + + // Using the priority queue + priorityQueue.add("Task 1"); + priorityQueue.add("Task 2"); + priorityQueue.add("Task 3"); + + // Print operation + System.out.println(priorityQueue); // Output: [Task 1, Task 3, Task 2] + + // Deletion operation + priorityQueue.poll(); + System.out.println(priorityQueue); // Output: [Task 2, Task 3] + + // Peek operation + System.out.println(priorityQueue.peek()); // Output: Task 2 + + // isEmpty operation + System.out.println(priorityQueue.isEmpty()); // Output: false + + // Size operation + System.out.println(priorityQueue.size()); // Output: 2 + + // Clear operation + priorityQueue.clear(); + System.out.println(priorityQueue); // Output: [] + } + } + ``` + + + + +## Conclusion + +In this tutorial, we explored priority queues in Data Structures and Algorithms. We discussed their characteristics, operations, and provided implementations in JavaScript, Python, TypeScript, C++, and Java. Priority queues are valuable for managing elements based on their priorities, enabling efficient processing of high-priority tasks. Understanding priority queues can enhance your problem-solving skills in various domains. + +This comprehensive tutorial covers priority queues, including their operations and implementations in different programming languages. It serves as a valuable resource for understanding and utilizing priority queues effectively in your projects. + \ No newline at end of file diff --git a/docs/intermediate/sliding_window.md b/docs/intermediate/sliding_window.md new file mode 100644 index 0000000..99c7683 --- /dev/null +++ b/docs/intermediate/sliding_window.md @@ -0,0 +1,483 @@ +--- +id: 03-Sliding-Window +title: Sliding Window in Data Structures and Algorithms +sidebar_label: Sliding Window +tags: + - dsa + - data-structures + - priority-queue + - intermediate + - javascript + - python + - c++ + - java + - programming + - tutorial + - typescript +sidebar_position: 7 +--- + +# Sliding Window Technique + +Sliding Window problems are problems in which a fixed or variable-size window is moved through a data structure, typically an array or string, to solve problems efficiently based on continuous subsets of elements. This technique is used when we need to find subarrays or substrings according to a given set of conditions. + +## What is Sliding Window Technique? + +``` +Sliding Window Technique is a method used to efficiently solve problems that involve defining a window or range in the input data (arrays or strings) and then moving that window across the data to perform some operation within the window. This technique is commonly used in algorithms like finding subarrays with a specific sum, finding the longest substring with unique characters, or solving problems that require a fixed-size window to process elements efficiently. +``` + +Let’s take an example to understand this properly, say we have an array of size N and also an integer K. Now, we have to calculate the maximum sum of a subarray having size exactly K. Now how should we approach this problem? + +One way to do this by taking each subarray of size K from the array and find out the maximum sum of these subarrays. This can be done using Nested loops which will result into &O(N2)& Time Complexity. + +### But can we optimize this approach? + +The answer is Yes, instead of taking each K sized subarray and calculating its sum, we can just take one K size subarray from 0 to K-1 index and calculate its sum now shift our range one by one along with the iterations and update the result, like in next iteration increase the left and right pointer and update the previous sum as shown in the below image: + + ![alt text](image.png) + +Now follow this method for each iteration till we reach the end of the array: + + ![alt text](image-1.png) + +So, we can see that instead of recalculating the sum of each K sized subarray we are using previous window of size K and using its results we update the sum and shift the window right by moving left and right pointers, this operation is optimal because it take O(1) time to shift the range instead of recalculating. + +This approach of shifting the pointers and calculating the results accordingly is known as Sliding window Technique. + +## How to use Sliding Window Technique? + +There are basically two types of sliding window: + +#### 1. Fixed Size Sliding Window: + + The general steps to solve these questions by following below steps: + + a) Find the size of the window required, say K. + + b) Compute the result for 1st window, i.e. include the first K elements of the data structure. + + c) Then use a loop to slide the window by 1 and keep computing the result window by window. + +#### 2. Variable Size Sliding Window: + + The general steps to solve these questions by following below steps: + + a) In this type of sliding window problem, we increase our right pointer one by one till our condition is true. + + b) At any step if our condition does not match, we shrink the size of our window by increasing left pointer. + + c) Again, when our condition satisfies, we start increasing the right pointer and follow step 1. + We follow these steps until we reach to the end of the array. + +## How to Identify Sliding Window Problems: + +1. These problems generally require Finding Maximum/Minimum Subarray, Substrings which satisfy some specific condition. + +2. The size of the subarray or substring β€˜K’ will be given in some of the problems. + +3. These problems can easily be solved in $O(N2)$ time complexity using nested loops, using sliding window we can solve these in $O(n)$ Time Complexity. + +4. Required Time Complexity: $O(N)$ or $O(Nlog(N))$ + +5. Constraints: N `<=` 106 , If N is the size of the Array/String. + +## Use Cases of Sliding Window Technique: + +### Question 1 + +1. To find the maximum sum of all subarrays of size K: + +Given an array of integers of size β€˜n’, Our aim is to calculate the maximum sum of β€˜k’ consecutive elements in the array. + +``` +Input : arr[] = {100, 200, 300, 400}, k = 2 +Output : 700 + +Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}, k = 4 +Output : 39 +We get maximum sum by adding subarray {4, 2, 10, 23} of size 4. + +Input : arr[] = {2, 3}, k = 3 +Output : Invalid +There is no subarray of size 3 as size of whole array is 2. +``` + +### NaΓ―ve Approach: + +So, let’s analyze the problem with Brute Force Approach. We start with the first index and sum till the kth element. We do it for all possible consecutive blocks or groups of k elements. This method requires a nested for loop, the outer for loop starts with the starting element of the block of k elements, and the inner or the nested loop will add up till the kth element. + +Below is the implementation of the above approach: + + + + + ```cpp + #include + #include + using namespace std; + + // Returns maximum sum in a subarray of size k. + int maxSum(int arr[], int n, int k) { + // Initialize result + int max_sum = INT_MIN; + + // Consider all blocks starting with i. + for (int i = 0; i < n - k + 1; i++) { + int current_sum = 0; + for (int j = 0; j < k; j++) + current_sum = current_sum + arr[i + j]; + + // Update result if required. + max_sum = max(current_sum, max_sum); + } + + return max_sum; + } + + // Driver code + int main() { + int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; + int k = 4; + int n = sizeof(arr) / sizeof(arr[0]); + cout << maxSum(arr, n, k); + return 0; + } + ``` + + + + ```java + import java.util.*; + + public class Main { + // Returns maximum sum in a subarray of size k. + public static int maxSum(int[] arr, int n, int k) { + // Initialize result + int max_sum = Integer.MIN_VALUE; + + // Consider all blocks starting with i. + for (int i = 0; i < n - k + 1; i++) { + int current_sum = 0; + for (int j = 0; j < k; j++) + current_sum = current_sum + arr[i + j]; + + // Update result if required. + max_sum = Math.max(current_sum, max_sum); + } + + return max_sum; + } + + // Driver code + public static void main(String[] args) { + int[] arr = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; + int k = 4; + int n = arr.length; + System.out.println(maxSum(arr, n, k)); + } + } + ``` + + + + ```python + # Returns maximum sum in a subarray of size k. + def maxSum(arr, n, k): + # Initialize result + max_sum = float('-inf') + + # Consider all blocks starting with i. + for i in range(n - k + 1): + current_sum = 0 + for j in range(k): + current_sum += arr[i + j] + + # Update result if required. + max_sum = max(current_sum, max_sum) + + return max_sum + + # Driver code + arr = [1, 4, 2, 10, 2, 3, 1, 0, 20] + k = 4 + n = len(arr) + print(maxSum(arr, n, k)) + ``` + + + + ```c + #include + #include + + // Returns maximum sum in a subarray of size k. + int maxSum(int arr[], int n, int k) { + // Initialize result + int max_sum = INT_MIN; + + // Consider all blocks starting with i. + for (int i = 0; i < n - k + 1; i++) { + int current_sum = 0; + for (int j = 0; j < k; j++) + current_sum = current_sum + arr[i + j]; + + // Update result if required. + if (current_sum > max_sum) { + max_sum = current_sum; + } + } + + return max_sum; + } + + // Driver code + int main() { + int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; + int k = 4; + int n = sizeof(arr) / sizeof(arr[0]); + printf("%d\n", maxSum(arr, n, k)); + return 0; + } + ``` + + + + +Output: + +``` +24 +``` + +Time complexity: $O(k*n)$ as it contains two nested loops. +Auxiliary Space: $O(1)$ + +### Applying the sliding window technique: + + 1. We compute the sum of the first k elements out of n terms using a linear loop and store the sum in variable window_sum. + + 2. Then we will traverse linearly over the array till it reaches the end and simultaneously keep track of the maximum sum. + + 3. To get the current sum of a block of k elements just subtract the first element from the previous block and add the last element of the current block. + +The below representation will make it clear how the window slides over the array. + +``` +Consider an array arr[] = {5, 2, -1, 0, 3} and value of k = 3 and n = 5 + +This is the initial phase where we have calculated the initial window sum starting from index 0 . At this stage the window sum is 6. Now, we set the maximum_sum as current_window i.e 6. + + ![alt text](image-2.png) + +Now, we slide our window by a unit index. Therefore, now it discards 5 from the window and adds 0 to the window. Hence, we will get our new window sum by subtracting 5 and then adding 0 to it. So, our window sum now becomes 1. Now, we will compare this window sum with the maximum_sum. As it is smaller, we won’t change the maximum_sum. + + ![alt text](image-3.png) + +Similarly, now once again we slide our window by a unit index and obtain the new window sum to be 2. Again we check if this current window sum is greater than the maximum_sum till now. Once, again it is smaller so we don’t change the maximum_sum. +Therefore, for the above array our maximum_sum is 6. + + ![alt text](image-4.png) + + +``` + +Below is the code for above approach: + + + + + ```cpp + #include + using namespace std; + + int maxSum(int arr[], int n, int k) { + // n must be greater + if (n <= k) { + cout << "Invalid"; + return -1; + } + + // Compute sum of first window of size k + int max_sum = 0; + for (int i = 0; i < k; i++) + max_sum += arr[i]; + + // Compute sums of remaining windows by + // removing first element of previous + // window and adding last element of + // current window. + int window_sum = max_sum; + for (int i = k; i < n; i++) { + window_sum += arr[i] - arr[i - k]; + max_sum = max(max_sum, window_sum); + } + + return max_sum; + } + + // Driver code + int main() { + int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; + int k = 4; + int n = sizeof(arr) / sizeof(arr[0]); + cout << maxSum(arr, n, k); + return 0; + } + ``` + + + + ```java + import java.util.*; + + public class Main { + public static int maxSum(int[] arr, int n, int k) { + // n must be greater + if (n <= k) { + System.out.println("Invalid"); + return -1; + } + + // Compute sum of first window of size k + int max_sum = 0; + for (int i = 0; i < k; i++) + max_sum += arr[i]; + + // Compute sums of remaining windows by + // removing first element of previous + // window and adding last element of + // current window. + int window_sum = max_sum; + for (int i = k; i < n; i++) { + window_sum += arr[i] - arr[i - k]; + max_sum = Math.max(max_sum, window_sum); + } + + return max_sum; + } + + // Driver code + public static void main(String[] args) { + int[] arr = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; + int k = 4; + int n = arr.length; + System.out.println(maxSum(arr, n, k)); + } + } + ``` + + + + ```python + def maxSum(arr, n, k): + # n must be greater + if n <= k: + print("Invalid") + return -1 + + # Compute sum of first window of size k + max_sum = sum(arr[:k]) + + # Compute sums of remaining windows by + # removing first element of previous + # window and adding last element of + # current window. + window_sum = max_sum + for i in range(k, n): + window_sum += arr[i] - arr[i - k] + max_sum = max(max_sum, window_sum) + + return max_sum + + # Driver code + arr = [1, 4, 2, 10, 2, 3, 1, 0, 20] + k = 4 + n = len(arr) + print(maxSum(arr, n, k)) + ``` + + + + ```c + #include + #include + + int maxSum(int arr[], int n, int k) { + // n must be greater + if (n <= k) { + printf("Invalid"); + return -1; + } + + // Compute sum of first window of size k + int max_sum = 0; + for (int i = 0; i < k; i++) + max_sum += arr[i]; + + // Compute sums of remaining windows by + // removing first element of previous + // window and adding last element of + // current window. + int window_sum = max_sum; + for (int i = k; i < n; i++) { + window_sum += arr[i] - arr[i - k]; + if (window_sum > max_sum) + max_sum = window_sum; + } + + return max_sum; + } + + // Driver code + int main() { + int arr[] = { 1, 4, 2, 10, 2, 3, 1, 0, 20 }; + int k = 4; + int n = sizeof(arr) / sizeof(arr[0]); + printf("%d\n", maxSum(arr, n, k)); + return 0; + } + ``` + + + + +Time Complexity: $O(n)$, where n is the size of input array arr[]. +Auxiliary Space: $O(1)$ + +### Question 2: + +2. Smallest subarray with sum greater than a given value: + +Given an array arr[] of integers and a number X, the task is to find the smallest subarray with a sum greater than the given value. + +Approach: + +``` +We can solve this problem using Sliding Window Technique and maintaining two pointers: start and end to mark the starting and ending of the window. We can keep incrementing the end pointer till the sum of the window is less than or equal to X. When, the sum of window becomes greater than X, we record the length of the window and start moving the start pointer till the sum of window becomes smaller than or equal to X. Now, when the sum becomes smaller than or equal to X, again start incrementing the end pointer. Keep on moving the start and end pointer till we have reached the end of the array. +``` + +### Question 3: + +3. Find subarray with given sum in an array of non-negative integers: + +Given an array arr[] of non-negative integers and an integer sum, find a subarray that adds to a given sum. + +Approch: + +``` +The idea is simple as we know that all the elements in subarray are positive so, If a subarray has sum greater than the given sum then there is no possibility that adding elements to the current subarray will be equal to the given sum. So the Idea is to use a similar approach to a sliding window. + + 1. Start with an empty subarray. + 2. add elements to the subarray until the sum is less than x( given sum ). + 3. If the sum is greater than x, remove elements from the start of the current subarray. +``` + +### Question 4: + +4. Smallest window that contains all characters of string itself: + +``` +Basically a window of characters is maintained by using two pointers namely start and end. These start and end pointers can be used to shrink and increase the size of window respectively. Whenever the window contains all characters of given string, the window is shrinked from left side to remove extra characters and then its length is compared with the smallest window found so far. +If in the present window, no more characters can be deleted then we start increasing the size of the window using the end until all the distinct characters present in the string are also there in the window. Finally, find the minimum size of each window. +``` diff --git a/docs/intermediate/sliding_window_leetcode.md b/docs/intermediate/sliding_window_leetcode.md new file mode 100644 index 0000000..bff305b --- /dev/null +++ b/docs/intermediate/sliding_window_leetcode.md @@ -0,0 +1,68 @@ +--- +id: 03-Sliding-Window-leetcode +title: Sliding Window Questions on leetcode +sidebar_label: Sliding Window practice Questions +tags: + - sliding window + - data-structures + - priority-queue + - intermediate + - leetcode + - python + - c++ + - java + - programming + - tutorial + - typescript +sidebar_position: 7 +--- + +1. [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/) + +2. [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) + +3. [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) + +4. [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/) + +5. [Permutation in String](https://leetcode.com/problems/permutation-in-string/) + +6. [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) + +7. [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/) + +8. [Subarray Product Less Than K](https://leetcode.com/problems/subarray-product-less-than-k/) + +9. [Maximum Number of Vowels in a Substring of Given Length](https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/) + +10. [Grumpy Bookstore Owner](https://leetcode.com/problems/grumpy-bookstore-owner/) + +11. [Max Consecutive Ones III](https://leetcode.com/problems/max-consecutive-ones-iii/) + +12. [Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/) + +13. [Count Number of Nice Subarrays](https://leetcode.com/problems/count-number-of-nice-subarrays/) + +14. [Binary Subarrays With Sum](https://leetcode.com/problems/binary-subarrays-with-sum/) + +15. [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) + +16. [Substrings of Size Three with Distinct Characters](https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/) + +17. [Longest Subarray of 1's After Deleting One Element](https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/) + +18. [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) + +19. [Shortest Subarray with Sum at Least K](https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/) + +20. [Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/) + +21. [Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/) + +22. [Maximize the Confusion of an Exam](https://leetcode.com/problems/maximize-the-confusion-of-an-exam/) + +23. [Replace the Substring for Balanced String](https://leetcode.com/problems/replace-the-substring-for-balanced-string/) + +24. [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) + +25. [Minimum Window Subsequence](https://leetcode.com/problems/minimum-window-subsequence/) diff --git a/docusaurus.config.js b/docusaurus.config.js new file mode 100644 index 0000000..4bb9ece --- /dev/null +++ b/docusaurus.config.js @@ -0,0 +1,430 @@ +import { themes as prismThemes } from "prism-react-renderer"; + +const remarkMath = require("remark-math"); +const rehypeKatex = require("rehype-katex"); + +const path = require("path"); +require("dotenv").config(); + +/** @type {import('@docusaurus/types').Config} */ +const config = { + title: "CodeHarborHub", + tagline: "A place to learn and grow", + favicon: "img/favicon_io/favicon.ico", + url: process.env.URL || "https://codeharborhub.github.io/", + baseUrl: "/dsa/", + customFields: { + admin: "Ajay Dhangar", + superman: "Shivay", + serviceId: process.env.EMAILJS_SERVICE_ID, + templateId: process.env.EMAILJS_TEMPLATE_ID, + userId: process.env.EMAILJS_USER_ID, + emailService: process.env.EMAIL_SERVICE, + }, + + organizationName: "codeharborhub", + projectName: "codeharborhub.github.io", + + onBrokenLinks: "throw", + onBrokenMarkdownLinks: "warn", + + presets: [ + [ + "@docusaurus/preset-classic", + /** @type {import('@docusaurus/preset-classic').Options} */ + ({ + // debug: true, + docs: { + sidebarPath: require.resolve("./sidebars.js"), + editUrl: "#", + routeBasePath: "/", + remarkPlugins: [remarkMath], + rehypePlugins: [rehypeKatex], + }, + theme: { + customCss: "./src/css/custom.css", + }, + }), + ], + ], + + scripts: [ + { + src:"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5832817025080991", + async: true, + crossOrigin: "anonymous", + }, + { + src: "https://cdn.ampproject.org/v0/amp-auto-ads-0.1.js", + customElement: "amp-auto-ads", + async: true, + }, + ], + + stylesheets: [ + { + href: "https://cdn.jsdelivr.net/npm/katex@0.13.24/dist/katex.min.css", + type: "text/css", + integrity: + "sha384-odtC+0UGzzFL/6PNoE8rX/SPcQDXBJ+uRepguP4QkPCm2LBxH3FA3y+fKSiJ+AmM", + crossorigin: "anonymous", + }, + ], + + themeConfig: + /** @type {import('@docusaurus/preset-classic').ThemeConfig} */ + ({ + image: "img/codeharborhub-social-card.jpg", + announcementBar: { + id: "announcementBar", + content: + 'Check out our latest project Algo a place to learn and grow with Data Structures and Algorithms.', + isCloseable: true, + backgroundColor: "#4d5061", + }, + + metadata: [ + { + name: "keywords", + content: + "CodeHarborHub, Docs, Tutorials, Courses, DSA, Problems, Solutions, Showcase, Community, Blog, Web Dev, Live Editor, Quiz, Tags, Donate, Careers, Team, GitHub, Products, LinkedIn, YouTube, Discord, Twitter, Privacy Policy, Terms of Service, Code of Conduct, Cookie Policy, Licensing, Web Development, React, JavaScript, Python, Java, Tailwind CSS, CPP, NextJs, MATLAB, Julia, HTML, CSS, TypeScript, DSA, Data Structures, Algorithms, Competitive Programming", + }, + { name: "twitter:card", content: "summary_large_image" }, + { name: "twitter:site", content: "@CodesWithAjay" }, + { name: "twitter:creator", content: "@CodesWithAjay" }, + { property: "og:type", content: "website" }, + { property: "og:site_name", content: "CodeHarborHub" }, + { + property: "og:title", + content: "CodeHarborHub - A place to learn and grow", + }, + { + name: "google-adsense-account", + content: "ca-pub-5832817025080991", + }, + { + property: "og:description", + content: + "CodeHarborHub is a place to learn and grow. We provide accessible and comprehensive educational resources to learners of all levels, from beginners to advanced professionals.", + }, + { + property: "og:image", + content: + "https://codeharborhub.github.io/img/codeharborhub-social-card.jpg", + }, + { property: "og:url", content: "https://codeharborhub.github.io" }, + ], + + navbar: { + title: "CodeHarborHub", + logo: { + alt: "CodeHarborHub Logo", + src: "img/nav-logo.jpg", + href: "https://codeharborhub.github.io/", + target: "_self", + }, + items: [ + { + to: "/", + position: "right", + label: "πŸ“š DSA", + }, + { + to: "/problems/", + label: "🧩 Problems", + position: "right", + }, + { + to: "/solutions/", + label: "🧩 Solutions", + position: "right", + }, + { + href: "https://github.com/codeharborhub", + position: "right", + className: "header-github-link", + "aria-label": "GitHub repository", + }, + ], + hideOnScroll: true, + }, + footer: { + style: "dark", + links: [ + { + title: " ", + items: [ + { + html: ` + + `, + }, + ], + }, + { + title: "Resources", + items: [ + { + label: "Tutorials", + to: "https://codeharborhub.github.io/docs/", + }, + { + label: "Courses", + to: "https://codeharborhub.github.io/courses/", + }, + { + label: "DSA Problems", + to: "#", + }, + { + label: "DSA Solutions", + to: "#", + }, + ], + }, + { + title: "Company", + items: [ + { + label: "About", + to: "https://codeharborhub.github.io/about/", + }, + { + label: "Contact", + to: "https://codeharborhub.github.io/contact/", + }, + { + label: "Careers", + to: "https://codeharborhub.github.io/careers/", + }, + { + label: "Team", + to: "https://codeharborhub.github.io/community/team/", + }, + ], + }, + { + title: "Terms/Conditions", + items: [ + { + label: "Privacy Policy", + to: "https://codeharborhub.github.io/privacy-policy/", + }, + { + label: "Terms of Service", + to: "https://codeharborhub.github.io/terms-service/", + }, + { + label: "Code of Conduct", + to: "https://codeharborhub.github.io/code-of-conduct", + }, + { + label: "Cookie Policy", + to: "https://codeharborhub.github.io/cookie-policy", + }, + + { + label: "License", + to: "https://codeharborhub.github.io/License/", + }, + ], + }, + { + title: "Quick Links", + items: [ + { + label: "Blog", + to: "https://codeharborhub.github.io/blog/", + }, + { + label: "Community", + to: "https://codeharborhub.github.io/community/", + }, + { + label: "GitHub", + href: "https://github.com/codeharborhub", + }, + ], + }, + { + title: "Social Media", + items: [ + { + label: "LinkedIn", + href: "https://www.linkedin.com/company/codeharborhub/", + }, + { + label: "YouTube", + href: "https://www.youtube.com/", + icon: "faYoutube", + }, + { + label: "Discord", + href: "https://discord.gg/c53FQn3pRv", + }, + { + label: "Twitter(X)", + href: "https://twitter.com/CodesWithAjay", + }, + ], + }, + ], + logo: { + alt: "Powered by CodeHarborHub | Product Hunt", + src: "https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=464236&theme=light", + href: "https://www.producthunt.com/posts/codeharborhub", + }, + copyright: `Copyright Β© ${new Date().getFullYear()} CodeHarborHub, Made by Ajay Dhangar`, + }, + prism: { + theme: prismThemes.github, + // theme: prismThemes.dracula, + // theme: prismThemes.vsDark, + darkTheme: prismThemes.dracula, + // darkTheme: prismThemes.github, + additionalLanguages: ["powershell"], + }, + docs: { + sidebar: { + hideable: true, + }, + }, + }), + + markdown: { + mermaid: true, + }, + themes: ["@docusaurus/theme-mermaid", "@docusaurus/theme-live-codeblock"], + + plugins: [ + [ + "vercel-analytics", + { + debug: true, + mode: "auto", + }, + ], + [ + "@docusaurus/plugin-google-tag-manager", + { + containerId: "GTM-MLJNRGC9", + }, + ], + [ + "@docusaurus/plugin-google-gtag", + { + trackingID: "G-8QK6Y7QDCB", + anonymizeIP: true, + }, + ], + [ + "@docusaurus/plugin-pwa", + { + debug: true, + offlineModeActivationStrategies: [ + "appInstalled", + "standalone", + "queryString", + ], + swCustom: require.resolve("./src/sw.js"), + pwaHead: [ + { + tagName: "link", + rel: "icon", + href: "/img/favicon_io/favicon.ico", + }, + { + tagName: "link", + rel: "manifest", + href: "/manifest.json", + }, + { + tagName: "meta", + name: "theme-color", + content: "rgb(37, 194, 160)", + }, + { + tagName: "meta", + name: "apple-mobile-web-app-capable", + content: "yes", + }, + { + tagName: "meta", + name: "apple-mobile-web-app-status-bar-style", + content: "#000", + }, + { + tagName: "link", + rel: "apple-touch-icon", + href: "/img/favicon_io/apple-touch-icon.png", + }, + { + tagName: "meta", + name: "msapplication-TileImage", + content: "/img/favicon_io/android-chrome-192x192.png", + }, + { + tagName: "meta", + name: "msapplication-TileColor", + content: "#000", + }, + ], + }, + ], + [ + "@docusaurus/plugin-ideal-image", + { + quality: 70, + max: 1030, + min: 640, + steps: 2, + disableInDev: false, + }, + ], + + [ + "@docusaurus/plugin-content-docs", + /** @type {import('@docusaurus/plugin-content-docs').Options} */ + { + id: "solutions", + path: "solutions", + routeBasePath: "solutions", + editUrl: "#", + sidebarPath: require.resolve("./sidebar.js"), + remarkPlugins: [remarkMath], + rehypePlugins: [rehypeKatex], + showLastUpdateAuthor: true, + showLastUpdateTime: true, + }, + ], + [ + "@docusaurus/plugin-content-docs", + /** @type {import('@docusaurus/plugin-content-docs').Options} */ + { + id: "problems", + path: "problems", + routeBasePath: "problems", + sidebarPath: require.resolve("./sidebar.js"), + remarkPlugins: [remarkMath], + rehypePlugins: [rehypeKatex], + showLastUpdateAuthor: true, + showLastUpdateTime: true, + }, + ], + [ + path.join(__dirname, "/plugins/my-plugin"), + { + settings: "Some20settings", + api: "Some-API", + keys: "Some-keys", + }, + ], + ], +}; + +export default config; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..05c6d45 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,22913 @@ +{ + "name": "codeharborhub", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "codeharborhub", + "version": "0.0.0", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "^3.4.0", + "@docusaurus/plugin-client-redirects": "^3.5.2", + "@docusaurus/plugin-content-pages": "^3.3.2", + "@docusaurus/plugin-google-analytics": "^3.3.2", + "@docusaurus/plugin-google-gtag": "^3.3.2", + "@docusaurus/plugin-google-tag-manager": "^3.3.2", + "@docusaurus/plugin-ideal-image": "^3.3.2", + "@docusaurus/plugin-pwa": "^3.3.2", + "@docusaurus/plugin-vercel-analytics": "^3.3.2", + "@docusaurus/preset-classic": "^3.3.2", + "@docusaurus/remark-plugin-npm2yarn": "^3.4.0", + "@docusaurus/theme-classic": "^3.4.0", + "@docusaurus/theme-live-codeblock": "^3.3.2", + "@docusaurus/theme-mermaid": "^3.3.2", + "@docusaurus/theme-search-algolia": "^3.3.2", + "@docusaurus/utils-validation": "^3.3.2", + "@fluentui/react-icons": "^2.0.242", + "@fortawesome/fontawesome-svg-core": "^6.5.2", + "@fortawesome/free-brands-svg-icons": "^6.5.2", + "@fortawesome/free-solid-svg-icons": "^6.5.1", + "@fortawesome/react-fontawesome": "^0.2.2", + "@giscus/react": "^3.0.0", + "@mdx-js/react": "^3.0.0", + "@tsparticles/react": "^3.0.0", + "@tsparticles/slim": "^3.4.0", + "@types/react": "^18.3.9", + "@types/react-dom": "^18.3.0", + "axios": "^1.7.2", + "class-variance-authority": "^0.7.0", + "clsx": "^2.1.1", + "docusaurus2-dotenv": "^1.4.0", + "express": "^4.18.2", + "fontawesome": "^5.6.3", + "framer-motion": "^11.2.10", + "joi": "^17.12.1", + "passport": "^0.7.0", + "passport-github": "^1.1.0", + "prism-react-renderer": "^2.3.1", + "raw-loader": "^4.0.2", + "react": "^18.0.0", + "react-dom": "^18.0.0", + "react-icons": "^5.2.1", + "react-lite-youtube-embed": "^2.4.0", + "react-phone-input-2": "^2.15.1", + "react-popper": "^2.3.0", + "react-redux": "^9.1.0", + "react-simple-code-editor": "^0.14.0", + "react-window": "^1.8.10", + "recharts": "^2.12.7", + "redux": "^5.0.1", + "rehype-katex": "^7.0.0", + "remark-math": "^6.0.0", + "styled-components": "^6.1.8", + "swiper": "^11.1.4", + "three": "^0.169.0", + "vanilla-tilt": "^1.8.1" + }, + "devDependencies": { + "@babel/core": "^7.24.7", + "@babel/plugin-syntax-jsx": "^7.24.7", + "@babel/preset-react": "^7.24.7", + "@docusaurus/module-type-aliases": "^3.3.2", + "@docusaurus/types": "^3.3.2", + "@types/node": "^22.6.1", + "autoprefixer": "^10.4.20", + "dotenv": "^16.4.5", + "gh-pages": "^6.1.1", + "lighthouse": "^12.1.0", + "postcss": "^8.4.47", + "tailwindcss": "^3.4.12" + }, + "engines": { + "node": ">=18.0" + } + }, + "node_modules/@algolia/autocomplete-core": { + "version": "1.9.3", + "license": "MIT", + "dependencies": { + "@algolia/autocomplete-plugin-algolia-insights": "1.9.3", + "@algolia/autocomplete-shared": "1.9.3" + } + }, + "node_modules/@algolia/autocomplete-plugin-algolia-insights": { + "version": "1.9.3", + "license": "MIT", + "dependencies": { + "@algolia/autocomplete-shared": "1.9.3" + }, + "peerDependencies": { + "search-insights": ">= 1 < 3" + } + }, + "node_modules/@algolia/autocomplete-preset-algolia": { + "version": "1.9.3", + "license": "MIT", + "dependencies": { + "@algolia/autocomplete-shared": "1.9.3" + }, + "peerDependencies": { + "@algolia/client-search": ">= 4.9.1 < 6", + "algoliasearch": ">= 4.9.1 < 6" + } + }, + "node_modules/@algolia/autocomplete-shared": { + "version": "1.9.3", + "license": "MIT", + "peerDependencies": { + "@algolia/client-search": ">= 4.9.1 < 6", + "algoliasearch": ">= 4.9.1 < 6" + } + }, + "node_modules/@algolia/cache-browser-local-storage": { + "version": "4.23.3", + "license": "MIT", + "dependencies": { + "@algolia/cache-common": "4.23.3" + } + }, + "node_modules/@algolia/cache-common": { + "version": "4.23.3", + "license": "MIT" + }, + "node_modules/@algolia/cache-in-memory": { + "version": "4.23.3", + "license": "MIT", + "dependencies": { + "@algolia/cache-common": "4.23.3" + } + }, + "node_modules/@algolia/client-account": { + "version": "4.23.3", + "license": "MIT", + "dependencies": { + "@algolia/client-common": "4.23.3", + "@algolia/client-search": "4.23.3", + "@algolia/transporter": "4.23.3" + } + }, + "node_modules/@algolia/client-analytics": { + "version": "4.23.3", + "license": "MIT", + "dependencies": { + "@algolia/client-common": "4.23.3", + "@algolia/client-search": "4.23.3", + "@algolia/requester-common": "4.23.3", + "@algolia/transporter": "4.23.3" + } + }, + "node_modules/@algolia/client-common": { + "version": "4.23.3", + "license": "MIT", + "dependencies": { + "@algolia/requester-common": "4.23.3", + "@algolia/transporter": "4.23.3" + } + }, + "node_modules/@algolia/client-personalization": { + "version": "4.23.3", + "license": "MIT", + "dependencies": { + "@algolia/client-common": "4.23.3", + "@algolia/requester-common": "4.23.3", + "@algolia/transporter": "4.23.3" + } + }, + "node_modules/@algolia/client-search": { + "version": "4.23.3", + "license": "MIT", + "dependencies": { + "@algolia/client-common": "4.23.3", + "@algolia/requester-common": "4.23.3", + "@algolia/transporter": "4.23.3" + } + }, + "node_modules/@algolia/events": { + "version": "4.0.1", + "license": "MIT" + }, + "node_modules/@algolia/logger-common": { + "version": "4.23.3", + "license": "MIT" + }, + "node_modules/@algolia/logger-console": { + "version": "4.23.3", + "license": "MIT", + "dependencies": { + "@algolia/logger-common": "4.23.3" + } + }, + "node_modules/@algolia/recommend": { + "version": "4.23.3", + "license": "MIT", + "dependencies": { + "@algolia/cache-browser-local-storage": "4.23.3", + "@algolia/cache-common": "4.23.3", + "@algolia/cache-in-memory": "4.23.3", + "@algolia/client-common": "4.23.3", + "@algolia/client-search": "4.23.3", + "@algolia/logger-common": "4.23.3", + "@algolia/logger-console": "4.23.3", + "@algolia/requester-browser-xhr": "4.23.3", + "@algolia/requester-common": "4.23.3", + "@algolia/requester-node-http": "4.23.3", + "@algolia/transporter": "4.23.3" + } + }, + "node_modules/@algolia/requester-browser-xhr": { + "version": "4.23.3", + "license": "MIT", + "dependencies": { + "@algolia/requester-common": "4.23.3" + } + }, + "node_modules/@algolia/requester-common": { + "version": "4.23.3", + "license": "MIT" + }, + "node_modules/@algolia/requester-node-http": { + "version": "4.23.3", + "license": "MIT", + "dependencies": { + "@algolia/requester-common": "4.23.3" + } + }, + "node_modules/@algolia/transporter": { + "version": "4.23.3", + "license": "MIT", + "dependencies": { + "@algolia/cache-common": "4.23.3", + "@algolia/logger-common": "4.23.3", + "@algolia/requester-common": "4.23.3" + } + }, + "node_modules/@alloc/quick-lru": { + "version": "5.2.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@ampproject/remapping": { + "version": "2.2.1", + "license": "Apache-2.0", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.0", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@apideck/better-ajv-errors": { + "version": "0.3.6", + "license": "MIT", + "dependencies": { + "json-schema": "^0.4.0", + "jsonpointer": "^5.0.0", + "leven": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "ajv": ">=8" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/highlight": "^7.25.7", + "picocolors": "^1.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.25.7", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@ampproject/remapping": "^2.2.0", + "@babel/code-frame": "^7.25.7", + "@babel/generator": "^7.25.7", + "@babel/helper-compilation-targets": "^7.25.7", + "@babel/helper-module-transforms": "^7.25.7", + "@babel/helpers": "^7.25.7", + "@babel/parser": "^7.25.7", + "@babel/template": "^7.25.7", + "@babel/traverse": "^7.25.7", + "@babel/types": "^7.25.7", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/core/node_modules/semver": { + "version": "6.3.1", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/generator": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.25.7", + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-annotate-as-pure": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.25.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-builder-binary-assignment-operator-visitor": { + "version": "7.22.15", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.22.15" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.25.7", + "@babel/helper-validator-option": "^7.25.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/semver": { + "version": "6.3.1", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-create-class-features-plugin": { + "version": "7.23.10", + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.22.5", + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-function-name": "^7.23.0", + "@babel/helper-member-expression-to-functions": "^7.23.0", + "@babel/helper-optimise-call-expression": "^7.22.5", + "@babel/helper-replace-supers": "^7.22.20", + "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5", + "@babel/helper-split-export-declaration": "^7.22.6", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-create-class-features-plugin/node_modules/semver": { + "version": "6.3.1", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-create-regexp-features-plugin": { + "version": "7.22.15", + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.22.5", + "regexpu-core": "^5.3.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-create-regexp-features-plugin/node_modules/semver": { + "version": "6.3.1", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-define-polyfill-provider": { + "version": "0.5.0", + "license": "MIT", + "dependencies": { + "@babel/helper-compilation-targets": "^7.22.6", + "@babel/helper-plugin-utils": "^7.22.5", + "debug": "^4.1.1", + "lodash.debounce": "^4.0.8", + "resolve": "^1.14.2" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/@babel/helper-environment-visitor": { + "version": "7.24.7", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.24.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-function-name": { + "version": "7.24.7", + "license": "MIT", + "dependencies": { + "@babel/template": "^7.24.7", + "@babel/types": "^7.24.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-hoist-variables": { + "version": "7.24.7", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.24.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-member-expression-to-functions": { + "version": "7.23.0", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.23.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.25.7", + "@babel/types": "^7.25.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.25.7", + "@babel/helper-simple-access": "^7.25.7", + "@babel/helper-validator-identifier": "^7.25.7", + "@babel/traverse": "^7.25.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-optimise-call-expression": { + "version": "7.22.5", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.25.7", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-remap-async-to-generator": { + "version": "7.22.20", + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.22.5", + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-wrap-function": "^7.22.20" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-replace-supers": { + "version": "7.22.20", + "license": "MIT", + "dependencies": { + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-member-expression-to-functions": "^7.22.15", + "@babel/helper-optimise-call-expression": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-simple-access": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.25.7", + "@babel/types": "^7.25.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-skip-transparent-expression-wrappers": { + "version": "7.22.5", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-split-export-declaration": { + "version": "7.24.7", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.24.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.25.7", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.25.7", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.25.7", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-wrap-function": { + "version": "7.22.20", + "license": "MIT", + "dependencies": { + "@babel/helper-function-name": "^7.22.5", + "@babel/template": "^7.22.15", + "@babel/types": "^7.22.19" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/template": "^7.25.7", + "@babel/types": "^7.25.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.25.7", + "chalk": "^2.4.2", + "js-tokens": "^4.0.0", + "picocolors": "^1.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight/node_modules/ansi-styles": { + "version": "3.2.1", + "license": "MIT", + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/chalk": { + "version": "2.4.2", + "license": "MIT", + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/color-convert": { + "version": "1.9.3", + "license": "MIT", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/@babel/highlight/node_modules/color-name": { + "version": "1.1.3", + "license": "MIT" + }, + "node_modules/@babel/highlight/node_modules/escape-string-regexp": { + "version": "1.0.5", + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@babel/highlight/node_modules/has-flag": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/supports-color": { + "version": "5.5.0", + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/parser": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.25.7" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5", + "@babel/plugin-transform-optional-chaining": "^7.23.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.13.0" + } + }, + "node_modules/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": { + "version": "7.23.7", + "license": "MIT", + "dependencies": { + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-proposal-private-property-in-object": { + "version": "7.21.0-placeholder-for-preset-env.2", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-async-generators": { + "version": "7.8.4", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-properties": { + "version": "7.12.13", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.12.13" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-static-block": { + "version": "7.14.5", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-dynamic-import": { + "version": "7.8.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-export-namespace-from": { + "version": "7.8.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.3" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-assertions": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-attributes": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-meta": { + "version": "7.10.4", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-json-strings": { + "version": "7.8.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.25.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-logical-assignment-operators": { + "version": "7.10.4", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { + "version": "7.8.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-numeric-separator": { + "version": "7.10.4", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-object-rest-spread": { + "version": "7.8.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-catch-binding": { + "version": "7.8.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-chaining": { + "version": "7.8.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-private-property-in-object": { + "version": "7.14.5", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-top-level-await": { + "version": "7.14.5", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-typescript": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-unicode-sets-regex": { + "version": "7.18.6", + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.18.6", + "@babel/helper-plugin-utils": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-transform-arrow-functions": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-async-generator-functions": { + "version": "7.23.9", + "license": "MIT", + "dependencies": { + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-remap-async-to-generator": "^7.22.20", + "@babel/plugin-syntax-async-generators": "^7.8.4" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-async-to-generator": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-remap-async-to-generator": "^7.22.20" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-block-scoped-functions": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-block-scoping": { + "version": "7.23.4", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-class-properties": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-class-static-block": { + "version": "7.23.4", + "license": "MIT", + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-class-static-block": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.12.0" + } + }, + "node_modules/@babel/plugin-transform-classes": { + "version": "7.23.8", + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.22.5", + "@babel/helper-compilation-targets": "^7.23.6", + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-function-name": "^7.23.0", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-replace-supers": "^7.22.20", + "@babel/helper-split-export-declaration": "^7.22.6", + "globals": "^11.1.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-computed-properties": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/template": "^7.22.15" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-destructuring": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-dotall-regex": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-duplicate-keys": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-dynamic-import": { + "version": "7.23.4", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-dynamic-import": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-exponentiation-operator": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-builder-binary-assignment-operator-visitor": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-export-namespace-from": { + "version": "7.23.4", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-export-namespace-from": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-for-of": { + "version": "7.23.6", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-function-name": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-compilation-targets": "^7.22.15", + "@babel/helper-function-name": "^7.23.0", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-json-strings": { + "version": "7.23.4", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-json-strings": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-literals": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-logical-assignment-operators": { + "version": "7.23.4", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-member-expression-literals": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-amd": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-module-transforms": "^7.23.3", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-commonjs": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-module-transforms": "^7.23.3", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-simple-access": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-systemjs": { + "version": "7.23.9", + "license": "MIT", + "dependencies": { + "@babel/helper-hoist-variables": "^7.22.5", + "@babel/helper-module-transforms": "^7.23.3", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-validator-identifier": "^7.22.20" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-umd": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-module-transforms": "^7.23.3", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-named-capturing-groups-regex": { + "version": "7.22.5", + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.22.5", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/plugin-transform-new-target": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-nullish-coalescing-operator": { + "version": "7.23.4", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-numeric-separator": { + "version": "7.23.4", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-numeric-separator": "^7.10.4" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-object-rest-spread": { + "version": "7.23.4", + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.23.3", + "@babel/helper-compilation-targets": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-transform-parameters": "^7.23.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-object-super": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-replace-supers": "^7.22.20" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-optional-catch-binding": { + "version": "7.23.4", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-optional-chaining": { + "version": "7.23.4", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5", + "@babel/plugin-syntax-optional-chaining": "^7.8.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-parameters": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-private-methods": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-private-property-in-object": { + "version": "7.23.4", + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.22.5", + "@babel/helper-create-class-features-plugin": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-property-literals": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-constant-elements": { + "version": "7.24.1", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.24.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-display-name": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.25.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.25.7", + "@babel/helper-module-imports": "^7.25.7", + "@babel/helper-plugin-utils": "^7.25.7", + "@babel/plugin-syntax-jsx": "^7.25.7", + "@babel/types": "^7.25.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-development": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/plugin-transform-react-jsx": "^7.25.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-pure-annotations": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.25.7", + "@babel/helper-plugin-utils": "^7.25.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-regenerator": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "regenerator-transform": "^0.15.2" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-reserved-words": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-runtime": { + "version": "7.23.9", + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5", + "babel-plugin-polyfill-corejs2": "^0.4.8", + "babel-plugin-polyfill-corejs3": "^0.9.0", + "babel-plugin-polyfill-regenerator": "^0.5.5", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-runtime/node_modules/semver": { + "version": "6.3.1", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/plugin-transform-shorthand-properties": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-spread": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-sticky-regex": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-template-literals": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-typeof-symbol": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-typescript": { + "version": "7.23.6", + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.22.5", + "@babel/helper-create-class-features-plugin": "^7.23.6", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/plugin-syntax-typescript": "^7.23.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-escapes": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-property-regex": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-regex": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-unicode-sets-regex": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-create-regexp-features-plugin": "^7.22.15", + "@babel/helper-plugin-utils": "^7.22.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/preset-env": { + "version": "7.23.9", + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.23.5", + "@babel/helper-compilation-targets": "^7.23.6", + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-validator-option": "^7.23.5", + "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^7.23.3", + "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^7.23.3", + "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": "^7.23.7", + "@babel/plugin-proposal-private-property-in-object": "7.21.0-placeholder-for-preset-env.2", + "@babel/plugin-syntax-async-generators": "^7.8.4", + "@babel/plugin-syntax-class-properties": "^7.12.13", + "@babel/plugin-syntax-class-static-block": "^7.14.5", + "@babel/plugin-syntax-dynamic-import": "^7.8.3", + "@babel/plugin-syntax-export-namespace-from": "^7.8.3", + "@babel/plugin-syntax-import-assertions": "^7.23.3", + "@babel/plugin-syntax-import-attributes": "^7.23.3", + "@babel/plugin-syntax-import-meta": "^7.10.4", + "@babel/plugin-syntax-json-strings": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.10.4", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.3", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5", + "@babel/plugin-syntax-top-level-await": "^7.14.5", + "@babel/plugin-syntax-unicode-sets-regex": "^7.18.6", + "@babel/plugin-transform-arrow-functions": "^7.23.3", + "@babel/plugin-transform-async-generator-functions": "^7.23.9", + "@babel/plugin-transform-async-to-generator": "^7.23.3", + "@babel/plugin-transform-block-scoped-functions": "^7.23.3", + "@babel/plugin-transform-block-scoping": "^7.23.4", + "@babel/plugin-transform-class-properties": "^7.23.3", + "@babel/plugin-transform-class-static-block": "^7.23.4", + "@babel/plugin-transform-classes": "^7.23.8", + "@babel/plugin-transform-computed-properties": "^7.23.3", + "@babel/plugin-transform-destructuring": "^7.23.3", + "@babel/plugin-transform-dotall-regex": "^7.23.3", + "@babel/plugin-transform-duplicate-keys": "^7.23.3", + "@babel/plugin-transform-dynamic-import": "^7.23.4", + "@babel/plugin-transform-exponentiation-operator": "^7.23.3", + "@babel/plugin-transform-export-namespace-from": "^7.23.4", + "@babel/plugin-transform-for-of": "^7.23.6", + "@babel/plugin-transform-function-name": "^7.23.3", + "@babel/plugin-transform-json-strings": "^7.23.4", + "@babel/plugin-transform-literals": "^7.23.3", + "@babel/plugin-transform-logical-assignment-operators": "^7.23.4", + "@babel/plugin-transform-member-expression-literals": "^7.23.3", + "@babel/plugin-transform-modules-amd": "^7.23.3", + "@babel/plugin-transform-modules-commonjs": "^7.23.3", + "@babel/plugin-transform-modules-systemjs": "^7.23.9", + "@babel/plugin-transform-modules-umd": "^7.23.3", + "@babel/plugin-transform-named-capturing-groups-regex": "^7.22.5", + "@babel/plugin-transform-new-target": "^7.23.3", + "@babel/plugin-transform-nullish-coalescing-operator": "^7.23.4", + "@babel/plugin-transform-numeric-separator": "^7.23.4", + "@babel/plugin-transform-object-rest-spread": "^7.23.4", + "@babel/plugin-transform-object-super": "^7.23.3", + "@babel/plugin-transform-optional-catch-binding": "^7.23.4", + "@babel/plugin-transform-optional-chaining": "^7.23.4", + "@babel/plugin-transform-parameters": "^7.23.3", + "@babel/plugin-transform-private-methods": "^7.23.3", + "@babel/plugin-transform-private-property-in-object": "^7.23.4", + "@babel/plugin-transform-property-literals": "^7.23.3", + "@babel/plugin-transform-regenerator": "^7.23.3", + "@babel/plugin-transform-reserved-words": "^7.23.3", + "@babel/plugin-transform-shorthand-properties": "^7.23.3", + "@babel/plugin-transform-spread": "^7.23.3", + "@babel/plugin-transform-sticky-regex": "^7.23.3", + "@babel/plugin-transform-template-literals": "^7.23.3", + "@babel/plugin-transform-typeof-symbol": "^7.23.3", + "@babel/plugin-transform-unicode-escapes": "^7.23.3", + "@babel/plugin-transform-unicode-property-regex": "^7.23.3", + "@babel/plugin-transform-unicode-regex": "^7.23.3", + "@babel/plugin-transform-unicode-sets-regex": "^7.23.3", + "@babel/preset-modules": "0.1.6-no-external-plugins", + "babel-plugin-polyfill-corejs2": "^0.4.8", + "babel-plugin-polyfill-corejs3": "^0.9.0", + "babel-plugin-polyfill-regenerator": "^0.5.5", + "core-js-compat": "^3.31.0", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/preset-env/node_modules/semver": { + "version": "6.3.1", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/preset-modules": { + "version": "0.1.6-no-external-plugins", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/types": "^7.4.4", + "esutils": "^2.0.2" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/@babel/preset-react": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.25.7", + "@babel/helper-validator-option": "^7.25.7", + "@babel/plugin-transform-react-display-name": "^7.25.7", + "@babel/plugin-transform-react-jsx": "^7.25.7", + "@babel/plugin-transform-react-jsx-development": "^7.25.7", + "@babel/plugin-transform-react-pure-annotations": "^7.25.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/preset-typescript": { + "version": "7.23.3", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.22.5", + "@babel/helper-validator-option": "^7.22.15", + "@babel/plugin-syntax-jsx": "^7.23.3", + "@babel/plugin-transform-modules-commonjs": "^7.23.3", + "@babel/plugin-transform-typescript": "^7.23.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/regjsgen": { + "version": "0.8.0", + "license": "MIT" + }, + "node_modules/@babel/runtime": { + "version": "7.24.7", + "license": "MIT", + "dependencies": { + "regenerator-runtime": "^0.14.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/runtime-corejs3": { + "version": "7.23.9", + "license": "MIT", + "dependencies": { + "core-js-pure": "^3.30.2", + "regenerator-runtime": "^0.14.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/template": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.25.7", + "@babel/parser": "^7.25.7", + "@babel/types": "^7.25.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.25.7", + "@babel/generator": "^7.25.7", + "@babel/parser": "^7.25.7", + "@babel/template": "^7.25.7", + "@babel/types": "^7.25.7", + "debug": "^4.3.1", + "globals": "^11.1.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.25.7", + "@babel/helper-validator-identifier": "^7.25.7", + "to-fast-properties": "^2.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@braintree/sanitize-url": { + "version": "6.0.4", + "license": "MIT" + }, + "node_modules/@colors/colors": { + "version": "1.5.0", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/@discoveryjs/json-ext": { + "version": "0.5.7", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/@docsearch/css": { + "version": "3.6.0", + "license": "MIT" + }, + "node_modules/@docsearch/react": { + "version": "3.6.0", + "license": "MIT", + "dependencies": { + "@algolia/autocomplete-core": "1.9.3", + "@algolia/autocomplete-preset-algolia": "1.9.3", + "@docsearch/css": "3.6.0", + "algoliasearch": "^4.19.1" + }, + "peerDependencies": { + "@types/react": ">= 16.8.0 < 19.0.0", + "react": ">= 16.8.0 < 19.0.0", + "react-dom": ">= 16.8.0 < 19.0.0", + "search-insights": ">= 1 < 3" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + }, + "search-insights": { + "optional": true + } + } + }, + "node_modules/@docusaurus/core": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@babel/core": "^7.23.3", + "@babel/generator": "^7.23.3", + "@babel/plugin-syntax-dynamic-import": "^7.8.3", + "@babel/plugin-transform-runtime": "^7.22.9", + "@babel/preset-env": "^7.22.9", + "@babel/preset-react": "^7.22.5", + "@babel/preset-typescript": "^7.22.5", + "@babel/runtime": "^7.22.6", + "@babel/runtime-corejs3": "^7.22.6", + "@babel/traverse": "^7.22.8", + "@docusaurus/cssnano-preset": "3.5.2", + "@docusaurus/logger": "3.5.2", + "@docusaurus/mdx-loader": "3.5.2", + "@docusaurus/utils": "3.5.2", + "@docusaurus/utils-common": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "autoprefixer": "^10.4.14", + "babel-loader": "^9.1.3", + "babel-plugin-dynamic-import-node": "^2.3.3", + "boxen": "^6.2.1", + "chalk": "^4.1.2", + "chokidar": "^3.5.3", + "clean-css": "^5.3.2", + "cli-table3": "^0.6.3", + "combine-promises": "^1.1.0", + "commander": "^5.1.0", + "copy-webpack-plugin": "^11.0.0", + "core-js": "^3.31.1", + "css-loader": "^6.8.1", + "css-minimizer-webpack-plugin": "^5.0.1", + "cssnano": "^6.1.2", + "del": "^6.1.1", + "detect-port": "^1.5.1", + "escape-html": "^1.0.3", + "eta": "^2.2.0", + "eval": "^0.1.8", + "file-loader": "^6.2.0", + "fs-extra": "^11.1.1", + "html-minifier-terser": "^7.2.0", + "html-tags": "^3.3.1", + "html-webpack-plugin": "^5.5.3", + "leven": "^3.1.0", + "lodash": "^4.17.21", + "mini-css-extract-plugin": "^2.7.6", + "p-map": "^4.0.0", + "postcss": "^8.4.26", + "postcss-loader": "^7.3.3", + "prompts": "^2.4.2", + "react-dev-utils": "^12.0.1", + "react-helmet-async": "^1.3.0", + "react-loadable": "npm:@docusaurus/react-loadable@6.0.0", + "react-loadable-ssr-addon-v5-slorber": "^1.0.1", + "react-router": "^5.3.4", + "react-router-config": "^5.1.1", + "react-router-dom": "^5.3.4", + "rtl-detect": "^1.0.4", + "semver": "^7.5.4", + "serve-handler": "^6.1.5", + "shelljs": "^0.8.5", + "terser-webpack-plugin": "^5.3.9", + "tslib": "^2.6.0", + "update-notifier": "^6.0.2", + "url-loader": "^4.1.1", + "webpack": "^5.88.1", + "webpack-bundle-analyzer": "^4.9.0", + "webpack-dev-server": "^4.15.1", + "webpack-merge": "^5.9.0", + "webpackbar": "^5.0.2" + }, + "bin": { + "docusaurus": "bin/docusaurus.mjs" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "@mdx-js/react": "^3.0.0", + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/cssnano-preset": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "cssnano-preset-advanced": "^6.1.2", + "postcss": "^8.4.38", + "postcss-sort-media-queries": "^5.2.0", + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=18.0" + } + }, + "node_modules/@docusaurus/logger": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "chalk": "^4.1.2", + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=18.0" + } + }, + "node_modules/@docusaurus/lqip-loader": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/logger": "3.5.2", + "file-loader": "^6.2.0", + "lodash": "^4.17.21", + "sharp": "^0.32.3", + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=18.0" + } + }, + "node_modules/@docusaurus/mdx-loader": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/logger": "3.5.2", + "@docusaurus/utils": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "@mdx-js/mdx": "^3.0.0", + "@slorber/remark-comment": "^1.0.0", + "escape-html": "^1.0.3", + "estree-util-value-to-estree": "^3.0.1", + "file-loader": "^6.2.0", + "fs-extra": "^11.1.1", + "image-size": "^1.0.2", + "mdast-util-mdx": "^3.0.0", + "mdast-util-to-string": "^4.0.0", + "rehype-raw": "^7.0.0", + "remark-directive": "^3.0.0", + "remark-emoji": "^4.0.0", + "remark-frontmatter": "^5.0.0", + "remark-gfm": "^4.0.0", + "stringify-object": "^3.3.0", + "tslib": "^2.6.0", + "unified": "^11.0.3", + "unist-util-visit": "^5.0.0", + "url-loader": "^4.1.1", + "vfile": "^6.0.1", + "webpack": "^5.88.1" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/module-type-aliases": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/types": "3.5.2", + "@types/history": "^4.7.11", + "@types/react": "*", + "@types/react-router-config": "*", + "@types/react-router-dom": "*", + "react-helmet-async": "*", + "react-loadable": "npm:@docusaurus/react-loadable@6.0.0" + }, + "peerDependencies": { + "react": "*", + "react-dom": "*" + } + }, + "node_modules/@docusaurus/plugin-client-redirects": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.5.2", + "@docusaurus/logger": "3.5.2", + "@docusaurus/utils": "3.5.2", + "@docusaurus/utils-common": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "eta": "^2.2.0", + "fs-extra": "^11.1.1", + "lodash": "^4.17.21", + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/plugin-content-blog": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.5.2", + "@docusaurus/logger": "3.5.2", + "@docusaurus/mdx-loader": "3.5.2", + "@docusaurus/theme-common": "3.5.2", + "@docusaurus/types": "3.5.2", + "@docusaurus/utils": "3.5.2", + "@docusaurus/utils-common": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "cheerio": "1.0.0-rc.12", + "feed": "^4.2.2", + "fs-extra": "^11.1.1", + "lodash": "^4.17.21", + "reading-time": "^1.5.0", + "srcset": "^4.0.0", + "tslib": "^2.6.0", + "unist-util-visit": "^5.0.0", + "utility-types": "^3.10.0", + "webpack": "^5.88.1" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "@docusaurus/plugin-content-docs": "*", + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/plugin-content-docs": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.5.2", + "@docusaurus/logger": "3.5.2", + "@docusaurus/mdx-loader": "3.5.2", + "@docusaurus/module-type-aliases": "3.5.2", + "@docusaurus/theme-common": "3.5.2", + "@docusaurus/types": "3.5.2", + "@docusaurus/utils": "3.5.2", + "@docusaurus/utils-common": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "@types/react-router-config": "^5.0.7", + "combine-promises": "^1.1.0", + "fs-extra": "^11.1.1", + "js-yaml": "^4.1.0", + "lodash": "^4.17.21", + "tslib": "^2.6.0", + "utility-types": "^3.10.0", + "webpack": "^5.88.1" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/plugin-content-pages": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.5.2", + "@docusaurus/mdx-loader": "3.5.2", + "@docusaurus/types": "3.5.2", + "@docusaurus/utils": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "fs-extra": "^11.1.1", + "tslib": "^2.6.0", + "webpack": "^5.88.1" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/plugin-debug": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.5.2", + "@docusaurus/types": "3.5.2", + "@docusaurus/utils": "3.5.2", + "fs-extra": "^11.1.1", + "react-json-view-lite": "^1.2.0", + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/plugin-google-analytics": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.5.2", + "@docusaurus/types": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/plugin-google-gtag": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.5.2", + "@docusaurus/types": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "@types/gtag.js": "^0.0.12", + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/plugin-google-tag-manager": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.5.2", + "@docusaurus/types": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/plugin-ideal-image": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.5.2", + "@docusaurus/lqip-loader": "3.5.2", + "@docusaurus/responsive-loader": "^1.7.0", + "@docusaurus/theme-translations": "3.5.2", + "@docusaurus/types": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "@slorber/react-ideal-image": "^0.0.12", + "react-waypoint": "^10.3.0", + "sharp": "^0.32.3", + "tslib": "^2.6.0", + "webpack": "^5.88.1" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "jimp": "*", + "react": "^18.0.0", + "react-dom": "^18.0.0" + }, + "peerDependenciesMeta": { + "jimp": { + "optional": true + } + } + }, + "node_modules/@docusaurus/plugin-pwa": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@babel/core": "^7.23.3", + "@babel/preset-env": "^7.23.3", + "@docusaurus/core": "3.5.2", + "@docusaurus/logger": "3.5.2", + "@docusaurus/theme-common": "3.5.2", + "@docusaurus/theme-translations": "3.5.2", + "@docusaurus/types": "3.5.2", + "@docusaurus/utils": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "babel-loader": "^9.1.3", + "clsx": "^2.0.0", + "core-js": "^3.31.1", + "terser-webpack-plugin": "^5.3.9", + "tslib": "^2.6.0", + "webpack": "^5.88.1", + "webpack-merge": "^5.9.0", + "webpackbar": "^5.0.2", + "workbox-build": "^7.0.0", + "workbox-precaching": "^7.0.0", + "workbox-window": "^7.0.0" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/plugin-sitemap": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.5.2", + "@docusaurus/logger": "3.5.2", + "@docusaurus/types": "3.5.2", + "@docusaurus/utils": "3.5.2", + "@docusaurus/utils-common": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "fs-extra": "^11.1.1", + "sitemap": "^7.1.1", + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/plugin-vercel-analytics": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.5.2", + "@docusaurus/logger": "3.5.2", + "@docusaurus/types": "3.5.2", + "@docusaurus/utils": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "@vercel/analytics": "^1.1.1", + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/preset-classic": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.5.2", + "@docusaurus/plugin-content-blog": "3.5.2", + "@docusaurus/plugin-content-docs": "3.5.2", + "@docusaurus/plugin-content-pages": "3.5.2", + "@docusaurus/plugin-debug": "3.5.2", + "@docusaurus/plugin-google-analytics": "3.5.2", + "@docusaurus/plugin-google-gtag": "3.5.2", + "@docusaurus/plugin-google-tag-manager": "3.5.2", + "@docusaurus/plugin-sitemap": "3.5.2", + "@docusaurus/theme-classic": "3.5.2", + "@docusaurus/theme-common": "3.5.2", + "@docusaurus/theme-search-algolia": "3.5.2", + "@docusaurus/types": "3.5.2" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/remark-plugin-npm2yarn": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "mdast-util-mdx": "^3.0.0", + "npm-to-yarn": "^2.2.1", + "tslib": "^2.6.0", + "unified": "^11.0.3", + "unist-util-visit": "^5.0.0" + }, + "engines": { + "node": ">=18.0" + } + }, + "node_modules/@docusaurus/responsive-loader": { + "version": "1.7.0", + "license": "BSD-3-Clause", + "dependencies": { + "loader-utils": "^2.0.0" + }, + "engines": { + "node": ">=12" + }, + "peerDependencies": { + "jimp": "*", + "sharp": "*" + }, + "peerDependenciesMeta": { + "jimp": { + "optional": true + }, + "sharp": { + "optional": true + } + } + }, + "node_modules/@docusaurus/theme-classic": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.5.2", + "@docusaurus/mdx-loader": "3.5.2", + "@docusaurus/module-type-aliases": "3.5.2", + "@docusaurus/plugin-content-blog": "3.5.2", + "@docusaurus/plugin-content-docs": "3.5.2", + "@docusaurus/plugin-content-pages": "3.5.2", + "@docusaurus/theme-common": "3.5.2", + "@docusaurus/theme-translations": "3.5.2", + "@docusaurus/types": "3.5.2", + "@docusaurus/utils": "3.5.2", + "@docusaurus/utils-common": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "@mdx-js/react": "^3.0.0", + "clsx": "^2.0.0", + "copy-text-to-clipboard": "^3.2.0", + "infima": "0.2.0-alpha.44", + "lodash": "^4.17.21", + "nprogress": "^0.2.0", + "postcss": "^8.4.26", + "prism-react-renderer": "^2.3.0", + "prismjs": "^1.29.0", + "react-router-dom": "^5.3.4", + "rtlcss": "^4.1.0", + "tslib": "^2.6.0", + "utility-types": "^3.10.0" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/theme-common": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/mdx-loader": "3.5.2", + "@docusaurus/module-type-aliases": "3.5.2", + "@docusaurus/utils": "3.5.2", + "@docusaurus/utils-common": "3.5.2", + "@types/history": "^4.7.11", + "@types/react": "*", + "@types/react-router-config": "*", + "clsx": "^2.0.0", + "parse-numeric-range": "^1.3.0", + "prism-react-renderer": "^2.3.0", + "tslib": "^2.6.0", + "utility-types": "^3.10.0" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "@docusaurus/plugin-content-docs": "*", + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/theme-live-codeblock": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.5.2", + "@docusaurus/theme-common": "3.5.2", + "@docusaurus/theme-translations": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "@philpl/buble": "^0.19.7", + "clsx": "^2.0.0", + "fs-extra": "^11.1.1", + "react-live": "^4.1.6", + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/theme-mermaid": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.5.2", + "@docusaurus/module-type-aliases": "3.5.2", + "@docusaurus/theme-common": "3.5.2", + "@docusaurus/types": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "mermaid": "^10.4.0", + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/theme-search-algolia": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docsearch/react": "^3.5.2", + "@docusaurus/core": "3.5.2", + "@docusaurus/logger": "3.5.2", + "@docusaurus/plugin-content-docs": "3.5.2", + "@docusaurus/theme-common": "3.5.2", + "@docusaurus/theme-translations": "3.5.2", + "@docusaurus/utils": "3.5.2", + "@docusaurus/utils-validation": "3.5.2", + "algoliasearch": "^4.18.0", + "algoliasearch-helper": "^3.13.3", + "clsx": "^2.0.0", + "eta": "^2.2.0", + "fs-extra": "^11.1.1", + "lodash": "^4.17.21", + "tslib": "^2.6.0", + "utility-types": "^3.10.0" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/theme-translations": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "fs-extra": "^11.1.1", + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=18.0" + } + }, + "node_modules/@docusaurus/types": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@mdx-js/mdx": "^3.0.0", + "@types/history": "^4.7.11", + "@types/react": "*", + "commander": "^5.1.0", + "joi": "^17.9.2", + "react-helmet-async": "^1.3.0", + "utility-types": "^3.10.0", + "webpack": "^5.88.1", + "webpack-merge": "^5.9.0" + }, + "peerDependencies": { + "react": "^18.0.0", + "react-dom": "^18.0.0" + } + }, + "node_modules/@docusaurus/utils": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/logger": "3.5.2", + "@docusaurus/utils-common": "3.5.2", + "@svgr/webpack": "^8.1.0", + "escape-string-regexp": "^4.0.0", + "file-loader": "^6.2.0", + "fs-extra": "^11.1.1", + "github-slugger": "^1.5.0", + "globby": "^11.1.0", + "gray-matter": "^4.0.3", + "jiti": "^1.20.0", + "js-yaml": "^4.1.0", + "lodash": "^4.17.21", + "micromatch": "^4.0.5", + "prompts": "^2.4.2", + "resolve-pathname": "^3.0.0", + "shelljs": "^0.8.5", + "tslib": "^2.6.0", + "url-loader": "^4.1.1", + "utility-types": "^3.10.0", + "webpack": "^5.88.1" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "@docusaurus/types": "*" + }, + "peerDependenciesMeta": { + "@docusaurus/types": { + "optional": true + } + } + }, + "node_modules/@docusaurus/utils-common": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "@docusaurus/types": "*" + }, + "peerDependenciesMeta": { + "@docusaurus/types": { + "optional": true + } + } + }, + "node_modules/@docusaurus/utils-validation": { + "version": "3.5.2", + "license": "MIT", + "dependencies": { + "@docusaurus/logger": "3.5.2", + "@docusaurus/utils": "3.5.2", + "@docusaurus/utils-common": "3.5.2", + "fs-extra": "^11.2.0", + "joi": "^17.9.2", + "js-yaml": "^4.1.0", + "lodash": "^4.17.21", + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=18.0" + } + }, + "node_modules/@emotion/hash": { + "version": "0.9.1", + "license": "MIT" + }, + "node_modules/@emotion/is-prop-valid": { + "version": "1.2.2", + "license": "MIT", + "dependencies": { + "@emotion/memoize": "^0.8.1" + } + }, + "node_modules/@emotion/memoize": { + "version": "0.8.1", + "license": "MIT" + }, + "node_modules/@emotion/unitless": { + "version": "0.8.1", + "license": "MIT" + }, + "node_modules/@fluentui/react-icons": { + "version": "2.0.260", + "license": "MIT", + "dependencies": { + "@griffel/react": "^1.0.0", + "tslib": "^2.1.0" + }, + "peerDependencies": { + "react": ">=16.8.0 <19.0.0" + } + }, + "node_modules/@formatjs/ecma402-abstract": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@formatjs/intl-localematcher": "0.5.4", + "tslib": "^2.4.0" + } + }, + "node_modules/@formatjs/fast-memoize": { + "version": "2.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@formatjs/icu-messageformat-parser": { + "version": "2.7.8", + "dev": true, + "license": "MIT", + "dependencies": { + "@formatjs/ecma402-abstract": "2.0.0", + "@formatjs/icu-skeleton-parser": "1.8.2", + "tslib": "^2.4.0" + } + }, + "node_modules/@formatjs/icu-skeleton-parser": { + "version": "1.8.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@formatjs/ecma402-abstract": "2.0.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@formatjs/intl-localematcher": { + "version": "0.5.4", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@fortawesome/fontawesome-common-types": { + "version": "6.6.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/@fortawesome/fontawesome-svg-core": { + "version": "6.6.0", + "license": "MIT", + "dependencies": { + "@fortawesome/fontawesome-common-types": "6.6.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@fortawesome/free-brands-svg-icons": { + "version": "6.6.0", + "license": "(CC-BY-4.0 AND MIT)", + "dependencies": { + "@fortawesome/fontawesome-common-types": "6.6.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@fortawesome/free-solid-svg-icons": { + "version": "6.6.0", + "license": "(CC-BY-4.0 AND MIT)", + "dependencies": { + "@fortawesome/fontawesome-common-types": "6.6.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@fortawesome/react-fontawesome": { + "version": "0.2.2", + "license": "MIT", + "dependencies": { + "prop-types": "^15.8.1" + }, + "peerDependencies": { + "@fortawesome/fontawesome-svg-core": "~1 || ~6", + "react": ">=16.3" + } + }, + "node_modules/@giscus/react": { + "version": "3.0.0", + "dependencies": { + "giscus": "^1.5.0" + }, + "peerDependencies": { + "react": "^16 || ^17 || ^18", + "react-dom": "^16 || ^17 || ^18" + } + }, + "node_modules/@griffel/core": { + "version": "1.17.0", + "license": "MIT", + "dependencies": { + "@emotion/hash": "^0.9.0", + "@griffel/style-types": "^1.2.0", + "csstype": "^3.1.3", + "rtl-css-js": "^1.16.1", + "stylis": "^4.2.0", + "tslib": "^2.1.0" + } + }, + "node_modules/@griffel/react": { + "version": "1.5.23", + "license": "MIT", + "dependencies": { + "@griffel/core": "^1.17.0", + "tslib": "^2.1.0" + }, + "peerDependencies": { + "react": ">=16.8.0 <19.0.0" + } + }, + "node_modules/@griffel/style-types": { + "version": "1.2.0", + "license": "MIT", + "dependencies": { + "csstype": "^3.1.3" + } + }, + "node_modules/@hapi/hoek": { + "version": "9.3.0", + "license": "BSD-3-Clause" + }, + "node_modules/@hapi/topo": { + "version": "5.1.0", + "license": "BSD-3-Clause", + "dependencies": { + "@hapi/hoek": "^9.0.0" + } + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-regex": { + "version": "6.0.1", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@jest/schemas": { + "version": "29.6.3", + "license": "MIT", + "dependencies": { + "@sinclair/typebox": "^0.27.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/types": { + "version": "29.6.3", + "license": "MIT", + "dependencies": { + "@jest/schemas": "^29.6.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.5", + "license": "MIT", + "dependencies": { + "@jridgewell/set-array": "^1.2.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.1", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.2.1", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.5", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.0", + "@jridgewell/trace-mapping": "^0.3.9" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@leichtgewicht/ip-codec": { + "version": "2.0.4", + "license": "MIT" + }, + "node_modules/@lit-labs/ssr-dom-shim": { + "version": "1.2.0", + "license": "BSD-3-Clause" + }, + "node_modules/@lit/reactive-element": { + "version": "2.0.4", + "license": "BSD-3-Clause", + "dependencies": { + "@lit-labs/ssr-dom-shim": "^1.2.0" + } + }, + "node_modules/@mdx-js/mdx": { + "version": "3.0.1", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/mdx": "^2.0.0", + "collapse-white-space": "^2.0.0", + "devlop": "^1.0.0", + "estree-util-build-jsx": "^3.0.0", + "estree-util-is-identifier-name": "^3.0.0", + "estree-util-to-js": "^2.0.0", + "estree-walker": "^3.0.0", + "hast-util-to-estree": "^3.0.0", + "hast-util-to-jsx-runtime": "^2.0.0", + "markdown-extensions": "^2.0.0", + "periscopic": "^3.0.0", + "remark-mdx": "^3.0.0", + "remark-parse": "^11.0.0", + "remark-rehype": "^11.0.0", + "source-map": "^0.7.0", + "unified": "^11.0.0", + "unist-util-position-from-estree": "^2.0.0", + "unist-util-stringify-position": "^4.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/@mdx-js/react": { + "version": "3.0.1", + "license": "MIT", + "dependencies": { + "@types/mdx": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + }, + "peerDependencies": { + "@types/react": ">=16", + "react": ">=16" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@paulirish/trace_engine": { + "version": "0.0.32", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/@philpl/buble": { + "version": "0.19.7", + "license": "MIT", + "dependencies": { + "acorn": "^6.1.1", + "acorn-class-fields": "^0.2.1", + "acorn-dynamic-import": "^4.0.0", + "acorn-jsx": "^5.0.1", + "chalk": "^2.4.2", + "magic-string": "^0.25.2", + "minimist": "^1.2.0", + "os-homedir": "^1.0.1", + "regexpu-core": "^4.5.4" + }, + "bin": { + "buble": "bin/buble" + } + }, + "node_modules/@philpl/buble/node_modules/acorn": { + "version": "6.4.2", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/@philpl/buble/node_modules/acorn-class-fields": { + "version": "0.2.1", + "license": "MIT", + "engines": { + "node": ">=4.8.2" + }, + "peerDependencies": { + "acorn": "^6.0.0" + } + }, + "node_modules/@philpl/buble/node_modules/acorn-dynamic-import": { + "version": "4.0.0", + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0" + } + }, + "node_modules/@philpl/buble/node_modules/ansi-styles": { + "version": "3.2.1", + "license": "MIT", + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@philpl/buble/node_modules/chalk": { + "version": "2.4.2", + "license": "MIT", + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@philpl/buble/node_modules/color-convert": { + "version": "1.9.3", + "license": "MIT", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/@philpl/buble/node_modules/color-name": { + "version": "1.1.3", + "license": "MIT" + }, + "node_modules/@philpl/buble/node_modules/escape-string-regexp": { + "version": "1.0.5", + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@philpl/buble/node_modules/has-flag": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/@philpl/buble/node_modules/jsesc": { + "version": "0.5.0", + "bin": { + "jsesc": "bin/jsesc" + } + }, + "node_modules/@philpl/buble/node_modules/regenerate-unicode-properties": { + "version": "9.0.0", + "license": "MIT", + "dependencies": { + "regenerate": "^1.4.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@philpl/buble/node_modules/regexpu-core": { + "version": "4.8.0", + "license": "MIT", + "dependencies": { + "regenerate": "^1.4.2", + "regenerate-unicode-properties": "^9.0.0", + "regjsgen": "^0.5.2", + "regjsparser": "^0.7.0", + "unicode-match-property-ecmascript": "^2.0.0", + "unicode-match-property-value-ecmascript": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@philpl/buble/node_modules/regjsparser": { + "version": "0.7.0", + "license": "BSD-2-Clause", + "dependencies": { + "jsesc": "~0.5.0" + }, + "bin": { + "regjsparser": "bin/parser" + } + }, + "node_modules/@philpl/buble/node_modules/supports-color": { + "version": "5.5.0", + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@pnpm/config.env-replace": { + "version": "1.1.0", + "license": "MIT", + "engines": { + "node": ">=12.22.0" + } + }, + "node_modules/@pnpm/network.ca-file": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "graceful-fs": "4.2.10" + }, + "engines": { + "node": ">=12.22.0" + } + }, + "node_modules/@pnpm/network.ca-file/node_modules/graceful-fs": { + "version": "4.2.10", + "license": "ISC" + }, + "node_modules/@pnpm/npm-conf": { + "version": "2.2.2", + "license": "MIT", + "dependencies": { + "@pnpm/config.env-replace": "^1.1.0", + "@pnpm/network.ca-file": "^1.0.1", + "config-chain": "^1.1.11" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@polka/url": { + "version": "1.0.0-next.24", + "license": "MIT" + }, + "node_modules/@popperjs/core": { + "version": "2.11.8", + "license": "MIT", + "peer": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/popperjs" + } + }, + "node_modules/@puppeteer/browsers": { + "version": "2.4.0", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "debug": "^4.3.6", + "extract-zip": "^2.0.1", + "progress": "^2.0.3", + "proxy-agent": "^6.4.0", + "semver": "^7.6.3", + "tar-fs": "^3.0.6", + "unbzip2-stream": "^1.4.3", + "yargs": "^17.7.2" + }, + "bin": { + "browsers": "lib/cjs/main-cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@rollup/plugin-babel": { + "version": "5.3.1", + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.10.4", + "@rollup/pluginutils": "^3.1.0" + }, + "engines": { + "node": ">= 10.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0", + "@types/babel__core": "^7.1.9", + "rollup": "^1.20.0||^2.0.0" + }, + "peerDependenciesMeta": { + "@types/babel__core": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-node-resolve": { + "version": "15.3.0", + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "@types/resolve": "1.20.2", + "deepmerge": "^4.2.2", + "is-module": "^1.0.0", + "resolve": "^1.22.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^2.78.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-node-resolve/node_modules/@rollup/pluginutils": { + "version": "5.1.2", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^2.0.2", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-node-resolve/node_modules/estree-walker": { + "version": "2.0.2", + "license": "MIT" + }, + "node_modules/@rollup/plugin-replace": { + "version": "2.4.2", + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^3.1.0", + "magic-string": "^0.25.7" + }, + "peerDependencies": { + "rollup": "^1.20.0 || ^2.0.0" + } + }, + "node_modules/@rollup/plugin-terser": { + "version": "0.4.4", + "license": "MIT", + "dependencies": { + "serialize-javascript": "^6.0.1", + "smob": "^1.0.0", + "terser": "^5.17.4" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/pluginutils": { + "version": "3.1.0", + "license": "MIT", + "dependencies": { + "@types/estree": "0.0.39", + "estree-walker": "^1.0.1", + "picomatch": "^2.2.2" + }, + "engines": { + "node": ">= 8.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0" + } + }, + "node_modules/@rollup/pluginutils/node_modules/@types/estree": { + "version": "0.0.39", + "license": "MIT" + }, + "node_modules/@rollup/pluginutils/node_modules/estree-walker": { + "version": "1.0.1", + "license": "MIT" + }, + "node_modules/@sentry/core": { + "version": "6.19.7", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@sentry/hub": "6.19.7", + "@sentry/minimal": "6.19.7", + "@sentry/types": "6.19.7", + "@sentry/utils": "6.19.7", + "tslib": "^1.9.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@sentry/core/node_modules/tslib": { + "version": "1.14.1", + "dev": true, + "license": "0BSD" + }, + "node_modules/@sentry/hub": { + "version": "6.19.7", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@sentry/types": "6.19.7", + "@sentry/utils": "6.19.7", + "tslib": "^1.9.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@sentry/hub/node_modules/tslib": { + "version": "1.14.1", + "dev": true, + "license": "0BSD" + }, + "node_modules/@sentry/minimal": { + "version": "6.19.7", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@sentry/hub": "6.19.7", + "@sentry/types": "6.19.7", + "tslib": "^1.9.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@sentry/minimal/node_modules/tslib": { + "version": "1.14.1", + "dev": true, + "license": "0BSD" + }, + "node_modules/@sentry/node": { + "version": "6.19.7", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@sentry/core": "6.19.7", + "@sentry/hub": "6.19.7", + "@sentry/types": "6.19.7", + "@sentry/utils": "6.19.7", + "cookie": "^0.4.1", + "https-proxy-agent": "^5.0.0", + "lru_map": "^0.3.3", + "tslib": "^1.9.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@sentry/node/node_modules/cookie": { + "version": "0.4.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/@sentry/node/node_modules/tslib": { + "version": "1.14.1", + "dev": true, + "license": "0BSD" + }, + "node_modules/@sentry/types": { + "version": "6.19.7", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=6" + } + }, + "node_modules/@sentry/utils": { + "version": "6.19.7", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@sentry/types": "6.19.7", + "tslib": "^1.9.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@sentry/utils/node_modules/tslib": { + "version": "1.14.1", + "dev": true, + "license": "0BSD" + }, + "node_modules/@sideway/address": { + "version": "4.1.5", + "license": "BSD-3-Clause", + "dependencies": { + "@hapi/hoek": "^9.0.0" + } + }, + "node_modules/@sideway/formula": { + "version": "3.0.1", + "license": "BSD-3-Clause" + }, + "node_modules/@sideway/pinpoint": { + "version": "2.0.0", + "license": "BSD-3-Clause" + }, + "node_modules/@sinclair/typebox": { + "version": "0.27.8", + "license": "MIT" + }, + "node_modules/@sindresorhus/is": { + "version": "4.6.0", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/@slorber/react-ideal-image": { + "version": "0.0.12", + "license": "MIT", + "engines": { + "node": ">= 8.9.0", + "npm": "> 3" + }, + "peerDependencies": { + "prop-types": ">=15", + "react": ">=0.14.x", + "react-waypoint": ">=9.0.2" + } + }, + "node_modules/@slorber/remark-comment": { + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "micromark-factory-space": "^1.0.0", + "micromark-util-character": "^1.1.0", + "micromark-util-symbol": "^1.0.1" + } + }, + "node_modules/@surma/rollup-plugin-off-main-thread": { + "version": "2.2.3", + "license": "Apache-2.0", + "dependencies": { + "ejs": "^3.1.6", + "json5": "^2.2.0", + "magic-string": "^0.25.0", + "string.prototype.matchall": "^4.0.6" + } + }, + "node_modules/@svgr/babel-plugin-add-jsx-attribute": { + "version": "8.0.0", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-plugin-remove-jsx-attribute": { + "version": "8.0.0", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-plugin-remove-jsx-empty-expression": { + "version": "8.0.0", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-plugin-replace-jsx-attribute-value": { + "version": "8.0.0", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-plugin-svg-dynamic-title": { + "version": "8.0.0", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-plugin-svg-em-dimensions": { + "version": "8.0.0", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-plugin-transform-react-native-svg": { + "version": "8.1.0", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-plugin-transform-svg-component": { + "version": "8.0.0", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/babel-preset": { + "version": "8.1.0", + "license": "MIT", + "dependencies": { + "@svgr/babel-plugin-add-jsx-attribute": "8.0.0", + "@svgr/babel-plugin-remove-jsx-attribute": "8.0.0", + "@svgr/babel-plugin-remove-jsx-empty-expression": "8.0.0", + "@svgr/babel-plugin-replace-jsx-attribute-value": "8.0.0", + "@svgr/babel-plugin-svg-dynamic-title": "8.0.0", + "@svgr/babel-plugin-svg-em-dimensions": "8.0.0", + "@svgr/babel-plugin-transform-react-native-svg": "8.1.0", + "@svgr/babel-plugin-transform-svg-component": "8.0.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@svgr/core": { + "version": "8.1.0", + "license": "MIT", + "dependencies": { + "@babel/core": "^7.21.3", + "@svgr/babel-preset": "8.1.0", + "camelcase": "^6.2.0", + "cosmiconfig": "^8.1.3", + "snake-case": "^3.0.4" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + } + }, + "node_modules/@svgr/hast-util-to-babel-ast": { + "version": "8.0.0", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.21.3", + "entities": "^4.4.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + } + }, + "node_modules/@svgr/plugin-jsx": { + "version": "8.1.0", + "license": "MIT", + "dependencies": { + "@babel/core": "^7.21.3", + "@svgr/babel-preset": "8.1.0", + "@svgr/hast-util-to-babel-ast": "8.0.0", + "svg-parser": "^2.0.4" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@svgr/core": "*" + } + }, + "node_modules/@svgr/plugin-svgo": { + "version": "8.1.0", + "license": "MIT", + "dependencies": { + "cosmiconfig": "^8.1.3", + "deepmerge": "^4.3.1", + "svgo": "^3.0.2" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + }, + "peerDependencies": { + "@svgr/core": "*" + } + }, + "node_modules/@svgr/webpack": { + "version": "8.1.0", + "license": "MIT", + "dependencies": { + "@babel/core": "^7.21.3", + "@babel/plugin-transform-react-constant-elements": "^7.21.3", + "@babel/preset-env": "^7.20.2", + "@babel/preset-react": "^7.18.6", + "@babel/preset-typescript": "^7.21.0", + "@svgr/core": "8.1.0", + "@svgr/plugin-jsx": "8.1.0", + "@svgr/plugin-svgo": "8.1.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/gregberge" + } + }, + "node_modules/@szmarczak/http-timer": { + "version": "5.0.1", + "license": "MIT", + "dependencies": { + "defer-to-connect": "^2.0.1" + }, + "engines": { + "node": ">=14.16" + } + }, + "node_modules/@tootallnate/quickjs-emscripten": { + "version": "0.23.0", + "dev": true, + "license": "MIT" + }, + "node_modules/@trysound/sax": { + "version": "0.2.0", + "license": "ISC", + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/@tsparticles/basic": { + "version": "3.5.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/matteobruni" + }, + { + "type": "github", + "url": "https://github.com/sponsors/tsparticles" + }, + { + "type": "buymeacoffee", + "url": "https://www.buymeacoffee.com/matteobruni" + } + ], + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0", + "@tsparticles/move-base": "^3.5.0", + "@tsparticles/shape-circle": "^3.5.0", + "@tsparticles/updater-color": "^3.5.0", + "@tsparticles/updater-opacity": "^3.5.0", + "@tsparticles/updater-out-modes": "^3.5.0", + "@tsparticles/updater-size": "^3.5.0" + } + }, + "node_modules/@tsparticles/engine": { + "version": "3.5.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/matteobruni" + }, + { + "type": "github", + "url": "https://github.com/sponsors/tsparticles" + }, + { + "type": "buymeacoffee", + "url": "https://www.buymeacoffee.com/matteobruni" + } + ], + "hasInstallScript": true, + "license": "MIT" + }, + "node_modules/@tsparticles/interaction-external-attract": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/interaction-external-bounce": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/interaction-external-bubble": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/interaction-external-connect": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/interaction-external-grab": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/interaction-external-pause": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/interaction-external-push": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/interaction-external-remove": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/interaction-external-repulse": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/interaction-external-slow": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/interaction-particles-attract": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/interaction-particles-collisions": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/interaction-particles-links": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/move-base": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/move-parallax": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/plugin-easing-quad": { + "version": "3.5.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/matteobruni" + }, + { + "type": "github", + "url": "https://github.com/sponsors/tsparticles" + }, + { + "type": "buymeacoffee", + "url": "https://www.buymeacoffee.com/matteobruni" + } + ], + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/react": { + "version": "3.0.0", + "peerDependencies": { + "@tsparticles/engine": "^3.0.2", + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@tsparticles/shape-circle": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/shape-emoji": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/shape-image": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/shape-line": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/shape-polygon": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/shape-square": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/shape-star": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/slim": { + "version": "3.5.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/matteobruni" + }, + { + "type": "github", + "url": "https://github.com/sponsors/tsparticles" + }, + { + "type": "buymeacoffee", + "url": "https://www.buymeacoffee.com/matteobruni" + } + ], + "license": "MIT", + "dependencies": { + "@tsparticles/basic": "^3.5.0", + "@tsparticles/engine": "^3.5.0", + "@tsparticles/interaction-external-attract": "^3.5.0", + "@tsparticles/interaction-external-bounce": "^3.5.0", + "@tsparticles/interaction-external-bubble": "^3.5.0", + "@tsparticles/interaction-external-connect": "^3.5.0", + "@tsparticles/interaction-external-grab": "^3.5.0", + "@tsparticles/interaction-external-pause": "^3.5.0", + "@tsparticles/interaction-external-push": "^3.5.0", + "@tsparticles/interaction-external-remove": "^3.5.0", + "@tsparticles/interaction-external-repulse": "^3.5.0", + "@tsparticles/interaction-external-slow": "^3.5.0", + "@tsparticles/interaction-particles-attract": "^3.5.0", + "@tsparticles/interaction-particles-collisions": "^3.5.0", + "@tsparticles/interaction-particles-links": "^3.5.0", + "@tsparticles/move-parallax": "^3.5.0", + "@tsparticles/plugin-easing-quad": "^3.5.0", + "@tsparticles/shape-emoji": "^3.5.0", + "@tsparticles/shape-image": "^3.5.0", + "@tsparticles/shape-line": "^3.5.0", + "@tsparticles/shape-polygon": "^3.5.0", + "@tsparticles/shape-square": "^3.5.0", + "@tsparticles/shape-star": "^3.5.0", + "@tsparticles/updater-life": "^3.5.0", + "@tsparticles/updater-rotate": "^3.5.0", + "@tsparticles/updater-stroke-color": "^3.5.0" + } + }, + "node_modules/@tsparticles/updater-color": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/updater-life": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/updater-opacity": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/updater-out-modes": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/updater-rotate": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/updater-size": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@tsparticles/updater-stroke-color": { + "version": "3.5.0", + "license": "MIT", + "dependencies": { + "@tsparticles/engine": "^3.5.0" + } + }, + "node_modules/@types/acorn": { + "version": "4.0.6", + "license": "MIT", + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/@types/body-parser": { + "version": "1.19.5", + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/bonjour": { + "version": "3.5.13", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/connect-history-api-fallback": { + "version": "1.5.4", + "license": "MIT", + "dependencies": { + "@types/express-serve-static-core": "*", + "@types/node": "*" + } + }, + "node_modules/@types/d3-array": { + "version": "3.2.1", + "license": "MIT" + }, + "node_modules/@types/d3-color": { + "version": "3.1.3", + "license": "MIT" + }, + "node_modules/@types/d3-ease": { + "version": "3.0.2", + "license": "MIT" + }, + "node_modules/@types/d3-interpolate": { + "version": "3.0.4", + "license": "MIT", + "dependencies": { + "@types/d3-color": "*" + } + }, + "node_modules/@types/d3-path": { + "version": "3.1.0", + "license": "MIT" + }, + "node_modules/@types/d3-scale": { + "version": "4.0.8", + "license": "MIT", + "dependencies": { + "@types/d3-time": "*" + } + }, + "node_modules/@types/d3-scale-chromatic": { + "version": "3.0.3", + "license": "MIT" + }, + "node_modules/@types/d3-shape": { + "version": "3.1.6", + "license": "MIT", + "dependencies": { + "@types/d3-path": "*" + } + }, + "node_modules/@types/d3-time": { + "version": "3.0.3", + "license": "MIT" + }, + "node_modules/@types/d3-timer": { + "version": "3.0.2", + "license": "MIT" + }, + "node_modules/@types/debug": { + "version": "4.1.12", + "license": "MIT", + "dependencies": { + "@types/ms": "*" + } + }, + "node_modules/@types/estree": { + "version": "1.0.5", + "license": "MIT" + }, + "node_modules/@types/estree-jsx": { + "version": "1.0.4", + "license": "MIT", + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/@types/express": { + "version": "4.17.21", + "license": "MIT", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "*" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.17.43", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/gtag.js": { + "version": "0.0.12", + "license": "MIT" + }, + "node_modules/@types/hast": { + "version": "3.0.4", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/history": { + "version": "4.7.11", + "license": "MIT" + }, + "node_modules/@types/html-minifier-terser": { + "version": "6.1.0", + "license": "MIT" + }, + "node_modules/@types/http-cache-semantics": { + "version": "4.0.4", + "license": "MIT" + }, + "node_modules/@types/http-errors": { + "version": "2.0.4", + "license": "MIT" + }, + "node_modules/@types/http-proxy": { + "version": "1.17.14", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/istanbul-lib-coverage": { + "version": "2.0.6", + "license": "MIT" + }, + "node_modules/@types/istanbul-lib-report": { + "version": "3.0.3", + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-coverage": "*" + } + }, + "node_modules/@types/istanbul-reports": { + "version": "3.0.4", + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-report": "*" + } + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "license": "MIT" + }, + "node_modules/@types/katex": { + "version": "0.16.7", + "license": "MIT" + }, + "node_modules/@types/mdast": { + "version": "4.0.3", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/mdx": { + "version": "2.0.11", + "license": "MIT" + }, + "node_modules/@types/mime": { + "version": "1.3.5", + "license": "MIT" + }, + "node_modules/@types/ms": { + "version": "0.7.34", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.7.4", + "license": "MIT", + "dependencies": { + "undici-types": "~6.19.2" + } + }, + "node_modules/@types/node-forge": { + "version": "1.3.11", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/parse-json": { + "version": "4.0.2", + "license": "MIT" + }, + "node_modules/@types/prismjs": { + "version": "1.26.3", + "license": "MIT" + }, + "node_modules/@types/prop-types": { + "version": "15.7.11", + "license": "MIT" + }, + "node_modules/@types/qs": { + "version": "6.9.11", + "license": "MIT" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "18.3.11", + "license": "MIT", + "dependencies": { + "@types/prop-types": "*", + "csstype": "^3.0.2" + } + }, + "node_modules/@types/react-dom": { + "version": "18.3.0", + "license": "MIT", + "dependencies": { + "@types/react": "*" + } + }, + "node_modules/@types/react-router": { + "version": "5.1.20", + "license": "MIT", + "dependencies": { + "@types/history": "^4.7.11", + "@types/react": "*" + } + }, + "node_modules/@types/react-router-config": { + "version": "5.0.11", + "license": "MIT", + "dependencies": { + "@types/history": "^4.7.11", + "@types/react": "*", + "@types/react-router": "^5.1.0" + } + }, + "node_modules/@types/react-router-dom": { + "version": "5.3.3", + "license": "MIT", + "dependencies": { + "@types/history": "^4.7.11", + "@types/react": "*", + "@types/react-router": "*" + } + }, + "node_modules/@types/resolve": { + "version": "1.20.2", + "license": "MIT" + }, + "node_modules/@types/retry": { + "version": "0.12.0", + "license": "MIT" + }, + "node_modules/@types/sax": { + "version": "1.2.7", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/send": { + "version": "0.17.4", + "license": "MIT", + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/serve-index": { + "version": "1.9.4", + "license": "MIT", + "dependencies": { + "@types/express": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.5", + "license": "MIT", + "dependencies": { + "@types/http-errors": "*", + "@types/mime": "*", + "@types/node": "*" + } + }, + "node_modules/@types/sockjs": { + "version": "0.3.36", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/stylis": { + "version": "4.2.5", + "license": "MIT" + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "license": "MIT" + }, + "node_modules/@types/unist": { + "version": "3.0.2", + "license": "MIT" + }, + "node_modules/@types/use-sync-external-store": { + "version": "0.0.3", + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.5.10", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/yargs": { + "version": "17.0.32", + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.3", + "license": "MIT" + }, + "node_modules/@types/yauzl": { + "version": "2.10.3", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@ungap/structured-clone": { + "version": "1.2.0", + "license": "ISC" + }, + "node_modules/@vercel/analytics": { + "version": "1.2.2", + "license": "MPL-2.0", + "dependencies": { + "server-only": "^0.0.1" + }, + "peerDependencies": { + "next": ">= 13", + "react": "^18 || ^19" + }, + "peerDependenciesMeta": { + "next": { + "optional": true + }, + "react": { + "optional": true + } + } + }, + "node_modules/@webassemblyjs/ast": { + "version": "1.12.1", + "license": "MIT", + "dependencies": { + "@webassemblyjs/helper-numbers": "1.11.6", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6" + } + }, + "node_modules/@webassemblyjs/floating-point-hex-parser": { + "version": "1.11.6", + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-api-error": { + "version": "1.11.6", + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-buffer": { + "version": "1.12.1", + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-code-frame": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/wast-printer": "1.9.0" + } + }, + "node_modules/@webassemblyjs/helper-code-frame/node_modules/@webassemblyjs/ast": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/helper-module-context": "1.9.0", + "@webassemblyjs/helper-wasm-bytecode": "1.9.0", + "@webassemblyjs/wast-parser": "1.9.0" + } + }, + "node_modules/@webassemblyjs/helper-code-frame/node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.9.0", + "license": "MIT", + "peer": true + }, + "node_modules/@webassemblyjs/helper-code-frame/node_modules/@webassemblyjs/wast-printer": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/wast-parser": "1.9.0", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/helper-fsm": { + "version": "1.9.0", + "license": "ISC", + "peer": true + }, + "node_modules/@webassemblyjs/helper-module-context": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.9.0" + } + }, + "node_modules/@webassemblyjs/helper-module-context/node_modules/@webassemblyjs/ast": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/helper-module-context": "1.9.0", + "@webassemblyjs/helper-wasm-bytecode": "1.9.0", + "@webassemblyjs/wast-parser": "1.9.0" + } + }, + "node_modules/@webassemblyjs/helper-module-context/node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.9.0", + "license": "MIT", + "peer": true + }, + "node_modules/@webassemblyjs/helper-numbers": { + "version": "1.11.6", + "license": "MIT", + "dependencies": { + "@webassemblyjs/floating-point-hex-parser": "1.11.6", + "@webassemblyjs/helper-api-error": "1.11.6", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.11.6", + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-wasm-section": { + "version": "1.12.1", + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.12.1", + "@webassemblyjs/helper-buffer": "1.12.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/wasm-gen": "1.12.1" + } + }, + "node_modules/@webassemblyjs/ieee754": { + "version": "1.11.6", + "license": "MIT", + "dependencies": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "node_modules/@webassemblyjs/leb128": { + "version": "1.11.6", + "license": "Apache-2.0", + "dependencies": { + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/utf8": { + "version": "1.11.6", + "license": "MIT" + }, + "node_modules/@webassemblyjs/wasm-edit": { + "version": "1.12.1", + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.12.1", + "@webassemblyjs/helper-buffer": "1.12.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/helper-wasm-section": "1.12.1", + "@webassemblyjs/wasm-gen": "1.12.1", + "@webassemblyjs/wasm-opt": "1.12.1", + "@webassemblyjs/wasm-parser": "1.12.1", + "@webassemblyjs/wast-printer": "1.12.1" + } + }, + "node_modules/@webassemblyjs/wasm-gen": { + "version": "1.12.1", + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.12.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/ieee754": "1.11.6", + "@webassemblyjs/leb128": "1.11.6", + "@webassemblyjs/utf8": "1.11.6" + } + }, + "node_modules/@webassemblyjs/wasm-opt": { + "version": "1.12.1", + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.12.1", + "@webassemblyjs/helper-buffer": "1.12.1", + "@webassemblyjs/wasm-gen": "1.12.1", + "@webassemblyjs/wasm-parser": "1.12.1" + } + }, + "node_modules/@webassemblyjs/wasm-parser": { + "version": "1.12.1", + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.12.1", + "@webassemblyjs/helper-api-error": "1.11.6", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/ieee754": "1.11.6", + "@webassemblyjs/leb128": "1.11.6", + "@webassemblyjs/utf8": "1.11.6" + } + }, + "node_modules/@webassemblyjs/wast-parser": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/floating-point-hex-parser": "1.9.0", + "@webassemblyjs/helper-api-error": "1.9.0", + "@webassemblyjs/helper-code-frame": "1.9.0", + "@webassemblyjs/helper-fsm": "1.9.0", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/wast-parser/node_modules/@webassemblyjs/ast": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/helper-module-context": "1.9.0", + "@webassemblyjs/helper-wasm-bytecode": "1.9.0", + "@webassemblyjs/wast-parser": "1.9.0" + } + }, + "node_modules/@webassemblyjs/wast-parser/node_modules/@webassemblyjs/floating-point-hex-parser": { + "version": "1.9.0", + "license": "MIT", + "peer": true + }, + "node_modules/@webassemblyjs/wast-parser/node_modules/@webassemblyjs/helper-api-error": { + "version": "1.9.0", + "license": "MIT", + "peer": true + }, + "node_modules/@webassemblyjs/wast-parser/node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.9.0", + "license": "MIT", + "peer": true + }, + "node_modules/@webassemblyjs/wast-printer": { + "version": "1.12.1", + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.12.1", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@xtuc/ieee754": { + "version": "1.2.0", + "license": "BSD-3-Clause" + }, + "node_modules/@xtuc/long": { + "version": "4.2.2", + "license": "Apache-2.0" + }, + "node_modules/accepts": { + "version": "1.3.8", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/accepts/node_modules/mime-db": { + "version": "1.52.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/accepts/node_modules/mime-types": { + "version": "2.1.35", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "8.11.3", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-import-attributes": { + "version": "1.9.5", + "license": "MIT", + "peerDependencies": { + "acorn": "^8" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.2", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/address": { + "version": "1.2.2", + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/aggregate-error": { + "version": "3.1.0", + "license": "MIT", + "dependencies": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ajv": { + "version": "8.12.0", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-errors": { + "version": "1.0.1", + "license": "MIT", + "peer": true, + "peerDependencies": { + "ajv": ">=5.0.0" + } + }, + "node_modules/ajv-formats": { + "version": "2.1.1", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ajv-keywords": { + "version": "5.1.0", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3" + }, + "peerDependencies": { + "ajv": "^8.8.2" + } + }, + "node_modules/algoliasearch": { + "version": "4.23.3", + "license": "MIT", + "dependencies": { + "@algolia/cache-browser-local-storage": "4.23.3", + "@algolia/cache-common": "4.23.3", + "@algolia/cache-in-memory": "4.23.3", + "@algolia/client-account": "4.23.3", + "@algolia/client-analytics": "4.23.3", + "@algolia/client-common": "4.23.3", + "@algolia/client-personalization": "4.23.3", + "@algolia/client-search": "4.23.3", + "@algolia/logger-common": "4.23.3", + "@algolia/logger-console": "4.23.3", + "@algolia/recommend": "4.23.3", + "@algolia/requester-browser-xhr": "4.23.3", + "@algolia/requester-common": "4.23.3", + "@algolia/requester-node-http": "4.23.3", + "@algolia/transporter": "4.23.3" + } + }, + "node_modules/algoliasearch-helper": { + "version": "3.19.0", + "license": "MIT", + "dependencies": { + "@algolia/events": "^4.0.1" + }, + "peerDependencies": { + "algoliasearch": ">= 3.1 < 6" + } + }, + "node_modules/ansi-align": { + "version": "3.0.1", + "license": "ISC", + "dependencies": { + "string-width": "^4.1.0" + } + }, + "node_modules/ansi-align/node_modules/emoji-regex": { + "version": "8.0.0", + "license": "MIT" + }, + "node_modules/ansi-align/node_modules/string-width": { + "version": "4.2.3", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-colors": { + "version": "4.1.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-html-community": { + "version": "0.0.8", + "engines": [ + "node >= 0.8.0" + ], + "license": "Apache-2.0", + "bin": { + "ansi-html": "bin/ansi-html" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/any-promise": { + "version": "1.3.0", + "license": "MIT" + }, + "node_modules/anymatch": { + "version": "3.1.3", + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/aproba": { + "version": "1.2.0", + "license": "ISC", + "peer": true + }, + "node_modules/arg": { + "version": "5.0.2", + "license": "MIT" + }, + "node_modules/argparse": { + "version": "2.0.1", + "license": "Python-2.0" + }, + "node_modules/arr-diff": { + "version": "4.0.0", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/arr-flatten": { + "version": "1.1.0", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/arr-union": { + "version": "3.1.0", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.1", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.5", + "is-array-buffer": "^3.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "license": "MIT" + }, + "node_modules/array-union": { + "version": "2.1.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/array-uniq": { + "version": "1.0.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/array-unique": { + "version": "0.3.2", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/arraybuffer.prototype.slice": { + "version": "1.0.3", + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "call-bind": "^1.0.5", + "define-properties": "^1.2.1", + "es-abstract": "^1.22.3", + "es-errors": "^1.2.1", + "get-intrinsic": "^1.2.3", + "is-array-buffer": "^3.0.4", + "is-shared-array-buffer": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/asn1.js": { + "version": "4.10.1", + "license": "MIT", + "peer": true, + "dependencies": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "node_modules/asn1.js/node_modules/bn.js": { + "version": "4.12.0", + "license": "MIT", + "peer": true + }, + "node_modules/assert": { + "version": "1.5.1", + "license": "MIT", + "peer": true, + "dependencies": { + "object.assign": "^4.1.4", + "util": "^0.10.4" + } + }, + "node_modules/assert/node_modules/inherits": { + "version": "2.0.3", + "license": "ISC", + "peer": true + }, + "node_modules/assert/node_modules/util": { + "version": "0.10.4", + "license": "MIT", + "peer": true, + "dependencies": { + "inherits": "2.0.3" + } + }, + "node_modules/assign-symbols": { + "version": "1.0.0", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ast-types": { + "version": "0.13.4", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/astring": { + "version": "1.8.6", + "license": "MIT", + "bin": { + "astring": "bin/astring" + } + }, + "node_modules/async": { + "version": "3.2.5", + "license": "MIT" + }, + "node_modules/async-each": { + "version": "1.0.6", + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "license": "MIT", + "optional": true, + "peer": true + }, + "node_modules/asynckit": { + "version": "0.4.0", + "license": "MIT" + }, + "node_modules/at-least-node": { + "version": "1.0.0", + "license": "ISC", + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/atob": { + "version": "2.1.2", + "license": "(MIT OR Apache-2.0)", + "peer": true, + "bin": { + "atob": "bin/atob.js" + }, + "engines": { + "node": ">= 4.5.0" + } + }, + "node_modules/autoprefixer": { + "version": "10.4.20", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/autoprefixer" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "browserslist": "^4.23.3", + "caniuse-lite": "^1.0.30001646", + "fraction.js": "^4.3.7", + "normalize-range": "^0.1.2", + "picocolors": "^1.0.1", + "postcss-value-parser": "^4.2.0" + }, + "bin": { + "autoprefixer": "bin/autoprefixer" + }, + "engines": { + "node": "^10 || ^12 || >=14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.6", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/axe-core": { + "version": "4.10.0", + "dev": true, + "license": "MPL-2.0", + "engines": { + "node": ">=4" + } + }, + "node_modules/axios": { + "version": "1.7.7", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/b4a": { + "version": "1.6.4", + "license": "ISC" + }, + "node_modules/babel-loader": { + "version": "9.1.3", + "license": "MIT", + "dependencies": { + "find-cache-dir": "^4.0.0", + "schema-utils": "^4.0.0" + }, + "engines": { + "node": ">= 14.15.0" + }, + "peerDependencies": { + "@babel/core": "^7.12.0", + "webpack": ">=5" + } + }, + "node_modules/babel-plugin-dynamic-import-node": { + "version": "2.3.3", + "license": "MIT", + "dependencies": { + "object.assign": "^4.1.0" + } + }, + "node_modules/babel-plugin-polyfill-corejs2": { + "version": "0.4.8", + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.22.6", + "@babel/helper-define-polyfill-provider": "^0.5.0", + "semver": "^6.3.1" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/babel-plugin-polyfill-corejs2/node_modules/semver": { + "version": "6.3.1", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/babel-plugin-polyfill-corejs3": { + "version": "0.9.0", + "license": "MIT", + "dependencies": { + "@babel/helper-define-polyfill-provider": "^0.5.0", + "core-js-compat": "^3.34.0" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/babel-plugin-polyfill-regenerator": { + "version": "0.5.5", + "license": "MIT", + "dependencies": { + "@babel/helper-define-polyfill-provider": "^0.5.0" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } + }, + "node_modules/bail": { + "version": "2.0.2", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/bare-events": { + "version": "2.4.2", + "license": "Apache-2.0", + "optional": true + }, + "node_modules/bare-fs": { + "version": "2.3.1", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "bare-events": "^2.0.0", + "bare-path": "^2.0.0", + "bare-stream": "^2.0.0" + } + }, + "node_modules/bare-os": { + "version": "2.4.0", + "license": "Apache-2.0", + "optional": true + }, + "node_modules/bare-path": { + "version": "2.1.3", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "bare-os": "^2.1.0" + } + }, + "node_modules/bare-stream": { + "version": "2.1.3", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "streamx": "^2.18.0" + } + }, + "node_modules/base": { + "version": "0.11.2", + "license": "MIT", + "peer": true, + "dependencies": { + "cache-base": "^1.0.1", + "class-utils": "^0.3.5", + "component-emitter": "^1.2.1", + "define-property": "^1.0.0", + "isobject": "^3.0.1", + "mixin-deep": "^1.2.0", + "pascalcase": "^0.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/base/node_modules/define-property": { + "version": "1.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "is-descriptor": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/base64url": { + "version": "3.0.1", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/basic-ftp": { + "version": "5.0.5", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/batch": { + "version": "0.6.1", + "license": "MIT" + }, + "node_modules/big.js": { + "version": "5.2.2", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/binary-extensions": { + "version": "2.2.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/bluebird": { + "version": "3.7.2", + "license": "MIT", + "peer": true + }, + "node_modules/bn.js": { + "version": "5.2.1", + "license": "MIT", + "peer": true + }, + "node_modules/body-parser": { + "version": "1.20.3", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/body-parser/node_modules/bytes": { + "version": "3.1.2", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/body-parser/node_modules/debug": { + "version": "2.6.9", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/body-parser/node_modules/ms": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/bonjour-service": { + "version": "1.2.1", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "multicast-dns": "^7.2.5" + } + }, + "node_modules/boolbase": { + "version": "1.0.0", + "license": "ISC" + }, + "node_modules/boxen": { + "version": "6.2.1", + "license": "MIT", + "dependencies": { + "ansi-align": "^3.0.1", + "camelcase": "^6.2.0", + "chalk": "^4.1.2", + "cli-boxes": "^3.0.0", + "string-width": "^5.0.1", + "type-fest": "^2.5.0", + "widest-line": "^4.0.1", + "wrap-ansi": "^8.0.1" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/brorand": { + "version": "1.1.0", + "license": "MIT", + "peer": true + }, + "node_modules/browserify-aes": { + "version": "1.2.0", + "license": "MIT", + "peer": true, + "dependencies": { + "buffer-xor": "^1.0.3", + "cipher-base": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.3", + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/browserify-cipher": { + "version": "1.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "browserify-aes": "^1.0.4", + "browserify-des": "^1.0.0", + "evp_bytestokey": "^1.0.0" + } + }, + "node_modules/browserify-des": { + "version": "1.0.2", + "license": "MIT", + "peer": true, + "dependencies": { + "cipher-base": "^1.0.1", + "des.js": "^1.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "node_modules/browserify-rsa": { + "version": "4.1.0", + "license": "MIT", + "peer": true, + "dependencies": { + "bn.js": "^5.0.0", + "randombytes": "^2.0.1" + } + }, + "node_modules/browserify-sign": { + "version": "4.2.3", + "license": "ISC", + "peer": true, + "dependencies": { + "bn.js": "^5.2.1", + "browserify-rsa": "^4.1.0", + "create-hash": "^1.2.0", + "create-hmac": "^1.1.7", + "elliptic": "^6.5.5", + "hash-base": "~3.0", + "inherits": "^2.0.4", + "parse-asn1": "^5.1.7", + "readable-stream": "^2.3.8", + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">= 0.12" + } + }, + "node_modules/browserify-sign/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/browserify-sign/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "peer": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/browserify-sign/node_modules/readable-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "peer": true + }, + "node_modules/browserify-sign/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/browserify-sign/node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "peer": true + }, + "node_modules/browserify-zlib": { + "version": "0.2.0", + "license": "MIT", + "peer": true, + "dependencies": { + "pako": "~1.0.5" + } + }, + "node_modules/browserslist": { + "version": "4.24.0", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "caniuse-lite": "^1.0.30001663", + "electron-to-chromium": "^1.5.28", + "node-releases": "^2.0.18", + "update-browserslist-db": "^1.1.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/buffer-crc32": { + "version": "0.2.13", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "license": "MIT" + }, + "node_modules/buffer-xor": { + "version": "1.0.3", + "license": "MIT", + "peer": true + }, + "node_modules/builtin-status-codes": { + "version": "3.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/bytes": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/cacache": { + "version": "12.0.4", + "license": "ISC", + "peer": true, + "dependencies": { + "bluebird": "^3.5.5", + "chownr": "^1.1.1", + "figgy-pudding": "^3.5.1", + "glob": "^7.1.4", + "graceful-fs": "^4.1.15", + "infer-owner": "^1.0.3", + "lru-cache": "^5.1.1", + "mississippi": "^3.0.0", + "mkdirp": "^0.5.1", + "move-concurrently": "^1.0.1", + "promise-inflight": "^1.0.1", + "rimraf": "^2.6.3", + "ssri": "^6.0.1", + "unique-filename": "^1.1.1", + "y18n": "^4.0.0" + } + }, + "node_modules/cacache/node_modules/rimraf": { + "version": "2.7.1", + "license": "ISC", + "peer": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, + "node_modules/cache-base": { + "version": "1.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "collection-visit": "^1.0.0", + "component-emitter": "^1.2.1", + "get-value": "^2.0.6", + "has-value": "^1.0.0", + "isobject": "^3.0.1", + "set-value": "^2.0.0", + "to-object-path": "^0.3.0", + "union-value": "^1.0.0", + "unset-value": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/cacheable-lookup": { + "version": "7.0.0", + "license": "MIT", + "engines": { + "node": ">=14.16" + } + }, + "node_modules/cacheable-request": { + "version": "10.2.14", + "license": "MIT", + "dependencies": { + "@types/http-cache-semantics": "^4.0.2", + "get-stream": "^6.0.1", + "http-cache-semantics": "^4.1.1", + "keyv": "^4.5.3", + "mimic-response": "^4.0.0", + "normalize-url": "^8.0.0", + "responselike": "^3.0.0" + }, + "engines": { + "node": ">=14.16" + } + }, + "node_modules/cacheable-request/node_modules/normalize-url": { + "version": "8.0.0", + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/call-bind": { + "version": "1.0.7", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/camel-case": { + "version": "4.1.2", + "license": "MIT", + "dependencies": { + "pascal-case": "^3.1.2", + "tslib": "^2.0.3" + } + }, + "node_modules/camelcase": { + "version": "6.3.0", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/camelcase-css": { + "version": "2.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/camelize": { + "version": "1.0.1", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/caniuse-api": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "browserslist": "^4.0.0", + "caniuse-lite": "^1.0.0", + "lodash.memoize": "^4.1.2", + "lodash.uniq": "^4.5.0" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001666", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/ccount": { + "version": "2.0.1", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/char-regex": { + "version": "1.0.2", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/character-entities": { + "version": "2.0.2", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-html4": { + "version": "2.1.0", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-legacy": { + "version": "3.0.0", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-reference-invalid": { + "version": "2.0.1", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/cheerio": { + "version": "1.0.0-rc.12", + "license": "MIT", + "dependencies": { + "cheerio-select": "^2.1.0", + "dom-serializer": "^2.0.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1", + "htmlparser2": "^8.0.1", + "parse5": "^7.0.0", + "parse5-htmlparser2-tree-adapter": "^7.0.0" + }, + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/cheeriojs/cheerio?sponsor=1" + } + }, + "node_modules/cheerio-select": { + "version": "2.1.0", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-select": "^5.1.0", + "css-what": "^6.1.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/chokidar": { + "version": "3.5.3", + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "license": "ISC" + }, + "node_modules/chrome-launcher": { + "version": "1.1.2", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/node": "*", + "escape-string-regexp": "^4.0.0", + "is-wsl": "^2.2.0", + "lighthouse-logger": "^2.0.1" + }, + "bin": { + "print-chrome-path": "bin/print-chrome-path.js" + }, + "engines": { + "node": ">=12.13.0" + } + }, + "node_modules/chrome-trace-event": { + "version": "1.0.3", + "license": "MIT", + "engines": { + "node": ">=6.0" + } + }, + "node_modules/chromium-bidi": { + "version": "0.6.5", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "mitt": "3.0.1", + "urlpattern-polyfill": "10.0.0", + "zod": "3.23.8" + }, + "peerDependencies": { + "devtools-protocol": "*" + } + }, + "node_modules/ci-info": { + "version": "3.9.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cipher-base": { + "version": "1.0.4", + "license": "MIT", + "peer": true, + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/class-utils": { + "version": "0.3.6", + "license": "MIT", + "peer": true, + "dependencies": { + "arr-union": "^3.1.0", + "define-property": "^0.2.5", + "isobject": "^3.0.0", + "static-extend": "^0.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/class-utils/node_modules/define-property": { + "version": "0.2.5", + "license": "MIT", + "peer": true, + "dependencies": { + "is-descriptor": "^0.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/class-utils/node_modules/is-descriptor": { + "version": "0.1.7", + "license": "MIT", + "peer": true, + "dependencies": { + "is-accessor-descriptor": "^1.0.1", + "is-data-descriptor": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/class-variance-authority": { + "version": "0.7.0", + "license": "Apache-2.0", + "dependencies": { + "clsx": "2.0.0" + }, + "funding": { + "url": "https://joebell.co.uk" + } + }, + "node_modules/class-variance-authority/node_modules/clsx": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/classnames": { + "version": "2.5.1", + "license": "MIT" + }, + "node_modules/clean-css": { + "version": "5.3.3", + "license": "MIT", + "dependencies": { + "source-map": "~0.6.0" + }, + "engines": { + "node": ">= 10.0" + } + }, + "node_modules/clean-css/node_modules/source-map": { + "version": "0.6.1", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/clean-stack": { + "version": "2.2.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/cli-boxes": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-table3": { + "version": "0.6.3", + "license": "MIT", + "dependencies": { + "string-width": "^4.2.0" + }, + "engines": { + "node": "10.* || >= 12.*" + }, + "optionalDependencies": { + "@colors/colors": "1.5.0" + } + }, + "node_modules/cli-table3/node_modules/emoji-regex": { + "version": "8.0.0", + "license": "MIT" + }, + "node_modules/cli-table3/node_modules/string-width": { + "version": "4.2.3", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/cliui/node_modules/emoji-regex": { + "version": "8.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/cliui/node_modules/string-width": { + "version": "4.2.3", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/wrap-ansi": { + "version": "7.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/clone-deep": { + "version": "4.0.1", + "license": "MIT", + "dependencies": { + "is-plain-object": "^2.0.4", + "kind-of": "^6.0.2", + "shallow-clone": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/clone-deep/node_modules/is-plain-object": { + "version": "2.0.4", + "license": "MIT", + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/collapse-white-space": { + "version": "2.1.0", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/collection-visit": { + "version": "1.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "map-visit": "^1.0.0", + "object-visit": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/color": { + "version": "4.2.3", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1", + "color-string": "^1.9.0" + }, + "engines": { + "node": ">=12.5.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "license": "MIT" + }, + "node_modules/color-string": { + "version": "1.9.1", + "license": "MIT", + "dependencies": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + } + }, + "node_modules/colord": { + "version": "2.9.3", + "license": "MIT" + }, + "node_modules/colorette": { + "version": "2.0.20", + "license": "MIT" + }, + "node_modules/combine-promises": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/comma-separated-tokens": { + "version": "2.0.3", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/commander": { + "version": "5.1.0", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/common-path-prefix": { + "version": "3.0.0", + "license": "ISC" + }, + "node_modules/common-tags": { + "version": "1.8.2", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/commondir": { + "version": "1.0.1", + "license": "MIT" + }, + "node_modules/component-emitter": { + "version": "1.3.1", + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/compressible": { + "version": "2.0.18", + "license": "MIT", + "dependencies": { + "mime-db": ">= 1.43.0 < 2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/compressible/node_modules/mime-db": { + "version": "1.52.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/compression": { + "version": "1.7.4", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.5", + "bytes": "3.0.0", + "compressible": "~2.0.16", + "debug": "2.6.9", + "on-headers": "~1.0.2", + "safe-buffer": "5.1.2", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/compression/node_modules/debug": { + "version": "2.6.9", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/compression/node_modules/ms": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/compression/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "license": "MIT" + }, + "node_modules/concat-stream": { + "version": "1.6.2", + "engines": [ + "node >= 0.8" + ], + "license": "MIT", + "peer": true, + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/concat-stream/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/concat-stream/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "peer": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/concat-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "peer": true + }, + "node_modules/concat-stream/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/config-chain": { + "version": "1.1.13", + "license": "MIT", + "dependencies": { + "ini": "^1.3.4", + "proto-list": "~1.2.1" + } + }, + "node_modules/configstore": { + "version": "6.0.0", + "license": "BSD-2-Clause", + "dependencies": { + "dot-prop": "^6.0.1", + "graceful-fs": "^4.2.6", + "unique-string": "^3.0.0", + "write-file-atomic": "^3.0.3", + "xdg-basedir": "^5.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/yeoman/configstore?sponsor=1" + } + }, + "node_modules/connect-history-api-fallback": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/consola": { + "version": "2.15.3", + "license": "MIT" + }, + "node_modules/console-browserify": { + "version": "1.2.0", + "peer": true + }, + "node_modules/consolidated-events": { + "version": "2.0.2", + "license": "MIT" + }, + "node_modules/constants-browserify": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/content-disposition": { + "version": "0.5.2", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/cookie": { + "version": "0.6.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "license": "MIT" + }, + "node_modules/copy-concurrently": { + "version": "1.0.5", + "license": "ISC", + "peer": true, + "dependencies": { + "aproba": "^1.1.1", + "fs-write-stream-atomic": "^1.0.8", + "iferr": "^0.1.5", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.0" + } + }, + "node_modules/copy-concurrently/node_modules/rimraf": { + "version": "2.7.1", + "license": "ISC", + "peer": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, + "node_modules/copy-descriptor": { + "version": "0.1.1", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/copy-text-to-clipboard": { + "version": "3.2.0", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/copy-webpack-plugin": { + "version": "11.0.0", + "license": "MIT", + "dependencies": { + "fast-glob": "^3.2.11", + "glob-parent": "^6.0.1", + "globby": "^13.1.1", + "normalize-path": "^3.0.0", + "schema-utils": "^4.0.0", + "serialize-javascript": "^6.0.0" + }, + "engines": { + "node": ">= 14.15.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + } + }, + "node_modules/copy-webpack-plugin/node_modules/glob-parent": { + "version": "6.0.2", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/copy-webpack-plugin/node_modules/globby": { + "version": "13.2.2", + "license": "MIT", + "dependencies": { + "dir-glob": "^3.0.1", + "fast-glob": "^3.3.0", + "ignore": "^5.2.4", + "merge2": "^1.4.1", + "slash": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/copy-webpack-plugin/node_modules/slash": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/core-js": { + "version": "3.35.1", + "hasInstallScript": true, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, + "node_modules/core-js-compat": { + "version": "3.35.1", + "license": "MIT", + "dependencies": { + "browserslist": "^4.22.2" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, + "node_modules/core-js-pure": { + "version": "3.35.1", + "hasInstallScript": true, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "license": "MIT" + }, + "node_modules/cose-base": { + "version": "1.0.3", + "license": "MIT", + "dependencies": { + "layout-base": "^1.0.0" + } + }, + "node_modules/cosmiconfig": { + "version": "8.3.6", + "license": "MIT", + "dependencies": { + "import-fresh": "^3.3.0", + "js-yaml": "^4.1.0", + "parse-json": "^5.2.0", + "path-type": "^4.0.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/d-fischer" + }, + "peerDependencies": { + "typescript": ">=4.9.5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/create-ecdh": { + "version": "4.0.4", + "license": "MIT", + "peer": true, + "dependencies": { + "bn.js": "^4.1.0", + "elliptic": "^6.5.3" + } + }, + "node_modules/create-ecdh/node_modules/bn.js": { + "version": "4.12.0", + "license": "MIT", + "peer": true + }, + "node_modules/create-hash": { + "version": "1.2.0", + "license": "MIT", + "peer": true, + "dependencies": { + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "md5.js": "^1.3.4", + "ripemd160": "^2.0.1", + "sha.js": "^2.4.0" + } + }, + "node_modules/create-hmac": { + "version": "1.1.7", + "license": "MIT", + "peer": true, + "dependencies": { + "cipher-base": "^1.0.3", + "create-hash": "^1.1.0", + "inherits": "^2.0.1", + "ripemd160": "^2.0.0", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/crypto-browserify": { + "version": "3.12.0", + "license": "MIT", + "peer": true, + "dependencies": { + "browserify-cipher": "^1.0.0", + "browserify-sign": "^4.0.0", + "create-ecdh": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.0", + "diffie-hellman": "^5.0.0", + "inherits": "^2.0.1", + "pbkdf2": "^3.0.3", + "public-encrypt": "^4.0.0", + "randombytes": "^2.0.0", + "randomfill": "^1.0.3" + }, + "engines": { + "node": "*" + } + }, + "node_modules/crypto-random-string": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "type-fest": "^1.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/crypto-random-string/node_modules/type-fest": { + "version": "1.4.0", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/csp_evaluator": { + "version": "1.1.1", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/css-color-keywords": { + "version": "1.0.0", + "license": "ISC", + "engines": { + "node": ">=4" + } + }, + "node_modules/css-declaration-sorter": { + "version": "7.2.0", + "license": "ISC", + "engines": { + "node": "^14 || ^16 || >=18" + }, + "peerDependencies": { + "postcss": "^8.0.9" + } + }, + "node_modules/css-loader": { + "version": "6.10.0", + "license": "MIT", + "dependencies": { + "icss-utils": "^5.1.0", + "postcss": "^8.4.33", + "postcss-modules-extract-imports": "^3.0.0", + "postcss-modules-local-by-default": "^4.0.4", + "postcss-modules-scope": "^3.1.1", + "postcss-modules-values": "^4.0.0", + "postcss-value-parser": "^4.2.0", + "semver": "^7.5.4" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "@rspack/core": "0.x || 1.x", + "webpack": "^5.0.0" + }, + "peerDependenciesMeta": { + "@rspack/core": { + "optional": true + }, + "webpack": { + "optional": true + } + } + }, + "node_modules/css-minimizer-webpack-plugin": { + "version": "5.0.1", + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.18", + "cssnano": "^6.0.1", + "jest-worker": "^29.4.3", + "postcss": "^8.4.24", + "schema-utils": "^4.0.1", + "serialize-javascript": "^6.0.1" + }, + "engines": { + "node": ">= 14.15.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.0.0" + }, + "peerDependenciesMeta": { + "@parcel/css": { + "optional": true + }, + "@swc/css": { + "optional": true + }, + "clean-css": { + "optional": true + }, + "csso": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "lightningcss": { + "optional": true + } + } + }, + "node_modules/css-select": { + "version": "5.1.0", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-what": "^6.1.0", + "domhandler": "^5.0.2", + "domutils": "^3.0.1", + "nth-check": "^2.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/css-to-react-native": { + "version": "3.2.0", + "license": "MIT", + "dependencies": { + "camelize": "^1.0.0", + "css-color-keywords": "^1.0.0", + "postcss-value-parser": "^4.0.2" + } + }, + "node_modules/css-tree": { + "version": "2.3.1", + "license": "MIT", + "dependencies": { + "mdn-data": "2.0.30", + "source-map-js": "^1.0.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/css-what": { + "version": "6.1.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/cssnano": { + "version": "6.1.2", + "license": "MIT", + "dependencies": { + "cssnano-preset-default": "^6.1.2", + "lilconfig": "^3.1.1" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/cssnano" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/cssnano-preset-advanced": { + "version": "6.1.2", + "license": "MIT", + "dependencies": { + "autoprefixer": "^10.4.19", + "browserslist": "^4.23.0", + "cssnano-preset-default": "^6.1.2", + "postcss-discard-unused": "^6.0.5", + "postcss-merge-idents": "^6.0.3", + "postcss-reduce-idents": "^6.0.3", + "postcss-zindex": "^6.0.2" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/cssnano-preset-default": { + "version": "6.1.2", + "license": "MIT", + "dependencies": { + "browserslist": "^4.23.0", + "css-declaration-sorter": "^7.2.0", + "cssnano-utils": "^4.0.2", + "postcss-calc": "^9.0.1", + "postcss-colormin": "^6.1.0", + "postcss-convert-values": "^6.1.0", + "postcss-discard-comments": "^6.0.2", + "postcss-discard-duplicates": "^6.0.3", + "postcss-discard-empty": "^6.0.3", + "postcss-discard-overridden": "^6.0.2", + "postcss-merge-longhand": "^6.0.5", + "postcss-merge-rules": "^6.1.1", + "postcss-minify-font-values": "^6.1.0", + "postcss-minify-gradients": "^6.0.3", + "postcss-minify-params": "^6.1.0", + "postcss-minify-selectors": "^6.0.4", + "postcss-normalize-charset": "^6.0.2", + "postcss-normalize-display-values": "^6.0.2", + "postcss-normalize-positions": "^6.0.2", + "postcss-normalize-repeat-style": "^6.0.2", + "postcss-normalize-string": "^6.0.2", + "postcss-normalize-timing-functions": "^6.0.2", + "postcss-normalize-unicode": "^6.1.0", + "postcss-normalize-url": "^6.0.2", + "postcss-normalize-whitespace": "^6.0.2", + "postcss-ordered-values": "^6.0.2", + "postcss-reduce-initial": "^6.1.0", + "postcss-reduce-transforms": "^6.0.2", + "postcss-svgo": "^6.0.3", + "postcss-unique-selectors": "^6.0.4" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/cssnano-utils": { + "version": "4.0.2", + "license": "MIT", + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/csso": { + "version": "5.0.5", + "license": "MIT", + "dependencies": { + "css-tree": "~2.2.0" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/csso/node_modules/css-tree": { + "version": "2.2.1", + "license": "MIT", + "dependencies": { + "mdn-data": "2.0.28", + "source-map-js": "^1.0.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/csso/node_modules/mdn-data": { + "version": "2.0.28", + "license": "CC0-1.0" + }, + "node_modules/csstype": { + "version": "3.1.3", + "license": "MIT" + }, + "node_modules/cyclist": { + "version": "1.0.2", + "license": "MIT", + "peer": true + }, + "node_modules/cytoscape": { + "version": "3.28.1", + "license": "MIT", + "dependencies": { + "heap": "^0.2.6", + "lodash": "^4.17.21" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/cytoscape-cose-bilkent": { + "version": "4.1.0", + "license": "MIT", + "dependencies": { + "cose-base": "^1.0.0" + }, + "peerDependencies": { + "cytoscape": "^3.2.0" + } + }, + "node_modules/d3": { + "version": "7.8.5", + "license": "ISC", + "dependencies": { + "d3-array": "3", + "d3-axis": "3", + "d3-brush": "3", + "d3-chord": "3", + "d3-color": "3", + "d3-contour": "4", + "d3-delaunay": "6", + "d3-dispatch": "3", + "d3-drag": "3", + "d3-dsv": "3", + "d3-ease": "3", + "d3-fetch": "3", + "d3-force": "3", + "d3-format": "3", + "d3-geo": "3", + "d3-hierarchy": "3", + "d3-interpolate": "3", + "d3-path": "3", + "d3-polygon": "3", + "d3-quadtree": "3", + "d3-random": "3", + "d3-scale": "4", + "d3-scale-chromatic": "3", + "d3-selection": "3", + "d3-shape": "3", + "d3-time": "3", + "d3-time-format": "4", + "d3-timer": "3", + "d3-transition": "3", + "d3-zoom": "3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-array": { + "version": "3.2.4", + "license": "ISC", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-axis": { + "version": "3.0.0", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-brush": { + "version": "3.0.0", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-drag": "2 - 3", + "d3-interpolate": "1 - 3", + "d3-selection": "3", + "d3-transition": "3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-chord": { + "version": "3.0.1", + "license": "ISC", + "dependencies": { + "d3-path": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-color": { + "version": "3.1.0", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-contour": { + "version": "4.0.2", + "license": "ISC", + "dependencies": { + "d3-array": "^3.2.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-delaunay": { + "version": "6.0.4", + "license": "ISC", + "dependencies": { + "delaunator": "5" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-dispatch": { + "version": "3.0.1", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-drag": { + "version": "3.0.0", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-selection": "3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-dsv": { + "version": "3.0.1", + "license": "ISC", + "dependencies": { + "commander": "7", + "iconv-lite": "0.6", + "rw": "1" + }, + "bin": { + "csv2json": "bin/dsv2json.js", + "csv2tsv": "bin/dsv2dsv.js", + "dsv2dsv": "bin/dsv2dsv.js", + "dsv2json": "bin/dsv2json.js", + "json2csv": "bin/json2dsv.js", + "json2dsv": "bin/json2dsv.js", + "json2tsv": "bin/json2dsv.js", + "tsv2csv": "bin/dsv2dsv.js", + "tsv2json": "bin/dsv2json.js" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-dsv/node_modules/commander": { + "version": "7.2.0", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/d3-dsv/node_modules/iconv-lite": { + "version": "0.6.3", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/d3-ease": { + "version": "3.0.1", + "license": "BSD-3-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-fetch": { + "version": "3.0.1", + "license": "ISC", + "dependencies": { + "d3-dsv": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-force": { + "version": "3.0.0", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-quadtree": "1 - 3", + "d3-timer": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-format": { + "version": "3.1.0", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-geo": { + "version": "3.1.0", + "license": "ISC", + "dependencies": { + "d3-array": "2.5.0 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-hierarchy": { + "version": "3.1.2", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-interpolate": { + "version": "3.0.1", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-path": { + "version": "3.1.0", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-polygon": { + "version": "3.0.1", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-quadtree": { + "version": "3.0.1", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-random": { + "version": "3.0.1", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-sankey": { + "version": "0.12.3", + "license": "BSD-3-Clause", + "dependencies": { + "d3-array": "1 - 2", + "d3-shape": "^1.2.0" + } + }, + "node_modules/d3-sankey/node_modules/d3-array": { + "version": "2.12.1", + "license": "BSD-3-Clause", + "dependencies": { + "internmap": "^1.0.0" + } + }, + "node_modules/d3-sankey/node_modules/d3-path": { + "version": "1.0.9", + "license": "BSD-3-Clause" + }, + "node_modules/d3-sankey/node_modules/d3-shape": { + "version": "1.3.7", + "license": "BSD-3-Clause", + "dependencies": { + "d3-path": "1" + } + }, + "node_modules/d3-sankey/node_modules/internmap": { + "version": "1.0.1", + "license": "ISC" + }, + "node_modules/d3-scale": { + "version": "4.0.2", + "license": "ISC", + "dependencies": { + "d3-array": "2.10.0 - 3", + "d3-format": "1 - 3", + "d3-interpolate": "1.2.0 - 3", + "d3-time": "2.1.1 - 3", + "d3-time-format": "2 - 4" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-scale-chromatic": { + "version": "3.0.0", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3", + "d3-interpolate": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-selection": { + "version": "3.0.0", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-shape": { + "version": "3.2.0", + "license": "ISC", + "dependencies": { + "d3-path": "^3.1.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time": { + "version": "3.1.0", + "license": "ISC", + "dependencies": { + "d3-array": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time-format": { + "version": "4.1.0", + "license": "ISC", + "dependencies": { + "d3-time": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-timer": { + "version": "3.0.1", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-transition": { + "version": "3.0.1", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3", + "d3-dispatch": "1 - 3", + "d3-ease": "1 - 3", + "d3-interpolate": "1 - 3", + "d3-timer": "1 - 3" + }, + "engines": { + "node": ">=12" + }, + "peerDependencies": { + "d3-selection": "2 - 3" + } + }, + "node_modules/d3-zoom": { + "version": "3.0.0", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-drag": "2 - 3", + "d3-interpolate": "1 - 3", + "d3-selection": "2 - 3", + "d3-transition": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/dagre-d3-es": { + "version": "7.0.10", + "license": "MIT", + "dependencies": { + "d3": "^7.8.2", + "lodash-es": "^4.17.21" + } + }, + "node_modules/data-uri-to-buffer": { + "version": "6.0.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/dayjs": { + "version": "1.11.10", + "license": "MIT" + }, + "node_modules/debounce": { + "version": "1.2.1", + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.3.6", + "license": "MIT", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js-light": { + "version": "2.5.1", + "license": "MIT" + }, + "node_modules/decode-named-character-reference": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "character-entities": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/decode-uri-component": { + "version": "0.2.2", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/decompress-response/node_modules/mimic-response": { + "version": "3.1.0", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/default-gateway": { + "version": "6.0.3", + "license": "BSD-2-Clause", + "dependencies": { + "execa": "^5.0.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/defer-to-connect": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-lazy-prop": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-property": { + "version": "2.0.2", + "license": "MIT", + "peer": true, + "dependencies": { + "is-descriptor": "^1.0.2", + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/degenerator": { + "version": "5.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "ast-types": "^0.13.4", + "escodegen": "^2.1.0", + "esprima": "^4.0.1" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/del": { + "version": "6.1.1", + "license": "MIT", + "dependencies": { + "globby": "^11.0.1", + "graceful-fs": "^4.2.4", + "is-glob": "^4.0.1", + "is-path-cwd": "^2.2.0", + "is-path-inside": "^3.0.2", + "p-map": "^4.0.0", + "rimraf": "^3.0.2", + "slash": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/delaunator": { + "version": "5.0.1", + "license": "ISC", + "dependencies": { + "robust-predicates": "^3.0.2" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dequal": { + "version": "2.0.3", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/des.js": { + "version": "1.1.0", + "license": "MIT", + "peer": true, + "dependencies": { + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/detect-libc": { + "version": "2.0.2", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/detect-node": { + "version": "2.1.0", + "license": "MIT" + }, + "node_modules/detect-port": { + "version": "1.5.1", + "license": "MIT", + "dependencies": { + "address": "^1.0.1", + "debug": "4" + }, + "bin": { + "detect": "bin/detect-port.js", + "detect-port": "bin/detect-port.js" + } + }, + "node_modules/detect-port-alt": { + "version": "1.1.6", + "license": "MIT", + "dependencies": { + "address": "^1.0.1", + "debug": "^2.6.0" + }, + "bin": { + "detect": "bin/detect-port", + "detect-port": "bin/detect-port" + }, + "engines": { + "node": ">= 4.2.1" + } + }, + "node_modules/detect-port-alt/node_modules/debug": { + "version": "2.6.9", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/detect-port-alt/node_modules/ms": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/devlop": { + "version": "1.1.0", + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/devtools-protocol": { + "version": "0.0.1312386", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/didyoumean": { + "version": "1.2.2", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/diff": { + "version": "5.1.0", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/diffie-hellman": { + "version": "5.0.3", + "license": "MIT", + "peer": true, + "dependencies": { + "bn.js": "^4.1.0", + "miller-rabin": "^4.0.0", + "randombytes": "^2.0.0" + } + }, + "node_modules/diffie-hellman/node_modules/bn.js": { + "version": "4.12.0", + "license": "MIT", + "peer": true + }, + "node_modules/dir-glob": { + "version": "3.0.1", + "license": "MIT", + "dependencies": { + "path-type": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/dlv": { + "version": "1.1.3", + "dev": true, + "license": "MIT" + }, + "node_modules/dns-packet": { + "version": "5.6.1", + "license": "MIT", + "dependencies": { + "@leichtgewicht/ip-codec": "^2.0.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/docusaurus2-dotenv": { + "version": "1.4.0", + "license": "MIT", + "dependencies": { + "dotenv-webpack": "1.7.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/@webassemblyjs/ast": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/helper-module-context": "1.9.0", + "@webassemblyjs/helper-wasm-bytecode": "1.9.0", + "@webassemblyjs/wast-parser": "1.9.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/@webassemblyjs/helper-api-error": { + "version": "1.9.0", + "license": "MIT", + "peer": true + }, + "node_modules/docusaurus2-dotenv/node_modules/@webassemblyjs/helper-buffer": { + "version": "1.9.0", + "license": "MIT", + "peer": true + }, + "node_modules/docusaurus2-dotenv/node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.9.0", + "license": "MIT", + "peer": true + }, + "node_modules/docusaurus2-dotenv/node_modules/@webassemblyjs/helper-wasm-section": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/helper-buffer": "1.9.0", + "@webassemblyjs/helper-wasm-bytecode": "1.9.0", + "@webassemblyjs/wasm-gen": "1.9.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/@webassemblyjs/ieee754": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/@webassemblyjs/leb128": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@xtuc/long": "4.2.2" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/@webassemblyjs/utf8": { + "version": "1.9.0", + "license": "MIT", + "peer": true + }, + "node_modules/docusaurus2-dotenv/node_modules/@webassemblyjs/wasm-edit": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/helper-buffer": "1.9.0", + "@webassemblyjs/helper-wasm-bytecode": "1.9.0", + "@webassemblyjs/helper-wasm-section": "1.9.0", + "@webassemblyjs/wasm-gen": "1.9.0", + "@webassemblyjs/wasm-opt": "1.9.0", + "@webassemblyjs/wasm-parser": "1.9.0", + "@webassemblyjs/wast-printer": "1.9.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/@webassemblyjs/wasm-gen": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/helper-wasm-bytecode": "1.9.0", + "@webassemblyjs/ieee754": "1.9.0", + "@webassemblyjs/leb128": "1.9.0", + "@webassemblyjs/utf8": "1.9.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/@webassemblyjs/wasm-opt": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/helper-buffer": "1.9.0", + "@webassemblyjs/wasm-gen": "1.9.0", + "@webassemblyjs/wasm-parser": "1.9.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/@webassemblyjs/wasm-parser": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/helper-api-error": "1.9.0", + "@webassemblyjs/helper-wasm-bytecode": "1.9.0", + "@webassemblyjs/ieee754": "1.9.0", + "@webassemblyjs/leb128": "1.9.0", + "@webassemblyjs/utf8": "1.9.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/@webassemblyjs/wast-printer": { + "version": "1.9.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/wast-parser": "1.9.0", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/acorn": { + "version": "6.4.2", + "license": "MIT", + "peer": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/ajv": { + "version": "6.12.6", + "license": "MIT", + "peer": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/ajv-keywords": { + "version": "3.5.2", + "license": "MIT", + "peer": true, + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/braces": { + "version": "2.3.2", + "license": "MIT", + "peer": true, + "dependencies": { + "arr-flatten": "^1.1.0", + "array-unique": "^0.3.2", + "extend-shallow": "^2.0.1", + "fill-range": "^4.0.0", + "isobject": "^3.0.1", + "repeat-element": "^1.1.2", + "snapdragon": "^0.8.1", + "snapdragon-node": "^2.0.1", + "split-string": "^3.0.2", + "to-regex": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/commander": { + "version": "2.20.3", + "license": "MIT", + "peer": true + }, + "node_modules/docusaurus2-dotenv/node_modules/dotenv-webpack": { + "version": "1.7.0", + "license": "MIT", + "dependencies": { + "dotenv-defaults": "^1.0.2" + }, + "peerDependencies": { + "webpack": "^1 || ^2 || ^3 || ^4" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/enhanced-resolve": { + "version": "4.5.0", + "peer": true, + "dependencies": { + "graceful-fs": "^4.1.2", + "memory-fs": "^0.5.0", + "tapable": "^1.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/enhanced-resolve/node_modules/memory-fs": { + "version": "0.5.0", + "license": "MIT", + "peer": true, + "dependencies": { + "errno": "^0.1.3", + "readable-stream": "^2.0.1" + }, + "engines": { + "node": ">=4.3.0 <5.0.0 || >=5.10" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/eslint-scope": { + "version": "4.0.3", + "license": "BSD-2-Clause", + "peer": true, + "dependencies": { + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/fill-range": { + "version": "4.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "extend-shallow": "^2.0.1", + "is-number": "^3.0.0", + "repeat-string": "^1.6.1", + "to-regex-range": "^2.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/find-cache-dir": { + "version": "2.1.0", + "license": "MIT", + "peer": true, + "dependencies": { + "commondir": "^1.0.1", + "make-dir": "^2.0.0", + "pkg-dir": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/find-up": { + "version": "3.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "locate-path": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/is-extendable": { + "version": "1.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "is-plain-object": "^2.0.4" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/is-number": { + "version": "3.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "kind-of": "^3.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/is-number/node_modules/kind-of": { + "version": "3.2.2", + "license": "MIT", + "peer": true, + "dependencies": { + "is-buffer": "^1.1.5" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/is-plain-object": { + "version": "2.0.4", + "license": "MIT", + "peer": true, + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/is-wsl": { + "version": "1.1.0", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/docusaurus2-dotenv/node_modules/json-schema-traverse": { + "version": "0.4.1", + "license": "MIT", + "peer": true + }, + "node_modules/docusaurus2-dotenv/node_modules/json5": { + "version": "1.0.2", + "license": "MIT", + "peer": true, + "dependencies": { + "minimist": "^1.2.0" + }, + "bin": { + "json5": "lib/cli.js" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/loader-runner": { + "version": "2.4.0", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=4.3.0 <5.0.0 || >=5.10" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/loader-utils": { + "version": "1.4.2", + "license": "MIT", + "peer": true, + "dependencies": { + "big.js": "^5.2.2", + "emojis-list": "^3.0.0", + "json5": "^1.0.1" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/locate-path": { + "version": "3.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/micromatch": { + "version": "3.1.10", + "license": "MIT", + "peer": true, + "dependencies": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "braces": "^2.3.1", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "extglob": "^2.0.4", + "fragment-cache": "^0.2.1", + "kind-of": "^6.0.2", + "nanomatch": "^1.2.9", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/micromatch/node_modules/extend-shallow": { + "version": "3.0.2", + "license": "MIT", + "peer": true, + "dependencies": { + "assign-symbols": "^1.0.0", + "is-extendable": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/p-limit": { + "version": "2.3.0", + "license": "MIT", + "peer": true, + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/p-locate": { + "version": "3.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "p-limit": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/path-exists": { + "version": "3.0.0", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/pkg-dir": { + "version": "3.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "find-up": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "peer": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "peer": true + }, + "node_modules/docusaurus2-dotenv/node_modules/schema-utils": { + "version": "1.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "ajv": "^6.1.0", + "ajv-errors": "^1.0.0", + "ajv-keywords": "^3.1.0" + }, + "engines": { + "node": ">= 4" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/serialize-javascript": { + "version": "4.0.0", + "license": "BSD-3-Clause", + "peer": true, + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/source-map": { + "version": "0.6.1", + "license": "BSD-3-Clause", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/tapable": { + "version": "1.1.3", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/terser": { + "version": "4.8.1", + "license": "BSD-2-Clause", + "peer": true, + "dependencies": { + "commander": "^2.20.0", + "source-map": "~0.6.1", + "source-map-support": "~0.5.12" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/terser-webpack-plugin": { + "version": "1.4.6", + "license": "MIT", + "peer": true, + "dependencies": { + "cacache": "^12.0.2", + "find-cache-dir": "^2.1.0", + "is-wsl": "^1.1.0", + "schema-utils": "^1.0.0", + "serialize-javascript": "^4.0.0", + "source-map": "^0.6.1", + "terser": "^4.1.2", + "webpack-sources": "^1.4.0", + "worker-farm": "^1.7.0" + }, + "engines": { + "node": ">= 6.9.0" + }, + "peerDependencies": { + "webpack": "^4.0.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/to-regex-range": { + "version": "2.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "is-number": "^3.0.0", + "repeat-string": "^1.6.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/watchpack": { + "version": "1.7.5", + "license": "MIT", + "peer": true, + "dependencies": { + "graceful-fs": "^4.1.2", + "neo-async": "^2.5.0" + }, + "optionalDependencies": { + "chokidar": "^3.4.1", + "watchpack-chokidar2": "^2.0.1" + } + }, + "node_modules/docusaurus2-dotenv/node_modules/webpack": { + "version": "4.47.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.9.0", + "@webassemblyjs/helper-module-context": "1.9.0", + "@webassemblyjs/wasm-edit": "1.9.0", + "@webassemblyjs/wasm-parser": "1.9.0", + "acorn": "^6.4.1", + "ajv": "^6.10.2", + "ajv-keywords": "^3.4.1", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^4.5.0", + "eslint-scope": "^4.0.3", + "json-parse-better-errors": "^1.0.2", + "loader-runner": "^2.4.0", + "loader-utils": "^1.2.3", + "memory-fs": "^0.4.1", + "micromatch": "^3.1.10", + "mkdirp": "^0.5.3", + "neo-async": "^2.6.1", + "node-libs-browser": "^2.2.1", + "schema-utils": "^1.0.0", + "tapable": "^1.1.3", + "terser-webpack-plugin": "^1.4.3", + "watchpack": "^1.7.4", + "webpack-sources": "^1.4.1" + }, + "bin": { + "webpack": "bin/webpack.js" + }, + "engines": { + "node": ">=6.11.5" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependenciesMeta": { + "webpack-cli": { + "optional": true + }, + "webpack-command": { + "optional": true + } + } + }, + "node_modules/docusaurus2-dotenv/node_modules/webpack-sources": { + "version": "1.4.3", + "license": "MIT", + "peer": true, + "dependencies": { + "source-list-map": "^2.0.0", + "source-map": "~0.6.1" + } + }, + "node_modules/dom-converter": { + "version": "0.2.0", + "license": "MIT", + "dependencies": { + "utila": "~0.4" + } + }, + "node_modules/dom-helpers": { + "version": "5.2.1", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.8.7", + "csstype": "^3.0.2" + } + }, + "node_modules/dom-serializer": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.2", + "entities": "^4.2.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/domain-browser": { + "version": "1.2.0", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.4", + "npm": ">=1.2" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause" + }, + "node_modules/domhandler": { + "version": "5.0.3", + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.3.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/dompurify": { + "version": "3.1.6", + "license": "(MPL-2.0 OR Apache-2.0)" + }, + "node_modules/domutils": { + "version": "3.1.0", + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^2.0.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/dot-case": { + "version": "3.0.4", + "license": "MIT", + "dependencies": { + "no-case": "^3.0.4", + "tslib": "^2.0.3" + } + }, + "node_modules/dot-prop": { + "version": "6.0.1", + "license": "MIT", + "dependencies": { + "is-obj": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/dot-prop/node_modules/is-obj": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/dotenv": { + "version": "16.4.5", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dotenv-defaults": { + "version": "1.1.1", + "license": "MIT", + "dependencies": { + "dotenv": "^6.2.0" + } + }, + "node_modules/dotenv-defaults/node_modules/dotenv": { + "version": "6.2.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">=6" + } + }, + "node_modules/duplexer": { + "version": "0.1.2", + "license": "MIT" + }, + "node_modules/duplexify": { + "version": "3.7.1", + "license": "MIT", + "peer": true, + "dependencies": { + "end-of-stream": "^1.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.0.0", + "stream-shift": "^1.0.0" + } + }, + "node_modules/duplexify/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/duplexify/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "peer": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/duplexify/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "peer": true + }, + "node_modules/duplexify/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "license": "MIT" + }, + "node_modules/ee-first": { + "version": "1.1.1", + "license": "MIT" + }, + "node_modules/ejs": { + "version": "3.1.10", + "license": "Apache-2.0", + "dependencies": { + "jake": "^10.8.5" + }, + "bin": { + "ejs": "bin/cli.js" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.31", + "license": "ISC" + }, + "node_modules/elkjs": { + "version": "0.9.1", + "license": "EPL-2.0" + }, + "node_modules/elliptic": { + "version": "6.5.7", + "license": "MIT", + "peer": true, + "dependencies": { + "bn.js": "^4.11.9", + "brorand": "^1.1.0", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.1", + "inherits": "^2.0.4", + "minimalistic-assert": "^1.0.1", + "minimalistic-crypto-utils": "^1.0.1" + } + }, + "node_modules/elliptic/node_modules/bn.js": { + "version": "4.12.0", + "license": "MIT", + "peer": true + }, + "node_modules/email-addresses": { + "version": "5.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "license": "MIT" + }, + "node_modules/emojilib": { + "version": "2.4.0", + "license": "MIT" + }, + "node_modules/emojis-list": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/emoticon": { + "version": "4.0.1", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.4", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/enhanced-resolve": { + "version": "5.17.1", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/enquirer": { + "version": "2.4.1", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-colors": "^4.1.1", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/entities": { + "version": "4.5.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/errno": { + "version": "0.1.8", + "license": "MIT", + "peer": true, + "dependencies": { + "prr": "~1.0.1" + }, + "bin": { + "errno": "cli.js" + } + }, + "node_modules/error-ex": { + "version": "1.3.2", + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es-abstract": { + "version": "1.22.3", + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.0", + "arraybuffer.prototype.slice": "^1.0.2", + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.5", + "es-set-tostringtag": "^2.0.1", + "es-to-primitive": "^1.2.1", + "function.prototype.name": "^1.1.6", + "get-intrinsic": "^1.2.2", + "get-symbol-description": "^1.0.0", + "globalthis": "^1.0.3", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0", + "internal-slot": "^1.0.5", + "is-array-buffer": "^3.0.2", + "is-callable": "^1.2.7", + "is-negative-zero": "^2.0.2", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.2", + "is-string": "^1.0.7", + "is-typed-array": "^1.1.12", + "is-weakref": "^1.0.2", + "object-inspect": "^1.13.1", + "object-keys": "^1.1.1", + "object.assign": "^4.1.4", + "regexp.prototype.flags": "^1.5.1", + "safe-array-concat": "^1.0.1", + "safe-regex-test": "^1.0.0", + "string.prototype.trim": "^1.2.8", + "string.prototype.trimend": "^1.0.7", + "string.prototype.trimstart": "^1.0.7", + "typed-array-buffer": "^1.0.0", + "typed-array-byte-length": "^1.0.0", + "typed-array-byte-offset": "^1.0.0", + "typed-array-length": "^1.0.4", + "unbox-primitive": "^1.0.2", + "which-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-define-property": { + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "1.4.1", + "license": "MIT" + }, + "node_modules/es-set-tostringtag": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.2", + "has-tostringtag": "^1.0.0", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-to-primitive": { + "version": "1.2.1", + "license": "MIT", + "dependencies": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/escalade": { + "version": "3.1.2", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-goat": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "license": "MIT" + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/escodegen": { + "version": "2.1.0", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esprima": "^4.0.1", + "estraverse": "^5.2.0", + "esutils": "^2.0.2" + }, + "bin": { + "escodegen": "bin/escodegen.js", + "esgenerate": "bin/esgenerate.js" + }, + "engines": { + "node": ">=6.0" + }, + "optionalDependencies": { + "source-map": "~0.6.1" + } + }, + "node_modules/escodegen/node_modules/estraverse": { + "version": "5.3.0", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/escodegen/node_modules/source-map": { + "version": "0.6.1", + "dev": true, + "license": "BSD-3-Clause", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eslint-scope": { + "version": "5.1.1", + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse/node_modules/estraverse": { + "version": "5.3.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "4.3.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estree-util-attach-comments": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/estree-util-build-jsx": { + "version": "3.0.1", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "devlop": "^1.0.0", + "estree-util-is-identifier-name": "^3.0.0", + "estree-walker": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/estree-util-is-identifier-name": { + "version": "3.0.0", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/estree-util-to-js": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "astring": "^1.8.0", + "source-map": "^0.7.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/estree-util-value-to-estree": { + "version": "3.1.1", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "is-plain-obj": "^4.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/remcohaszing" + } + }, + "node_modules/estree-util-visit": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eta": { + "version": "2.2.0", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + }, + "funding": { + "url": "https://github.com/eta-dev/eta?sponsor=1" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eval": { + "version": "0.1.8", + "dependencies": { + "@types/node": "*", + "require-like": ">= 0.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "license": "MIT" + }, + "node_modules/events": { + "version": "3.3.0", + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/evp_bytestokey": { + "version": "1.0.3", + "license": "MIT", + "peer": true, + "dependencies": { + "md5.js": "^1.3.4", + "safe-buffer": "^5.1.1" + } + }, + "node_modules/execa": { + "version": "5.1.1", + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/expand-brackets": { + "version": "2.1.4", + "license": "MIT", + "peer": true, + "dependencies": { + "debug": "^2.3.3", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "posix-character-classes": "^0.1.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/expand-brackets/node_modules/debug": { + "version": "2.6.9", + "license": "MIT", + "peer": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/expand-brackets/node_modules/define-property": { + "version": "0.2.5", + "license": "MIT", + "peer": true, + "dependencies": { + "is-descriptor": "^0.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/expand-brackets/node_modules/is-descriptor": { + "version": "0.1.7", + "license": "MIT", + "peer": true, + "dependencies": { + "is-accessor-descriptor": "^1.0.1", + "is-data-descriptor": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/expand-brackets/node_modules/ms": { + "version": "2.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/expand-template": { + "version": "2.0.3", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/express": { + "version": "4.21.0", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.3", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.6.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.3.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.10", + "proxy-addr": "~2.0.7", + "qs": "6.13.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.19.0", + "serve-static": "1.16.2", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/express/node_modules/content-disposition": { + "version": "0.5.4", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express/node_modules/debug": { + "version": "2.6.9", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/express/node_modules/ms": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/express/node_modules/path-to-regexp": { + "version": "0.1.10", + "license": "MIT" + }, + "node_modules/express/node_modules/range-parser": { + "version": "1.2.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "license": "MIT" + }, + "node_modules/extend-shallow": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "is-extendable": "^0.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/extglob": { + "version": "2.0.4", + "license": "MIT", + "peer": true, + "dependencies": { + "array-unique": "^0.3.2", + "define-property": "^1.0.0", + "expand-brackets": "^2.1.4", + "extend-shallow": "^2.0.1", + "fragment-cache": "^0.2.1", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/extglob/node_modules/define-property": { + "version": "1.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "is-descriptor": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/extract-zip": { + "version": "2.0.1", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "debug": "^4.1.1", + "get-stream": "^5.1.0", + "yauzl": "^2.10.0" + }, + "bin": { + "extract-zip": "cli.js" + }, + "engines": { + "node": ">= 10.17.0" + }, + "optionalDependencies": { + "@types/yauzl": "^2.9.1" + } + }, + "node_modules/extract-zip/node_modules/get-stream": { + "version": "5.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "pump": "^3.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "license": "MIT" + }, + "node_modules/fast-equals": { + "version": "5.0.1", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/fast-fifo": { + "version": "1.3.2", + "license": "MIT" + }, + "node_modules/fast-glob": { + "version": "3.3.2", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.4" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "license": "MIT" + }, + "node_modules/fast-url-parser": { + "version": "1.1.3", + "license": "MIT", + "dependencies": { + "punycode": "^1.3.2" + } + }, + "node_modules/fastq": { + "version": "1.17.0", + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fault": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "format": "^0.2.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/faye-websocket": { + "version": "0.11.4", + "license": "Apache-2.0", + "dependencies": { + "websocket-driver": ">=0.5.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/fd-slicer": { + "version": "1.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "pend": "~1.2.0" + } + }, + "node_modules/feed": { + "version": "4.2.2", + "license": "MIT", + "dependencies": { + "xml-js": "^1.6.11" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/figgy-pudding": { + "version": "3.5.2", + "license": "ISC", + "peer": true + }, + "node_modules/file-loader": { + "version": "6.2.0", + "license": "MIT", + "dependencies": { + "loader-utils": "^2.0.0", + "schema-utils": "^3.0.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^4.0.0 || ^5.0.0" + } + }, + "node_modules/file-loader/node_modules/ajv": { + "version": "6.12.6", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/file-loader/node_modules/ajv-keywords": { + "version": "3.5.2", + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/file-loader/node_modules/json-schema-traverse": { + "version": "0.4.1", + "license": "MIT" + }, + "node_modules/file-loader/node_modules/schema-utils": { + "version": "3.3.0", + "license": "MIT", + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/filelist": { + "version": "1.0.4", + "license": "Apache-2.0", + "dependencies": { + "minimatch": "^5.0.1" + } + }, + "node_modules/filelist/node_modules/brace-expansion": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/filelist/node_modules/minimatch": { + "version": "5.1.6", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/filename-reserved-regex": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/filenamify": { + "version": "4.3.0", + "dev": true, + "license": "MIT", + "dependencies": { + "filename-reserved-regex": "^2.0.0", + "strip-outer": "^1.0.1", + "trim-repeated": "^1.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/filesize": { + "version": "8.0.7", + "license": "BSD-3-Clause", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.3.1", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/finalhandler/node_modules/debug": { + "version": "2.6.9", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/finalhandler/node_modules/ms": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/find-cache-dir": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "common-path-prefix": "^3.0.0", + "pkg-dir": "^7.0.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/find-up": { + "version": "6.3.0", + "license": "MIT", + "dependencies": { + "locate-path": "^7.1.0", + "path-exists": "^5.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat": { + "version": "5.0.2", + "license": "BSD-3-Clause", + "bin": { + "flat": "cli.js" + } + }, + "node_modules/flush-write-stream": { + "version": "1.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "inherits": "^2.0.3", + "readable-stream": "^2.3.6" + } + }, + "node_modules/flush-write-stream/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/flush-write-stream/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "peer": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/flush-write-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "peer": true + }, + "node_modules/flush-write-stream/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.6", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/fontawesome": { + "version": "5.6.3", + "license": "MIT" + }, + "node_modules/for-each": { + "version": "0.3.3", + "license": "MIT", + "dependencies": { + "is-callable": "^1.1.3" + } + }, + "node_modules/for-in": { + "version": "1.0.2", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/foreground-child": { + "version": "3.1.1", + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/foreground-child/node_modules/signal-exit": { + "version": "4.1.0", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/fork-ts-checker-webpack-plugin": { + "version": "6.5.3", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.8.3", + "@types/json-schema": "^7.0.5", + "chalk": "^4.1.0", + "chokidar": "^3.4.2", + "cosmiconfig": "^6.0.0", + "deepmerge": "^4.2.2", + "fs-extra": "^9.0.0", + "glob": "^7.1.6", + "memfs": "^3.1.2", + "minimatch": "^3.0.4", + "schema-utils": "2.7.0", + "semver": "^7.3.2", + "tapable": "^1.0.0" + }, + "engines": { + "node": ">=10", + "yarn": ">=1.0.0" + }, + "peerDependencies": { + "eslint": ">= 6", + "typescript": ">= 2.7", + "vue-template-compiler": "*", + "webpack": ">= 4" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + }, + "vue-template-compiler": { + "optional": true + } + } + }, + "node_modules/fork-ts-checker-webpack-plugin/node_modules/ajv": { + "version": "6.12.6", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/fork-ts-checker-webpack-plugin/node_modules/ajv-keywords": { + "version": "3.5.2", + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/fork-ts-checker-webpack-plugin/node_modules/cosmiconfig": { + "version": "6.0.0", + "license": "MIT", + "dependencies": { + "@types/parse-json": "^4.0.0", + "import-fresh": "^3.1.0", + "parse-json": "^5.0.0", + "path-type": "^4.0.0", + "yaml": "^1.7.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fork-ts-checker-webpack-plugin/node_modules/fs-extra": { + "version": "9.1.0", + "license": "MIT", + "dependencies": { + "at-least-node": "^1.0.0", + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/fork-ts-checker-webpack-plugin/node_modules/json-schema-traverse": { + "version": "0.4.1", + "license": "MIT" + }, + "node_modules/fork-ts-checker-webpack-plugin/node_modules/schema-utils": { + "version": "2.7.0", + "license": "MIT", + "dependencies": { + "@types/json-schema": "^7.0.4", + "ajv": "^6.12.2", + "ajv-keywords": "^3.4.1" + }, + "engines": { + "node": ">= 8.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/fork-ts-checker-webpack-plugin/node_modules/tapable": { + "version": "1.1.3", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data-encoder": { + "version": "2.1.4", + "license": "MIT", + "engines": { + "node": ">= 14.17" + } + }, + "node_modules/format": { + "version": "0.2.2", + "engines": { + "node": ">=0.4.x" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fraction.js": { + "version": "4.3.7", + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "patreon", + "url": "https://github.com/sponsors/rawify" + } + }, + "node_modules/fragment-cache": { + "version": "0.2.1", + "license": "MIT", + "peer": true, + "dependencies": { + "map-cache": "^0.2.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/framer-motion": { + "version": "11.11.1", + "license": "MIT", + "dependencies": { + "tslib": "^2.4.0" + }, + "peerDependencies": { + "@emotion/is-prop-valid": "*", + "react": "^18.0.0", + "react-dom": "^18.0.0" + }, + "peerDependenciesMeta": { + "@emotion/is-prop-valid": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/from2": { + "version": "2.3.0", + "license": "MIT", + "peer": true, + "dependencies": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.0" + } + }, + "node_modules/from2/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/from2/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "peer": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/from2/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "peer": true + }, + "node_modules/from2/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/fs-extra": { + "version": "11.2.0", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/fs-monkey": { + "version": "1.0.5", + "license": "Unlicense" + }, + "node_modules/fs-write-stream-atomic": { + "version": "1.0.10", + "license": "ISC", + "peer": true, + "dependencies": { + "graceful-fs": "^4.1.2", + "iferr": "^0.1.5", + "imurmurhash": "^0.1.4", + "readable-stream": "1 || 2" + } + }, + "node_modules/fs-write-stream-atomic/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/fs-write-stream-atomic/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "peer": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/fs-write-stream-atomic/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "peer": true + }, + "node_modules/fs-write-stream-atomic/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "license": "ISC" + }, + "node_modules/function-bind": { + "version": "1.1.2", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/function.prototype.name": { + "version": "1.1.6", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1", + "functions-have-names": "^1.2.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.2.4", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-own-enumerable-property-symbols": { + "version": "3.0.2", + "license": "ISC" + }, + "node_modules/get-stream": { + "version": "6.0.1", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-symbol-description": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.5", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-uri": { + "version": "6.0.3", + "dev": true, + "license": "MIT", + "dependencies": { + "basic-ftp": "^5.0.2", + "data-uri-to-buffer": "^6.0.2", + "debug": "^4.3.4", + "fs-extra": "^11.2.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/get-value": { + "version": "2.0.6", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/gh-pages": { + "version": "6.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "async": "^3.2.4", + "commander": "^11.0.0", + "email-addresses": "^5.0.0", + "filenamify": "^4.3.0", + "find-cache-dir": "^3.3.1", + "fs-extra": "^11.1.1", + "globby": "^6.1.0" + }, + "bin": { + "gh-pages": "bin/gh-pages.js", + "gh-pages-clean": "bin/gh-pages-clean.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/gh-pages/node_modules/array-union": { + "version": "1.0.2", + "dev": true, + "license": "MIT", + "dependencies": { + "array-uniq": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/gh-pages/node_modules/commander": { + "version": "11.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16" + } + }, + "node_modules/gh-pages/node_modules/find-cache-dir": { + "version": "3.3.2", + "dev": true, + "license": "MIT", + "dependencies": { + "commondir": "^1.0.1", + "make-dir": "^3.0.2", + "pkg-dir": "^4.1.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/avajs/find-cache-dir?sponsor=1" + } + }, + "node_modules/gh-pages/node_modules/find-up": { + "version": "4.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/gh-pages/node_modules/globby": { + "version": "6.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "array-union": "^1.0.1", + "glob": "^7.0.3", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/gh-pages/node_modules/locate-path": { + "version": "5.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/gh-pages/node_modules/make-dir": { + "version": "3.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/gh-pages/node_modules/p-limit": { + "version": "2.3.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/gh-pages/node_modules/p-locate": { + "version": "4.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/gh-pages/node_modules/path-exists": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/gh-pages/node_modules/pify": { + "version": "2.3.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/gh-pages/node_modules/pkg-dir": { + "version": "4.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/gh-pages/node_modules/semver": { + "version": "6.3.1", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/giscus": { + "version": "1.5.0", + "license": "MIT", + "dependencies": { + "lit": "^3.1.2" + } + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "license": "MIT" + }, + "node_modules/github-slugger": { + "version": "1.5.0", + "license": "ISC" + }, + "node_modules/glob": { + "version": "7.2.3", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "license": "BSD-2-Clause" + }, + "node_modules/global-dirs": { + "version": "3.0.1", + "license": "MIT", + "dependencies": { + "ini": "2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/global-dirs/node_modules/ini": { + "version": "2.0.0", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/global-modules": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "global-prefix": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/global-prefix": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "ini": "^1.3.5", + "kind-of": "^6.0.2", + "which": "^1.3.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/global-prefix/node_modules/which": { + "version": "1.3.1", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "which": "bin/which" + } + }, + "node_modules/globals": { + "version": "11.12.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/globalthis": { + "version": "1.0.3", + "license": "MIT", + "dependencies": { + "define-properties": "^1.1.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/globby": { + "version": "11.1.0", + "license": "MIT", + "dependencies": { + "array-union": "^2.1.0", + "dir-glob": "^3.0.1", + "fast-glob": "^3.2.9", + "ignore": "^5.2.0", + "merge2": "^1.4.1", + "slash": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/got": { + "version": "12.6.1", + "license": "MIT", + "dependencies": { + "@sindresorhus/is": "^5.2.0", + "@szmarczak/http-timer": "^5.0.1", + "cacheable-lookup": "^7.0.0", + "cacheable-request": "^10.2.8", + "decompress-response": "^6.0.0", + "form-data-encoder": "^2.1.2", + "get-stream": "^6.0.1", + "http2-wrapper": "^2.1.10", + "lowercase-keys": "^3.0.0", + "p-cancelable": "^3.0.0", + "responselike": "^3.0.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sindresorhus/got?sponsor=1" + } + }, + "node_modules/got/node_modules/@sindresorhus/is": { + "version": "5.6.0", + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "license": "ISC" + }, + "node_modules/gray-matter": { + "version": "4.0.3", + "license": "MIT", + "dependencies": { + "js-yaml": "^3.13.1", + "kind-of": "^6.0.2", + "section-matter": "^1.0.0", + "strip-bom-string": "^1.0.0" + }, + "engines": { + "node": ">=6.0" + } + }, + "node_modules/gray-matter/node_modules/argparse": { + "version": "1.0.10", + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/gray-matter/node_modules/js-yaml": { + "version": "3.14.1", + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/gzip-size": { + "version": "6.0.0", + "license": "MIT", + "dependencies": { + "duplexer": "^0.1.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/handle-thing": { + "version": "2.0.1", + "license": "MIT" + }, + "node_modules/has-bigints": { + "version": "1.0.2", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-value": { + "version": "1.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "get-value": "^2.0.6", + "has-values": "^1.0.0", + "isobject": "^3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/has-values": { + "version": "1.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "is-number": "^3.0.0", + "kind-of": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/has-values/node_modules/is-number": { + "version": "3.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "kind-of": "^3.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/has-values/node_modules/is-number/node_modules/kind-of": { + "version": "3.2.2", + "license": "MIT", + "peer": true, + "dependencies": { + "is-buffer": "^1.1.5" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/has-values/node_modules/kind-of": { + "version": "4.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "is-buffer": "^1.1.5" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/has-yarn": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/hash-base": { + "version": "3.0.4", + "license": "MIT", + "peer": true, + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/hash.js": { + "version": "1.1.7", + "license": "MIT", + "peer": true, + "dependencies": { + "inherits": "^2.0.3", + "minimalistic-assert": "^1.0.1" + } + }, + "node_modules/hasown": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hast-util-from-dom": { + "version": "5.0.0", + "license": "ISC", + "dependencies": { + "@types/hast": "^3.0.0", + "hastscript": "^8.0.0", + "web-namespaces": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-from-html": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "devlop": "^1.1.0", + "hast-util-from-parse5": "^8.0.0", + "parse5": "^7.0.0", + "vfile": "^6.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-from-html-isomorphic": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-from-dom": "^5.0.0", + "hast-util-from-html": "^2.0.0", + "unist-util-remove-position": "^5.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-from-parse5": { + "version": "8.0.1", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "devlop": "^1.0.0", + "hastscript": "^8.0.0", + "property-information": "^6.0.0", + "vfile": "^6.0.0", + "vfile-location": "^5.0.0", + "web-namespaces": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-is-element": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-parse-selector": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-raw": { + "version": "9.0.3", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "@ungap/structured-clone": "^1.0.0", + "hast-util-from-parse5": "^8.0.0", + "hast-util-to-parse5": "^8.0.0", + "html-void-elements": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "parse5": "^7.0.0", + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0", + "web-namespaces": "^2.0.0", + "zwitch": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-to-estree": { + "version": "3.1.0", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "comma-separated-tokens": "^2.0.0", + "devlop": "^1.0.0", + "estree-util-attach-comments": "^3.0.0", + "estree-util-is-identifier-name": "^3.0.0", + "hast-util-whitespace": "^3.0.0", + "mdast-util-mdx-expression": "^2.0.0", + "mdast-util-mdx-jsx": "^3.0.0", + "mdast-util-mdxjs-esm": "^2.0.0", + "property-information": "^6.0.0", + "space-separated-tokens": "^2.0.0", + "style-to-object": "^0.4.0", + "unist-util-position": "^5.0.0", + "zwitch": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-to-jsx-runtime": { + "version": "2.3.0", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "comma-separated-tokens": "^2.0.0", + "devlop": "^1.0.0", + "estree-util-is-identifier-name": "^3.0.0", + "hast-util-whitespace": "^3.0.0", + "mdast-util-mdx-expression": "^2.0.0", + "mdast-util-mdx-jsx": "^3.0.0", + "mdast-util-mdxjs-esm": "^2.0.0", + "property-information": "^6.0.0", + "space-separated-tokens": "^2.0.0", + "style-to-object": "^1.0.0", + "unist-util-position": "^5.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-to-jsx-runtime/node_modules/inline-style-parser": { + "version": "0.2.3", + "license": "MIT" + }, + "node_modules/hast-util-to-jsx-runtime/node_modules/style-to-object": { + "version": "1.0.6", + "license": "MIT", + "dependencies": { + "inline-style-parser": "0.2.3" + } + }, + "node_modules/hast-util-to-parse5": { + "version": "8.0.0", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "comma-separated-tokens": "^2.0.0", + "devlop": "^1.0.0", + "property-information": "^6.0.0", + "space-separated-tokens": "^2.0.0", + "web-namespaces": "^2.0.0", + "zwitch": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-to-text": { + "version": "4.0.2", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "hast-util-is-element": "^3.0.0", + "unist-util-find-after": "^5.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-whitespace": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hastscript": { + "version": "8.0.0", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "comma-separated-tokens": "^2.0.0", + "hast-util-parse-selector": "^4.0.0", + "property-information": "^6.0.0", + "space-separated-tokens": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/he": { + "version": "1.2.0", + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, + "node_modules/heap": { + "version": "0.2.7", + "license": "MIT" + }, + "node_modules/history": { + "version": "4.10.1", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.1.2", + "loose-envify": "^1.2.0", + "resolve-pathname": "^3.0.0", + "tiny-invariant": "^1.0.2", + "tiny-warning": "^1.0.0", + "value-equal": "^1.0.1" + } + }, + "node_modules/hmac-drbg": { + "version": "1.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "hash.js": "^1.0.3", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.1" + } + }, + "node_modules/hoist-non-react-statics": { + "version": "3.3.2", + "license": "BSD-3-Clause", + "dependencies": { + "react-is": "^16.7.0" + } + }, + "node_modules/hpack.js": { + "version": "2.1.6", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.1", + "obuf": "^1.0.0", + "readable-stream": "^2.0.1", + "wbuf": "^1.1.0" + } + }, + "node_modules/hpack.js/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/hpack.js/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/hpack.js/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT" + }, + "node_modules/hpack.js/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/html-entities": { + "version": "2.4.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/mdevils" + }, + { + "type": "patreon", + "url": "https://patreon.com/mdevils" + } + ], + "license": "MIT" + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "license": "MIT" + }, + "node_modules/html-minifier-terser": { + "version": "7.2.0", + "license": "MIT", + "dependencies": { + "camel-case": "^4.1.2", + "clean-css": "~5.3.2", + "commander": "^10.0.0", + "entities": "^4.4.0", + "param-case": "^3.0.4", + "relateurl": "^0.2.7", + "terser": "^5.15.1" + }, + "bin": { + "html-minifier-terser": "cli.js" + }, + "engines": { + "node": "^14.13.1 || >=16.0.0" + } + }, + "node_modules/html-minifier-terser/node_modules/commander": { + "version": "10.0.1", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/html-tags": { + "version": "3.3.1", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/html-void-elements": { + "version": "3.0.0", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/html-webpack-plugin": { + "version": "5.6.0", + "license": "MIT", + "dependencies": { + "@types/html-minifier-terser": "^6.0.0", + "html-minifier-terser": "^6.0.2", + "lodash": "^4.17.21", + "pretty-error": "^4.0.0", + "tapable": "^2.0.0" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/html-webpack-plugin" + }, + "peerDependencies": { + "@rspack/core": "0.x || 1.x", + "webpack": "^5.20.0" + }, + "peerDependenciesMeta": { + "@rspack/core": { + "optional": true + }, + "webpack": { + "optional": true + } + } + }, + "node_modules/html-webpack-plugin/node_modules/commander": { + "version": "8.3.0", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/html-webpack-plugin/node_modules/html-minifier-terser": { + "version": "6.1.0", + "license": "MIT", + "dependencies": { + "camel-case": "^4.1.2", + "clean-css": "^5.2.2", + "commander": "^8.3.0", + "he": "^1.2.0", + "param-case": "^3.0.4", + "relateurl": "^0.2.7", + "terser": "^5.10.0" + }, + "bin": { + "html-minifier-terser": "cli.js" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/htmlparser2": { + "version": "8.0.2", + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1", + "entities": "^4.4.0" + } + }, + "node_modules/http-cache-semantics": { + "version": "4.1.1", + "license": "BSD-2-Clause" + }, + "node_modules/http-deceiver": { + "version": "1.2.7", + "license": "MIT" + }, + "node_modules/http-errors": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-link-header": { + "version": "1.1.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/http-parser-js": { + "version": "0.5.8", + "license": "MIT" + }, + "node_modules/http-proxy": { + "version": "1.18.1", + "license": "MIT", + "dependencies": { + "eventemitter3": "^4.0.0", + "follow-redirects": "^1.0.0", + "requires-port": "^1.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/http-proxy-agent/node_modules/agent-base": { + "version": "7.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/http-proxy-middleware": { + "version": "2.0.6", + "license": "MIT", + "dependencies": { + "@types/http-proxy": "^1.17.8", + "http-proxy": "^1.18.1", + "is-glob": "^4.0.1", + "is-plain-obj": "^3.0.0", + "micromatch": "^4.0.2" + }, + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "@types/express": "^4.17.13" + }, + "peerDependenciesMeta": { + "@types/express": { + "optional": true + } + } + }, + "node_modules/http-proxy-middleware/node_modules/is-plain-obj": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/http2-wrapper": { + "version": "2.2.1", + "license": "MIT", + "dependencies": { + "quick-lru": "^5.1.1", + "resolve-alpn": "^1.2.0" + }, + "engines": { + "node": ">=10.19.0" + } + }, + "node_modules/https-browserify": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/human-signals": { + "version": "2.1.0", + "license": "Apache-2.0", + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/icss-utils": { + "version": "5.1.0", + "license": "ISC", + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/idb": { + "version": "7.1.1", + "license": "ISC" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/iferr": { + "version": "0.1.5", + "license": "MIT", + "peer": true + }, + "node_modules/ignore": { + "version": "5.3.1", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/image-size": { + "version": "1.1.1", + "license": "MIT", + "dependencies": { + "queue": "6.0.2" + }, + "bin": { + "image-size": "bin/image-size.js" + }, + "engines": { + "node": ">=16.x" + } + }, + "node_modules/image-ssim": { + "version": "0.2.0", + "dev": true, + "license": "MIT" + }, + "node_modules/immer": { + "version": "9.0.21", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/immer" + } + }, + "node_modules/import-fresh": { + "version": "3.3.0", + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/import-lazy": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/indent-string": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/infer-owner": { + "version": "1.0.4", + "license": "ISC", + "peer": true + }, + "node_modules/infima": { + "version": "0.2.0-alpha.44", + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "license": "ISC" + }, + "node_modules/inline-style-parser": { + "version": "0.1.1", + "license": "MIT" + }, + "node_modules/internal-slot": { + "version": "1.0.7", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "hasown": "^2.0.0", + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/internmap": { + "version": "2.0.3", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/interpret": { + "version": "1.4.0", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/intl-messageformat": { + "version": "10.5.14", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@formatjs/ecma402-abstract": "2.0.0", + "@formatjs/fast-memoize": "2.2.0", + "@formatjs/icu-messageformat-parser": "2.7.8", + "tslib": "^2.4.0" + } + }, + "node_modules/invariant": { + "version": "2.2.4", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.0.0" + } + }, + "node_modules/ip-address": { + "version": "9.0.5", + "dev": true, + "license": "MIT", + "dependencies": { + "jsbn": "1.1.0", + "sprintf-js": "^1.1.3" + }, + "engines": { + "node": ">= 12" + } + }, + "node_modules/ip-address/node_modules/sprintf-js": { + "version": "1.1.3", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/ipaddr.js": { + "version": "2.1.0", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/is-accessor-descriptor": { + "version": "1.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-alphabetical": { + "version": "2.0.1", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-alphanumerical": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.4", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "license": "MIT" + }, + "node_modules/is-bigint": { + "version": "1.0.4", + "license": "MIT", + "dependencies": { + "has-bigints": "^1.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-boolean-object": { + "version": "1.1.2", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-buffer": { + "version": "1.1.6", + "license": "MIT", + "peer": true + }, + "node_modules/is-callable": { + "version": "1.2.7", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-ci": { + "version": "3.0.1", + "license": "MIT", + "dependencies": { + "ci-info": "^3.2.0" + }, + "bin": { + "is-ci": "bin.js" + } + }, + "node_modules/is-core-module": { + "version": "2.13.1", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-data-descriptor": { + "version": "1.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-date-object": { + "version": "1.0.5", + "license": "MIT", + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-decimal": { + "version": "2.0.1", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-descriptor": { + "version": "1.0.3", + "license": "MIT", + "peer": true, + "dependencies": { + "is-accessor-descriptor": "^1.0.1", + "is-data-descriptor": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-docker": { + "version": "2.2.1", + "license": "MIT", + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-extendable": { + "version": "0.1.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-hexadecimal": { + "version": "2.0.1", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-installed-globally": { + "version": "0.4.0", + "license": "MIT", + "dependencies": { + "global-dirs": "^3.0.0", + "is-path-inside": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-module": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/is-negative-zero": { + "version": "2.0.2", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-npm": { + "version": "6.0.0", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-number-object": { + "version": "1.0.7", + "license": "MIT", + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-obj": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-path-cwd": { + "version": "2.2.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/is-path-inside": { + "version": "3.0.3", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-plain-obj": { + "version": "4.1.0", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-plain-object": { + "version": "5.0.0", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-reference": { + "version": "3.0.2", + "license": "MIT", + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/is-regex": { + "version": "1.1.4", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-regexp": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-root": { + "version": "2.1.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-string": { + "version": "1.0.7", + "license": "MIT", + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.0.4", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.13", + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typedarray": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/is-weakref": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-windows": { + "version": "1.0.2", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-wsl": { + "version": "2.2.0", + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-yarn-global": { + "version": "0.4.1", + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/isarray": { + "version": "0.0.1", + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "license": "ISC" + }, + "node_modules/isobject": { + "version": "3.0.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/jackspeak": { + "version": "2.3.6", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/jake": { + "version": "10.8.7", + "license": "Apache-2.0", + "dependencies": { + "async": "^3.2.3", + "chalk": "^4.0.2", + "filelist": "^1.0.4", + "minimatch": "^3.1.2" + }, + "bin": { + "jake": "bin/cli.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/jest-util": { + "version": "29.7.0", + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-worker": { + "version": "29.7.0", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "jest-util": "^29.7.0", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-worker/node_modules/supports-color": { + "version": "8.1.1", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/jiti": { + "version": "1.21.0", + "license": "MIT", + "bin": { + "jiti": "bin/jiti.js" + } + }, + "node_modules/joi": { + "version": "17.13.3", + "license": "BSD-3-Clause", + "dependencies": { + "@hapi/hoek": "^9.3.0", + "@hapi/topo": "^5.1.0", + "@sideway/address": "^4.1.5", + "@sideway/formula": "^3.0.1", + "@sideway/pinpoint": "^2.0.0" + } + }, + "node_modules/jpeg-js": { + "version": "0.4.4", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/js-library-detector": { + "version": "6.7.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsbn": { + "version": "1.1.0", + "dev": true, + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.0.2", + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "license": "MIT" + }, + "node_modules/json-parse-better-errors": { + "version": "1.0.2", + "license": "MIT", + "peer": true + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "license": "MIT" + }, + "node_modules/json-schema": { + "version": "0.4.0", + "license": "(AFL-2.1 OR BSD-3-Clause)" + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/jsonfile": { + "version": "6.1.0", + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/jsonpointer": { + "version": "5.0.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/katex": { + "version": "0.16.10", + "funding": [ + "https://opencollective.com/katex", + "https://github.com/sponsors/katex" + ], + "license": "MIT", + "dependencies": { + "commander": "^8.3.0" + }, + "bin": { + "katex": "cli.js" + } + }, + "node_modules/katex/node_modules/commander": { + "version": "8.3.0", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/khroma": { + "version": "2.1.0" + }, + "node_modules/kind-of": { + "version": "6.0.3", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/kleur": { + "version": "3.0.3", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/latest-version": { + "version": "7.0.0", + "license": "MIT", + "dependencies": { + "package-json": "^8.1.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/launch-editor": { + "version": "2.6.1", + "license": "MIT", + "dependencies": { + "picocolors": "^1.0.0", + "shell-quote": "^1.8.1" + } + }, + "node_modules/layout-base": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/leven": { + "version": "3.1.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/lighthouse": { + "version": "12.2.1", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@paulirish/trace_engine": "0.0.32", + "@sentry/node": "^6.17.4", + "axe-core": "^4.10.0", + "chrome-launcher": "^1.1.2", + "configstore": "^5.0.1", + "csp_evaluator": "1.1.1", + "devtools-protocol": "0.0.1312386", + "enquirer": "^2.3.6", + "http-link-header": "^1.1.1", + "intl-messageformat": "^10.5.3", + "jpeg-js": "^0.4.4", + "js-library-detector": "^6.7.0", + "lighthouse-logger": "^2.0.1", + "lighthouse-stack-packs": "1.12.1", + "lodash": "^4.17.21", + "lookup-closest-locale": "6.2.0", + "metaviewport-parser": "0.3.0", + "open": "^8.4.0", + "parse-cache-control": "1.0.1", + "puppeteer-core": "^23.3.0", + "robots-parser": "^3.0.1", + "semver": "^5.3.0", + "speedline-core": "^1.4.3", + "third-party-web": "^0.24.5", + "tldts-icann": "^6.1.16", + "ws": "^7.0.0", + "yargs": "^17.3.1", + "yargs-parser": "^21.0.0" + }, + "bin": { + "chrome-debug": "core/scripts/manual-chrome-launcher.js", + "lighthouse": "cli/index.js", + "smokehouse": "cli/test/smokehouse/frontends/smokehouse-bin.js" + }, + "engines": { + "node": ">=18.16" + } + }, + "node_modules/lighthouse-logger": { + "version": "2.0.1", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "debug": "^2.6.9", + "marky": "^1.2.2" + } + }, + "node_modules/lighthouse-logger/node_modules/debug": { + "version": "2.6.9", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/lighthouse-logger/node_modules/ms": { + "version": "2.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/lighthouse-stack-packs": { + "version": "1.12.1", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/lighthouse/node_modules/configstore": { + "version": "5.0.1", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "dot-prop": "^5.2.0", + "graceful-fs": "^4.1.2", + "make-dir": "^3.0.0", + "unique-string": "^2.0.0", + "write-file-atomic": "^3.0.0", + "xdg-basedir": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lighthouse/node_modules/crypto-random-string": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/lighthouse/node_modules/dot-prop": { + "version": "5.3.0", + "dev": true, + "license": "MIT", + "dependencies": { + "is-obj": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lighthouse/node_modules/is-obj": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/lighthouse/node_modules/make-dir": { + "version": "3.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lighthouse/node_modules/make-dir/node_modules/semver": { + "version": "6.3.1", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/lighthouse/node_modules/semver": { + "version": "5.7.2", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/lighthouse/node_modules/unique-string": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "crypto-random-string": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lighthouse/node_modules/xdg-basedir": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/lilconfig": { + "version": "3.1.1", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "license": "MIT" + }, + "node_modules/lit": { + "version": "3.1.2", + "license": "BSD-3-Clause", + "dependencies": { + "@lit/reactive-element": "^2.0.4", + "lit-element": "^4.0.4", + "lit-html": "^3.1.2" + } + }, + "node_modules/lit-element": { + "version": "4.0.4", + "license": "BSD-3-Clause", + "dependencies": { + "@lit-labs/ssr-dom-shim": "^1.2.0", + "@lit/reactive-element": "^2.0.4", + "lit-html": "^3.1.2" + } + }, + "node_modules/lit-html": { + "version": "3.1.2", + "license": "BSD-3-Clause", + "dependencies": { + "@types/trusted-types": "^2.0.2" + } + }, + "node_modules/loader-runner": { + "version": "4.3.0", + "license": "MIT", + "engines": { + "node": ">=6.11.5" + } + }, + "node_modules/loader-utils": { + "version": "2.0.4", + "license": "MIT", + "dependencies": { + "big.js": "^5.2.2", + "emojis-list": "^3.0.0", + "json5": "^2.1.2" + }, + "engines": { + "node": ">=8.9.0" + } + }, + "node_modules/locate-path": { + "version": "7.2.0", + "license": "MIT", + "dependencies": { + "p-locate": "^6.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "license": "MIT" + }, + "node_modules/lodash-es": { + "version": "4.17.21", + "license": "MIT" + }, + "node_modules/lodash.debounce": { + "version": "4.0.8", + "license": "MIT" + }, + "node_modules/lodash.memoize": { + "version": "4.1.2", + "license": "MIT" + }, + "node_modules/lodash.reduce": { + "version": "4.6.0", + "license": "MIT" + }, + "node_modules/lodash.sortby": { + "version": "4.7.0", + "license": "MIT" + }, + "node_modules/lodash.startswith": { + "version": "4.2.1", + "license": "MIT" + }, + "node_modules/lodash.uniq": { + "version": "4.5.0", + "license": "MIT" + }, + "node_modules/longest-streak": { + "version": "3.1.0", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/lookup-closest-locale": { + "version": "6.2.0", + "dev": true, + "license": "MIT" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lower-case": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.3" + } + }, + "node_modules/lowercase-keys": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lru_map": { + "version": "0.3.3", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/magic-string": { + "version": "0.25.9", + "license": "MIT", + "dependencies": { + "sourcemap-codec": "^1.4.8" + } + }, + "node_modules/make-dir": { + "version": "2.1.0", + "license": "MIT", + "peer": true, + "dependencies": { + "pify": "^4.0.1", + "semver": "^5.6.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/make-dir/node_modules/semver": { + "version": "5.7.2", + "license": "ISC", + "peer": true, + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/map-cache": { + "version": "0.2.2", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/map-visit": { + "version": "1.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "object-visit": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/markdown-extensions": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/markdown-table": { + "version": "3.0.3", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/marky": { + "version": "1.2.5", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/md5.js": { + "version": "1.3.5", + "license": "MIT", + "peer": true, + "dependencies": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "node_modules/mdast-util-directive": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "devlop": "^1.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0", + "parse-entities": "^4.0.0", + "stringify-entities": "^4.0.0", + "unist-util-visit-parents": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-find-and-replace": { + "version": "3.0.1", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "escape-string-regexp": "^5.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp": { + "version": "5.0.0", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mdast-util-from-markdown": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "mdast-util-to-string": "^4.0.0", + "micromark": "^4.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-decode-string": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-from-markdown/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/mdast-util-frontmatter": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "escape-string-regexp": "^5.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0", + "micromark-extension-frontmatter": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-frontmatter/node_modules/escape-string-regexp": { + "version": "5.0.0", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mdast-util-gfm": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-gfm-autolink-literal": "^2.0.0", + "mdast-util-gfm-footnote": "^2.0.0", + "mdast-util-gfm-strikethrough": "^2.0.0", + "mdast-util-gfm-table": "^2.0.0", + "mdast-util-gfm-task-list-item": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-gfm-autolink-literal": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "ccount": "^2.0.0", + "devlop": "^1.0.0", + "mdast-util-find-and-replace": "^3.0.0", + "micromark-util-character": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-gfm-autolink-literal/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/mdast-util-gfm-autolink-literal/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/mdast-util-gfm-footnote": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "devlop": "^1.1.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-gfm-strikethrough": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-gfm-table": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "markdown-table": "^3.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-gfm-task-list-item": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-math": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "longest-streak": "^3.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.1.0", + "unist-util-remove-position": "^5.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-mdx": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-mdx-expression": "^2.0.0", + "mdast-util-mdx-jsx": "^3.0.0", + "mdast-util-mdxjs-esm": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-mdx-expression": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-mdx-jsx": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "devlop": "^1.1.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0", + "parse-entities": "^4.0.0", + "stringify-entities": "^4.0.0", + "unist-util-remove-position": "^5.0.0", + "unist-util-stringify-position": "^4.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-mdxjs-esm": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.0", + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "devlop": "^1.0.0", + "mdast-util-from-markdown": "^2.0.0", + "mdast-util-to-markdown": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-phrasing": { + "version": "4.1.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-to-hast": { + "version": "13.1.0", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@ungap/structured-clone": "^1.0.0", + "devlop": "^1.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "trim-lines": "^3.0.0", + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-to-markdown": { + "version": "2.1.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "@types/unist": "^3.0.0", + "longest-streak": "^3.0.0", + "mdast-util-phrasing": "^4.0.0", + "mdast-util-to-string": "^4.0.0", + "micromark-util-decode-string": "^2.0.0", + "unist-util-visit": "^5.0.0", + "zwitch": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdast-util-to-string": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mdn-data": { + "version": "2.0.30", + "license": "CC0-1.0" + }, + "node_modules/media-typer": { + "version": "0.3.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/memfs": { + "version": "3.5.3", + "license": "Unlicense", + "dependencies": { + "fs-monkey": "^1.0.4" + }, + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/memoize-one": { + "version": "5.2.1", + "license": "MIT" + }, + "node_modules/memory-fs": { + "version": "0.4.1", + "license": "MIT", + "peer": true, + "dependencies": { + "errno": "^0.1.3", + "readable-stream": "^2.0.1" + } + }, + "node_modules/memory-fs/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/memory-fs/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "peer": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/memory-fs/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "peer": true + }, + "node_modules/memory-fs/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/merge2": { + "version": "1.4.1", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/mermaid": { + "version": "10.8.0", + "license": "MIT", + "dependencies": { + "@braintree/sanitize-url": "^6.0.1", + "@types/d3-scale": "^4.0.3", + "@types/d3-scale-chromatic": "^3.0.0", + "cytoscape": "^3.28.1", + "cytoscape-cose-bilkent": "^4.1.0", + "d3": "^7.4.0", + "d3-sankey": "^0.12.3", + "dagre-d3-es": "7.0.10", + "dayjs": "^1.11.7", + "dompurify": "^3.0.5", + "elkjs": "^0.9.0", + "khroma": "^2.0.0", + "lodash-es": "^4.17.21", + "mdast-util-from-markdown": "^1.3.0", + "non-layered-tidy-tree-layout": "^2.0.2", + "stylis": "^4.1.3", + "ts-dedent": "^2.2.0", + "uuid": "^9.0.0", + "web-worker": "^1.2.0" + } + }, + "node_modules/mermaid/node_modules/@types/mdast": { + "version": "3.0.15", + "license": "MIT", + "dependencies": { + "@types/unist": "^2" + } + }, + "node_modules/mermaid/node_modules/@types/unist": { + "version": "2.0.10", + "license": "MIT" + }, + "node_modules/mermaid/node_modules/mdast-util-from-markdown": { + "version": "1.3.1", + "license": "MIT", + "dependencies": { + "@types/mdast": "^3.0.0", + "@types/unist": "^2.0.0", + "decode-named-character-reference": "^1.0.0", + "mdast-util-to-string": "^3.1.0", + "micromark": "^3.0.0", + "micromark-util-decode-numeric-character-reference": "^1.0.0", + "micromark-util-decode-string": "^1.0.0", + "micromark-util-normalize-identifier": "^1.0.0", + "micromark-util-symbol": "^1.0.0", + "micromark-util-types": "^1.0.0", + "unist-util-stringify-position": "^3.0.0", + "uvu": "^0.5.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mermaid/node_modules/mdast-util-to-string": { + "version": "3.2.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mermaid/node_modules/micromark": { + "version": "3.2.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "@types/debug": "^4.0.0", + "debug": "^4.0.0", + "decode-named-character-reference": "^1.0.0", + "micromark-core-commonmark": "^1.0.1", + "micromark-factory-space": "^1.0.0", + "micromark-util-character": "^1.0.0", + "micromark-util-chunked": "^1.0.0", + "micromark-util-combine-extensions": "^1.0.0", + "micromark-util-decode-numeric-character-reference": "^1.0.0", + "micromark-util-encode": "^1.0.0", + "micromark-util-normalize-identifier": "^1.0.0", + "micromark-util-resolve-all": "^1.0.0", + "micromark-util-sanitize-uri": "^1.0.0", + "micromark-util-subtokenize": "^1.0.0", + "micromark-util-symbol": "^1.0.0", + "micromark-util-types": "^1.0.1", + "uvu": "^0.5.0" + } + }, + "node_modules/mermaid/node_modules/micromark-core-commonmark": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "decode-named-character-reference": "^1.0.0", + "micromark-factory-destination": "^1.0.0", + "micromark-factory-label": "^1.0.0", + "micromark-factory-space": "^1.0.0", + "micromark-factory-title": "^1.0.0", + "micromark-factory-whitespace": "^1.0.0", + "micromark-util-character": "^1.0.0", + "micromark-util-chunked": "^1.0.0", + "micromark-util-classify-character": "^1.0.0", + "micromark-util-html-tag-name": "^1.0.0", + "micromark-util-normalize-identifier": "^1.0.0", + "micromark-util-resolve-all": "^1.0.0", + "micromark-util-subtokenize": "^1.0.0", + "micromark-util-symbol": "^1.0.0", + "micromark-util-types": "^1.0.1", + "uvu": "^0.5.0" + } + }, + "node_modules/mermaid/node_modules/micromark-factory-destination": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^1.0.0", + "micromark-util-symbol": "^1.0.0", + "micromark-util-types": "^1.0.0" + } + }, + "node_modules/mermaid/node_modules/micromark-factory-label": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^1.0.0", + "micromark-util-symbol": "^1.0.0", + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" + } + }, + "node_modules/mermaid/node_modules/micromark-factory-title": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-factory-space": "^1.0.0", + "micromark-util-character": "^1.0.0", + "micromark-util-symbol": "^1.0.0", + "micromark-util-types": "^1.0.0" + } + }, + "node_modules/mermaid/node_modules/micromark-factory-whitespace": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-factory-space": "^1.0.0", + "micromark-util-character": "^1.0.0", + "micromark-util-symbol": "^1.0.0", + "micromark-util-types": "^1.0.0" + } + }, + "node_modules/mermaid/node_modules/micromark-util-chunked": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^1.0.0" + } + }, + "node_modules/mermaid/node_modules/micromark-util-classify-character": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^1.0.0", + "micromark-util-symbol": "^1.0.0", + "micromark-util-types": "^1.0.0" + } + }, + "node_modules/mermaid/node_modules/micromark-util-combine-extensions": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-chunked": "^1.0.0", + "micromark-util-types": "^1.0.0" + } + }, + "node_modules/mermaid/node_modules/micromark-util-decode-numeric-character-reference": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^1.0.0" + } + }, + "node_modules/mermaid/node_modules/micromark-util-decode-string": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "decode-named-character-reference": "^1.0.0", + "micromark-util-character": "^1.0.0", + "micromark-util-decode-numeric-character-reference": "^1.0.0", + "micromark-util-symbol": "^1.0.0" + } + }, + "node_modules/mermaid/node_modules/micromark-util-encode": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/mermaid/node_modules/micromark-util-html-tag-name": { + "version": "1.2.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/mermaid/node_modules/micromark-util-normalize-identifier": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^1.0.0" + } + }, + "node_modules/mermaid/node_modules/micromark-util-resolve-all": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-types": "^1.0.0" + } + }, + "node_modules/mermaid/node_modules/micromark-util-sanitize-uri": { + "version": "1.2.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^1.0.0", + "micromark-util-encode": "^1.0.0", + "micromark-util-symbol": "^1.0.0" + } + }, + "node_modules/mermaid/node_modules/micromark-util-subtokenize": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-chunked": "^1.0.0", + "micromark-util-symbol": "^1.0.0", + "micromark-util-types": "^1.0.0", + "uvu": "^0.5.0" + } + }, + "node_modules/mermaid/node_modules/micromark-util-types": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/mermaid/node_modules/unist-util-stringify-position": { + "version": "3.0.3", + "license": "MIT", + "dependencies": { + "@types/unist": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/mermaid/node_modules/uuid": { + "version": "9.0.1", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/metaviewport-parser": { + "version": "0.3.0", + "dev": true, + "license": "MIT" + }, + "node_modules/methods": { + "version": "1.1.2", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/micromark": { + "version": "4.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "@types/debug": "^4.0.0", + "debug": "^4.0.0", + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "micromark-core-commonmark": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-combine-extensions": "^2.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-subtokenize": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-core-commonmark": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "micromark-factory-destination": "^2.0.0", + "micromark-factory-label": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-factory-title": "^2.0.0", + "micromark-factory-whitespace": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-html-tag-name": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-subtokenize": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-core-commonmark/node_modules/micromark-factory-space": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-core-commonmark/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-core-commonmark/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-extension-directive": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-factory-whitespace": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "parse-entities": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-directive/node_modules/micromark-factory-space": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-directive/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-directive/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-extension-frontmatter": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "fault": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-frontmatter/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-frontmatter/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-extension-gfm": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "micromark-extension-gfm-autolink-literal": "^2.0.0", + "micromark-extension-gfm-footnote": "^2.0.0", + "micromark-extension-gfm-strikethrough": "^2.0.0", + "micromark-extension-gfm-table": "^2.0.0", + "micromark-extension-gfm-tagfilter": "^2.0.0", + "micromark-extension-gfm-task-list-item": "^2.0.0", + "micromark-util-combine-extensions": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-autolink-literal": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-autolink-literal/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-gfm-autolink-literal/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-extension-gfm-footnote": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-core-commonmark": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-footnote/node_modules/micromark-factory-space": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-gfm-footnote/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-gfm-footnote/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-extension-gfm-strikethrough": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-strikethrough/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-extension-gfm-table": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-table/node_modules/micromark-factory-space": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-gfm-table/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-gfm-table/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-extension-gfm-tagfilter": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-task-list-item": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-task-list-item/node_modules/micromark-factory-space": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-gfm-task-list-item/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-gfm-task-list-item/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-extension-math": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "@types/katex": "^0.16.0", + "devlop": "^1.0.0", + "katex": "^0.16.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-math/node_modules/micromark-factory-space": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-math/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-math/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-extension-mdx-expression": { + "version": "3.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "devlop": "^1.0.0", + "micromark-factory-mdx-expression": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-events-to-acorn": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-mdx-expression/node_modules/micromark-factory-space": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-mdx-expression/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-mdx-expression/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-extension-mdx-jsx": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "@types/acorn": "^4.0.0", + "@types/estree": "^1.0.0", + "devlop": "^1.0.0", + "estree-util-is-identifier-name": "^3.0.0", + "micromark-factory-mdx-expression": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-mdx-jsx/node_modules/micromark-factory-space": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-mdx-jsx/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-mdx-jsx/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-extension-mdx-md": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-mdxjs": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "acorn": "^8.0.0", + "acorn-jsx": "^5.0.0", + "micromark-extension-mdx-expression": "^3.0.0", + "micromark-extension-mdx-jsx": "^3.0.0", + "micromark-extension-mdx-md": "^2.0.0", + "micromark-extension-mdxjs-esm": "^3.0.0", + "micromark-util-combine-extensions": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-mdxjs-esm": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "devlop": "^1.0.0", + "micromark-core-commonmark": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-events-to-acorn": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unist-util-position-from-estree": "^2.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-mdxjs-esm/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-extension-mdxjs-esm/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-factory-destination": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-destination/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-destination/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-factory-label": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-label/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-label/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-factory-mdx-expression": { + "version": "2.0.1", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "devlop": "^1.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-events-to-acorn": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unist-util-position-from-estree": "^2.0.0", + "vfile-message": "^4.0.0" + } + }, + "node_modules/micromark-factory-mdx-expression/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-mdx-expression/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-factory-space": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^1.0.0", + "micromark-util-types": "^1.0.0" + } + }, + "node_modules/micromark-factory-space/node_modules/micromark-util-types": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-factory-title": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-title/node_modules/micromark-factory-space": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-title/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-title/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-factory-whitespace": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-whitespace/node_modules/micromark-factory-space": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-whitespace/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-whitespace/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-character": { + "version": "1.2.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^1.0.0", + "micromark-util-types": "^1.0.0" + } + }, + "node_modules/micromark-util-character/node_modules/micromark-util-types": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-chunked": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-chunked/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-classify-character": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-classify-character/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-classify-character/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-combine-extensions": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-chunked": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-decode-numeric-character-reference": { + "version": "2.0.1", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-decode-numeric-character-reference/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-decode-string": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "decode-named-character-reference": "^1.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-decode-string/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-decode-string/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-encode": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-events-to-acorn": { + "version": "2.0.2", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "@types/acorn": "^4.0.0", + "@types/estree": "^1.0.0", + "@types/unist": "^3.0.0", + "devlop": "^1.0.0", + "estree-util-visit": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0", + "vfile-message": "^4.0.0" + } + }, + "node_modules/micromark-util-events-to-acorn/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-html-tag-name": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-normalize-identifier": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-normalize-identifier/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-resolve-all": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-sanitize-uri": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-sanitize-uri/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-sanitize-uri/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-subtokenize": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-subtokenize/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-symbol": { + "version": "1.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-types": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark/node_modules/micromark-factory-space": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark/node_modules/micromark-util-character": { + "version": "2.1.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark/node_modules/micromark-util-symbol": { + "version": "2.0.0", + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromatch": { + "version": "4.0.8", + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/miller-rabin": { + "version": "4.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "bn.js": "^4.0.0", + "brorand": "^1.0.1" + }, + "bin": { + "miller-rabin": "bin/miller-rabin" + } + }, + "node_modules/miller-rabin/node_modules/bn.js": { + "version": "4.12.0", + "license": "MIT", + "peer": true + }, + "node_modules/mime": { + "version": "1.6.0", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.33.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.18", + "license": "MIT", + "dependencies": { + "mime-db": "~1.33.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/mimic-response": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mini-css-extract-plugin": { + "version": "2.8.0", + "license": "MIT", + "dependencies": { + "schema-utils": "^4.0.0", + "tapable": "^2.2.1" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.0.0" + } + }, + "node_modules/minimalistic-assert": { + "version": "1.0.1", + "license": "ISC" + }, + "node_modules/minimalistic-crypto-utils": { + "version": "1.0.1", + "license": "MIT", + "peer": true + }, + "node_modules/minimatch": { + "version": "3.1.2", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minipass": { + "version": "7.0.4", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/mississippi": { + "version": "3.0.0", + "license": "BSD-2-Clause", + "peer": true, + "dependencies": { + "concat-stream": "^1.5.0", + "duplexify": "^3.4.2", + "end-of-stream": "^1.1.0", + "flush-write-stream": "^1.0.0", + "from2": "^2.1.0", + "parallel-transform": "^1.1.0", + "pump": "^3.0.0", + "pumpify": "^1.3.3", + "stream-each": "^1.1.0", + "through2": "^2.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mitt": { + "version": "3.0.1", + "dev": true, + "license": "MIT" + }, + "node_modules/mixin-deep": { + "version": "1.3.2", + "license": "MIT", + "peer": true, + "dependencies": { + "for-in": "^1.0.2", + "is-extendable": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/mixin-deep/node_modules/is-extendable": { + "version": "1.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "is-plain-object": "^2.0.4" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/mixin-deep/node_modules/is-plain-object": { + "version": "2.0.4", + "license": "MIT", + "peer": true, + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/mkdirp": { + "version": "0.5.6", + "license": "MIT", + "peer": true, + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "license": "MIT" + }, + "node_modules/move-concurrently": { + "version": "1.0.1", + "license": "ISC", + "peer": true, + "dependencies": { + "aproba": "^1.1.1", + "copy-concurrently": "^1.0.0", + "fs-write-stream-atomic": "^1.0.8", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.3" + } + }, + "node_modules/move-concurrently/node_modules/rimraf": { + "version": "2.7.1", + "license": "ISC", + "peer": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, + "node_modules/mri": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/mrmime": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "license": "MIT" + }, + "node_modules/multicast-dns": { + "version": "7.2.5", + "license": "MIT", + "dependencies": { + "dns-packet": "^5.2.2", + "thunky": "^1.0.2" + }, + "bin": { + "multicast-dns": "cli.js" + } + }, + "node_modules/mz": { + "version": "2.7.0", + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.7", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/nanomatch": { + "version": "1.2.13", + "license": "MIT", + "peer": true, + "dependencies": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "fragment-cache": "^0.2.1", + "is-windows": "^1.0.2", + "kind-of": "^6.0.2", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/nanomatch/node_modules/extend-shallow": { + "version": "3.0.2", + "license": "MIT", + "peer": true, + "dependencies": { + "assign-symbols": "^1.0.0", + "is-extendable": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/nanomatch/node_modules/is-extendable": { + "version": "1.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "is-plain-object": "^2.0.4" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/nanomatch/node_modules/is-plain-object": { + "version": "2.0.4", + "license": "MIT", + "peer": true, + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/napi-build-utils": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/neo-async": { + "version": "2.6.2", + "license": "MIT" + }, + "node_modules/netmask": { + "version": "2.0.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/no-case": { + "version": "3.0.4", + "license": "MIT", + "dependencies": { + "lower-case": "^2.0.2", + "tslib": "^2.0.3" + } + }, + "node_modules/node-abi": { + "version": "3.54.0", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-addon-api": { + "version": "6.1.0", + "license": "MIT" + }, + "node_modules/node-emoji": { + "version": "2.1.3", + "license": "MIT", + "dependencies": { + "@sindresorhus/is": "^4.6.0", + "char-regex": "^1.0.2", + "emojilib": "^2.4.0", + "skin-tone": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/node-forge": { + "version": "1.3.1", + "license": "(BSD-3-Clause OR GPL-2.0)", + "engines": { + "node": ">= 6.13.0" + } + }, + "node_modules/node-libs-browser": { + "version": "2.2.1", + "license": "MIT", + "peer": true, + "dependencies": { + "assert": "^1.1.1", + "browserify-zlib": "^0.2.0", + "buffer": "^4.3.0", + "console-browserify": "^1.1.0", + "constants-browserify": "^1.0.0", + "crypto-browserify": "^3.11.0", + "domain-browser": "^1.1.1", + "events": "^3.0.0", + "https-browserify": "^1.0.0", + "os-browserify": "^0.3.0", + "path-browserify": "0.0.1", + "process": "^0.11.10", + "punycode": "^1.2.4", + "querystring-es3": "^0.2.0", + "readable-stream": "^2.3.3", + "stream-browserify": "^2.0.1", + "stream-http": "^2.7.2", + "string_decoder": "^1.0.0", + "timers-browserify": "^2.0.4", + "tty-browserify": "0.0.0", + "url": "^0.11.0", + "util": "^0.11.0", + "vm-browserify": "^1.0.1" + } + }, + "node_modules/node-libs-browser/node_modules/buffer": { + "version": "4.9.2", + "license": "MIT", + "peer": true, + "dependencies": { + "base64-js": "^1.0.2", + "ieee754": "^1.1.4", + "isarray": "^1.0.0" + } + }, + "node_modules/node-libs-browser/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/node-libs-browser/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "peer": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/node-libs-browser/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "peer": true + }, + "node_modules/node-libs-browser/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/node-releases": { + "version": "2.0.18", + "license": "MIT" + }, + "node_modules/non-layered-tidy-tree-layout": { + "version": "2.0.2", + "license": "MIT" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/normalize-range": { + "version": "0.1.2", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm-run-path": { + "version": "4.0.1", + "license": "MIT", + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npm-to-yarn": { + "version": "2.2.1", + "license": "MIT", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/nebrelbug/npm-to-yarn?sponsor=1" + } + }, + "node_modules/nprogress": { + "version": "0.2.0", + "license": "MIT" + }, + "node_modules/nth-check": { + "version": "2.1.1", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0" + }, + "funding": { + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, + "node_modules/oauth": { + "version": "0.10.0", + "license": "MIT" + }, + "node_modules/object-assign": { + "version": "4.1.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-copy": { + "version": "0.1.0", + "license": "MIT", + "peer": true, + "dependencies": { + "copy-descriptor": "^0.1.0", + "define-property": "^0.2.5", + "kind-of": "^3.0.3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-copy/node_modules/define-property": { + "version": "0.2.5", + "license": "MIT", + "peer": true, + "dependencies": { + "is-descriptor": "^0.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-copy/node_modules/is-descriptor": { + "version": "0.1.7", + "license": "MIT", + "peer": true, + "dependencies": { + "is-accessor-descriptor": "^1.0.1", + "is-data-descriptor": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object-copy/node_modules/kind-of": { + "version": "3.2.2", + "license": "MIT", + "peer": true, + "dependencies": { + "is-buffer": "^1.1.5" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-hash": { + "version": "3.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/object-inspect": { + "version": "1.13.1", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object-visit": { + "version": "1.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "isobject": "^3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object.assign": { + "version": "4.1.5", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.5", + "define-properties": "^1.2.1", + "has-symbols": "^1.0.3", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.pick": { + "version": "1.3.0", + "license": "MIT", + "peer": true, + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/obuf": { + "version": "1.1.2", + "license": "MIT" + }, + "node_modules/on-finished": { + "version": "2.4.1", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/on-headers": { + "version": "1.0.2", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/open": { + "version": "8.4.2", + "license": "MIT", + "dependencies": { + "define-lazy-prop": "^2.0.0", + "is-docker": "^2.1.1", + "is-wsl": "^2.2.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/opener": { + "version": "1.5.2", + "license": "(WTFPL OR MIT)", + "bin": { + "opener": "bin/opener-bin.js" + } + }, + "node_modules/os-browserify": { + "version": "0.3.0", + "license": "MIT", + "peer": true + }, + "node_modules/os-homedir": { + "version": "1.0.2", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/p-cancelable": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=12.20" + } + }, + "node_modules/p-limit": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "yocto-queue": "^1.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "6.0.0", + "license": "MIT", + "dependencies": { + "p-limit": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-map": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "aggregate-error": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-retry": { + "version": "4.6.2", + "license": "MIT", + "dependencies": { + "@types/retry": "0.12.0", + "retry": "^0.13.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/pac-proxy-agent": { + "version": "7.0.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@tootallnate/quickjs-emscripten": "^0.23.0", + "agent-base": "^7.0.2", + "debug": "^4.3.4", + "get-uri": "^6.0.1", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.5", + "pac-resolver": "^7.0.1", + "socks-proxy-agent": "^8.0.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/pac-proxy-agent/node_modules/agent-base": { + "version": "7.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/pac-proxy-agent/node_modules/https-proxy-agent": { + "version": "7.0.5", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.0.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/pac-resolver": { + "version": "7.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "degenerator": "^5.0.0", + "netmask": "^2.0.2" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/package-json": { + "version": "8.1.1", + "license": "MIT", + "dependencies": { + "got": "^12.1.0", + "registry-auth-token": "^5.0.1", + "registry-url": "^6.0.0", + "semver": "^7.3.7" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/pako": { + "version": "1.0.11", + "license": "(MIT AND Zlib)", + "peer": true + }, + "node_modules/parallel-transform": { + "version": "1.2.0", + "license": "MIT", + "peer": true, + "dependencies": { + "cyclist": "^1.0.1", + "inherits": "^2.0.3", + "readable-stream": "^2.1.5" + } + }, + "node_modules/parallel-transform/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/parallel-transform/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "peer": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/parallel-transform/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "peer": true + }, + "node_modules/parallel-transform/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/param-case": { + "version": "3.0.4", + "license": "MIT", + "dependencies": { + "dot-case": "^3.0.4", + "tslib": "^2.0.3" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-asn1": { + "version": "5.1.7", + "license": "ISC", + "peer": true, + "dependencies": { + "asn1.js": "^4.10.1", + "browserify-aes": "^1.2.0", + "evp_bytestokey": "^1.0.3", + "hash-base": "~3.0", + "pbkdf2": "^3.1.2", + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/parse-cache-control": { + "version": "1.0.1", + "dev": true + }, + "node_modules/parse-entities": { + "version": "4.0.1", + "license": "MIT", + "dependencies": { + "@types/unist": "^2.0.0", + "character-entities": "^2.0.0", + "character-entities-legacy": "^3.0.0", + "character-reference-invalid": "^2.0.0", + "decode-named-character-reference": "^1.0.0", + "is-alphanumerical": "^2.0.0", + "is-decimal": "^2.0.0", + "is-hexadecimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/parse-entities/node_modules/@types/unist": { + "version": "2.0.10", + "license": "MIT" + }, + "node_modules/parse-json": { + "version": "5.2.0", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parse-numeric-range": { + "version": "1.3.0", + "license": "ISC" + }, + "node_modules/parse5": { + "version": "7.1.2", + "license": "MIT", + "dependencies": { + "entities": "^4.4.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-htmlparser2-tree-adapter": { + "version": "7.0.0", + "license": "MIT", + "dependencies": { + "domhandler": "^5.0.2", + "parse5": "^7.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/pascal-case": { + "version": "3.1.2", + "license": "MIT", + "dependencies": { + "no-case": "^3.0.4", + "tslib": "^2.0.3" + } + }, + "node_modules/pascalcase": { + "version": "0.1.1", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/passport": { + "version": "0.7.0", + "license": "MIT", + "dependencies": { + "passport-strategy": "1.x.x", + "pause": "0.0.1", + "utils-merge": "^1.0.1" + }, + "engines": { + "node": ">= 0.4.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/jaredhanson" + } + }, + "node_modules/passport-github": { + "version": "1.1.0", + "license": "MIT", + "dependencies": { + "passport-oauth2": "1.x.x" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/passport-oauth2": { + "version": "1.8.0", + "license": "MIT", + "dependencies": { + "base64url": "3.x.x", + "oauth": "0.10.x", + "passport-strategy": "1.x.x", + "uid2": "0.0.x", + "utils-merge": "1.x.x" + }, + "engines": { + "node": ">= 0.4.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/jaredhanson" + } + }, + "node_modules/passport-strategy": { + "version": "1.0.0", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/path-browserify": { + "version": "0.0.1", + "license": "MIT", + "peer": true + }, + "node_modules/path-dirname": { + "version": "1.0.2", + "license": "MIT", + "optional": true, + "peer": true + }, + "node_modules/path-exists": { + "version": "5.0.0", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-is-inside": { + "version": "1.0.2", + "license": "(WTFPL OR MIT)" + }, + "node_modules/path-key": { + "version": "3.1.1", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "license": "MIT" + }, + "node_modules/path-scurry": { + "version": "1.10.1", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^9.1.1 || ^10.0.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-scurry/node_modules/lru-cache": { + "version": "10.2.0", + "license": "ISC", + "engines": { + "node": "14 || >=16.14" + } + }, + "node_modules/path-to-regexp": { + "version": "1.9.0", + "license": "MIT", + "dependencies": { + "isarray": "0.0.1" + } + }, + "node_modules/path-type": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/pause": { + "version": "0.0.1" + }, + "node_modules/pbkdf2": { + "version": "3.1.2", + "license": "MIT", + "peer": true, + "dependencies": { + "create-hash": "^1.1.2", + "create-hmac": "^1.1.4", + "ripemd160": "^2.0.1", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + }, + "engines": { + "node": ">=0.12" + } + }, + "node_modules/pend": { + "version": "1.2.0", + "dev": true, + "license": "MIT" + }, + "node_modules/periscopic": { + "version": "3.1.0", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^3.0.0", + "is-reference": "^3.0.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.0", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pify": { + "version": "4.0.1", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/pinkie": { + "version": "2.0.4", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pinkie-promise": { + "version": "2.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "pinkie": "^2.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pirates": { + "version": "4.0.6", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/pkg-dir": { + "version": "7.0.0", + "license": "MIT", + "dependencies": { + "find-up": "^6.3.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/pkg-up": { + "version": "3.1.0", + "license": "MIT", + "dependencies": { + "find-up": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pkg-up/node_modules/find-up": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "locate-path": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/pkg-up/node_modules/locate-path": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/pkg-up/node_modules/p-limit": { + "version": "2.3.0", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/pkg-up/node_modules/p-locate": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "p-limit": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/pkg-up/node_modules/path-exists": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/posix-character-classes": { + "version": "0.1.1", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postcss": { + "version": "8.4.47", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.7", + "picocolors": "^1.1.0", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-calc": { + "version": "9.0.1", + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.0.11", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.2.2" + } + }, + "node_modules/postcss-colormin": { + "version": "6.1.0", + "license": "MIT", + "dependencies": { + "browserslist": "^4.23.0", + "caniuse-api": "^3.0.0", + "colord": "^2.9.3", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-convert-values": { + "version": "6.1.0", + "license": "MIT", + "dependencies": { + "browserslist": "^4.23.0", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-discard-comments": { + "version": "6.0.2", + "license": "MIT", + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-discard-duplicates": { + "version": "6.0.3", + "license": "MIT", + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-discard-empty": { + "version": "6.0.3", + "license": "MIT", + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-discard-overridden": { + "version": "6.0.2", + "license": "MIT", + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-discard-unused": { + "version": "6.0.5", + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.0.16" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-import": { + "version": "15.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.0.0", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, + "node_modules/postcss-js": { + "version": "4.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "camelcase-css": "^2.0.1" + }, + "engines": { + "node": "^12 || ^14 || >= 16" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + "peerDependencies": { + "postcss": "^8.4.21" + } + }, + "node_modules/postcss-load-config": { + "version": "4.0.2", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "lilconfig": "^3.0.0", + "yaml": "^2.3.4" + }, + "engines": { + "node": ">= 14" + }, + "peerDependencies": { + "postcss": ">=8.0.9", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "postcss": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/postcss-load-config/node_modules/yaml": { + "version": "2.5.1", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/postcss-loader": { + "version": "7.3.4", + "license": "MIT", + "dependencies": { + "cosmiconfig": "^8.3.5", + "jiti": "^1.20.0", + "semver": "^7.5.4" + }, + "engines": { + "node": ">= 14.15.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "postcss": "^7.0.0 || ^8.0.1", + "webpack": "^5.0.0" + } + }, + "node_modules/postcss-merge-idents": { + "version": "6.0.3", + "license": "MIT", + "dependencies": { + "cssnano-utils": "^4.0.2", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-merge-longhand": { + "version": "6.0.5", + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0", + "stylehacks": "^6.1.1" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-merge-rules": { + "version": "6.1.1", + "license": "MIT", + "dependencies": { + "browserslist": "^4.23.0", + "caniuse-api": "^3.0.0", + "cssnano-utils": "^4.0.2", + "postcss-selector-parser": "^6.0.16" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-minify-font-values": { + "version": "6.1.0", + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-minify-gradients": { + "version": "6.0.3", + "license": "MIT", + "dependencies": { + "colord": "^2.9.3", + "cssnano-utils": "^4.0.2", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-minify-params": { + "version": "6.1.0", + "license": "MIT", + "dependencies": { + "browserslist": "^4.23.0", + "cssnano-utils": "^4.0.2", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-minify-selectors": { + "version": "6.0.4", + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.0.16" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-modules-extract-imports": { + "version": "3.0.0", + "license": "ISC", + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-modules-local-by-default": { + "version": "4.0.4", + "license": "MIT", + "dependencies": { + "icss-utils": "^5.0.0", + "postcss-selector-parser": "^6.0.2", + "postcss-value-parser": "^4.1.0" + }, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-modules-scope": { + "version": "3.1.1", + "license": "ISC", + "dependencies": { + "postcss-selector-parser": "^6.0.4" + }, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-modules-values": { + "version": "4.0.0", + "license": "ISC", + "dependencies": { + "icss-utils": "^5.0.0" + }, + "engines": { + "node": "^10 || ^12 || >= 14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/postcss-nested": { + "version": "6.2.0", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.1.1" + }, + "engines": { + "node": ">=12.0" + }, + "peerDependencies": { + "postcss": "^8.2.14" + } + }, + "node_modules/postcss-normalize-charset": { + "version": "6.0.2", + "license": "MIT", + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-normalize-display-values": { + "version": "6.0.2", + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-normalize-positions": { + "version": "6.0.2", + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-normalize-repeat-style": { + "version": "6.0.2", + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-normalize-string": { + "version": "6.0.2", + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-normalize-timing-functions": { + "version": "6.0.2", + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-normalize-unicode": { + "version": "6.1.0", + "license": "MIT", + "dependencies": { + "browserslist": "^4.23.0", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-normalize-url": { + "version": "6.0.2", + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-normalize-whitespace": { + "version": "6.0.2", + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-ordered-values": { + "version": "6.0.2", + "license": "MIT", + "dependencies": { + "cssnano-utils": "^4.0.2", + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-reduce-idents": { + "version": "6.0.3", + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-reduce-initial": { + "version": "6.1.0", + "license": "MIT", + "dependencies": { + "browserslist": "^4.23.0", + "caniuse-api": "^3.0.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-reduce-transforms": { + "version": "6.0.2", + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.1.2", + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-sort-media-queries": { + "version": "5.2.0", + "license": "MIT", + "dependencies": { + "sort-css-media-queries": "2.2.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "postcss": "^8.4.23" + } + }, + "node_modules/postcss-svgo": { + "version": "6.0.3", + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.2.0", + "svgo": "^3.2.0" + }, + "engines": { + "node": "^14 || ^16 || >= 18" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-unique-selectors": { + "version": "6.0.4", + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.0.16" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "license": "MIT" + }, + "node_modules/postcss-zindex": { + "version": "6.0.2", + "license": "MIT", + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.1", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^1.0.1", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/prebuild-install/node_modules/tar-fs": { + "version": "2.1.1", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/prebuild-install/node_modules/tar-stream": { + "version": "2.2.0", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/pretty-bytes": { + "version": "5.6.0", + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/pretty-error": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "lodash": "^4.17.20", + "renderkid": "^3.0.0" + } + }, + "node_modules/pretty-time": { + "version": "1.1.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/prism-react-renderer": { + "version": "2.4.0", + "license": "MIT", + "dependencies": { + "@types/prismjs": "^1.26.0", + "clsx": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.0.0" + } + }, + "node_modules/prismjs": { + "version": "1.29.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/process": { + "version": "0.11.10", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "license": "MIT" + }, + "node_modules/progress": { + "version": "2.0.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/promise-inflight": { + "version": "1.0.1", + "license": "ISC", + "peer": true + }, + "node_modules/prompts": { + "version": "2.4.2", + "license": "MIT", + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/prop-types": { + "version": "15.8.1", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + } + }, + "node_modules/property-information": { + "version": "6.4.1", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/proto-list": { + "version": "1.2.4", + "license": "ISC" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/proxy-addr/node_modules/ipaddr.js": { + "version": "1.9.1", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/proxy-agent": { + "version": "6.4.0", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.0.2", + "debug": "^4.3.4", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.3", + "lru-cache": "^7.14.1", + "pac-proxy-agent": "^7.0.1", + "proxy-from-env": "^1.1.0", + "socks-proxy-agent": "^8.0.2" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/proxy-agent/node_modules/agent-base": { + "version": "7.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/proxy-agent/node_modules/https-proxy-agent": { + "version": "7.0.5", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.0.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/proxy-agent/node_modules/lru-cache": { + "version": "7.18.3", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "license": "MIT" + }, + "node_modules/prr": { + "version": "1.0.1", + "license": "MIT", + "peer": true + }, + "node_modules/public-encrypt": { + "version": "4.0.3", + "license": "MIT", + "peer": true, + "dependencies": { + "bn.js": "^4.1.0", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "parse-asn1": "^5.0.0", + "randombytes": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "node_modules/public-encrypt/node_modules/bn.js": { + "version": "4.12.0", + "license": "MIT", + "peer": true + }, + "node_modules/pump": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/pumpify": { + "version": "1.5.1", + "license": "MIT", + "peer": true, + "dependencies": { + "duplexify": "^3.6.0", + "inherits": "^2.0.3", + "pump": "^2.0.0" + } + }, + "node_modules/pumpify/node_modules/pump": { + "version": "2.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/punycode": { + "version": "1.4.1", + "license": "MIT" + }, + "node_modules/pupa": { + "version": "3.1.0", + "license": "MIT", + "dependencies": { + "escape-goat": "^4.0.0" + }, + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/puppeteer-core": { + "version": "23.3.0", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@puppeteer/browsers": "2.4.0", + "chromium-bidi": "0.6.5", + "debug": "^4.3.6", + "devtools-protocol": "0.0.1330662", + "typed-query-selector": "^2.12.0", + "ws": "^8.18.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/puppeteer-core/node_modules/devtools-protocol": { + "version": "0.0.1330662", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/puppeteer-core/node_modules/ws": { + "version": "8.18.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/qs": { + "version": "6.13.0", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/querystring-es3": { + "version": "0.2.1", + "peer": true, + "engines": { + "node": ">=0.4.x" + } + }, + "node_modules/queue": { + "version": "6.0.2", + "license": "MIT", + "dependencies": { + "inherits": "~2.0.3" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/queue-tick": { + "version": "1.0.1", + "license": "MIT" + }, + "node_modules/quick-lru": { + "version": "5.1.1", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/randombytes": { + "version": "2.1.0", + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/randomfill": { + "version": "1.0.4", + "license": "MIT", + "peer": true, + "dependencies": { + "randombytes": "^2.0.5", + "safe-buffer": "^5.1.0" + } + }, + "node_modules/range-parser": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/raw-body/node_modules/bytes": { + "version": "3.1.2", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/raw-loader": { + "version": "4.0.2", + "license": "MIT", + "dependencies": { + "loader-utils": "^2.0.0", + "schema-utils": "^3.0.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^4.0.0 || ^5.0.0" + } + }, + "node_modules/raw-loader/node_modules/ajv": { + "version": "6.12.6", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/raw-loader/node_modules/ajv-keywords": { + "version": "3.5.2", + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/raw-loader/node_modules/json-schema-traverse": { + "version": "0.4.1", + "license": "MIT" + }, + "node_modules/raw-loader/node_modules/schema-utils": { + "version": "3.3.0", + "license": "MIT", + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/rc/node_modules/strip-json-comments": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react": { + "version": "18.3.1", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dev-utils": { + "version": "12.0.1", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.16.0", + "address": "^1.1.2", + "browserslist": "^4.18.1", + "chalk": "^4.1.2", + "cross-spawn": "^7.0.3", + "detect-port-alt": "^1.1.6", + "escape-string-regexp": "^4.0.0", + "filesize": "^8.0.6", + "find-up": "^5.0.0", + "fork-ts-checker-webpack-plugin": "^6.5.0", + "global-modules": "^2.0.0", + "globby": "^11.0.4", + "gzip-size": "^6.0.0", + "immer": "^9.0.7", + "is-root": "^2.1.0", + "loader-utils": "^3.2.0", + "open": "^8.4.0", + "pkg-up": "^3.1.0", + "prompts": "^2.4.2", + "react-error-overlay": "^6.0.11", + "recursive-readdir": "^2.2.2", + "shell-quote": "^1.7.3", + "strip-ansi": "^6.0.1", + "text-table": "^0.2.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/react-dev-utils/node_modules/find-up": { + "version": "5.0.0", + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/react-dev-utils/node_modules/loader-utils": { + "version": "3.2.1", + "license": "MIT", + "engines": { + "node": ">= 12.13.0" + } + }, + "node_modules/react-dev-utils/node_modules/locate-path": { + "version": "6.0.0", + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/react-dev-utils/node_modules/p-limit": { + "version": "3.1.0", + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/react-dev-utils/node_modules/p-locate": { + "version": "5.0.0", + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/react-dev-utils/node_modules/path-exists": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/react-dev-utils/node_modules/yocto-queue": { + "version": "0.1.0", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/react-dom": { + "version": "18.3.1", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/react-error-overlay": { + "version": "6.0.11", + "license": "MIT" + }, + "node_modules/react-fast-compare": { + "version": "3.2.2", + "license": "MIT" + }, + "node_modules/react-helmet-async": { + "version": "1.3.0", + "license": "Apache-2.0", + "dependencies": { + "@babel/runtime": "^7.12.5", + "invariant": "^2.2.4", + "prop-types": "^15.7.2", + "react-fast-compare": "^3.2.0", + "shallowequal": "^1.1.0" + }, + "peerDependencies": { + "react": "^16.6.0 || ^17.0.0 || ^18.0.0", + "react-dom": "^16.6.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/react-icons": { + "version": "5.3.0", + "license": "MIT", + "peerDependencies": { + "react": "*" + } + }, + "node_modules/react-is": { + "version": "16.13.1", + "license": "MIT" + }, + "node_modules/react-json-view-lite": { + "version": "1.4.0", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "react": "^16.13.1 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/react-lite-youtube-embed": { + "version": "2.4.0", + "license": "MIT", + "peerDependencies": { + "react": ">=18.2.0", + "react-dom": ">=18.2.0" + } + }, + "node_modules/react-live": { + "version": "4.1.6", + "license": "MIT", + "dependencies": { + "prism-react-renderer": "^2.0.6", + "sucrase": "^3.31.0", + "use-editable": "^2.3.3" + }, + "engines": { + "node": ">= 0.12.0", + "npm": ">= 2.0.0" + }, + "peerDependencies": { + "react": ">=18.0.0", + "react-dom": ">=18.0.0" + } + }, + "node_modules/react-loadable": { + "name": "@docusaurus/react-loadable", + "version": "6.0.0", + "license": "MIT", + "dependencies": { + "@types/react": "*" + }, + "peerDependencies": { + "react": "*" + } + }, + "node_modules/react-loadable-ssr-addon-v5-slorber": { + "version": "1.0.1", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.10.3" + }, + "engines": { + "node": ">=10.13.0" + }, + "peerDependencies": { + "react-loadable": "*", + "webpack": ">=4.41.1 || 5.x" + } + }, + "node_modules/react-phone-input-2": { + "version": "2.15.1", + "license": "MIT", + "dependencies": { + "classnames": "^2.2.6", + "lodash.debounce": "^4.0.8", + "lodash.memoize": "^4.1.2", + "lodash.reduce": "^4.6.0", + "lodash.startswith": "^4.2.1", + "prop-types": "^15.7.2" + }, + "peerDependencies": { + "react": "^16.12.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^20.0.0 || ^21.0.0", + "react-dom": "^16.12.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^20.0.0 || ^21.0.0" + } + }, + "node_modules/react-popper": { + "version": "2.3.0", + "license": "MIT", + "dependencies": { + "react-fast-compare": "^3.0.1", + "warning": "^4.0.2" + }, + "peerDependencies": { + "@popperjs/core": "^2.0.0", + "react": "^16.8.0 || ^17 || ^18", + "react-dom": "^16.8.0 || ^17 || ^18" + } + }, + "node_modules/react-redux": { + "version": "9.1.2", + "license": "MIT", + "dependencies": { + "@types/use-sync-external-store": "^0.0.3", + "use-sync-external-store": "^1.0.0" + }, + "peerDependencies": { + "@types/react": "^18.2.25", + "react": "^18.0", + "redux": "^5.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "redux": { + "optional": true + } + } + }, + "node_modules/react-router": { + "version": "5.3.4", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.13", + "history": "^4.9.0", + "hoist-non-react-statics": "^3.1.0", + "loose-envify": "^1.3.1", + "path-to-regexp": "^1.7.0", + "prop-types": "^15.6.2", + "react-is": "^16.6.0", + "tiny-invariant": "^1.0.2", + "tiny-warning": "^1.0.0" + }, + "peerDependencies": { + "react": ">=15" + } + }, + "node_modules/react-router-config": { + "version": "5.1.1", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.1.2" + }, + "peerDependencies": { + "react": ">=15", + "react-router": ">=5" + } + }, + "node_modules/react-router-dom": { + "version": "5.3.4", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.13", + "history": "^4.9.0", + "loose-envify": "^1.3.1", + "prop-types": "^15.6.2", + "react-router": "5.3.4", + "tiny-invariant": "^1.0.2", + "tiny-warning": "^1.0.0" + }, + "peerDependencies": { + "react": ">=15" + } + }, + "node_modules/react-simple-code-editor": { + "version": "0.14.1", + "license": "MIT", + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/react-smooth": { + "version": "4.0.1", + "license": "MIT", + "dependencies": { + "fast-equals": "^5.0.1", + "prop-types": "^15.8.1", + "react-transition-group": "^4.4.5" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0", + "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/react-transition-group": { + "version": "4.4.5", + "license": "BSD-3-Clause", + "dependencies": { + "@babel/runtime": "^7.5.5", + "dom-helpers": "^5.0.1", + "loose-envify": "^1.4.0", + "prop-types": "^15.6.2" + }, + "peerDependencies": { + "react": ">=16.6.0", + "react-dom": ">=16.6.0" + } + }, + "node_modules/react-waypoint": { + "version": "10.3.0", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5", + "consolidated-events": "^1.1.0 || ^2.0.0", + "prop-types": "^15.0.0", + "react-is": "^17.0.1 || ^18.0.0" + }, + "peerDependencies": { + "react": "^15.3.0 || ^16.0.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/react-waypoint/node_modules/react-is": { + "version": "18.2.0", + "license": "MIT" + }, + "node_modules/react-window": { + "version": "1.8.10", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.0.0", + "memoize-one": ">=3.1.1 <6" + }, + "engines": { + "node": ">8.0.0" + }, + "peerDependencies": { + "react": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0", + "react-dom": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/read-cache": { + "version": "1.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "pify": "^2.3.0" + } + }, + "node_modules/read-cache/node_modules/pify": { + "version": "2.3.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/reading-time": { + "version": "1.5.0", + "license": "MIT" + }, + "node_modules/recharts": { + "version": "2.12.7", + "license": "MIT", + "dependencies": { + "clsx": "^2.0.0", + "eventemitter3": "^4.0.1", + "lodash": "^4.17.21", + "react-is": "^16.10.2", + "react-smooth": "^4.0.0", + "recharts-scale": "^0.4.4", + "tiny-invariant": "^1.3.1", + "victory-vendor": "^36.6.8" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "react": "^16.0.0 || ^17.0.0 || ^18.0.0", + "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/recharts-scale": { + "version": "0.4.5", + "license": "MIT", + "dependencies": { + "decimal.js-light": "^2.4.1" + } + }, + "node_modules/rechoir": { + "version": "0.6.2", + "dependencies": { + "resolve": "^1.1.6" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/recursive-readdir": { + "version": "2.2.3", + "license": "MIT", + "dependencies": { + "minimatch": "^3.0.5" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/redux": { + "version": "5.0.1", + "license": "MIT" + }, + "node_modules/regenerate": { + "version": "1.4.2", + "license": "MIT" + }, + "node_modules/regenerate-unicode-properties": { + "version": "10.1.1", + "license": "MIT", + "dependencies": { + "regenerate": "^1.4.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.14.1", + "license": "MIT" + }, + "node_modules/regenerator-transform": { + "version": "0.15.2", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.8.4" + } + }, + "node_modules/regex-not": { + "version": "1.0.2", + "license": "MIT", + "peer": true, + "dependencies": { + "extend-shallow": "^3.0.2", + "safe-regex": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/regex-not/node_modules/extend-shallow": { + "version": "3.0.2", + "license": "MIT", + "peer": true, + "dependencies": { + "assign-symbols": "^1.0.0", + "is-extendable": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/regex-not/node_modules/is-extendable": { + "version": "1.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "is-plain-object": "^2.0.4" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/regex-not/node_modules/is-plain-object": { + "version": "2.0.4", + "license": "MIT", + "peer": true, + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.1", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "set-function-name": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/regexpu-core": { + "version": "5.3.2", + "license": "MIT", + "dependencies": { + "@babel/regjsgen": "^0.8.0", + "regenerate": "^1.4.2", + "regenerate-unicode-properties": "^10.1.0", + "regjsparser": "^0.9.1", + "unicode-match-property-ecmascript": "^2.0.0", + "unicode-match-property-value-ecmascript": "^2.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/registry-auth-token": { + "version": "5.0.2", + "license": "MIT", + "dependencies": { + "@pnpm/npm-conf": "^2.1.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/registry-url": { + "version": "6.0.1", + "license": "MIT", + "dependencies": { + "rc": "1.2.8" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/regjsgen": { + "version": "0.5.2", + "license": "MIT" + }, + "node_modules/regjsparser": { + "version": "0.9.1", + "license": "BSD-2-Clause", + "dependencies": { + "jsesc": "~0.5.0" + }, + "bin": { + "regjsparser": "bin/parser" + } + }, + "node_modules/regjsparser/node_modules/jsesc": { + "version": "0.5.0", + "bin": { + "jsesc": "bin/jsesc" + } + }, + "node_modules/rehype-katex": { + "version": "7.0.1", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/katex": "^0.16.0", + "hast-util-from-html-isomorphic": "^2.0.0", + "hast-util-to-text": "^4.0.0", + "katex": "^0.16.0", + "unist-util-visit-parents": "^6.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/rehype-raw": { + "version": "7.0.0", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-raw": "^9.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/relateurl": { + "version": "0.2.7", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/remark-directive": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-directive": "^3.0.0", + "micromark-extension-directive": "^3.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-emoji": { + "version": "4.0.1", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.2", + "emoticon": "^4.0.1", + "mdast-util-find-and-replace": "^3.0.1", + "node-emoji": "^2.1.0", + "unified": "^11.0.4" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/remark-frontmatter": { + "version": "5.0.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-frontmatter": "^2.0.0", + "micromark-extension-frontmatter": "^2.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-gfm": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-gfm": "^3.0.0", + "micromark-extension-gfm": "^3.0.0", + "remark-parse": "^11.0.0", + "remark-stringify": "^11.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-math": { + "version": "6.0.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-math": "^3.0.0", + "micromark-extension-math": "^3.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-mdx": { + "version": "3.0.1", + "license": "MIT", + "dependencies": { + "mdast-util-mdx": "^3.0.0", + "micromark-extension-mdxjs": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-parse": { + "version": "11.0.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-from-markdown": "^2.0.0", + "micromark-util-types": "^2.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-rehype": { + "version": "11.1.0", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "mdast-util-to-hast": "^13.0.0", + "unified": "^11.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remark-stringify": { + "version": "11.0.0", + "license": "MIT", + "dependencies": { + "@types/mdast": "^4.0.0", + "mdast-util-to-markdown": "^2.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/remove-trailing-separator": { + "version": "1.1.0", + "license": "ISC", + "optional": true, + "peer": true + }, + "node_modules/renderkid": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "css-select": "^4.1.3", + "dom-converter": "^0.2.0", + "htmlparser2": "^6.1.0", + "lodash": "^4.17.21", + "strip-ansi": "^6.0.1" + } + }, + "node_modules/renderkid/node_modules/css-select": { + "version": "4.3.0", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-what": "^6.0.1", + "domhandler": "^4.3.1", + "domutils": "^2.8.0", + "nth-check": "^2.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/renderkid/node_modules/dom-serializer": { + "version": "1.4.1", + "license": "MIT", + "dependencies": { + "domelementtype": "^2.0.1", + "domhandler": "^4.2.0", + "entities": "^2.0.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/renderkid/node_modules/domhandler": { + "version": "4.3.1", + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.2.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/renderkid/node_modules/domutils": { + "version": "2.8.0", + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^1.0.1", + "domelementtype": "^2.2.0", + "domhandler": "^4.2.0" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/renderkid/node_modules/entities": { + "version": "2.2.0", + "license": "BSD-2-Clause", + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/renderkid/node_modules/htmlparser2": { + "version": "6.1.0", + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.0.1", + "domhandler": "^4.0.0", + "domutils": "^2.5.2", + "entities": "^2.0.0" + } + }, + "node_modules/repeat-element": { + "version": "1.1.4", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/repeat-string": { + "version": "1.6.1", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-like": { + "version": "0.1.2", + "engines": { + "node": "*" + } + }, + "node_modules/requires-port": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/resolve": { + "version": "1.22.8", + "license": "MIT", + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-alpn": { + "version": "1.2.1", + "license": "MIT" + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/resolve-pathname": { + "version": "3.0.0", + "license": "MIT" + }, + "node_modules/resolve-url": { + "version": "0.2.1", + "license": "MIT", + "peer": true + }, + "node_modules/responselike": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "lowercase-keys": "^3.0.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ret": { + "version": "0.1.15", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.12" + } + }, + "node_modules/retry": { + "version": "0.13.1", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/reusify": { + "version": "1.0.4", + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rimraf": { + "version": "3.0.2", + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ripemd160": { + "version": "2.0.2", + "license": "MIT", + "peer": true, + "dependencies": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1" + } + }, + "node_modules/robots-parser": { + "version": "3.0.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/robust-predicates": { + "version": "3.0.2", + "license": "Unlicense" + }, + "node_modules/rollup": { + "version": "2.79.2", + "license": "MIT", + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=10.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/rtl-css-js": { + "version": "1.16.1", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.1.2" + } + }, + "node_modules/rtl-detect": { + "version": "1.1.2", + "license": "BSD-3-Clause" + }, + "node_modules/rtlcss": { + "version": "4.1.1", + "license": "MIT", + "dependencies": { + "escalade": "^3.1.1", + "picocolors": "^1.0.0", + "postcss": "^8.4.21", + "strip-json-comments": "^3.1.1" + }, + "bin": { + "rtlcss": "bin/rtlcss.js" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/run-queue": { + "version": "1.0.3", + "license": "ISC", + "peer": true, + "dependencies": { + "aproba": "^1.1.1" + } + }, + "node_modules/rw": { + "version": "1.3.3", + "license": "BSD-3-Clause" + }, + "node_modules/sade": { + "version": "1.8.1", + "license": "MIT", + "dependencies": { + "mri": "^1.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/safe-array-concat": { + "version": "1.1.0", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.5", + "get-intrinsic": "^1.2.2", + "has-symbols": "^1.0.3", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-array-concat/node_modules/isarray": { + "version": "2.0.5", + "license": "MIT" + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safe-regex": { + "version": "1.1.0", + "license": "MIT", + "peer": true, + "dependencies": { + "ret": "~0.1.10" + } + }, + "node_modules/safe-regex-test": { + "version": "1.0.3", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.6", + "es-errors": "^1.3.0", + "is-regex": "^1.1.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "license": "MIT" + }, + "node_modules/sax": { + "version": "1.3.0", + "license": "ISC" + }, + "node_modules/scheduler": { + "version": "0.23.2", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/schema-utils": { + "version": "4.2.0", + "license": "MIT", + "dependencies": { + "@types/json-schema": "^7.0.9", + "ajv": "^8.9.0", + "ajv-formats": "^2.1.1", + "ajv-keywords": "^5.1.0" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/search-insights": { + "version": "2.14.0", + "license": "MIT", + "peer": true + }, + "node_modules/section-matter": { + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "extend-shallow": "^2.0.1", + "kind-of": "^6.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/select-hose": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/selfsigned": { + "version": "2.4.1", + "license": "MIT", + "dependencies": { + "@types/node-forge": "^1.3.0", + "node-forge": "^1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/semver": { + "version": "7.6.3", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/semver-diff": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/send": { + "version": "0.19.0", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/debug": { + "version": "2.6.9", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/send/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "license": "MIT" + }, + "node_modules/send/node_modules/range-parser": { + "version": "1.2.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/serialize-javascript": { + "version": "6.0.2", + "license": "BSD-3-Clause", + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/serve-handler": { + "version": "6.1.5", + "license": "MIT", + "dependencies": { + "bytes": "3.0.0", + "content-disposition": "0.5.2", + "fast-url-parser": "1.1.3", + "mime-types": "2.1.18", + "minimatch": "3.1.2", + "path-is-inside": "1.0.2", + "path-to-regexp": "2.2.1", + "range-parser": "1.2.0" + } + }, + "node_modules/serve-handler/node_modules/path-to-regexp": { + "version": "2.2.1", + "license": "MIT" + }, + "node_modules/serve-index": { + "version": "1.9.1", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.4", + "batch": "0.6.1", + "debug": "2.6.9", + "escape-html": "~1.0.3", + "http-errors": "~1.6.2", + "mime-types": "~2.1.17", + "parseurl": "~1.3.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/serve-index/node_modules/debug": { + "version": "2.6.9", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/serve-index/node_modules/depd": { + "version": "1.1.2", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/serve-index/node_modules/http-errors": { + "version": "1.6.3", + "license": "MIT", + "dependencies": { + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.0", + "statuses": ">= 1.4.0 < 2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/serve-index/node_modules/inherits": { + "version": "2.0.3", + "license": "ISC" + }, + "node_modules/serve-index/node_modules/ms": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/serve-index/node_modules/setprototypeof": { + "version": "1.1.0", + "license": "ISC" + }, + "node_modules/serve-index/node_modules/statuses": { + "version": "1.5.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/serve-static": { + "version": "1.16.2", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/server-only": { + "version": "0.0.1", + "license": "MIT" + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-function-name": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-value": { + "version": "2.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.3", + "split-string": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/set-value/node_modules/is-plain-object": { + "version": "2.0.4", + "license": "MIT", + "peer": true, + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/setimmediate": { + "version": "1.0.5", + "license": "MIT", + "peer": true + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "license": "ISC" + }, + "node_modules/sha.js": { + "version": "2.4.11", + "license": "(MIT AND BSD-3-Clause)", + "peer": true, + "dependencies": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + }, + "bin": { + "sha.js": "bin.js" + } + }, + "node_modules/shallow-clone": { + "version": "3.0.1", + "license": "MIT", + "dependencies": { + "kind-of": "^6.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shallowequal": { + "version": "1.1.0", + "license": "MIT" + }, + "node_modules/sharp": { + "version": "0.32.6", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "color": "^4.2.3", + "detect-libc": "^2.0.2", + "node-addon-api": "^6.1.0", + "prebuild-install": "^7.1.1", + "semver": "^7.5.4", + "simple-get": "^4.0.1", + "tar-fs": "^3.0.4", + "tunnel-agent": "^0.6.0" + }, + "engines": { + "node": ">=14.15.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/shell-quote": { + "version": "1.8.1", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/shelljs": { + "version": "0.8.5", + "license": "BSD-3-Clause", + "dependencies": { + "glob": "^7.0.0", + "interpret": "^1.0.0", + "rechoir": "^0.6.2" + }, + "bin": { + "shjs": "bin/shjs" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/side-channel": { + "version": "1.0.6", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "license": "ISC" + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/simple-swizzle": { + "version": "0.2.2", + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.3.1" + } + }, + "node_modules/simple-swizzle/node_modules/is-arrayish": { + "version": "0.3.2", + "license": "MIT" + }, + "node_modules/sirv": { + "version": "2.0.4", + "license": "MIT", + "dependencies": { + "@polka/url": "^1.0.0-next.24", + "mrmime": "^2.0.0", + "totalist": "^3.0.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/sisteransi": { + "version": "1.0.5", + "license": "MIT" + }, + "node_modules/sitemap": { + "version": "7.1.1", + "license": "MIT", + "dependencies": { + "@types/node": "^17.0.5", + "@types/sax": "^1.2.1", + "arg": "^5.0.0", + "sax": "^1.2.4" + }, + "bin": { + "sitemap": "dist/cli.js" + }, + "engines": { + "node": ">=12.0.0", + "npm": ">=5.6.0" + } + }, + "node_modules/sitemap/node_modules/@types/node": { + "version": "17.0.45", + "license": "MIT" + }, + "node_modules/skin-tone": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "unicode-emoji-modifier-base": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/slash": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/smob": { + "version": "1.5.0", + "license": "MIT" + }, + "node_modules/snake-case": { + "version": "3.0.4", + "license": "MIT", + "dependencies": { + "dot-case": "^3.0.4", + "tslib": "^2.0.3" + } + }, + "node_modules/snapdragon": { + "version": "0.8.2", + "license": "MIT", + "peer": true, + "dependencies": { + "base": "^0.11.1", + "debug": "^2.2.0", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "map-cache": "^0.2.2", + "source-map": "^0.5.6", + "source-map-resolve": "^0.5.0", + "use": "^3.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/snapdragon-node": { + "version": "2.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "define-property": "^1.0.0", + "isobject": "^3.0.0", + "snapdragon-util": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/snapdragon-node/node_modules/define-property": { + "version": "1.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "is-descriptor": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/snapdragon-util": { + "version": "3.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "kind-of": "^3.2.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/snapdragon-util/node_modules/kind-of": { + "version": "3.2.2", + "license": "MIT", + "peer": true, + "dependencies": { + "is-buffer": "^1.1.5" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/snapdragon/node_modules/debug": { + "version": "2.6.9", + "license": "MIT", + "peer": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/snapdragon/node_modules/define-property": { + "version": "0.2.5", + "license": "MIT", + "peer": true, + "dependencies": { + "is-descriptor": "^0.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/snapdragon/node_modules/is-descriptor": { + "version": "0.1.7", + "license": "MIT", + "peer": true, + "dependencies": { + "is-accessor-descriptor": "^1.0.1", + "is-data-descriptor": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/snapdragon/node_modules/ms": { + "version": "2.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/snapdragon/node_modules/source-map": { + "version": "0.5.7", + "license": "BSD-3-Clause", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/sockjs": { + "version": "0.3.24", + "license": "MIT", + "dependencies": { + "faye-websocket": "^0.11.3", + "uuid": "^8.3.2", + "websocket-driver": "^0.7.4" + } + }, + "node_modules/socks": { + "version": "2.8.3", + "dev": true, + "license": "MIT", + "dependencies": { + "ip-address": "^9.0.5", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks-proxy-agent": { + "version": "8.0.4", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.1", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/socks-proxy-agent/node_modules/agent-base": { + "version": "7.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/sort-css-media-queries": { + "version": "2.2.0", + "license": "MIT", + "engines": { + "node": ">= 6.3.0" + } + }, + "node_modules/source-list-map": { + "version": "2.0.1", + "license": "MIT", + "peer": true + }, + "node_modules/source-map": { + "version": "0.7.4", + "license": "BSD-3-Clause", + "engines": { + "node": ">= 8" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-resolve": { + "version": "0.5.3", + "license": "MIT", + "peer": true, + "dependencies": { + "atob": "^2.1.2", + "decode-uri-component": "^0.2.0", + "resolve-url": "^0.2.1", + "source-map-url": "^0.4.0", + "urix": "^0.1.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/source-map-support/node_modules/source-map": { + "version": "0.6.1", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-url": { + "version": "0.4.1", + "license": "MIT", + "peer": true + }, + "node_modules/sourcemap-codec": { + "version": "1.4.8", + "license": "MIT" + }, + "node_modules/space-separated-tokens": { + "version": "2.0.2", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/spdy": { + "version": "4.0.2", + "license": "MIT", + "dependencies": { + "debug": "^4.1.0", + "handle-thing": "^2.0.0", + "http-deceiver": "^1.2.7", + "select-hose": "^2.0.0", + "spdy-transport": "^3.0.0" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/spdy-transport": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "debug": "^4.1.0", + "detect-node": "^2.0.4", + "hpack.js": "^2.1.6", + "obuf": "^1.1.2", + "readable-stream": "^3.0.6", + "wbuf": "^1.7.3" + } + }, + "node_modules/speedline-core": { + "version": "1.4.3", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "image-ssim": "^0.2.0", + "jpeg-js": "^0.4.1" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/split-string": { + "version": "3.1.0", + "license": "MIT", + "peer": true, + "dependencies": { + "extend-shallow": "^3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/split-string/node_modules/extend-shallow": { + "version": "3.0.2", + "license": "MIT", + "peer": true, + "dependencies": { + "assign-symbols": "^1.0.0", + "is-extendable": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/split-string/node_modules/is-extendable": { + "version": "1.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "is-plain-object": "^2.0.4" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/split-string/node_modules/is-plain-object": { + "version": "2.0.4", + "license": "MIT", + "peer": true, + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "license": "BSD-3-Clause" + }, + "node_modules/srcset": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ssri": { + "version": "6.0.2", + "license": "ISC", + "peer": true, + "dependencies": { + "figgy-pudding": "^3.5.1" + } + }, + "node_modules/static-extend": { + "version": "0.1.2", + "license": "MIT", + "peer": true, + "dependencies": { + "define-property": "^0.2.5", + "object-copy": "^0.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/static-extend/node_modules/define-property": { + "version": "0.2.5", + "license": "MIT", + "peer": true, + "dependencies": { + "is-descriptor": "^0.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/static-extend/node_modules/is-descriptor": { + "version": "0.1.7", + "license": "MIT", + "peer": true, + "dependencies": { + "is-accessor-descriptor": "^1.0.1", + "is-data-descriptor": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/std-env": { + "version": "3.7.0", + "license": "MIT" + }, + "node_modules/stream-browserify": { + "version": "2.0.2", + "license": "MIT", + "peer": true, + "dependencies": { + "inherits": "~2.0.1", + "readable-stream": "^2.0.2" + } + }, + "node_modules/stream-browserify/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/stream-browserify/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "peer": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/stream-browserify/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "peer": true + }, + "node_modules/stream-browserify/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/stream-each": { + "version": "1.2.3", + "license": "MIT", + "peer": true, + "dependencies": { + "end-of-stream": "^1.1.0", + "stream-shift": "^1.0.0" + } + }, + "node_modules/stream-http": { + "version": "2.8.3", + "license": "MIT", + "peer": true, + "dependencies": { + "builtin-status-codes": "^3.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.3.6", + "to-arraybuffer": "^1.0.0", + "xtend": "^4.0.0" + } + }, + "node_modules/stream-http/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/stream-http/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "peer": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/stream-http/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "peer": true + }, + "node_modules/stream-http/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/stream-shift": { + "version": "1.0.3", + "license": "MIT", + "peer": true + }, + "node_modules/streamx": { + "version": "2.18.0", + "license": "MIT", + "dependencies": { + "fast-fifo": "^1.3.2", + "queue-tick": "^1.0.1", + "text-decoder": "^1.1.0" + }, + "optionalDependencies": { + "bare-events": "^2.2.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "5.1.2", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "license": "MIT" + }, + "node_modules/string-width/node_modules/ansi-regex": { + "version": "6.0.1", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/string-width/node_modules/strip-ansi": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/string.prototype.matchall": { + "version": "4.0.10", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1", + "get-intrinsic": "^1.2.1", + "has-symbols": "^1.0.3", + "internal-slot": "^1.0.5", + "regexp.prototype.flags": "^1.5.0", + "set-function-name": "^2.0.0", + "side-channel": "^1.0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trim": { + "version": "1.2.8", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimend": { + "version": "1.0.7", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimstart": { + "version": "1.0.7", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/stringify-entities": { + "version": "4.0.3", + "license": "MIT", + "dependencies": { + "character-entities-html4": "^2.0.0", + "character-entities-legacy": "^3.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/stringify-object": { + "version": "3.3.0", + "license": "BSD-2-Clause", + "dependencies": { + "get-own-enumerable-property-symbols": "^3.0.0", + "is-obj": "^1.0.1", + "is-regexp": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-bom-string": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/strip-comments": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-outer": { + "version": "1.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^1.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/strip-outer/node_modules/escape-string-regexp": { + "version": "1.0.5", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/style-to-object": { + "version": "0.4.4", + "license": "MIT", + "dependencies": { + "inline-style-parser": "0.1.1" + } + }, + "node_modules/styled-components": { + "version": "6.1.13", + "license": "MIT", + "dependencies": { + "@emotion/is-prop-valid": "1.2.2", + "@emotion/unitless": "0.8.1", + "@types/stylis": "4.2.5", + "css-to-react-native": "3.2.0", + "csstype": "3.1.3", + "postcss": "8.4.38", + "shallowequal": "1.1.0", + "stylis": "4.3.2", + "tslib": "2.6.2" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/styled-components" + }, + "peerDependencies": { + "react": ">= 16.8.0", + "react-dom": ">= 16.8.0" + } + }, + "node_modules/styled-components/node_modules/postcss": { + "version": "8.4.38", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.7", + "picocolors": "^1.0.0", + "source-map-js": "^1.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/stylehacks": { + "version": "6.1.1", + "license": "MIT", + "dependencies": { + "browserslist": "^4.23.0", + "postcss-selector-parser": "^6.0.16" + }, + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/stylis": { + "version": "4.3.2", + "license": "MIT" + }, + "node_modules/sucrase": { + "version": "3.35.0", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "glob": "^10.3.10", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/sucrase/node_modules/brace-expansion": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/sucrase/node_modules/commander": { + "version": "4.1.1", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/sucrase/node_modules/glob": { + "version": "10.3.10", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^2.3.5", + "minimatch": "^9.0.1", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0", + "path-scurry": "^1.10.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/sucrase/node_modules/minimatch": { + "version": "9.0.3", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/svg-parser": { + "version": "2.0.4", + "license": "MIT" + }, + "node_modules/svgo": { + "version": "3.3.0", + "license": "MIT", + "dependencies": { + "@trysound/sax": "0.2.0", + "commander": "^7.2.0", + "css-select": "^5.1.0", + "css-tree": "^2.3.1", + "css-what": "^6.1.0", + "csso": "^5.0.5", + "picocolors": "^1.0.0" + }, + "bin": { + "svgo": "bin/svgo.js" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/svgo" + } + }, + "node_modules/svgo/node_modules/commander": { + "version": "7.2.0", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/swiper": { + "version": "11.1.14", + "funding": [ + { + "type": "patreon", + "url": "https://www.patreon.com/swiperjs" + }, + { + "type": "open_collective", + "url": "http://opencollective.com/swiper" + } + ], + "license": "MIT", + "engines": { + "node": ">= 4.7.0" + } + }, + "node_modules/tailwindcss": { + "version": "3.4.13", + "dev": true, + "license": "MIT", + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "arg": "^5.0.2", + "chokidar": "^3.5.3", + "didyoumean": "^1.2.2", + "dlv": "^1.1.3", + "fast-glob": "^3.3.0", + "glob-parent": "^6.0.2", + "is-glob": "^4.0.3", + "jiti": "^1.21.0", + "lilconfig": "^2.1.0", + "micromatch": "^4.0.5", + "normalize-path": "^3.0.0", + "object-hash": "^3.0.0", + "picocolors": "^1.0.0", + "postcss": "^8.4.23", + "postcss-import": "^15.1.0", + "postcss-js": "^4.0.1", + "postcss-load-config": "^4.0.1", + "postcss-nested": "^6.0.1", + "postcss-selector-parser": "^6.0.11", + "resolve": "^1.22.2", + "sucrase": "^3.32.0" + }, + "bin": { + "tailwind": "lib/cli.js", + "tailwindcss": "lib/cli.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tailwindcss/node_modules/glob-parent": { + "version": "6.0.2", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/tailwindcss/node_modules/lilconfig": { + "version": "2.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/tapable": { + "version": "2.2.1", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/tar-fs": { + "version": "3.0.6", + "license": "MIT", + "dependencies": { + "pump": "^3.0.0", + "tar-stream": "^3.1.5" + }, + "optionalDependencies": { + "bare-fs": "^2.1.1", + "bare-path": "^2.1.0" + } + }, + "node_modules/tar-stream": { + "version": "3.1.7", + "license": "MIT", + "dependencies": { + "b4a": "^1.6.4", + "fast-fifo": "^1.2.0", + "streamx": "^2.15.0" + } + }, + "node_modules/temp-dir": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/tempy": { + "version": "0.6.0", + "license": "MIT", + "dependencies": { + "is-stream": "^2.0.0", + "temp-dir": "^2.0.0", + "type-fest": "^0.16.0", + "unique-string": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/tempy/node_modules/crypto-random-string": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/tempy/node_modules/type-fest": { + "version": "0.16.0", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/tempy/node_modules/unique-string": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "crypto-random-string": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/terser": { + "version": "5.27.0", + "license": "BSD-2-Clause", + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.8.2", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser-webpack-plugin": { + "version": "5.3.10", + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.20", + "jest-worker": "^27.4.5", + "schema-utils": "^3.1.1", + "serialize-javascript": "^6.0.1", + "terser": "^5.26.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "uglify-js": { + "optional": true + } + } + }, + "node_modules/terser-webpack-plugin/node_modules/ajv": { + "version": "6.12.6", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/terser-webpack-plugin/node_modules/ajv-keywords": { + "version": "3.5.2", + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/terser-webpack-plugin/node_modules/jest-worker": { + "version": "27.5.1", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/terser-webpack-plugin/node_modules/json-schema-traverse": { + "version": "0.4.1", + "license": "MIT" + }, + "node_modules/terser-webpack-plugin/node_modules/schema-utils": { + "version": "3.3.0", + "license": "MIT", + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/terser-webpack-plugin/node_modules/supports-color": { + "version": "8.1.1", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/terser/node_modules/commander": { + "version": "2.20.3", + "license": "MIT" + }, + "node_modules/text-decoder": { + "version": "1.1.1", + "license": "Apache-2.0", + "dependencies": { + "b4a": "^1.6.4" + } + }, + "node_modules/text-table": { + "version": "0.2.0", + "license": "MIT" + }, + "node_modules/thenify": { + "version": "3.3.1", + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "license": "MIT", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/third-party-web": { + "version": "0.24.5", + "dev": true, + "license": "MIT" + }, + "node_modules/three": { + "version": "0.169.0", + "license": "MIT" + }, + "node_modules/through": { + "version": "2.3.8", + "dev": true, + "license": "MIT" + }, + "node_modules/through2": { + "version": "2.0.5", + "license": "MIT", + "peer": true, + "dependencies": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "node_modules/through2/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/through2/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "peer": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/through2/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "peer": true + }, + "node_modules/through2/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "peer": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/thunky": { + "version": "1.1.0", + "license": "MIT" + }, + "node_modules/timers-browserify": { + "version": "2.0.12", + "license": "MIT", + "peer": true, + "dependencies": { + "setimmediate": "^1.0.4" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/tiny-invariant": { + "version": "1.3.1", + "license": "MIT" + }, + "node_modules/tiny-warning": { + "version": "1.0.3", + "license": "MIT" + }, + "node_modules/tldts-core": { + "version": "6.1.31", + "dev": true, + "license": "MIT" + }, + "node_modules/tldts-icann": { + "version": "6.1.31", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.31" + } + }, + "node_modules/to-arraybuffer": { + "version": "1.0.1", + "license": "MIT", + "peer": true + }, + "node_modules/to-fast-properties": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/to-object-path": { + "version": "0.3.0", + "license": "MIT", + "peer": true, + "dependencies": { + "kind-of": "^3.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/to-object-path/node_modules/kind-of": { + "version": "3.2.2", + "license": "MIT", + "peer": true, + "dependencies": { + "is-buffer": "^1.1.5" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/to-regex": { + "version": "3.0.2", + "license": "MIT", + "peer": true, + "dependencies": { + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "regex-not": "^1.0.2", + "safe-regex": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/to-regex/node_modules/extend-shallow": { + "version": "3.0.2", + "license": "MIT", + "peer": true, + "dependencies": { + "assign-symbols": "^1.0.0", + "is-extendable": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/to-regex/node_modules/is-extendable": { + "version": "1.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "is-plain-object": "^2.0.4" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/to-regex/node_modules/is-plain-object": { + "version": "2.0.4", + "license": "MIT", + "peer": true, + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/totalist": { + "version": "3.0.1", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/tr46": { + "version": "1.0.1", + "license": "MIT", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/tr46/node_modules/punycode": { + "version": "2.3.1", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/trim-lines": { + "version": "3.0.1", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/trim-repeated": { + "version": "1.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^1.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/trim-repeated/node_modules/escape-string-regexp": { + "version": "1.0.5", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/trough": { + "version": "2.1.0", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/ts-dedent": { + "version": "2.2.0", + "license": "MIT", + "engines": { + "node": ">=6.10" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "license": "Apache-2.0" + }, + "node_modules/tslib": { + "version": "2.6.2", + "license": "0BSD" + }, + "node_modules/tty-browserify": { + "version": "0.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/type-fest": { + "version": "2.19.0", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/type-is/node_modules/mime-db": { + "version": "1.52.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/type-is/node_modules/mime-types": { + "version": "2.1.35", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typed-array-buffer": { + "version": "1.0.1", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.6", + "es-errors": "^1.3.0", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/typed-array-byte-length": { + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "has-proto": "^1.0.1", + "is-typed-array": "^1.1.10" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-byte-offset": { + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.5", + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "has-proto": "^1.0.1", + "is-typed-array": "^1.1.10" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-length": { + "version": "1.0.4", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "for-each": "^0.3.3", + "is-typed-array": "^1.1.9" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-query-selector": { + "version": "2.12.0", + "dev": true, + "license": "MIT" + }, + "node_modules/typedarray": { + "version": "0.0.6", + "license": "MIT", + "peer": true + }, + "node_modules/typedarray-to-buffer": { + "version": "3.1.5", + "license": "MIT", + "dependencies": { + "is-typedarray": "^1.0.0" + } + }, + "node_modules/typescript": { + "version": "5.5.3", + "license": "Apache-2.0", + "peer": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/uid2": { + "version": "0.0.4", + "license": "MIT" + }, + "node_modules/unbox-primitive": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "has-bigints": "^1.0.2", + "has-symbols": "^1.0.3", + "which-boxed-primitive": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/unbzip2-stream": { + "version": "1.4.3", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer": "^5.2.1", + "through": "^2.3.8" + } + }, + "node_modules/undici-types": { + "version": "6.19.6", + "license": "MIT" + }, + "node_modules/unicode-canonical-property-names-ecmascript": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/unicode-emoji-modifier-base": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/unicode-match-property-ecmascript": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "unicode-canonical-property-names-ecmascript": "^2.0.0", + "unicode-property-aliases-ecmascript": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/unicode-match-property-value-ecmascript": { + "version": "2.1.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/unicode-property-aliases-ecmascript": { + "version": "2.1.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/unified": { + "version": "11.0.4", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "bail": "^2.0.0", + "devlop": "^1.0.0", + "extend": "^3.0.0", + "is-plain-obj": "^4.0.0", + "trough": "^2.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/union-value": { + "version": "1.0.1", + "license": "MIT", + "peer": true, + "dependencies": { + "arr-union": "^3.1.0", + "get-value": "^2.0.6", + "is-extendable": "^0.1.1", + "set-value": "^2.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/unique-filename": { + "version": "1.1.1", + "license": "ISC", + "peer": true, + "dependencies": { + "unique-slug": "^2.0.0" + } + }, + "node_modules/unique-slug": { + "version": "2.0.2", + "license": "ISC", + "peer": true, + "dependencies": { + "imurmurhash": "^0.1.4" + } + }, + "node_modules/unique-string": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "crypto-random-string": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/unist-util-find-after": { + "version": "5.0.0", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-is": { + "version": "6.0.0", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-position": { + "version": "5.0.0", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-position-from-estree": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-remove-position": { + "version": "5.0.0", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-visit": "^5.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-stringify-position": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit": { + "version": "5.0.0", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit-parents": { + "version": "6.0.1", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/universalify": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/unset-value": { + "version": "1.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "has-value": "^0.3.1", + "isobject": "^3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/unset-value/node_modules/has-value": { + "version": "0.3.1", + "license": "MIT", + "peer": true, + "dependencies": { + "get-value": "^2.0.3", + "has-values": "^0.1.4", + "isobject": "^2.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/unset-value/node_modules/has-value/node_modules/isobject": { + "version": "2.1.0", + "license": "MIT", + "peer": true, + "dependencies": { + "isarray": "1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/unset-value/node_modules/has-values": { + "version": "0.1.4", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/unset-value/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/upath": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">=4", + "yarn": "*" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.1.0", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.1.2", + "picocolors": "^1.0.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/update-notifier": { + "version": "6.0.2", + "license": "BSD-2-Clause", + "dependencies": { + "boxen": "^7.0.0", + "chalk": "^5.0.1", + "configstore": "^6.0.0", + "has-yarn": "^3.0.0", + "import-lazy": "^4.0.0", + "is-ci": "^3.0.1", + "is-installed-globally": "^0.4.0", + "is-npm": "^6.0.0", + "is-yarn-global": "^0.4.0", + "latest-version": "^7.0.0", + "pupa": "^3.1.0", + "semver": "^7.3.7", + "semver-diff": "^4.0.0", + "xdg-basedir": "^5.1.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/yeoman/update-notifier?sponsor=1" + } + }, + "node_modules/update-notifier/node_modules/boxen": { + "version": "7.1.1", + "license": "MIT", + "dependencies": { + "ansi-align": "^3.0.1", + "camelcase": "^7.0.1", + "chalk": "^5.2.0", + "cli-boxes": "^3.0.0", + "string-width": "^5.1.2", + "type-fest": "^2.13.0", + "widest-line": "^4.0.1", + "wrap-ansi": "^8.1.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/update-notifier/node_modules/camelcase": { + "version": "7.0.1", + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/update-notifier/node_modules/chalk": { + "version": "5.3.0", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/uri-js/node_modules/punycode": { + "version": "2.3.1", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/urix": { + "version": "0.1.0", + "license": "MIT", + "peer": true + }, + "node_modules/url": { + "version": "0.11.3", + "license": "MIT", + "peer": true, + "dependencies": { + "punycode": "^1.4.1", + "qs": "^6.11.2" + } + }, + "node_modules/url-loader": { + "version": "4.1.1", + "license": "MIT", + "dependencies": { + "loader-utils": "^2.0.0", + "mime-types": "^2.1.27", + "schema-utils": "^3.0.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "file-loader": "*", + "webpack": "^4.0.0 || ^5.0.0" + }, + "peerDependenciesMeta": { + "file-loader": { + "optional": true + } + } + }, + "node_modules/url-loader/node_modules/ajv": { + "version": "6.12.6", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/url-loader/node_modules/ajv-keywords": { + "version": "3.5.2", + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/url-loader/node_modules/json-schema-traverse": { + "version": "0.4.1", + "license": "MIT" + }, + "node_modules/url-loader/node_modules/mime-db": { + "version": "1.52.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/url-loader/node_modules/mime-types": { + "version": "2.1.35", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/url-loader/node_modules/schema-utils": { + "version": "3.3.0", + "license": "MIT", + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/urlpattern-polyfill": { + "version": "10.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/use": { + "version": "3.1.1", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/use-editable": { + "version": "2.3.3", + "license": "MIT", + "peerDependencies": { + "react": ">= 16.8.0" + } + }, + "node_modules/use-sync-external-store": { + "version": "1.2.0", + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/util": { + "version": "0.11.1", + "license": "MIT", + "peer": true, + "dependencies": { + "inherits": "2.0.3" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/util/node_modules/inherits": { + "version": "2.0.3", + "license": "ISC", + "peer": true + }, + "node_modules/utila": { + "version": "0.4.0", + "license": "MIT" + }, + "node_modules/utility-types": { + "version": "3.11.0", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "8.3.2", + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/uvu": { + "version": "0.5.6", + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0", + "diff": "^5.0.0", + "kleur": "^4.0.3", + "sade": "^1.7.3" + }, + "bin": { + "uvu": "bin.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/uvu/node_modules/kleur": { + "version": "4.1.5", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/value-equal": { + "version": "1.0.1", + "license": "MIT" + }, + "node_modules/vanilla-tilt": { + "version": "1.8.1", + "license": "MIT" + }, + "node_modules/vary": { + "version": "1.1.2", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vfile": { + "version": "6.0.1", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-stringify-position": "^4.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-location": { + "version": "5.0.2", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-message": { + "version": "4.0.2", + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/victory-vendor": { + "version": "36.9.2", + "license": "MIT AND ISC", + "dependencies": { + "@types/d3-array": "^3.0.3", + "@types/d3-ease": "^3.0.0", + "@types/d3-interpolate": "^3.0.1", + "@types/d3-scale": "^4.0.2", + "@types/d3-shape": "^3.1.0", + "@types/d3-time": "^3.0.0", + "@types/d3-timer": "^3.0.0", + "d3-array": "^3.1.6", + "d3-ease": "^3.0.1", + "d3-interpolate": "^3.0.1", + "d3-scale": "^4.0.2", + "d3-shape": "^3.1.0", + "d3-time": "^3.0.0", + "d3-timer": "^3.0.1" + } + }, + "node_modules/vm-browserify": { + "version": "1.1.2", + "license": "MIT", + "peer": true + }, + "node_modules/warning": { + "version": "4.0.3", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.0.0" + } + }, + "node_modules/watchpack": { + "version": "2.4.1", + "license": "MIT", + "dependencies": { + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/watchpack-chokidar2": { + "version": "2.0.1", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "chokidar": "^2.1.8" + } + }, + "node_modules/watchpack-chokidar2/node_modules/anymatch": { + "version": "2.0.0", + "license": "ISC", + "optional": true, + "peer": true, + "dependencies": { + "micromatch": "^3.1.4", + "normalize-path": "^2.1.1" + } + }, + "node_modules/watchpack-chokidar2/node_modules/anymatch/node_modules/normalize-path": { + "version": "2.1.1", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "remove-trailing-separator": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/watchpack-chokidar2/node_modules/binary-extensions": { + "version": "1.13.1", + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/watchpack-chokidar2/node_modules/braces": { + "version": "2.3.2", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "arr-flatten": "^1.1.0", + "array-unique": "^0.3.2", + "extend-shallow": "^2.0.1", + "fill-range": "^4.0.0", + "isobject": "^3.0.1", + "repeat-element": "^1.1.2", + "snapdragon": "^0.8.1", + "snapdragon-node": "^2.0.1", + "split-string": "^3.0.2", + "to-regex": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/watchpack-chokidar2/node_modules/chokidar": { + "version": "2.1.8", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "anymatch": "^2.0.0", + "async-each": "^1.0.1", + "braces": "^2.3.2", + "glob-parent": "^3.1.0", + "inherits": "^2.0.3", + "is-binary-path": "^1.0.0", + "is-glob": "^4.0.0", + "normalize-path": "^3.0.0", + "path-is-absolute": "^1.0.0", + "readdirp": "^2.2.1", + "upath": "^1.1.1" + }, + "optionalDependencies": { + "fsevents": "^1.2.7" + } + }, + "node_modules/watchpack-chokidar2/node_modules/fill-range": { + "version": "4.0.0", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "extend-shallow": "^2.0.1", + "is-number": "^3.0.0", + "repeat-string": "^1.6.1", + "to-regex-range": "^2.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/watchpack-chokidar2/node_modules/glob-parent": { + "version": "3.1.0", + "license": "ISC", + "optional": true, + "peer": true, + "dependencies": { + "is-glob": "^3.1.0", + "path-dirname": "^1.0.0" + } + }, + "node_modules/watchpack-chokidar2/node_modules/glob-parent/node_modules/is-glob": { + "version": "3.1.0", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "is-extglob": "^2.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/watchpack-chokidar2/node_modules/is-binary-path": { + "version": "1.0.1", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "binary-extensions": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/watchpack-chokidar2/node_modules/is-extendable": { + "version": "1.0.1", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "is-plain-object": "^2.0.4" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/watchpack-chokidar2/node_modules/is-number": { + "version": "3.0.0", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "kind-of": "^3.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/watchpack-chokidar2/node_modules/is-number/node_modules/kind-of": { + "version": "3.2.2", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "is-buffer": "^1.1.5" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/watchpack-chokidar2/node_modules/is-plain-object": { + "version": "2.0.4", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/watchpack-chokidar2/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "optional": true, + "peer": true + }, + "node_modules/watchpack-chokidar2/node_modules/micromatch": { + "version": "3.1.10", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "braces": "^2.3.1", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "extglob": "^2.0.4", + "fragment-cache": "^0.2.1", + "kind-of": "^6.0.2", + "nanomatch": "^1.2.9", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/watchpack-chokidar2/node_modules/micromatch/node_modules/extend-shallow": { + "version": "3.0.2", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "assign-symbols": "^1.0.0", + "is-extendable": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/watchpack-chokidar2/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/watchpack-chokidar2/node_modules/readdirp": { + "version": "2.2.1", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "graceful-fs": "^4.1.11", + "micromatch": "^3.1.10", + "readable-stream": "^2.0.2" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/watchpack-chokidar2/node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "optional": true, + "peer": true + }, + "node_modules/watchpack-chokidar2/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/watchpack-chokidar2/node_modules/to-regex-range": { + "version": "2.1.1", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "is-number": "^3.0.0", + "repeat-string": "^1.6.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/wbuf": { + "version": "1.7.3", + "license": "MIT", + "dependencies": { + "minimalistic-assert": "^1.0.0" + } + }, + "node_modules/web-namespaces": { + "version": "2.0.1", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/web-worker": { + "version": "1.3.0", + "license": "Apache-2.0" + }, + "node_modules/webidl-conversions": { + "version": "4.0.2", + "license": "BSD-2-Clause" + }, + "node_modules/webpack": { + "version": "5.95.0", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.5", + "@webassemblyjs/ast": "^1.12.1", + "@webassemblyjs/wasm-edit": "^1.12.1", + "@webassemblyjs/wasm-parser": "^1.12.1", + "acorn": "^8.7.1", + "acorn-import-attributes": "^1.9.5", + "browserslist": "^4.21.10", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^5.17.1", + "es-module-lexer": "^1.2.1", + "eslint-scope": "5.1.1", + "events": "^3.2.0", + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.2.11", + "json-parse-even-better-errors": "^2.3.1", + "loader-runner": "^4.2.0", + "mime-types": "^2.1.27", + "neo-async": "^2.6.2", + "schema-utils": "^3.2.0", + "tapable": "^2.1.1", + "terser-webpack-plugin": "^5.3.10", + "watchpack": "^2.4.1", + "webpack-sources": "^3.2.3" + }, + "bin": { + "webpack": "bin/webpack.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependenciesMeta": { + "webpack-cli": { + "optional": true + } + } + }, + "node_modules/webpack-bundle-analyzer": { + "version": "4.10.1", + "license": "MIT", + "dependencies": { + "@discoveryjs/json-ext": "0.5.7", + "acorn": "^8.0.4", + "acorn-walk": "^8.0.0", + "commander": "^7.2.0", + "debounce": "^1.2.1", + "escape-string-regexp": "^4.0.0", + "gzip-size": "^6.0.0", + "html-escaper": "^2.0.2", + "is-plain-object": "^5.0.0", + "opener": "^1.5.2", + "picocolors": "^1.0.0", + "sirv": "^2.0.3", + "ws": "^7.3.1" + }, + "bin": { + "webpack-bundle-analyzer": "lib/bin/analyzer.js" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/webpack-bundle-analyzer/node_modules/commander": { + "version": "7.2.0", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/webpack-dev-middleware": { + "version": "5.3.4", + "license": "MIT", + "dependencies": { + "colorette": "^2.0.10", + "memfs": "^3.4.3", + "mime-types": "^2.1.31", + "range-parser": "^1.2.1", + "schema-utils": "^4.0.0" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^4.0.0 || ^5.0.0" + } + }, + "node_modules/webpack-dev-middleware/node_modules/mime-db": { + "version": "1.52.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/webpack-dev-middleware/node_modules/mime-types": { + "version": "2.1.35", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/webpack-dev-middleware/node_modules/range-parser": { + "version": "1.2.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/webpack-dev-server": { + "version": "4.15.1", + "license": "MIT", + "dependencies": { + "@types/bonjour": "^3.5.9", + "@types/connect-history-api-fallback": "^1.3.5", + "@types/express": "^4.17.13", + "@types/serve-index": "^1.9.1", + "@types/serve-static": "^1.13.10", + "@types/sockjs": "^0.3.33", + "@types/ws": "^8.5.5", + "ansi-html-community": "^0.0.8", + "bonjour-service": "^1.0.11", + "chokidar": "^3.5.3", + "colorette": "^2.0.10", + "compression": "^1.7.4", + "connect-history-api-fallback": "^2.0.0", + "default-gateway": "^6.0.3", + "express": "^4.17.3", + "graceful-fs": "^4.2.6", + "html-entities": "^2.3.2", + "http-proxy-middleware": "^2.0.3", + "ipaddr.js": "^2.0.1", + "launch-editor": "^2.6.0", + "open": "^8.0.9", + "p-retry": "^4.5.0", + "rimraf": "^3.0.2", + "schema-utils": "^4.0.0", + "selfsigned": "^2.1.1", + "serve-index": "^1.9.1", + "sockjs": "^0.3.24", + "spdy": "^4.0.2", + "webpack-dev-middleware": "^5.3.1", + "ws": "^8.13.0" + }, + "bin": { + "webpack-dev-server": "bin/webpack-dev-server.js" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^4.37.0 || ^5.0.0" + }, + "peerDependenciesMeta": { + "webpack": { + "optional": true + }, + "webpack-cli": { + "optional": true + } + } + }, + "node_modules/webpack-dev-server/node_modules/ws": { + "version": "8.17.1", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/webpack-merge": { + "version": "5.10.0", + "license": "MIT", + "dependencies": { + "clone-deep": "^4.0.1", + "flat": "^5.0.2", + "wildcard": "^2.0.0" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/webpack-sources": { + "version": "3.2.3", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/webpack/node_modules/ajv": { + "version": "6.12.6", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/webpack/node_modules/ajv-keywords": { + "version": "3.5.2", + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/webpack/node_modules/json-schema-traverse": { + "version": "0.4.1", + "license": "MIT" + }, + "node_modules/webpack/node_modules/mime-db": { + "version": "1.52.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/webpack/node_modules/mime-types": { + "version": "2.1.35", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/webpack/node_modules/schema-utils": { + "version": "3.3.0", + "license": "MIT", + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/webpackbar": { + "version": "5.0.2", + "license": "MIT", + "dependencies": { + "chalk": "^4.1.0", + "consola": "^2.15.3", + "pretty-time": "^1.1.0", + "std-env": "^3.0.1" + }, + "engines": { + "node": ">=12" + }, + "peerDependencies": { + "webpack": "3 || 4 || 5" + } + }, + "node_modules/websocket-driver": { + "version": "0.7.4", + "license": "Apache-2.0", + "dependencies": { + "http-parser-js": ">=0.5.1", + "safe-buffer": ">=5.1.0", + "websocket-extensions": ">=0.1.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/websocket-extensions": { + "version": "0.1.4", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/whatwg-url": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "lodash.sortby": "^4.7.0", + "tr46": "^1.0.1", + "webidl-conversions": "^4.0.2" + } + }, + "node_modules/which": { + "version": "2.0.2", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "is-bigint": "^1.0.1", + "is-boolean-object": "^1.1.0", + "is-number-object": "^1.0.4", + "is-string": "^1.0.5", + "is-symbol": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.14", + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.6", + "call-bind": "^1.0.5", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/widest-line": { + "version": "4.0.1", + "license": "MIT", + "dependencies": { + "string-width": "^5.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/wildcard": { + "version": "2.0.1", + "license": "MIT" + }, + "node_modules/workbox-background-sync": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "idb": "^7.0.1", + "workbox-core": "7.1.0" + } + }, + "node_modules/workbox-broadcast-update": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "workbox-core": "7.1.0" + } + }, + "node_modules/workbox-build": { + "version": "7.1.1", + "license": "MIT", + "dependencies": { + "@apideck/better-ajv-errors": "^0.3.1", + "@babel/core": "^7.24.4", + "@babel/preset-env": "^7.11.0", + "@babel/runtime": "^7.11.2", + "@rollup/plugin-babel": "^5.2.0", + "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-replace": "^2.4.1", + "@rollup/plugin-terser": "^0.4.3", + "@surma/rollup-plugin-off-main-thread": "^2.2.3", + "ajv": "^8.6.0", + "common-tags": "^1.8.0", + "fast-json-stable-stringify": "^2.1.0", + "fs-extra": "^9.0.1", + "glob": "^7.1.6", + "lodash": "^4.17.20", + "pretty-bytes": "^5.3.0", + "rollup": "^2.43.1", + "source-map": "^0.8.0-beta.0", + "stringify-object": "^3.3.0", + "strip-comments": "^2.0.1", + "tempy": "^0.6.0", + "upath": "^1.2.0", + "workbox-background-sync": "7.1.0", + "workbox-broadcast-update": "7.1.0", + "workbox-cacheable-response": "7.1.0", + "workbox-core": "7.1.0", + "workbox-expiration": "7.1.0", + "workbox-google-analytics": "7.1.0", + "workbox-navigation-preload": "7.1.0", + "workbox-precaching": "7.1.0", + "workbox-range-requests": "7.1.0", + "workbox-recipes": "7.1.0", + "workbox-routing": "7.1.0", + "workbox-strategies": "7.1.0", + "workbox-streams": "7.1.0", + "workbox-sw": "7.1.0", + "workbox-window": "7.1.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/workbox-build/node_modules/fs-extra": { + "version": "9.1.0", + "license": "MIT", + "dependencies": { + "at-least-node": "^1.0.0", + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/workbox-build/node_modules/source-map": { + "version": "0.8.0-beta.0", + "license": "BSD-3-Clause", + "dependencies": { + "whatwg-url": "^7.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/workbox-cacheable-response": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "workbox-core": "7.1.0" + } + }, + "node_modules/workbox-core": { + "version": "7.1.0", + "license": "MIT" + }, + "node_modules/workbox-expiration": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "idb": "^7.0.1", + "workbox-core": "7.1.0" + } + }, + "node_modules/workbox-google-analytics": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "workbox-background-sync": "7.1.0", + "workbox-core": "7.1.0", + "workbox-routing": "7.1.0", + "workbox-strategies": "7.1.0" + } + }, + "node_modules/workbox-navigation-preload": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "workbox-core": "7.1.0" + } + }, + "node_modules/workbox-precaching": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "workbox-core": "7.1.0", + "workbox-routing": "7.1.0", + "workbox-strategies": "7.1.0" + } + }, + "node_modules/workbox-range-requests": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "workbox-core": "7.1.0" + } + }, + "node_modules/workbox-recipes": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "workbox-cacheable-response": "7.1.0", + "workbox-core": "7.1.0", + "workbox-expiration": "7.1.0", + "workbox-precaching": "7.1.0", + "workbox-routing": "7.1.0", + "workbox-strategies": "7.1.0" + } + }, + "node_modules/workbox-routing": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "workbox-core": "7.1.0" + } + }, + "node_modules/workbox-strategies": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "workbox-core": "7.1.0" + } + }, + "node_modules/workbox-streams": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "workbox-core": "7.1.0", + "workbox-routing": "7.1.0" + } + }, + "node_modules/workbox-sw": { + "version": "7.1.0", + "license": "MIT" + }, + "node_modules/workbox-window": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "@types/trusted-types": "^2.0.2", + "workbox-core": "7.1.0" + } + }, + "node_modules/worker-farm": { + "version": "1.7.0", + "license": "MIT", + "peer": true, + "dependencies": { + "errno": "~0.1.7" + } + }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "license": "MIT" + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-regex": { + "version": "6.0.1", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "6.2.1", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/strip-ansi": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "license": "ISC" + }, + "node_modules/write-file-atomic": { + "version": "3.0.3", + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4", + "is-typedarray": "^1.0.0", + "signal-exit": "^3.0.2", + "typedarray-to-buffer": "^3.1.5" + } + }, + "node_modules/ws": { + "version": "7.5.10", + "license": "MIT", + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xdg-basedir": { + "version": "5.1.0", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/xml-js": { + "version": "1.6.11", + "license": "MIT", + "dependencies": { + "sax": "^1.2.4" + }, + "bin": { + "xml-js": "bin/cli.js" + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.4" + } + }, + "node_modules/y18n": { + "version": "4.0.3", + "license": "ISC", + "peer": true + }, + "node_modules/yallist": { + "version": "3.1.1", + "license": "ISC" + }, + "node_modules/yaml": { + "version": "1.10.2", + "license": "ISC", + "engines": { + "node": ">= 6" + } + }, + "node_modules/yargs": { + "version": "17.7.2", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs/node_modules/emoji-regex": { + "version": "8.0.0", + "dev": true, + "license": "MIT" + }, + "node_modules/yargs/node_modules/string-width": { + "version": "4.2.3", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/y18n": { + "version": "5.0.8", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yauzl": { + "version": "2.10.0", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-crc32": "~0.2.3", + "fd-slicer": "~1.1.0" + } + }, + "node_modules/yocto-queue": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "3.23.8", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zwitch": { + "version": "2.0.4", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..021a2e7 --- /dev/null +++ b/package.json @@ -0,0 +1,107 @@ +{ + "name": "codeharborhub", + "version": "0.0.0", + "private": true, + "scripts": { + "docusaurus": "docusaurus", + "start": "docusaurus start", + "build": "docusaurus build", + "swizzle": "docusaurus swizzle", + "deploy": "docusaurus deploy", + "deploy-gh-pages": "gh-pages -d build", + "build:fast": "docusaurus build --no-minify", + "clear": "docusaurus clear", + "serve": "docusaurus serve", + "write-translations": "docusaurus write-translations", + "write-heading-ids": "docusaurus write-heading-ids" + }, + "dependencies": { + "@docusaurus/core": "^3.4.0", + "@docusaurus/plugin-client-redirects": "^3.5.2", + "@docusaurus/plugin-content-pages": "^3.3.2", + "@docusaurus/plugin-google-analytics": "^3.3.2", + "@docusaurus/plugin-google-gtag": "^3.3.2", + "@docusaurus/plugin-google-tag-manager": "^3.3.2", + "@docusaurus/plugin-ideal-image": "^3.3.2", + "@docusaurus/plugin-pwa": "^3.3.2", + "@docusaurus/plugin-vercel-analytics": "^3.3.2", + "@docusaurus/preset-classic": "^3.3.2", + "@docusaurus/remark-plugin-npm2yarn": "^3.4.0", + "@docusaurus/theme-classic": "^3.4.0", + "@docusaurus/theme-live-codeblock": "^3.3.2", + "@docusaurus/theme-mermaid": "^3.3.2", + "@docusaurus/theme-search-algolia": "^3.3.2", + "@docusaurus/utils-validation": "^3.3.2", + "@fluentui/react-icons": "^2.0.242", + "@fortawesome/fontawesome-svg-core": "^6.5.2", + "@fortawesome/free-brands-svg-icons": "^6.5.2", + "@fortawesome/free-solid-svg-icons": "^6.5.1", + "@fortawesome/react-fontawesome": "^0.2.2", + "@giscus/react": "^3.0.0", + "@mdx-js/react": "^3.0.0", + "@tsparticles/react": "^3.0.0", + "@tsparticles/slim": "^3.4.0", + "@types/react": "^18.3.9", + "@types/react-dom": "^18.3.0", + "axios": "^1.7.2", + "class-variance-authority": "^0.7.0", + "clsx": "^2.1.1", + "docusaurus2-dotenv": "^1.4.0", + "express": "^4.18.2", + "fontawesome": "^5.6.3", + "framer-motion": "^11.2.10", + "joi": "^17.12.1", + "passport": "^0.7.0", + "passport-github": "^1.1.0", + "prism-react-renderer": "^2.3.1", + "raw-loader": "^4.0.2", + "react": "^18.0.0", + "react-dom": "^18.0.0", + "react-icons": "^5.2.1", + "react-lite-youtube-embed": "^2.4.0", + "react-phone-input-2": "^2.15.1", + "react-popper": "^2.3.0", + "react-redux": "^9.1.0", + "react-simple-code-editor": "^0.14.0", + "react-window": "^1.8.10", + "recharts": "^2.12.7", + "redux": "^5.0.1", + "rehype-katex": "^7.0.0", + "remark-math": "^6.0.0", + "styled-components": "^6.1.8", + "swiper": "^11.1.4", + "three": "^0.169.0", + "vanilla-tilt": "^1.8.1" + }, + "devDependencies": { + "@babel/core": "^7.24.7", + "@babel/plugin-syntax-jsx": "^7.24.7", + "@babel/preset-react": "^7.24.7", + "@docusaurus/module-type-aliases": "^3.3.2", + "@docusaurus/types": "^3.3.2", + "@types/node": "^22.6.1", + "autoprefixer": "^10.4.20", + "dotenv": "^16.4.5", + "gh-pages": "^6.1.1", + "lighthouse": "^12.1.0", + "postcss": "^8.4.47", + "tailwindcss": "^3.4.12" + }, + "browserslist": { + "production": [ + ">0.5%", + "not dead", + "not op_mini all" + ], + "development": [ + "last 3 chrome version", + "last 3 firefox version", + "last 5 safari version" + ] + }, + "engines": { + "node": ">=18.0" + }, + "license": "MIT", + "author": "Ajay-Dhangar" +} diff --git a/particlesjs-config.js b/particlesjs-config.js new file mode 100644 index 0000000..d639787 --- /dev/null +++ b/particlesjs-config.js @@ -0,0 +1,647 @@ +const particlesConfig = { + autoPlay: true, + background: { + color: { + value: "black" + }, + image: "", + position: "", + repeat: "", + size: "", + opacity: 1 + }, + backgroundMask: { + composite: "destination-out", + cover: { + color: { + value: "#fff" + }, + opacity: 1 + }, + enable: false + }, + clear: true, + defaultThemes: {}, + delay: 0, + fullScreen: { + enable: true, + zIndex: -1 + }, + detectRetina: true, + duration: 0, + fpsLimit: 120, + interactivity: { + detectsOn: "window", + events: { + onClick: { + enable: false, + mode: [] + }, + onDiv: { + selectors: [], + enable: false, + mode: [], + type: "circle" + }, + onHover: { + enable: true, + mode: "light", + parallax: { + enable: false, + force: 2, + smooth: 10 + } + }, + resize: { + delay: 0.5, + enable: true + } + }, + modes: { + trail: { + delay: 1, + pauseOnStop: false, + quantity: 1, + particles: { + bounce: { + horizontal: { + random: {} + }, + vertical: { + random: {} + } + }, + collisions: { + bounce: { + horizontal: { + random: {} + }, + vertical: { + random: {} + } + }, + overlap: {} + }, + color: { + animation: {} + }, + destroy: { + split: { + factor: { + random: {} + }, + rate: { + random: {} + } + } + }, + life: { + delay: { + random: {} + }, + duration: { + random: {} + } + }, + links: { + shadow: {}, + triangles: {} + }, + move: { + angle: {}, + attract: { + rotate: {} + }, + distance: {}, + gravity: {}, + outModes: {}, + path: { + delay: { + random: {} + } + }, + trail: { + fill: {} + } + }, + number: { + density: {} + }, + opacity: { + animation: {}, + random: {} + }, + roll: { + darken: {}, + enlighten: {} + }, + rotate: { + animation: {} + }, + shadow: { + offset: {} + }, + shape: {}, + size: { + animation: {}, + random: {} + }, + stroke: { + color: { + value: "", + animation: { + count: 0, + enable: false, + offset: { + max: 0, + min: 0 + }, + speed: 0, + decay: 0, + sync: false + } + } + }, + tilt: { + animation: {} + }, + twinkle: { + lines: {}, + particles: {} + }, + wobble: {} + } + }, + attract: { + distance: 200, + duration: 0.4, + easing: "ease-out-quad", + factor: 1, + maxSpeed: 50, + speed: 1 + }, + bounce: { + distance: 200 + }, + bubble: { + distance: 200, + duration: 0.4, + mix: false, + divs: { + distance: 200, + duration: 0.4, + mix: false, + selectors: [] + } + }, + connect: { + distance: 80, + links: { + opacity: 0.5 + }, + radius: 60 + }, + grab: { + distance: 100, + links: { + blink: false, + consent: false, + opacity: 1 + } + }, + push: { + default: true, + groups: [], + quantity: 4 + }, + remove: { + quantity: 2 + }, + repulse: { + distance: 150, + duration: 0.4, + factor: 100, + speed: 1, + maxSpeed: 50, + easing: "ease-out-quad", + divs: { + distance: 200, + duration: 0.4, + factor: 100, + speed: 1, + maxSpeed: 50, + easing: "ease-out-quad", + selectors: [] + } + }, + slow: { + factor: 3, + radius: 200 + }, + light: { + area: { + gradient: { + start: { + value: "3b5e98" + }, + stop: { + value: "#17163e" + } + }, + radius: 1000 + }, + shadow: { + color: { + value: "#17163e" + }, + length: 2000 + } + } + } + }, + manualParticles: [], + particles: { + bounce: { + horizontal: { + value: 1 + }, + vertical: { + value: 1 + } + }, + collisions: { + absorb: { + speed: 2 + }, + bounce: { + horizontal: { + value: 1 + }, + vertical: { + value: 1 + } + }, + enable: false, + maxSpeed: 50, + mode: "bounce", + overlap: { + enable: true, + retries: 0 + } + }, + color: { + value: "#ff0000", + animation: { + h: { + count: 0, + enable: true, + speed: 20, + decay: 0, + delay: 0, + sync: true, + offset: 0 + }, + s: { + count: 0, + enable: false, + speed: 1, + decay: 0, + delay: 0, + sync: true, + offset: 0 + }, + l: { + count: 0, + enable: false, + speed: 1, + decay: 0, + delay: 0, + sync: true, + offset: 0 + } + } + }, + effect: { + close: true, + fill: true, + options: {}, + type: [] + }, + groups: {}, + move: { + angle: { + offset: 0, + value: 90 + }, + attract: { + distance: 200, + enable: false, + rotate: { + x: 3000, + y: 3000 + } + }, + center: { + x: 50, + y: 50, + mode: "percent", + radius: 0 + }, + decay: 0, + distance: {}, + direction: "none", + drift: 0, + enable: true, + gravity: { + acceleration: 9.81, + enable: false, + inverse: false, + maxSpeed: 50 + }, + path: { + clamp: true, + delay: { + value: 0 + }, + enable: false, + options: {} + }, + outModes: { + default: "out", + bottom: "out", + left: "out", + right: "out", + top: "out" + }, + random: false, + size: false, + speed: 6, + spin: { + acceleration: 0, + enable: false + }, + straight: false, + trail: { + enable: false, + length: 10, + fill: {} + }, + vibrate: false, + warp: false + }, + number: { + density: { + enable: true, + width: 1920, + height: 1080 + }, + limit: { + mode: "delete", + value: 0 + }, + value: 30 + }, + opacity: { + value: 1, + animation: { + count: 0, + enable: false, + speed: 2, + decay: 0, + delay: 0, + sync: false, + mode: "auto", + startValue: "random", + destroy: "none" + } + }, + reduceDuplicates: false, + shadow: { + blur: 0, + color: { + value: "#000" + }, + enable: false, + offset: { + x: 0, + y: 0 + } + }, + shape: { + close: true, + fill: true, + options: {}, + type: [ + "circle", + "square" + ] + }, + size: { + value: { + min: 15, + max: 30 + }, + animation: { + count: 0, + enable: false, + speed: 5, + decay: 0, + delay: 0, + sync: false, + mode: "auto", + startValue: "random", + destroy: "none" + } + }, + stroke: { + width: 0, + color: { + value: "", + animation: { + h: { + count: 0, + enable: false, + speed: 0, + decay: 0, + delay: 0, + sync: false, + offset: 0 + }, + s: { + count: 0, + enable: false, + speed: 1, + decay: 0, + delay: 0, + sync: true, + offset: 0 + }, + l: { + count: 0, + enable: false, + speed: 1, + decay: 0, + delay: 0, + sync: true, + offset: 0 + } + } + } + }, + zIndex: { + value: 0, + opacityRate: 1, + sizeRate: 1, + velocityRate: 1 + }, + destroy: { + bounds: {}, + mode: "none", + split: { + count: 1, + factor: { + value: 3 + }, + rate: { + value: { + min: 4, + max: 9 + } + }, + sizeOffset: true, + particles: {} + } + }, + roll: { + darken: { + enable: false, + value: 0 + }, + enable: false, + enlighten: { + enable: false, + value: 0 + }, + mode: "vertical", + speed: 25 + }, + tilt: { + value: 0, + animation: { + enable: false, + speed: 0, + decay: 0, + sync: false + }, + direction: "clockwise", + enable: false + }, + twinkle: { + lines: { + enable: false, + frequency: 0.05, + opacity: 1 + }, + particles: { + enable: false, + frequency: 0.05, + opacity: 1 + } + }, + wobble: { + distance: 5, + enable: false, + speed: { + angle: 50, + move: 10 + } + }, + life: { + count: 0, + delay: { + value: 0, + sync: false + }, + duration: { + value: 0, + sync: false + } + }, + rotate: { + value: 0, + animation: { + enable: true, + speed: 5, + decay: 0, + sync: false + }, + direction: "clockwise", + path: false + }, + orbit: { + animation: { + count: 0, + enable: false, + speed: 1, + decay: 0, + delay: 0, + sync: false + }, + enable: false, + opacity: 1, + rotation: { + value: 45 + }, + width: 1 + }, + links: { + blink: false, + color: { + value: "#fff" + }, + consent: false, + distance: 100, + enable: false, + frequency: 1, + opacity: 1, + shadow: { + blur: 5, + color: { + value: "#000" + }, + enable: false + }, + triangles: { + enable: false, + frequency: 1 + }, + width: 1, + warp: false + }, + repulse: { + value: 0, + enabled: false, + distance: 1, + duration: 1, + factor: 1, + speed: 1 + } + }, + pauseOnBlur: true, + pauseOnOutsideViewport: true, + responsive: [], + smooth: false, + style: {}, + themes: [], + zLayers: 100, + emitters: [], + motion: { + disable: false, + reduce: { + factor: 4, + value: true + } + } + } + + export default particlesConfig; \ No newline at end of file diff --git a/plugins/my-plugin/index.js b/plugins/my-plugin/index.js new file mode 100644 index 0000000..965e8f8 --- /dev/null +++ b/plugins/my-plugin/index.js @@ -0,0 +1,50 @@ +const Joi = require("joi"); + +module.exports = function (context, options) { + return { + name: "my-plugin", + // lifecycle methods + injectHtmlTags() { + return { + headTags: [ + { + tagName: "meta", + attributes: { + "og:description": "My custom OG: Description", + }, + }, + ], + }; + }, + extendCli(cli) { + cli + .command("my-command action") + .description("This is a custom command") + .action(() => { + console.log("Hello World! - This is a custom command!"); + console.log("Plugin options:", options); + }); + }, + configurePostCss(postcssOptions) { + // Add Tailwind CSS and other PostCSS plugins + postcssOptions.plugins = [ + require("postcss-import"), + require("tailwindcss"), + require("autoprefixer"), + ]; + return postcssOptions; + }, + }; +}; + +module.exports.validateOptions = ({ validate, options }) => { + const joiSchema = Joi.object({ + settings: Joi.string().alphanum().min(3).max(30).required(), + api: Joi.string().required(), + keys: Joi.string().min(2).required(), + }); + + const validateOptions = validate(joiSchema, options); + + return validateOptions; +}; diff --git a/problems/gfg-problems/_category_.json b/problems/gfg-problems/_category_.json new file mode 100644 index 0000000..24c228f --- /dev/null +++ b/problems/gfg-problems/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "GFG Problems", + "position": 3, + "link": { + "type": "generated-index", + "description": "You will learn about the GFG Problems of Data Structures and Algorithms." + } + } \ No newline at end of file diff --git a/problems/gfg-problems/basic/0001-0100.md b/problems/gfg-problems/basic/0001-0100.md new file mode 100644 index 0000000..92a728d --- /dev/null +++ b/problems/gfg-problems/basic/0001-0100.md @@ -0,0 +1,622 @@ +--- +id: 0001-0100 +title: GFG basic problems 0001-0100 +sidebar_label: 0001-0100 +keywords: + - gfg problems + - gfg problems basic + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/binary-search-1587115620/1", + "solutionLink": "#", + "problemName": "Binary Search" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/peak-element/1", + "solutionLink": "#", + "problemName": "Peak element" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/power-of-2-1587115620/1", + "solutionLink": "#", + "problemName": "Power of 2" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/union-of-two-arrays3538/1", + "solutionLink": "#", + "problemName": "Union of two arrays" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-a-string/1", + "solutionLink": "#", + "problemName": "Reverse a String" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/search-an-element-in-an-array-1587115621/1", + "solutionLink": "#", + "problemName": "Search an Element in an array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-two-arrays-are-equal-or-not3847/1", + "solutionLink": "#", + "problemName": "Check if two arrays are equal or not" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/array-subset-of-another-array2317/1", + "solutionLink": "#", + "problemName": "Array Subset of another array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-array-in-groups0255/1", + "solutionLink": "#", + "problemName": "Reverse array in groups" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/cyclically-rotate-an-array-by-one2614/1", + "solutionLink": "#", + "problemName": "Cyclically rotate an array by one" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-minimum-and-maximum-element-in-an-array4428/1", + "solutionLink": "#", + "problemName": "Find minimum and maximum element in an array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/prime-number2314/1", + "solutionLink": "#", + "problemName": "Prime Number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-element-in-array4009/1", + "solutionLink": "#", + "problemName": "Largest Element in Array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-first-n-fibonacci-numbers1002/1", + "solutionLink": "#", + "problemName": "Print first n Fibonacci Numbers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/who-will-win-1587115621/1", + "solutionLink": "#", + "problemName": "Searching an element in a sorted array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/linked-list-insertion-1587115620/1", + "solutionLink": "#", + "problemName": "Linked List Insertion" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-element-in-bst/1", + "solutionLink": "#", + "problemName": "Minimum element in BST" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/immediate-smaller-element1142/1", + "solutionLink": "#", + "problemName": "Immediate Smaller Element" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/implement-strstr/1", + "solutionLink": "#", + "problemName": "Implement strstr" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/implement-stack-using-array/1", + "solutionLink": "#", + "problemName": "Implement stack using array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-nodes-of-linked-list/1", + "solutionLink": "#", + "problemName": "Count nodes of linked list" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/preorder-traversal/1", + "solutionLink": "#", + "problemName": "Preorder Traversal" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/circular-linked-list/1", + "solutionLink": "#", + "problemName": "Check If Circular Linked List" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/inorder-traversal/1", + "solutionLink": "#", + "problemName": "Inorder Traversal" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/implement-queue-using-array/1", + "solutionLink": "#", + "problemName": "Implement Queue using array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-squares3649/1", + "solutionLink": "#", + "problemName": "Count Squares" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-linked-list-elements/1", + "solutionLink": "#", + "problemName": "Print Linked List elements" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/implement-stack-using-linked-list/1", + "solutionLink": "#", + "problemName": "Implement Stack using Linked List" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/factorial5739/1", + "solutionLink": "#", + "problemName": "Factorial" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/identical-linked-lists/1", + "solutionLink": "#", + "problemName": "Identical Linked Lists" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/searching-a-number0324/1", + "solutionLink": "#", + "problemName": "Searching a number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sort-the-array0055/1", + "solutionLink": "#", + "problemName": "Sort The Array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/postorder-traversal/1", + "solutionLink": "#", + "problemName": "Postorder Traversal" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/lcm-and-gcd4516/1", + "solutionLink": "#", + "problemName": "LCM And GCD" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/reversal-algorithm5340/1", + "solutionLink": "#", + "problemName": "Rotating an Array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/binary-array-sorting-1587115620/1", + "solutionLink": "#", + "problemName": "Binary Array Sorting" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-leaves-in-binary-tree/1", + "solutionLink": "#", + "problemName": "Count Leaves in Binary Tree" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/third-largest-element/1", + "solutionLink": "#", + "problemName": "Third largest element" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/insert-in-middle-of-linked-list/1", + "solutionLink": "#", + "problemName": "Insert in Middle of Linked List" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-occuring-character-1587115620/1", + "solutionLink": "#", + "problemName": "Maximum Occuring Character" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-odd-even/1", + "solutionLink": "#", + "problemName": "Count Odd Even" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/implement-queue-using-linked-list/1", + "solutionLink": "#", + "problemName": "Implement Queue using Linked List" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-min/1", + "solutionLink": "#", + "problemName": "Max Min" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/bit-difference-1587115620/1", + "solutionLink": "#", + "problemName": "Bit Difference" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-smallest-and-second-smallest-element-in-an-array3226/1", + "solutionLink": "#", + "problemName": "Find the smallest and second smallest element in an array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-hello-world3402/1", + "solutionLink": "#", + "problemName": "C++ Hello World" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/last-index-of-15847/1", + "solutionLink": "#", + "problemName": "Last index of One" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/missing-number4257/1", + "solutionLink": "#", + "problemName": "Missing number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/closest-number5728/1", + "solutionLink": "#", + "problemName": "Closest Number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/node-at-a-given-index-in-linked-list/1", + "solutionLink": "#", + "problemName": "Node at a given index in linked list" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/uncommon-characters4932/1", + "solutionLink": "#", + "problemName": "Uncommon characters" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/search-a-node-in-bst/1", + "solutionLink": "#", + "problemName": "Search a node in BST" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/product-of-array-element/1", + "solutionLink": "#", + "problemName": "Product of array elements" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/consecutive-elements2306/1", + "solutionLink": "#", + "problemName": "Remove Consecutive Characters" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/middle-of-three2926/1", + "solutionLink": "#", + "problemName": "Middle of Three" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/replace-all-0s-with-5/1", + "solutionLink": "#", + "problemName": "Replace all 0's with 5" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/insert-a-node-in-doubly-linked-list/1", + "solutionLink": "#", + "problemName": "Doubly linked list Insertion at given position" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/repeated-character2058/1", + "solutionLink": "#", + "problemName": "Repeated Character" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-odd-occurence4820/1", + "solutionLink": "#", + "problemName": "Exceptionally odd" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-first-n-terms5843/1", + "solutionLink": "#", + "problemName": "Sum of first n terms" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/binary-string-1587115620/1", + "solutionLink": "#", + "problemName": "Binary String" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/linked-list-length-even-or-odd/1", + "solutionLink": "#", + "problemName": "Linked List Length Even or Odd?" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-position-of-set-bit3706/1", + "solutionLink": "#", + "problemName": "Find position of set bit" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-common-characters-and-concatenate-1587115621/1", + "solutionLink": "#", + "problemName": "Remove common characters and concatenate" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/square-pattern/1", + "solutionLink": "#", + "problemName": "Pattern 1" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/anagram-of-string/1", + "solutionLink": "#", + "problemName": "Anagram of String" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-is-sparse-or-not-1587115620/1", + "solutionLink": "#", + "problemName": "Number is sparse or not" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/delete-alternate-nodes/1", + "solutionLink": "#", + "problemName": "Delete Alternate Nodes" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/ishaan-loves-chocolates2156/1", + "solutionLink": "#", + "problemName": "Ishaan Loves Chocolates" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/binary-number-to-decimal-number3525/1", + "solutionLink": "#", + "problemName": "Binary number to decimal number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-a-string-is-isogram-or-not-1587115620/1", + "solutionLink": "#", + "problemName": "Check if a string is Isogram or not" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/size-of-binary-tree/1", + "solutionLink": "#", + "problemName": "Size of Binary Tree" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/elements-in-the-range2834/1", + "solutionLink": "#", + "problemName": "Elements in the Range" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/game-with-nos3123/1", + "solutionLink": "#", + "problemName": "Game with nos" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-numbers-in-string-1587115621/1", + "solutionLink": "#", + "problemName": "Sum of numbers in string" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/start-coding/1", + "solutionLink": "#", + "problemName": "Start Coding" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/angle-between-hour-and-minute-hand0545/1", + "solutionLink": "#", + "problemName": "Angle between hour and minute hand" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sorted-matrix2333/1", + "solutionLink": "#", + "problemName": "Sorted matrix" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-for-subsequence4930/1", + "solutionLink": "#", + "problemName": "Check for subsequence" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/multiply-left-and-right-array-sum1555/1", + "solutionLink": "#", + "problemName": "Multiply left and right array sum." + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/leap-year0943/1", + "solutionLink": "#", + "problemName": "Leap Year" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-nk-th-node-in-linked-list/1", + "solutionLink": "#", + "problemName": "Find n/k th node in Linked list" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/first-and-last-occurrences-of-x2041/1", + "solutionLink": "#", + "problemName": "First and last occurrences of X" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-money2855/1", + "solutionLink": "#", + "problemName": "Maximum money" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangle-pattern/1", + "solutionLink": "#", + "problemName": "Pattern 5" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/balanced-array07200720/1", + "solutionLink": "#", + "problemName": "Balanced Array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/product-of-maximum-in-first-array-and-minimum-in-second3943/1", + "solutionLink": "#", + "problemName": "Product of maximum in first array and minimum in second" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-fine4353/1", + "solutionLink": "#", + "problemName": "Find the fine" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/ways-to-tile-a-floor5836/1", + "solutionLink": "#", + "problemName": "Ways To Tile A Floor" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/index-of-first-1-in-a-sorted-array-of-0s-and-1s4048/1", + "solutionLink": "#", + "problemName": "Index of first 1 in a sorted array of 0s and 1s" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-character3815/1", + "solutionLink": "#", + "problemName": "Remove character" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-first-letter-of-every-word-in-the-string3632/1", + "solutionLink": "#", + "problemName": "Print first letter of every word in the string" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/replace-all-0-with-5-in-an-input-integer/1", + "solutionLink": "#", + "problemName": "Replace all 0's with 5" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangle-number-1661489840/1", + "solutionLink": "#", + "problemName": "Pattern 6" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/set-kth-bit3724/1", + "solutionLink": "#", + "problemName": "Set kth bit" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/gcd-of-array0614/1", + "solutionLink": "#", + "problemName": "GCD of Array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/greater-on-right-side4305/1", + "solutionLink": "#", + "problemName": "Greater on right side" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/fighting-the-darkness3949/1", + "solutionLink": "#", + "problemName": "Fighting the darkness" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangle-pattern-1661718013/1", + "solutionLink": "#", + "problemName": "Pattern 10" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-all-factorial-numbers-less-than-or-equal-to-n3548/1", + "solutionLink": "#", + "problemName": "Find all factorial numbers less than or equal to N" + } +] + + + +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/basic/0101-0200.md b/problems/gfg-problems/basic/0101-0200.md new file mode 100644 index 0000000..f31d5b8 --- /dev/null +++ b/problems/gfg-problems/basic/0101-0200.md @@ -0,0 +1,622 @@ +--- +id: 0101-0200 +title: GFG basic problems 0101-0200 +sidebar_label: 0101-0200 +keywords: + - gfg problems + - gfg problems basic + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-binary-tree/1", + "solutionLink": "#", + "problemName": "Sum of Binary Tree" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangle-pattern-1661492263/1", + "solutionLink": "#", + "problemName": "Pattern 7" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-sum-of-last-n-nodes-of-the-linked-list/1", + "solutionLink": "#", + "problemName": "Find the Sum of Last N nodes of the Linked List" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-product-of-two-numbers2730/1", + "solutionLink": "#", + "problemName": "Maximum product of two numbers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sort-in-specific-order2422/1", + "solutionLink": "#", + "problemName": "Sort in specific order" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/operating-an-array/1", + "solutionLink": "#", + "problemName": "Operating an array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-a-number-is-power-of-another-number5442/1", + "solutionLink": "#", + "problemName": "Check if a number is power of another number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-in-struct-array/0", + "solutionLink": "/dsa-solutions/gfg-solutions/Basic/maximum-in-struct-array", + "problemName": "Maximum in Struct Array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/anagram-palindrome4720/1", + "solutionLink": "#", + "problemName": "Anagram Palindrome" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/merge-two-strings2736/1", + "solutionLink": "#", + "problemName": "Merge two strings" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-the-kth-digit3520/1", + "solutionLink": "#", + "problemName": "Print the Kth Digit" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/gf-series3535/1", + "solutionLink": "#", + "problemName": "G.F Series" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/modular-node/1", + "solutionLink": "#", + "problemName": "Modular Node" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-non-leaf-nodes-in-tree/1", + "solutionLink": "#", + "problemName": "Count Non-Leaf Nodes in Tree" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangle-pattern-1661493231/1", + "solutionLink": "#", + "problemName": "Pattern 8" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/extract-maximum2943/1", + "solutionLink": "#", + "problemName": "Extract Maximum" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/keypad-typing0119/1", + "solutionLink": "#", + "problemName": "Keypad typing" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/doubling-the-value4859/1", + "solutionLink": "#", + "problemName": "Doubling the value" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-unique-element2632/1", + "solutionLink": "#", + "problemName": "Find unique element" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-divisible-number/1", + "solutionLink": "#", + "problemName": "Smallest divisible number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/finding-position2223/1", + "solutionLink": "#", + "problemName": "Finding Position" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/good-or-bad-string1417/1", + "solutionLink": "#", + "problemName": "Good or Bad string" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/zero-converter-python/1", + "solutionLink": "#", + "problemName": "Zero Converter - Python" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-number-of-numbers/1", + "solutionLink": "#", + "problemName": "Find Number of Numbers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-set-bits5408/1", + "solutionLink": "#", + "problemName": "Check set bits" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/total-count2415/1", + "solutionLink": "#", + "problemName": "Total count" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-program-to-remove-consonants-from-a-string1945/1", + "solutionLink": "#", + "problemName": "Remove consonants from a string" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/change-the-string3541/1", + "solutionLink": "#", + "problemName": "Change the string" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/segregate-even-and-odd-numbers4629/1", + "solutionLink": "#", + "problemName": "Segregate Even and Odd numbers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/red-or-green5711/1", + "solutionLink": "#", + "problemName": "Red OR Green" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-zeros-in-a-sorted-matrix/1", + "solutionLink": "#", + "problemName": "Count zeros in a sorted matrix" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/stack-designer/1", + "solutionLink": "/dsa-solutions/gfg-solutions/Basic/stack-designer", + "problemName": "Stack designer" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sort-a-string2943/1", + "solutionLink": "#", + "problemName": "Sort a String" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-difference-pair5444/1", + "solutionLink": "#", + "problemName": "Minimum difference pair" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-repeating-number4858/1", + "solutionLink": "#", + "problemName": "Maximum repeating number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-the-characters1821/1", + "solutionLink": "#", + "problemName": "Count the characters" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-an-array-in-pendulum-arrangement4004/1", + "solutionLink": "#", + "problemName": "Print an array in Pendulum Arrangement" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/data-type-1666706751/1", + "solutionLink": "#", + "problemName": "Data Type" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangle-pattern-1661718455/1", + "solutionLink": "#", + "problemName": "Pattern 11" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/type-of-array4605/1", + "solutionLink": "#", + "problemName": "Type of array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/string-with-numbers-at-its-end5749/1", + "solutionLink": "#", + "problemName": "String with numbers at its end" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-product-of-k-integers2553/1", + "solutionLink": "#", + "problemName": "Minimum Product of k Integers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-size-of/1", + "solutionLink": "#", + "problemName": "The Size of" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-basic-data-types3128/1", + "solutionLink": "#", + "problemName": "C++ Basic Data types" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangle-pattern-1661718712/1", + "solutionLink": "#", + "problemName": "Pattern 13" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/permutations-in-array1747/1", + "solutionLink": "#", + "problemName": "Permutations in array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/queue-designer/1", + "solutionLink": "#", + "problemName": "Queue Push & Pop" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/professor-and-parties2000/1", + "solutionLink": "#", + "problemName": "Professor and Parties" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sort-and-reverse-vector/1", + "solutionLink": "#", + "problemName": "Sort and Reverse Vector" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/play-with-an-array/1", + "solutionLink": "#", + "problemName": "Play with an array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/add-two-fractions/1", + "solutionLink": "#", + "problemName": "Add two fractions" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/height-of-heap5025/1", + "solutionLink": "#", + "problemName": "Height of Heap" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/matching-pair5320/1", + "solutionLink": "#", + "problemName": "Matching Pair" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-substring-containing-1/1", + "solutionLink": "#", + "problemName": "longest substring containing '1'" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/circular-linked-list-traversal/1", + "solutionLink": "#", + "problemName": "Circular Linked List Traversal" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/java-1-d-and-2-d-array2952/1", + "solutionLink": "#", + "problemName": "Java 1-d and 2-d Array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-pair-sum5956/1", + "solutionLink": "#", + "problemName": "Count pair sum" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sort-the-string-in-descending-order3542/1", + "solutionLink": "#", + "problemName": "Sort the string in descending order" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-sub-array5620/1", + "solutionLink": "#", + "problemName": "Reverse sub array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/positive-and-negative-elements4613/1", + "solutionLink": "#", + "problemName": "Positive and negative elements" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-duplicates-from-unsorted-array4141/1", + "solutionLink": "#", + "problemName": "Remove Duplicates from unsorted array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/logical-operators/1", + "solutionLink": "#", + "problemName": "Logical Operators" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/geek-and-coffee-shop5721/1", + "solutionLink": "#", + "problemName": "Half N by M" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-stl-set-1-vector/1", + "solutionLink": "#", + "problemName": "C++ STL | Set 1 (vector)" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/toggle-bits-given-range0952/1", + "solutionLink": "#", + "problemName": "Toggle bits in the given range" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/set-the-rightmost-unset-bit4436/1", + "solutionLink": "#", + "problemName": "Set the rightmost unset bit" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/absolute-difference-11156/1", + "solutionLink": "#", + "problemName": "Absolute Difference of 1" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-primes0042/1", + "solutionLink": "#", + "problemName": "Sum of primes" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/decimal-to-binary-1587115620/1", + "solutionLink": "#", + "problemName": "Decimal to binary" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/thief-try-to-excape0710/1", + "solutionLink": "#", + "problemName": "Thief trying to escape" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/anshumans-favourite-number2029/1", + "solutionLink": "#", + "problemName": "Anshuman's Favourite Number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/alternative-sorting1311/1", + "solutionLink": "#", + "problemName": "Alternative Sorting" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/product-is-even-or-odd3020/1", + "solutionLink": "#", + "problemName": "Product is even or odd?" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-repeated-digits-in-a-given-number4014/1", + "solutionLink": "#", + "problemName": "Remove repeated digits in a given number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/odd-to-even0537/1", + "solutionLink": "#", + "problemName": "Odd to Even" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/front-to-back/1", + "solutionLink": "#", + "problemName": "Front to Back" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/pairwise-consecutive-elements/1", + "solutionLink": "#", + "problemName": "Pairwise Consecutive Elements" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-distinct-elements4801/1", + "solutionLink": "#", + "problemName": "Sum of distinct elements" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/repetitive-addition-of-digits2221/1", + "solutionLink": "#", + "problemName": "Repetitive Addition Of Digits" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-duplicates-under-given-constraints0856/1", + "solutionLink": "#", + "problemName": "Find duplicates under given constraints" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-the-door-is-open-or-closed2013/1", + "solutionLink": "#", + "problemName": "Check if the door is open or closed" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/remainder-with-7/1", + "solutionLink": "#", + "problemName": "Remainder with 7" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-penalty-shootout3810/1", + "solutionLink": "#", + "problemName": "The Penalty Shootout" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-fai-aj-over-all-pairs-in-an-array-of-n-integers4057/1", + "solutionLink": "#", + "problemName": "Sum of f(a[i], a[j]) over all pairs in an array of n integers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/middle-pattern/1", + "solutionLink": "#", + "problemName": "Middle Pattern" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/welcome-aboard-python/1", + "solutionLink": "#", + "problemName": "Welcome aboard - Python" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-divisible-by-43813/1", + "solutionLink": "#", + "problemName": "Check if divisible by 4" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-difference-among-k5805/1", + "solutionLink": "#", + "problemName": "Minimum Difference among K" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/squares-in-a-matrix5716/1", + "solutionLink": "#", + "problemName": "Squares in a Matrix" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/nth-even-fibonacci-number1119/1", + "solutionLink": "#", + "problemName": "Nth Even Fibonacci Number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/last-index-of-a-character-in-the-string4516/1", + "solutionLink": "#", + "problemName": "Last index of a character in the string" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/inverse-permutation0344/1", + "solutionLink": "#", + "problemName": "Inverse Permutation" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/unique-numbers3019/1", + "solutionLink": "#", + "problemName": "Unique Numbers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sums-of-i-th-row-and-i-th-column3054/1", + "solutionLink": "#", + "problemName": "Sums of i-th row and i-th column" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/midori-and-chocolates2438/1", + "solutionLink": "#", + "problemName": "Midori and chocolates" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/power-of-four/1", + "solutionLink": "#", + "problemName": "Power of Four" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-the-number-is-fibonacci4654/1", + "solutionLink": "#", + "problemName": "Check if the number is Fibonacci" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/encrypt-the-string-10337/1", + "solutionLink": "#", + "problemName": "Encrypt the string - 1" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-all-characters-other-than-alphabets4923/1", + "solutionLink": "#", + "problemName": "Remove all characters other than alphabets" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/rearrange-the-array5802/1", + "solutionLink": "#", + "problemName": "Rearrange the array" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/basic/0201-0300.md b/problems/gfg-problems/basic/0201-0300.md new file mode 100644 index 0000000..70b7932 --- /dev/null +++ b/problems/gfg-problems/basic/0201-0300.md @@ -0,0 +1,623 @@ +--- +id: 0201-0300 +title: GFG basic problems 0201-0300 +sidebar_label: 0201-0300 +keywords: + - gfg problems + - gfg problems basic + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimize-string-value1010/1", + "solutionLink": "#", + "problemName": "Minimize string value" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-product-of-x-and-y-with-floornx-y3711/1", + "solutionLink": "#", + "problemName": "Sum of product of x and y with floor(n/x) = y" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/form-largest-number-from-digits5430/1", + "solutionLink": "#", + "problemName": "Form largest number from digits" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/pairs-of-prime-number2612/1", + "solutionLink": "#", + "problemName": "Pairs of prime number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-n-th-term-in-the-series3926/1", + "solutionLink": "#", + "problemName": "Find N-th term in the series" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/pattern-jumping4855/1", + "solutionLink": "#", + "problemName": "Pattern Jumping" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/java-operatorsarithmetic-set-12417/1", + "solutionLink": "#", + "problemName": "Java Operators(Arithmetic) | Set 1" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/length-of-last-word5721/1", + "solutionLink": "#", + "problemName": "Length of Last word" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-array-puzzle/1", + "solutionLink": "#", + "problemName": "Sum Array Puzzle" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-number-which-contain-the-digit-d4144/1", + "solutionLink": "#", + "problemName": "Find the Number which contain the digit d" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-problem-of-identical-arrays3229/1", + "solutionLink": "#", + "problemName": "The problem of identical arrays" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-increasing-subarray3811/1", + "solutionLink": "#", + "problemName": "Longest increasing subarray" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-arithmetic-progression1842/1", + "solutionLink": "#", + "problemName": "Check Arithmetic Progression" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/three-distinct-factors5613/1", + "solutionLink": "#", + "problemName": "Three distinct factors" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/difference-series4345/1", + "solutionLink": "#", + "problemName": "Difference series" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/mega-sale1431/1", + "solutionLink": "#", + "problemName": "Mega Sale" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/substrings-with-similar-first-and-last-characters3644/1", + "solutionLink": "#", + "problemName": "Substrings with same first and last characters" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/doctors-clinic0431/1", + "solutionLink": "#", + "problemName": "Doctors Clinic" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-number-of-elements-between-two-given-elements-in-array4044/1", + "solutionLink": "#", + "problemName": "Count number of elements between two given elements in array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-call-by-reference/1", + "solutionLink": "#", + "problemName": "C++ Call by reference" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/fibonacci-to-n0811/1", + "solutionLink": "#", + "problemName": "Fibonacci to N" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-triplet-sum-in-array0129/1", + "solutionLink": "#", + "problemName": "Maximum triplet sum in array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-stl-set-5-queue/1", + "solutionLink": "#", + "problemName": "C++ STL | Set 5 (queue)" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-perfect-square5253/1", + "solutionLink": "#", + "problemName": "Check perfect square" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sorting-employees5907/1", + "solutionLink": "#", + "problemName": "Sorting Employees" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-divisible-by-114724/1", + "solutionLink": "#", + "problemName": "Check if divisible by 11" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/triplet-family/1", + "solutionLink": "#", + "problemName": "Triplet Family" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-a-number-can-be-expressed-as-xy1606/1", + "solutionLink": "#", + "problemName": "Check if a number can be expressed as x^y" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/string-reversalunpublished-for-now5324/1", + "solutionLink": "#", + "problemName": "String Reversal" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-given-four-points-form-a-square3026/1", + "solutionLink": "#", + "problemName": "Check if given four points form a square" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-stl-set-3-map/1", + "solutionLink": "#", + "problemName": "C++ STL | Set 3 (map)" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-lazy-caterers-problem2527/1", + "solutionLink": "#", + "problemName": "The Lazy Caterer's Problem" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/perfect-squares-in-a-range2253/1", + "solutionLink": "#", + "problemName": "Perfect Squares in a Range" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/snake-case0219/1", + "solutionLink": "#", + "problemName": "Snake Case" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-the-numbers2359/1", + "solutionLink": "#", + "problemName": "Digits in a set" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/map-operations/1", + "solutionLink": "#", + "problemName": "Map Operations" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-product-pair3608/1", + "solutionLink": "#", + "problemName": "Minimum product pair" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/jays-apples2724/1", + "solutionLink": "#", + "problemName": "Jay's Apples" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/difference-between-highest-and-lowest-occurrence4613/1", + "solutionLink": "#", + "problemName": "Difference between highest and lowest occurrence" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/rock-paper-scissors2830/1", + "solutionLink": "#", + "problemName": "Rock Paper Scissors!" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/replace-the-bit3212/1", + "solutionLink": "#", + "problemName": "Replace the Bit" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/change-all-even-bits-in-a-number-to-03253/1", + "solutionLink": "#", + "problemName": "Change all even bits in a number to 0" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/message-spreading4258/1", + "solutionLink": "#", + "problemName": "Message Spreading" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/make-a-distinct-digit-array2007/1", + "solutionLink": "#", + "problemName": "Make a Distinct Digit Array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/mind-game3637/1", + "solutionLink": "#", + "problemName": "Mind Game" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-number-repeating-k-times3239/1", + "solutionLink": "#", + "problemName": "Smallest number repeating K times" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/last-duplicate-element-in-a-sorted-array5539/1", + "solutionLink": "#", + "problemName": "Last duplicate element in a sorted array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/java-arraylist5312/1", + "solutionLink": "#", + "problemName": "Java Collection | Set 1 (ArrayList) Part-1" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-out-the-team0025/1", + "solutionLink": "#", + "problemName": "Binary Shift to Divide" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-perfect-square2503/1", + "solutionLink": "#", + "problemName": "Check perfect square" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/set-operations/1", + "solutionLink": "#", + "problemName": "Set Operations" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-a-speed-breaker5249/1", + "solutionLink": "#", + "problemName": "C++ | A Speed Breaker" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/strong-numbers4336/1", + "solutionLink": "#", + "problemName": "Strong Numbers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-amazing-number0459/1", + "solutionLink": "#", + "problemName": "The amazing number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-distinct-elements-15115/1", + "solutionLink": "#", + "problemName": "Sum of distinct elements for a limited range" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/strong-numbers3315/1", + "solutionLink": "#", + "problemName": "Strong Numbers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sort-the-half-sorted2157/1", + "solutionLink": "#", + "problemName": "Sort the Half Sorted" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-k-smallest-elements-in-their-original-order5407/1", + "solutionLink": "#", + "problemName": "Print K smallest elements in their original order" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/average-count-array2215/1", + "solutionLink": "#", + "problemName": "Average Count Array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/merge-and-sort5821/1", + "solutionLink": "#", + "problemName": "Merge and Sort" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/rearranging-array1648/1", + "solutionLink": "#", + "problemName": "Rearranging array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/confused-pappu5749/1", + "solutionLink": "#", + "problemName": "Confused pappu" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/zero-number2158/1", + "solutionLink": "#", + "problemName": "Duck Number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/java-anagram-strings3549/1", + "solutionLink": "#", + "problemName": "Anagram Strings" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/compare-two-large-numbers3413/1", + "solutionLink": "#", + "problemName": "Compare two Large Numbers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/regex-python/1", + "solutionLink": "#", + "problemName": "Regex - Python" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-a-string-with-spaces-intact5213/1", + "solutionLink": "#", + "problemName": "Reverse a string with spaces intact" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-digits-divisibility5311/1", + "solutionLink": "#", + "problemName": "Sum of Digits Divisibility" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-power-of-2-greater-than-or-equal-to-n2630/1", + "solutionLink": "#", + "problemName": "Smallest power of 2 greater than or equal to n" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-area2642/1", + "solutionLink": "#", + "problemName": "Maximum Area" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/shortest-un-ordered-subarray3634/1", + "solutionLink": "#", + "problemName": "Shortest un-ordered subarray" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/parties-and-seats/1", + "solutionLink": "/dsa-solutions/gfg-solutions/Basic/parties-and-seats", + "problemName": "Parties and seats" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/reducing-walls4443/1", + "solutionLink": "#", + "problemName": "Reducing Walls" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-sorted-rows2702/1", + "solutionLink": "#", + "problemName": "Count Sorted Rows" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/missing-number-in-shuffled-array0938/1", + "solutionLink": "#", + "problemName": "Missing number in shuffled array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/krishnamurthy-number1323/1", + "solutionLink": "#", + "problemName": "Krishnamurthy number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/area-of-a-triangle5739/1", + "solutionLink": "#", + "problemName": "Area of a triangle" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/celsius-to-fahrenheit-conversion5212/1", + "solutionLink": "/dsa-solutions/gfg-solutions/Basic/celsius-to-fahrenheit-conversion", + "problemName": "Celsius to Fahrenheit Conversion" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-product/1", + "solutionLink": "#", + "problemName": "Largest product" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/good-string5712/1", + "solutionLink": "#", + "problemName": "Good String" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-inheritance-introduction/1", + "solutionLink": "#", + "problemName": "C++ Inheritance introduction" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/riyas-test1450/1", + "solutionLink": "#", + "problemName": "Same frequency in two halves" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/shortest-direction4201/1", + "solutionLink": "#", + "problemName": "Shortest direction" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-numbers-divisible-by-m1524/1", + "solutionLink": "#", + "problemName": "Count numbers divisible by M" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-a-integer-is-power-of-3-or-not3850/1", + "solutionLink": "#", + "problemName": "Check an Integer is power of 3 or not" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/series-x14741/1", + "solutionLink": "#", + "problemName": "Series X1" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-spider-steps3600/1", + "solutionLink": "#", + "problemName": "The Spider Steps" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimize-sum-of-alternate-product2033/1", + "solutionLink": "#", + "problemName": "Minimize sum of alternate product" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/factors-sum2016/1", + "solutionLink": "#", + "problemName": "Factors Sum" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/finger-game1755/1", + "solutionLink": "#", + "problemName": "Finger Game" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-fifth-powers-of-the-first-n-natural-numbers3415/1", + "solutionLink": "#", + "problemName": "Sum of fifth powers of the first n natural numbers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-classes-introduction/1", + "solutionLink": "/dsa-solutions/gfg-solutions/Basic/cpp-classes-introduction", + "problemName": "C++ Classes Introduction" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/fake-profile3906/1", + "solutionLink": "#", + "problemName": "Fake Profile" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/xor-of-all-elements0736/1", + "solutionLink": "#", + "problemName": "XOR of all elements" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/product-sum3012/1", + "solutionLink": "#", + "problemName": "Product Sum" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/magical-string3653/1", + "solutionLink": "#", + "problemName": "Magical String[Duplicate Problem]" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/java-collection-set-3-hashmap/1", + "solutionLink": "#", + "problemName": "HashMap Operations" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/student-record1752/1", + "solutionLink": "#", + "problemName": "Student record" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/making-elements-distinct3139/1", + "solutionLink": "#", + "problemName": "Making elements distinct" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-integer-value1434/1", + "solutionLink": "#", + "problemName": "Maximum Integer Value " + } +] + + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GeeksforGeeks website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/basic/0301-0400.md b/problems/gfg-problems/basic/0301-0400.md new file mode 100644 index 0000000..4e7517b --- /dev/null +++ b/problems/gfg-problems/basic/0301-0400.md @@ -0,0 +1,623 @@ +--- +id: 0301-0400 +title: GFG basic problems 0301-0400 +sidebar_label: 0301-0400 +keywords: + - gfg problems + - gfg problems basic + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/ishaans-internship4400/1", + "solutionLink": "#", + "problemName": "Ishaan's Internship" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sort-first-half-in-ascending-and-second-half-in-descending1714/1", + "solutionLink": "#", + "problemName": "Sort first half in ascending and second half in descending" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sandwiched-vowels5158/1", + "solutionLink": "#", + "problemName": "Sandwiched_Vowels" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/repeated-ids0116/1", + "solutionLink": "#", + "problemName": "Repeated IDs" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/countries-at-war2936/1", + "solutionLink": "#", + "problemName": "Countries at war" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/special-series-sum0903/1", + "solutionLink": "#", + "problemName": "Special Series Sum" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/perfect-square-string5914/1", + "solutionLink": "#", + "problemName": "Perfect Square String" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/parity-of-unsigned-integer4247/1", + "solutionLink": "#", + "problemName": "Parity of unsigned integer" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/common-divisors4712/1", + "solutionLink": "#", + "problemName": "Common Divisors" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/multiply-2-matrices4144/1", + "solutionLink": "#", + "problemName": "Multiply 2 matrices" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/fibonacci-in-the-array5817/1", + "solutionLink": "#", + "problemName": "Fibonacci in the array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-zero3710/1", + "solutionLink": "#", + "problemName": "Count zero" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/java-hashmap1033/1", + "solutionLink": "#", + "problemName": "Java Collection | Set 3 (HashMap) Part-1" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/how-many-pizzas4832/1", + "solutionLink": "#", + "problemName": "How many pizzas ?" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/why-is-melody-so-chocolaty0446/1", + "solutionLink": "#", + "problemName": "Why is Melody so chocolaty?" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/squares-difference0939/1", + "solutionLink": "#", + "problemName": "Squares Difference" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/perfect-reversible-string4828/1", + "solutionLink": "#", + "problemName": "Perfect Reversible String" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/java-iterator2702/1", + "solutionLink": "#", + "problemName": "Java Iterator" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-divisible-by-52730/1", + "solutionLink": "#", + "problemName": "Check if divisible by 5" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-perimeter-of-triangle-from-array4322/1", + "solutionLink": "#", + "problemName": "Maximum Perimeter of Triangle from array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/repeated-sum-of-digits3955/1", + "solutionLink": "#", + "problemName": "Repeated sum of digits" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/tough-competitors0540/1", + "solutionLink": "#", + "problemName": "Tough Competitors" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/equal-sum-and-xor/1", + "solutionLink": "#", + "problemName": "Equal Sum and XOR" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-divisors3601/1", + "solutionLink": "#", + "problemName": "Sum of divisors" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/a-guy-with-a-mental-problem1604/1", + "solutionLink": "#", + "problemName": "A guy with a mental problem" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/perfect-array2344/1", + "solutionLink": "#", + "problemName": "Perfect Array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-position-of-m-th-item1723/1", + "solutionLink": "#", + "problemName": "Find the position of M-th item" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-stl-set-6-set/1", + "solutionLink": "#", + "problemName": "C++ STL | Set 6 (set)" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-or-gate3122/1", + "solutionLink": "#", + "problemName": "The OR Gate" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-stl-set-8-unordered-set/1", + "solutionLink": "#", + "problemName": "C++ STL | Set 8 (unordered set)" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-stl-set-4-stack/1", + "solutionLink": "#", + "problemName": "C++ STL | Set 4 (stack)" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-diagonals-1587115621/1", + "solutionLink": "#", + "problemName": "Sum of diagonals" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/pattern-13116/1", + "solutionLink": "#", + "problemName": "Pattern-1" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/even-occurring-elements4332/1", + "solutionLink": "#", + "problemName": "Even occurring elements" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-binary-string0402/1", + "solutionLink": "#", + "problemName": "Check Binary String" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/elements-before-which-no-element-is-bigger0602/1", + "solutionLink": "#", + "problemName": "Elements before which no element is bigger" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/product-of-factors-of-number4757/1", + "solutionLink": "#", + "problemName": "Product of factors of number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/disarium-number1045/1", + "solutionLink": "#", + "problemName": "Disarium Number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/multiples-power2816/1", + "solutionLink": "#", + "problemName": "Multiples Power" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/friendly-array2009/1", + "solutionLink": "#", + "problemName": "Friendly Array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-sum-of-even-factors-of-a-number1725/1", + "solutionLink": "#", + "problemName": "Find sum of even factors of a number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-pairs-odd-xor0308/1", + "solutionLink": "#", + "problemName": "Count Pairs Odd Xor" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-digits-prime-non-prime1935/1", + "solutionLink": "#", + "problemName": "Sum of Digits Prime/Non-Prime " + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-divisible-by-363149/1", + "solutionLink": "#", + "problemName": "Check if divisible by 36" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/pronic-number0729/1", + "solutionLink": "#", + "problemName": "Pronic Number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-sequence1346/1", + "solutionLink": "#", + "problemName": "Find The Sequence" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-sum-of-two-elements-from-two-arrays0253/1", + "solutionLink": "#", + "problemName": "Minimum sum of two elements from two arrays" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-min-conversion5257/1", + "solutionLink": "#", + "problemName": "Max-Min conversion" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-remainder1439/1", + "solutionLink": "#", + "problemName": "Find the remainder " + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-and-gate1231/1", + "solutionLink": "#", + "problemName": "The AND Gate" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/square-divisors4319/1", + "solutionLink": "#", + "problemName": "Square Divisors" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/ones-complement5928/1", + "solutionLink": "#", + "problemName": "One's Complement" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/lcm-of-given-array-elements3919/1", + "solutionLink": "#", + "problemName": "LCM of given array elements" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/tiger-zinda-hai5531/1", + "solutionLink": "#", + "problemName": "Tiger Zinda Hai" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/composite-series1258/1", + "solutionLink": "#", + "problemName": "Composite Series" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/special-odd-series-sum1235/1", + "solutionLink": "#", + "problemName": "Special Odd Series Sum" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/jumpy-ball1449/1", + "solutionLink": "#", + "problemName": "Jumpy Ball" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-the-characters-in-each-word-in-a-given-sentence3451/1", + "solutionLink": "#", + "problemName": "Count the characters in each word in a given sentence" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-substring-from-last-of-the-given-string3440/1", + "solutionLink": "#", + "problemName": "Find Substring from last of the Given String" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/ishaans-weight0106/1", + "solutionLink": "#", + "problemName": "Geek's Weight" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/factor-or-multiple1128/1", + "solutionLink": "#", + "problemName": "Factor OR Multiple" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/2s-complement3124/1", + "solutionLink": "#", + "problemName": "2's Complement" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/difference-between-sums-of-odd-and-even-digits2837/1", + "solutionLink": "#", + "problemName": "Difference between sums of odd and even digits" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/factorial-number2446/1", + "solutionLink": "#", + "problemName": "Factorial Number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangle-growing-downwards2344/1", + "solutionLink": "#", + "problemName": "Triangle growing downwards" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-large-numbers5827/1", + "solutionLink": "#", + "problemName": "Sum of large numbers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/wrong-ball5239/1", + "solutionLink": "#", + "problemName": "Wrong Ball" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-number-of-days-between-two-given-dates5400/1", + "solutionLink": "#", + "problemName": "Find number of days between two given dates" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-xor-gate0918/1", + "solutionLink": "#", + "problemName": "The XOR Gate" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/perfect-cubes-in-a-range3933/1", + "solutionLink": "#", + "problemName": "Perfect Cubes in a Range" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/gray-code4907/1", + "solutionLink": "#", + "problemName": "Gray Code " + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/java-interface/1", + "solutionLink": "#", + "problemName": "Java Interface" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/java-collection-set-4-treemap/1", + "solutionLink": "#", + "problemName": "TreeMap Operations" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-modulo-task1736/1", + "solutionLink": "#", + "problemName": "The Modulo Task" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-weight-difference5036/1", + "solutionLink": "#", + "problemName": "Maximum weight difference" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/evaluate-the-expression0307/1", + "solutionLink": "#", + "problemName": "Evaluate the expression" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/total-distance-travelled-in-an-array3628/1", + "solutionLink": "#", + "problemName": "Total distance travelled in an array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/k-th-distinct-element4510/1", + "solutionLink": "#", + "problemName": "K-th distinct element" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/kings-war2448/1", + "solutionLink": "#", + "problemName": "King's War" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/xor-play1544/1", + "solutionLink": "#", + "problemName": "XOR play" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/stuffs-division5735/1", + "solutionLink": "#", + "problemName": "Stuffs Division" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/trimorphic-number3553/1", + "solutionLink": "#", + "problemName": "Trimorphic Number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-the-common-elements/1", + "solutionLink": "#", + "problemName": "Sum the common elements" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/strange-sort4316/1", + "solutionLink": "#", + "problemName": "Strange Sort - copy" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-consecutives1030/1", + "solutionLink": "#", + "problemName": "Sum of Consecutives" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/interesting-patterns1430/1", + "solutionLink": "#", + "problemName": "Interesting Patterns" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/string-of-commons4503/1", + "solutionLink": "#", + "problemName": "String of Commons" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-stl-set-7-unordered-map/1", + "solutionLink": "#", + "problemName": "C++ STL | Set 7 (unordered map)" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/tracks0436/1", + "solutionLink": "#", + "problemName": "Tracks" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-whether-two-numbers-differ-at-one-bit-position-only3415/1", + "solutionLink": "#", + "problemName": "Check whether two numbers differ at one bit position only" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-muskteers3519/1", + "solutionLink": "#", + "problemName": "The Muskteers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/is-digital-root-of-n-a-prime2522/1", + "solutionLink": "#", + "problemName": "Is digital root of N a prime?" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/crazy-string1157/1", + "solutionLink": "#", + "problemName": "Crazy String" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/corner-digits1317/1", + "solutionLink": "#", + "problemName": "Corner Digits Sum" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/floating-point-number-even-or-odd0146/1", + "solutionLink": "#", + "problemName": "Floating point number even or odd" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/got-tv-series3124/1", + "solutionLink": "#", + "problemName": "set-bits and number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/modulus-of-two-double-numbers5159/1", + "solutionLink": "#", + "problemName": "Modulus of two double numbers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/distinct-elements-in-a-stream1557/1", + "solutionLink": "#", + "problemName": "Distinct Elements in a Stream" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/multiple-in-table-tennis3310/1", + "solutionLink": "#", + "problemName": "Face off Tournament" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/message-decoding4305/1", + "solutionLink": "#", + "problemName": "Message decoding" + } +] + + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/basic/0401-0500.md b/problems/gfg-problems/basic/0401-0500.md new file mode 100644 index 0000000..49d5420 --- /dev/null +++ b/problems/gfg-problems/basic/0401-0500.md @@ -0,0 +1,623 @@ +--- +id: 0401-0500 +title: GFG basic problems 0401-0500 +sidebar_label: 0401-0500 +keywords: + - gfg problems + - gfg problems basic + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-stl-deque/1", + "solutionLink": "#", + "problemName": "C++ STL Deque" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sort-the-fest0016/1", + "solutionLink": "#", + "problemName": "Sort the fest" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-terms-nth-row3128/1", + "solutionLink": "#", + "problemName": "Sum Terms Nth Row" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/ladoo-problem2929/1", + "solutionLink": "#", + "problemName": "Ladoo problem" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/tywins-war-strategy0527/1", + "solutionLink": "#", + "problemName": "Tywin's War Strategy" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-all-sub-sequences-of-a-number3437/1", + "solutionLink": "#", + "problemName": "Sum of all sub-sequences of a number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/prime-number-validation-java-regex0450/1", + "solutionLink": "#", + "problemName": "Prime number validation-JAVA regex" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/tidy-number0519/1", + "solutionLink": "#", + "problemName": "Tidy Number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/xor-count-zero-and-one2724/1", + "solutionLink": "#", + "problemName": "XOR Count Zero and One" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/extraction-of-secret-message0616/1", + "solutionLink": "#", + "problemName": "Extraction of secret message" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-odd-sum0651/1", + "solutionLink": "#", + "problemName": "Max Odd Sum" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/no-of-carry-operations0456/1", + "solutionLink": "#", + "problemName": "No of Carry Operations " + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/reading-books3803/1", + "solutionLink": "#", + "problemName": "Reading books" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-equal-prefix3139/1", + "solutionLink": "#", + "problemName": "Longest Equal Prefix" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/ishwar-and-his-proposals1140/1", + "solutionLink": "#", + "problemName": "Ishwar and his proposals" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-integer-solutions2458/1", + "solutionLink": "#", + "problemName": "Number of Integer solutions" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/swapping-triangles5209/1", + "solutionLink": "#", + "problemName": "Swapping Triangles" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/stable-sort-and-position1359/1", + "solutionLink": "#", + "problemName": "Stable Sort and Position" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/repated-sum-and-then-multiply1046/1", + "solutionLink": "#", + "problemName": "Repeated Sum and then Multiply" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/dull-jack1909/1", + "solutionLink": "#", + "problemName": "Dull Jack" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-triangle-for-given-array1159/1", + "solutionLink": "#", + "problemName": "Sum Triangle for given array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sophie-germain-prime2014/1", + "solutionLink": "#", + "problemName": "Sophie Germain Prime" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/just-one-mismatch1714/1", + "solutionLink": "#", + "problemName": "Just One Mismatch" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/total-digits4030/1", + "solutionLink": "#", + "problemName": "Total digits" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/distinct-adjacent-element2121/1", + "solutionLink": "#", + "problemName": "Distinct Adjacent Element" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/nth-digit-of-fibonacci1449/1", + "solutionLink": "#", + "problemName": "nth digit of Fibonacci " + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-maximum-number-of-handshakes2349/1", + "solutionLink": "#", + "problemName": "Maximum Handshakes" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/narcissistic-number4852/1", + "solutionLink": "#", + "problemName": "Narcissistic number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-sum-of-factors5829/1", + "solutionLink": "#", + "problemName": "Minimum sum of factors" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/prime-palindrome-sum3700/1", + "solutionLink": "#", + "problemName": "Prime Palindrome Sum" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/convert-from-any-base-to-decimal3736/1", + "solutionLink": "#", + "problemName": "Convert from any base to decimal" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/learning-output4058/1", + "solutionLink": "#", + "problemName": "Learning Output" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/java-collections-set-9-queue/1", + "solutionLink": "#", + "problemName": "Java Collections | Set 9 (Queue)" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/weak-maths0559/1", + "solutionLink": "#", + "problemName": "Smallest number with maximum and minimum divisor in an array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/first-and-last-bit2357/1", + "solutionLink": "#", + "problemName": "First and last Bit" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/java-collection-set-5-linkedhash-set/1", + "solutionLink": "#", + "problemName": "Java Collection | Set 5 (LinkedHash Set)" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-digit-modified1409/1", + "solutionLink": "#", + "problemName": "Sum of Digit Modified" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/even-odd-turn-game1832/1", + "solutionLink": "#", + "problemName": "Even-Odd turn game" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/odd-divisors5347/1", + "solutionLink": "#", + "problemName": "Odd Divisors" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/adam-number2650/1", + "solutionLink": "#", + "problemName": "Adam Number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/powers-game3701/1", + "solutionLink": "#", + "problemName": "Powers game" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-move-to-front-operations2232/1", + "solutionLink": "#", + "problemName": "Minimum move to front operations" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-digits-in-given-number-n-which-divide-n3331/1", + "solutionLink": "#", + "problemName": "Count digits in given number N which divide N" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/demonitisation0013/1", + "solutionLink": "#", + "problemName": "Demonitisation" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/azad-and-chocolates4845/1", + "solutionLink": "#", + "problemName": "Buy chocolates and save N rupees" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/finding-pairs2835/1", + "solutionLink": "#", + "problemName": "Finding-Pairs" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/make-coprime-array3058/1", + "solutionLink": "#", + "problemName": "Make Co-prime Array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/long-long-decimal4552/1", + "solutionLink": "#", + "problemName": "Long Long Decimal" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-distance3248/1", + "solutionLink": "#", + "problemName": "Maximum distance" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/equalization-of-an-array1656/1", + "solutionLink": "#", + "problemName": "Equalization of an array" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/java-date-and-day5024/1", + "solutionLink": "#", + "problemName": "Java Date and Day" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/java-generic-class/1", + "solutionLink": "#", + "problemName": "Java Generic Class" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/cricket-average2031/1", + "solutionLink": "#", + "problemName": "Cricket Average" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/mrs-s-java-bits-set-1/1", + "solutionLink": "#", + "problemName": "Mrs. S- JAVA Bits Set 1" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-number-of-equal-pairs-in-a-string0520/1", + "solutionLink": "#", + "problemName": "Count number of equal pairs in a string" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-date-is-valid0050/1", + "solutionLink": "#", + "problemName": "Check if date is valid" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/jumping-geek3420/1", + "solutionLink": "#", + "problemName": "Jumping Geek" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-x-and-y-in-linear-equation1334/1", + "solutionLink": "#", + "problemName": "Find X and Y in Linear Equation" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/an-easy-problem0811/1", + "solutionLink": "#", + "problemName": "An Easy problem" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/divide-the-number5320/1", + "solutionLink": "#", + "problemName": "Divide the number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/rahul-lucky-unlucky5101/1", + "solutionLink": "#", + "problemName": "Rahul lucky-unlucky" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/product-of-digits4348/1", + "solutionLink": "#", + "problemName": "Numbers having alternate bits" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/carol-number4645/1", + "solutionLink": "#", + "problemName": "Carol Number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/set-all-odd-bits1900/1", + "solutionLink": "#", + "problemName": "Set all odd bits" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/starting-point0909/1", + "solutionLink": "#", + "problemName": "Starting Point" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/ishaans-sum-problem0934/1", + "solutionLink": "#", + "problemName": "Ishaan's Sum Problem" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-remaining-cake1349/1", + "solutionLink": "#", + "problemName": "The Remaining Cake" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/dr-stranges-powers3333/1", + "solutionLink": "#", + "problemName": "Binary Addition of 1" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/binary-representation-of-previous-number0638/1", + "solutionLink": "#", + "problemName": "Binary representation of previous number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-sets5648/1", + "solutionLink": "#", + "problemName": "C++ Sets" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/weird-number0933/1", + "solutionLink": "#", + "problemName": "Weird Number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-nth-number-in-the-sequence2245/1", + "solutionLink": "#", + "problemName": "Find the nth number in the sequence " + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/numbers-containing-0s-from-1-to-n4704/1", + "solutionLink": "#", + "problemName": "Numbers containing 0's from 1 to N" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/rectangle-number4650/1", + "solutionLink": "#", + "problemName": "Rectangle Number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/evaluate-the-x-a-b-statement0744/1", + "solutionLink": "#", + "problemName": "Evaluate the x + a = b statement" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/flying-jet4644/1", + "solutionLink": "#", + "problemName": "Flying Jet" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-for-three-consecutive-numbers5729/1", + "solutionLink": "#", + "problemName": "Check for three consecutive numbers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/point-lies-or-not0417/1", + "solutionLink": "#", + "problemName": "Point lies or not" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/gcd-lcm-and-distributive-property4419/1", + "solutionLink": "#", + "problemName": "GCD, LCM and Distributive Property" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/invert-the-bits2942/1", + "solutionLink": "#", + "problemName": "Invert the Bits" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/chocolate-lengths0332/1", + "solutionLink": "#", + "problemName": "Chocolate lengths" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-k-digit-number-divisible-by-x2351/1", + "solutionLink": "#", + "problemName": "Smallest K digit number divisible by X" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-cycle-game4441/1", + "solutionLink": "#", + "problemName": "The Cycle Game" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-series3015/1", + "solutionLink": "#", + "problemName": "Number Series" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/different-ways-to-spell-a-number4014/1", + "solutionLink": "#", + "problemName": "Spell a Number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-number-system4241/1", + "solutionLink": "#", + "problemName": "Decimal to Base K conversion" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/help-joey5246/1", + "solutionLink": "#", + "problemName": "Help Joey" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-squares2421/1", + "solutionLink": "#", + "problemName": "Check squares" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/palindrome-in-both-decimal-and-binary4517/1", + "solutionLink": "#", + "problemName": "Palindrome in both Decimal and Binary" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/indias-unique-railway-track0906/1", + "solutionLink": "#", + "problemName": "India's unique railway tracks" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/encoding-names1310/1", + "solutionLink": "#", + "problemName": "Encoding names" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/extended-euclidean-algorithm3848/1", + "solutionLink": "#", + "problemName": "Extended Euclidean Algorithm" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-subarray-with-gcd-one4535/1", + "solutionLink": "#", + "problemName": "Largest subarray with GCD one" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximize-or0509/1", + "solutionLink": "#", + "problemName": "Maximize OR" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-nega-bit2019/1", + "solutionLink": "#", + "problemName": "C++ Nega Bit" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/pattern-for-reverse-character-bridge5738/1", + "solutionLink": "#", + "problemName": "Pattern for Reverse Character Bridge" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/min-value-of-x2252/1", + "solutionLink": "#", + "problemName": "Min value of x" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/base-conversion0924/1", + "solutionLink": "#", + "problemName": "Base Conversion" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/akash-and-friend5145/1", + "solutionLink": "#", + "problemName": "Akash and Friend" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/difficult-problems1303/1", + "solutionLink": "#", + "problemName": "Difficult Problems" + } +] + + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GeeksforGeeks website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/basic/0501-0525.md b/problems/gfg-problems/basic/0501-0525.md new file mode 100644 index 0000000..c215550 --- /dev/null +++ b/problems/gfg-problems/basic/0501-0525.md @@ -0,0 +1,173 @@ +--- +id: 0501-0525 +title: GFG basic problems 0501-0525 +sidebar_label: 0501-0525 +keywords: + - gfg problems + - gfg problems basic + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/multiple-of-x-closest-to-n1719/1", + "solutionLink": "#", + "problemName": "Multiple of N closest to X" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/java-collections-set-8-treeset/1", + "solutionLink": "#", + "problemName": "Java Collections | Set 8 (TreeSet)" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/biggest-integer-having-maximum-digit-sum1704/1", + "solutionLink": "#", + "problemName": "Biggest integer having maximum digit sum" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/lucky-number-and-a-sum0329/1", + "solutionLink": "#", + "problemName": "Lucky number and a sum" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/metro-problem3513/1", + "solutionLink": "#", + "problemName": "Metro Problem" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/gray-to-binary-and-binary-to-gray5518/1", + "solutionLink": "#", + "problemName": "Gray to Binary and Binary to Gray " + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-the-number-of-elements-in-array-1-for-each-element-of-the-array-22903/1", + "solutionLink": "#", + "problemName": "Numbers having two adjacent set bits" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/nth-multiple/1", + "solutionLink": "#", + "problemName": "Nth Multiple" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-all-subsets-formed-by-first-n-natural-numbers0603/1", + "solutionLink": "#", + "problemName": "Sum of all subsets formed by first N natural numbers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/finding-dory3455/1", + "solutionLink": "#", + "problemName": "Finding Dory" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/make-the-hit-in-power-game3729/1", + "solutionLink": "#", + "problemName": "Make the hit in power game !" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/line-passing-through-2-points5031/1", + "solutionLink": "#", + "problemName": "Line passing through 2 points" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/human-and-the-tower5254/1", + "solutionLink": "#", + "problemName": "Human and the tower" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/generate-all-cyclic-permutations-of-a-number2921/1", + "solutionLink": "#", + "problemName": "Generate all cyclic permutations of a number" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-rotations-divisible-by-43523/1", + "solutionLink": "#", + "problemName": "Count rotations divisible by 4" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/euler-totient-sum-and-divisors5501/1", + "solutionLink": "#", + "problemName": "Euler Totient Sum and Divisors" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/distance-and-displacement4145/1", + "solutionLink": "#", + "problemName": "Distance and Displacement" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/search-for-traitor5950/1", + "solutionLink": "#", + "problemName": "Find the safe position" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/binary-fraction-to-decimal4656/1", + "solutionLink": "#", + "problemName": "Binary fraction to decimal" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/product-of-complex-numbers1426/1", + "solutionLink": "#", + "problemName": "Product of Complex Numbers" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-unique-rectangles1849/1", + "solutionLink": "#", + "problemName": "Number of unique rectangles" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-number-of-digits-after-decimal1516/1", + "solutionLink": "#", + "problemName": "Count number of digits after decimal" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/rotate-page0923/1", + "solutionLink": "#", + "problemName": "Rotate Page" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/frobenius-coin-problem5532/1", + "solutionLink": "#", + "problemName": "Frobenius coin problem" + }, + { + "difficulty": "Basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/lucky-number-22638/1", + "solutionLink": "#", + "problemName": "Lucky Number-2" + } +] + + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GeeksforGeeks website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/basic/problems.md b/problems/gfg-problems/basic/problems.md new file mode 100644 index 0000000..3482553 --- /dev/null +++ b/problems/gfg-problems/basic/problems.md @@ -0,0 +1,81 @@ +--- +id: problems +title: GFG basic problems +sidebar_label: problems +keywords: + - gfg problems + - gfg problems basic + - gfg problems problems +--- + +export const problems = [ + { + "problemName": "1. Inorder Traversal", + "difficulty": "basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/inorder-traversal/0", + "solutionLink": "#" + }, + { + "problemName": "2. Preorder Traversal", + "difficulty": "basic", + "gfgLink": "https://geeksforgeeks.org/problems/preorder-traversal/0", + "solutionLink": "#" + }, + { + "problemName": "3. Peak element", + "difficulty": "basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/peak-element/0", + "solutionLink": "#" + }, + { + "problemName": "4. Minimum-element-in-bst", + "difficulty": "basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-element-in-bst/0", + "solutionLink": "#" + }, + { + "problemName": "5. Find-nk-th-node-in-linked-list", + "difficulty": "basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-nk-th-node-in-linked-list/0", + "solutionLink": "#" + }, + { + "problemName": "6. Power-of-2", + "difficulty": "basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/power-of-2-1587115620/0", + "solutionLink": "#" + }, + { + "problemName": "7. Search-an-element-in-an-array", + "difficulty": "basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/search-an-element-in-an-array-1587115621/0", + "solutionLink": "#" + }, + { + "problemName": "8. Print-first-n-fibonacci-numbers", + "difficulty": "basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-first-n-fibonacci-numbers1002/0", + "solutionLink": "#" + }, + { + "problemName": "9. Find minimum and maximum element in an array", + "difficulty": "basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-minimum-and-maximum-element-in-an-array4428/0", + "solutionLink": "#" + }, + { + "problemName": "10. Factorial-number", + "difficulty": "basic", + "gfgLink": "https://www.geeksforgeeks.org/problems/factorial-number2446/0", + "solutionLink": "#" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GFG website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/easy/0001-0100.md b/problems/gfg-problems/easy/0001-0100.md new file mode 100644 index 0000000..e303db6 --- /dev/null +++ b/problems/gfg-problems/easy/0001-0100.md @@ -0,0 +1,622 @@ +--- +id: 0001-0100 +title: GFG easy problems 0001-0100 +sidebar_label: 0001-0100 +keywords: + - gfg problems + - gfg problems easy + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/missing-number-in-array1416/1", + "solutionLink": "#", + "problemName": "Missing number in array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-duplicates-in-an-array/1", + "solutionLink": "#", + "problemName": "Find duplicates in an array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/leaders-in-an-array-1587115620/1", + "solutionLink": "#", + "problemName": "Leaders in an array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/equilibrium-point-1587115620/1", + "solutionLink": "#", + "problemName": "Equilibrium Point" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/parenthesis-checker2744/1", + "solutionLink": "#", + "problemName": "Parenthesis Checker" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/second-largest3735/1", + "solutionLink": "#", + "problemName": "Second Largest" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-for-bst/1", + "solutionLink": "#", + "problemName": "Check for BST" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/left-view-of-binary-tree/1", + "solutionLink": "#", + "problemName": "Left View of Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/1", + "solutionLink": "#", + "problemName": "Count pairs with given sum" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/nth-node-from-end-of-linked-list/1", + "solutionLink": "#", + "problemName": "Nth node from end of linked list" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/common-elements1132/1", + "solutionLink": "#", + "problemName": "Common elements" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/bfs-traversal-of-graph/1", + "solutionLink": "#", + "problemName": "BFS of graph" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/palindrome-string0817/1", + "solutionLink": "#", + "problemName": "Palindrome String" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/rotate-array-by-n-elements-1587115621/1", + "solutionLink": "#", + "problemName": "Rotate Array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/finding-middle-element-in-a-linked-list/1", + "solutionLink": "#", + "problemName": "Finding middle element in a linked list" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/nth-fibonacci-number1335/1", + "solutionLink": "#", + "problemName": "Nth Fibonacci Number" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/anagram-1587115620/1", + "solutionLink": "#", + "problemName": "Anagram" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-words-in-a-given-string5459/1", + "solutionLink": "#", + "problemName": "Reverse words in a given string" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-for-balanced-tree/1", + "solutionLink": "#", + "problemName": "Check for Balanced Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-a-linked-list/1", + "solutionLink": "#", + "problemName": "Reverse a linked list" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-duplicate-element-from-sorted-linked-list/1", + "solutionLink": "#", + "problemName": "Remove duplicate element from sorted Linked List" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/height-of-binary-tree/1", + "solutionLink": "#", + "problemName": "Height of Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/key-pair5616/1", + "solutionLink": "#", + "problemName": "Key Pair" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-transition-point-1587115620/1", + "solutionLink": "#", + "problemName": "Find Transition Point" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/determine-if-two-trees-are-identical/1", + "solutionLink": "#", + "problemName": "Determine if Two Trees are Identical" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/frequency-of-array-elements-1587115620/1", + "solutionLink": "#", + "problemName": "Frequencies of Limited Range Array Elements" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-common-prefix-in-an-array5129/1", + "solutionLink": "#", + "problemName": "Longest Common Prefix in an Array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/depth-first-traversal-for-a-graph/1", + "solutionLink": "#", + "problemName": "DFS of Graph" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/wave-array-1587115621/1", + "solutionLink": "#", + "problemName": "Wave Array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/first-repeating-element4018/1", + "solutionLink": "#", + "problemName": "First Repeating Element" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-pair-given-difference1559/1", + "solutionLink": "#", + "problemName": "Find Pair Given Difference" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-distance-between-two-numbers/1", + "solutionLink": "#", + "problemName": "Minimum distance between two numbers" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/floor-in-a-sorted-array-1587115620/1", + "solutionLink": "#", + "problemName": "Floor in a Sorted Array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-duplicate-elements-from-sorted-array/1", + "solutionLink": "#", + "problemName": "Remove duplicate elements from sorted Array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-duplicates-from-an-unsorted-linked-list/1", + "solutionLink": "#", + "problemName": "Remove duplicates from an unsorted linked list" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/n-meetings-in-one-room-1587115620/1", + "solutionLink": "#", + "problemName": "N meetings in one room" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/chocolate-distribution-problem3825/1", + "solutionLink": "#", + "problemName": "Chocolate Distribution Problem" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximize-arrii-of-an-array0026/1", + "solutionLink": "#", + "problemName": "Maximize sum(arr[i]*i) of an Array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-string-is-rotated-by-two-places-1587115620/1", + "solutionLink": "#", + "problemName": "Check if string is rotated by two places" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/non-repeating-character-1587115620/1", + "solutionLink": "#", + "problemName": "Non Repeating Character" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/level-order-traversal-in-spiral-form/1", + "solutionLink": "#", + "problemName": "Level order traversal in spiral form" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/product-array-puzzle4525/1", + "solutionLink": "#", + "problemName": "Product array puzzle" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/delete-without-head-pointer/1", + "solutionLink": "#", + "problemName": "Delete without head pointer" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/level-order-traversal/1", + "solutionLink": "#", + "problemName": "Level order traversal" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/delete-a-node-in-single-linked-list/1", + "solutionLink": "#", + "problemName": "Delete a Node in Single Linked List" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/first-element-to-occur-k-times5150/1", + "solutionLink": "#", + "problemName": "First element to occur k times" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-the-triplets4615/1", + "solutionLink": "#", + "problemName": "Count the triplets" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-an-array-is-sorted0701/1", + "solutionLink": "#", + "problemName": "Check if array is sorted" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/square-root/1", + "solutionLink": "#", + "problemName": "Square root of a number" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/intersection-of-two-arrays2404/1", + "solutionLink": "#", + "problemName": "Intersection of two arrays" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-cost-of-ropes-1587115620/1", + "solutionLink": "#", + "problemName": "Minimum Cost of ropes" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/move-all-zeroes-to-end-of-array0751/1", + "solutionLink": "#", + "problemName": "Move all zeroes to end of array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/isomorphic-strings-1587115620/1", + "solutionLink": "#", + "problemName": "Isomorphic Strings" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/mirror-tree/1", + "solutionLink": "#", + "problemName": "Mirror Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/arithmetic-number2815/1", + "solutionLink": "#", + "problemName": "Arithmetic Number" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-all-nodes-that-dont-have-sibling/1", + "solutionLink": "#", + "problemName": "Print all nodes that don't have sibling" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/right-view-of-binary-tree/1", + "solutionLink": "#", + "problemName": "Right View of Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/bubble-sort/1", + "solutionLink": "#", + "problemName": "Bubble Sort" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/given-a-linked-list-of-0s-1s-and-2s-sort-it/1", + "solutionLink": "#", + "problemName": "Given a linked list of 0s, 1s and 2s, sort it." + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/roman-number-to-integer3201/1", + "solutionLink": "#", + "problemName": "Roman Number to Integer" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/array-of-alternate-ve-and-ve-nos1401/1", + "solutionLink": "#", + "problemName": "Alternate positive and negative numbers" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/perfect-numbers3207/1", + "solutionLink": "#", + "problemName": "Perfect Numbers" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/rotation4723/1", + "solutionLink": "#", + "problemName": "Rotation" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-digits5716/1", + "solutionLink": "#", + "problemName": "Count Digits" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-strings-are-rotations-of-each-other-or-not-1587115620/1", + "solutionLink": "#", + "problemName": "Check if strings are rotations of each other or not" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/three-way-partitioning/1", + "solutionLink": "#", + "problemName": "Three way partitioning" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-whether-k-th-bit-is-set-or-not-1587115620/1", + "solutionLink": "#", + "problemName": "Check whether K-th bit is set or not" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-first-set-bit-1587115620/1", + "solutionLink": "#", + "problemName": "Find first set bit" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/insert-a-node-in-a-bst/1", + "solutionLink": "#", + "problemName": "Insert a node in a BST" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/implement-two-stacks-in-an-array/1", + "solutionLink": "#", + "problemName": "Implement two stacks in an array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-all-pairs-whose-sum-is-x5808/1", + "solutionLink": "#", + "problemName": "Find all pairs with a given sum" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/kth-largest-element-in-bst/1", + "solutionLink": "#", + "problemName": "Kth largest element in BST" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/symmetric-tree/1", + "solutionLink": "#", + "problemName": "Symmetric Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-bst/1", + "solutionLink": "#", + "problemName": "Lowest Common Ancestor in a BST" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-sum-subarray-of-size-k5313/1", + "solutionLink": "#", + "problemName": "Max Sum Subarray of size K" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-number-of-hops-1587115620/1", + "solutionLink": "#", + "problemName": "Count number of hops" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-length-of-loop/1", + "solutionLink": "#", + "problemName": "Find length of Loop" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/stack-using-two-queues/1", + "solutionLink": "#", + "problemName": "Stack using two queues" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/delete-nodes-having-greater-value-on-right/1", + "solutionLink": "#", + "problemName": "Delete nodes having greater value on right" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/intersection-of-two-sorted-linked-lists/1", + "solutionLink": "#", + "problemName": "Intersection of two sorted Linked lists" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-level-order-traversal/1", + "solutionLink": "#", + "problemName": "Reverse Level Order Traversal" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-number-possible5028/1", + "solutionLink": "#", + "problemName": "Largest number possible" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/set-bits0143/1", + "solutionLink": "#", + "problemName": "Number of 1 Bits" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/insertion-sort/1", + "solutionLink": "#", + "problemName": "Insertion Sort" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/delete-middle-element-of-a-stack/1", + "solutionLink": "#", + "problemName": "Delete middle element of a stack" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/queue-using-two-stacks/1", + "solutionLink": "#", + "problemName": "Queue using two Stacks" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/insert-in-a-sorted-list/1", + "solutionLink": "#", + "problemName": "Insert in a Sorted List" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/unsorted-array4925/1", + "solutionLink": "#", + "problemName": "Element with left side smaller and right side greater" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/search-in-a-matrix17201720/1", + "solutionLink": "#", + "problemName": "Search in a matrix" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-value-in-a-bitonic-array3001/1", + "solutionLink": "#", + "problemName": "Bitonic Point" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/pairwise-swap-elements-of-a-linked-list-by-swapping-data/1", + "solutionLink": "#", + "problemName": "Pairwise swap elements of a linked list" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/delete-middle-of-linked-list/1", + "solutionLink": "#", + "problemName": "Delete Middle of Linked List" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-first-k-elements-of-queue/1", + "solutionLink": "#", + "problemName": "Reverse First K elements of Queue" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-adjacency-list-1587115620/1", + "solutionLink": "#", + "problemName": "Print adjacency list" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-subarray-with-sum-greater-than-x5651/1", + "solutionLink": "#", + "problemName": "Smallest subarray with sum greater than x" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/leaf-at-same-level/1", + "solutionLink": "#", + "problemName": "Check if all leaves are at same level" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/move-all-negative-elements-to-end1813/1", + "solutionLink": "#", + "problemName": "Move all negative elements to end" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-distinct-characters-in-string5848/1", + "solutionLink": "#", + "problemName": "Longest Distinct characters in string" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/convert-array-into-zig-zag-fashion1638/1", + "solutionLink": "#", + "problemName": "Convert array into Zig-Zag fashion" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/queue-reversal/1", + "solutionLink": "#", + "problemName": "Queue Reversal" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GFG website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/easy/0101-0200.md b/problems/gfg-problems/easy/0101-0200.md new file mode 100644 index 0000000..425d799 --- /dev/null +++ b/problems/gfg-problems/easy/0101-0200.md @@ -0,0 +1,622 @@ +--- +id: 0101-0200 +title: GFG easy problems 0101-0200 +sidebar_label: 0101-0200 +keywords: + - gfg problems + - gfg problems easy + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-distinct-elements-in-every-window/1", + "solutionLink": "/dsa-solutions/gfg-solutions/easy/count-distinct-elements-in-every-window", + "problemName": "Count distinct elements in every window" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/inorder-successor-in-bst/1", + "solutionLink": "/dsa-solutions/gfg-solutions/easy/inorder-successor-in-bst", + "problemName": "Inorder Successor in BST" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/index-of-an-extra-element/1", + "solutionLink": "/dsa-solutions/gfg-solutions/easy/index-of-an-extra-element", + "problemName": "Index of an Extra Element" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/armstrong-numbers2727/1", + "solutionLink": "/dsa-solutions/gfg-solutions/easy/armstrong-numbers", + "problemName": "Armstrong Numbers" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-a-doubly-linked-list/1", + "solutionLink": "/dsa-solutions/gfg-solutions/easy/reverse-a-doubly-linked-list", + "problemName": "Reverse a Doubly Linked List" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/rightmost-different-bit-1587115621/1", + "solutionLink": "/dsa-solutions/gfg-solutions/easy/rightmost-different-bit", + "problemName": "Rightmost different bit" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-duplicates3034/1", + "solutionLink": "/dsa-solutions/gfg-solutions/easy/remove-duplicates", + "problemName": "Remove Duplicates" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-the-zeros2550/1", + "solutionLink": "/dsa-solutions/gfg-solutions/easy/count-the-zeros", + "problemName": "Count the Zeros" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-pairs-whose-sum-is-equal-to-x/1", + "solutionLink": "/dsa-solutions/gfg-solutions/easy/count-pairs-whose-sum-is-equal-to-x", + "problemName": "Count Pairs whose sum is equal to X" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/is-binary-number-multiple-of-30654/1", + "solutionLink": "/dsa-solutions/gfg-solutions/easy/is-binary-number-multiple-of-3", + "problemName": "Is Binary Number Multiple of 3" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/k-distance-from-root/1", + "solutionLink": "/dsa-solutions/gfg-solutions/easy/k-distance-from-root", + "problemName": "K distance from root" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-element-occurences/1", + "solutionLink": "#", + "problemName": "Count More than n/k Occurences" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-element-in-a-sorted-and-rotated-array3611/1", + "solutionLink": "#", + "problemName": "Minimum element in a sorted and rotated array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/josephus-problem/1", + "solutionLink": "#", + "problemName": "Josephus problem" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/non-repeating-element3958/1", + "solutionLink": "#", + "problemName": "Non-Repeating Element" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/selection-sort/1", + "solutionLink": "#", + "problemName": "Selection Sort" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-nth-root-of-m5843/1", + "solutionLink": "#", + "problemName": "Find Nth root of M" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/root-to-leaf-path-sum/1", + "solutionLink": "#", + "problemName": "Root to leaf path sum" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/boundary-traversal-of-matrix-1587115620/1", + "solutionLink": "#", + "problemName": "Boundary traversal of matrix" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-optimum-operation4504/1", + "solutionLink": "#", + "problemName": "Minimum Operations" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/transpose-of-matrix-1587115621/1", + "solutionLink": "#", + "problemName": "Transpose of Matrix" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-a-string-using-stack/1", + "solutionLink": "#", + "problemName": "Reverse a string using Stack" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/precise-fomat-java/1", + "solutionLink": "#", + "problemName": "Precise Format - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/trailing-zeroes-in-factorial5134/1", + "solutionLink": "#", + "problemName": "Trailing zeroes in factorial" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-all-duplicates-from-a-given-string4321/1", + "solutionLink": "#", + "problemName": "Remove all duplicates from a given string" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-all-divisors-from-1-to-n4738/1", + "solutionLink": "#", + "problemName": "Sum of all divisors from 1 to n" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/in-first-but-second5423/1", + "solutionLink": "#", + "problemName": "Find missing in second array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-element-that-appears-once-in-sorted-array0624/1", + "solutionLink": "#", + "problemName": "Find the element that appears once in sorted array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/median-of-bst/1", + "solutionLink": "#", + "problemName": "Median of BST" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-bst-nodes-that-lie-in-a-given-range/1", + "solutionLink": "#", + "problemName": "Count BST nodes that lie in a given range" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimize-the-sum-of-product1525/1", + "solutionLink": "#", + "problemName": "Minimize the sum of product" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-coding2452/1", + "solutionLink": "#", + "problemName": "Reverse Coding" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/winner-of-an-election-where-votes-are-represented-as-candidate-names-1587115621/1", + "solutionLink": "#", + "problemName": "Winner of an election" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-every-kth-node/1", + "solutionLink": "#", + "problemName": "Remove every kth node" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/need-some-change/1", + "solutionLink": "#", + "problemName": "Swap the array elements" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/delete-node-in-doubly-linked-list/1", + "solutionLink": "#", + "problemName": "Delete node in Doubly Linked List" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-subarray-of-0s-and-1s/1", + "solutionLink": "#", + "problemName": "Largest subarray of 0's and 1's" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-all-possible-paths-from-top-left-to-bottom-right3011/1", + "solutionLink": "#", + "problemName": "Count all possible paths from top left to bottom right" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/special-stack/1", + "solutionLink": "#", + "problemName": "Special Stack" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-pattern3549/1", + "solutionLink": "#", + "problemName": "Print Pattern" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-indexed-character-1587115620/1", + "solutionLink": "#", + "problemName": "Minimum indexed character" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/rotate-bits4524/1", + "solutionLink": "#", + "problemName": "Rotate Bits" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/evaluation-of-postfix-expression1735/1", + "solutionLink": "#", + "problemName": "Evaluation of Postfix Expression" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/shortest-path-from-1-to-n0156/1", + "solutionLink": "#", + "problemName": "Shortest path from 1 to n" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/alone-in-couple5507/1", + "solutionLink": "#", + "problemName": "Party of Couples" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-closest-number5513/1", + "solutionLink": "#", + "problemName": "Find the closest number" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/segregate-0s-and-1s5106/1", + "solutionLink": "#", + "problemName": "Segregate 0s and 1s" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-first-repeated-character4108/1", + "solutionLink": "#", + "problemName": "Find first repeated character" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximize-toys0331/1", + "solutionLink": "#", + "problemName": "Maximize Toys" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/level-order-traversal-line-by-line/1", + "solutionLink": "#", + "problemName": "Level order traversal Line by Line" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/rotate-by-90-degree-1587115621/1", + "solutionLink": "#", + "problemName": "Rotate by 90 degree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/form-a-number-divisible-by-3-using-array-digits0717/1", + "solutionLink": "#", + "problemName": "Form a number divisible by 3 using array digits" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/start-coding-java/1", + "solutionLink": "#", + "problemName": "Start Coding - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/binary-tree-to-bst/1", + "solutionLink": "#", + "problemName": "Binary Tree to BST" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-width-of-tree/1", + "solutionLink": "#", + "problemName": "Maximum Width of Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/predict-the-column/1", + "solutionLink": "#", + "problemName": "Predict the Column" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/pangram-checking-1587115620/1", + "solutionLink": "#", + "problemName": "Panagram Checking" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/series-gp4646/1", + "solutionLink": "#", + "problemName": "Series GP" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/reach-the-nth-point5433/1", + "solutionLink": "#", + "problemName": "Reach the Nth point" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/modular-multiplicative-inverse-1587115620/1", + "solutionLink": "#", + "problemName": "Modular Multiplicative Inverse" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximize-sum-after-k-negations1149/1", + "solutionLink": "#", + "problemName": "Maximize sum after K negations" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/shop-in-candy-store1145/1", + "solutionLink": "#", + "problemName": "Shop in Candy Store" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-number-in-a-sorted-rotated-array-1587115620/1", + "solutionLink": "#", + "problemName": "Minimum Number in a sorted rotated array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-first-and-last-occurrence-of-x0849/1", + "solutionLink": "#", + "problemName": "Left most and right most index" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-frequency/1", + "solutionLink": "#", + "problemName": "Find the Frequency" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-the-status/1", + "solutionLink": "#", + "problemName": "Check the status - Python" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/decimal-equivalent-of-binary-linked-list/1", + "solutionLink": "#", + "problemName": "Decimal Equivalent of Binary Linked List" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/-minimum-number-of-coins4426/1", + "solutionLink": "#", + "problemName": "Minimum number of Coins" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/transform-to-sum-tree/1", + "solutionLink": "#", + "problemName": "Transform to Sum Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-new-line/1", + "solutionLink": "#", + "problemName": "The New Line" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-depth-of-a-binary-tree/1", + "solutionLink": "#", + "problemName": "Minimum Depth of a Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/second-most-repeated-string-in-a-sequence0534/1", + "solutionLink": "#", + "problemName": "Second most repeated string in a sequence" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/plus-one/1", + "solutionLink": "#", + "problemName": "Plus One" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-highest-number2259/1", + "solutionLink": "#", + "problemName": "Find the Highest number" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-matrix-in-snake-pattern-1587115621/1", + "solutionLink": "#", + "problemName": "Print Matrix in snake Pattern" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-a-number-is-divisible-by-83957/1", + "solutionLink": "#", + "problemName": "Check if a number is divisible by 8" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-bits3556/1", + "solutionLink": "#", + "problemName": "Reverse Bits" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-upper-and-lower-triangles-1587115621/1", + "solutionLink": "#", + "problemName": "Sum of upper and lower triangles" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/taking-input-java/1", + "solutionLink": "#", + "problemName": "Taking input - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/search-insert-position-of-k-in-a-sorted-array/1", + "solutionLink": "#", + "problemName": "Search insert position of K in a sorted array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-ways-to-nth-stairorder-does-not-matter1322/1", + "solutionLink": "#", + "problemName": "Count ways to N'th Stair" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-new-line-java/1", + "solutionLink": "#", + "problemName": "The New Line - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/play-with-or5515/1", + "solutionLink": "#", + "problemName": "Play With OR" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/row-with-minimum-number-of-1s5430/1", + "solutionLink": "#", + "problemName": "Row with minimum number of 1's" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-closest-pair-from-two-arrays4215/1", + "solutionLink": "#", + "problemName": "Find the closest pair from two arrays" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/k-largest-elements3736/1", + "solutionLink": "#", + "problemName": "K largest elements" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-consecutive-1s-1587115620/1", + "solutionLink": "#", + "problemName": "Longest Consecutive 1's" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-integer--170647/1", + "solutionLink": "#", + "problemName": "Minimum Integer" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/for-loop-primechecl/1", + "solutionLink": "#", + "problemName": "For Loop- primeCheck" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/reach-a-given-score-1587115621/1", + "solutionLink": "#", + "problemName": "Reach a given score" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/brothers-from-different-root/1", + "solutionLink": "#", + "problemName": "Brothers From Different Roots" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/does-array-represent-heap4345/1", + "solutionLink": "#", + "problemName": "Does array represent Heap" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-the-elements1529/1", + "solutionLink": "#", + "problemName": "Count the elements" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/intersection-of-two-linked-list/1", + "solutionLink": "#", + "problemName": "Intersection of Two Linked Lists" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/get-min-at-pop/1", + "solutionLink": "#", + "problemName": "Get min at pop" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/learn-to-comment/1", + "solutionLink": "#", + "problemName": "Learn to Comment" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-two-strings-are-k-anagrams-or-not/1", + "solutionLink": "#", + "problemName": "Check if two strings are k-anagrams or not" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/for-loop-primecheck-java/1", + "solutionLink": "#", + "problemName": "For Loop- primeCheck - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/run-length-encoding/1", + "solutionLink": "#", + "problemName": "Run Length Encoding" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/equal-to-product3836/1", + "solutionLink": "#", + "problemName": "Product Pair" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GFG website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/gfg-problems/easy/0201-0300.md b/problems/gfg-problems/easy/0201-0300.md new file mode 100644 index 0000000..ce9ebb2 --- /dev/null +++ b/problems/gfg-problems/easy/0201-0300.md @@ -0,0 +1,622 @@ +--- +id: 0201-0300 +title: GFG easy problems 0201-0300 +sidebar_label: 0201-0300 +keywords: + - gfg problems + - gfg problems easy + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/occurence-of-an-integer-in-a-linked-list/1", + "solutionLink": "#", + "problemName": "Occurence of an integer in a Linked List" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-all-prime-numbers-between-1-and-n4404/1", + "solutionLink": "#", + "problemName": "Sum of all prime numbers between 1 and N." + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-sum-problem2211/1", + "solutionLink": "#", + "problemName": "Maximum Sum Problem" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/learn-to-comment-java/1", + "solutionLink": "#", + "problemName": "Learn to Comment - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-open-doors1552/1", + "solutionLink": "#", + "problemName": "Number Of Open Doors" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sieve-of-eratosthenes5242/1", + "solutionLink": "#", + "problemName": "Sieve of Eratosthenes" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-it-is-possible-to-survive-on-island4922/1", + "solutionLink": "#", + "problemName": "Check if it is possible to survive on Island" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/four-elements2452/1", + "solutionLink": "#", + "problemName": "Four Elements" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/copy-set-bits-in-range0623/1", + "solutionLink": "#", + "problemName": "Copy Set Bits in Range" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/three-great-candidates0515/1", + "solutionLink": "#", + "problemName": "Three Great Candidates" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/split-a-circular-linked-list-into-two-halves/1", + "solutionLink": "#", + "problemName": "Split a Circular Linked List into two halves" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-bst-elements-in-given-range/1", + "solutionLink": "#", + "problemName": "Print BST elements in given range" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-window-containing-0-1-and-2--170637/1", + "solutionLink": "#", + "problemName": "Smallest window containing 0, 1 and 2" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/roof-top-1587115621/1", + "solutionLink": "#", + "problemName": "Roof Top" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/numbers-containing-1-2-and-32555/1", + "solutionLink": "#", + "problemName": "Numbers containing 1, 2 and 3" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/right-triangle/1", + "solutionLink": "#", + "problemName": "Pattern 2" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/inorder-traversal-and-bst5855/1", + "solutionLink": "#", + "problemName": "Inorder Traversal and BST" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/delete-n-nodes-after-m-nodes-of-a-linked-list/1", + "solutionLink": "#", + "problemName": "Delete N nodes after M nodes of a linked list" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/frogs-and-jumps--170647/1", + "solutionLink": "#", + "problemName": "Frogs and Jumps" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-number-with-given-sum-1587115620/1", + "solutionLink": "#", + "problemName": "Largest number with given sum" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/recursive-sequence1611/1", + "solutionLink": "#", + "problemName": "Recursive sequence" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sort-by-set-bit-count1153/1", + "solutionLink": "#", + "problemName": "Sort by Set Bit Count" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/make-the-array-beautiful--170647/1", + "solutionLink": "#", + "problemName": "Make the array beautiful" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/pair-with-given-sum-in-a-sorted-array4940/1", + "solutionLink": "#", + "problemName": "Pair with given sum in a sorted array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/closest-neighbor-in-bst/1", + "solutionLink": "#", + "problemName": "Closest Neighbour in BST" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-subset-with-greater-sum/1", + "solutionLink": "#", + "problemName": "Smallest Subset with Greater Sum" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/fibonacci-series-up-to-nth-term/1", + "solutionLink": "#", + "problemName": "Fibonacci series up to Nth term" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/unique-rows-in-boolean-matrix/1", + "solutionLink": "#", + "problemName": "Unique rows in boolean matrix" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/ceil-the-floor2802/1", + "solutionLink": "#", + "problemName": "Ceil The Floor" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/min-number-of-flips3210/1", + "solutionLink": "#", + "problemName": "Min Number of Flips" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-of-strings-that-can-be-formed-using-a-b-and-c-under-given-constraints1135/1", + "solutionLink": "#", + "problemName": "String's Count" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-dependencies-in-a-graph5311/1", + "solutionLink": "#", + "problemName": "Sum of dependencies in a graph" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/search-in-a-rotated-array0959/1", + "solutionLink": "#", + "problemName": "Search an element in sorted and rotated array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-leaf-nodes-in-bst/1", + "solutionLink": "#", + "problemName": "Sum of leaf nodes in BST" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangle-number/1", + "solutionLink": "#", + "problemName": "Pattern 3" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/chinky-and-diamonds3340/1", + "solutionLink": "#", + "problemName": "Maximum Diamonds" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/facing-the-sun2126/1", + "solutionLink": "#", + "problemName": "Facing the sun" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/searching-in-an-array-where-adjacent-differ-by-at-most-k0456/1", + "solutionLink": "#", + "problemName": "Searching in an array where adjacent differ by at most k" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/adding-ones3628/1", + "solutionLink": "#", + "problemName": "Adding Ones" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/multiply-two-linked-lists/1", + "solutionLink": "#", + "problemName": "Multiply two linked lists" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/swap-all-odd-and-even-bits-1587115621/1", + "solutionLink": "#", + "problemName": "Swap all odd and even bits" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/unique-frequencies-of-not/1", + "solutionLink": "#", + "problemName": "Unique Number of Occurrences" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/seating-arrangement--170647/1", + "solutionLink": "#", + "problemName": "Seating Arrangement" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/leaf-under-budget/1", + "solutionLink": "#", + "problemName": "Leaf under budget" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-pairs-sum-in-matrices4332/1", + "solutionLink": "#", + "problemName": "Count pairs Sum in matrices" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/convert-an-array-to-reduced-form1101/1", + "solutionLink": "#", + "problemName": "Convert an array to reduced form" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/generate-binary-numbers-1587115620/1", + "solutionLink": "#", + "problemName": "Generate Binary Numbers" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-first-node-of-loop-in-linked-list--170645/1", + "solutionLink": "#", + "problemName": "Find the first node of loop in linked list" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/page-faults-in-lru5603/1", + "solutionLink": "#", + "problemName": "Page Faults in LRU" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-distance-between-same-elements/1", + "solutionLink": "#", + "problemName": "Max distance between same elements" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/nextline-and-next/1", + "solutionLink": "#", + "problemName": "nextLine and next" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/surround-the-1s2505/1", + "solutionLink": "#", + "problemName": "Surround the 1's" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/merge-two-binary-max-heap0144/1", + "solutionLink": "#", + "problemName": "Merge two binary Max heaps" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/common-elements5420/1", + "solutionLink": "#", + "problemName": "Common Elements" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/overlapping-rectangles1924/1", + "solutionLink": "#", + "problemName": "Overlapping rectangles" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-elements-between-k1th-and-k2th-smallest-elements3133/1", + "solutionLink": "#", + "problemName": "Sum of elements between k1'th and k2'th smallest elements" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/swap-two-nibbles-in-a-byte0446/1", + "solutionLink": "#", + "problemName": "Swap two nibbles in a byte" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/min-sum-formed-by-digits3551/1", + "solutionLink": "#", + "problemName": "Min sum formed by digits" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/recamans-sequence4856/1", + "solutionLink": "#", + "problemName": "Recamans sequence" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangle-number-1661428795/1", + "solutionLink": "#", + "problemName": "Pattern 4" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/counting-sort/1", + "solutionLink": "#", + "problemName": "Counting Sort" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/primes-sum5827/1", + "solutionLink": "#", + "problemName": "Primes sum" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/data-types-java/1", + "solutionLink": "#", + "problemName": "Data Types - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/juggler-sequence3930/1", + "solutionLink": "#", + "problemName": "Juggler Sequence" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-no-of-1s-row3027/1", + "solutionLink": "#", + "problemName": "Maximum no of 1's row" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/taking-input/1", + "solutionLink": "#", + "problemName": "Taking input" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/intersection-of-two-sorted-array-1587115620/1", + "solutionLink": "#", + "problemName": "Intersection of two sorted arrays" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sort-by-absolute-difference-1587115621/1", + "solutionLink": "#", + "problemName": "Sort by Absolute Difference" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/step-by-step-condition-java/1", + "solutionLink": "#", + "problemName": "Step by Step Condition - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/frequency-game/1", + "solutionLink": "#", + "problemName": "Frequency Game" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/ancestors-in-binary-tree/1", + "solutionLink": "#", + "problemName": "Ancestors in Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/twice-counter4236/1", + "solutionLink": "#", + "problemName": "Twice Counter" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/you-and-your-books/1", + "solutionLink": "#", + "problemName": "You and your books" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/help-nobita0532/1", + "solutionLink": "#", + "problemName": "Odd Even Problem" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/insert-an-element-at-the-bottom-of-a-stack/1", + "solutionLink": "#", + "problemName": "Insert an Element at the Bottom of a Stack" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/remainder-on-dividing-by-11--170647/1", + "solutionLink": "#", + "problemName": "Remainder on dividing by 11" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/if-loop-python/1", + "solutionLink": "#", + "problemName": "If conditional statement- Python" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/nearest-multiple-of-102437/1", + "solutionLink": "#", + "problemName": "Nearest multiple of 10" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/adding-array-element4756/1", + "solutionLink": "#", + "problemName": "Adding Array Elements" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/ease-the-array0633/1", + "solutionLink": "#", + "problemName": "Ease the Array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/xoring-and-clearing/1", + "solutionLink": "#", + "problemName": "Xoring and Clearing" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/missing-element-of-ap2228/1", + "solutionLink": "#", + "problemName": "Missing element of AP" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/queue-operations/1", + "solutionLink": "#", + "problemName": "Queue Operations" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/remaining-string3515/1", + "solutionLink": "#", + "problemName": "Remaining String" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-diagonally4331/1", + "solutionLink": "#", + "problemName": "Print Diagonally" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/two-mirror-trees/1", + "solutionLink": "#", + "problemName": "Two Mirror Trees" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/closest-strings0611/1", + "solutionLink": "#", + "problemName": "Closest Strings" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/step-by-step-condition/1", + "solutionLink": "#", + "problemName": "Step by Step Condition" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/positive-negative-pair5209/1", + "solutionLink": "#", + "problemName": "Positive Negative Pair" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/learning-to-be-precise/1", + "solutionLink": "#", + "problemName": "Learning to be precise" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-leaf-nodes/1", + "solutionLink": "#", + "problemName": "Sum of Leaf Nodes" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-odd-even-java/1", + "solutionLink": "#", + "problemName": "Count Odd Even - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/move-last-element-to-front-of-a-linked-list/1", + "solutionLink": "#", + "problemName": "Move Last Element to Front of a Linked List" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/while-loop-printtable-java/1", + "solutionLink": "#", + "problemName": "While loop- printTable - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-duplicates-in-small-prime-array/1", + "solutionLink": "#", + "problemName": "Remove duplicates in small prime array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-level-sum-in-binary-tree/1", + "solutionLink": "#", + "problemName": "Max Level Sum in Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/vertical-width-of-a-binary-tree/1", + "solutionLink": "#", + "problemName": "Vertical Width of a Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-n-to-1-without-loop/1", + "solutionLink": "#", + "problemName": "Print N to 1 without loop" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/make-array-elements-equal--170647/1", + "solutionLink": "#", + "problemName": "Make Array Elements Equal" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/dominant-pairs/1", + "solutionLink": "#", + "problemName": "Dominant Pairs" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GFG website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/easy/0301-0400.md b/problems/gfg-problems/easy/0301-0400.md new file mode 100644 index 0000000..63d8613 --- /dev/null +++ b/problems/gfg-problems/easy/0301-0400.md @@ -0,0 +1,623 @@ +--- +id: 0301-0400 +title: GFG easy problems 0301-0400 +sidebar_label: 0301-0400 +keywords: + - gfg problems + - gfg problems easy + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/make-array-elements-equal--170647/1", + "solutionLink": "#", + "problemName": "Make Array Elements Equal" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/dominant-pairs/1", + "solutionLink": "#", + "problemName": "Dominant Pairs" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/least-prime-factor5216/1", + "solutionLink": "#", + "problemName": "Least Prime Factor" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-gfg-n-times/1", + "solutionLink": "#", + "problemName": "Print GFG n times" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/array-operations--170648/1", + "solutionLink": "#", + "problemName": "Array Operations" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/pairs-with-specific-difference1533/1", + "solutionLink": "#", + "problemName": "Pairs with certain difference" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/even-odd/1", + "solutionLink": "#", + "problemName": "Even Odd" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/convert-to-roman-no/1", + "solutionLink": "#", + "problemName": "Convert to Roman No" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/tom-and-jerry1325/1", + "solutionLink": "#", + "problemName": "Tom and Jerry" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-the-paths4332/1", + "solutionLink": "#", + "problemName": "Count the paths" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/equal-left-and-right-subarray-sum--170647/1", + "solutionLink": "#", + "problemName": "Equal Left and Right Subarray Sum" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/binary-modulo--170648/1", + "solutionLink": "#", + "problemName": "Binary Modulo" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/logical-operators-java/1", + "solutionLink": "#", + "problemName": "logical Operators - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/c-letters-collection4552/1", + "solutionLink": "#", + "problemName": "Letters Collection" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/make-palindrome--170647/1", + "solutionLink": "#", + "problemName": "Make Palindrome" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/swap-and-maximize5859/1", + "solutionLink": "#", + "problemName": "Swap and Maximize" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/wifi-range--170647/1", + "solutionLink": "#", + "problemName": "Wifi Range" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/learning-macros/1", + "solutionLink": "#", + "problemName": "Learning Macros" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/total-traversal-time/1", + "solutionLink": "#", + "problemName": "Total Traversal Time" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-left-leaf-nodes/1", + "solutionLink": "#", + "problemName": "Sum of Left Leaf Nodes" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/reversing-the-equation2205/1", + "solutionLink": "#", + "problemName": "Reversing the equation" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/convert-a-sentence-into-its-equivalent-mobile-numeric-keypad-sequence0547/1", + "solutionLink": "#", + "problemName": "Convert a sentence into its equivalent mobile numeric keypad sequence" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/ticket-counter-2731/1", + "solutionLink": "#", + "problemName": "Ticket Counter" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/insert-in-sorted-way-in-a-sorted-dll/1", + "solutionLink": "#", + "problemName": "Insert in Sorted way in a Sorted DLL" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-and-min-element-in-binary-tree/1", + "solutionLink": "#", + "problemName": "Max and min element in Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/odd-even-level-difference/1", + "solutionLink": "#", + "problemName": "Odd even level difference" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/mark-even-and-odd/1", + "solutionLink": "#", + "problemName": "Mark Even and Odd - Python" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/extract-the-number-from-the-string3428/1", + "solutionLink": "#", + "problemName": "Extract the Number from the String" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/deque-implementations/1", + "solutionLink": "#", + "problemName": "Deque Implementations" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/getline-and-ignore/1", + "solutionLink": "#", + "problemName": "GetLine and Ignore" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-pairs-with-given-sum-in-doubly-linked-list/1", + "solutionLink": "#", + "problemName": "Find pairs with given sum in doubly linked list" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-depth-of-binary-tree/1", + "solutionLink": "#", + "problemName": "Maximum Depth Of Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/reorganize-the-array4810/1", + "solutionLink": "#", + "problemName": "Reorganize The Array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/expression-tree/1", + "solutionLink": "#", + "problemName": "Expression Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-sum-of-absolute-differences-of-pairs/1", + "solutionLink": "#", + "problemName": "Minimum Sum of Absolute Differences of Pairs" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/pairs-with-positive-negative-values3719/1", + "solutionLink": "#", + "problemName": "Pairs with Positive Negative values" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/squares-in-nn-chessboard1801/1", + "solutionLink": "#", + "problemName": "Squares in N*N Chessboard" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/trace-path3840/1", + "solutionLink": "#", + "problemName": "Trace Path" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/geek-jump/1", + "solutionLink": "#", + "problemName": "Geek Jump" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-bracket-number4058/1", + "solutionLink": "#", + "problemName": "Print Bracket Number" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/string-mirror--170647/1", + "solutionLink": "#", + "problemName": "String Mirror" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/divisor-game-1664432414/1", + "solutionLink": "#", + "problemName": "Divisor Game" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/fitting-the-array1514/1", + "solutionLink": "#", + "problemName": "Fitting The Array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-number-of-words1500/1", + "solutionLink": "#", + "problemName": "Count number of words" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/bit-magic--170648/1", + "solutionLink": "#", + "problemName": "Bit Magic" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-identical-bowls--170647/1", + "solutionLink": "#", + "problemName": "Maximum Identical Bowls" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/while-loop-printtable/1", + "solutionLink": "#", + "problemName": "While loop- printTable" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/bitwise-operators/1", + "solutionLink": "#", + "problemName": "Bitwise Operators" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/pattern-searching4145/1", + "solutionLink": "#", + "problemName": "Pattern Searching" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/prime-factors5052/1", + "solutionLink": "#", + "problemName": "Prime Factors" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/total-cuts--170648/1", + "solutionLink": "#", + "problemName": "Total Cuts" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-number--170647/1", + "solutionLink": "#", + "problemName": "Minimum Number" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/binary-search-in-forest--141631/1", + "solutionLink": "#", + "problemName": "Binary Search in forest" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/root-to-leaf-paths-sum/1", + "solutionLink": "#", + "problemName": "Root to leaf paths sum" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/powerfull-integer--170647/1", + "solutionLink": "#", + "problemName": "Powerfull Integer" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-k-smallest-elements-in-bst3029/1", + "solutionLink": "#", + "problemName": "Sum of k smallest elements in BST" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/k-th-missing-element3635/1", + "solutionLink": "#", + "problemName": "K-th missing element" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/deletion-and-reverse-in-linked-list/1", + "solutionLink": "#", + "problemName": "Deletion and Reverse in Linked List" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/license-key-formatting/1", + "solutionLink": "#", + "problemName": "License Key Formatting" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/is-it-fibonacci--170647/1", + "solutionLink": "#", + "problemName": "Is it Fibonacci" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sequence-fun5018/1", + "solutionLink": "#", + "problemName": "Sequence Fun" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-modified-string-1587115621/1", + "solutionLink": "#", + "problemName": "The Modified String" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-subarrays-of-0s--170647/1", + "solutionLink": "#", + "problemName": "Number of Subarrays of 0's" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/length-unsorted-subarray3022/1", + "solutionLink": "#", + "problemName": "Length Unsorted Subarray" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/level-of-a-node-in-binary-tree/1", + "solutionLink": "#", + "problemName": "Level of a Node in Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/consonants-and-vowels-check-java/1", + "solutionLink": "#", + "problemName": "Consonants and Vowels check - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-two-numbers-without-using-arithmetic-operators/1", + "solutionLink": "#", + "problemName": "Sum of two numbers without using arithmetic operators" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/bbt-counter4914/1", + "solutionLink": "#", + "problemName": "BBT counter" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/counts-zeros-xor-pairs0349/1", + "solutionLink": "#", + "problemName": "Counts Zeros Xor Pairs" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-weight-node--170645/1", + "solutionLink": "#", + "problemName": "Maximum Weight Node" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/chicks-in-a-zoo1159/1", + "solutionLink": "#", + "problemName": "Chicks in a Zoo" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/break-a-number5913/1", + "solutionLink": "#", + "problemName": "Break a number" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/next-greater-number-set-digits3503/1", + "solutionLink": "#", + "problemName": "Next greater number set digits" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/compare-two-linked-lists/1", + "solutionLink": "#", + "problemName": "Compare two linked lists" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/taxi-booking--170647/1", + "solutionLink": "#", + "problemName": "Taxi Booking" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-numbers-containing-43022/1", + "solutionLink": "#", + "problemName": "Count numbers containing 4" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/disjoint-set-union-find/1", + "solutionLink": "#", + "problemName": "Disjoint set (Union-Find)" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-indexed-character0221/1", + "solutionLink": "#", + "problemName": "Minimum indexed character" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/queue-using-stack/1", + "solutionLink": "#", + "problemName": "Queue using stack" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/cutting-rectangles--170647/1", + "solutionLink": "#", + "problemName": "Cutting Rectangles" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/balloon-everywhere--170646/1", + "solutionLink": "#", + "problemName": "Balloon Everywhere" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-to-words0335/1", + "solutionLink": "#", + "problemName": "Integer to Words" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-greater-elements-in-whole-array2751/1", + "solutionLink": "#", + "problemName": "Smallest greater elements in whole array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/buildings-receiving-sunlight3032/1", + "solutionLink": "#", + "problemName": "Buildings receiving sunlight" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-pattern-matcher-java/1", + "solutionLink": "#", + "problemName": "The Pattern Matcher - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/split-the-binary-string-into-substrings-with-equal-number-of-0s-and-1s/1", + "solutionLink": "#", + "problemName": "Split the binary string into substrings with equal number of 0s and 1s" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-the-specials/1", + "solutionLink": "#", + "problemName": "Count the Specials" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-number-of-zeroes4048/1", + "solutionLink": "#", + "problemName": "Maximum number of zeroes" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-two-numbers-represented-as-arrays3110/1", + "solutionLink": "#", + "problemName": "Sum of two numbers represented as arrays" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-array-contains-contiguous-integers-with-duplicates-allowed2046/1", + "solutionLink": "#", + "problemName": "Check if array contains contiguous integers with duplicates allowed" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/single-number1014/1", + "solutionLink": "#", + "problemName": "Single Number" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/binary-matrix-having-maximum-number-of-1s--170647/1", + "solutionLink": "#", + "problemName": "Binary matrix having maximum number of 1s" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/help-ishaan5837/1", + "solutionLink": "#", + "problemName": "Help Ishaan" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangle-pattern-1662286302/1", + "solutionLink": "#", + "problemName": "Pattern 18" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/full-binary-tree/1", + "solutionLink": "#", + "problemName": "Full Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/almost-equal-java/1", + "solutionLink": "#", + "problemName": "Almost Equal -Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/matrix-interchange-java/1", + "solutionLink": "#", + "problemName": "Matrix Interchange - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/rectangles-in-nn-board5930/1", + "solutionLink": "#", + "problemName": "Rectangles in N*N Board" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/make-zeroes4042/1", + "solutionLink": "#", + "problemName": "Make Zeroes" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-node-level/1", + "solutionLink": "#", + "problemName": "Maximum Node Level" + } +] + + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GeeksforGeeks website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/easy/0401-0500.md b/problems/gfg-problems/easy/0401-0500.md new file mode 100644 index 0000000..12f0669 --- /dev/null +++ b/problems/gfg-problems/easy/0401-0500.md @@ -0,0 +1,623 @@ +--- +id: 0401-0500 +title: GFG easy problems 0401-0500 +sidebar_label: 0401-0500 +keywords: + - gfg problems + - gfg problems easy + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-node-level/1", + "solutionLink": "#", + "problemName": "Maximum Node Level" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangle-pattern-1662284916/1", + "solutionLink": "#", + "problemName": "Pattern 14" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/equilibrium-index-of-an-array/1", + "solutionLink": "#", + "problemName": "Equilibrium index of an array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/type-it--170645/1", + "solutionLink": "#", + "problemName": "Type it!" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/next-right-node/1", + "solutionLink": "#", + "problemName": "Next Right Node" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimize-the-sum--170645/1", + "solutionLink": "#", + "problemName": "Minimize the sum" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-the-substrings--141634/1", + "solutionLink": "#", + "problemName": "Count the Substrings" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/match-specific-pattern/1", + "solutionLink": "#", + "problemName": "Match specific pattern" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-the-number-is-balanced3014/1", + "solutionLink": "#", + "problemName": "Check if the number is balanced" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/even-and-odd/1", + "solutionLink": "#", + "problemName": "Even and Odd" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/square-pattern-1662287714/1", + "solutionLink": "#", + "problemName": "Pattern 21" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/bus-conductor--170647/1", + "solutionLink": "#", + "problemName": "Bus Conductor" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-number-of-free-cell--170646/1", + "solutionLink": "#", + "problemName": "Count number of free cell" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/k-pangrams0909/1", + "solutionLink": "#", + "problemName": "K-Pangrams" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/deletion-in-a-binary-tree/1", + "solutionLink": "#", + "problemName": "Deletion in a Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-node-with-maximum-gcd-of-the-siblings-of-a-binary-tree/1", + "solutionLink": "#", + "problemName": "Find the Node with maximum GCD of the siblings of a Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/bitwise-operators-java/1", + "solutionLink": "#", + "problemName": "Bitwise Operators - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/magic-in-cpp/1", + "solutionLink": "#", + "problemName": "Magic in CPP" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangle-pattern-1662285196/1", + "solutionLink": "#", + "problemName": "Pattern 15" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-b-and-ac-from-a-given-string4336/1", + "solutionLink": "#", + "problemName": "Remove b and ac from a given string" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-steps-to-make-product-equal-to-one/1", + "solutionLink": "#", + "problemName": "Minimum steps to make product equal to one" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-substrings0427/1", + "solutionLink": "#", + "problemName": "Count Substrings" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/101-pattern-count1341/1", + "solutionLink": "#", + "problemName": "1[0]1 Pattern Count" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-level-sum-in-binary-tree--170647/1", + "solutionLink": "#", + "problemName": "Max Level Sum in Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/pair-cube-count4132/1", + "solutionLink": "#", + "problemName": "Pair cube count" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/arraylist-operation/1", + "solutionLink": "#", + "problemName": "ArrayList Operation" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-it-is-possible-to-convert-one-string-into-another-with-given-constraints4116/1", + "solutionLink": "#", + "problemName": "Check if it is possible to convert one string into another with given constraints" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-sum-lcm3025/1", + "solutionLink": "#", + "problemName": "Maximum Sum LCM" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/double-triangle-pattern-1662664259/1", + "solutionLink": "#", + "problemName": "Pattern 12" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-height-of-the-staircase5755/1", + "solutionLink": "#", + "problemName": "Maximum height of the staircase" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/min-operations--170645/1", + "solutionLink": "#", + "problemName": "Min operations" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/jumping-through-while-python/1", + "solutionLink": "#", + "problemName": "Jumping through While - Python" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangle-pattern-1662285334/1", + "solutionLink": "#", + "problemName": "Pattern 16" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-half-nodes/1", + "solutionLink": "#", + "problemName": "Remove Half Nodes" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/start-elements3447/1", + "solutionLink": "#", + "problemName": "Star elements" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/even-odd-java/1", + "solutionLink": "#", + "problemName": "Even Odd - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/rearrange-a-string4100/1", + "solutionLink": "#", + "problemName": "Rearrange a string" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/linked-list-of-strings-forms-a-palindrome/1", + "solutionLink": "#", + "problemName": "linked list of strings forms a palindrome" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/union-find/1", + "solutionLink": "#", + "problemName": "Union-Find" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-both-parts--170647/1", + "solutionLink": "#", + "problemName": "Reverse both parts" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/add-two-numbers-represented-by-two-arrays2408/1", + "solutionLink": "#", + "problemName": "Add two numbers represented by two arrays" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/last-cell-in-a-matrix/1", + "solutionLink": "#", + "problemName": "Last cell in a Matrix" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/need-some-change-java/1", + "solutionLink": "#", + "problemName": "Need Some Change - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/linked-list-in-zig-zag-fashion/1", + "solutionLink": "#", + "problemName": "Linked List in Zig-Zag fashion" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-minimum-time0253/1", + "solutionLink": "#", + "problemName": "Find the minimum time" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/transform-to-sum-tree--170645/1", + "solutionLink": "#", + "problemName": "Transform to Sum Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-equals-to-sum4006/1", + "solutionLink": "#", + "problemName": "Sum equals to Sum" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/jumping-caterpillars4412/1", + "solutionLink": "#", + "problemName": "Jumping Caterpillars" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/introduction-to-linked-list/1", + "solutionLink": "#", + "problemName": "Introduction to Linked List" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/two-dimensional-world/1", + "solutionLink": "#", + "problemName": "Two Dimensional World" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/help-the-old-man3848/1", + "solutionLink": "#", + "problemName": "Help the Old Man!!!" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/delete-array/1", + "solutionLink": "#", + "problemName": "Delete Array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/magical-number-1587115620/1", + "solutionLink": "#", + "problemName": "Magical Number" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-consecutive-sequence-in-binary-tree/1", + "solutionLink": "#", + "problemName": "Longest consecutive sequence in Binary tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-nth-fibonnaci3150/1", + "solutionLink": "#", + "problemName": "The Nth Fibonnaci" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-fibonacci-subsequence2206/1", + "solutionLink": "#", + "problemName": "Largest Fibonacci Subsequence" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-equal-point-in-string-of-brackets2542/1", + "solutionLink": "#", + "problemName": "Equal point in a string of brackets" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/easy-string2212/1", + "solutionLink": "#", + "problemName": "Easy string" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/last-modified-ball--170645/1", + "solutionLink": "#", + "problemName": "Last modified ball" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/move-all-zeros-to-the-front-of-the-linked-list/1", + "solutionLink": "#", + "problemName": "Move all zeros to the front of the linked list" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-number-with-sum-of-digits-as-n-and-divisible-by-10n4032/1", + "solutionLink": "#", + "problemName": "Smallest number with sum of digits as N and divisible by 10^N" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/right-most-non-zero-digit1834/1", + "solutionLink": "#", + "problemName": "Right most non zero digit" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/special-array-reversal2328/1", + "solutionLink": "#", + "problemName": "Special array reversal" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/is-square1846/1", + "solutionLink": "#", + "problemName": "Is Square" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/double-triangle-pattern-1662287416/1", + "solutionLink": "#", + "problemName": "Pattern 20" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/nth-number-made-of-prime-digits4319/1", + "solutionLink": "#", + "problemName": "Nth number made of prime digits" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/balanced-string1627/1", + "solutionLink": "#", + "problemName": "Balanced string" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/string-manipulation3706/1", + "solutionLink": "#", + "problemName": "String Manipulation" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/pair-in-array-whose-sum-is-closest-to-x1124/1", + "solutionLink": "#", + "problemName": "Sum Pair closest to X" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/predict-the-column-java/1", + "solutionLink": "#", + "problemName": "Predict the Column - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/nodes-at-odd-levels/1", + "solutionLink": "#", + "problemName": "Nodes at Odd Levels" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/all-divisors-of-a-number/1", + "solutionLink": "#", + "problemName": "All divisors of a Number" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/pairs-which-are-divisible-by-41920/1", + "solutionLink": "#", + "problemName": "Pairs which are Divisible by 4" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/for-loop-python/1", + "solutionLink": "#", + "problemName": "For loop - Python" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/abset-25327/1", + "solutionLink": "#", + "problemName": "Exponentiation (Set 2)" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-number-of-22-squares/1", + "solutionLink": "#", + "problemName": "Maximum number of 2X2 squares" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-leaf-nodes-at-min-level/1", + "solutionLink": "#", + "problemName": "Sum of Leaf Nodes at Min Level" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/back-to-front/1", + "solutionLink": "#", + "problemName": "Back to Front" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-gap3845/1", + "solutionLink": "#", + "problemName": "Maximum Gap" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/pairs-with-difference-k1713/1", + "solutionLink": "#", + "problemName": "Pairs with difference k" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-the-specials-java/1", + "solutionLink": "#", + "problemName": "Count the Specials - Java" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-right-leaf-nodes/1", + "solutionLink": "#", + "problemName": "Sum of Right Leaf Nodes" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangle-pattern-1662285911/1", + "solutionLink": "#", + "problemName": "Pattern 17" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/summed-matrix5834/1", + "solutionLink": "#", + "problemName": "Summed Matrix" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/subarray-range-with-given-sum2804/1", + "solutionLink": "#", + "problemName": "Subarrays with given sum" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-bit-game2313/1", + "solutionLink": "#", + "problemName": "The Bit Game" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/k-sorted-array1610/1", + "solutionLink": "#", + "problemName": "k sorted array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-value-in-each-level/1", + "solutionLink": "#", + "problemName": "Largest value in each level" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/divisible-by-73224/1", + "solutionLink": "#", + "problemName": "Divisible by 7" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/learning-structs/1", + "solutionLink": "#", + "problemName": "Learning Structs" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/double-triangle-pattern/1", + "solutionLink": "#", + "problemName": "Pattern 19" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/perfect-binary-tree/1", + "solutionLink": "#", + "problemName": "Perfect Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/while-loop-in-python/1", + "solutionLink": "#", + "problemName": "While loop in Python" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/meta-strings5713/1", + "solutionLink": "#", + "problemName": "Meta Strings" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/nth-item-through-sum3544/1", + "solutionLink": "#", + "problemName": "Nth item through sum" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/addition-of-submatrix5835/1", + "solutionLink": "#", + "problemName": "Addition of submatrix" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/stacks-operations/1", + "solutionLink": "#", + "problemName": "Stack Operations" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/consonants-and-vowels-check/1", + "solutionLink": "#", + "problemName": "Consonants and Vowels check" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/almost-equal/1", + "solutionLink": "#", + "problemName": "Almost Equal" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/final-destination4628/1", + "solutionLink": "#", + "problemName": "Final Destination" + } +] + + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GeeksforGeeks website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/easy/0501-0600.md b/problems/gfg-problems/easy/0501-0600.md new file mode 100644 index 0000000..13f4d70 --- /dev/null +++ b/problems/gfg-problems/easy/0501-0600.md @@ -0,0 +1,623 @@ +--- +id: 0501-0600 +title: GFG easy problems 0501-0600 +sidebar_label: 0501-0600 +keywords: + - gfg problems + - gfg problems easy + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/bit-manipulation-1666686020/1", + "solutionLink": "#", + "problemName": "Bit Manipulation" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/transform-the-array4344/1", + "solutionLink": "#", + "problemName": "Transform the array" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/aryas-long-string5840/1", + "solutionLink": "#", + "problemName": "Arya's Long String" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/even-and-odd-elements-at-even-and-odd-positions1342/1", + "solutionLink": "#", + "problemName": "Even and odd elements at even and odd positions" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/modified-numbers-and-queries0904/1", + "solutionLink": "#", + "problemName": "Modified Numbers and Queries" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/length-of-longest-subarray0440/1", + "solutionLink": "#", + "problemName": "Length of longest subarray" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/pair-sum-in-vector/1", + "solutionLink": "#", + "problemName": "Pair Sum in Vector" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-pattern-matcher/1", + "solutionLink": "#", + "problemName": "The Pattern Matcher" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/padovan-sequence2855/1", + "solutionLink": "#", + "problemName": "Padovan Sequence" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/merge-list-alternatingly/1", + "solutionLink": "#", + "problemName": "Merge Lists Alternatingly" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/merging-two-unsorted-arrays-in-sorted-order1020/1", + "solutionLink": "#", + "problemName": "Merging two unsorted arrays in sorted order" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-odd-number-in-string/1", + "solutionLink": "#", + "problemName": "Largest odd number in string" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-average-subarray5859/1", + "solutionLink": "#", + "problemName": "Maximum average subarray" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/pattern-searching5231/1", + "solutionLink": "#", + "problemName": "Pattern searching" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-value1205/1", + "solutionLink": "#", + "problemName": "Max value" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/ball-coloring3450/1", + "solutionLink": "#", + "problemName": "Ball coloring" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/for-loop-2-python/1", + "solutionLink": "#", + "problemName": "For Loop 2- Python" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-steps-to-minimize-n-as-per-given-condition0618/1", + "solutionLink": "#", + "problemName": "Minimum steps to minimize n as per given condition" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/rearrange-geek-and-his-classmates--141630/1", + "solutionLink": "#", + "problemName": "Rearrange Geek and his Classmates" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/distributing-question-papers2513/1", + "solutionLink": "#", + "problemName": "Minimum Exchange" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/encrypt-the-string-21117/1", + "solutionLink": "#", + "problemName": "Encrypt the string - 2" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/construct-bst-from-post-order/1", + "solutionLink": "#", + "problemName": "Construct BST from Postorder" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/closing-bracket-index5900/1", + "solutionLink": "#", + "problemName": "Closing bracket index" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-duplicates-from-a-sorted-doubly-linked-list/1", + "solutionLink": "#", + "problemName": "Remove duplicates from a sorted doubly linked list" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/linked-list-matrix/1", + "solutionLink": "#", + "problemName": "Linked List Matrix" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/triangular-number2850/1", + "solutionLink": "#", + "problemName": "Triangular Number" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-xor-of-numbers-from-l-to-r/1", + "solutionLink": "#", + "problemName": "Find XOR of numbers from L to R." + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/slicing-in-string-python/1", + "solutionLink": "#", + "problemName": "Slicing in String - Python" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/biginteger-multiply/1", + "solutionLink": "#", + "problemName": "BigInteger Multiply" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-shift-for-longest-common-prefix0759/1", + "solutionLink": "#", + "problemName": "Longest common prefix" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/string-comparison5858/1", + "solutionLink": "#", + "problemName": "String comparison" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/introduction-to-doubly-linked-list/1", + "solutionLink": "#", + "problemName": "Introduction to Doubly Linked List" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/split-singly-linked-list-alternatingly/1", + "solutionLink": "#", + "problemName": "Split Singly Linked List Alternatingly" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/delete-array-elements-which-are-smaller-than-next-or-become-smaller3115/1", + "solutionLink": "#", + "problemName": "Delete array elements which are smaller than next or become smaller" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/k-palindrome/1", + "solutionLink": "#", + "problemName": "K-Palindrome" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/punish-the-students5726/1", + "solutionLink": "#", + "problemName": "Punish the Students" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/pass-by-reference-and-value/1", + "solutionLink": "#", + "problemName": "Pass by Reference and Value" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/excel-sheet-part-21138/1", + "solutionLink": "#", + "problemName": "Excel Sheet | Part - 2" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/string-functions-ii/1", + "solutionLink": "#", + "problemName": "String Functions - II - Python" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-big-integers/1", + "solutionLink": "#", + "problemName": "Sum of Big Integers" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/change-bits1538/1", + "solutionLink": "#", + "problemName": "Change Bits" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/word-with-maximum-frequency0120/1", + "solutionLink": "#", + "problemName": "Word with maximum frequency" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/binary-search-trees/1", + "solutionLink": "#", + "problemName": "Binary Search Trees" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/ishaan-and-sticks0542/1", + "solutionLink": "#", + "problemName": "Ishaan and Sticks" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/distinct-absolute-array-elements4529/1", + "solutionLink": "#", + "problemName": "Distinct absolute array elements" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-changes-to-make-all-substrings-distinct4722/1", + "solutionLink": "#", + "problemName": "Minimum changes to make all substrings distinct" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-game0303/1", + "solutionLink": "#", + "problemName": "Number Game" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/square-pattern-1662666141/1", + "solutionLink": "#", + "problemName": "Pattern 22" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-lengths-of-non-overlapping-subarrays2237/1", + "solutionLink": "#", + "problemName": "Sum of Lengths of Non-Overlapping SubArrays" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/string-palindromic-ignoring-spaces4723/1", + "solutionLink": "#", + "problemName": "Palindrome Sentence" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/binary-tree-k-level-sum3857/1", + "solutionLink": "#", + "problemName": "Binary Tree K level sum" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/drive-the-car2541/1", + "solutionLink": "#", + "problemName": "Drive the car" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/even-fibonacci-numbers-sum1455/1", + "solutionLink": "#", + "problemName": "Even Fibonacci Numbers Sum" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/tilt-of-binary-tree/1", + "solutionLink": "#", + "problemName": "Tilt of Binary Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-sum-bitonic-subsequence1857/1", + "solutionLink": "#", + "problemName": "Maximum Sum Bitonic Subsequence" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/height-of-spiral-tree/1", + "solutionLink": "#", + "problemName": "Height of Spiral Tree" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/earthquake-and-the-paint-shop4518/1", + "solutionLink": "#", + "problemName": "Earthquake and the Paint Shop" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/swap-the-objects/1", + "solutionLink": "#", + "problemName": "Swap the objects" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/introduction-to-trees/1", + "solutionLink": "#", + "problemName": "Introduction to Trees" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/palindrome-numbers0942/1", + "solutionLink": "#", + "problemName": "Palindrome numbers" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/roll-the-characters-of-a-string2127/1", + "solutionLink": "#", + "problemName": "Roll the characters of a String" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-alphabets3649/1", + "solutionLink": "#", + "problemName": "Count Alphabets" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/operations-on-arraylist/1", + "solutionLink": "#", + "problemName": "Operations on ArrayList" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-area-rectangle/1", + "solutionLink": "#", + "problemName": "Maximum Area Rectangle" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/sort-the-given-array-after-applying-the-given-equation0304/1", + "solutionLink": "#", + "problemName": "Sort the given array after applying the given equation" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/min-subsets-with-consecutive-numbers0601/1", + "solutionLink": "#", + "problemName": "Min Subsets with Consecutive Numbers" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/divisible-by-82732/1", + "solutionLink": "#", + "problemName": "Divisible by 8" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/duplicate-elements/1", + "solutionLink": "#", + "problemName": "Duplicate Elements" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-factors1435/1", + "solutionLink": "#", + "problemName": "Number of factors" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/day-of-the-week1637/1", + "solutionLink": "#", + "problemName": "Day of the week" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/toppers-of-class3826/1", + "solutionLink": "#", + "problemName": "Toppers Of Class" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/biginteger-mod/1", + "solutionLink": "#", + "problemName": "BigInteger mod" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/amend-the-sentence3235/1", + "solutionLink": "#", + "problemName": "Amend The Sentence" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/generate-binary-string3642/1", + "solutionLink": "#", + "problemName": "Generate binary string" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/subarray-with-least-average5031/1", + "solutionLink": "#", + "problemName": "Subarray with least average" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-primes-in-range1604/1", + "solutionLink": "#", + "problemName": "Count Primes In Range" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-sum-of-subarray-less-than-or-equal-to-x4033/1", + "solutionLink": "#", + "problemName": "Maximum sum of subarray less than or equal to x" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/pangram-strings3155/1", + "solutionLink": "#", + "problemName": "Pangram Strings" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/prime-string3953/1", + "solutionLink": "#", + "problemName": "Prime String" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/repeat-the-strings/1", + "solutionLink": "#", + "problemName": "Repeat the Strings - Python" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/common-subsequence4049/1", + "solutionLink": "#", + "problemName": "Common Subsequence" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/min-cost-climbing-stairs/1", + "solutionLink": "#", + "problemName": "Min Cost Climbing Stairs" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/karatsuba-algorithm0135/1", + "solutionLink": "#", + "problemName": "Karatsuba Algorithm" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/string-functions-i/1", + "solutionLink": "#", + "problemName": "String Functions I - Python" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/love-for-the-twins2623/1", + "solutionLink": "#", + "problemName": "Love For The Twins" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/fill-array-by-1s0920/1", + "solutionLink": "#", + "problemName": "Fill array with 1's" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/first-come-first-serve1328/1", + "solutionLink": "#", + "problemName": "First Come First Serve" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/part-sort2851/1", + "solutionLink": "#", + "problemName": "Part Sort" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/difficulty-of-sentence5856/1", + "solutionLink": "#", + "problemName": "Difficulty of sentence" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/operations-on-priorityqueue/1", + "solutionLink": "#", + "problemName": "Operations on PriorityQueue" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/adjacents-are-not-allowed3528/1", + "solutionLink": "#", + "problemName": "Adjacents are not allowed" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/last-two-digit-fibonacci3353/1", + "solutionLink": "#", + "problemName": "Last two digit Fibonacci" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/magic-numbers3143/1", + "solutionLink": "#", + "problemName": "Magic numbers" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-energy1107/1", + "solutionLink": "#", + "problemName": "Minimum Energy" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-distinct-elements-after-removing-k-elements5906/1", + "solutionLink": "#", + "problemName": "Maximum distinct elements after removing K elements" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/multiply-two-polynomals0721/1", + "solutionLink": "#", + "problemName": "Multiply two polynomials" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/rearrange-array-such-that-even-positioned-are-greater-than-odd4804/1", + "solutionLink": "#", + "problemName": "Rearrange array such that even positioned are greater than odd" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/adding-one2529/1", + "solutionLink": "#", + "problemName": "Adding One" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-minimum-elements4612/1", + "solutionLink": "#", + "problemName": "Remove minimum elements" + }, + { + "difficulty": "Easy", + "gfgLink": "https://www.geeksforgeeks.org/problems/partition-a-number-into-two-divisible-parts3605/1", + "solutionLink": "#", + "problemName": "Partition a number into two divisible parts" + } +] + + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GeeksforGeeks website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/easy/0601-0700.md b/problems/gfg-problems/easy/0601-0700.md new file mode 100644 index 0000000..293206d --- /dev/null +++ b/problems/gfg-problems/easy/0601-0700.md @@ -0,0 +1,621 @@ +--- +id: 0601-0700 +title: GFG easy problems 0601-0700 +sidebar_label: 0601-0700 +keywords: + - gfg problems + - gfg problems easy + - gfg problems problems +--- + +export const problems = [ +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/maximum-possible-sum-of-products3637/1", +"solutionLink": "#", +"problemName": "Maximum Possible Sum of Products" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/exchange-the-leaf-nodes/1", +"solutionLink": "#", +"problemName": "Exchange the Leaf Nodes" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-exception-handling3103/1", +"solutionLink": "#", +"problemName": "C++ Exception Handling" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/print-the-pattern1025/1", +"solutionLink": "#", +"problemName": "Print the pattern" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/twisted-prime-number0500/1", +"solutionLink": "#", +"problemName": "Twisted Prime Number" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/unique-binary-tree-requirements/1", +"solutionLink": "#", +"problemName": "Unique Binary Tree Requirements" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/student-of-the-year/1", +"solutionLink": "#", +"problemName": "Student of the Year" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/multiply-by-111820/1", +"solutionLink": "#", +"problemName": "Multiply by 11" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/check-if-a-integer-is-power-of-8-or-not2537/1", +"solutionLink": "#", +"problemName": "Check if a Integer is power of 8 or not" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/crack-the-series0304/1", +"solutionLink": "#", +"problemName": "Crack the series" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/prime-number-of-set-bits4632/1", +"solutionLink": "#", +"problemName": "Prime number of set bits" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/hungry-pizza-lovers3148/1", +"solutionLink": "#", +"problemName": "Hungry Pizza Lovers" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/rearrange-an-array-such-that-arri-i3618/1", +"solutionLink": "#", +"problemName": "Rearrange an array such that arr[i] = i" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-matrix-rotation-by-180-degree0745/1", +"solutionLink": "#", +"problemName": "C++ Matrix Rotation by 180 degree" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-template/1", +"solutionLink": "#", +"problemName": "C++ Template" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/minimum-swaps-required-to-group-all-1s-together2451/1", +"solutionLink": "#", +"problemName": "Minimum Swaps required to group all 1s together" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/xor-of-a-given-range/1", +"solutionLink": "#", +"problemName": "XOR of a given range" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/good-pairs4519/1", +"solutionLink": "#", +"problemName": "Good Pairs" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/numbers-with-same-first-and-last-digit4228/1", +"solutionLink": "#", +"problemName": "Numbers with same first and last digit" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-collection-set-1-arraylist/1", +"solutionLink": "#", +"problemName": "Java Collection | Set 1 (ArrayList) Part-2" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/left-out-candies5652/1", +"solutionLink": "#", +"problemName": "Left out candies" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/pair-sum-existence/1", +"solutionLink": "#", +"problemName": "Pair Sum Existence" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/min-manipulations-to-make-strings-anagram1421/1", +"solutionLink": "#", +"problemName": "Min Manipulations to make Strings Anagram" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/generate-grey-code-sequences/1", +"solutionLink": "#", +"problemName": "Generate Grey Code Sequences" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/increasing-sub-sequence1712/1", +"solutionLink": "#", +"problemName": "Increasing Sub Sequence" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/dictionary-in-python-ii/1", +"solutionLink": "#", +"problemName": "Dictionary in Python - II" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/carry-counter0937/1", +"solutionLink": "#", +"problemName": "Carry counter" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/rearrange-linked-list-in-place/1", +"solutionLink": "#", +"problemName": "Rearrange linked list in-place" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-function-overloading-1587115620/1", +"solutionLink": "#", +"problemName": "C++ Function overloading" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/geek-and-his-tricky-series2207/1", +"solutionLink": "#", +"problemName": "Geek and his Tricky Series" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/huffman-decoding-1/1", +"solutionLink": "#", +"problemName": "Huffman Decoding-1" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/inverted-triangle-of-stars0110/1", +"solutionLink": "#", +"problemName": "Inverted triangle of stars" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/gadgets-of-doraland--141631/1", +"solutionLink": "#", +"problemName": "Gadgets of Doraland" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/mean-of-range-in-array2123/1", +"solutionLink": "#", +"problemName": "Mean of range in array" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/multiset-operations/1", +"solutionLink": "#", +"problemName": "Multiset Operations" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/postorder-traversal-from-given-inorder-and-preorder-traversals/1", +"solutionLink": "#", +"problemName": "Postorder traversal from given Inorder and Preorder traversals" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/bitonic-generator-sort3343/1", +"solutionLink": "#", +"problemName": "Bitonic Generator Sort" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/depth-of-node/1", +"solutionLink": "#", +"problemName": "Depth of node" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/outermost-parentheses/1", +"solutionLink": "#", +"problemName": "Outermost Parentheses" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/boundary-elements-of-matrix1102/1", +"solutionLink": "#", +"problemName": "Boundary Elements of Matrix" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-corresponding-position-in-the-two-strings-that-hold-exactly-the-same-characters5013/1", +"solutionLink": "#", +"problemName": "Same characters in two strings" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/rope-cutting3334/1", +"solutionLink": "#", +"problemName": "Rope Cutting" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/geek-and-his-binary-strings1951/1", +"solutionLink": "#", +"problemName": "Geek and his Binary Strings" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/faithful-numbers0014/1", +"solutionLink": "#", +"problemName": "Faithful Numbers" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/dictionary-in-python-iii/1", +"solutionLink": "#", +"problemName": "Dictionary in Python - III" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/amicable-pair0804/1", +"solutionLink": "#", +"problemName": "Amicable Pair" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/count-odd-factors0844/1", +"solutionLink": "#", +"problemName": "Count Odd Factors" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/check-if-a-given-string-is-a-rotation-of-a-palindrome0317/1", +"solutionLink": "#", +"problemName": "Check if a given string is a rotation of a palindrome" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/rotate-matrix-elements-clockwise2336/1", +"solutionLink": "#", +"problemName": "Rotate matrix elements clockwise" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/kth-distance3757/1", +"solutionLink": "#", +"problemName": "Kth distance" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/multimap-operations/1", +"solutionLink": "#", +"problemName": "Multimap Operations" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/consecutive-array-elements2711/1", +"solutionLink": "#", +"problemName": "Consecutive Array Elements" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/next-greater-even-number0828/1", +"solutionLink": "#", +"problemName": "Next Greater Even Number" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/missing-ranges-of-numbers1019/1", +"solutionLink": "#", +"problemName": "Missing ranges of numbers" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/assign-mice-holes3053/1", +"solutionLink": "#", +"problemName": "Assign Mice Holes" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-sum-of-divisors5636/1", +"solutionLink": "#", +"problemName": "Find sum of divisors " +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/ordering-of-strings5527/1", +"solutionLink": "#", +"problemName": "Ordering of strings" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/lucky-number0707/1", +"solutionLink": "#", +"problemName": "Lucky Number" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/cross-character2630/1", +"solutionLink": "#", +"problemName": "Cross character" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/string-modification-1587115621/1", +"solutionLink": "#", +"problemName": "String Modification" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/check-if-actual-binary-representation-of-a-number-is-palindrome0624/1", +"solutionLink": "#", +"problemName": "Check if actual binary representation of a number is palindrome" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/largest-zigzag-sequence5416/1", +"solutionLink": "#", +"problemName": "Largest zigzag sequence" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/minimal-moves-to-form-a-string4331/1", +"solutionLink": "#", +"problemName": "Minimal moves to form a string" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/happy-number1408/1", +"solutionLink": "#", +"problemName": "Happy Number" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/subtraction-and-two-numbers0816/1", +"solutionLink": "#", +"problemName": "Subtraction and two numbers" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/structs-and-objects/1", +"solutionLink": "#", +"problemName": "Structs and Objects" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/even-subsets/1", +"solutionLink": "#", +"problemName": "Even Subsets" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/magic-number4431/1", +"solutionLink": "#", +"problemName": "Magic Number" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-stl-priority-queue/1", +"solutionLink": "#", +"problemName": "C++ STL Priority Queue" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-the-most-frequent-digit4432/1", +"solutionLink": "#", +"problemName": "Find the most frequent digit" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-maximum-value/1", +"solutionLink": "#", +"problemName": "Find Maximum value" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/swap-bits5726/1", +"solutionLink": "#", +"problemName": "Swap bits" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/product-of-prime-factors5121/1", +"solutionLink": "#", +"problemName": "Product of Prime Factors" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/kth-prime-factor-of-a-number0132/1", +"solutionLink": "#", +"problemName": "Kth Prime Factor" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/xor-linked-list/1", +"solutionLink": "#", +"problemName": "XOR Linked List" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/triangle-and-square--170637/1", +"solutionLink": "#", +"problemName": "Triangle and Square" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/maximum-number-of-characters-between-any-two-same-character4552/1", +"solutionLink": "#", +"problemName": "Maximum number of characters between any two same character" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/print-this-pattern0709/1", +"solutionLink": "#", +"problemName": "Print this pattern!" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/distinct-substrings2516/1", +"solutionLink": "#", +"problemName": "Distinct Substrings" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-multi-level-inheritance/1", +"solutionLink": "#", +"problemName": "C++ Multi-level inheritance" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/adding-one2529/1", +"solutionLink": "#", +"problemName": "Adding One" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/remove-minimum-elements4612/1", +"solutionLink": "#", +"problemName": "Remove minimum elements" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/partition-a-number-into-two-divisible-parts3605/1", +"solutionLink": "#", +"problemName": "Partition a number into two divisible parts" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/does-robot-moves-circular0414/1", +"solutionLink": "#", +"problemName": "Does robot moves circular" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/minimum-number-of-deletions-to-make-a-sorted-sequence3248/1", +"solutionLink": "#", +"problemName": "Minimum number of deletions to make a sorted sequence" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/maximum-sum-of-increasing-order-elements-from-n-arrays4848/1", +"solutionLink": "#", +"problemName": "Maximum sum of increasing order elements from n arrays" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/number-that-are-not-divisible4541/1", +"solutionLink": "#", +"problemName": "Number that are not divisible" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/deficient-number1612/1", +"solutionLink": "#", +"problemName": "Deficient Number" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/minimum-distinct-ids3251/1", +"solutionLink": "#", +"problemName": "Minimum Distinct Ids" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/k-ary-tree1235/1", +"solutionLink": "#", +"problemName": "K-Ary Tree" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-the-highest-occurring-digit-in-prime-numbers-in-a-range3634/1", +"solutionLink": "#", +"problemName": "Find the highest occurring digit in prime numbers in a range" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-stl-set-2-pair/1", +"solutionLink": "#", +"problemName": "C++ STL | Set 2 (pair)" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/largest-even-number3821/1", +"solutionLink": "#", +"problemName": "Largest Even Number" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/pair-with-greatest-product-in-array3342/1", +"solutionLink": "#", +"problemName": "Pair with greatest product in array" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/chocolate-station2951/1", +"solutionLink": "#", +"problemName": "Chocolate Station" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/regular-expressions-2-python/1", +"solutionLink": "#", +"problemName": "Regular Expressions 2 - Python" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-all-possible-paths-from-top-to-bottom/1", +"solutionLink": "#", +"problemName": "Find all possible paths from top to bottom" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-maximum-number2152/1", +"solutionLink": "#", +"problemName": "Find maximum number" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/binary-tree-representation/1", +"solutionLink": "#", +"problemName": "Binary Tree Representation" +}, +{ +"difficulty": "Easy", +"gfgLink": "https://www.geeksforgeeks.org/problems/count-digits-in-a-factorial3957/1", +"solutionLink": "#", +"problemName": "Count digits in a factorial" +} +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GeeksforGeeks website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/gfg-problems/hard/0001-0100.md b/problems/gfg-problems/hard/0001-0100.md new file mode 100644 index 0000000..0596468 --- /dev/null +++ b/problems/gfg-problems/hard/0001-0100.md @@ -0,0 +1,622 @@ +--- +id: 0001-0100 +title: GFG hard problems 0001-0100 +sidebar_label: 0001-0100 +keywords: + - gfg problems + - gfg problems hard + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/merge-two-sorted-arrays-1587115620/1", + "solutionLink": "#", + "problemName": "Merge Without Extra Space" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-a-linked-list-in-groups-of-given-size/1", + "solutionLink": "#", + "problemName": "Reverse a Linked List in groups of given size" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/edit-distance3702/1", + "solutionLink": "#", + "problemName": "Edit Distance" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-path-sum/1", + "solutionLink": "#", + "problemName": "Maximum Path Sum between 2 Special Nodes" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-rectangular-area-in-a-histogram-1587115620/1", + "solutionLink": "#", + "problemName": "Maximum Rectangular Area in a Histogram" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-sum-partition3317/1", + "solutionLink": "#", + "problemName": "Minimum sum partition" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/lru-cache/1", + "solutionLink": "#", + "problemName": "LRU Cache" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/palindromic-patitioning4845/1", + "solutionLink": "#", + "problemName": "Palindromic Partitioning" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-window-in-a-string-containing-all-the-characters-of-another-string-1587115621/1", + "solutionLink": "#", + "problemName": "Smallest window in a string containing all the characters of another string" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/binary-tree-to-dll/1", + "solutionLink": "#", + "problemName": "Binary Tree to DLL" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-median-in-a-stream-1587115620/1", + "solutionLink": "#", + "problemName": "Find median in a stream" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/boolean-parenthesization5610/1", + "solutionLink": "#", + "problemName": "Boolean Parenthesization" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/median-of-2-sorted-arrays-of-different-sizes/1", + "solutionLink": "#", + "problemName": "Median of 2 Sorted Arrays of Different Sizes" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/matrix-chain-multiplication0303/1", + "solutionLink": "#", + "problemName": "Matrix Chain Multiplication" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-prefix-suffix2527/1", + "solutionLink": "#", + "problemName": "Longest Prefix Suffix" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-painters-partition-problem1535/1", + "solutionLink": "#", + "problemName": "The Painter's Partition Problem-II" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-rectangle/1", + "solutionLink": "#", + "problemName": "Max rectangle" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-circular-subarray-sum-1587115620/1", + "solutionLink": "#", + "problemName": "Max Circular Subarray Sum" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/alien-dictionary/1", + "solutionLink": "#", + "problemName": "Alien Dictionary" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/median-in-a-row-wise-sorted-matrix1527/1", + "solutionLink": "#", + "problemName": "Median in a row-wise sorted Matrix" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/solve-the-sudoku-1587115621/1", + "solutionLink": "#", + "problemName": "Solve the Sudoku" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-valid-parentheses5657/1", + "solutionLink": "#", + "problemName": "Longest valid Parentheses" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/form-a-palindrome1455/1", + "solutionLink": "#", + "problemName": "Form a palindrome" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-cost-path3833/1", + "solutionLink": "#", + "problemName": "Minimum Cost Path" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/nodes-at-given-distance-in-binary-tree/1", + "solutionLink": "#", + "problemName": "Nodes at given distance in binary tree" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/subtraction-in-linked-list/1", + "solutionLink": "#", + "problemName": "Subtraction in Linked List" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/n-queen-problem0315/1", + "solutionLink": "#", + "problemName": "N-Queen Problem" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/clone-a-linked-list-with-next-and-random-pointer/1", + "solutionLink": "#", + "problemName": "Clone a linked list with next and random pointer" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/distinct-occurrences/1", + "solutionLink": "#", + "problemName": "Distinct occurrences" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-distinct-subsequences0909/1", + "solutionLink": "#", + "problemName": "Number of distinct subsequences" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/next-smallest-palindrome4740/1", + "solutionLink": "#", + "problemName": "Next Smallest Palindrome" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/permutations-of-a-given-string-1587115620/1", + "solutionLink": "#", + "problemName": "String Permutations" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/wildcard-string-matching1126/1", + "solutionLink": "#", + "problemName": "Wildcard string matching" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/reorder-list/1", + "solutionLink": "#", + "problemName": "Reorder List" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/merge-two-bst-s/1", + "solutionLink": "#", + "problemName": "Merge two BST 's" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/aggressive-cows/1", + "solutionLink": "#", + "problemName": "Aggressive Cows" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/circle-of-strings4530/1", + "solutionLink": "#", + "problemName": "Circle of strings" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/burning-tree/1", + "solutionLink": "#", + "problemName": "Burning Tree" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/wildcard-pattern-matching/1", + "solutionLink": "#", + "problemName": "Wildcard Pattern Matching" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/nth-natural-number/1", + "solutionLink": "#", + "problemName": "Nth Natural Number" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-pairs-in-an-array4145/1", + "solutionLink": "#", + "problemName": "Count Pairs in an Array" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/articulation-point-1/1", + "solutionLink": "#", + "problemName": "Articulation Point - I" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-smaller-elements2214/1", + "solutionLink": "#", + "problemName": "Count Smaller elements" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimize-max-distance-to-gas-station/1", + "solutionLink": "#", + "problemName": "Minimize Max Distance to Gas Station" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/generalised-fibonacci-numbers1820/1", + "solutionLink": "#", + "problemName": "Generalised Fibonacci numbers" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/split-array-largest-sum--141634/1", + "solutionLink": "#", + "problemName": "Split Array Largest Sum" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/better-string/1", + "solutionLink": "#", + "problemName": "Better String" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/fixed-two-nodes-of-a-bst/1", + "solutionLink": "#", + "problemName": "Fixing Two nodes of a BST" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/convert-to-strictly-increasing-array3351/1", + "solutionLink": "#", + "problemName": "Strictly Increasing Array" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-repeating-and-non-overlapping-substring3421/1", + "solutionLink": "#", + "problemName": "Longest repeating and non-overlapping substring" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-sum-of-different-corresponding-bits-for-all-pairs4652/1", + "solutionLink": "#", + "problemName": "Bit Difference" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/closest-palindrome4519/1", + "solutionLink": "#", + "problemName": "Closest Palindrome" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-points-to-reach-destination0540/1", + "solutionLink": "#", + "problemName": "Minimum Points To Reach Destination" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/avl-tree-insertion/1", + "solutionLink": "#", + "problemName": "AVL Tree Insertion" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/word-wrap1646/1", + "solutionLink": "#", + "problemName": "Word Wrap" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/merge-sort-on-doubly-linked-list/1", + "solutionLink": "#", + "problemName": "Merge Sort on Doubly Linked List" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/word-ladder/1", + "solutionLink": "#", + "problemName": "Word Ladder I" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/phone-directory4628/1", + "solutionLink": "#", + "problemName": "Phone directory" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-positive-integer-that-can-not-be-represented-as-sum--141631/1", + "solutionLink": "#", + "problemName": "Smallest Positive Integer that can not be represented as Sum" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-of-minimum-for-every-window-size3453/1", + "solutionLink": "#", + "problemName": "Maximum of minimum for every window size" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/partition-array-to-k-subsets/1", + "solutionLink": "#", + "problemName": "Partition array to K subsets" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/making-a-large-island/1", + "solutionLink": "#", + "problemName": "Making A Large Island" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-characters-to-be-added-at-front-to-make-string-palindrome/1", + "solutionLink": "#", + "problemName": "Minimum characters to be added at front to make string palindrome" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/avl-tree-deletion/1", + "solutionLink": "#", + "problemName": "AVL Tree Deletion" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/candy/1", + "solutionLink": "#", + "problemName": "Candy" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-rectangular-sub-matrix-whose-sum-is-0/1", + "solutionLink": "#", + "problemName": "Largest rectangular sub-matrix whose sum is 0" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/account-merge/1", + "solutionLink": "#", + "problemName": "Account Merge" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/next-happy-number4538/1", + "solutionLink": "#", + "problemName": "Next Happy Number" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-profit4657/1", + "solutionLink": "#", + "problemName": "Maximum Profit" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/critical-connections/1", + "solutionLink": "#", + "problemName": "Find all Critical Connections in the Graph" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/brackets-in-matrix-chain-multiplication1024/1", + "solutionLink": "#", + "problemName": "Brackets in Matrix Chain Multiplication" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/return-two-prime-numbers2509/1", + "solutionLink": "#", + "problemName": "Return two prime numbers" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-string3151/1", + "solutionLink": "#", + "problemName": "Sum-string" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/word-break-part-23249/1", + "solutionLink": "#", + "problemName": "Word Break - Part 2" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-xor-subarray--141631/1", + "solutionLink": "#", + "problemName": "Maximum XOR subarray" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/box-stacking/1", + "solutionLink": "#", + "problemName": "Box Stacking" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-subset-xor/1", + "solutionLink": "#", + "problemName": "Maximum subset XOR" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-last-digit-of-ab-for-large-numbers1936/1", + "solutionLink": "#", + "problemName": "Find Last Digit Of a^b for Large Numbers" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/distribute-candies-in-a-binary-tree/1", + "solutionLink": "#", + "problemName": "Distribute candies in a binary tree" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/geek-collects-the-balls5515/1", + "solutionLink": "#", + "problemName": "Geek collects the balls" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/special-digits--170647/1", + "solutionLink": "#", + "problemName": "Special Digits" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/word-ladder-ii/1", + "solutionLink": "#", + "problemName": "Word Ladder II" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-smallest-range-containing-elements-from-k-lists/1", + "solutionLink": "#", + "problemName": "Smallest range in K lists" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/possible-paths--141628/1", + "solutionLink": "#", + "problemName": "Possible Paths in a Tree" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/vertex-cover/1", + "solutionLink": "#", + "problemName": "Vertex Cover" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/geekina-hate-1s/1", + "solutionLink": "#", + "problemName": "Geekina Hate 1s" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-string/1", + "solutionLink": "#", + "problemName": "Find the String" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-sum-cycle--170645/1", + "solutionLink": "#", + "problemName": "Largest Sum Cycle" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-number-of-closed-islands/1", + "solutionLink": "#", + "problemName": "Find number of closed islands" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/redundant-parenthesis--170647/1", + "solutionLink": "#", + "problemName": "Redundant Parenthesis" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/walls-coloring-ii--170647/1", + "solutionLink": "#", + "problemName": "Walls Coloring II" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/strongly-connected-component-tarjanss-algo-1587115621/1", + "solutionLink": "#", + "problemName": "Strongly connected component (Tarjans's Algo)" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/distinct-palindromic-substrings5141/1", + "solutionLink": "#", + "problemName": "Distinct palindromic substrings" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-binary-strings-with-no-consecutive-1s/1", + "solutionLink": "#", + "problemName": "Count Binary Strings With No Consecutive 1s" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/min-time--170648/1", + "solutionLink": "#", + "problemName": "Min Time" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-all-lcs-sequences3413/1", + "solutionLink": "#", + "problemName": "Print all LCS sequences" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/sorted-list-to-bst/1", + "solutionLink": "#", + "problemName": "Sorted Link List to BST" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/cake-distribution-problem--170647/1", + "solutionLink": "#", + "problemName": "Cake Distribution Problem" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-number-of-toys/1", + "solutionLink": "#", + "problemName": "Maximum Number of Toys" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/expression-add-operators/1", + "solutionLink": "#", + "problemName": "Expression Add Operators" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GFG website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/hard/0101-0200.md b/problems/gfg-problems/hard/0101-0200.md new file mode 100644 index 0000000..7252944 --- /dev/null +++ b/problems/gfg-problems/hard/0101-0200.md @@ -0,0 +1,634 @@ +--- +id: 0101-0200 +title: GFG hard problems 0101-0200 +sidebar_label: 0101-0200 +keywords: + - gfg problems + - gfg problems hard + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/binary-tree-to-dll/1", + "solutionLink": "/dsa-solutions/gfg-solutions/Hard/0101-0200/binary-tree-to-dll", + "problemName": "Binary Tree to DLL" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/lru-cache/1", + "solutionLink": "/dsa-solutions/gfg-solutions/Hard/0101-0200/lru-cache", + "problemName": "LRU Cache" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-turns-in-binary-tree/1", + "solutionLink": "#", + "problemName": "Number of Turns in Binary Tree" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-bst-sum-subtree--170647/1", + "solutionLink": "#", + "problemName": "Minimum BST Sum Subtree" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/partition-the-array--170647/1", + "solutionLink": "#", + "problemName": "Partition the Array" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/shortest-path-by-removing-k-walls/1", + "solutionLink": "#", + "problemName": "Shortest Path by Removing K walls" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/scrambled-string/1", + "solutionLink": "#", + "problemName": "Scrambled String" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/travelling-salesman-problem2732/1", + "solutionLink": "#", + "problemName": "Travelling Salesman Problem" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/divide-in-incremental-groups--170647/1", + "solutionLink": "#", + "problemName": "Divide in Incremental Groups" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/game-of-subsets/1", + "solutionLink": "#", + "problemName": "Game Of Subsets" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/132-geeky-buildings--141631/1", + "solutionLink": "#", + "problemName": "132 Geeky Buildings" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/median-of-the-subarrays--170647/1", + "solutionLink": "#", + "problemName": "Median of the Subarrays" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-number-of-coins--170647/1", + "solutionLink": "#", + "problemName": "Maximum Number of coins" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/fixing-two-swapped-nodes-of-a-bst--170646/1", + "solutionLink": "#", + "problemName": "Fixing Two swapped nodes of a BST" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/palindrome-pairs/1", + "solutionLink": "#", + "problemName": "Palindrome Pairs" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/water-connection-problem5822/1", + "solutionLink": "#", + "problemName": "Water Connection Problem" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/shortest-path-using-atmost-one-curved-edge--170647/1", + "solutionLink": "#", + "problemName": "Shortest Path Using Atmost One Curved Edge" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-formation3506/1", + "solutionLink": "#", + "problemName": "Number Formation" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/avoid-explosion--170647/1", + "solutionLink": "#", + "problemName": "Avoid Explosion" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/ipl-2021-final--141634/1", + "solutionLink": "#", + "problemName": "IPL 2021 - Final" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-min-height--170647/1", + "solutionLink": "#", + "problemName": "Max min Height" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/select-nodes--170645/1", + "solutionLink": "#", + "problemName": "Select Nodes" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-occurences-of-a-given-word-in-a-2-d-array/1", + "solutionLink": "#", + "problemName": "Count occurrences of a given word in a 2-d array" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-connected-group/1", + "solutionLink": "#", + "problemName": "Maximum Connected group" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-insertions-to-make-two-arrays-equal/1", + "solutionLink": "#", + "problemName": "Minimum operations to convert array A to B" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-the-substring--170645/1", + "solutionLink": "#", + "problemName": "Count the Substring" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-a-sublist-of-a-linked-list/1", + "solutionLink": "#", + "problemName": "Reverse a sublist of a linked list" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-lucky-permutations--170645/1", + "solutionLink": "#", + "problemName": "Count Lucky Permutations" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/burst-balloons/1", + "solutionLink": "#", + "problemName": "Burst Balloons" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/shortest-unique-prefix-for-every-word/1", + "solutionLink": "#", + "problemName": "Shortest Unique prefix for every word" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/assignment-problem3016/1", + "solutionLink": "#", + "problemName": "Assignment Problem" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/x-xor-a-is-minimum-and-set-bits-in-x-b/1", + "solutionLink": "#", + "problemName": "Minimum X (xor) A" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/convex-hull2138/1", + "solutionLink": "#", + "problemName": "Convex Hull" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/adventure-in-a-maze2051/1", + "solutionLink": "#", + "problemName": "Adventure in a Maze" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/ncr-mod-m-part-10038/1", + "solutionLink": "#", + "problemName": "nCr mod M | Part 1" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-subsets-with-product-less-than-k/1", + "solutionLink": "#", + "problemName": "Number of subsets with product less than k" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-the-number-of-subarrays/1", + "solutionLink": "#", + "problemName": "Count the number of subarrays" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-tree-traversal--141628/1", + "solutionLink": "#", + "problemName": "Check Tree Traversal" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-path-in-a-matrix3019/1", + "solutionLink": "#", + "problemName": "Longest Path in a matrix" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/bike-racing0543/1", + "solutionLink": "#", + "problemName": "Bike Racing" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/word-break-trie--141631/1", + "solutionLink": "#", + "problemName": "Word Break (Trie)" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/chocolates-pickup/1", + "solutionLink": "#", + "problemName": "Chocolates Pickup" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/huffman-decoding/1", + "solutionLink": "#", + "problemName": "Huffman Decoding" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-zig-zag-sub-sequence2656/1", + "solutionLink": "#", + "problemName": "Longest Zig-Zag Sub Sequence" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/optimal-binary-search-tree2214/1", + "solutionLink": "#", + "problemName": "Optimal binary search tree" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-time-to-fulfil-all-orders/1", + "solutionLink": "#", + "problemName": "Minimum time to fulfil all orders" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-maximum-flow2126/1", + "solutionLink": "#", + "problemName": "Find the Maximum Flow" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-palindromic-substring-in-linear-time/1", + "solutionLink": "#", + "problemName": "Longest Palindromic Substring in Linear Time" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/points-in-straight-line/1", + "solutionLink": "#", + "problemName": "Points in Straight Line" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/articulation-point2616/1", + "solutionLink": "#", + "problemName": "Articulation Point - II" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/interesting-queries4742/1", + "solutionLink": "#", + "problemName": "Interesting Queries" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-distinct-words-with-k-maximum-contiguous-vowels--141631/1", + "solutionLink": "#", + "problemName": "Number of distinct words with K maximum contiguous vowels" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-substring-whose-character-rearranged-can-form-a-palindrome/1", + "solutionLink": "#", + "problemName": "Longest substring to form a Palindrome" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/corona-vaccine--141631/1", + "solutionLink": "#", + "problemName": "Corona Vaccine" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/kill-captain-america0228/1", + "solutionLink": "#", + "problemName": "Kill Captain America" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/geek-in-a-maze--170637/1", + "solutionLink": "#", + "problemName": "Geek in a Maze" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-increasing-path-in-a-matrix/1", + "solutionLink": "#", + "problemName": "Longest Increasing Path in a Matrix" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/array-partition/1", + "solutionLink": "#", + "problemName": "Array Partition" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-largest-rectangle-of-1s-with-swapping-of-columns-allowed0243/1", + "solutionLink": "#", + "problemName": "Largest rectangle of 1s with swapping of columns allowed" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-invalid-parentheses/1", + "solutionLink": "#", + "problemName": "Remove Invalid Parentheses" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/lets-play0201/1", + "solutionLink": "#", + "problemName": "Let's Play!!!" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/doctor-strange2206/1", + "solutionLink": "#", + "problemName": "Doctor Strange" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-reverse-pairs/1", + "solutionLink": "#", + "problemName": "Count Reverse Pairs" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-swap-required-to-convert-binary-tree-to-binary-search-tree/1", + "solutionLink": "#", + "problemName": "Minimum swap required to convert binary tree to binary search tree" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/secret-cipher--141631/1", + "solutionLink": "#", + "problemName": "Secret Cipher" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-xor-subset0715/1", + "solutionLink": "#", + "problemName": "Maximum XOR subset" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-path-in-a-directed-acyclic-graph/1", + "solutionLink": "#", + "problemName": "Longest Path in a Directed Acyclic Graph" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-number-to-make-median-x3029/1", + "solutionLink": "#", + "problemName": "Minimum number to make median X" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/kth-smallest-number-in-multiplication-table/1", + "solutionLink": "#", + "problemName": "Kth Smallest Number in Multiplication Table" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/nth-digit-of-pie5851/1", + "solutionLink": "#", + "problemName": "Nth digit of pi" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/elixir-of-life--141631/1", + "solutionLink": "#", + "problemName": "Elixir of Life" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/all-numbers-with-specific-difference3558/1", + "solutionLink": "#", + "problemName": "All numbers with specific difference" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-pairs-1645358985/1", + "solutionLink": "#", + "problemName": "Number of pairs" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/rearrange-the-array-1639032648/1", + "solutionLink": "#", + "problemName": "Rearrange the array" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/shortest-range-in-bst--141631/1", + "solutionLink": "#", + "problemName": "Shortest Range In BST" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/search-query-auto-complete/1", + "solutionLink": "#", + "problemName": "Search Query Auto Complete" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/cut-woods/1", + "solutionLink": "#", + "problemName": "Cut woods" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/intersecting-intervals/1", + "solutionLink": "#", + "problemName": "Maximum number of overlapping Intervals" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/create-your-own-calculator4308/1", + "solutionLink": "#", + "problemName": "Create your own Calculator" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/very-tough-problem2653/1", + "solutionLink": "#", + "problemName": "Very Tough Problem" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-number-of-elements-which-are-not-part-of-increasing-or-decreasing-subsequence2617/1", + "solutionLink": "#", + "problemName": "Minimum number of elements" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-minimum-s-t-cut-in-a-flow-network2902/1", + "solutionLink": "#", + "problemName": "Find minimum s-t cut in a flow network" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/lfu-cache-1665050355/1", + "solutionLink": "#", + "problemName": "LFU cache" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/sid-and-his-prime-money5736/1", + "solutionLink": "#", + "problemName": "Sid and his prime money" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-difference-between-pair-in-a-matrix/1", + "solutionLink": "#", + "problemName": "Maximum difference between pair in a matrix" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-palindrome-pattern3900/1", + "solutionLink": "#", + "problemName": "The Palindrome Pattern" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-pattern4155/1", + "solutionLink": "#", + "problemName": "Find the pattern" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/akku-and-arrays4452/1", + "solutionLink": "#", + "problemName": "Akku and Arrays" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/subset-sums-between-the-given-range/1", + "solutionLink": "#", + "problemName": "Subset sums between the given range" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/partition-a-set-into-two-subsets-such-that-the-difference-of-subset-sums-is-minimum-set-2/1", + "solutionLink": "#", + "problemName": "Partition a set into two subsets such that the difference of subset sums is minimum (Set-2)" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/k-centers-problem/1", + "solutionLink": "#", + "problemName": "K Centers Problem" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/ipl-2021-match-day-6-semi-final--141634/1", + "solutionLink": "#", + "problemName": "IPL 2021 - Match Day 6 - Semi Final" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-xor-with-an-element-from-array/1", + "solutionLink": "#", + "problemName": "Maximum XOR With an Element From Array" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/next-optimal-move-in-tic-tac-toe2842/1", + "solutionLink": "#", + "problemName": "Next Optimal Move in Tic Tac Toe" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/hexadecimal-to-decimal-counter1627/1", + "solutionLink": "#", + "problemName": "Hexadecimal to decimal counter" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-triple-product/1", + "solutionLink": "#", + "problemName": "Maximum Triple Product" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/total-number-of-spanning-trees-in-a-graph/1", + "solutionLink": "#", + "problemName": "Total Number Of Spanning Trees In A Graph" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-travel-time/1", + "solutionLink": "#", + "problemName": "Minimum travel time" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-number-of-sprinkler--170645/1", + "solutionLink": "#", + "problemName": "Minimum Number Of Sprinkler" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/joey-doesnt-share-food5712/1", + "solutionLink": "#", + "problemName": "Joey doesn't share food" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/greater-or-less--170646/1", + "solutionLink": "#", + "problemName": "Greater or Less" + }, + { + "difficulty": "Hard", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-cost-to-merge-stones/1", + "solutionLink": "#", + "problemName": "Minimum Cost to Merge Stones" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GFG website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/medium/0001-0100.md b/problems/gfg-problems/medium/0001-0100.md new file mode 100644 index 0000000..30fb162 --- /dev/null +++ b/problems/gfg-problems/medium/0001-0100.md @@ -0,0 +1,622 @@ +--- +id: 0001-0100 +title: GFG medium problems 0001-0100 +sidebar_label: 0001-0100 +keywords: + - gfg problems + - gfg problems medium + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/subarray-with-given-sum-1587115621/1", + "solutionLink": "#", + "problemName": "Find Indexes of a subarray with given sum" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1", + "solutionLink": "#", + "problemName": "Kadane's Algorithm" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-number-of-jumps-1587115620/1", + "solutionLink": "#", + "problemName": "Minimum number of jumps" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s4231/1", + "solutionLink": "#", + "problemName": "Sort an array of 0s, 1s and 2s" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/majority-element-1587115620/1", + "solutionLink": "#", + "problemName": "Majority Element" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/kth-smallest-element5635/1", + "solutionLink": "#", + "problemName": "Kth smallest element" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimize-the-heights3351/1", + "solutionLink": "#", + "problemName": "Minimize the Heights II" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/inversion-of-array-1587115620/1", + "solutionLink": "#", + "problemName": "Count Inversions" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-loop-in-linked-list/1", + "solutionLink": "#", + "problemName": "Remove loop in Linked List" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/detect-loop-in-linked-list/1", + "solutionLink": "#", + "problemName": "Detect Loop in linked list" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-platforms-1587115620/1", + "solutionLink": "#", + "problemName": "Minimum Platforms" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/trapping-rain-water-1587115621/1", + "solutionLink": "#", + "problemName": "Trapping Rain Water" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-missing-and-repeating2512/1", + "solutionLink": "#", + "problemName": "Find Missing And Repeating" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/0-1-knapsack-problem0945/1", + "solutionLink": "#", + "problemName": "0 - 1 Knapsack Problem" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/detect-cycle-in-an-undirected-graph/1", + "solutionLink": "#", + "problemName": "Detect cycle in an undirected graph" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/next-larger-element-1587115620/1", + "solutionLink": "#", + "problemName": "Next Greater Element" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/detect-cycle-in-a-directed-graph/1", + "solutionLink": "#", + "problemName": "Detect cycle in a directed graph" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-product-subarray3604/1", + "solutionLink": "#", + "problemName": "Maximum Product Subarray" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/boundary-traversal-of-binary-tree/1", + "solutionLink": "#", + "problemName": "Boundary Traversal of binary tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-positive-missing-number-1587115621/1", + "solutionLink": "#", + "problemName": "Smallest Positive missing number" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-triplets-with-zero-sum/1", + "solutionLink": "#", + "problemName": "Find triplets with zero sum" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-linked-list-is-pallindrome/1", + "solutionLink": "#", + "problemName": "Check if Linked List is Palindrome" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-of-all-subarrays-of-size-k3101/1", + "solutionLink": "#", + "problemName": "Maximum of all subarrays of size k" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/ncr1019/1", + "solutionLink": "#", + "problemName": "nCr" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-palindrome-in-a-string3411/1", + "solutionLink": "#", + "problemName": "Longest Palindrome in a String" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-consecutive-subsequence2449/1", + "solutionLink": "#", + "problemName": "Longest consecutive subsequence" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/power-of-numbers-1587115620/1", + "solutionLink": "#", + "problemName": "Power Of Numbers" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/top-view-of-binary-tree/1", + "solutionLink": "#", + "problemName": "Top View of Binary Tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-increasing-subsequence-1587115620/1", + "solutionLink": "#", + "problemName": "Longest Increasing Subsequence" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-subarray-with-0-sum/1", + "solutionLink": "#", + "problemName": "Largest subarray with 0 sum" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/triplet-sum-in-array-1587115621/1", + "solutionLink": "#", + "problemName": "Triplet Sum in Array" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/diameter-of-binary-tree/1", + "solutionLink": "#", + "problemName": "Diameter of a Binary Tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-common-subsequence-1587115620/1", + "solutionLink": "#", + "problemName": "Longest Common Subsequence" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/perfect-sum-problem5633/1", + "solutionLink": "#", + "problemName": "Perfect Sum Problem" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/add-two-numbers-represented-by-linked-lists/1", + "solutionLink": "#", + "problemName": "Add two numbers represented by linked lists" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/stock-buy-and-sell-1587115621/1", + "solutionLink": "#", + "problemName": "Stock buy and sell" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/intersection-point-in-y-shapped-linked-lists/1", + "solutionLink": "#", + "problemName": "Intersection Point in Y Shaped Linked Lists" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1", + "solutionLink": "#", + "problemName": "Subarray with 0 sum" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/permutations-of-a-given-string2041/1", + "solutionLink": "#", + "problemName": "Permutations of a given string" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-sub-array-with-sum-k0809/1", + "solutionLink": "#", + "problemName": "Longest Sub-Array with Sum K" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/first-and-last-occurrences-of-x3116/1", + "solutionLink": "#", + "problemName": "First and last occurrences of x" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/coin-change2448/1", + "solutionLink": "#", + "problemName": "Coin Change" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/row-with-max-1s0023/1", + "solutionLink": "#", + "problemName": "Row with max 1s" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/spirally-traversing-a-matrix-1587115621/1", + "solutionLink": "#", + "problemName": "Spirally traversing a matrix" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/rat-in-a-maze-problem/1", + "solutionLink": "#", + "problemName": "Rat in a Maze Problem - I" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/get-minimum-element-from-stack/1", + "solutionLink": "#", + "problemName": "Get minimum element from stack" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/fractional-knapsack-1587115620/1", + "solutionLink": "#", + "problemName": "Fractional Knapsack" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-index-1587115620/1", + "solutionLink": "#", + "problemName": "Maximum Index" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/-rearrange-array-alternately-1587115620/1", + "solutionLink": "#", + "problemName": "Rearrange Array Alternately" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/the-celebrity-problem/1", + "solutionLink": "#", + "problemName": "The Celebrity Problem" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/subset-sum-problem2014/1", + "solutionLink": "#", + "problemName": "Partition Equal Subset Sum" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/validate-an-ip-address-1587115621/1", + "solutionLink": "#", + "problemName": "Validate an IP Address" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-tree/1", + "solutionLink": "#", + "problemName": "Sum Tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/union-of-two-sorted-arrays-1587115621/1", + "solutionLink": "#", + "problemName": "Union of Two Sorted Arrays" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/bottom-view-of-binary-tree/1", + "solutionLink": "#", + "problemName": "Bottom View of Binary Tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/stickler-theif-1587115621/1", + "solutionLink": "#", + "problemName": "Stickler Thief" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/rotate-a-linked-list/1", + "solutionLink": "#", + "problemName": "Rotate a Linked List" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/k-th-element-of-two-sorted-array1317/1", + "solutionLink": "#", + "problemName": "K-th element of two Arrays" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/implement-atoi/1", + "solutionLink": "#", + "problemName": "Implement Atoi" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/pythagorean-triplet3018/1", + "solutionLink": "#", + "problemName": "Pythagorean Triplet" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-index3307/1", + "solutionLink": "#", + "problemName": "Maximum Index" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/multiply-two-strings/1", + "solutionLink": "#", + "problemName": "Multiply two strings" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/topological-sort/1", + "solutionLink": "#", + "problemName": "Topological sort" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/cutted-segments1642/1", + "solutionLink": "#", + "problemName": "Maximize The Cut Segments" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/subset-sum-problem-1611555638/1", + "solutionLink": "#", + "problemName": "Subset Sum Problem" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/job-sequencing-problem-1587115620/1", + "solutionLink": "#", + "problemName": "Job Sequencing Problem" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/first-non-repeating-character-in-a-stream1216/1", + "solutionLink": "#", + "problemName": "First non-repeating character in a stream" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-common-substring1452/1", + "solutionLink": "#", + "problemName": "Longest Common Substring" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/search-in-a-rotated-array4618/1", + "solutionLink": "#", + "problemName": "Search in a Rotated Array" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/quick-sort/1", + "solutionLink": "#", + "problemName": "Quick Sort" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/add-1-to-a-number-represented-as-linked-list/1", + "solutionLink": "#", + "problemName": "Add 1 to a number represented as linked list" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-all-four-sum-numbers1732/1", + "solutionLink": "#", + "problemName": "Find All Four Sum Numbers" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-ways-to-reach-the-nth-stair-1587115620/1", + "solutionLink": "#", + "problemName": "Count ways to reach the n'th stair" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-occurrence2259/1", + "solutionLink": "#", + "problemName": "Number of occurrence" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/allocate-minimum-number-of-pages0937/1", + "solutionLink": "#", + "problemName": "Allocate minimum number of pages" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-sum-increasing-subsequence4749/1", + "solutionLink": "#", + "problemName": "Maximum sum increasing subsequence" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-number-of-islands/1", + "solutionLink": "#", + "problemName": "Find the number of islands" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-a-binary-tree-in-vertical-order/1", + "solutionLink": "#", + "problemName": "Vertical Traversal of Binary Tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/stock-span-problem-1587115621/1", + "solutionLink": "#", + "problemName": "Stock span problem" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-binary-tree/1", + "solutionLink": "#", + "problemName": "Lowest Common Ancestor in a Binary Tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/recursively-remove-all-adjacent-duplicates0744/1", + "solutionLink": "#", + "problemName": "Recursively remove all adjacent duplicates" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-coins1824/1", + "solutionLink": "#", + "problemName": "Number of Coins" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/circular-tour-1587115620/1", + "solutionLink": "#", + "problemName": "Circular tour" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/bipartite-graph/1", + "solutionLink": "#", + "problemName": "Bipartite Graph" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/construct-tree-1/1", + "solutionLink": "#", + "problemName": "Construct Tree from Inorder & Preorder" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/zigzag-tree-traversal/1", + "solutionLink": "#", + "problemName": "ZigZag Tree Traversal" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/merge-sort/1", + "solutionLink": "#", + "problemName": "Merge Sort" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-swaps/1", + "solutionLink": "#", + "problemName": "Minimum Swaps to Sort" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-number-formed-from-an-array1117/1", + "solutionLink": "#", + "problemName": "Largest Number formed from an Array" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/k-largest-elements4206/1", + "solutionLink": "#", + "problemName": "k largest elements" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-total-set-bits-1587115620/1", + "solutionLink": "#", + "problemName": "Count total set bits" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/implementing-dijkstra-set-1-adjacency-matrix/1", + "solutionLink": "#", + "problemName": "Implementing Dijkstra Algorithm" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/merge-two-sorted-linked-lists/1", + "solutionLink": "#", + "problemName": "Merge two sorted linked lists" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/first-negative-integer-in-every-window-of-size-k3345/1", + "solutionLink": "#", + "problemName": "First negative integer in every window of size k" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/finding-the-numbers0215/1", + "solutionLink": "#", + "problemName": "Non Repeating Numbers" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-k-unique-characters-substring0853/1", + "solutionLink": "#", + "problemName": "Longest K unique characters substring" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/flattening-a-linked-list/1", + "solutionLink": "#", + "problemName": "Flattening a Linked List" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/factorials-of-large-numbers2508/1", + "solutionLink": "#", + "problemName": "Factorials of large numbers" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/tower-of-hanoi-1587115621/1", + "solutionLink": "#", + "problemName": "Tower Of Hanoi" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/rotten-oranges2536/1", + "solutionLink": "#", + "problemName": "Rotten Oranges" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GFG website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/medium/0101-0200.md b/problems/gfg-problems/medium/0101-0200.md new file mode 100644 index 0000000..eb96e3e --- /dev/null +++ b/problems/gfg-problems/medium/0101-0200.md @@ -0,0 +1,622 @@ +--- +id: 0101-0200 +title: GFG medium problems 0101-0200 +sidebar_label: 0101-0200 +keywords: + - gfg problems + - gfg problems medium + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/egg-dropping-puzzle-1587115620/1", + "solutionLink": "#", + "problemName": "Egg Dropping Puzzle" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-subtree/1", + "solutionLink": "#", + "problemName": "Check if subtree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-palindromic-subsequences/1", + "solutionLink": "#", + "problemName": "Count Palindromic Subsequences" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/children-sum-parent/1", + "solutionLink": "#", + "problemName": "Check for Children Sum Property in a Binary Tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/total-decoding-messages1235/1", + "solutionLink": "#", + "problemName": "Total Decoding Messages" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/knapsack-with-duplicate-items4201/1", + "solutionLink": "#", + "problemName": "Knapsack with Duplicate Items" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/next-permutation5226/1", + "solutionLink": "#", + "problemName": "Next Permutation" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-swaps-required-to-bring-all-elements-less-than-or-equal-to-k-together4847/1", + "solutionLink": "#", + "problemName": "Minimum swaps and K together" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/array-pair-sum-divisibility-problem3257/1", + "solutionLink": "#", + "problemName": "Array Pair Sum Divisibility Problem" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-repeating-subsequence2004/1", + "solutionLink": "#", + "problemName": "Longest Repeating Subsequence" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/activity-selection-1587115620/1", + "solutionLink": "#", + "problemName": "Activity Selection" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/nth-catalan-number0817/1", + "solutionLink": "#", + "problemName": "Nth catalan number" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/zero-sum-subarrays1825/1", + "solutionLink": "#", + "problemName": "Zero Sum Subarrays" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/word-break1352/1", + "solutionLink": "#", + "problemName": "Word Break" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/implementing-floyd-warshall2042/1", + "solutionLink": "#", + "problemName": "Floyd Warshall" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/valid-substring0624/1", + "solutionLink": "#", + "problemName": "Valid Substring" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/friends-pairing-problem5425/1", + "solutionLink": "#", + "problemName": "Friends Pairing Problem" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/min-distance-between-two-given-nodes-of-a-binary-tree/1", + "solutionLink": "#", + "problemName": "Min distance between two given nodes of a Binary Tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/gold-mine-problem2608/1", + "solutionLink": "#", + "problemName": "Gold Mine Problem" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/two-repeated-elements-1587115621/1", + "solutionLink": "#", + "problemName": "Two Repeated Elements" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/shortest-common-supersequence0322/1", + "solutionLink": "#", + "problemName": "Shortest Common Supersequence" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-bst/1", + "solutionLink": "#", + "problemName": "Largest BST" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-length-chain/1", + "solutionLink": "#", + "problemName": "Max length chain" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/sorted-insert-for-circular-linked-list/1", + "solutionLink": "#", + "problemName": "Sorted insert for circular linked list" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-spanning-tree/1", + "solutionLink": "#", + "problemName": "Minimum Spanning Tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/delete-a-node-from-bst/1", + "solutionLink": "#", + "problemName": "Delete a node from BST" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/m-coloring-problem-1587115620/1", + "solutionLink": "#", + "problemName": "M-Coloring Problem" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/boolean-matrix-problem-1587115620/1", + "solutionLink": "#", + "problemName": "Boolean Matrix" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-frequencies4211/1", + "solutionLink": "#", + "problemName": "Check if frequencies can be equal" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/lucky-numbers2911/1", + "solutionLink": "#", + "problemName": "Lucky Numbers" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/rod-cutting0840/1", + "solutionLink": "#", + "problemName": "Rod Cutting" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-k-th-smallest-element-in-bst/1", + "solutionLink": "#", + "problemName": "k-th smallest element in BST" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/heap-sort/1", + "solutionLink": "#", + "problemName": "Heap Sort" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/rearrange-an-array-with-o1-extra-space3142/1", + "solutionLink": "#", + "problemName": "Rearrange an array with O(1) extra space" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-paths0926/1", + "solutionLink": "#", + "problemName": "Number of paths" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/length-of-the-longest-substring3036/1", + "solutionLink": "#", + "problemName": "Length of the longest substring" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/flood-fill-algorithm1856/1", + "solutionLink": "#", + "problemName": "Flood fill Algorithm" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/stock-buy-and-sell2615/1", + "solutionLink": "#", + "problemName": "Stock buy and sell II" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/shortest-source-to-destination-path3544/1", + "solutionLink": "#", + "problemName": "Shortest Source to Destination Path" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/sort-a-stack/1", + "solutionLink": "#", + "problemName": "Sort a stack" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/predecessor-and-successor/1", + "solutionLink": "#", + "problemName": "Predecessor and Successor" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/consecutive-1s-not-allowed1912/1", + "solutionLink": "#", + "problemName": "Consecutive 1's not allowed" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/steps-by-knight5927/1", + "solutionLink": "#", + "problemName": "Steps by Knight" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/pascal-triangle0652/1", + "solutionLink": "#", + "problemName": "Pascal Triangle" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-sum-without-adjacents2430/1", + "solutionLink": "#", + "problemName": "Max Sum without Adjacents" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/combination-sum-1587115620/1", + "solutionLink": "#", + "problemName": "Combination Sum" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-tree-is-isomorphic/1", + "solutionLink": "#", + "problemName": "Check if Tree is Isomorphic" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/kth-ancestor-in-a-tree/1", + "solutionLink": "#", + "problemName": "Kth Ancestor in a Tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/subset-sums2234/1", + "solutionLink": "#", + "problemName": "Subset Sums" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/painting-the-fence3727/1", + "solutionLink": "#", + "problemName": "Painting the Fence" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-prime-factor2601/1", + "solutionLink": "#", + "problemName": "Largest prime factor" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/path-in-matrix3805/1", + "solutionLink": "#", + "problemName": "Maximum path sum in matrix" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/relative-sorting4323/1", + "solutionLink": "#", + "problemName": "Sort an array according to the other" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-numbers-or-number1219/1", + "solutionLink": "#", + "problemName": "Sum of two large numbers" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-the-longest-bloodline-of-a-tree/1", + "solutionLink": "#", + "problemName": "Sum of nodes on the longest path from root to leaf node" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/replace-os-with-xs0052/1", + "solutionLink": "#", + "problemName": "Replace O's with X's" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-possible-triangles-1587115620/1", + "solutionLink": "#", + "problemName": "Count the number of possible triangles" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-the-subarrays-having-product-less-than-k1708/1", + "solutionLink": "#", + "problemName": "Count the subarrays having product less than k" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/shortest-path-in-undirected-graph/1", + "solutionLink": "#", + "problemName": "Shortest path in Directed Acyclic Graph" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/k-sum-paths/1", + "solutionLink": "#", + "problemName": "K Sum Paths" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/distance-from-the-source-bellman-ford-algorithm/1", + "solutionLink": "#", + "problemName": "Distance from the Source (Bellman-Ford Algorithm)" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/is-binary-tree-heap/1", + "solutionLink": "#", + "problemName": "Is Binary Tree Heap" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/duplicate-subtree-in-binary-tree/1", + "solutionLink": "#", + "problemName": "Duplicate subtree in Binary Tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/connect-nodes-at-same-level/1", + "solutionLink": "#", + "problemName": "Connect Nodes at Same Level" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/power-set4302/1", + "solutionLink": "#", + "problemName": "Power Set" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/swapping-pairs-make-sum-equal4142/1", + "solutionLink": "#", + "problemName": "Swapping pairs make sum equal" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-provinces/1", + "solutionLink": "#", + "problemName": "Number of Provinces" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/interleaved-strings/1", + "solutionLink": "#", + "problemName": "Interleaved Strings" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-sum4058/1", + "solutionLink": "#", + "problemName": "Minimum sum" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-distant-window3132/1", + "solutionLink": "#", + "problemName": "Smallest distinct window" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-number-of-substrings4528/1", + "solutionLink": "#", + "problemName": "Count number of substrings" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-number-in-k-swaps-1587115620/1", + "solutionLink": "#", + "problemName": "Largest number in K swaps" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/search-in-a-matrix-1587115621/1", + "solutionLink": "#", + "problemName": "Search in a row-column sorted Matrix" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-multiplications-to-reach-end/1", + "solutionLink": "#", + "problemName": "Minimum Multiplications to reach End" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-subarray-with-sum-divisible-by-k1259/1", + "solutionLink": "#", + "problemName": "Longest subarray with sum divisible by K" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/partitions-with-given-difference/1", + "solutionLink": "#", + "problemName": "Partitions with Given Difference" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/top-k-frequent-elements-in-array/1", + "solutionLink": "#", + "problemName": "Top K Frequent Elements in Array - I" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-triplets-with-sum-smaller-than-x5549/1", + "solutionLink": "#", + "problemName": "Count triplets with sum smaller than X" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/merge-k-sorted-arrays/1", + "solutionLink": "#", + "problemName": "Merge k Sorted Arrays" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-palindromic-subsequence-1612327878/1", + "solutionLink": "#", + "problemName": "Longest Palindromic Subsequence" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/segregate-even-and-odd-nodes-in-a-linked-list5035/1", + "solutionLink": "#", + "problemName": "Segregate even and odd nodes in a Linked List" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-sub-array5443/1", + "solutionLink": "#", + "problemName": "Maximum Sub Array" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/element-appearing-once2552/1", + "solutionLink": "#", + "problemName": "Find the element that appears once" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-square-formed-in-a-matrix0806/1", + "solutionLink": "#", + "problemName": "Largest square formed in a matrix" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-whether-path-exist5238/1", + "solutionLink": "#", + "problemName": "Find whether path exist" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/optimal-strategy-for-a-game-1587115620/1", + "solutionLink": "#", + "problemName": "Optimal Strategy For A Game" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/word-boggle4143/1", + "solutionLink": "#", + "problemName": "Word Boggle" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/strongly-connected-components-kosarajus-algo/1", + "solutionLink": "#", + "problemName": "Strongly Connected Components (Kosaraju's Algo)" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/distance-of-nearest-cell-having-1-1587115620/1", + "solutionLink": "#", + "problemName": "Distance of nearest cell having 1" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/root-to-leaf-paths/1", + "solutionLink": "#", + "problemName": "Root to Leaf Paths" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/operations-on-binary-min-heap/1", + "solutionLink": "#", + "problemName": "Binary Heap Operations" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/diagonal-traversal-of-binary-tree/1", + "solutionLink": "#", + "problemName": "Diagonal Traversal of Binary Tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/serialize-and-deserialize-a-binary-tree/1", + "solutionLink": "#", + "problemName": "Serialize and deserialize a binary tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/merge-k-sorted-linked-lists/1", + "solutionLink": "#", + "problemName": "Merge K sorted linked lists" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-closest-element-in-bst/1", + "solutionLink": "#", + "problemName": "Find the Closest Element in BST" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/column-name-from-a-given-column-number4244/1", + "solutionLink": "#", + "problemName": "Column name from a given column number" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/kth-largest-element-in-a-stream2220/1", + "solutionLink": "#", + "problemName": "Kth largest element in a stream" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/unique-bsts-1587115621/1", + "solutionLink": "#", + "problemName": "Unique BST's" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/mother-vertex/1", + "solutionLink": "#", + "problemName": "Mother Vertex" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-string-in-grid0111/1", + "solutionLink": "#", + "problemName": "Find the string in grid" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GFG website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/medium/0201-0300.md b/problems/gfg-problems/medium/0201-0300.md new file mode 100644 index 0000000..62d7edb --- /dev/null +++ b/problems/gfg-problems/medium/0201-0300.md @@ -0,0 +1,622 @@ +--- +id: 0201-0300 +title: GFG medium problems 0201-0300 +sidebar_label: 0201-0300 +keywords: + - gfg problems + - gfg problems medium + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-whether-bst-contains-dead-end/1", + "solutionLink": "#", + "problemName": "Check whether BST contains Dead End" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/tree-from-postorder-and-inorder/1", + "solutionLink": "#", + "problemName": "Construct Binary Tree from Inorder and Postorder" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/infix-to-postfix-1587115620/1", + "solutionLink": "#", + "problemName": "Infix to Postfix" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/two-numbers-with-sum-closest-to-zero1737/1", + "solutionLink": "#", + "problemName": "Sum of two elements with sum nearest to zero" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/choose-and-swap0531/1", + "solutionLink": "#", + "problemName": "Choose and Swap" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/counting-elements-in-two-arrays/1", + "solutionLink": "#", + "problemName": "Counting elements in two arrays" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-subsequence-such-that-difference-between-adjacents-is-one4724/1", + "solutionLink": "#", + "problemName": "Longest subsequence-1" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-occurences-of-anagrams5839/1", + "solutionLink": "#", + "problemName": "Count Occurences of Anagrams" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-a-stack/1", + "solutionLink": "#", + "problemName": "Reverse a Stack" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-enclaves/1", + "solutionLink": "#", + "problemName": "Number Of Enclaves" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/lcs-of-three-strings0028/1", + "solutionLink": "#", + "problemName": "LCS of three strings" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimize-the-heights-i/1", + "solutionLink": "#", + "problemName": "Minimize the Heights I" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-cost-to-fill-given-weight-in-a-bag1956/1", + "solutionLink": "#", + "problemName": "Minimum cost to fill given weight in a bag" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-sum-in-the-configuration/1", + "solutionLink": "#", + "problemName": "Max sum in the configuration" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/sort-a-linked-list/1", + "solutionLink": "#", + "problemName": "Merge Sort for Linked List" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-k-digits/1", + "solutionLink": "#", + "problemName": "Remove K Digits" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/k-closest-elements3619/1", + "solutionLink": "#", + "problemName": "K closest elements" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-distinct-islands/1", + "solutionLink": "#", + "problemName": "Number of Distinct Islands" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/implementing-ceil-in-bst/1", + "solutionLink": "#", + "problemName": "Ceil in BST" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/arranging-the-array1131/1", + "solutionLink": "#", + "problemName": "Arranging the array" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-path-sum-from-any-node/1", + "solutionLink": "#", + "problemName": "Maximum path sum from any node" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/node-at-distance/1", + "solutionLink": "#", + "problemName": "Count the nodes at distance K from leaf" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/course-schedule/1", + "solutionLink": "#", + "problemName": "Course Schedule" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/jump-game/1", + "solutionLink": "#", + "problemName": "Jump Game" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-difference-between-node-and-its-ancestor/1", + "solutionLink": "#", + "problemName": "Maximum difference between node and its ancestor" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/prerequisite-tasks/1", + "solutionLink": "#", + "problemName": "Prerequisite Tasks" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/length-of-largest-region-of-1s-1587115620/1", + "solutionLink": "#", + "problemName": "Unit Area of largest region of 1's" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-the-n-th-character5925/1", + "solutionLink": "#", + "problemName": "Find the N-th character" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/search-pattern-rabin-karp-algorithm--141631/1", + "solutionLink": "#", + "problemName": "Search Pattern (Rabin-Karp Algorithm)" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-common-nodes-in-bst/1", + "solutionLink": "#", + "problemName": "Find Common Nodes in two BSTs" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-the-reversals0401/1", + "solutionLink": "#", + "problemName": "Count the Reversals" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-anagrams-together/1", + "solutionLink": "#", + "problemName": "Print Anagrams Together" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/negative-weight-cycle3504/1", + "solutionLink": "#", + "problemName": "Negative weight cycle" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/ipl-2021-match-day-2--141634/1", + "solutionLink": "#", + "problemName": "IPL 2021 - Match Day 2" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-sum-of-non-adjacent-nodes/1", + "solutionLink": "#", + "problemName": "Maximum sum of Non-adjacent nodes" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-bitonic-subsequence0824/1", + "solutionLink": "#", + "problemName": "Longest Bitonic subsequence" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-middle-elements-of-two-sorted-arrays2305/1", + "solutionLink": "#", + "problemName": "Sum of Middle Elements of two sorted arrays" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-meetings-in-one-room/1", + "solutionLink": "#", + "problemName": "Maximum Meetings in One Room" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-sum-combination/1", + "solutionLink": "#", + "problemName": "Maximum Sum Combination" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/trie-insert-and-search0651/1", + "solutionLink": "#", + "problemName": "Insert and Search in a Trie" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/jumping-numbers3805/1", + "solutionLink": "#", + "problemName": "Jumping Numbers" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/overlapping-intervals--170633/1", + "solutionLink": "#", + "problemName": "Overlapping Intervals" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/floor-in-bst/1", + "solutionLink": "#", + "problemName": "Floor in BST" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/bleak-numbers1552/1", + "solutionLink": "#", + "problemName": "Bleak Numbers" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/search-pattern0205/1", + "solutionLink": "#", + "problemName": "Search Pattern (KMP-Algorithm)" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/flip-bits0240/1", + "solutionLink": "#", + "problemName": "Flip Bits" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/possible-words-from-phone-digits-1587115620/1", + "solutionLink": "#", + "problemName": "Possible Words From Phone Digits" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/modular-exponentiation-for-large-numbers5537/1", + "solutionLink": "#", + "problemName": "Modular Exponentiation for large numbers" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/merge-2-sorted-linked-list-in-reverse-order/1", + "solutionLink": "#", + "problemName": "Merge 2 sorted linked list in reverse order" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-possible-ways-to-construct-buildings5007/1", + "solutionLink": "#", + "problemName": "Count possible ways to construct buildings" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/array-to-bst4443/1", + "solutionLink": "#", + "problemName": "Array to BST" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/union-of-two-linked-list/1", + "solutionLink": "#", + "problemName": "Union of Two Linked Lists" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/preorder-to-postorder4423/1", + "solutionLink": "#", + "problemName": "Preorder to BST" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/shortest-path-in-undirected-graph-having-unit-distance/1", + "solutionLink": "#", + "problemName": "Shortest path in Undirected Graph" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/shortest-path-in-a-binary-maze-1655453161/1", + "solutionLink": "#", + "problemName": "Shortest Distance in a Binary Maze" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/game-with-string4100/1", + "solutionLink": "#", + "problemName": "Game with String" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-sum-subarray-of-size-at-least-k3121/1", + "solutionLink": "#", + "problemName": "Largest Sum Subarray of Size at least K" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/eventual-safe-states/1", + "solutionLink": "#", + "problemName": "Eventual Safe States" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximize-dot-product2649/1", + "solutionLink": "#", + "problemName": "Maximize dot product" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/linked-list-that-is-sorted-alternatingly/1", + "solutionLink": "#", + "problemName": "Linked List that is Sorted Alternatingly" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-number-on-left3403/1", + "solutionLink": "#", + "problemName": "Smallest number on left" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/case-specific-sorting-of-strings4845/1", + "solutionLink": "#", + "problemName": "Case-specific Sorting of Strings" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/leftmost-and-rightmost-nodes-of-binary-tree/1", + "solutionLink": "#", + "problemName": "Leftmost and rightmost nodes of binary tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-deletitions1648/1", + "solutionLink": "#", + "problemName": "Minimum Deletions" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/kth-element-in-matrix/1", + "solutionLink": "#", + "problemName": "Kth element in Matrix" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-a-pair-with-given-target-in-bst/1", + "solutionLink": "#", + "problemName": "Find a pair with given target in BST" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-paths-in-a-matrix-with-k-coins2728/1", + "solutionLink": "#", + "problemName": "Number of paths in a matrix with k coins" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-occured-integer4602/1", + "solutionLink": "#", + "problemName": "Maximum occured integer" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/paths-to-reach-origin3850/1", + "solutionLink": "#", + "problemName": "Paths to reach origin" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/detect-cycle-using-dsu/1", + "solutionLink": "#", + "problemName": "Detect Cycle using DSU" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/swap-kth-node-from-beginning-and-kth-node-from-end-in-a-singly-linked-list/1", + "solutionLink": "#", + "problemName": "Swap Kth nodes from ends" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-all-substrings-of-a-number-1587115621/1", + "solutionLink": "#", + "problemName": "Sum of all substrings of a number" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/shuffle-integers2401/1", + "solutionLink": "#", + "problemName": "Shuffle integers" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-ways-to-arrive-at-destination/1", + "solutionLink": "#", + "problemName": "Number of Ways to Arrive at Destination" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/level-of-nodes-1587115620/1", + "solutionLink": "#", + "problemName": "Level of Nodes" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-following-a-pattern3126/1", + "solutionLink": "#", + "problemName": "Number following a pattern" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/given-a-linked-list-reverse-alternate-nodes-and-append-at-the-end/1", + "solutionLink": "#", + "problemName": "Reverse alternate nodes in Link List" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/normal-bst-to-balanced-bst/1", + "solutionLink": "#", + "problemName": "Normal BST to Balanced BST" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/nuts-and-bolts-problem0431/1", + "solutionLink": "#", + "problemName": "Nuts and Bolts Problem" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-pairs-1587115620/1", + "solutionLink": "#", + "problemName": "Number of pairs" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/buy-and-sell-a-share-at-most-twice/1", + "solutionLink": "#", + "problemName": "Buy and Sell a Share at most twice" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/excel-sheet5448/1", + "solutionLink": "#", + "problemName": "Excel Sheet | Part - 1" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-bit-differences2937/1", + "solutionLink": "#", + "problemName": "Sum of bit differences" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/binary-tree-to-cdll/1", + "solutionLink": "#", + "problemName": "Binary Tree to CDLL" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/vertical-sum/1", + "solutionLink": "#", + "problemName": "Vertical sum" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-tip-calculator2631/1", + "solutionLink": "#", + "problemName": "Maximum Tip Calculator" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/make-matrix-beautiful-1587115620/1", + "solutionLink": "#", + "problemName": "Make Matrix Beautiful" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/snake-and-ladder-problem4816/1", + "solutionLink": "#", + "problemName": "Snake and Ladder Problem" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/1", + "solutionLink": "#", + "problemName": "City With the Smallest Number of Neighbors at a Threshold Distance" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/most-frequent-word-in-an-array-of-strings3528/1", + "solutionLink": "#", + "problemName": "Most frequent word in an array of strings" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-subarrays-with-equal-number-of-1s-and-0s-1587115620/1", + "solutionLink": "#", + "problemName": "Subarrays with equal 1s and 0s" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-unique-paths5339/1", + "solutionLink": "#", + "problemName": "Number of Unique Paths" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-difference-1587115620/1", + "solutionLink": "#", + "problemName": "Maximum Difference" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-xor-of-all-pairs0723/1", + "solutionLink": "#", + "problemName": "Sum of XOR of all pairs" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-nth-element-of-spiral-matrix/1", + "solutionLink": "#", + "problemName": "Find kth element of spiral matrix" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/transitive-closure-of-a-graph0930/1", + "solutionLink": "#", + "problemName": "Transitive closure of a Graph" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/sorted-subsequence-of-size-3/1", + "solutionLink": "#", + "problemName": "Sorted subsequence of size 3" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/gray-to-binary-equivalent-1587115620/1", + "solutionLink": "#", + "problemName": "Gray to Binary equivalent" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/sorting-elements-of-an-array-by-frequency-1587115621/1", + "solutionLink": "#", + "problemName": "Sorting Elements of an Array by Frequency" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/add-binary-strings3805/1", + "solutionLink": "#", + "problemName": "Add Binary Strings" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GFG website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/medium/0301-0400.md b/problems/gfg-problems/medium/0301-0400.md new file mode 100644 index 0000000..9c44bbe --- /dev/null +++ b/problems/gfg-problems/medium/0301-0400.md @@ -0,0 +1,622 @@ +--- +id: 0301-0400 +title: GFG medium problems 0301-0400 +sidebar_label: 0301-0400 +keywords: + - gfg problems + - gfg problems medium + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/grinding-geek/1", + "solutionLink": "#", + "problemName": "Grinding Geek" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-element-occuring-once-when-all-other-are-present-thrice/1", + "solutionLink": "#", + "problemName": "Find element occuring once when all other are present thrice" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/word-search/1", + "solutionLink": "#", + "problemName": "Word Search" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-and-value-1587115620/1", + "solutionLink": "#", + "problemName": "Maximum AND Value" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-sum-path-in-two-arrays/1", + "solutionLink": "#", + "problemName": "Max sum path in two arrays" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-prime-numbers-in-a-range4718/1", + "solutionLink": "#", + "problemName": "Find Prime numbers in a range" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/diagonal-sum-in-binary-tree/1", + "solutionLink": "#", + "problemName": "Diagonal sum in binary tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/special-keyboard3018/1", + "solutionLink": "#", + "problemName": "Special Keyboard" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/bridge-edge-in-graph/1", + "solutionLink": "#", + "problemName": "Bridge edge in a graph" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/transform-to-prime4635/1", + "solutionLink": "#", + "problemName": "Transform to prime" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximize-number-of-1s0905/1", + "solutionLink": "#", + "problemName": "Maximize Number of 1's" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/a-simple-fraction0921/1", + "solutionLink": "#", + "problemName": "A Simple Fraction" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/top-k-numbers3425/1", + "solutionLink": "#", + "problemName": "Top k numbers in a stream" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/container-with-most-water0535/1", + "solutionLink": "#", + "problemName": "Container With Most Water" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/reverse-each-word-in-a-given-string1001/1", + "solutionLink": "#", + "problemName": "Reverse each word in a given string" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-number-of-deletions-and-insertions0209/1", + "solutionLink": "#", + "problemName": "Minimum number of deletions and insertions." + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-ways-to-nth-stairorder-does-not-matter5639/1", + "solutionLink": "#", + "problemName": "Count ways to N'th Stair(Order does not matter)" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/game-of-death-in-a-circle1840/1", + "solutionLink": "#", + "problemName": "Find the Safe Position" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-good-components--170647/1", + "solutionLink": "#", + "problemName": "Number of Good Components" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/rearrange-a-linked-list/1", + "solutionLink": "#", + "problemName": "Rearrange a linked list" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/path-with-minimum-effort/1", + "solutionLink": "#", + "problemName": "Path With Minimum Effort" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/knight-walk4521/1", + "solutionLink": "#", + "problemName": "Knight Walk" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/buy-maximum-stocks-if-i-stocks-can-be-bought-on-i-th-day/1", + "solutionLink": "#", + "problemName": "Buy Maximum Stocks if i stocks can be bought on i-th day" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-n-bit-binary-numbers-having-more-1s-than-0s0252/1", + "solutionLink": "#", + "problemName": "Print N-bit binary numbers having more 1s than 0s" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-maximum-equal-sum-of-three-stacks/1", + "solutionLink": "#", + "problemName": "Find Maximum Equal sum of Three Stacks" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/three-sum-closest/1", + "solutionLink": "#", + "problemName": "Three Sum Closest" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/fraction-pairs-with-sum-1/1", + "solutionLink": "#", + "problemName": "Fraction pairs with sum 1" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-number-of-subtrees-having-given-sum/1", + "solutionLink": "#", + "problemName": "Count Number of SubTrees having given Sum" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/camelcase-pattern-matching2259/1", + "solutionLink": "#", + "problemName": "CamelCase Pattern Matching" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/3-divisors3942/1", + "solutionLink": "#", + "problemName": "3 Divisors" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/smith-number4132/1", + "solutionLink": "#", + "problemName": "Smith Number" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/two-numbers-with-odd-occurrences5846/1", + "solutionLink": "#", + "problemName": "Two numbers with odd occurrences" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/x-total-shapes3617/1", + "solutionLink": "#", + "problemName": "X Total Shapes" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-number-of-steps-to-reach-a-given-number5234/1", + "solutionLink": "#", + "problemName": "Minimum steps to destination" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/lemonade-change/1", + "solutionLink": "#", + "problemName": "Lemonade Change" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/foldable-binary-tree/1", + "solutionLink": "#", + "problemName": "Foldable Binary Tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/how-many-xs4514/1", + "solutionLink": "#", + "problemName": "How Many X's?" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/geek-and-its-game-of-coins4043/1", + "solutionLink": "#", + "problemName": "Geek and its Game of Coins" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/nearly-sorted-1587115620/1", + "solutionLink": "#", + "problemName": "Nearly sorted" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/subsets-1587115621/1", + "solutionLink": "#", + "problemName": "Unique Subsets" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-if-string-is-k-palindrome-or-not1923/1", + "solutionLink": "#", + "problemName": "K-Palindrome" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-special-numbers--170647/1", + "solutionLink": "#", + "problemName": "Count Special Numbers" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/duplicate-subtrees/1", + "solutionLink": "#", + "problemName": "Duplicate Subtrees" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-number-of-times-a-string-occurs-as-a-subsequence3020/1", + "solutionLink": "#", + "problemName": "String Subsequence" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-products5049/1", + "solutionLink": "#", + "problemName": "Sum of Products" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/transform-string5648/1", + "solutionLink": "#", + "problemName": "Transform String" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-two-nodes-are-cousins/1", + "solutionLink": "#", + "problemName": "Check if two Nodes are Cousins" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-factorial-number5929/1", + "solutionLink": "#", + "problemName": "Smallest factorial number" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/arrange-consonants-and-vowels/1", + "solutionLink": "#", + "problemName": "Arrange Consonants and Vowels" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/hamiltonian-path2522/1", + "solutionLink": "#", + "problemName": "Hamiltonian Path" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-if-a-string-is-repetition-of-its-substring-of-k-length3302/1", + "solutionLink": "#", + "problemName": "Check if a string is repetition of its substring of k-length" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/game-of-xor1541/1", + "solutionLink": "#", + "problemName": "Game of XOR" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/all-unique-permutations-of-an-array/1", + "solutionLink": "#", + "problemName": "All Unique Permutations of an array" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/prefix-match-with-other-strings/1", + "solutionLink": "#", + "problemName": "Prefix match with other strings" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/-matchsticks-game4906/1", + "solutionLink": "#", + "problemName": "Matchsticks game" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/rohans-love-for-matrix4723/1", + "solutionLink": "#", + "problemName": "Rohan's Love for Matrix" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/shortest-path-in-weighted-undirected-graph/1", + "solutionLink": "#", + "problemName": "Shortest Path in Weighted undirected graph" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/rotate-by-90-degree0356/1", + "solutionLink": "#", + "problemName": "Rotate by 90 degree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/flatten-binary-tree-to-linked-list/1", + "solutionLink": "#", + "problemName": "Flatten binary tree to linked list" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/combination-sum-ii-1664263832/1", + "solutionLink": "#", + "problemName": "Combination Sum II" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/determinant-of-a-matrix-1587115620/1", + "solutionLink": "#", + "problemName": "Determinant of a Matrix" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-difference-of-zeros-and-ones-in-binary-string4111/1", + "solutionLink": "#", + "problemName": "Maximum difference of zeros and ones in binary string" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/generate-ip-addresses/1", + "solutionLink": "#", + "problemName": "Generate IP Addresses" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-subsquare-surrounded-by-x0558/1", + "solutionLink": "#", + "problemName": "Largest subsquare surrounded by X" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/paths-from-root-with-a-specified-sum/1", + "solutionLink": "#", + "problemName": "Paths from root with a specified sum" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/exit-point-in-a-matrix0905/1", + "solutionLink": "#", + "problemName": "Exit Point in a Matrix" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/decode-the-string2444/1", + "solutionLink": "#", + "problemName": "Decode the string" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-sum-rectangle2948/1", + "solutionLink": "#", + "problemName": "Maximum sum Rectangle" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-number5829/1", + "solutionLink": "#", + "problemName": "Smallest number" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-distinct-pairs-with-difference-k1233/1", + "solutionLink": "#", + "problemName": "Count distinct pairs with difference k" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/construct-binary-tree-from-parent-array/1", + "solutionLink": "#", + "problemName": "Construct Binary Tree from Parent Array" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/insertion-sort-for-singly-linked-list/1", + "solutionLink": "#", + "problemName": "Insertion Sort for Singly Linked List" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/techfest-and-the-queue1044/1", + "solutionLink": "#", + "problemName": "Techfest and the Queue" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-swaps-for-bracket-balancing2704/1", + "solutionLink": "#", + "problemName": "Minimum Swaps for Bracket Balancing" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/generate-all-possible-parentheses/1", + "solutionLink": "#", + "problemName": "Generate Parentheses" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/restrictive-candy-crush--141631/1", + "solutionLink": "#", + "problemName": "Restrictive Candy Crush" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-duplicate-rows-in-a-binary-matrix/1", + "solutionLink": "#", + "problemName": "Find duplicate rows in a binary matrix" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/euler-circuit-and-path/1", + "solutionLink": "#", + "problemName": "Euler circuit and Path" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-arithmetic-progression1019/1", + "solutionLink": "#", + "problemName": "Longest Arithmetic Progression" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/additive-sequence/1", + "solutionLink": "#", + "problemName": "Additive sequence" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/populate-inorder-successor-for-all-nodes/1", + "solutionLink": "#", + "problemName": "Populate Inorder Successor for all nodes" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimize-the-difference/1", + "solutionLink": "#", + "problemName": "Minimize the Difference" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/huffman-encoding3345/1", + "solutionLink": "#", + "problemName": "Huffman Encoding" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/construct-list-using-given-q-xor-queries/1", + "solutionLink": "#", + "problemName": "Construct list using given q XOR queries" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-shortest-safe-route-in-a-matrix/1", + "solutionLink": "#", + "problemName": "Find shortest safe route in a matrix" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/preorder-traversal-and-bst4006/1", + "solutionLink": "#", + "problemName": "Preorder Traversal and BST" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/is-it-a-tree/1", + "solutionLink": "#", + "problemName": "Check if a given graph is tree or not" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/smaller-on-left20360700/1", + "solutionLink": "#", + "problemName": "Smaller on Left" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-matrix-in-diagonal-pattern/1", + "solutionLink": "#", + "problemName": "Print matrix in diagonal pattern" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/water-the-plants--170646/1", + "solutionLink": "#", + "problemName": "Water the plants" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/add-minimum-characters--170648/1", + "solutionLink": "#", + "problemName": "Add Minimum Characters" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/absolute-list-sorting/1", + "solutionLink": "#", + "problemName": "Absolute List Sorting" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-product-subset-of-an-array/1", + "solutionLink": "#", + "problemName": "Maximum product subset of an array" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-palindrome-in-a-string1956/1", + "solutionLink": "#", + "problemName": "Longest Palindromic Substring" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-subarrays-with-maximum-values-in-given-range5949/1", + "solutionLink": "#", + "problemName": "Number of subarrays with maximum values in given range" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-sum-of-hour-glass3842/1", + "solutionLink": "#", + "problemName": "Maximum sum of hour glass" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-absolute-difference-in-bst-1665139652/1", + "solutionLink": "#", + "problemName": "Minimum Absolute Difference In BST" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/make-binary-tree/1", + "solutionLink": "#", + "problemName": "Make Binary Tree From Linked List" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/add-all-greater-values-to-every-node-in-a-bst/1", + "solutionLink": "#", + "problemName": "Add all greater values to every node in a BST" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/euler-circuit-in-a-directed-graph/1", + "solutionLink": "#", + "problemName": "Euler Circuit in an Undirected Graph" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GeeksforGeeks website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/medium/0401-0500.md b/problems/gfg-problems/medium/0401-0500.md new file mode 100644 index 0000000..309b769 --- /dev/null +++ b/problems/gfg-problems/medium/0401-0500.md @@ -0,0 +1,622 @@ +--- +id: 0401-0500 +title: GFG medium problems 0401-0500 +sidebar_label: 0401-0500 +keywords: + - gfg problems + - gfg problems medium + - gfg problems problems +--- + + +export const problems = [ + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/get-minimum-squares0538/1", + "solutionLink": "#", + "problemName": "Get Minimum Squares" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/sequence-of-sequence1155/1", + "solutionLink": "#", + "problemName": "Sequence of Sequence" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-islands/1", + "solutionLink": "#", + "problemName": "Number Of Islands" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/good-by-2023/1", + "solutionLink": "#", + "problemName": "New Year Resolution" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-cost-to-make-two-strings-identical1107/1", + "solutionLink": "#", + "problemName": "Minimum Cost To Make Two Strings Identical" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/unique-paths-in-a-grid--170647/1", + "solutionLink": "#", + "problemName": "Unique Paths in a Grid" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-subsequences-of-type-ai-bj-ck4425/1", + "solutionLink": "#", + "problemName": "Count subsequences of type a^i, b^j, c^k" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-digit-groupings-of-a-number1520/1", + "solutionLink": "#", + "problemName": "Count digit groupings of a number" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/mobile-numeric-keypad5456/1", + "solutionLink": "#", + "problemName": "Mobile numeric keypad" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/preorder-traversal-iterative/1", + "solutionLink": "#", + "problemName": "Preorder traversal (Iterative)" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/large-factorial4721/1", + "solutionLink": "#", + "problemName": "Large Factorial" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/check-mirror-in-n-ary-tree1528/1", + "solutionLink": "#", + "problemName": "Check Mirror in N-ary tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/trail-of-ones3242/1", + "solutionLink": "#", + "problemName": "Trail of ones" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/inorder-traversal-iterative/1", + "solutionLink": "#", + "problemName": "Inorder Traversal (Iterative)" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/variation-in-nim-game4317/1", + "solutionLink": "#", + "problemName": "Modified Game of Nim" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/subarrays-with-sum-k/1", + "solutionLink": "#", + "problemName": "Subarrays with sum K" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/longest-alternating-subsequence5951/1", + "solutionLink": "#", + "problemName": "Longest alternating subsequence" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/asteroid-collision/1", + "solutionLink": "#", + "problemName": "Asteroid Collision" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/pairs-violating-bst-property--212515/1", + "solutionLink": "#", + "problemName": "Pairs violating the BST property" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/rearrange-characters4649/1", + "solutionLink": "#", + "problemName": "Rearrange characters" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/valid-compressed-string--170647/1", + "solutionLink": "#", + "problemName": "Valid Compressed String" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/rotate-a-2d-array-without-using-extra-space1004/1", + "solutionLink": "#", + "problemName": "Rotate a 2D array without using extra space" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/string-rp-or-pr--170647/1", + "solutionLink": "#", + "problemName": "String rp or pr" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/express-as-sum-of-power-of-natural-numbers5647/1", + "solutionLink": "#", + "problemName": "Express as sum of power of natural numbers" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/help-classmates--141631/1", + "solutionLink": "#", + "problemName": "Help Classmates" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/kth-common-ancestor-in-bst/1", + "solutionLink": "#", + "problemName": "Kth common ancestor in BST" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/castle-run3644/1", + "solutionLink": "#", + "problemName": "Traverse All Edges And Vertices" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/pattern/1", + "solutionLink": "#", + "problemName": "Pattern" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/dice-throw5349/1", + "solutionLink": "#", + "problemName": "Dice throw" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-of-subarrays5922/1", + "solutionLink": "#", + "problemName": "Count of Subarrays" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-k-th-smallest-element-in-given-n-ranges/1", + "solutionLink": "#", + "problemName": "Find k-th smallest element in given n ranges" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/subsets-1613027340/1", + "solutionLink": "#", + "problemName": "Subsets" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/clone-graph/1", + "solutionLink": "#", + "problemName": "Clone an Undirected Graph" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/min-coin5549/1", + "solutionLink": "#", + "problemName": "Min Coin" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-and-reverse--170634/1", + "solutionLink": "#", + "problemName": "Remove and Reverse" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/permutation-with-spaces3627/1", + "solutionLink": "#", + "problemName": "Permutation with Spaces" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/cheapest-flights-within-k-stops/1", + "solutionLink": "#", + "problemName": "Cheapest Flights Within K Stops" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/smaller-sum--170647/1", + "solutionLink": "#", + "problemName": "Smaller Sum" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/decode-the-pattern1138/1", + "solutionLink": "#", + "problemName": "Look and Say Pattern" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/cutting-binary-string1342/1", + "solutionLink": "#", + "problemName": "Cutting Binary String" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/postorder-traversal-iterative/1", + "solutionLink": "#", + "problemName": "Postorder Traversal (Iterative)" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/alternate-vowel-and-consonant-string2939/1", + "solutionLink": "#", + "problemName": "Alternate Vowel and Consonant String" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/print-diagonally1623/1", + "solutionLink": "#", + "problemName": "Anti Diagonal Traversal of Matrix" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/rotate-and-delete-1587115621/1", + "solutionLink": "#", + "problemName": "Rotate and delete" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/santa-banta2814/1", + "solutionLink": "#", + "problemName": "Santa Banta" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/special-matrix4201/1", + "solutionLink": "#", + "problemName": "Special Matrix" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/task-scheduler/1", + "solutionLink": "#", + "problemName": "Task Scheduler" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/target-sum-1626326450/1", + "solutionLink": "#", + "problemName": "Target Sum" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/equal-sum0810/1", + "solutionLink": "#", + "problemName": "Equal Sum" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-triplet-product--170647/1", + "solutionLink": "#", + "problemName": "Maximum Triplet product" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-subset-sum--170648/1", + "solutionLink": "#", + "problemName": "Maximum subset sum" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/next-greater-element/1", + "solutionLink": "#", + "problemName": "Next Greater Element in Circular Array" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-length--170647/1", + "solutionLink": "#", + "problemName": "Maximum Length" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/possible-paths-between-2-vertices-1587115620/1", + "solutionLink": "#", + "problemName": "Possible paths between 2 vertices" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/flatten-bst-to-sorted-list--111950/1", + "solutionLink": "#", + "problemName": "Flatten BST to sorted list" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/subarray-range-with-given-sum0128/1", + "solutionLink": "#", + "problemName": "Subarray range with given sum" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/shortest-prime-path--141631/1", + "solutionLink": "#", + "problemName": "Shortest Prime Path" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/composite-and-prime0359/1", + "solutionLink": "#", + "problemName": "Composite and Prime" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/product-of-primes5328/1", + "solutionLink": "#", + "problemName": "Product of Primes" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/make-array-elements-unique--170645/1", + "solutionLink": "#", + "problemName": "Make array elements unique" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/complete-binary-tree/1", + "solutionLink": "#", + "problemName": "Complete Binary Tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/remove-the-balls--170647/1", + "solutionLink": "#", + "problemName": "Remove the balls" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/string-formation-from-substring2734/1", + "solutionLink": "#", + "problemName": "String formation from substring" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/nearest-smaller-tower--170647/1", + "solutionLink": "#", + "problemName": "Nearest smaller tower" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/replace-every-element-with-the-least-greater-element-on-its-right/1", + "solutionLink": "#", + "problemName": "Replace every element with the least greater element on its right" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/number-of-ways2552/1", + "solutionLink": "#", + "problemName": "Number of ways" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-times-a-has-to-be-repeated-such-that-b-is-a-substring-of-it--170645/1", + "solutionLink": "#", + "problemName": "Minimum times A has to be repeated such that B is a substring of it" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/second-smallest-number--170647/1", + "solutionLink": "#", + "problemName": "Second smallest number" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/leaves-to-dll/1", + "solutionLink": "#", + "problemName": "Leaves to DLL" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/finding-profession3834/1", + "solutionLink": "#", + "problemName": "Finding Profession" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-palindrome-sub-strings-of-a-string0652/1", + "solutionLink": "#", + "problemName": "Count Palindrome Sub-Strings of a String" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/polynomial-addition/1", + "solutionLink": "#", + "problemName": "Polynomial Addition" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/shy-geek--170647/1", + "solutionLink": "#", + "problemName": "Shy Geek" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/array-removals/1", + "solutionLink": "#", + "problemName": "Array Removals" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/intersection-point-in-y-shaped-linked-lists--170645/1", + "solutionLink": "#", + "problemName": "Intersection Point in Y Shaped Linked Lists" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/prime-list--170646/1", + "solutionLink": "#", + "problemName": "Prime List" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/smallest-sum-contiguous-subarray/1", + "solutionLink": "#", + "problemName": "Smallest sum contiguous subarray" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/minimum-steps-required--170647/1", + "solutionLink": "#", + "problemName": "Minimum Steps Required" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/maximum-intersecting-lines--170647/1", + "solutionLink": "#", + "problemName": "Maximum Intersecting Lines" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/delete-nodes-greater-than-k/1", + "solutionLink": "#", + "problemName": "Delete nodes greater than k" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/hands-of-straights/1", + "solutionLink": "#", + "problemName": "Hands of Straights" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/length-of-the-longest-subarray-with-positive-product--170646/1", + "solutionLink": "#", + "problemName": "Length of the longest subarray with positive product" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/magic-triplets4003/1", + "solutionLink": "#", + "problemName": "Magic Triplets" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/is-sudoku-valid4820/1", + "solutionLink": "#", + "problemName": "Is Sudoku Valid" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/geek-and-number-string--141631/1", + "solutionLink": "#", + "problemName": "Geek and Number String" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-even-length1907/1", + "solutionLink": "#", + "problemName": "Count even length" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-pairs-in-array-divisible-by-k/1", + "solutionLink": "#", + "problemName": "Count pairs in array divisible by K" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/bst-maximum-difference--170647/1", + "solutionLink": "#", + "problemName": "BST Maximum Difference" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/another-coin-change-problem--170647/1", + "solutionLink": "#", + "problemName": "Another Coin Change Problem" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/subsets-with-xor-value2023/1", + "solutionLink": "#", + "problemName": "Subsets with XOR value" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/find-kth-permutation-0932/1", + "solutionLink": "#", + "problemName": "Find Kth permutation" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/max-coins--170647/1", + "solutionLink": "#", + "problemName": "Max Coins" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/stack-permutations/1", + "solutionLink": "#", + "problemName": "Stack Permutations" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/geeks-training/1", + "solutionLink": "#", + "problemName": "Geek's Training" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/black-and-white-1587115620/1", + "solutionLink": "#", + "problemName": "Black and White" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/largest-subtree-sum-in-a-tree/1", + "solutionLink": "#", + "problemName": "Largest subtree sum in a tree" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/distinct-coloring--170645/1", + "solutionLink": "#", + "problemName": "Distinct Coloring" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/prefix-suffix-string--170647/1", + "solutionLink": "#", + "problemName": "Prefix Suffix String" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/easy-task--170647/1", + "solutionLink": "#", + "problemName": "Easy Task" + }, + { + "difficulty": "Medium", + "gfgLink": "https://www.geeksforgeeks.org/problems/count-total-setbits/1", + "solutionLink": "#", + "problemName": "Count Total Setbits" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GeeksforGeeks website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/gfg-problems/medium/0501-0600.md b/problems/gfg-problems/medium/0501-0600.md new file mode 100644 index 0000000..afb1b9c --- /dev/null +++ b/problems/gfg-problems/medium/0501-0600.md @@ -0,0 +1,621 @@ +--- +id: 0501-0600 +title: GFG medium problems 0501-0600 +sidebar_label: 0501-0600 +keywords: + - gfg problems + - gfg problems medium + - gfg problems problems +--- + +export const problems = [ +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/maximum-possible-value--170647/1", +"solutionLink": "#", +"problemName": "Maximum Possible Value" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/geeks-and-the-string--170645/1", +"solutionLink": "#", +"problemName": "Geeks And The String" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/carpet-into-box--170645/1", +"solutionLink": "#", +"problemName": "Carpet into Box" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/max-sum-without-adjacents--170645/1", +"solutionLink": "#", +"problemName": "Max Sum without Adjacents" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/maximum-sum-leaf-to-root-path/1", +"solutionLink": "#", +"problemName": "Maximum sum leaf to root path" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/minimize-number-of-students-to-be-removed--170645/1", +"solutionLink": "#", +"problemName": "Minimize number of Students to be removed" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/tree-transformation--170648/1", +"solutionLink": "#", +"problemName": "Tree Transformation" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/divisibility-tree1902/1", +"solutionLink": "#", +"problemName": "Divisibility tree" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/shortest-xy-distance-in-grid--170647/1", +"solutionLink": "#", +"problemName": "Shortest XY distance in Grid" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/spiral-matrix--141631/1", +"solutionLink": "#", +"problemName": "Spiral Matrix" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/apple-sequences--170646/1", +"solutionLink": "#", +"problemName": "Apple Sequences" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/unequal-arrays--170647/1", +"solutionLink": "#", +"problemName": "Unequal Arrays" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/division-without-using-multiplication-division-and-mod-operator/1", +"solutionLink": "#", +"problemName": "Division without using multiplication, division and mod operator" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/even-swap/1", +"solutionLink": "#", +"problemName": "Even Swap" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/save-your-life4601/1", +"solutionLink": "#", +"problemName": "Save Your Life" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-number--170647/1", +"solutionLink": "#", +"problemName": "Find Number" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/minimum-number-of-deletions4610/1", +"solutionLink": "#", +"problemName": "Minimum number of deletions." +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/possible-paths3834/1", +"solutionLink": "#", +"problemName": "Possible paths" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/absolute-difference-divisible-by-k/1", +"solutionLink": "#", +"problemName": "Absolute difference divisible by K" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/count-cyclic-paths--170647/1", +"solutionLink": "#", +"problemName": "Count Cyclic Paths" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/geeks-village-and-wells--170647/1", +"solutionLink": "#", +"problemName": "Geek's Village and Wells" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/bst-downward-traversal--170646/1", +"solutionLink": "#", +"problemName": "BST Downward Traversal" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/champagne-overflow2636/1", +"solutionLink": "#", +"problemName": "Water Overflow" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/stepping-numberswrong-output1813/1", +"solutionLink": "#", +"problemName": "Stepping Numbers" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/police-and-thieves--141631/1", +"solutionLink": "#", +"problemName": "Police and Thieves" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/job-sequencing-problem--170647/1", +"solutionLink": "#", +"problemName": "Job Sequencing Problem" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/print-leaf-nodes-from-preorder-traversal-of-bst2657/1", +"solutionLink": "#", +"problemName": "Print leaf nodes from preorder traversal of BST" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/minimum-days--170646/1", +"solutionLink": "#", +"problemName": "Minimum Days" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/substrings-of-length-k-with-k-1-distinct-elements/1", +"solutionLink": "#", +"problemName": "Substrings of length k with k-1 distinct elements" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/modify-linked-list-1-0546/1", +"solutionLink": "#", +"problemName": "Modify Linked List-1" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-distinct-elements2054/1", +"solutionLink": "#", +"problemName": "Find distinct elements" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-patterns0606/1", +"solutionLink": "#", +"problemName": "Find patterns" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/update-queries--170647/1", +"solutionLink": "#", +"problemName": "Update Queries" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/fruit-into-baskets-1663137462/1", +"solutionLink": "#", +"problemName": "Fruit Into Baskets" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/palindrome-with-minimum-sum--170648/1", +"solutionLink": "#", +"problemName": "Palindrome with minimum sum" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/expression-contains-redundant-bracket-or-not/1", +"solutionLink": "#", +"problemName": "Expression contains redundant bracket or not" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/maximize-the-sum-of-selected-numbers-from-an-array-to-make-it-empty0836/1", +"solutionLink": "#", +"problemName": "Maximize the sum of selected numbers from a sorted array to make it empty" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/minimal-cost/1", +"solutionLink": "#", +"problemName": "Minimal Cost" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-prime4751/1", +"solutionLink": "#", +"problemName": "Sum Of Prime" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/coin-piles5152/1", +"solutionLink": "#", +"problemName": "Coin Piles" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-minimum-number-of-laptops-required--170645/1", +"solutionLink": "#", +"problemName": "Find minimum number of Laptops required" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/good-stones--170647/1", +"solutionLink": "#", +"problemName": "Good Stones" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/distinct-difference--170647/1", +"solutionLink": "#", +"problemName": "Distinct Difference" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/form-a-palindrome2544/1", +"solutionLink": "#", +"problemName": "Form a palindrome" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/transfiguration--141631/1", +"solutionLink": "#", +"problemName": "Transfiguration" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/a-difference-of-values-and-indexes0302/1", +"solutionLink": "#", +"problemName": "A difference of values and indexes" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/check-if-all-levels-of-two-trees-are-anagrams-or-not/1", +"solutionLink": "#", +"problemName": "Check if all levels of two trees are anagrams or not" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/maximum-intervals-overlap5708/1", +"solutionLink": "#", +"problemName": "Maximum Intervals Overlap" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/clone-a-binary-tree/1", +"solutionLink": "#", +"problemName": "Clone a Binary Tree" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/flattening-a-linked-list--170645/1", +"solutionLink": "#", +"problemName": "Flattening a Linked List" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/fibonacci-sum1423/1", +"solutionLink": "#", +"problemName": "Fibonacci Sum" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/max-sum-subarray-by-removing-at-most-one-element/1", +"solutionLink": "#", +"problemName": "Max sum subarray by removing at most one element" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/bheem-wants-ladoos--170647/1", +"solutionLink": "#", +"problemName": "Bheem Wants Ladoos" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/kth-smallest-factor2345/1", +"solutionLink": "#", +"problemName": "Kth Smallest Factor" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-all-distinct-subset-or-subsequence-sums4424/1", +"solutionLink": "#", +"problemName": "Find all distinct subset (or subsequence) sums" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-k-th-character-in-string3841/1", +"solutionLink": "#", +"problemName": "Find k-th character in string" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/length-of-longest-palindrome-in-linked-list/1", +"solutionLink": "#", +"problemName": "Length of longest palindrome in linked list" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/construct-tree-from-preorder-traversal/1", +"solutionLink": "#", +"problemName": "Construct Tree from Preorder Traversal" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/convert-level-order-traversal-to-bst/1", +"solutionLink": "#", +"problemName": "Convert Level Order Traversal to BST" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/construct-binary-tree-from-string-with-bracket-representation/1", +"solutionLink": "#", +"problemName": "Construct Binary Tree from String with bracket representation" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/super-primes2443/1", +"solutionLink": "#", +"problemName": "Super Primes" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/bst-to-max-heap/1", +"solutionLink": "#", +"problemName": "BST to max heap" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/geek-hates-too-many-1s--170647/1", +"solutionLink": "#", +"problemName": "Geek hates too many 1s" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/capacity-to-ship-packages-within-d-days/1", +"solutionLink": "#", +"problemName": "Capacity To Ship Packages Within D Days" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-subarrays2229/1", +"solutionLink": "#", +"problemName": "Sum of Subarrays" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/count-of-sum-of-consecutives3741/1", +"solutionLink": "#", +"problemName": "Count of sum of consecutives" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/walls-coloring--170646/1", +"solutionLink": "#", +"problemName": "Walls Coloring" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/valid-expression1025/1", +"solutionLink": "#", +"problemName": "Valid Expression" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/missing-number-in-matrix5316/1", +"solutionLink": "#", +"problemName": "Missing number in matrix" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/search-in-rotated-array-2/1", +"solutionLink": "#", +"problemName": "Search in Rotated Array 2" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/connect-nodes-at-same-level--170647/1", +"solutionLink": "#", +"problemName": "Connect Nodes at Same Level" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/fill-the-matrix--170647/1", +"solutionLink": "#", +"problemName": "Fill the Matrix" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-beauty-of-all-substrings-1662962118/1", +"solutionLink": "#", +"problemName": "Sum of Beauty of All Substrings" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/pots-of-gold-game/1", +"solutionLink": "#", +"problemName": "Pots of Gold Game" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/akku-and-binary-numbers0902/1", +"solutionLink": "#", +"problemName": "Akku and Binary Numbers" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/good-subtrees--170647/1", +"solutionLink": "#", +"problemName": "Good Subtrees" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/construct-a-full-binary-tree--170648/1", +"solutionLink": "#", +"problemName": "Construct a Full Binary Tree" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/close-to-perfection1525/1", +"solutionLink": "#", +"problemName": "Longest Perfect Piece" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/valid-pair-sum--141631/1", +"solutionLink": "#", +"problemName": "Valid Pair Sum" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/save-gotham1222/1", +"solutionLink": "#", +"problemName": "Save Gotham!" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-the-longest-string--170645/1", +"solutionLink": "#", +"problemName": "Find the longest string" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/lcm-triplet1501/1", +"solutionLink": "#", +"problemName": "LCM Triplet" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-largest-word-in-dictionary2430/1", +"solutionLink": "#", +"problemName": "Find largest word in dictionary" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/ways-to-write-n-as-sum-1587115621/1", +"solutionLink": "#", +"problemName": "Ways to write n as sum" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/tic-tac-toe2412/1", +"solutionLink": "#", +"problemName": "Tic Tac Toe" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/complement3911/1", +"solutionLink": "#", +"problemName": "Complement" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/handshakes1303/1", +"solutionLink": "#", +"problemName": "Handshakes" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/yet-another-query-problem--170647/1", +"solutionLink": "#", +"problemName": "Yet another query problem" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/minimum-x-xor-a--170645/1", +"solutionLink": "#", +"problemName": "Minimum X (xor) A" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/fill-up-buckets3500/1", +"solutionLink": "#", +"problemName": "Fill up buckets" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/special-palindrome-substrings--170647/1", +"solutionLink": "#", +"problemName": "Special Palindrome Substrings" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/quick-sort-on-linked-list/1", +"solutionLink": "#", +"problemName": "Quick Sort on Linked List" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/mila-and-strings0435/1", +"solutionLink": "#", +"problemName": "Lexicographically smallest string" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/build-the-smallest2841/1", +"solutionLink": "#", +"problemName": "Build the smallest" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/cat-and-hat-python/1", +"solutionLink": "#", +"problemName": "Cat and Hat" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/single-valued-subtree/1", +"solutionLink": "#", +"problemName": "Single valued subtree" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/knight-in-geekland--170647/1", +"solutionLink": "#", +"problemName": "Knight in Geekland" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/optimal-array--170647/1", +"solutionLink": "#", +"problemName": "Optimal Array" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-all-possible-palindromic-partitions-of-a-string/1", +"solutionLink": "#", +"problemName": "Find all possible palindromic partitions of a String" +}, +{ +"difficulty": "Medium", +"gfgLink": "https://www.geeksforgeeks.org/problems/merging-details/1", +"solutionLink": "#", +"problemName": "Merging Details" +} +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GeeksforGeeks website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/gfg-problems/school/0001-0100.md b/problems/gfg-problems/school/0001-0100.md new file mode 100644 index 0000000..16e483a --- /dev/null +++ b/problems/gfg-problems/school/0001-0100.md @@ -0,0 +1,621 @@ +--- +id: 0001-0100 +title: GFG school problems 0001-0100 +sidebar_label: 0001-0100 +keywords: + - gfg problems + - gfg problems school + - gfg problems problems +--- + +export const problems = [ +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-series2811/1", +"solutionLink": "#", +"problemName": "Sum of Series" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/value-equal-to-index-value1330/1", +"solutionLink": "#", +"problemName": "Value equal to index value" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/print-1-to-n-without-using-loops-1587115620/1", +"solutionLink": "#", +"problemName": "Print 1 To N Without Loop" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/print-alternate-elements-of-an-array/1", +"solutionLink": "#", +"problemName": "Print alternate elements of an array" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/palindromic-array-1587115620/1", +"solutionLink": "#", +"problemName": "Palindromic Array" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/print-the-pattern-set-1/1", +"solutionLink": "#", +"problemName": "Print the pattern | Set-1" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-the-median0527/1", +"solutionLink": "#", +"problemName": "Find the median" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/check-for-binary/1", +"solutionLink": "#", +"problemName": "Check for Binary" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-hello-world4004/1", +"solutionLink": "#", +"problemName": "Java Hello World" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/count-of-smaller-elements5947/1", +"solutionLink": "#", +"problemName": "Count of smaller elements" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-array2326/1", +"solutionLink": "#", +"problemName": "Sum of Array" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/print-elements-of-array4910/1", +"solutionLink": "#", +"problemName": "Print Elements of Array" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-index4752/1", +"solutionLink": "#", +"problemName": "Find Index" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/palindrome0746/1", +"solutionLink": "#", +"problemName": "Palindrome" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/reverse-digit0316/1", +"solutionLink": "#", +"problemName": "Reverse digits" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-if-else-decision-making0924/1", +"solutionLink": "#", +"problemName": "if-else (Decision Making)" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/gcd-of-two-numbers3459/1", +"solutionLink": "#", +"problemName": "GCD of two numbers" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/swap-kth-elements5500/1", +"solutionLink": "#", +"problemName": "Swap kth elements" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/display-longest-name0853/1", +"solutionLink": "#", +"problemName": "Display longest name" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/odd-or-even3618/1", +"solutionLink": "#", +"problemName": "Odd or Even" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-convert-string-to-lowercase2313/1", +"solutionLink": "#", +"problemName": "Convert String to LowerCase" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-array-print-an-element-set-25933/1", +"solutionLink": "#", +"problemName": "C++ Array (print an element) | Set 2" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/remove-spaces0128/1", +"solutionLink": "#", +"problemName": "Remove Spaces" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/perfect-arrays4645/1", +"solutionLink": "#", +"problemName": "Perfect Arrays" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/smaller-and-larger4005/1", +"solutionLink": "#", +"problemName": "Smaller and Larger" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-if-else-decision-making4138/1", +"solutionLink": "#", +"problemName": "C++ if-else (Decision Making)" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/addition-of-two-numbers0812/1", +"solutionLink": "#", +"problemName": "Addition of Two Numbers" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-digit-is-pallindrome-or-not2751/1", +"solutionLink": "#", +"problemName": "Sum of Digit is Pallindrome or not" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/series-ap5310/1", +"solutionLink": "#", +"problemName": "Series AP" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-reverse-a-string0416/1", +"solutionLink": "#", +"problemName": "Reverse a String" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/print-1-to-n-without-using-loops3621/1", +"solutionLink": "#", +"problemName": "Print 1 to n without using loops" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/at-least-two-greater-elements4625/1", +"solutionLink": "#", +"problemName": "At least two greater elements" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-input-output2432/1", +"solutionLink": "#", +"problemName": "C++ Input / Output" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/swap-two-numbers3844/1", +"solutionLink": "#", +"problemName": "Swap two numbers" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/print-table0303/1", +"solutionLink": "#", +"problemName": "Multiplication Table" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/reversing-the-vowels5304/1", +"solutionLink": "#", +"problemName": "Reversing the vowels" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-arrays-set-11354/1", +"solutionLink": "#", +"problemName": "Java Arrays | Set 1" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/upper-case-conversion5419/1", +"solutionLink": "#", +"problemName": "Upper case conversion" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/print-the-left-element2009/1", +"solutionLink": "#", +"problemName": "Print the left element" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-digits1742/1", +"solutionLink": "#", +"problemName": "Sum Of Digits" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/remove-vowels-from-string1446/1", +"solutionLink": "#", +"problemName": "Remove vowels from string" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/npr4253/1", +"solutionLink": "#", +"problemName": "nPr" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/average4856/1", +"solutionLink": "#", +"problemName": "Average in a stream" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/check-string1818/1", +"solutionLink": "#", +"problemName": "Check String" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/the-dice-problem2316/1", +"solutionLink": "#", +"problemName": "The dice problem" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/sum-palindrome3857/1", +"solutionLink": "#", +"problemName": "Sum Palindrome" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/vowel-or-not0831/1", +"solutionLink": "#", +"problemName": "Vowel or Not" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-switch-case-statement3529/1", +"solutionLink": "#", +"problemName": "Java Switch Case statement" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-strings-set-15112/1", +"solutionLink": "#", +"problemName": "Java Strings | Set 1" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-delete-alternate-characters4036/1", +"solutionLink": "#", +"problemName": "Delete alternate characters" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/compete-the-skills5807/1", +"solutionLink": "#", +"problemName": "Compete the skills" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-strings4609/1", +"solutionLink": "#", +"problemName": "C++ Strings" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-elements-in-a-matrix2000/1", +"solutionLink": "#", +"problemName": "Sum of elements in a matrix" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-the-camel3348/1", +"solutionLink": "#", +"problemName": "Count of camel case characters" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-functions-set-1introduction/1", +"solutionLink": "#", +"problemName": "C++ Functions (Sum of numbers) | Set 1" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/greatest-of-three-numbers2520/1", +"solutionLink": "#", +"problemName": "Greatest of three numbers" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-inputoutput0118/1", +"solutionLink": "#", +"problemName": "Java Input/Output" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-switch-case-statement5900/1", +"solutionLink": "#", +"problemName": "C++ Switch Case Statement" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/remainder-evaluation3755/1", +"solutionLink": "#", +"problemName": "Remainder Evaluation" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/convert-a-list-of-characters-into-a-string5142/1", +"solutionLink": "#", +"problemName": "Convert a list of characters into a String" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/lower-case-to-upper-case3410/1", +"solutionLink": "#", +"problemName": "Lower case to upper case" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/number-of-divisors1631/1", +"solutionLink": "#", +"problemName": "Number of divisors" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-2-d-arrays0708/1", +"solutionLink": "#", +"problemName": "C++ 2-D Arrays | Set-1" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-operators4602/1", +"solutionLink": "#", +"problemName": "C++ Operators | Set 1 (Arithmetic)" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/count-type-of-characters3635/1", +"solutionLink": "#", +"problemName": "Count type of Characters" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/simple-interest3457/1", +"solutionLink": "#", +"problemName": "Simple Interest" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-pointers-set-1introduction/1", +"solutionLink": "#", +"problemName": "C++ Pointers ( Incrementing a variable) | Set 1" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-n-th-term-of-series-1-3-6-10-15-215506/1", +"solutionLink": "#", +"problemName": "Find n-th term of series 1, 3, 6, 10, 15, 21" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/multiply-matrices/1", +"solutionLink": "#", +"problemName": "Multiply Matrices" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/binary-representation5003/1", +"solutionLink": "#", +"problemName": "Binary representation" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/mean0021/1", +"solutionLink": "#", +"problemName": "Mean" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/power-of-pow-even-number5440/1", +"solutionLink": "#", +"problemName": "Power of Pow | Even Number" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-inheritance/1", +"solutionLink": "#", +"problemName": "Java Inheritance" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-substring5058/1", +"solutionLink": "#", +"problemName": "Java Substring" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/remove-characters-from-alphanumeric-string0648/1", +"solutionLink": "#", +"problemName": "Remove characters from alphanumeric string" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/pattern-printing1347/1", +"solutionLink": "#", +"problemName": "Pattern Printing" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-ap-series4512/1", +"solutionLink": "#", +"problemName": "Sum of AP series" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/multiply-array-1658312632/1", +"solutionLink": "#", +"problemName": "Multiply Array" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-data-types1523/1", +"solutionLink": "#", +"problemName": "C++ Data Types" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/pattern-of-strings3829/1", +"solutionLink": "#", +"problemName": "Pattern of Strings" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-basic-data-types0041/1", +"solutionLink": "#", +"problemName": "Java Basic Data Types" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/full-prime2659/1", +"solutionLink": "#", +"problemName": "Full Prime" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/small-factorial0854/1", +"solutionLink": "#", +"problemName": "Small Factorial" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/perfect-number3759/1", +"solutionLink": "#", +"problemName": "Perfect Number" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/c-operators-relational-set-21407/1", +"solutionLink": "#", +"problemName": "C++ Operators (Relational) | Set 2" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/cube-root-of-a-number0915/1", +"solutionLink": "#", +"problemName": "Cube root of a number" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/split-strings5211/1", +"solutionLink": "#", +"problemName": "Split Strings" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/power-of-pow-odd-numbers1103/1", +"solutionLink": "#", +"problemName": "Power of Pow | Odd Numbers" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-loops-set-11726/1", +"solutionLink": "#", +"problemName": "Java loops | Set 1" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-odd-and-even-elements3033/1", +"solutionLink": "#", +"problemName": "Sum of odd and even elements" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/distance-between-2-points3200/1", +"solutionLink": "#", +"problemName": "Distance between 2 points" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/1s-complement2819/1", +"solutionLink": "#", +"problemName": "1s Complement" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/surface-area-and-volume-of-cuboid0522/1", +"solutionLink": "#", +"problemName": "Surface Area and Volume of Cuboid" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-gp2120/1", +"solutionLink": "#", +"problemName": "Sum of GP" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-operatorsrelational-set-22338/1", +"solutionLink": "#", +"problemName": "Java Operators(Relational) | Set - 2" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/extract-the-integers4428/1", +"solutionLink": "#", +"problemName": "Extract the integers" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-override/1", +"solutionLink": "#", +"problemName": "Java Override" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/floyds-triangle1222/1", +"solutionLink": "#", +"problemName": "Floyd's triangle" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/even-odd-sum5450/1", +"solutionLink": "#", +"problemName": "Even Odd Sum" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/identical-matrices1042/1", +"solutionLink": "#", +"problemName": "Identical Matrices" +} +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GeeksforGeeks website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/gfg-problems/school/0101-0123.md b/problems/gfg-problems/school/0101-0123.md new file mode 100644 index 0000000..9e52aeb --- /dev/null +++ b/problems/gfg-problems/school/0101-0123.md @@ -0,0 +1,159 @@ +--- +id: 0101-0123 +title: GFG school problems 0101-0123 +sidebar_label: 0101-0123 +keywords: + - gfg problems + - gfg problems school + - gfg problems problems +--- + +export const problems = [ +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/automorphic-number4721/1", +"solutionLink": "#", +"problemName": "Automorphic Number" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/triangle-shrinking-downwards0459/1", +"solutionLink": "#", +"problemName": "Triangle shrinking downwards" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/diagonal-sum0158/1", +"solutionLink": "#", +"problemName": "Diagonal sum" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/sum-of-an-ap1025/1", +"solutionLink": "#", +"problemName": "Sum of an AP" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/area-of-rectange-right-angled-triangle-and-circle2600/1", +"solutionLink": "#", +"problemName": "Area of Rectangle, Right Angled Triangle and Circle" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/find-difference-between-sum-of-diagonals1554/1", +"solutionLink": "#", +"problemName": "Find difference between sum of diagonals" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/front-back-transformation1659/1", +"solutionLink": "#", +"problemName": "Front-Back Transformation - copy" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/addition-of-two-square-matrices4916/1", +"solutionLink": "#", +"problemName": "Addition of two square matrices" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/12-hour-clock-subtraction1708/1", +"solutionLink": "#", +"problemName": "12 hour clock subtraction" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-classes-introduction/1", +"solutionLink": "#", +"problemName": "Java Classes Introduction" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/number-of-diagonals1020/1", +"solutionLink": "#", +"problemName": "Number of Diagonals" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/12-hour-clock-addition1206/1", +"solutionLink": "#", +"problemName": "12 hour clock addition" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/checcheck-if-two-given-circles-touch-each-other5038/1", +"solutionLink": "#", +"problemName": "Check if two given circles touch each other" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/combinational-logic1908/1", +"solutionLink": "#", +"problemName": "Combinational Logic" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/java-abstract-keyword/1", +"solutionLink": "#", +"problemName": "Java Abstract keyword" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/compound-interest0235/1", +"solutionLink": "#", +"problemName": "Compound Interest" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/program-to-print-reciprocal-of-letters36233623/1", +"solutionLink": "#", +"problemName": "Program to print reciprocal of letters" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/determine-focal-length-of-a-spherical-mirror5415/1", +"solutionLink": "#", +"problemName": "Determine focal length of a spherical mirror" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/12-hour-clock-multiplication4709/1", +"solutionLink": "#", +"problemName": "12 hour clock Multiplication " +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/number-pattern0517/1", +"solutionLink": "#", +"problemName": "Number Pattern" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/parallel-or-perpendicular4257/1", +"solutionLink": "#", +"problemName": "Parallel or Perpendicular?" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/decimal-to-any-base-conversion2440/1", +"solutionLink": "#", +"problemName": "Decimal to any base conversion" +}, +{ +"difficulty": "School", +"gfgLink": "https://www.geeksforgeeks.org/problems/time-to-words3728/1", +"solutionLink": "#", +"problemName": "Time to Words" +} +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the GeeksforGeeks website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/index.md b/problems/index.md new file mode 100644 index 0000000..a5e21c0 --- /dev/null +++ b/problems/index.md @@ -0,0 +1,50 @@ +--- +title: Data Structures and Algorithms Problems +sidebar_label: DSA Problems +sidebar_position: 1 +--- + +DSA Problems are a collection of problems that are frequently asked in coding interviews. These problems are categorized based on the data structures and algorithms they use. The problems are available in multiple programming languages like C++, Java, Python, and JavaScript. The problems are also available in the form of video tutorials and solutions. + +## What is Data Structures and Algorithms? + +Data Structures and Algorithms are the building blocks of computer science. Data structures are a way of organizing and storing data in a computer so that it can be accessed and modified efficiently. Algorithms are a set of instructions that are used to perform a specific task. Data structures and algorithms are used to solve complex problems in computer science and software development. + +## Why Data Structures and Algorithms are important? + +Data Structures and Algorithms are important because they help in writing efficient code. By using the right data structure and algorithm, you can reduce the time and space complexity of your code. This can help in improving the performance of your code and making it more scalable. Data Structures and Algorithms are also important for coding interviews as they are frequently asked in coding interviews. + +## How to prepare for Data Structures and Algorithms? + +To prepare for Data Structures and Algorithms, you can start by learning the basic data structures like arrays, linked lists, stacks, queues, trees, graphs, etc. You can then move on to learning the basic algorithms like sorting, searching, recursion, dynamic programming, etc. You can practice solving problems on these data structures and algorithms on platforms like LeetCode, HackerRank, Codeforces, etc. You can also refer to books like "Introduction to Algorithms" by Cormen, Leiserson, Rivest, and Stein, "Cracking the Coding Interview" by Gayle Laakmann McDowell, etc. + +## List of Data Structures and Algorithms Problems + +Here is a list of Data Structures and Algorithms Problems that are available on this website: + +- [Array Problems](#) +- [Linked List Problems](#) +- [Stack Problems](#) +- [Queue Problems](#) +- [Tree Problems](#) +- [Graph Problems](#) +- [Sorting Problems](#) +- [Searching Problems](#) +- [Recursion Problems](#) +- [Dynamic Programming Problems](#) +- [Greedy Problems](#) +- [Backtracking Problems](#) +- [Bit Manipulation Problems](#) +- [Math Problems](#) +- [String Problems](#) +- [Matrix Problems](#) +- [Miscellaneous Problems](#) +- [LeetCode Problems](#) +- [HackerRank Problems](#) +- [Codeforces Problems](#) + +You can click on the links above to view the problems in each category. You can also use the search bar at the top of the page to search for specific problems. + +## Conclusion + +Data Structures and Algorithms are an important part of computer science and software development. By learning and practicing data structures and algorithms, you can improve your problem-solving skills and become a better programmer. The problems available on this website are a great resource for practicing data structures and algorithms and preparing for coding interviews. I hope you find these problems helpful in your journey of learning data structures and algorithms. diff --git a/problems/leetcode-problems/0000-0099.md b/problems/leetcode-problems/0000-0099.md new file mode 100644 index 0000000..3f7920e --- /dev/null +++ b/problems/leetcode-problems/0000-0099.md @@ -0,0 +1,615 @@ +--- +id: 0000-0099 +title: LeetCode Problems 0 - 99 +sidebar_label: 0000-0099 +keywords: + - leetcode problems + - leetcode problems 0 - 99 + - leetcode problems problems +--- + +export const problems = [ +{ +"problemName": "1. Two Sum", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/two-sum/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/two-sum" +}, +{ +"problemName": "2. Add Two Numbers", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/add-two-numbers/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/add-two-numbers" +}, +{ +"problemName": "3. Longest Substring Without Repeating Characters", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/longest-substring-without-repeating-characters/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/longest-substrings-without-repeating-characters" +}, +{ +"problemName": "4. Median of Two Sorted Arrays", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/median-of-two-sorted-arrays/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/median-of-two-sorted-arrays" +}, +{ +"problemName": "5. Longest Palindromic Substring", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/longest-palindromic-substring/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/Longest Palindromic Substring" +}, +{ +"problemName": "6. ZigZag Conversion", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/zigzag-conversion/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/Zigzag Conversion" +}, +{ +"problemName": "7. Reverse Integer", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/reverse-integer/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/Reverse Integer" +}, +{ +"problemName": "8. String to Integer (atoi)", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/string-to-integer-atoi/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/String to Integer" +}, +{ +"problemName": "9. Palindrome Number", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/palindrome-number/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/Palindrome Number" +}, +{ +"problemName": "10. Regular Expression Matching", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/regular-expression-matching/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/Regular Expression Matching" +}, +{ +"problemName": "11. Container With Most Water", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/container-with-most-water/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/Container With Most Water" +}, +{ +"problemName": "12. Integer to Roman", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/integer-to-roman/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/Integer to Roman" +}, +{ +"problemName": "13. Roman to Integer", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/roman-to-integer/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/Roman to Integer" +}, +{ +"problemName": "14. Longest Common Prefix", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/longest-common-prefix/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/Longest Comman Prefix" +}, +{ +"problemName": "15. 3Sum", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/3sum/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/3Sum" +}, +{ +"problemName": "16. 3Sum Closest", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/3sum-closest/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/3Sum Closest" +}, +{ +"problemName": "17. Letter Combinations of a Phone Number", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/letter-combinations-of-a-phone-number/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/letter-combination" +}, +{ +"problemName": "18. 4Sum", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/4sum/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/four-sum" +}, +{ +"problemName": "19. Remove Nth Node From End of List", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/remove-nth-node-from-end-of-list/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/remove-nth-node-from-end-of-list" +}, +{ +"problemName": "20. Valid Parentheses", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/valid-parentheses/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/valid-parentheses" +}, +{ +"problemName": "21. Merge Two Sorted Lists", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/merge-two-sorted-lists/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/merge-two-sorted-lists" +}, +{ +"problemName": "22. Generate Parentheses", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/generate-parentheses/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/generate-parentheses" +}, +{ +"problemName": "23. Merge k Sorted Lists", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/merge-k-sorted-lists/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/merge-k-sorted-list" +}, +{ +"problemName": "24. Swap Nodes in Pairs", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/swap-nodes-in-pairs/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/swap-nodes-in-pairs" +}, +{ +"problemName": "25. Reverse Nodes in k-Group", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/reverse-nodes-in-k-group/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/remove-duplicates-from-sorted-list-2" +}, +{ +"problemName": "26. Remove Duplicates from Sorted Array", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/remove-duplicates-from-sorted-array/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/remove-duplicates-from-sorted-array" +}, +{ +"problemName": "27. Remove Element", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/remove-element/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/remove-element" +}, +{ +"problemName": "28. Implement strStr()", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/implement-strstr/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/find-first-occurrence-in-string" +}, +{ +"problemName": "29. Divide Two Integers", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/divide-two-integers/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/divide-two-integers" +}, +{ +"problemName": "30. Substring with Concatenation of All Words", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/substring-with-concatenation-of-all-words/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/substring-with-concatenation-of-all-words" +}, +{ +"problemName": "31. Next Permutation", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/next-permutation/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/next-permutation" +}, +{ +"problemName": "32. Longest Valid Parentheses", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/longest-valid-parentheses/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/longest-valid-parentheses" +}, +{ +"problemName": "33. Search in Rotated Sorted Array", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/search-in-rotated-sorted-array/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/search-in-rotated-sorted-array" +}, +{ +"problemName": "34. Find First and Last Position of Element in Sorted Array", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/find-first-and-last-position-of-element-in-sorted-array" +}, +{ +"problemName": "35. Search Insert Position", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/search-insert-position/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/search-insert-position" +}, +{ +"problemName": "36. Valid Sudoku", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/valid-sudoku/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/valid-sudoku" +}, +{ +"problemName": "37. Sudoku Solver", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/sudoku-solver/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/sudoku-solver" +}, +{ +"problemName": "38. Count and Say", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/count-and-say/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/count-and-say" +}, +{ +"problemName": "39. Combination Sum", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/combination-sum/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/combination-sum" +}, +{ +"problemName": "40. Combination Sum II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/combination-sum-ii/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/combination-sum-II" +}, +{ +"problemName": "41. First Missing Positive", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/first-missing-positive/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/41FirstMissingPositive" +}, +{ +"problemName": "42. Trapping Rain Water", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/trapping-rain-water/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/trapping-rain-water" +}, +{ +"problemName": "43. Multiply Strings", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/multiply-strings/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/Multiple-Strings" +}, +{ +"problemName": "44. Wildcard Matching", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/wildcard-matching/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/Wildcard-Matching" +}, +{ +"problemName": "45. Jump Game II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/jump-game-ii/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/jump-game-II" +}, +{ +"problemName": "46. Permutations", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/permutations/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/permutations" +}, +{ +"problemName": "47. Permutations II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/permutations-ii/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/permutations-ll" +}, +{ +"problemName": "48. Rotate Image", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/rotate-image/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/rotate-image" +}, +{ +"problemName": "49. Group Anagrams", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/group-anagrams/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/group-anagrams" +}, +{ +"problemName": "50. Pow(x, n)", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/powx-n/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/powx-n" +}, +{ +"problemName": "51. N-Queens", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/n-queens/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/N-Queens-Puzzle" +}, +{ +"problemName": "52. N-Queens II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/n-queens-ii/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/n-queens-ll" +}, +{ +"problemName": "53. Maximum Subarray", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/maximum-subarray/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/maximum-subarray" +}, +{ +"problemName": "54. Spiral Matrix", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/spiral-matrix/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/spiral-matrix" +}, +{ +"problemName": "55. Jump Game", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/jump-game/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/jump-game" +}, +{ +"problemName": "56. Merge Intervals", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/merge-intervals/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/merge-intervals" +}, +{ +"problemName": "57. Insert Interval", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/insert-interval/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/insert-interval" +}, +{ +"problemName": "58. Length of Last Word", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/length-of-last-word/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/length-of-last-word" +}, +{ +"problemName": "59. Spiral Matrix II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/spiral-matrix-ii/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/spiral-matrix-II" +}, +{ +"problemName": "60. Permutation Sequence", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/permutation-sequence/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/permutation-sequence" +}, +{ +"problemName": "61. Rotate List", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/rotate-list/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/rotate-list" +}, +{ +"problemName": "62. Unique Paths", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/unique-paths/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/unique-paths/" +}, +{ +"problemName": "63. Unique Paths II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/unique-paths-ii/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/unique-paths-II" +}, +{ +"problemName": "64. Minimum Path Sum", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-path-sum/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/minimum-path-sum" +}, +{ +"problemName": "65. Valid Number", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/valid-number/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/valid-number" +}, +{ +"problemName": "66. Plus One", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/plus-one/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/plus-one" +}, +{ +"problemName": "67. Add Binary", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/add-binary/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/add-binary" +}, +{ +"problemName": "68. Text Justification", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/text-justification/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/text-justification" +}, +{ +"problemName": "69. Sqrt(x)", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/sqrtx/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/sqrt-x" +}, +{ +"problemName": "70. Climbing Stairs", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/climbing-stairs/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/climbing-stairs" +}, +{ +"problemName": "71. Simplify Path", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/simplify-path/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/simplify-path" +}, +{ +"problemName": "72. Edit Distance", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/edit-distance/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/edit-distance" +}, +{ +"problemName": "73. Set Matrix Zeroes", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/set-matrix-zeroes/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/set-matrix-zeros" +}, +{ +"problemName": "74. Search a 2D Matrix", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/search-a-2d-matrix/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/search-a-2D-matrix" +}, +{ +"problemName": "75. Sort Colors", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/sort-colors/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/sort-colors" +}, +{ +"problemName": "76. Minimum Window Substring", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/minimum-window-substring/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/minimum-window-substring" +}, +{ +"problemName": "77. Combinations", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/combinations/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/combinations" +}, +{ +"problemName": "78. Subsets", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/subsets/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/subsets" +}, +{ +"problemName": "79. Word Search", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/word-search/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/word-search" +}, +{ +"problemName": "80. Remove Duplicates from Sorted Array II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/remove-duplicates-from-sorted-array-II" +}, +{ +"problemName": "81. Search in Rotated Sorted Array II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/search-in-rotated-sorted-array-ii/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/search-in-rotated-sorted-array-II" +}, +{ +"problemName": "82. Remove Duplicates from Sorted List II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/82-remove-duplicates-from-sorted-list-2" +}, +{ +"problemName": "83. Remove Duplicates from Sorted List", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/remove-duplicates-from-sorted-list/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/remove-duplicates-from-sorted-list" +}, +{ +"problemName": "84. Largest Rectangle in Histogram", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/largest-rectangle-in-histogram/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/largest-rectangle-in-histogram" +}, +{ +"problemName": "85. Maximal Rectangle", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/maximal-rectangle/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/Maximal-Rectangle" +}, +{ +"problemName": "86. Partition List", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/partition-list/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/partition-list" +}, +{ +"problemName": "87. Scramble String", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/scramble-string/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/scramble-string" +}, +{ +"problemName": "88. Merge Sorted Array", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/merge-sorted-array/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/merge-sorted-array" +}, +{ +"problemName": "89. Gray Code", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/gray-code/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/gray-code" +}, +{ +"problemName": "90. Subsets II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/subsets-ii/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/subsets-ii" +}, +{ +"problemName": "91. Decode Ways", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/decode-ways/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/decode-ways" +}, +{ +"problemName": "92. Reverse Linked List II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/reverse-linked-list-ii/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/reverse-linked-list-II" +}, +{ +"problemName": "93. Restore IP Addresses", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/restore-ip-addresses/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/restore-ip-addresses" +}, +{ +"problemName": "94. Binary Tree Inorder Traversal", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/binary-tree-inorder-traversal/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/binary-tree-inorder-traversal" +}, +{ +"problemName": "95. Unique Binary Search Trees II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/unique-binary-search-trees-ii/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/unique-binary-search-tree-II" +}, +{ +"problemName": "96. Unique Binary Search Trees", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/unique-binary-search-trees/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/unique-binary-search-tree" +}, +{ +"problemName": "97. Interleaving String", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/interleaving-string/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/Interleaving-Strings" +}, +{ +"problemName": "98. Validate Binary Search Tree", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/validate-binary-search-tree/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/validate-binary-search-tree" +}, +{ +"problemName": "99. Recover Binary Search Tree", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/recover-binary-search-tree/", +"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/recover-binary-search-tree" +} +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/0100-0199.md b/problems/leetcode-problems/0100-0199.md new file mode 100644 index 0000000..1e98510 --- /dev/null +++ b/problems/leetcode-problems/0100-0199.md @@ -0,0 +1,623 @@ +--- +id: 0100-0199 +title: LeetCode Problems 100 - 199 +sidebar_label: 0100 - 0199 +keywords: + - LeetCode + - LeeCode Problems + - LeeCode Problems 100 - 199 + - dsa problems +--- + +export const problems = [ +{ + "problemName": "100. Same Tree", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/same-tree/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/same-tree" + }, + { + "problemName": "101. Symmetric Tree", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/symmetric-tree/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/symmetric-tree" + }, + { + "problemName": "102. Binary Tree Level Order Traversal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/binary-tree-level-order-traversal/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/binary-tree-level-order-traversal" + }, + { + "problemName": "103.. Binary Tree Zigzag Level Order Traversal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/binary-tree-zigzag-level-order-traversal" + }, + { + "problemName": "104. Maximum Depth of Binary Tree", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-depth-of-binary-tree/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/max-depth-binary-tree" + }, + { + "problemName": "105. Construct Binary Tree from Preorde...", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal" + }, + { + "problemName": "106. Construct Binary Tree from Inorder", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/Construct-Binary-Tree-from-Inorder-and-postorder-Traversal" + }, + { + "problemName": "107. Binary Tree Level Order Traversal II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/binary-tree-level-order-traversal-ii/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/0107-Binary-Tree-Level-Order-Traversal-II" + }, + { + "problemName": "108. Convert Sorted Array to Binary Sear...", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/convert-sorted-array-to-binary-search-tree" + }, + { + "problemName": "109. Convert Sorted List to Binary Searc...", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/convert-sorted-list-to-binary-search-tree" + }, + { + "problemName": "110. Balanced Binary Tree", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/balanced-binary-tree", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/balanced-binary-tree" + }, + { + "problemName": "111. Minimum Depth of Binary Tree", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-depth-of-binary-tree", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/minimum-depth-of-binary-tree" + }, + { + "problemName": "112. Path Sum", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/path-sum/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/path-sum" + }, + { + "problemName": "113. Path Sum II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/path-sum-ii/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/path-sum-II" + }, + { + "problemName": "114. Flatten Binary Tree to Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/flatten-binary-tree-to-linked-list/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/flatten-binary-tree-to-linked-list" + }, + { + "problemName": "115. Distinct Subsequences", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/distinct-subsequences/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/distinct-subsequence" + }, + { + "problemName": "116. Populating Next Right Pointers in Each Node", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/populating-next-right-pointers-in-each-node/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/116-populating-next-right-pointers-in-each-node" + }, + { + "problemName": "117. Populating Next Right Pointers in E...", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/117-populating-next-right-pointer-2" + }, + { + "problemName": "118. Pascal's Triangle", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/pascals-triangle", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/118-pascals-triangle" + }, + { + "problemName": "119. Pascal's Triangle II", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/pascals-triangle-ii/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/119-pascals-triangle-ii" + }, + { + "problemName":"120. Triangle", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/triangle/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/triangle" + }, + { + "problemName": "121. Best Time to Buy and Sell Stock", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/best-time-to-buy-sell-stock" + }, + { + "problemName": "122. Best Time to Buy and Sell Stock II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/best-time-to-buy-sell-stock-II" + }, + { + "problemName": "123. Best Time to Buy and Sell Stock III", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/best-time-to-buy-sell-stock-III" + }, + { + "problemName": "124. Binary Tree Maximum Path Sum", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/binary-tree-maximum-path-sum/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/binary-tree-path-sum" + }, + { + "problemName": "125. Valid Palindrome", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/valid-palindrome/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/valid-palindrome" + }, + { + "problemName": "126. Word Ladder II" , + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/word-ladder-ii/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/word-ladder-II" + }, + { + "problemName": "127. Word Ladder", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/word-ladder/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/word-ladder" + }, + { + "problemName": "128. Longest Consecutive Sequence", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-consecutive-sequence/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/longest-consecutive-sequence" + }, + { + "problemName": "129. Sum Root to Leaf Numbers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-root-to-leaf-numbers/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/sum-root-to-leaf-numbers" + }, + { + "problemName": "130. Surrounded Regions", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/surrounded-regions/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/surrounded-regions" + }, + { + "problemName": "131. Palindrome Partitioning", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/palindrome-partitioning/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/palindrom-partitioning" + }, + { + "problemName": "132. Palindrome Partitioning II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/palindrome-partitioning-ii/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/palindrom-partitioning-II" + }, + { + "problemName": "133. Clone Graph" , + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/clone-graph/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/clone-graph" + }, + { + "problemName": "134. Gas Station", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/gas-station/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/gas-station" + }, + { + "problemName": "135. Candy", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/candy/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/Candy" + }, + { + "problemName": "136. Single Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/single-number/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/single-number" + }, + { + "problemName": "137. Single Number II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/single-number-ii/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/single-number-II" + }, + { + "problemName": "138. Copy List with Random Pointer", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/copy-list-with-random-pointer/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/copy-list-with-random-pointer" + }, + { + "problemName": "139. Word Break", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/word-break/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/word-break" + }, + { + "problemName": "140. Word Break II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/word-break-ii/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/0140-word-break-ii" + }, + { + "problemName": "141. Linked List Cycle", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/linked-list-cycle/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/linked-list-cycle" + }, + { + "problemName": "142. Linked List Cycle II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/linked-list-cycle-ii/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/linked-list-cycle--II" + }, + { + "problemName": "143. Reorder List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reorder-list/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/reorder-list" + }, + { + "problemName": "144. Binary Tree Preorder Traversal", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/binary-tree-preorder-traversal/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/binary tree preorder traversal" + }, + { + "problemName": "145.Binary Tree Postorder Traversal", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/binary-tree-postorder-traversal/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/binary-tree-postorder-traversal" + }, + { + "problemName": "146. LRU Cache", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/lru-cache/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/lru-cache" + }, + { + "problemName": "147. Insertion Sort List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/insertion-sort-list/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/insertion-sort-list" + }, + { + "problemName": "148. Sort List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sort-list/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/sort-list" + }, + { + "problemName": "149. Max Points on a Line", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/max-points-on-a-line/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/max-points-on-a-line.md" + }, + { + "problemName": "150. Evaluate Reverse Polish Notation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/evaluate-reverse-polish-notation/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/evaluate-reverse-polish-notation" + }, + { + "problemName": "151. Reverse Words in a String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reverse-words-in-a-string/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/reverse-words-in-a-string" + }, + { + "problemName": "152. Maximum Product Subarray", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-product-subarray/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/maximum-product-subarray" + }, + { + "problemName": "153. Find Minimum in Rotated Sorted Ar...", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/find-minimum-in-rotated-sorted-array" + }, + { + "problemName": "154. Find Minimum in Rotated Sorted Ar...", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/find-minimum-in-rotated-sorted-array-II" + }, + { + "problemName": "155. Min Stack", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/min-stack/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/min-stack" + }, + { + "problemName": "156. Binary Tree Upside Down", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/binary-tree-upside-down/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/binary-tree-upside-down" + }, + { + "problemName": "157. Read N Charcters Given", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/read-n-characters-given-read4/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/read-n-characters-given" + }, + { + "problemName": "158. Read N Charcters Given", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/read-n-characters-given-read4-II" + }, + { + "problemName": "159. Longest Substring with At", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/longest-substring-with-at" + }, + { + "problemName": "160. Intersection of Two Linked Lists", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/intersection-of-two-linked-lists", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/intersection-of-two-linked-list." + }, + { + "problemName": "161. One Edit Distance", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/one-edit-distance", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/one-edit-distance" + }, + { + "problemName": "162. Find Peak Element", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-peak-element/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/Find-Peak-Element" + }, + { + "problemName": "163. Missing Ranges Premium", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/missing-ranges", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/missing-range" + }, + { + "problemName": "164. Maximum Gap", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-gap", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/maximum-gap" + }, + { + "problemName": "165. Compare Version Numbers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/compare-version-numbers", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/compare-version-numbers" + }, + { + "problemName": "166. Fraction to Recurring Decimal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/fraction-to-recurring-decimal", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/fraction-to-recurring-decimal" + }, + { + "problemName": "167. Two Sum II - Input Array Is Sorted", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/two-sum-ii-input-array-is-sorted", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/two-sum-II" + }, + { + "problemName": "168. Excel Sheet Column Title", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/excel-sheet-column-title", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/Excel-sheet-column-title" + }, + { + "problemName": "169. Majority Element", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/majority-element/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/Majority-ELement" + }, + { + "problemName": "170. Two Sum III - Data structu... ", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/two-sum-iii-data-structure-design", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/two-sum-III-data-structure-design" + }, + { + "problemName": "171. Excel Sheet Column Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/excel-sheet-column-number", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/Excel-sheet-column-number" + }, + { + "problemName": "172. Factorial Trailing Zeroes", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/factorial-trailing-zeroes", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/factorial-trailing-zeroes" + }, + { + "problemName": "173. Binary Search Tree Iterator", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/binary-search-tree-iterator/", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/binary-search-tree-iterator" + }, + { + "problemName": "174. Dungeon Game", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/dungeon-game", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/dungeon-game" + }, + { + "problemName": "175. Combine Two Tables", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/combine-two-tables", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/combine-two-tables" + }, + { + "problemName": "176. Second Highest Salary", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/second-highest-salary", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/second-highest-salary" + }, + { + "problemName": "177. Nth Highest Salary", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/nth-highest-salary", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/nth-highest-salary" + }, + { + "problemName": "178. Rank Scores", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/rank-scores", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/rank-scores" + }, + { + "problemName": "179. Largest Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/largest-number", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/largest-number" + }, + { + "problemName": "180. Consecutive Numbbers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/consecutive-numbers", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/consecutive-numbers" + }, + { + "problemName": "181. Employees Earning More Than Their Managers", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/employees-earning-more-than-their-managers", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/employee-earning" + }, + { + "problemName": "182. Duplicate Emails", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/duplicate-emails", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/Duplicate-Emails" + }, + { + "problemName": "183. Customers Who Never Order", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/customers-who-never-order", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/Customers-Who-Never-Order" + }, + { + "problemName": "184. Department Highest Salary", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/department-highest-salary", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/department-highest-salary" + }, + { + "problemName": "185. Department Top Three Salaries", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/department-top-three-salaries", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/department-top-three-salaries" + }, + { + "problemName": "186. Reverse Words in a String II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reverse-words-in-a-string-ii", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/reverse-words-in-string-II" + }, + { + "problemName": "187. Repeated DNA Sequences", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/repeated-dna-sequences", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/repeated-dna-sequence" + + }, + { + "problemName": "188. Best Time to Buy and Sell Stock IV", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/best-time-to-buy-sell-stock-IV" + }, + { + "problemName": "189. Rotate Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/rotate-array", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/189-rotate-array" + }, + { + "problemName": "190. Reverse Bits", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/reverse-bits", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/Reverse-Bits" + }, + { + "problemName": "191. Number of 1 Bits", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-1-bits", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/number-of-1-bits" + }, + { + "problemName": "192. Word Frequency", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/word-frequency", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/word-frequency" + }, + { + "problemName": "193. Valid Phone Numbers", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/valid-phone-numbers", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/valid-phone-numbers" + }, + { + "problemName": "194. Transpose File", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/transpose-file", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/transpose-file" + }, + { + "problemName": "195. Tenth Line", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/tenth-line", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/tenth-line" + }, + { + "problemName": "196. Delete Duplicate Emails", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/delete-duplicate-emails", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/delete-duplicate-emails" + }, + { + "problemName": "197. Rising Temperature", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/rising-temperature", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/rising-temperature" + }, + { + "problemName": "198. House Robber", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/house-robber", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/house-robber" + }, + { + "problemName": "199. Binary Tree Right Side View", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/binary-tree-right-side-view", + "solutionLink": "/dsa-solutions/lc-solutions/0100-0199/binary-tree-right-side-view" + }, +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/leetcode-problems/0200-0299.md b/problems/leetcode-problems/0200-0299.md new file mode 100644 index 0000000..d95fc8a --- /dev/null +++ b/problems/leetcode-problems/0200-0299.md @@ -0,0 +1,624 @@ +--- +id: 0200-0299 +title: LeetCode Problems 200 - 299 +sidebar_label: 0200 - 0299 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 200 - 299 + - DSA problems +--- + +export const problems = [ + +{ +"problemName": "200. Number of Islands", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/number-of-islands", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/number-of-islands" +}, +{ +"problemName": "201. Bitwise AND of Numbers Range", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/bitwise-and-of-numbers-range", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/bitwise-and-of-numbers-range" +}, +{ +"problemName": "202. Happy Number", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/happy-number", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/happy-number" +}, +{ +"problemName": "203. Remove Linked List Elements", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/remove-linked-list-elements", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299//dsa-solutions/lc-solutions/0200-0299/Remove-Linked-List-Elements" +}, +{ +"problemName": "204. Count Primes", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/count-primes", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/count-primes" +}, +{ +"problemName": "205. Isomorphic Strings", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/isomorphic-strings", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/isomorphic-strings" +}, +{ +"problemName": "206. Reverse Linked List", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/reverse-linked-list", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/Reverse-Linkedlist" +}, +{ +"problemName": "207. Course Schedule", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/course-schedule", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/course-schedule" +}, +{ +"problemName": "208. Implement Trie (Prefix Tree)", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/implement-trie-prefix-tree", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/Implement-Trie" +}, +{ +"problemName": "209. Minimum Size Subarray Sum", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-size-subarray-sum", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/minimum-size-subarray-sum" +}, +{ +"problemName": "210. Course Schedule II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/course-schedule-ii", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/course-schedule-II" +}, +{ +"problemName": "211. Design Add and Search Words Data Structure", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/design-add-and-search-words-data-structure", +"solutionLink": "dsa-solutions/lc-solutions/0200-0299/design-add-and-search-words-data-structure" +}, +{ +"problemName": "212. Word Search II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/word-search-ii", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/word-search-ii" +}, +{ +"problemName": "213. House Robber II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/house-robber-ii", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/house-robber-II" +}, +{ +"problemName": "214. Shortest Palindrome", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/shortest-palindrome", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/shortest-palindrome" +}, +{ +"problemName": "215. Kth Largest Element in an Array", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/kth-largest-element-in-an-array", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/kth-largest-element-in-an-array" +}, +{ +"problemName": "216. Combination Sum III", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/combination-sum-iii", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/combination-sum-III" +}, +{ +"problemName": "217. Contains Duplicate", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/contains-duplicate", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/contains-duplicate" +}, +{ +"problemName": "218. The Skyline Problem", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/the-skyline-problem", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/the-skyline-problem" +}, +{ +"problemName": "219. Contains Duplicate II", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/contains-duplicate-ii", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/contains-duplicate-II" +}, +{ +"problemName": "220. Contains Duplicate III", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/contains-duplicate-iii", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/contains-duplicate-III" +}, +{ +"problemName": "221. Maximal Square", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximal-square", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/Maximal Square" +}, +{ +"problemName": "222. Count Complete Tree Nodes", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/count-complete-tree-nodes", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/count-complete-tree-nodes" +}, +{ +"problemName": "223. Rectangle Area", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/rectangle-area", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/rectangle-area" +}, +{ +"problemName": "224. Basic Calculator", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/basic-calculator", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/0224-Basic-Calculator.md" +}, +{ +"problemName": "225. Implement Stack using Queues", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/implement-stack-using-queues", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/0225-Implement-Stack-using-Queues.md" +}, +{ +"problemName": "226. Invert Binary Tree", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/invert-binary-tree", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/invert-binary-search-tree" +}, +{ +"problemName": "227. Basic Calculator II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/basic-calculator-ii", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/0227-Basic-Calculator-II.md" +}, +{ +"problemName": "228. Summary Ranges", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/summary-ranges", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/summary-ranges" +}, +{ +"problemName": "229. Majority Element II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/majority-element-ii", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/majority-element-II" +}, +{ +"problemName": "230. Kth Smallest Element in a BST", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/kth-smallest-element-in-a-bst", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/Kth-smallest-element-in-BST" +}, +{ +"problemName": "231. Power of Two", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/power-of-two", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/power-of-two" +}, +{ +"problemName": "232. Implement Queue using Stacks", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/implement-queue-using-stacks", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/queue-using-stacks" +}, +{ +"problemName": "233. Number of Digit One", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/number-of-digit-one", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/Number of Digit One" +}, +{ +"problemName": "234. Palindrome Linked List", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/palindrome-linked-list", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/palindrome-linked-list" +}, +{ +"problemName": "235. Lowest Common Ancestor of a Binary Search Tree", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/lowest-common-Ancestor-of-binary-search-tree" +}, +{ +"problemName": "236. Lowest Common Ancestor of a Binary Tree", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/Lowest-Common-Ancestor-of-a-Binary-Tree" +}, +{ +"problemName": "237. Delete Node in a Linked List", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/delete-node-in-a-linked-list", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/delete-node-in-a-linked-list" +}, +{ +"problemName": "238. Product of Array Except Self", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/product-of-array-except-self", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/product-of-array-except-self" +}, +{ +"problemName": "239. Sliding Window Maximum", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/sliding-window-maximum", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/sliding-window-maximum" +}, +{ +"problemName": "240. Search a 2D Matrix II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/search-a-2d-matrix-ii", +"solutionLink": "#" +}, +{ +"problemName": "241. Different Ways to Add Parentheses", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/different-ways-to-add-parentheses", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/different-ways-to-add-parentheses" +}, +{ +"problemName": "242. Valid Anagram", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/valid-anagram", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/valid-anagram" +}, +{ +"problemName": "243. Shortest Word Distance", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/shortest-word-distance", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/shortest-word-distance" +}, +{ +"problemName": "244. Shortest Word Distance II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/shortest-word-distance-ii", +"solutionLink": "#" +}, +{ +"problemName": "245. Shortest Word Distance III", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/shortest-word-distance-iii", +"solutionLink": "#" +}, +{ +"problemName": "246. Strobogrammatic Number", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/strobogrammatic-number", +"solutionLink": "#" +}, +{ +"problemName": "247. Strobogrammatic Number II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/strobogrammatic-number-ii", +"solutionLink": "#" +}, +{ +"problemName": "248. Strobogrammatic Number III", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/strobogrammatic-number-iii", +"solutionLink": "#" +}, +{ +"problemName": "249. Group Shifted Strings", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/group-shifted-strings", +"solutionLink": "#" +}, +{ +"problemName": "250. Count Univalue Subtrees", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/count-univalue-subtrees", +"solutionLink": "#" +}, +{ +"problemName": "251. Flatten 2D Vector", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/flatten-2d-vector", +"solutionLink": "#" +}, +{ +"problemName": "252. Meeting Rooms", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/meeting-rooms", +"solutionLink": "#" +}, +{ +"problemName": "253. Meeting Rooms II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/meeting-rooms-ii", +"solutionLink": "#" +}, +{ +"problemName": "254. Factor Combinations", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/factor-combinations", +"solutionLink": "#" +}, +{ +"problemName": "255. Verify Preorder Sequence in Binary Search Tree", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree", +"solutionLink": "#" +}, +{ +"problemName": "256. Paint House", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/paint-house", +"solutionLink": "#" +}, +{ +"problemName": "257. Binary Tree Paths", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/binary-tree-paths", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/Binary-Tree-Paths" +}, +{ +"problemName": "258. Add Digits", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/add-digits", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/add-digits" +}, +{ +"problemName": "259. 3Sum Smaller", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/3sum-smaller", +"solutionLink": "#" +}, +{ +"problemName": "260. Single Number III", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/single-number-iii", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/single-number-III" +}, +{ +"problemName": "261. Graph Valid Tree", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/graph-valid-tree", +"solutionLink": "#" +}, +{ +"problemName": "262. Trips and Users", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/trips-and-users", +"solutionLink": "#" +}, +{ +"problemName": "263. Ugly Number", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/ugly-number", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/ugly-number" +}, +{ +"problemName": "264. Ugly Number II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/ugly-number-ii", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/ugly-number-II" +}, +{ +"problemName": "265. Paint House II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/paint-house-ii", +"solutionLink": "#" +}, +{ +"problemName": "266. Palindrome Permutation", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/palindrome-permutation", +"solutionLink": "#" +}, +{ +"problemName": "267. Palindrome Permutation II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/palindrome-permutation-ii", +"solutionLink": "#" +}, +{ +"problemName": "268. Missing Number", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/missing-number", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/Missing-Number" +}, +{ +"problemName": "269. Alien Dictionary", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/alien-dictionary", +"solutionLink": "#" +}, +{ +"problemName": "270. Closest Binary Search Tree Value", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/closest-binary-search-tree-value", +"solutionLink": "#" +}, +{ +"problemName": "271. Encode and Decode Strings", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/encode-and-decode-strings", +"solutionLink": "#" +}, +{ +"problemName": "272. Closest Binary Search Tree Value II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/closest-binary-search-tree-value-ii", +"solutionLink": "#" +}, +{ +"problemName": "273. Integer to English Words", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/integer-to-english-words", +"solutionLink": "#" +}, +{ +"problemName": "274. H-Index", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/h-index", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/H-index" +}, +{ +"problemName": "275. H-Index II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/h-index-ii", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/H-Index-II" +}, +{ +"problemName": "276. Paint Fence", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/paint-fence", +"solutionLink": "#" +}, +{ +"problemName": "277. Find the Celebrity", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-the-celebrity", +"solutionLink": "#" +}, +{ +"problemName": "278. First Bad Version", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/first-bad-version", +"solutionLink": "#" +}, +{ +"problemName": "279. Perfect Squares", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/perfect-squares", +"solutionLink": "#" +}, +{ +"problemName": "280. Wiggle Sort", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/wiggle-sort", +"solutionLink": "#" +}, +{ +"problemName": "281. Zigzag Iterator", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/zigzag-iterator", +"solutionLink": "#" +}, +{ +"problemName": "282. Expression Add Operators", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/expression-add-operators", +"solutionLink": "#" +}, +{ +"problemName": "283. Move Zeroes", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/move-zeroes", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/move-zeroes" +}, +{ +"problemName": "284. Peeking Iterator", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/peeking-iterator", +"solutionLink": "#" +}, +{ +"problemName": "285. Inorder Successor in BST", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/inorder-successor-in-bst", +"solutionLink": "#" +}, +{ +"problemName": "286. Walls and Gates", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/walls-and-gates", +"solutionLink": "#" +}, +{ +"problemName": "287. Find the Duplicate Number", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-the-duplicate-number", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/find-the-duplicate-number" +}, +{ +"problemName": "288. Unique Word Abbreviation", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/unique-word-abbreviation", +"solutionLink": "#" +}, +{ +"problemName": "289. Game of Life", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/game-of-life", +"solutionLink": "#" +}, +{ +"problemName": "290. Word Pattern", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/word-pattern", +"solutionLink": "#" +}, +{ +"problemName": "291. Word Pattern II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/word-pattern-ii", +"solutionLink": "#" +}, +{ +"problemName": "292. Nim Game", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/nim-game", +"solutionLink": "#" +}, +{ +"problemName": "293. Flip Game", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/flip-game", +"solutionLink": "#" +}, +{ +"problemName": "294. Flip Game II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/flip-game-ii", +"solutionLink": "#" +}, +{ +"problemName": "295. Find Median from Data Stream", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-median-from-data-stream", +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/median-finder" +}, +{ +"problemName": "296. Best Meeting Point", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/best-meeting-point", +"solutionLink": "#" +}, +{ +"problemName": "297. Serialize and Deserialize Binary Tree", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/serialize-and-deserialize-binary-tree", +"solutionLink": "#" +}, +{ +"problemName": "298. Binary Tree Longest Consecutive Sequence", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/binary-tree-longest-consecutive-sequence", +"solutionLink": "#" +}, +{ +"problemName": "299. Bulls and Cows", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/bulls-and-cows", +"solutionLink": "#" +} + +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/leetcode-problems/0300-0399.md b/problems/leetcode-problems/0300-0399.md new file mode 100644 index 0000000..299a24d --- /dev/null +++ b/problems/leetcode-problems/0300-0399.md @@ -0,0 +1,617 @@ +--- +id: 0300-0399 +title: LeetCode Problems 300 - 399 +sidebar_label: 0300 - 0399 +keywords: + - LeetCode + - LeeCode Problems + - LeeCode Problems 300 - 399 + - dsa problems +--- + + +export const problems = [ + { + "problemName": "300. Longest Increasing Subsequence", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-increasing-subsequence/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/longest-increasing-subsequence" + }, + { + "problemName": "301. Remove Invalid Parentheses", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/remove-invalid-parentheses/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/0301-Remove-Invalid-Parentheses" + }, + { + "problemName": "302. Smallest Rectangle Enclosing Black Pixels", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/", + "solutionLink": "#" + }, + { + "problemName": "303. Range Sum Query - Immutable", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/range-sum-query-immutable/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/range-sum-query-immutable" + }, + { + "problemName": "304. Range Sum Query 2D - Immutable", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/range-sum-query-2d-immutable/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/range-sum-query-2d-immutable" + }, + { + "problemName": "305. number-of-islands-ii", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-islands-ii/", + "solutionLink": "#" + }, + { + "problemName": "306. Additive Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/additive-number/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/additive-number" + }, + { + "problemName": "307. Range Sum Query - Mutable", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/range-sum-query-mutable/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/0307-Range-Sum-Query-Mutable" + }, + { + "problemName": "308. range-sum-query-2d-mutable", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/range-sum-query-2d-mutable/", + "solutionLink": "#" + }, + { + "problemName": "309. Best Time to Buy and Sell Stock with Cooldown", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/best-time-to-buy-and-sell-stock" + }, + { + "problemName": "310. Minimum Height Trees", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-height-trees/", + "solutionLink": "#" + }, + { + "problemName": "311. sparse-matrix-multiplication", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sparse-matrix-multiplication/", + "solutionLink": "#" + }, + { + "problemName": "312. Burst Balloons", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/burst-balloons/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/burst-ballons" + }, + { + "problemName": "313. Super Ugly Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/super-ugly-number/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/0313-Super-Ugly-Number" + }, + { + "problemName": "314. binary-tree-vertical-order-traversal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/binary-tree-vertical-order-traversal/", + "solutionLink": "#" + }, + { + "problemName": "315. Count of Smaller Numbers After Self", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-of-smaller-numbers-after-self/", + "solutionLink": "#" + }, + { + "problemName": "316. Remove Duplicate Letters", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-duplicate-letters/", + "solutionLink": "#" + }, + { + "problemName": "317. shortest-distance-from-all-buildings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shortest-distance-from-all-buildings/", + "solutionLink": "#" + }, + { + "problemName": "318. Maximum Product of Word Lengths", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-product-of-word-lengths/", + "solutionLink": "#" + }, + { + "problemName": "319. Bulb Switcher", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/bulb-switcher/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/bulb-switcher" + }, + { + "problemName": "320. generalized-abbreviation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/generalized-abbreviation/", + "solutionLink": "#" + }, + { + "problemName": "321. Create Maximum Number", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/create-maximum-number/", + "solutionLink": "#" + }, + { + "problemName": "322. Coin Change", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/coin-change/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/coin-change" + }, + { + "problemName": "323. number-of-connected-components-in-an-undirected-graph", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/", + "solutionLink": "#" + }, + { + "problemName": "324. Wiggle Sort II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/wiggle-sort-ii/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/wiggle-sort-ii" + }, + { + "problemName": "325. maximum-size-subarray-sum-equals-k", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/", + "solutionLink": "#" + }, + { + "problemName": "326. Power of Three", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/power-of-three/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/0326-power-of-three" + }, + { + "problemName": "327. Count of Range Sum", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-of-range-sum/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/0327-Count-of-Range-Sum" + }, + { + "problemName": "328. Odd Even Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/odd-even-linked-list/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/odd-even-linked-list" + }, + { + "problemName": "329. Longest Increasing Path in a Matrix", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/longest-increasing-path-in-a-matrix/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/longest-increasing-path-in-a-matrix" + }, + { + "problemName": "330. Patching Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/patching-array/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/0330-patching-array" + }, + { + "problemName": "331. Verify Preorder Serialization of a Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/", + "solutionLink": "#" + }, + { + "problemName": "332. Reconstruct Itinerary", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/reconstruct-itinerary/", + "solutionLink": "#" + }, + { + "problemName": "333. largest-bst-subtree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/largest-bst-subtree/", + "solutionLink": "#" + }, + { + "problemName": "334. Increasing Triplet Subsequence", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/increasing-triplet-subsequence/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/0334-increasing-triplet-subsequence" + }, + { + "problemName": "335. Self Crossing", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/self-crossing/", + "solutionLink": "#" + }, + { + "problemName": "336. Palindrome Pairs", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/palindrome-pairs/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/palindrome-pairs" + }, + { + "problemName": "337. House Robber III", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/house-robber-iii/", + "solutionLink": "#" + }, + { + "problemName": "338. Counting Bits", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/counting-bits/", + "solutionLink": "#" + }, + { + "problemName": "339. nested-list-weight-sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/nested-list-weight-sum/", + "solutionLink": "#" + }, + { + "problemName": "340. longest-substring-with-at-most-k-distinct-characters", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/", + "solutionLink": "#" + }, + { + "problemName": "341. Flatten Nested List Iterator", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/flatten-nested-list-iterator/", + "solutionLink": "#" + }, + { + "problemName": "342. Power of Four", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/power-of-four/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/0342-powerof-four" + }, + { + "problemName": "343. Integer Break", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/integer-break/", + "solutionLink": "#" + }, + { + "problemName": "344. Reverse String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/reverse-string/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/reverse-string" + }, + { + "problemName": "345. Reverse Vowels of a String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/reverse-vowels-of-a-string/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/0345-reverse-vowels-of-a-string" + }, + { + "problemName": "346. moving-average-from-data-stream", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/moving-average-from-data-stream/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/0346-moving-average-from-data-stream" + }, + { + "problemName": "347. Top K Frequent Elements", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/top-k-frequent-elements/", + "solutionLink": "#" + }, + { + "problemName": "348. design-tic-tac-toe", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-tic-tac-toe/", + "solutionLink": "#" + }, + { + "problemName": "349. Intersection of Two Arrays", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/intersection-of-two-arrays/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/0349-Intersection-of-Two-Arrays" + }, + { + "problemName": "350. Intersection of Two Arrays II", + "difficulty": "Easy", + "leetCodeLink": "350. Intersection of Two Arrays II", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/0350-Intersection-of-Two-Arrays-II" + }, + { + "problemName": "351. android-unlock-patterns", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/android-unlock-patterns/", + "solutionLink": "#" + }, + { + "problemName": "352. Data Stream as Disjoint Intervals", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/data-stream-as-disjoint-intervals/", + "solutionLink": "#" + }, + { + "problemName": "353. design-snake-game", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-snake-game/", + "solutionLink": "#" + }, + { + "problemName": "354. Russian Doll Envelopes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/russian-doll-envelopes/", + "solutionLink": "#" + }, + { + "problemName": "355. Design Twitter", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-twitter/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/twitter-design" + }, + { + "problemName": "356. line-reflection", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/line-reflection/", + "solutionLink": "#" + }, + { + "problemName": "357. Count Numbers with Unique Digits", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-numbers-with-unique-digits/", + "solutionLink": "#" + }, + { + "problemName": "358.rearrange-string-k-distance-apart", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/rearrange-string-k-distance-apart/", + "solutionLink": "#" + }, + { + "problemName": "359. logger-rate-limiter", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/logger-rate-limiter/", + "solutionLink": "#" + }, + { + "problemName": "360. sort-transformed-arrayt", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sort-transformed-array/", + "solutionLink": "#" + }, + { + "problemName": "361. bomb-enemy", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/bomb-enemy/", + "solutionLink": "#" + }, + { + "problemName": "362. design-hit-counter", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-hit-counter/", + "solutionLink": "#" + }, + { + "problemName": "363. Max Sum of Rectangle No Larger Than K", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/", + "solutionLink": "#" + }, + { + "problemName": "364. nested-list-weight-sum-ii", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/nested-list-weight-sum-ii/", + "solutionLink": "#" + }, + { + "problemName": "365. Water and Jug Problem", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/water-and-jug-problem/", + "solutionLink": "#" + }, + { + "problemName": "366. find-leaves-of-binary-tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-leaves-of-binary-tree/", + "solutionLink": "#" + }, + { + "problemName": "367. Valid Perfect Square", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/valid-perfect-square/", + "solutionLink": "#" + }, + { + "problemName": "368. Largest Divisible Subset", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/largest-divisible-subset/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/largest-divisible-subset" + }, + { + "problemName": "369. plus-one-linked-list", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/plus-one-linked-list/", + "solutionLink": "#" + }, + { + "problemName": "370. range-addition", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/range-addition/", + "solutionLink": "#" + }, + { + "problemName": "371. Sum of Two Integers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-of-two-integers/", + "solutionLink": "#" + }, + { + "problemName": "372. Super Pow", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/super-pow/", + "solutionLink": "#" + }, + { + "problemName": "373. Find K Pairs with Smallest Sums", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-k-pairs-with-smallest-sums/", + "solutionLink": "#" + }, + { + "problemName": "374. Guess Number Higher or Lower", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/guess-number-higher-or-lower/", + "solutionLink": "/dsa-solutions/lc-solutions/0300-0399/guess-number-higher-or-lower" + }, + { + "problemName": "375. Guess Number Higher or Lower II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/guess-number-higher-or-lower-ii/", + "solutionLink": "#" + }, + { + "problemName": "376. Wiggle Subsequence", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/wiggle-subsequence/", + "solutionLink": "#" + }, + { + "problemName": "377. Combination Sum IV", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/combination-sum-iv/", + "solutionLink": "#" + }, + { + "problemName": "378. Kth Smallest Element in a Sorted Matrix", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/", + "solutionLink": "#" + }, + { + "problemName": "379. design-phone-directory", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-phone-directory/", + "solutionLink": "#" + }, + { + "problemName": "380. Insert Delete GetRandom O(1)", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/insert-delete-getrandom-o1/", + "solutionLink": "#" + }, + { + "problemName": "381. Insert Delete GetRandom O(1) - Duplicates allowed", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/", + "solutionLink": "#" + }, + { + "problemName": "382. Linked List Random Node", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/linked-list-random-node/", + "solutionLink": "#" + }, + { + "problemName": "383. Ransom Note", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/ransom-note/", + "solutionLink": "#" + }, + { + "problemName": "384. Shuffle an Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shuffle-an-array/", + "solutionLink": "#" + }, + { + "problemName": "385. Mini Parser", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/mini-parser/", + "solutionLink": "#" + }, + { + "problemName": "386. Lexicographical Numbers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/lexicographical-numbers/", + "solutionLink": "#" + }, + { + "problemName": "387. First Unique Character in a String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/first-unique-character-in-a-string/", + "solutionLink": "#" + }, + { + "problemName": "388. Longest Absolute File Path", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-absolute-file-path/", + "solutionLink": "#" + }, + { + "problemName": "389. Find the Difference", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-difference/", + "solutionLink": "#" + }, + { + "problemName": "390. Elimination Game", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/elimination-game/", + "solutionLink": "#" + }, + { + "problemName": "391. Perfect Rectangle", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/perfect-rectangle/", + "solutionLink": "#" + }, + { + "problemName": "392. Is Subsequence", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/is-subsequence/", + "solutionLink": "#" + }, + { + "problemName": "393. UTF-8 Validation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/utf-8-validation/", + "solutionLink": "#" + }, + { + "problemName": "394. Decode String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/decode-string/", + "solutionLink": "#" + }, + { + "problemName": "395. Longest Substring with At Least K Repeating Characters", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/", + "solutionLink": "#" + }, + { + "problemName": "396. Rotate Function", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/rotate-function/", + "solutionLink": "#" + }, + { + "problemName": "397. Integer Replacement", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/integer-replacement/", + "solutionLink": "#" + }, + { + "problemName": "399. Random Pick Index", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/random-pick-index/", + "solutionLink": "#" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/leetcode-problems/0400-0499.md b/problems/leetcode-problems/0400-0499.md new file mode 100644 index 0000000..43555dd --- /dev/null +++ b/problems/leetcode-problems/0400-0499.md @@ -0,0 +1,622 @@ +--- +id: 0400-0499 +title: LeetCode Problems 400 - 499 +sidebar_label: 0400 - 0499 +keywords: + - LeetCode + - LeeCode Problems + - LeeCode Problems 400 - 499 + - dsa problems +--- + +export const problems = [ + { + "problemName": "400. Nth Digit", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/nth-digit", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/nth-digit" + }, + { + "problemName": "401. Binary Watch", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/binary-watch", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/binary-watch" + }, + { + "problemName": "402. Remove K Digits", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-k-digits", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/remove-k-digits" + }, + { + "problemName": "403. Frog Jump", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/frog-jump", + "solutionLink": "#" + }, + { + "problemName": "404. Sum of Left Leaves", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sum-of-left-leaves", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/sum-of-left-leaves" + }, + { + "problemName": "405. Convert a Number to Hexadecimal", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/convert-a-number-to-hexadecimal", + "solutionLink": "#" + }, + { + "problemName": "406. Queue Reconstruction by Height", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/queue-reconstruction-by-height", + "solutionLink": "#" + }, + { + "problemName": "407. Trapping Rain Water II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/trapping-rain-water-ii", + "solutionLink": "#" + }, + { + "problemName": "408. Valid Word Abbreviation", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/valid-word-abbreviation", + "solutionLink": "#" + }, + { + "problemName": "409. Longest Palindrome", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/longest-palindrome", + "solutionLink": "#" + }, + { + "problemName": "410. Split Array Largest Sum", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/split-array-largest-sum", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/split-array-largest-sum" + }, + { + "problemName": "411. Minimum Unique Word Abbreviation", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-unique-word-abbreviation", + "solutionLink": "#" + }, + { + "problemName": "412. Fizz Buzz", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/fizz-buzz", + "solutionLink": "#" + }, + { + "problemName": "413. Arithmetic Slices", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/arithmetic-slices", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/arithmetic-slices" + }, + { + "problemName": "414. Third Maximum Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/third-maximum-number", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/third-maximum-number" + }, + { + "problemName": "415. Add Strings", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/add-strings", + "solutionLink": "#" + }, + { + "problemName": "416. Partition Equal Subset Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/partition-equal-subset-sum", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/" + }, + { + "problemName": "417. Pacific Atlantic Water Flow", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/pacific-atlantic-water-flow", + "solutionLink": "#" + }, + { + "problemName": "418. Sentence Screen Fitting", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sentence-screen-fitting", + "solutionLink": "#" + }, + { + "problemName": "419. Battleships in a Board", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/battleships-in-a-board", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/" + }, + { + "problemName": "420. Strong Password Checker", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/strong-password-checker", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/strong-password-checker" + }, + { + "problemName": "421. Maximum XOR of Two Numbers in an Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/" + }, + { + "problemName": "422. Valid Word Square", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/valid-word-square", + "solutionLink": "#" + }, + { + "problemName": "423. Reconstruct Original Digits from English", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reconstruct-original-digits-from-english", + "solutionLink": "#" + }, + { + "problemName": "424. Longest Repeating Character Replacement", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-repeating-character-replacement", + "solutionLink": "#" + }, + { + "problemName": "425. Word Squares", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/word-squares", + "solutionLink": "#" + }, + { + "problemName": "426. Convert Binary Search Tree to Sorted Doubly Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list", + "solutionLink": "#" + }, + { + "problemName": "427. Construct Quad Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/construct-quad-tree", + "solutionLink": "#" + }, + { + "problemName": "428. Serialize and Deserialize N-ary Tree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/serialize-and-deserialize-n-ary-tree", + "solutionLink": "#" + }, + { + "problemName": "429. N-ary Tree Level Order Traversal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/n-ary-tree-level-order-traversal", + "solutionLink": "#" + }, + { + "problemName": "430. Flatten a Multilevel Doubly Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/flatten-a-multilevel-doubly-linked-list" + }, + { + "problemName": "431. Encode N-ary Tree to Binary Tree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/encode-n-ary-tree-to-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "432. All Oone Data Structure", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/all-oone-data-structure", + "solutionLink": "#" + }, + { + "problemName": "433. Minimum Genetic Mutation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-genetic-mutation", + "solutionLink": "#" + }, + { + "problemName": "434. Number of Segments in a String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-segments-in-a-string", + "solutionLink": "#" + }, + { + "problemName": "435. Non-overlapping Intervals", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/non-overlapping-intervals", + "solutionLink": "#" + }, + { + "problemName": "436. Find Right Interval", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-right-interval", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/find-right-interval" + }, + { + "problemName": "437. Path Sum III", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/path-sum-iii", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/path-sum-iii" + }, + { + "problemName": "438. Find All Anagrams in a String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-all-anagrams-in-a-string", + "solutionLink": "#" + }, + { + "problemName": "439. Ternary Expression Parser", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/ternary-expression-parser", + "solutionLink": "#" + }, + { + "problemName": "440. K-th Smallest in Lexicographical Order", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/k-th-smallest-in-lexicographical-order", + "solutionLink": "#" + }, + { + "problemName": "441. Arranging Coins", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/arranging-coins", + "solutionLink": "#" + }, + { + "problemName": "442. Find All Duplicates in an Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-all-duplicates-in-an-array", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/find-all-duplicates-in-an-array" + }, + { + "problemName": "443. String Compression", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/string-compression", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/string-compression" + }, + { + "problemName": "444. Sequence Reconstruction", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sequence-reconstruction", + "solutionLink": "#" + }, + { + "problemName": "445. Add Two Numbers II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/add-two-numbers-ii", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/add-two-numbers-ii" + }, + { + "problemName": "446. Arithmetic Slices II - Subsequence", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/arithmetic-slices-ii-subsequence", + "solutionLink": "#" + }, + { + "problemName": "447. Number of Boomerangs", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-boomerangs", + "solutionLink": "#" + }, + { + "problemName": "448. Find All Numbers Disappeared in an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "449. Serialize and Deserialize BST", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/serialize-and-deserialize-bst", + "solutionLink": "#" + }, + { + "problemName": "450. Delete Node in a BST", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/delete-node-in-a-bst", + "solutionLink": "#" + }, + { + "problemName": "451. Sort Characters By Frequency", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sort-characters-by-frequency", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/sort-characters-by-frequency" + }, + { + "problemName": "452. Minimum Number of Arrows to Burst Balloons", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons", + "solutionLink": "#" + }, + { + "problemName": "453. Minimum Moves to Equal Array Elements", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-moves-to-equal-array-elements", + "solutionLink": "#" + }, + { + "problemName": "454. 4Sum II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/4sum-ii", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/4Sum-II" + }, + { + "problemName": "455. Assign Cookies", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/assign-cookies", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/assign-cookies" + }, + { + "problemName": "456. 132 Pattern", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/132-pattern", + "solutionLink": "#" + }, + { + "problemName": "457. Circular Array Loop", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/circular-array-loop", + "solutionLink": "#" + }, + { + "problemName": "458. Poor Pigs", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/poor-pigs", + "solutionLink": "#" + }, + { + "problemName": "459. Repeated Substring Pattern", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/repeated-substring-pattern", + "solutionLink": "#" + }, + { + "problemName": "460. LFU Cache", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/lfu-cache", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/lfu-cache" + }, + { + "problemName": "461. Hamming Distance", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/hamming-distance", + "solutionLink": "#" + }, + { + "problemName": "462. Minimum Moves to Equal Array Elements II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii", + "solutionLink": "#" + }, + { + "problemName": "463. Island Perimeter", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/island-perimeter", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/island-perimeter" + }, + { + "problemName": "464. Can I Win", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/can-i-win", + "solutionLink": "#" + }, + { + "problemName": "465. Optimal Account Balancing", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/optimal-account-balancing", + "solutionLink": "#" + }, + { + "problemName": "466. Count The Repetitions", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-the-repetitions", + "solutionLink": "#" + }, + { + "problemName": "467. Unique Substrings in Wraparound String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/unique-substrings-in-wraparound-string", + "solutionLink": "#" + }, + { + "problemName": "468. Validate IP Address", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/validate-ip-address", + "solutionLink": "#" + }, + { + "problemName": "469. Convex Polygon", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/convex-polygon", + "solutionLink": "#" + }, + { + "problemName": "470. Implement Rand10() Using Rand7()", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/implement-rand10-using-rand7", + "solutionLink": "#" + }, + { + "problemName": "471. Encode String with Shortest Length", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/encode-string-with-shortest-length", + "solutionLink": "#" + }, + { + "problemName": "472. Concatenated Words", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/concatenated-words", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/concatenated-words" + }, + { + "problemName": "473. Matchsticks to Square", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/matchsticks-to-square", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/matchsticks-to-square" + }, + { + "problemName": "474. Ones and Zeroes", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/ones-and-zeroes", + "solutionLink": "#" + }, + { + "problemName": "475. Heaters", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/heaters", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/heaters" + }, + { + "problemName": "476. Number Complement", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-complement", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/number-complement" + }, + { + "problemName": "477. Total Hamming Distance", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/total-hamming-distance", + "solutionLink": "#" + }, + { + "problemName": "478. Generate Random Point in a Circle", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/generate-random-point-in-a-circle", + "solutionLink": "#" + }, + { + "problemName": "479. Largest Palindrome Product", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/largest-palindrome-product", + "solutionLink": "#" + }, + { + "problemName": "480. Sliding Window Median", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sliding-window-median", + "solutionLink": "#" + }, + { + "problemName": "481. Magical String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/magical-string", + "solutionLink": "#" + }, + { + "problemName": "482. License Key Formatting", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/license-key-formatting", + "solutionLink": "#" + }, + { + "problemName": "483. Smallest Good Base", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/smallest-good-base", + "solutionLink": "#" + }, + { + "problemName": "484. Find Permutation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-permutation", + "solutionLink": "#" + }, + { + "problemName": "485. Max Consecutive Ones", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/max-consecutive-ones", + "solutionLink": "#" + }, + { + "problemName": "486. Predict the Winner", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/predict-the-winner", + "solutionLink": "#" + }, + { + "problemName": "487. Max Consecutive Ones II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/max-consecutive-ones-ii", + "solutionLink": "#" + }, + { + "problemName": "488. Zuma Game", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/zuma-game", + "solutionLink": "#" + }, + { + "problemName": "489. Robot Room Cleaner", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/robot-room-cleaner", + "solutionLink": "#" + }, + { + "problemName": "490. The Maze", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-maze", + "solutionLink": "#" + }, + { + "problemName": "491. Increasing Subsequences", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/increasing-subsequences", + "solutionLink": "#" + }, + { + "problemName": "492. Construct the Rectangle", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/construct-the-rectangle", + "solutionLink": "#" + }, + { + "problemName": "493. Reverse Pairs", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/reverse-pairs", + "solutionLink": "#" + }, + { + "problemName": "494. Target Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/target-sum", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/target-sum" + }, + { + "problemName": "495. Teemo Attacking", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/teemo-attacking", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/teemo-attacking" + }, + { + "problemName": "496. Next Greater Element I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/next-greater-element-i", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/next-greater-element-I" + }, + { + "problemName": "497. Random Point in Non-overlapping Rectangles", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/random-point-in-non-overlapping-rectangles", + "solutionLink": "#" + }, + { + "problemName": "498. Diagonal Traverse", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/diagonal-traverse", + "solutionLink": "/dsa-solutions/lc-solutions/0400-0499/diagonal-traverse" + }, + { + "problemName": "499. The Maze III", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/the-maze-iii", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/leetcode-problems/0500-0599.md b/problems/leetcode-problems/0500-0599.md new file mode 100644 index 0000000..65b2b6c --- /dev/null +++ b/problems/leetcode-problems/0500-0599.md @@ -0,0 +1,520 @@ +--- +id: 0500-0599 +title: LeetCode Problems 500 - 599 +sidebar_label: 0500 - 0599 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 500 - 599 + - DSA problems +--- + +export const problems =[ + { + "problemName": "500. Keyboard Row", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/keyboard-row", + "solutionLink": "#" + }, + { + "problemName": "501. Find Mode in Binary Search Tree", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-mode-in-binary-search-tree", + "solutionLink": "#" + }, + { + "problemName": "502. IPO", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/ipo", + "solutionLink": "#" + }, + { + "problemName": "503. Next Greater Element II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/next-greater-element-ii", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/next-greater-element-ii" + }, + { + "problemName": "504. Base 7", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/base-7", + "solutionLink": "#" + }, + { + "problemName": "505. The Maze II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-maze-ii", + "solutionLink": "#" + }, + { + "problemName": "506. Relative Ranks", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/relative-ranks", + "solutionLink": "#" + }, + { + "problemName": "507. Perfect Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/perfect-number", + "solutionLink": "#" + }, + { + "problemName": "508. Most Frequent Subtree Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/most-frequent-subtree-sum", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/most-frequent-subtree-sum" + }, + { + "problemName": "509. Fibonacci Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/fibonacci-number", + "solutionLink": "#" + }, + { + "problemName": "510. Inorder Successor in BST II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/inorder-successor-in-bst-ii", + "solutionLink": "#" + }, + { + "problemName": "513. Find Bottom Left Tree Value", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-bottom-left-tree-value", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/find-bottom-left-tree-value" + }, + { + "problemName": "514. Freedom Trail", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/freedom-trail", + "solutionLink": "#" + }, + { + "problemName": "515. Find Largest Value in Each Tree Row", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-largest-value-in-each-tree-row", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/find-largest-value-in-each-tree-row" + }, + { + "problemName": "516. Longest Palindromic Subsequence", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-palindromic-subsequence", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/longest-palindromic-subsequence" + }, + { + "problemName": "517. Super Washing Machines", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/super-washing-machines", + "solutionLink": "#" + }, + { + "problemName": "518. Coin Change 2", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/coin-change-2", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/coin-change-2" + }, + { + "problemName": "519. Random Flip Matrix", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/random-flip-matrix", + "solutionLink": "#" + }, + { + "problemName": "520. Detect Capital", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/detect-capital", + "solutionLink": "#" + }, + { + "problemName": "521. Longest Uncommon Subsequence I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/longest-uncommon-subsequence-i", + "solutionLink": "#" + }, + { + "problemName": "522. Longest Uncommon Subsequence II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-uncommon-subsequence-ii", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/longest-uncommon-subsequence-ii" + }, + { + "problemName": "523. Continuous Subarray Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/continuous-subarray-sum", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/continuous-subarray-sum" + }, + { + "problemName": "524. Longest Word in Dictionary through Deleting", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-word-in-dictionary-through-deleting", + "solutionLink": "#" + }, + { + "problemName": "525. Contiguous Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/contiguous-array", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/contiguous-array" + }, + { + "problemName": "526. Beautiful Arrangement", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/beautiful-arrangement", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/0526-Beautiful-Arrangement" + }, + { + "problemName": "527. Word Abbreviation", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/word-abbreviation", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/0527-Word-Abbreviation" + }, + { + "problemName": "528. Random Pick with Weight", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/random-pick-with-weight", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/random-pick-with-weight" + }, + { + "problemName": "529. Minesweeper", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minesweeper", + "solutionLink": "#" + }, + { + "problemName": "530. Minimum Absolute Difference in BST", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-absolute-difference-in-bst", + "solutionLink": "#" + }, + { + "problemName": "531. Lonely Pixel I", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/lonely-pixel-i", + "solutionLink": "#" + }, + { + "problemName": "532. K-diff Pairs in an Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/k-diff-pairs-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "533. Lonely Pixel II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/lonely-pixel-ii", + "solutionLink": "#" + }, + { + "problemName": "535. Encode and Decode TinyURL", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/encode-and-decode-tinyurl", + "solutionLink": "#" + }, + { + "problemName": "536. Construct Binary Tree from String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/construct-binary-tree-from-string", + "solutionLink": "#" + }, + { + "problemName": "537. Complex Number Multiplication", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/complex-number-multiplication", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/complex-number-multiplication" + }, + { + "problemName": "538. Convert BST to Greater Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/convert-bst-to-greater-tree", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/convert-bst-to-greater-tree" + }, + { + "problemName": "539. Minimum Time Difference", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-difference", + "solutionLink": "#" + }, + { + "problemName": "540. Single Element in a Sorted Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/single-element-in-a-sorted-array", + "solutionLink": "#" + }, + { + "problemName": "541. Reverse String II", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/reverse-string-ii", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/reverse-string-ii" + }, + { + "problemName": "542. 01 Matrix", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/01-matrix", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/matrix" + }, + { + "problemName": "543. Diameter of Binary Tree", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/diameter-of-binary-tree", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/diameter-of-a-binary-tree" + }, + { + "problemName": "544. Output Contest Matches", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/output-contest-matches", + "solutionLink": "#" + }, + { + "problemName": "545. Boundary of Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/boundary-of-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "546. Remove Boxes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/remove-boxes", + "solutionLink": "#" + }, + { + "problemName": "547. Number of Provinces", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-provinces/", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/number-of-provinces" + }, + { + "problemName": "548. Split Array with Equal Sum", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/split-array-with-equal-sum", + "solutionLink": "#" + }, + { + "problemName": "549. Binary Tree Longest Consecutive Sequence II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii", + "solutionLink": "#" + }, + { + "problemName": "550. Game Play Analysis IV", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/game-play-analysis-iv", + "solutionLink": "#" + }, + { + "problemName": "551. Student Attendance Record I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/student-attendance-record-i", + "solutionLink": "#" + }, + { + "problemName": "552. Student Attendance Record II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/student-attendance-record-ii", + "solutionLink": "#" + }, + { + "problemName": "553. Optimal Division", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/optimal-division", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/optimal-division" + }, + { + "problemName": "554. Brick Wall", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/brick-wall", + "solutionLink": "#" + }, + { + "problemName": "555. Split Concatenated Strings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/split-concatenated-strings", + "solutionLink": "#" + }, + { + "problemName": "556. Next Greater Element III", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/next-greater-element-iii", + "solutionLink": "#" + }, + { + "problemName": "557. Reverse Words in a String III", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/reverse-words-in-a-string-iii", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/reverse-words-in-a-string-iii" + }, + { + "problemName": "558. Quad Tree Intersection", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/quad-tree-intersection", + "solutionLink": "#" + }, + { + "problemName": "559. Maximum Depth of N-ary Tree", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-depth-of-n-ary-tree", + "solutionLink": "#" + }, + { + "problemName": "560. Subarray Sum Equals K", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/subarray-sum-equals-k", + "solutionLink": "#" + }, + { + "problemName": "561. Array Partition I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/array-partition-i", + "solutionLink": "#" + }, + { + "problemName": "562. Longest Line of Consecutive One in Matrix", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix", + "solutionLink": "#" + }, + { + "problemName": "563. Binary Tree Tilt", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/binary-tree-tilt", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/binary-tree-tilt" + }, + { + "problemName": "564. Find the Closest Palindrome", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-the-closest-palindrome", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/find-the-closest-palindrome" + }, + { + "problemName": "565. Array Nesting", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/array-nesting", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/array-nesting" + }, + { + "problemName": "566. Reshape the Matrix", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/reshape-the-matrix", + "solutionLink": "#" + }, + { + "problemName": "567. Permutation in String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/permutation-in-string", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/permutation-in-string" + }, + { + "problemName": "568. Maximum Vacation Days", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-vacation-days", + "solutionLink": "#" + }, + { + "problemName": "572. Subtree of Another Tree", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/subtree-of-another-tree", + "solutionLink": "#" + }, + { + "problemName": "573. Squirrel Simulation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/squirrel-simulation", + "solutionLink": "#" + }, + { + "problemName": "575. Distribute Candies", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/distribute-candies", + "solutionLink": "#" + }, + { + "problemName": "576. Out of Boundary Paths", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/out-of-boundary-paths", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/out-of-boundary-paths" + }, + { + "problemName": "581. Shortest Unsorted Continuous Subarray", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shortest-unsorted-continuous-subarray", + "solutionLink": "#" + }, + { + "problemName": "582. Kill Process", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/kill-process", + "solutionLink": "#" + }, + { + "problemName": "583. Delete Operation for Two Strings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/delete-operation-for-two-strings", + "solutionLink": "#" + }, + { + "problemName": "587. Erect the Fence", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/erect-the-fence", + "solutionLink": "#" + }, + { + "problemName": "588. Design In-Memory File System", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/design-in-memory-file-system", + "solutionLink": "#" + }, + { + "problemName": "589. N-ary Tree Preorder Traversal", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/n-ary-tree-preorder-traversal", + "solutionLink": "#" + }, + { + "problemName": "590. N-ary Tree Postorder Traversal", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/n-ary-tree-postorder-traversal", + "solutionLink": "#" + }, + { + "problemName": "591. Tag Validator", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/tag-validator", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/tag-validator" + }, + { + "problemName": "592. Fraction Addition and Subtraction", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/fraction-addition-and-subtraction", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/fraction-addition-and-subtraction" + }, + { + "problemName": "593. Valid Square", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/valid-square", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/valid-square" + }, + { + "problemName": "594. Longest Harmonious Subsequence", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/longest-harmonious-subsequence", + "solutionLink": "#" + }, + { + "problemName": "598. Range Addition II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/range-addition-ii", + "solutionLink": "#" + }, + { + "problemName": "599. Minimum Index Sum of Two Lists", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-index-sum-of-two-lists", + "solutionLink": "/dsa-solutions/lc-solutions/0500-0599/minimum-index-sum-of-two-lists" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/leetcode-problems/0600-0699.md b/problems/leetcode-problems/0600-0699.md new file mode 100644 index 0000000..88c3c2a --- /dev/null +++ b/problems/leetcode-problems/0600-0699.md @@ -0,0 +1,623 @@ +--- +id: 0600-0699 +title: LeetCode Problems 600 - 699 +sidebar_label: 0600 - 0699 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 600 - 699 + - DSA problems +--- + +export const problems = [ +{ + "problemName": "600. Non-negative Integers without Consecutive Ones", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/non-negative-integers-without-consecutive-ones", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/non-negative-integers-without-consecutive-ones" +}, +{ + "problemName": "601. Human Traffic of Stadium", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/human-traffic-of-stadium", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/human-traffic-of-stadium" +}, +{ + "problemName": "602. Friend Requests II: Whow has the Most Friends", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/friend-requests-ii-who-has-the-most-friends" +}, +{ + "problemName": "603. Consecutive Available Seats", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/consecutive-available-seats", + "solutionLink": "#" +}, +{ + "problemName": "604. Design Compressed String Iterator", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/design-compressed-string-iterator", + "solutionLink": "#" +}, +{ + "problemName": "605. Can Place Flowers", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/can-place-flowers", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/can-place-flowers" +}, +{ + "problemName": "606. Construct String from Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/construct-string-from-binary-tree", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/construct-string-from-binary-tree" +}, +{ + "problemName": "607. Sales Person", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sales-person", + "solutionLink": "#" +}, +{ + "problemName": "608. Tree Node", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/tree-node", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/tree-node" +}, +{ + "problemName": "609. Find Duplicate File in System", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-duplicate-file-in-system", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/find-duplicate-file-in-system" +}, +{ + "problemName": "610. Triangle Judgement", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/triangle-judgement", + "solutionLink": "#" +}, +{ + "problemName": "611. Valid Triangle Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/valid-triangle-number", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/valid-triangle-number" +}, +{ + "problemName": "612. Shortest Distance in a Plane", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shortest-distance-in-a-plane", + "solutionLink": "#" +}, +{ + "problemName": "613. Shortest Distance in a Line", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/shortest-distance-in-a-line", + "solutionLink": "#" +}, +{ + "problemName": "614. Second Degree Follower", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/second-degree-follower", + "solutionLink": "#" +}, +{ + "problemName": "615. Average Salary: Departments VS Company" +, + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/average-salary-departments-vs-company", + "solutionLink": "#" +}, +{ + "problemName": "616. Add Bold Tag in String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/add-bold-tag-in-string", + "solutionLink": "#" +}, + { + "problemName": "617. Merge Two Binary Trees", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/merge-two-binary-trees", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/merge-two-binary-trees" + }, +{ + "problemName": "618. Students Report By Geography", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/students-report-by-geography", + "solutionLink": "#" + }, + { + "problemName": "619. Biggest Single Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/biggest-single-number", + "solutionLink": "#" + }, + { + "problemName": "620. Not Boring Movies", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/not-boring-movies", + "solutionLink": "#" + }, + { + "problemName": "621. Task Scheduler", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/task-scheduler", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/task-scheduler" + }, + { + "problemName": "622. Design Circular Queue", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-circular-queue", + "solutionLink": "#" + }, + { + "problemName": "623. Add One Row to Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/add-one-row-to-tree", + "solutionLink": "#" + }, + { + "problemName": "624. Maximum Distance in Arrays", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-distance-in-arrays", + "solutionLink": "#" + }, + { + "problemName": "625. Minimum Factorization", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-factorization", + "solutionLink": "#" + }, + { + "problemName": "626. Exchange Seats", + "difficulty": "Meidum", + "leetCodeLink": "https://leetcode.com/problems/exchange-seats", + "solutionLink": "#" + }, + { + "problemName": "627. Swap Salary", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/swap-salary", + "solutionLink": "#" + }, + { + "problemName": "628. Maximum Product of Three Numbers", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-product-of-three-numbers", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/maximum-product-of-three-numbers" + }, + { + "problemName": "629. K Inverse Pairs Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/k-inverse-pairs-array", + "solutionLink": "#" + }, + { + "problemName": "630. Course Schedule III", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/course-schedule-iii", + "solutionLink": "#" + }, + { + "problemName": "631. Design Excel Sum Formula", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/design-excel-sum-formula", + "solutionLink": "#" + }, + { + "problemName": "632. Smallest Range Covering Elements from K Lists", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists", + "solutionLink": "#" + }, + { + "problemName": "633. Sum of Square Numbers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-of-square-numbers", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/sum-of-square-numbers" + }, + { + "problemName": "634. Find the Derangement of An Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-derangement-of-an-array", + "solutionLink": "#" + }, + { + "problemName": "635. Design Log Storage System", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-log-storage-system", + "solutionLink": "#" + }, + { + "problemName": "636. Exclusive Time of Functions", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/exclusive-time-of-functions", + "solutionLink": "#" + }, + { + "problemName": "637. Average of Levels in Binary Tree", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/average-of-levels-in-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "638. Shopping Offers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shopping-offers", + "solutionLink": "#" + }, + { + "problemName": "639. Decode Ways II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/decode-ways-ii", + "solutionLink": "#" + }, + { + "problemName": "640. Solve the Equation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/solve-the-equation", + "solutionLink": "#" + }, + { + "problemName": "641. Design Circular Deque", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-circular-deque", + "solutionLink": "#" + }, + { + "problemName": "642. Design Search Autocomplete System", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/design-search-autocomplete-system", + "solutionLink": "#" + }, + { + "problemName": "643. Maximum Average Subarray I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-average-subarray-i", + "solutionLink": "#" + }, + { + "problemName": "644. Maximum Average Subarray II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-average-subarray-ii", + "solutionLink": "#" + }, + { + "problemName": "645. Set Mismatch", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/set-mismatch", + "solutionLink": "#" + }, + { + "problemName": "646. Maximum Length of Pair Chain", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-length-of-pair-chain", + "solutionLink": "#" + }, + { + "problemName": "647. Palindromic Substrings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/palindromic-substrings", + "solutionLink": "#" + }, + { + "problemName": "648. Replace Words", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/replace-words", + "solutionLink": "#" + }, + { + "problemName": "649. Dota2 Senate", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/dota2-senate", + "solutionLink": "#" + }, + { + "problemName": "650. 2 Keys Keyboard", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/2-keys-keyboard", + "solutionLink": "#" + }, + { + "problemName": "651. 4 Keys Keyboard", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/4-keys-keyboard", + "solutionLink": "#" + }, + { + "problemName": "652. Find Duplicate Subtrees", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-duplicate-subtrees", + "solutionLink": "#" + }, + { + "problemName": "653. Two Sum IV - Input is a BST", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/two-sum-iv-input-is-a-bst", + "solutionLink": "#" + }, + { + "problemName": "654. Maximum Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "655. Print Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/print-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "656. Coin Path", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/coin-path", + "solutionLink": "#" + }, + { + "problemName": "657. Robot Return to Origin", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/robot-return-to-origin", + "solutionLink": "#" + }, + { + "problemName": "658. Find K Closest Elements", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-k-closest-elements", + "solutionLink": "#" + }, + { + "problemName": "659. Split Array into Consecutive Subsequences", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/split-array-into-consecutive-subsequences", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/split-array-into-consecutive-subsequences" + }, + { + "problemName": "660. Remove 9", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/remove-9", + "solutionLink": "#" + }, + { + "problemName": "661. Image Smoother", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/image-smoother", + "solutionLink": "#" + }, + { + "problemName": "662. Maximum Width of Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-width-of-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "663. Equal Tree Partition", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/equal-tree-partition", + "solutionLink": "#" + }, + { + "problemName": "664. Strange Printer", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/strange-printer", + "solutionLink": "#" + }, + { + "problemName": "665. Non-decreasing Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/non-decreasing-array", + "solutionLink": "#" + }, + { + "problemName": "666. Path Sum IV", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/path-sum-iv", + "solutionLink": "#" + }, + { + "problemName": "667. Beautiful Arrangement II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/beautiful-arrangement-ii", + "solutionLink": "#" + }, + { + "problemName": "668. Kth Smallest Number in Multiplication Table", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/kth-smallest-number-in-multiplication-table", + "solutionLink": "#" + }, + { + "problemName": "669. Trim a Binary Search Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/trim-a-binary-search-tree", + "solutionLink": "#" + }, + { + "problemName": "670. Maximum Swap", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-swap", + "solutionLink": "#" + }, + { + "problemName": "671. Second Minimum Node In a Binary Tree", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/second-minimum-node-in-a-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "672. Bulb Switcher II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/bulb-switcher-ii", + "solutionLink": "#" + }, + { + "problemName": "673. Number of Longest Increasing Subsequence", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-longest-increasing-subsequence", + "solutionLink": "#" + }, + { + "problemName": "674. Longest Continuous Increasing Subsequence", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/longest-continuous-increasing-subsequence", + "solutionLink": "#" + }, + { + "problemName": "675. Cut Off Trees for Golf Event", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/cut-off-trees-for-golf-event", + "solutionLink": "#" + }, + { + "problemName": "676. Implement Magic Dictionary", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/implement-magic-dictionary", + "solutionLink": "#" + }, + { + "problemName": "677. Map Sum Pairs", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/map-sum-pairs", + "solutionLink": "#" + }, + { + "problemName": "678. Valid Parenthesis String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/valid-parenthesis-string", + "solutionLink": "#" + }, + { + "problemName": "679. 24 Game", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/24-game", + "solutionLink": "#" + }, + { + "problemName": "680. Valid Palindrome II", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/valid-palindrome-ii", + "solutionLink": "#" + }, + { + "problemName": "681. Next Closest Time", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/next-closest-time", + "solutionLink": "#" + }, + { + "problemName": "682. Baseball Game", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/baseball-game", + "solutionLink": "#" + }, + { + "problemName": "683. K Empty Slots", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/k-empty-slots", + "solutionLink": "#" + }, + { + "problemName": "684. Redundant Connection", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/redundant-connection", + "solutionLink": "#" + }, + { + "problemName": "685. Redundant Connection II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/redundant-connection-ii", + "solutionLink": "#" + }, + { + "problemName": "686. Repeated String Match", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/repeated-string-match", + "solutionLink": "#" + }, + { + "problemName": "687. Longest Univalue Path", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-univalue-path", + "solutionLink": "#" + }, + { + "problemName": "688. Knight Probability in Chessboard", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/knight-probability-in-chessboard", + "solutionLink": "#" + }, + { + "problemName": "689. Maximum Sum of 3 Non-Overlapping Subarrays", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays", + "solutionLink": "#" + }, + { + "problemName": "690. Employee Importance", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/employee-importance", + "solutionLink": "#" + }, + { + "problemName": "691. Stickers to Spell Word", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/stickers-to-spell-word", + "solutionLink": "#" + }, + { + "problemName": "692. Top K Frequent Words", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/top-k-frequent-words", + "solutionLink": "#" + }, + { + "problemName": "693. Binary Number with Alternating Bits", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/binary-number-with-alternating-bits", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/binary-number-with-alternating-bits" + }, + { + "problemName": "694. Number of Distinct Islands", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-distinct-islands", + "solutionLink": "#" + }, + { + "problemName": "695. Max Area of Island", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/max-area-of-island", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/max-area-of-island" + }, + { + "problemName": "696. Count Binary Substrings", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-binary-substrings", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/count-binary-substrings" + }, + { + "problemName": "697. Degree of an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/degree-of-an-array", + "solutionLink": "/dsa-solutions/lc-solutions/0600-0699/degree-of-an-array" + }, + { + "problemName": "698. Partition to K Equal Sum Subsets", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/partition-to-k-equal-sum-subsets", + "solutionLink": "#" + }, + { + "problemName": "699. Falling Squares", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/falling-squares", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/0700-0799.md b/problems/leetcode-problems/0700-0799.md new file mode 100644 index 0000000..0ff1ede --- /dev/null +++ b/problems/leetcode-problems/0700-0799.md @@ -0,0 +1,622 @@ +--- +id: 0700-0799 +title: LeetCode Problems 700 - 799 +sidebar_label: 0700 - 0799 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 700 - 799 + - DSA problems +--- + +export const problems = [ + { + "problemName": "700. Search in a Binary Search Tree", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/search-in-a-binary-search-tree", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/search-in-a-binary-search-tree" + }, + { + "problemName": "701. Insert into a Binary Search Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/insert-into-a-binary-search-tree", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/insert-into-a-binary-search-tree" + }, + { + "problemName": "702. Search in a Sorted Array of Unknown Size", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size", + "solutionLink": "#" + }, + { + "problemName": "703. Kth Largest Element in a Stream", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/kth-largest-element-in-a-stream", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/kth-largest-element-in-a-stream" + }, + { + "problemName": "704. Binary Search", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/binary-search", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/binary-search" + }, + { + "problemName": "705. Design HashSet", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/design-hashset", + "solutionLink": "#" + }, + { + "problemName": "706. Design HashMap", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/design-hashmap", + "solutionLink": "#" + }, + { + "problemName": "707. Design Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-linked-list", + "solutionLink": "#" + }, + { + "problemName": "708. Insert into a Sorted Circular Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/insert-into-a-sorted-circular-linked-list", + "solutionLink": "#" + }, + { + "problemName": "709. To Lower Case", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/to-lower-case", + "solutionLink": "#" + }, + { + "problemName": "710. Random Pick with Blacklist", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/random-pick-with-blacklist", + "solutionLink": "#" + }, + { + "problemName": "711. Number of Distinct Islands II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-distinct-islands-ii", + "solutionLink": "#" + }, + { + "problemName": "712. Minimum ASCII Delete Sum for Two Strings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings", + "solutionLink": "#" + }, + { + "problemName": "713. Subarray Product Less Than K", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/subarray-product-less-than-k", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/subarray-product-less-than-k" + }, + { + "problemName": "714. Best Time to Buy and Sell Stock with Transaction Fee", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee", + "solutionLink": "#" + }, + { + "problemName": "715. Range Module", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/range-module", + "solutionLink": "#" + }, + { + "problemName": "716. Max Stack", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/max-stack", + "solutionLink": "#" + }, + { + "problemName": "717. 1-bit and 2-bit Characters", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/1-bit-and-2-bit-characters", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/1-bit-and-2-bit-characters" + }, + { + "problemName": "718. Maximum Length of Repeated Subarray", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-length-of-repeated-subarray", + "solutionLink": "#" + }, + { + "problemName": "719. Find K-th Smallest Pair Distance", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-k-th-smallest-pair-distance", + "solutionLink": "#" + }, + { + "problemName": "720. Longest Word in Dictionary", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-word-in-dictionary", + "solutionLink": "#" + }, + { + "problemName": "721. Accounts Merge", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/accounts-merge", + "solutionLink": "#" + }, + { + "problemName": "722. Remove Comments", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-comments", + "solutionLink": "#" + }, + { + "problemName": "723. Candy Crush", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/candy-crush", + "solutionLink": "#" + }, + { + "problemName": "724. Find Pivot Index", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-pivot-index", + "solutionLink": "#" + }, + { + "problemName": "725. Split Linked List in Parts", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/split-linked-list-in-parts", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/split-linked-list-in-parts" + }, + { + "problemName": "726. Number of Atoms", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-atoms", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/number-of-atoms" + }, + { + "problemName": "727. Minimum Window Subsequence", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-window-subsequence", + "solutionLink": "#" + }, + { + "problemName": "728. Self Dividing Numbers", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/self-dividing-numbers", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/self-dividing-numbers" + }, + { + "problemName": "729. My Calendar I", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/my-calendar-i", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/my-calendar-i" + }, + { + "problemName": "730. Count Different Palindromic Subsequences", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-different-palindromic-subsequences", + "solutionLink": "#" + }, + { + "problemName": "731. My Calendar II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/my-calendar-ii", + "solutionLink": "#" + }, + { + "problemName": "732. My Calendar III", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/my-calendar-iii", + "solutionLink": "#" + }, + { + "problemName": "733. Flood Fill", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/flood-fill", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/flood-fill" + }, + { + "problemName": "734. Sentence Similarity", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sentence-similarity", + "solutionLink": "#" + }, + { + "problemName": "735. Asteroid Collision", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/asteroid-collision", + "solutionLink": "#" + }, + { + "problemName": "736. Parse Lisp Expression", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/parse-lisp-expression", + "solutionLink": "#" + }, + { + "problemName": "737. Sentence Similarity II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sentence-similarity-ii", + "solutionLink": "#" + }, + { + "problemName": "738. Monotone Increasing Digits", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/monotone-increasing-digits", + "solutionLink": "#" + }, + { + "problemName": "739. Daily Temperatures", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/daily-temperatures", + "solutionLink": "#" + }, + { + "problemName": "740. Delete and Earn", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/delete-and-earn", + "solutionLink": "#" + }, + { + "problemName": "741. Cherry Pickup", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/cherry-pickup", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/cherry-pickup" + }, + { + "problemName": "742. Closest Leaf in a Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/closest-leaf-in-a-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "743. Network Delay Time", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/network-delay-time", + "solutionLink": "#" + }, + { + "problemName": "744. Find Smallest Letter Greater Than Target", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-smallest-letter-greater-than-target", + "solutionLink": "#" + }, + { + "problemName": "745. Prefix and Suffix Search", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/prefix-and-suffix-search", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/prefix-and-suffix-search" + }, + { + "problemName": "746. Min Cost Climbing Stairs", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/min-cost-climbing-stairs", + "solutionLink": "#" + }, + { + "problemName": "747. Largest Number At Least Twice of Others", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/largest-number-at-least-twice-of-others", + "solutionLink": "#" + }, + { + "problemName": "748. Shortest Completing Word", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/shortest-completing-word", + "solutionLink": "#" + }, + { + "problemName": "749. Contain Virus", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/contain-virus", + "solutionLink": "#" + }, + { + "problemName": "750. Number Of Corner Rectangles", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-corner-rectangles", + "solutionLink": "#" + }, + { + "problemName": "751. IP to CIDR", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/ip-to-cidr", + "solutionLink": "#" + }, + { + "problemName": "752. Open the Lock", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/open-the-lock", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/open-the-lock" + }, + { + "problemName": "753. Cracking the Safe", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/cracking-the-safe", + "solutionLink": "#" + }, + { + "problemName": "754. Reach a Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reach-a-number", + "solutionLink": "#" + }, + { + "problemName": "755. Pour Water", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/pour-water", + "solutionLink": "#" + }, + { + "problemName": "756. Pyramid Transition Matrix", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/pyramid-transition-matrix", + "solutionLink": "#" + }, + { + "problemName": "757. Set Intersection Size At Least Two", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/set-intersection-size-at-least-two", + "solutionLink": "#" + }, + { + "problemName": "758. Bold Words in String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/bold-words-in-string", + "solutionLink": "#" + }, + { + "problemName": "759. Employee Free Time", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/employee-free-time", + "solutionLink": "#" + }, + { + "problemName": "760. Find Anagram Mappings", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-anagram-mappings", + "solutionLink": "#" + }, + { + "problemName": "761. Special Binary String", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/special-binary-string", + "solutionLink": "#" + }, + { + "problemName": "762. Prime Number of Set Bits in Binary Representation", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation", + "solutionLink": "#" + }, + { + "problemName": "763. Partition Labels", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/partition-labels", + "solutionLink": "#" + }, + { + "problemName": "764. Largest Plus Sign", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/largest-plus-sign", + "solutionLink": "#" + }, + { + "problemName": "765. Couples Holding Hands", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/couples-holding-hands", + "solutionLink": "#" + }, + { + "problemName": "766. Toeplitz Matrix", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/toeplitz-matrix", + "solutionLink": "#" + }, + { + "problemName": "767. Reorganize String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reorganize-string", + "solutionLink": "#" + }, + { + "problemName": "768. Max Chunks To Make Sorted II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/max-chunks-to-make-sorted-ii", + "solutionLink": "#" + }, + { + "problemName": "769. Max Chunks To Make Sorted", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/max-chunks-to-make-sorted", + "solutionLink": "#" + }, + { + "problemName": "770. Basic Calculator IV", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/basic-calculator-iv", + "solutionLink": "#" + }, + { + "problemName": "771. Jewels and Stones", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/jewels-and-stones", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/jewels-and-stones" + }, + { + "problemName": "772. Basic Calculator III", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/basic-calculator-iii", + "solutionLink": "#" + }, + { + "problemName": "773. Sliding Puzzle", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sliding-puzzle", + "solutionLink": "#" + }, + { + "problemName": "774. Minimize Max Distance to Gas Station", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimize-max-distance-to-gas-station", + "solutionLink": "#" + }, + { + "problemName": "775. Global and Local Inversions", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/global-and-local-inversions", + "solutionLink": "#" + }, + { + "problemName": "776. Split BST", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/split-bst", + "solutionLink": "#" + }, + { + "problemName": "777. Swap Adjacent in LR String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/swap-adjacent-in-lr-string", + "solutionLink": "#" + }, + { + "problemName": "778. Swim in Rising Water", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/swim-in-rising-water", + "solutionLink": "#" + }, + { + "problemName": "779. K-th Symbol in Grammar", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/k-th-symbol-in-grammar", + "solutionLink": "#" + }, + { + "problemName": "780. Reaching Points", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/reaching-points", + "solutionLink": "#" + }, + { + "problemName": "781. Rabbits in Forest", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/rabbits-in-forest", + "solutionLink": "#" + }, + { + "problemName": "782. Transform to Chessboard", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/transform-to-chessboard", + "solutionLink": "#" + }, + { + "problemName": "783. Minimum Distance Between BST Nodes", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-distance-between-bst-nodes", + "solutionLink": "#" + }, + { + "problemName": "784. Letter Case Permutation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/letter-case-permutation", + "solutionLink": "#" + }, + { + "problemName": "785. Is Graph Bipartite?", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/is-graph-bipartite", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/is-graph-bipartite" + }, + { + "problemName": "786. K-th Smallest Prime Fraction", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/k-th-smallest-prime-fraction", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/k-th-smallest-prime-fraction" + }, + { + "problemName": "787. Cheapest Flights Within K Stops", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/cheapest-flights-within-k-stops", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/cheapest-flights-within-k-stops" + }, + { + "problemName": "788. Rotated Digits", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/rotated-digits", + "solutionLink": "#" + }, + { + "problemName": "789. Escape The Ghosts", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/escape-the-ghosts", + "solutionLink": "#" + }, + { + "problemName": "790. Domino and Tromino Tiling", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/domino-and-tromino-tiling", + "solutionLink": "#" + }, + { + "problemName": "791. Custom Sort String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/custom-sort-string", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/custom-sort-string" + }, + { + "problemName": "792. Number of Matching Subsequences", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-matching-subsequences", + "solutionLink": "#" + }, + { + "problemName": "793. Preimage Size of Factorial Zeroes Function", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function", + "solutionLink": "#" + }, + { + "problemName": "794. Valid Tic-Tac-Toe State", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/valid-tic-tac-toe-state", + "solutionLink": "#" + }, + { + "problemName": "795. Number of Subarrays with Bounded Maximum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum", + "solutionLink": "#" + }, + { + "problemName": "796. Rotate String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/rotate-string", + "solutionLink": "/dsa-solutions/lc-solutions/0700-0799/rotate-string" + }, + { + "problemName": "797. All Paths From Source to Target", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/all-paths-from-source-to-target", + "solutionLink": "#" + }, + { + "problemName": "798. Smallest Rotation with Highest Score", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/smallest-rotation-with-highest-score", + "solutionLink": "#" + }, + { + "problemName": "799. Champagne Tower", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/champagne-tower", + "solutionLink": "#" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/leetcode-problems/0800-0899.md b/problems/leetcode-problems/0800-0899.md new file mode 100644 index 0000000..02998f5 --- /dev/null +++ b/problems/leetcode-problems/0800-0899.md @@ -0,0 +1,621 @@ +--- +id: 0800-0899 +title: LeetCode Problems 800 - 899 +sidebar_label: 0800 - 0899 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 800 - 899 + - DSA problems +--- + +export const problems = [ + { + "problemName": "800. Similar RGB Color", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/similar-rgb-color", + "solutionLink": "#" + }, + { + "problemName": "801. Minimum Swaps To Make Sequences Increasing", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing", + "solutionLink": "#" + }, + { + "problemName": "802. Find Eventual Safe States", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-eventual-safe-states", + "solutionLink": "#" + }, + { + "problemName": "803. Bricks Falling When Hit", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/bricks-falling-when-hit", + "solutionLink": "#" + }, + { + "problemName": "804. Unique Morse Code Words", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/unique-morse-code-words", + "solutionLink": "#" + }, + { + "problemName": "805. Split Array With Same Average", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/split-array-with-same-average", + "solutionLink": "#" + }, + { + "problemName": "806. Number of Lines To Write String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-lines-to-write-string", + "solutionLink": "#" + }, + { + "problemName": "807. Max Increase to Keep City Skyline", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/max-increase-to-keep-city-skyline", + "solutionLink": "#" + }, + { + "problemName": "808. Soup Servings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/soup-servings", + "solutionLink": "#" + }, + { + "problemName": "809. Expressive Words", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/expressive-words", + "solutionLink": "#" + }, + { + "problemName": "810. Chalkboard XOR Game", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/chalkboard-xor-game", + "solutionLink": "#" + }, + { + "problemName": "811. Subdomain Visit Count", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/subdomain-visit-count", + "solutionLink": "#" + }, + { + "problemName": "812. Largest Triangle Area", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/largest-triangle-area", + "solutionLink": "#" + }, + { + "problemName": "813. Largest Sum of Averages", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/largest-sum-of-averages", + "solutionLink": "#" + }, + { + "problemName": "814. Binary Tree Pruning", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/binary-tree-pruning", + "solutionLink": "#" + }, + { + "problemName": "815. Bus Routes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/bus-routes", + "solutionLink": "#" + }, + { + "problemName": "816. Ambiguous Coordinates", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/ambiguous-coordinates", + "solutionLink": "#" + }, + { + "problemName": "817. Linked List Components", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/linked-list-components", + "solutionLink": "#" + }, + { + "problemName": "818. Race Car", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/race-car", + "solutionLink": "#" + }, + { + "problemName": "819. Most Common Word", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/most-common-word", + "solutionLink": "#" + }, + { + "problemName": "820. Short Encoding of Words", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/short-encoding-of-words", + "solutionLink": "#" + }, + { + "problemName": "821. Shortest Distance to a Character", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/shortest-distance-to-a-character", + "solutionLink": "#" + }, + { + "problemName": "822. Card Flipping Game", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/card-flipping-game", + "solutionLink": "#" + }, + { + "problemName": "823. Binary Trees With Factors", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/binary-trees-with-factors", + "solutionLink": "#" + }, + { + "problemName": "824. Goat Latin", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/goat-latin", + "solutionLink": "#" + }, + { + "problemName": "825. Friends Of Appropriate Ages", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/friends-of-appropriate-ages", + "solutionLink": "#" + }, + { + "problemName": "826. Most Profit Assigning Work", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/most-profit-assigning-work", + "solutionLink": "#" + }, + { + "problemName": "827. Making A Large Island", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/making-a-large-island", + "solutionLink": "#" + }, + { + "problemName": "828. Count Unique Characters of All Substrings of a Given String", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string", + "solutionLink": "#" + }, + { + "problemName": "829. Consecutive Numbers Sum", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/consecutive-numbers-sum", + "solutionLink": "#" + }, + { + "problemName": "830. Positions of Large Groups", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/positions-of-large-groups", + "solutionLink": "#" + }, + { + "problemName": "831. Masking Personal Information", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/masking-personal-information", + "solutionLink": "#" + }, + { + "problemName": "832. Flipping an Image", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/flipping-an-image", + "solutionLink": "#" + }, + { + "problemName": "833. Find And Replace in String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-and-replace-in-string", + "solutionLink": "#" + }, + { + "problemName": "834. Sum of Distances in Tree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sum-of-distances-in-tree", + "solutionLink": "#" + }, + { + "problemName": "835. Image Overlap", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/image-overlap", + "solutionLink": "#" + }, + { + "problemName": "836. Rectangle Overlap", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/rectangle-overlap", + "solutionLink": "#" + }, + { + "problemName": "837. New 21 Game", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/new-21-game", + "solutionLink": "#" + }, + { + "problemName": "838. Push Dominoes", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/push-dominoes", + "solutionLink": "#" + }, + { + "problemName": "839. Similar String Groups", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/similar-string-groups", + "solutionLink": "#" + }, + { + "problemName": "840. Magic Squares In Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/magic-squares-in-grid", + "solutionLink": "#" + }, + { + "problemName": "841. Keys and Rooms", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/keys-and-rooms", + "solutionLink": "#" + }, + { + "problemName": "842. Split Array into Fibonacci Sequence", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/split-array-into-fibonacci-sequence", + "solutionLink": "#" + }, + { + "problemName": "843. Guess the Word", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/guess-the-word", + "solutionLink": "#" + }, + { + "problemName": "844. Backspace String Compare", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/backspace-string-compare", + "solutionLink": "#" + }, + { + "problemName": "845. Longest Mountain in Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-mountain-in-array", + "solutionLink": "#" + }, + { + "problemName": "846. Hand of Straights", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/hand-of-straights", + "solutionLink": "#" + }, + { + "problemName": "847. Shortest Path Visiting All Nodes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/shortest-path-visiting-all-nodes", + "solutionLink": "#" + }, + { + "problemName": "848. Shifting Letters", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shifting-letters", + "solutionLink": "#" + }, + { + "problemName": "849. Maximize Distance to Closest Person", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximize-distance-to-closest-person", + "solutionLink": "#" + }, + { + "problemName": "850. Rectangle Area II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/rectangle-area-ii", + "solutionLink": "#" + },{ + "problemName": "851. Loud and Rich", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/loud-and-rich", + "solutionLink": "#" + }, + { + "problemName": "852. Peak Index in a Mountain Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/peak-index-in-a-mountain-array", + "solutionLink": "#" + }, + { + "problemName": "853. Car Fleet", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/car-fleet", + "solutionLink": "#" + }, + { + "problemName": "854. K-Similar Strings", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/k-similar-strings", + "solutionLink": "#" + }, + { + "problemName": "855. Exam Room", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/exam-room", + "solutionLink": "#" + }, + { + "problemName": "856. Score of Parentheses", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/score-of-parentheses", + "solutionLink": "#" + }, + { + "problemName": "857. Minimum Cost to Hire K Workers", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-hire-k-workers", + "solutionLink": "#" + }, + { + "problemName": "858. Mirror Reflection", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/mirror-reflection", + "solutionLink": "#" + }, + { + "problemName": "859. Buddy Strings", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/buddy-strings", + "solutionLink": "#" + }, + { + "problemName": "860. Lemonade Change", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/lemonade-change", + "solutionLink": "#" + }, + { + "problemName": "861. Score After Flipping Matrix", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/score-after-flipping-matrix", + "solutionLink": "#" + }, + { + "problemName": "862. Shortest Subarray with Sum at Least K", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k", + "solutionLink": "#" + }, + { + "problemName": "863. All Nodes Distance K in Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "864. Shortest Path to Get All Keys", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/shortest-path-to-get-all-keys", + "solutionLink": "#" + }, + { + "problemName": "865. Smallest Subtree with all the Deepest Nodes", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes", + "solutionLink": "#" + }, + { + "problemName": "866. Prime Palindrome", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/prime-palindrome", + "solutionLink": "#" + }, + { + "problemName": "867. Transpose Matrix", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/transpose-matrix", + "solutionLink": "#" + }, + { + "problemName": "868. Binary Gap", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/binary-gap", + "solutionLink": "#" + }, + { + "problemName": "869. Reordered Power of 2", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reordered-power-of-2", + "solutionLink": "#" + }, + { + "problemName": "870. Advantage Shuffle", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/advantage-shuffle", + "solutionLink": "#" + }, + { + "problemName": "871. Minimum Number of Refueling Stops", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-refueling-stops", + "solutionLink": "#" + }, + { + "problemName": "872. Leaf-Similar Trees", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/leaf-similar-trees", + "solutionLink": "#" + }, + { + "problemName": "873. Length of Longest Fibonacci Subsequence", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/length-of-longest-fibonacci-subsequence", + "solutionLink": "#" + }, + { + "problemName": "874. Walking Robot Simulation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/walking-robot-simulation", + "solutionLink": "#" + }, + { + "problemName": "875. Koko Eating Bananas", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/koko-eating-bananas", + "solutionLink": "#" + }, + { + "problemName": "876. Middle of the Linked List", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/middle-of-the-linked-list", + "solutionLink": "#" + }, + { + "problemName": "877. Stone Game", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/stone-game", + "solutionLink": "#" + }, + { + "problemName": "878. Nth Magical Number", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/nth-magical-number", + "solutionLink": "#" + }, + { + "problemName": "879. Profitable Schemes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/profitable-schemes", + "solutionLink": "#" + }, + { + "problemName": "880. Decoded String at Index", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/decoded-string-at-index", + "solutionLink": "#" + }, + { + "problemName": "881. Boats to Save People", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/boats-to-save-people", + "solutionLink": "#" + }, + { + "problemName": "882. Reachable Nodes In Subdivided Graph", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/reachable-nodes-in-subdivided-graph", + "solutionLink": "#" + }, + { + "problemName": "883. Projection Area of 3D Shapes", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/projection-area-of-3d-shapes", + "solutionLink": "#" + }, + { + "problemName": "884. Uncommon Words from Two Sentences", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/uncommon-words-from-two-sentences", + "solutionLink": "#" + }, + { + "problemName": "885. Spiral Matrix III", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/spiral-matrix-iii", + "solutionLink": "#" + }, + { + "problemName": "886. Possible Bipartition", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/possible-bipartition", + "solutionLink": "#" + }, + { + "problemName": "887. Super Egg Drop", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/super-egg-drop", + "solutionLink": "#" + }, + { + "problemName": "888. Fair Candy Swap", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/fair-candy-swap", + "solutionLink": "#" + }, + { + "problemName": "889. Construct Binary Tree from Preorder and Postorder Traversal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal", + "solutionLink": "#" + }, + { + "problemName": "890. Find and Replace Pattern", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-and-replace-pattern", + "solutionLink": "#" + }, + { + "problemName": "891. Sum of Subsequence Widths", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sum-of-subsequence-widths", + "solutionLink": "#" + }, + { + "problemName": "892. Surface Area of 3D Shapes", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/surface-area-of-3d-shapes", + "solutionLink": "#" + }, + { + "problemName": "893. Groups of Special-Equivalent Strings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/groups-of-special-equivalent-strings", + "solutionLink": "#" + }, + { + "problemName": "894. All Possible Full Binary Trees", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/all-possible-full-binary-trees", + "solutionLink": "#" + }, + { + "problemName": "895. Maximum Frequency Stack", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-frequency-stack", + "solutionLink": "#" + }, + { + "problemName": "896. Monotonic Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/monotonic-array", + "solutionLink": "#" + }, + { + "problemName": "897. Increasing Order Search Tree", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/increasing-order-search-tree", + "solutionLink": "#" + }, + { + "problemName": "898. Bitwise ORs of Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/bitwise-ors-of-subarrays", + "solutionLink": "#" + }, + { + "problemName": "899. Orderly Queue", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/orderly-queue", + "solutionLink": "#" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/0900-0999.md b/problems/leetcode-problems/0900-0999.md new file mode 100644 index 0000000..12c2ea0 --- /dev/null +++ b/problems/leetcode-problems/0900-0999.md @@ -0,0 +1,623 @@ +--- +id: 0900-0999 +title: LeetCode Problems 900 - 999 +sidebar_label: 0900 - 0999 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 900 - 999 + - DSA problems +--- + + +export const problems = [ + { + problemName: "900. RLE Iterator", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/rle-iterator", + solutionLink: "#" + }, + { + problemName: "901. Online Stock Span", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/online-stock-span", + solutionLink: "#" + }, + { + problemName: "902. Numbers At Most N Given Digit Set", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/numbers-at-most-n-given-digit-set", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/numbers-at-most-n-given-digit-set" + }, + { + problemName: "903. Valid Permutations for DI Sequence", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/valid-permutations-for-di-sequence", + solutionLink: "#" + }, + { + problemName: "904. Fruit Into Baskets", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/fruit-into-baskets", + solutionLink: "#" + }, + { + problemName: "905. Sort Array By Parity", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/sort-array-by-parity", + solutionLink: "#" + }, + { + problemName: "906. Super Palindromes", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/super-palindromes", + solutionLink: "#" + }, + { + problemName: "907. Sum of Subarray Minimums", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/sum-of-subarray-minimums", + solutionLink: "#" + }, + { + problemName: "908. Smallest Range I", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/smallest-range-i", + solutionLink: "#" + }, + { + problemName: "909. Snakes and Ladders", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/snakes-and-ladders", + solutionLink: "#" + }, + { + problemName: "910. Smallest Range II", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/smallest-range-ii", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/smallest-range-ii" + }, + { + problemName: "911. Online Election", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/online-election", + solutionLink: "#" + }, + { + problemName: "912. Sort an Array", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/sort-an-array", + solutionLink: "#" + }, + { + problemName: "913. Cat and Mouse", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/cat-and-mouse", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/cat-and-mouse" + }, + { + problemName: "914. X of a Kind in a Deck of Cards", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/x-of-a-kind-in-a-deck-of-cards" + }, + { + problemName: "915. Partition Array into Disjoint Intervals", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/partition-array-into-disjoint-intervals", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/partition-array-into-disjoint-intervals" + }, + { + problemName: "916. Word Subsets", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/word-subsets", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/word-subsets" + }, + { + problemName: "917. Reverse Only Letters", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/reverse-only-letters", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/reverse-only-letters" + }, + { + problemName: "918. Maximum Sum Circular Subarray", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/maximum-sum-circular-subarray", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/maximum-sum-circular-subarray" + }, + { + problemName: "919. Complete Binary Tree Inserter", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/complete-binary-tree-inserter", + solutionLink: "#" + }, + { + problemName: "920. Number of Music Playlists", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/number-of-music-playlists", + solutionLink: "#" + }, + { + problemName: "921. Minimum Add to Make Parentheses Valid", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/minimum-add-to-make-parentheses-valid", + solutionLink: "#" + }, + { + problemName: "922. Sort Array By Parity II", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/sort-array-by-parity-ii", + solutionLink: "#" + }, + { + problemName: "923. 3Sum With Multiplicity", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/3sum-with-multiplicity", + solutionLink: "#" + }, + { + problemName: "924. Minimize Malware Spread", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/minimize-malware-spread", + solutionLink: "#" + }, + { + problemName: "925. Long Pressed Name", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/long-pressed-name", + solutionLink: "#" + }, + { + problemName: "926. Flip String to Monotone Increasing", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/flip-string-to-monotone-increasing", + solutionLink: "#" + }, + { + problemName: "927. Three Equal Parts", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/three-equal-parts", + solutionLink: "#" + }, + { + problemName: "928. Minimize Malware Spread II", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/minimize-malware-spread-ii", + solutionLink: "#" + }, + { + problemName: "929. Unique Email Addresses", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/unique-email-addresses", + solutionLink: "#" + }, + { + problemName: "930. Binary Subarrays With Sum", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/binary-subarrays-with-sum", + solutionLink: "#" + }, + { + problemName: "931. Minimum Falling Path Sum", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/minimum-falling-path-sum", + solutionLink: "#" + }, + { + problemName: "932. Beautiful Array", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/beautiful-array", + solutionLink: "#" + }, + { + problemName: "933. Number of Recent Calls", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/number-of-recent-calls", + solutionLink: "#" + }, + { + problemName: "934. Shortest Bridge", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/shortest-bridge", + solutionLink: "#" + }, + { + problemName: "935. Knight Dialer", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/knight-dialer", + solutionLink: "#" + }, + { + problemName: "936. Stamping The Sequence", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/stamping-the-sequence", + solutionLink: "#" + }, + { + problemName: "937. Reorder Data in Log Files", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/reorder-data-in-log-files", + solutionLink: "#" + }, + { + problemName: "938. Range Sum of BST", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/range-sum-of-bst", + solutionLink: "#" + }, + { + problemName: "939. Minimum Area Rectangle", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/minimum-area-rectangle", + solutionLink: "#" + }, + { + problemName: "940. Distinct Subsequences II", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/distinct-subsequences-ii", + solutionLink: "#" + }, + { + problemName: "941. Valid Mountain Array", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/valid-mountain-array", + solutionLink: "#" + }, + { + problemName: "942. DI String Match", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/di-string-match", + solutionLink: "#" + }, + { + problemName: "943. Find the Shortest Superstring", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/find-the-shortest-superstring", + solutionLink: "#" + }, + { + problemName: "944. Delete Columns to Make Sorted", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/delete-columns-to-make-sorted", + solutionLink: "#" + }, + { + problemName: "945. Minimum Increment to Make Array Unique", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/minimum-increment-to-make-array-unique", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/minimum-increment-to-make-array-unique" + }, + { + problemName: "946. Validate Stack Sequences", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/validate-stack-sequences", + solutionLink: "#" + }, + { + problemName: "947. Most Stones Removed with Same Row or Column", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/most-stones-removed-with-same-row-or-column", + solutionLink: "#" + }, + { + problemName: "948. Bag of Tokens", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/bag-of-tokens", + solutionLink: "#" + }, + { + problemName: "949. Largest Time for Given Digits", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/largest-time-for-given-digits", + solutionLink: "#" + }, + { + problemName: "950. Reveal Cards In Increasing Order", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/reveal-cards-in-increasing-order", + solutionLink: "#" + }, + { + problemName: "951. Flip Equivalent Binary Trees", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/flip-equivalent-binary-trees", + solutionLink: "#" + }, + { + problemName: "952. Largest Component Size by Common Factor", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/largest-component-size-by-common-factor", + solutionLink: "#" + }, + { + problemName: "953. Verifying an Alien Dictionary", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/verifying-an-alien-dictionary", + solutionLink: "#" + }, + { + problemName: "954. Array of Doubled Pairs", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/array-of-doubled-pairs", + solutionLink: "#" + }, + { + problemName: "955. Delete Columns to Make Sorted II", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/delete-columns-to-make-sorted-ii", + solutionLink: "#" + }, + { + problemName: "956. Tallest Billboard", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/tallest-billboard", + solutionLink: "#" + }, + { + problemName: "957. Prison Cells After N Days", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/prison-cells-after-n-days", + solutionLink: "#" + }, + { + problemName: "958. Check Completeness of a Binary Tree", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/check-completeness-of-a-binary-tree", + solutionLink: "#" + }, + { + problemName: "959. Regions Cut By Slashes", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/regions-cut-by-slashes", + solutionLink: "#" + }, + { + problemName: "960. Delete Columns to Make Sorted III", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/delete-columns-to-make-sorted-iii", + solutionLink: "#" + }, + { + problemName: "961. N-Repeated Element in Size 2N Array", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/n-repeated-element-in-size-2n-array", + solutionLink: "#" + }, + { + problemName: "962. Maximum Width Ramp", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/maximum-width-ramp", + solutionLink: "#" + }, + { + problemName: "963. Minimum Area Rectangle II", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/minimum-area-rectangle-ii", + solutionLink: "#" + }, + { + problemName: "964. Least Operators to Express Number", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/least-operators-to-express-number", + solutionLink: "#" + }, + { + problemName: "965. Univalued Binary Tree", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/univalued-binary-tree", + solutionLink: "#" + }, + { + problemName: "966. Vowel Spellchecker", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/vowel-spellchecker", + solutionLink: "#" + }, + { + problemName: "967. Numbers With Same Consecutive Differences", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/numbers-with-same-consecutive-differences", + solutionLink: "#" + }, + { + problemName: "968. Binary Tree Cameras", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/binary-tree-cameras", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/binary-tree-cameras" + }, + { + problemName: "969. Pancake Sorting", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/pancake-sorting", + solutionLink: "#" + }, + { + problemName: "970. Powerful Integers", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/powerful-integers", + solutionLink: "#" + }, + { + problemName: "971. Flip Binary Tree To Match Preorder Traversal", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal", + solutionLink: "#" + }, + { + problemName: "972. Equal Rational Numbers", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/equal-rational-numbers", + solutionLink: "#" + }, + { + problemName: "973. K Closest Points to Origin", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/k-closest-points-to-origin", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/k-closest-points-to-origin" + }, + { + problemName: "974. Subarray Sums Divisible by K", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/subarray-sums-divisible-by-k", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/subarray-sums-divisible-by-k" + }, + { + problemName: "975. Odd Even Jump", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/odd-even-jump", + solutionLink: "#" + }, + { + problemName: "976. Largest Perimeter Triangle", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/largest-perimeter-triangle", + solutionLink: "#" + }, + { + problemName: "977. Squares of a Sorted Array", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/squares-of-a-sorted-array", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/squares-of-a-sorted-array" + }, + { + problemName: "978. Longest Turbulent Subarray", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/longest-turbulent-subarray", + solutionLink: "#" + }, + { + problemName: "979. Distribute Coins in Binary Tree", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/distribute-coins-in-binary-tree", + solutionLink: "#" + }, + { + problemName: "980. Unique Paths III", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/unique-paths-iii", + solutionLink: "#" + }, + { + problemName: "981. Time Based Key-Value Store", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/time-based-key-value-store", + solutionLink: "#" + }, + { + problemName: "982. Triples with Bitwise AND Equal To Zero", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero", + solutionLink: "#" + }, + { + problemName: "983. Minimum Cost For Tickets", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/minimum-cost-for-tickets", + solutionLink: "#" + }, + { + problemName: "984. String Without AAA or BBB", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/string-without-aaa-or-bbb", + solutionLink: "#" + }, + { + problemName: "985. Sum of Even Numbers After Queries", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/sum-of-even-numbers-after-queries", + solutionLink: "#" + }, + { + problemName: "986. Interval List Intersections", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/interval-list-intersections", + solutionLink: "#" + }, + { + problemName: "987. Vertical Order Traversal of a Binary Tree", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/vertical-order-traversal-binary-tree" + }, + { + problemName: "988. Smallest String Starting From Leaf", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/smallest-string-starting-from-leaf", + solutionLink: "#" + }, + { + problemName: "989. Add to Array-Form of Integer", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/add-to-array-form-of-integer", + solutionLink: "#" + }, + { + problemName: "990. Satisfiability of Equality Equations", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/satisfiability-of-equality-equations", + solutionLink: "#" + }, + { + problemName: "991. Broken Calculator", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/broken-calculator", + solutionLink: "#" + }, + { + problemName: "992. Subarrays with K Different Integers", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/subarrays-with-k-different-integers", + solutionLink: "#" + }, + { + problemName: "993. Cousins in Binary Tree", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/cousins-in-binary-tree", + solutionLink: "#" + }, + { + problemName: "994. Rotting Oranges", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/rotting-oranges", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/rotting-oranges" + }, + { + problemName: "995. Minimum Number of K Consecutive Bit Flips", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/minimum-number-of-k-consecutive-bit-flips", + solutionLink: "#" + }, + { + problemName: "996. Number of Squareful Arrays", + difficulty: "Hard", + leetCodeLink: "https://leetcode.com/problems/number-of-squareful-arrays", + solutionLink: "#" + }, + { + problemName: "997. Find the Town Judge", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/find-the-town-judge", + solutionLink: "/dsa-solutions/lc-solutions/0900-0999/find-the-town-judge" + }, + { + problemName: "998. Maximum Binary Tree II", + difficulty: "Medium", + leetCodeLink: "https://leetcode.com/problems/maximum-binary-tree-ii", + solutionLink: "#" + }, + { + problemName: "999. Available Captures for Rook", + difficulty: "Easy", + leetCodeLink: "https://leetcode.com/problems/available-captures-for-rook", + solutionLink: "#" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/leetcode-problems/1000-1099.md b/problems/leetcode-problems/1000-1099.md new file mode 100644 index 0000000..d371e2e --- /dev/null +++ b/problems/leetcode-problems/1000-1099.md @@ -0,0 +1,622 @@ +--- +id: 1000-1099 +title: LeetCode Problems 1000 - 1099 +sidebar_label: 1000 - 1099 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 1000 - 1099 + - DSA problems +--- + +export const problems = [ + { + "problemName": "1000. Minimum Cost to Merge Stones", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-merge-stones", + "solutionLink": "#" + }, + { + "problemName": "1001. Grid Illumination", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/grid-illumination", + "solutionLink": "#" + }, + { + "problemName": "1002. Find Common Characters", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-common-characters", + "solutionLink": "#" + }, + { + "problemName": "1003. Check If Word Is Valid After Substitutions", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-word-is-valid-after-substitutions", + "solutionLink": "#" + }, + { + "problemName": "1004. Max Consecutive Ones III", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/max-consecutive-ones-iii", + "solutionLink": "#" + }, + { + "problemName": "1005. Maximize Sum Of Array After K Negations", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximize-sum-of-array-after-k-negations", + "solutionLink": "#" + }, + { + "problemName": "1006. Clumsy Factorial", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/clumsy-factorial", + "solutionLink": "#" + }, + { + "problemName": "1007. Minimum Domino Rotations For Equal Row", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-domino-rotations-for-equal-row", + "solutionLink": "#" + }, + { + "problemName": "1008. Construct Binary Search Tree from Preorder Traversal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal", + "solutionLink": "#" + }, + { + "problemName": "1009. Complement of Base 10 Integer", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/complement-of-base-10-integer", + "solutionLink": "#" + }, + { + "problemName": "1010. Pairs of Songs With Total Durations Divisible by 60", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60", + "solutionLink": "#" + }, + { + "problemName": "1011. Capacity To Ship Packages Within D Days", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/capacity-to-ship-packages-within-d-days", + "solutionLink": "#" + }, + { + "problemName": "1012. Numbers With Repeated Digits", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/numbers-with-repeated-digits", + "solutionLink": "#" + }, + { + "problemName": "1013. Partition Array Into Three Parts With Equal Sum", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum", + "solutionLink": "#" + }, + { + "problemName": "1014. Best Sightseeing Pair", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/best-sightseeing-pair", + "solutionLink": "#" + }, + { + "problemName": "1015. Smallest Integer Divisible by K", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/smallest-integer-divisible-by-k", + "solutionLink": "#" + }, + { + "problemName": "1016. Binary String With Substrings Representing 1 To N", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n", + "solutionLink": "#" + }, + { + "problemName": "1017. Convert to Base -2", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/convert-to-base-2", + "solutionLink": "#" + }, + { + "problemName": "1018. Binary Prefix Divisible By 5", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/binary-prefix-divisible-by-5", + "solutionLink": "#" + }, + { + "problemName": "1019. Next Greater Node In Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/next-greater-node-in-linked-list", + "solutionLink": "#" + }, + { + "problemName": "1020. Number of Enclaves", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-enclaves", + "solutionLink": "#" + }, + { + "problemName": "1021. Remove Outermost Parentheses", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/remove-outermost-parentheses", + "solutionLink": "#" + }, + { + "problemName": "1022. Sum of Root To Leaf Binary Numbers", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers", + "solutionLink": "#" + }, + { + "problemName": "1023. Camelcase Matching", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/camelcase-matching", + "solutionLink": "#" + }, + { + "problemName": "1024. Video Stitching", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/video-stitching", + "solutionLink": "#" + }, + { + "problemName": "1025. Divisor Game", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/divisor-game", + "solutionLink": "#" + }, + { + "problemName": "1026. Maximum Difference Between Node and Ancestor", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-difference-between-node-and-ancestor", + "solutionLink": "#" + }, + { + "problemName": "1027. Longest Arithmetic Subsequence", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-arithmetic-subsequence", + "solutionLink": "#" + }, + { + "problemName": "1028. Recover a Tree From Preorder Traversal", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/recover-a-tree-from-preorder-traversal", + "solutionLink": "#" + }, + { + "problemName": "1029. Two City Scheduling", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/two-city-scheduling", + "solutionLink": "#" + }, + { + "problemName": "1030. Matrix Cells in Distance Order", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/matrix-cells-in-distance-order", + "solutionLink": "#" + }, + { + "problemName": "1031. Maximum Sum of Two Non-Overlapping Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays", + "solutionLink": "#" + }, + { + "problemName": "1032. Stream of Characters", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/stream-of-characters", + "solutionLink": "#" + }, + { + "problemName": "1033. Moving Stones Until Consecutive", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/moving-stones-until-consecutive", + "solutionLink": "#" + }, + { + "problemName": "1034. Coloring A Border", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/coloring-a-border", + "solutionLink": "#" + }, + { + "problemName": "1035. Uncrossed Lines", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/uncrossed-lines", + "solutionLink": "#" + }, + { + "problemName": "1036. Escape a Large Maze", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/escape-a-large-maze", + "solutionLink": "#" + }, + { + "problemName": "1037. Valid Boomerang", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/valid-boomerang", + "solutionLink": "#" + }, + { + "problemName": "1038. Binary Search Tree to Greater Sum Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree", + "solutionLink": "/dsa-solutions/lc-solutions/1000-1099/binary-search-tree-to-greater-sum-tree" + }, + { + "problemName": "1039. Minimum Score Triangulation of Polygon", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-score-triangulation-of-polygon", + "solutionLink": "#" + }, + { + "problemName": "1040. Moving Stones Until Consecutive II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/moving-stones-until-consecutive-ii", + "solutionLink": "#" + }, + { + "problemName": "1041. Robot Bounded In Circle", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/robot-bounded-in-circle", + "solutionLink": "#" + }, + { + "problemName": "1042. Flower Planting With No Adjacent", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/flower-planting-with-no-adjacent", + "solutionLink": "#" + }, + { + "problemName": "1043. Partition Array for Maximum Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/partition-array-for-maximum-sum", + "solutionLink": "#" + }, + { + "problemName": "1044. Longest Duplicate Substring", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/longest-duplicate-substring", + "solutionLink": "#" + }, + { + "problemName": "1045. Customers Who Bought All Products", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/customers-who-bought-all-products", + "solutionLink": "#" + }, + { + "problemName": "1046. Last Stone Weight", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/last-stone-weight", + "solutionLink": "#" + }, + { + "problemName": "1047. Remove All Adjacent Duplicates In String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string", + "solutionLink": "#" + }, + { + "problemName": "1048. Longest String Chain", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-string-chain", + "solutionLink": "#" + }, + { + "problemName": "1049. Last Stone Weight II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/last-stone-weight-ii", + "solutionLink": "#" + }, + { + "problemName": "1050. Actors and Directors Who Cooperated At Least Three Times", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/actors-and-directors-who-cooperated-at-least-three-times", + "solutionLink": "#" + }, + { + "problemName": "1051. Height Checker", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/height-checker", + "solutionLink": "#" + }, + { + "problemName": "1052. Grumpy Bookstore Owner", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/grumpy-bookstore-owner", + "solutionLink": "#" + }, + { + "problemName": "1053. Previous Permutation With One Swap", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/previous-permutation-with-one-swap", + "solutionLink": "#" + }, + { + "problemName": "1054. Distant Barcodes", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/distant-barcodes", + "solutionLink": "#" + }, + { + "problemName": "1055. Shortest Way to Form String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shortest-way-to-form-string", + "solutionLink": "#" + }, + { + "problemName": "1056. Confusing Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/confusing-number", + "solutionLink": "#" + }, + { + "problemName": "1057. Campus Bikes", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/campus-bikes", + "solutionLink": "#" + }, + { + "problemName": "1058. Minimize Rounding Error to Meet Target", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimize-rounding-error-to-meet-target", + "solutionLink": "#" + }, + { + "problemName": "1059. All Paths from Source Lead to Destination", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/all-paths-from-source-lead-to-destination", + "solutionLink": "#" + }, + { + "problemName": "1060. Missing Element in Sorted Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/missing-element-in-sorted-array", + "solutionLink": "#" + }, + { + "problemName": "1061. Lexicographically Smallest Equivalent String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/lexicographically-smallest-equivalent-string", + "solutionLink": "#" + }, + { + "problemName": "1062. Longest Repeating Substring", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-repeating-substring", + "solutionLink": "#" + }, + { + "problemName": "1063. Number of Valid Subarrays", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-valid-subarrays", + "solutionLink": "#" + }, + { + "problemName": "1064. Fixed Point", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/fixed-point", + "solutionLink": "#" + }, + { + "problemName": "1065. Index Pairs of a String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/index-pairs-of-a-string", + "solutionLink": "#" + }, + { + "problemName": "1066. Campus Bikes II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/campus-bikes-ii", + "solutionLink": "#" + }, + { + "problemName": "1067. Digit Count in Range", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/digit-count-in-range", + "solutionLink": "#" + }, + { + "problemName": "1068. Product Sales Analysis I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/product-sales-analysis-i", + "solutionLink": "#" + }, + { + "problemName": "1069. Product Sales Analysis II", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/product-sales-analysis-ii", + "solutionLink": "#" + }, + { + "problemName": "1070. Product Sales Analysis III", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/product-sales-analysis-iii", + "solutionLink": "#" + }, + { + "problemName": "1071. Greatest Common Divisor of Strings", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/greatest-common-divisor-of-strings", + "solutionLink": "#" + }, + { + "problemName": "1072. Flip Columns For Maximum Number of Equal Rows", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows", + "solutionLink": "#" + }, + { + "problemName": "1073. Adding Two Negabinary Numbers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/adding-two-negabinary-numbers", + "solutionLink": "#" + }, + { + "problemName": "1074. Number of Submatrices That Sum to Target", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-submatrices-that-sum-to-target", + "solutionLink": "#" + }, + { + "problemName": "1075. Project Employees I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/project-employees-i", + "solutionLink": "#" + }, + { + "problemName": "1076. Project Employees II", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/project-employees-ii", + "solutionLink": "#" + }, + { + "problemName": "1077. Project Employees III", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/project-employees-iii", + "solutionLink": "#" + }, + { + "problemName": "1078. Occurrences After Bigram", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/occurrences-after-bigram", + "solutionLink": "#" + }, + { + "problemName": "1079. Letter Tile Possibilities", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/letter-tile-possibilities", + "solutionLink": "#" + }, + { + "problemName": "1080. Insufficient Nodes in Root to Leaf Paths", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths", + "solutionLink": "#" + }, + { + "problemName": "1081. Smallest Subsequence of Distinct Characters", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/smallest-subsequence-of-distinct-characters", + "solutionLink": "#" + }, + { + "problemName": "1082. Sales Analysis I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sales-analysis-i", + "solutionLink": "#" + }, + { + "problemName": "1083. Sales Analysis II", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sales-analysis-ii", + "solutionLink": "#" + }, + { + "problemName": "1084. Sales Analysis III", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sales-analysis-iii", + "solutionLink": "#" + }, + { + "problemName": "1085. Sum of Digits in the Minimum Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sum-of-digits-in-the-minimum-number", + "solutionLink": "#" + }, + { + "problemName": "1086. High Five", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/high-five", + "solutionLink": "#" + }, + { + "problemName": "1087. Brace Expansion", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/brace-expansion", + "solutionLink": "#" + }, + { + "problemName": "1088. Confusing Number II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/confusing-number-ii", + "solutionLink": "#" + }, + { + "problemName": "1089. Duplicate Zeros", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/duplicate-zeros", + "solutionLink": "#" + }, + { + "problemName": "1090. Largest Values From Labels", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/largest-values-from-labels", + "solutionLink": "#" + }, + { + "problemName": "1091. Shortest Path in Binary Matrix", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shortest-path-in-binary-matrix", + "solutionLink": "#" + }, + { + "problemName": "1092. Shortest Common Supersequence", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/shortest-common-supersequence", + "solutionLink": "#" + }, + { + "problemName": "1093. Statistics from a Large Sample", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/statistics-from-a-large-sample", + "solutionLink": "#" + }, + { + "problemName": "1094. Car Pooling", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/car-pooling", + "solutionLink": "#" + }, + { + "problemName": "1095. Find in Mountain Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-in-mountain-array", + "solutionLink": "#" + }, + { + "problemName": "1096. Brace Expansion II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/brace-expansion-ii", + "solutionLink": "#" + }, + { + "problemName": "1097. Game Play Analysis V", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/game-play-analysis-v", + "solutionLink": "#" + }, + { + "problemName": "1098. Unpopular Books", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/unpopular-books", + "solutionLink": "#" + }, + { + "problemName": "1099. Two Sum Less Than K", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/two-sum-less-than-k", + "solutionLink": "#" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/1100-1199.md b/problems/leetcode-problems/1100-1199.md new file mode 100644 index 0000000..c1d704a --- /dev/null +++ b/problems/leetcode-problems/1100-1199.md @@ -0,0 +1,562 @@ +--- +id: 1100-1199 +title: LeetCode Problems 1100 - 1199 +sidebar_label: 1100 - 1199 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 1100 - 1199 + - DSA problems +--- + +export const problems = [ + { + "problemName": "1100. Find K-Length Substrings With No Repeated Characters", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-k-length-substrings-with-no-repeated-characters", + "solutionLink": "#" + }, + { + "problemName": "1111. Maximum Nesting Depth of Two Valid Parentheses Strings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings", + "solutionLink": "#" + }, + { + "problemName": "1112. Highest Grade For Each Student", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/highest-grade-for-each-student", + "solutionLink": "#" + }, + { + "problemName": "1113. Reported Posts", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/reported-posts", + "solutionLink": "#" + }, + { + "problemName": "1114. Print in Order", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/print-in-order", + "solutionLink": "#" + }, + { + "problemName": "1115. Print FooBar Alternately", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/print-foobar-alternately", + "solutionLink": "#" + }, + { + "problemName": "1116. Print Zero Even Odd", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/print-zero-even-odd", + "solutionLink": "#" + }, + { + "problemName": "1117. Building H2O", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/building-h2o", + "solutionLink": "#" + }, + { + "problemName": "1118. Number of Days in a Month", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-days-in-a-month", + "solutionLink": "#" + }, + { + "problemName": "1119. Remove Vowels from a String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/remove-vowels-from-a-string", + "solutionLink": "#" + }, + { + "problemName": "1120. Maximum Average Subtree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-average-subtree", + "solutionLink": "#" + }, + { + "problemName": "1121. Divide Array Into Increasing Sequences", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/divide-array-into-increasing-sequences", + "solutionLink": "#" + }, + { + "problemName": "1122. Relative Sort Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/relative-sort-array", + "solutionLink": "#" + }, + { + "problemName": "1123. Lowest Common Ancestor of Deepest Leaves", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves", + "solutionLink": "#" + }, + { + "problemName": "1124. Longest Well-Performing Interval", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-well-performing-interval", + "solutionLink": "#" + }, + { + "problemName": "1125. Smallest Sufficient Team", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/smallest-sufficient-team", + "solutionLink": "#" + }, + { + "problemName": "1126. Active Businesses", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/active-businesses", + "solutionLink": "#" + }, + { + "problemName": "1127. User Purchase Platform", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/user-purchase-platform", + "solutionLink": "#" + }, + { + "problemName": "1128. Number of Equivalent Domino Pairs", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-equivalent-domino-pairs", + "solutionLink": "#" + }, + { + "problemName": "1129. Shortest Path with Alternating Colors", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shortest-path-with-alternating-colors", + "solutionLink": "/dsa-solutions/lc-solutions/1100-1200/shortest-path-with-allternating-colors" + }, + { + "problemName": "1130. Minimum Cost Tree From Leaf Values", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-tree-from-leaf-values", + "solutionLink": "#" + }, + { + "problemName": "1131. Maximum of Absolute Value Expression", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-of-absolute-value-expression", + "solutionLink": "#" + }, + { + "problemName": "1132. Reported Posts", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reported-posts", + "solutionLink": "#" + }, + { + "problemName": "1133. Largest Unique Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/largest-unique-number", + "solutionLink": "#" + }, + { + "problemName": "1134. Armstrong Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/armstrong-number", + "solutionLink": "#" + }, + { + "problemName": "1135. Connecting Cities With Minimum Cost", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/connecting-cities-with-minimum-cost", + "solutionLink": "#" + }, + { + "problemName": "1136. Parallel Courses", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/parallel-courses", + "solutionLink": "#" + }, + { + "problemName": "1137. N-th Tribonacci Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/n-th-tribonacci-number", + "solutionLink": "#" + }, + { + "problemName": "1138. Alphabet Board Path", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/alphabet-board-path", + "solutionLink": "#" + }, + { + "problemName": "1139. Largest 1-Bordered Square", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/largest-1-bordered-square", + "solutionLink": "#" + }, + { + "problemName": "1140. Stone Game II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/stone-game-ii", + "solutionLink": "#" + }, + { + "problemName": "1141. User Activity for the Past 30 Days I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/user-activity-for-the-past-30-days-i", + "solutionLink": "#" + }, + { + "problemName": "1142. User Activity for the Past 30 Days II", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/user-activity-for-the-past-30-days-ii", + "solutionLink": "#" + }, + { + "problemName": "1143. Longest Common Subsequence", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-common-subsequence", + "solutionLink": "/dsa-solutions/lc-solutions/1100-1199/longest common subsequence" + }, + { + "problemName": "1144. Decrease Elements To Make Array Zigzag", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/decrease-elements-to-make-array-zigzag", + "solutionLink": "#" + }, + { + "problemName": "1145. Binary Tree Coloring Game", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/binary-tree-coloring-game", + "solutionLink": "#" + }, + { + "problemName": "1146. Snapshot Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/snapshot-array", + "solutionLink": "#" + }, + { + "problemName": "1147. Longest Chunked Palindrome Decomposition", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/longest-chunked-palindrome-decomposition", + "solutionLink": "#" + }, + { + "problemName": "1148. Article Views I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/article-views-i", + "solutionLink": "#" + }, + { + "problemName": "1149. Article Views II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/article-views-ii", + "solutionLink": "#" + }, + { + "problemName": "1150. Check If a Number Is Majority Element in a Sorted Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array", + "solutionLink": "#" + }, + { + "problemName": "1151. Minimum Swaps to Group All 1's Together", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together", + "solutionLink": "#" + }, + { + "problemName": "1152. Analyze User Website Visit Pattern", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/analyze-user-website-visit-pattern", + "solutionLink": "#" + }, + { + "problemName": "1153. String Transforms Into Another String", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/string-transforms-into-another-string", + "solutionLink": "#" + }, + { + "problemName": "1154. Day of the Year", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/day-of-the-year", + "solutionLink": "#" + }, + { + "problemName": "1155. Number of Dice Rolls With Target Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-dice-rolls-with-target-sum", + "solutionLink": "#" + }, + { + "problemName": "1156. Swap For Longest Repeated Character Substring", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/swap-for-longest-repeated-character-substring", + "solutionLink": "#" + }, + { + "problemName": "1157. Online Majority Element In Subarray", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/online-majority-element-in-subarray", + "solutionLink": "#" + }, + { + "problemName": "1158. Market Analysis I", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/market-analysis-i", + "solutionLink": "#" + }, + { + "problemName": "1159. Market Analysis II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/market-analysis-ii", + "solutionLink": "#" + }, + { + "problemName": "1160. Find Words That Can Be Formed by Characters", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-words-that-can-be-formed-by-characters", + "solutionLink": "#" + }, + { + "problemName": "1161. Maximum Level Sum of a Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree", + "solutionLink": "/dsa-solutions/lc-solutions/1100-1199/maximum-level-sum-of-a-binary-tree" + }, + { + "problemName": "1162. As Far from Land as Possible", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/as-far-from-land-as-possible", + "solutionLink": "#" + }, + { + "problemName": "1163. Last Substring in Lexicographical Order", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/last-substring-in-lexicographical-order", + "solutionLink": "#" + }, + { + "problemName": "1164. Product Price at a Given Date", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/product-price-at-a-given-date", + "solutionLink": "#" + }, + { + "problemName": "1165. Single-Row Keyboard", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/single-row-keyboard", + "solutionLink": "#" + }, + { + "problemName": "1166. Design File System", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-file-system", + "solutionLink": "#" + }, + { + "problemName": "1167. Minimum Cost to Connect Sticks", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-connect-sticks", + "solutionLink": "#" + }, + { + "problemName": "1168. Optimize Water Distribution in a Village", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/optimize-water-distribution-in-a-village", + "solutionLink": "#" + }, + { + "problemName": "1169. Invalid Transactions", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/invalid-transactions", + "solutionLink": "#" + }, + { + "problemName": "1170. Compare Strings by Frequency of the Smallest Character", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character", + "solutionLink": "#" + }, + { + "problemName": "1171. Remove Zero Sum Consecutive Nodes from Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list", + "solutionLink": "#" + }, + { + "problemName": "1172. Dinner Plate Stacks", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/dinner-plate-stacks", + "solutionLink": "#" + }, + { + "problemName": "1173. Immediate Food Delivery I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/immediate-food-delivery-i", + "solutionLink": "#" + }, + { + "problemName": "1174. Immediate Food Delivery II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/immediate-food-delivery-ii", + "solutionLink": "#" + }, + { + "problemName": "1175. Prime Arrangements", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/prime-arrangements", + "solutionLink": "#" + }, + { + "problemName": "1176. Diet Plan Performance", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/diet-plan-performance", + "solutionLink": "#" + }, + { + "problemName": "1177. Can Make Palindrome from Substring", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/can-make-palindrome-from-substring", + "solutionLink": "#" + }, + { + "problemName": "1178. Number of Valid Words for Each Puzzle", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-valid-words-for-each-puzzle", + "solutionLink": "#" + }, + { + "problemName": "1179. Reformat Department Table", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/reformat-department-table", + "solutionLink": "#" + }, + { + "problemName": "1180. Count Substrings with Only One Distinct Letter", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-substrings-with-only-one-distinct-letter", + "solutionLink": "#" + }, + { + "problemName": "1181. Before and After Puzzle", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/before-and-after-puzzle", + "solutionLink": "#" + }, + { + "problemName": "1182. Shortest Distance to Target Color", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shortest-distance-to-target-color", + "solutionLink": "#" + }, + { + "problemName": "1183. Maximum Number of Ones", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-ones", + "solutionLink": "#" + }, + { + "problemName": "1184. Distance Between Bus Stops", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/distance-between-bus-stops", + "solutionLink": "#" + }, + { + "problemName": "1185. Day of the Week", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/day-of-the-week", + "solutionLink": "#" + }, + { + "problemName": "1186. Maximum Subarray Sum with One Deletion", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion", + "solutionLink": "#" + }, + { + "problemName": "1187. Make Array Strictly Increasing", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/make-array-strictly-increasing", + "solutionLink": "#" + }, + { + "problemName": "1188. Design Bounded Blocking Queue", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-bounded-blocking-queue", + "solutionLink": "#" + }, + { + "problemName": "1189. Maximum Number of Balloons", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-balloons", + "solutionLink": "#" + }, + { + "problemName": "1190. Reverse Substrings Between Each Pair of Parentheses", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses", + "solutionLink": "/dsa-solutions/lc-solutions/1100-1199/reverse-substrings-between-each-pair-of-parentheses" + }, + { + "problemName": "1191. K-Concatenation Maximum Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/k-concatenation-maximum-sum", + "solutionLink": "#" + }, + { + "problemName": "1192. Critical Connections in a Network", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/critical-connections-in-a-network", + "solutionLink": "#" + }, + { + "problemName": "1193. Monthly Transactions I", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/monthly-transactions-i", + "solutionLink": "#" + }, + { + "problemName": "1194. Tournament Winners", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/tournament-winners", + "solutionLink": "#" + }, + { + "problemName": "1195. Fizz Buzz Multithreaded", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/fizz-buzz-multithreaded", + "solutionLink": "#" + }, + { + "problemName": "1196. How Many Apples Can You Put into the Basket", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/how-many-apples-can-you-put-into-the-basket", + "solutionLink": "#" + }, + { + "problemName": "1197. Minimum Knight Moves", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-knight-moves", + "solutionLink": "#" + }, + { + "problemName": "1198. Find Smallest Common Element in All Rows", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-smallest-common-element-in-all-rows", + "solutionLink": "#" + }, + { + "problemName": "1199. Minimum Time to Build Blocks", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-to-build-blocks", + "solutionLink": "#" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/leetcode-problems/1200-1299.md b/problems/leetcode-problems/1200-1299.md new file mode 100644 index 0000000..47ccdc8 --- /dev/null +++ b/problems/leetcode-problems/1200-1299.md @@ -0,0 +1,621 @@ +--- +id: 1200-1299 +title: LeetCode Problems 1200 - 1299 +sidebar_label: 1200 - 1299 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 1200 - 1299 + - DSA problems +--- +export const problems = [ + { + "problemName": "1200. Minimum Absolute Difference", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-absolute-difference", + "solutionLink": "/dsa-solutions/lc-solutions/1200-1299/minimum-absolute-difference" + }, + { + "problemName": "1201. Ugly Number III", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/ugly-number-iii", + "solutionLink": "#" + }, + { + "problemName": "1202. Smallest String With Swaps", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/smallest-string-with-swaps", + "solutionLink": "#" + }, + { + "problemName": "1203. Sort Items by Groups Respecting Dependencies", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sort-items-by-groups-respecting-dependencies", + "solutionLink": "#" + }, + { + "problemName": "1204. Last Person to Fit in the Elevator", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/last-person-to-fit-in-the-elevator", + "solutionLink": "#" + }, + { + "problemName": "1205. Monthly Transactions I", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/monthly-transactions-i", + "solutionLink": "#" + }, + { + "problemName": "1206. Design Skiplist", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/design-skiplist", + "solutionLink": "#" + }, + { + "problemName": "1207. Unique Number of Occurrences", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/unique-number-of-occurrences", + "solutionLink": "#" + }, + { + "problemName": "1208. Get Equal Substrings Within Budget", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/get-equal-substrings-within-budget", + "solutionLink": "#" + }, + { + "problemName": "1209. Remove All Adjacent Duplicates in String II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii", + "solutionLink": "#" + }, + { + "problemName": "1210. Minimum Moves to Reach Target with Rotations", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-moves-to-reach-target-with-rotations", + "solutionLink": "#" + }, + { + "problemName": "1211. Queries Quality and Percentage", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/queries-quality-and-percentage", + "solutionLink": "#" + }, + { + "problemName": "1212. Team Scores in Football Tournament", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/team-scores-in-football-tournament", + "solutionLink": "#" + }, + { + "problemName": "1213. Intersection of Three Sorted Arrays", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/intersection-of-three-sorted-arrays", + "solutionLink": "#" + }, + { + "problemName": "1214. Two Sum BSTs", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/two-sum-bsts", + "solutionLink": "#" + }, + { + "problemName": "1215. Stepping Numbers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/stepping-numbers", + "solutionLink": "#" + }, + { + "problemName": "1216. Valid Palindrome III", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/valid-palindrome-iii", + "solutionLink": "#" + }, + { + "problemName": "1217. Play with Chips", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/play-with-chips", + "solutionLink": "#" + }, + { + "problemName": "1218. Longest Arithmetic Subsequence of Given Difference", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference", + "solutionLink": "#" + }, + { + "problemName": "1219. Path with Maximum Gold", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/path-with-maximum-gold", + "solutionLink": "#" + }, + { + "problemName": "1220. Count Vowels Permutation", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-vowels-permutation", + "solutionLink": "#" + }, + { + "problemName": "1221. Split a String in Balanced Strings", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/split-a-string-in-balanced-strings", + "solutionLink": "#" + }, + { + "problemName": "1222. Queens That Can Attack the King", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/queens-that-can-attack-the-king", + "solutionLink": "#" + }, + { + "problemName": "1223. Dice Roll Simulation", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/dice-roll-simulation", + "solutionLink": "#" + }, + { + "problemName": "1224. Maximum Equal Frequency", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-equal-frequency", + "solutionLink": "#" + }, + { + "problemName": "1225. Report Contiguous Dates", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/report-contiguous-dates", + "solutionLink": "#" + }, + { + "problemName": "1226. The Dining Philosophers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-dining-philosophers", + "solutionLink": "#" + }, + { + "problemName": "1227. Airplane Seat Assignment Probability", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/airplane-seat-assignment-probability", + "solutionLink": "#" + }, + { + "problemName": "1228. Missing Number In Arithmetic Progression", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/missing-number-in-arithmetic-progression", + "solutionLink": "#" + }, + { + "problemName": "1229. Meeting Scheduler", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/meeting-scheduler", + "solutionLink": "#" + }, + { + "problemName": "1230. Toss Strange Coins", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/toss-strange-coins", + "solutionLink": "#" + }, + { + "problemName": "1231. Divide Chocolate", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/divide-chocolate", + "solutionLink": "#" + }, + { + "problemName": "1232. Check If It Is a Straight Line", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-it-is-a-straight-line", + "solutionLink": "/dsa-solutions/lc-solutions/1200-1299/check-if-it-is-a-straight-line" + }, + { + "problemName": "1233. Remove Sub-Folders from the Filesystem", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-sub-folders-from-the-filesystem", + "solutionLink": "#" + }, + { + "problemName": "1234. Replace the Substring for Balanced String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/replace-the-substring-for-balanced-string", + "solutionLink": "#" + }, + { + "problemName": "1235. Maximum Profit in Job Scheduling", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-profit-in-job-scheduling", + "solutionLink": "#" + }, + { + "problemName": "1236. Web Crawler", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/web-crawler", + "solutionLink": "#" + }, + { + "problemName": "1237. Find Positive Integer Solution for a Given Equation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation", + "solutionLink": "#" + }, + { + "problemName": "1238. Circular Permutation in Binary Representation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/circular-permutation-in-binary-representation", + "solutionLink": "#" + }, + { + "problemName": "1239. Maximum Length of a Concatenated String with Unique Characters", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters", + "solutionLink": "#" + }, + { + "problemName": "1240. Tiling a Rectangle with the Fewest Squares", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares", + "solutionLink": "#" + }, + { + "problemName": "1241. Number of Comments per Post", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-comments-per-post", + "solutionLink": "#" + }, + { + "problemName": "1242. Web Crawler Multithreaded", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/web-crawler-multithreaded", + "solutionLink": "#" + }, + { + "problemName": "1243. Array Transformation", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/array-transformation", + "solutionLink": "#" + }, + { + "problemName": "1244. Design A Leaderboard", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-a-leaderboard", + "solutionLink": "#" + }, + { + "problemName": "1245. Tree Diameter", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/tree-diameter", + "solutionLink": "#" + }, + { + "problemName": "1246. Palindrome Removal", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/palindrome-removal", + "solutionLink": "#" + }, + { + "problemName": "1247. Minimum Swaps to Make Strings Equal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-swaps-to-make-strings-equal", + "solutionLink": "#" + }, + { + "problemName": "1248. Count Number of Nice Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-number-of-nice-subarrays", + "solutionLink": "/dsa-solutions/lc-solutions/1200-1299/count-number-of-nice-subarrays" + }, + { + "problemName": "1249. Minimum Remove to Make Valid Parentheses", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses", + "solutionLink": "#" + }, + { + "problemName": "1250. Check If It Is a Good Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/check-if-it-is-a-good-array", + "solutionLink": "#" + }, + { + "problemName": "1251. Average Selling Price", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/average-selling-price", + "solutionLink": "#" + }, + { + "problemName": "1252. Cells with Odd Values in a Matrix", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/cells-with-odd-values-in-a-matrix", + "solutionLink": "#" + }, + { + "problemName": "1253. Reconstruct a 2-Row Binary Matrix", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix", + "solutionLink": "#" + }, + { + "problemName": "1254. Number of Closed Islands", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-closed-islands", + "solutionLink": "#" + }, + { + "problemName": "1255. Maximum Score Words Formed by Letters", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-score-words-formed-by-letters", + "solutionLink": "#" + }, + { + "problemName": "1256. Encode Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/encode-number", + "solutionLink": "#" + }, + { + "problemName": "1257. Smallest Common Region", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/smallest-common-region", + "solutionLink": "#" + }, + { + "problemName": "1258. Synonymous Sentences", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/synonymous-sentences", + "solutionLink": "#" + }, + { + "problemName": "1259. Handshakes That Don't Cross", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/handshakes-that-dont-cross", + "solutionLink": "#" + }, + { + "problemName": "1260. Shift 2D Grid", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/shift-2d-grid", + "solutionLink": "#" + }, + { + "problemName": "1261. Find Elements in a Contaminated Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-elements-in-a-contaminated-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "1262. Greatest Sum Divisible by Three", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/greatest-sum-divisible-by-three", + "solutionLink": "#" + }, + { + "problemName": "1263. Minimum Moves to Move a Box to Their Target Location", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-moves-to-move-a-box-to-their-target-location", + "solutionLink": "#" + }, + { + "problemName": "1264. Page Recommendations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/page-recommendations", + "solutionLink": "#" + }, + { + "problemName": "1265. Print Immutable Linked List in Reverse", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/print-immutable-linked-list-in-reverse", + "solutionLink": "#" + }, + { + "problemName": "1266. Minimum Time Visiting All Points", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-visiting-all-points", + "solutionLink": "#" + }, + { + "problemName": "1267. Count Servers that Communicate", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-servers-that-communicate", + "solutionLink": "#" + }, + { + "problemName": "1268. Search Suggestions System", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/search-suggestions-system", + "solutionLink": "#" + }, + { + "problemName": "1269. Number of Ways to Stay in the Same Place After Some Steps", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps", + "solutionLink": "#" + }, + { + "problemName": "1270. All People Report to the Given Manager", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/all-people-report-to-the-given-manager", + "solutionLink": "#" + }, + { + "problemName": "1271. Hexspeak", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/hexspeak", + "solutionLink": "#" + }, + { + "problemName": "1272. Remove Interval", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-interval", + "solutionLink": "#" + }, + { + "problemName": "1273. Delete Tree Nodes", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/delete-tree-nodes", + "solutionLink": "#" + }, + { + "problemName": "1274. Number of Ships in a Rectangle", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-ships-in-a-rectangle", + "solutionLink": "#" + }, + { + "problemName": "1275. Find Winner on a Tic Tac Toe Game", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game", + "solutionLink": "#" + }, + { + "problemName": "1276. Number of Burgers with No Waste of Ingredients", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients", + "solutionLink": "#" + }, + { + "problemName": "1277. Count Square Submatrices with All Ones", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-square-submatrices-with-all-ones", + "solutionLink": "#" + }, + { + "problemName": "1278. Palindrome Partitioning III", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/palindrome-partitioning-iii", + "solutionLink": "#" + }, + { + "problemName": "1279. Traffic Light Controlled Intersection", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/traffic-light-controlled-intersection", + "solutionLink": "#" + }, + { + "problemName": "1280. Students and Examinations", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/students-and-examinations", + "solutionLink": "#" + }, + { + "problemName": "1281. Subtract the Product and Sum of Digits of an Integer", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer", + "solutionLink": "#" + }, + { + "problemName": "1282. Group the People Given the Group Size They Belong To", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to", + "solutionLink": "#" + }, + { + "problemName": "1283. Find the Smallest Divisor Given a Threshold", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold", + "solutionLink": "#" + }, + { + "problemName": "1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix", + "solutionLink": "#" + }, + { + "problemName": "1285. Find the Start and End Number of Continuous Ranges", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-start-and-end-number-of-continuous-ranges", + "solutionLink": "#" + }, + { + "problemName": "1286. Iterator for Combination", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/iterator-for-combination", + "solutionLink": "#" + }, + { + "problemName": "1287. Element Appearing More Than 25% In Sorted Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array", + "solutionLink": "#" + }, + { + "problemName": "1288. Remove Covered Intervals", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-covered-intervals", + "solutionLink": "/dsa-solutions/lc-solutions/1200-1299/remove-covered-intervals" + }, + { + "problemName": "1289. Minimum Falling Path Sum II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-falling-path-sum-ii", + "solutionLink": "#" + }, + { + "problemName": "1290. Convert Binary Number in a Linked List to Integer", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer", + "solutionLink": "#" + }, + { + "problemName": "1291. Sequential Digits", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sequential-digits", + "solutionLink": "#" + }, + { + "problemName": "1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold", + "solutionLink": "#" + }, + { + "problemName": "1293. Shortest Path in a Grid with Obstacles Elimination", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination", + "solutionLink": "#" + }, + { + "problemName": "1294. Weather Type in Each Country", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/weather-type-in-each-country", + "solutionLink": "#" + }, + { + "problemName": "1295. Find Numbers with Even Number of Digits", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-numbers-with-even-number-of-digits", + "solutionLink": "#" + }, + { + "problemName": "1296. Divide Array in Sets of K Consecutive Numbers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers", + "solutionLink": "#" + }, + { + "problemName": "1297. Maximum Number of Occurrences of a Substring", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring", + "solutionLink": "#" + }, + { + "problemName": "1298. Maximum Candies You Can Get from Boxes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes", + "solutionLink": "#" + }, + { + "problemName": "1299. Replace Elements with Greatest Element on Right Side", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side", + "solutionLink": "#" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/1300-1399.md b/problems/leetcode-problems/1300-1399.md new file mode 100644 index 0000000..424d1f5 --- /dev/null +++ b/problems/leetcode-problems/1300-1399.md @@ -0,0 +1,622 @@ +--- +id: 1300-1399 +title: LeetCode Problems 1300 - 1399 +sidebar_label: 1300 - 1399 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 1300 - 1399 + - DSA problems +--- + +export const problems = [ + { + "problemName": "1300. Sum of Mutated Array Closest to Target", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-of-mutated-array-closest-to-target", + "solutionLink": "#" + }, + { + "problemName": "1301. Number of Paths with Max Score", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-paths-with-max-score", + "solutionLink": "#" + }, + { + "problemName": "1302. Deepest Leaves Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/deepest-leaves-sum", + "solutionLink": "/dsa-solutions/lc-solutions/1300-1399/1302-Deepest-Leaves-Sum" + }, + { + "problemName": "1303. Find the Team Size", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-team-size", + "solutionLink": "#" + }, + { + "problemName": "1304. Find N Unique Integers Sum up to Zero", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero", + "solutionLink": "#" + }, + { + "problemName": "1305. All Elements in Two Binary Search Trees", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/all-elements-in-two-binary-search-trees", + "solutionLink": "/dsa-solutions/lc-solutions/1300-1399/all-elements-in-two-binary-search-trees" + }, + { + "problemName": "1306. Jump Game III", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/jump-game-iii", + "solutionLink": "#" + }, + { + "problemName": "1307. Verbal Arithmetic Puzzle", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/verbal-arithmetic-puzzle", + "solutionLink": "#" + }, + { + "problemName": "1308. Running Total for Different Genders", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/running-total-for-different-genders", + "solutionLink": "#" + }, + { + "problemName": "1309. Decrypt String from Alphabet to Integer Mapping", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping", + "solutionLink": "#" + }, + { + "problemName": "1310. XOR Queries of a Subarray", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/xor-queries-of-a-subarray", + "solutionLink": "/dsa-solutions/lc-solutions/1300-1399/xor-queries-of-a-subarray" + }, + { + "problemName": "1311. Get Watched Videos by Your Friends", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/get-watched-videos-by-your-friends", + "solutionLink": "#" + }, + { + "problemName": "1312. Minimum Insertion Steps to Make a String Palindrome", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome", + "solutionLink": "#" + }, + { + "problemName": "1313. Decompress Run-Length Encoded List", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/decompress-run-length-encoded-list", + "solutionLink": "#" + }, + { + "problemName": "1314. Matrix Block Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/matrix-block-sum", + "solutionLink": "#" + }, + { + "problemName": "1315. Sum of Nodes with Even-Valued Grandparent", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent", + "solutionLink": "#" + }, + { + "problemName": "1316. Distinct Echo Substrings", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/distinct-echo-substrings", + "solutionLink": "#" + }, + { + "problemName": "1317. Convert Integer to the Sum of Two No-Zero Integers", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers", + "solutionLink": "#" + }, + { + "problemName": "1318. Minimum Flips to Make a OR b Equal to c", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c", + "solutionLink": "#" + }, + { + "problemName": "1319. Number of Operations to Make Network Connected", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-operations-to-make-network-connected", + "solutionLink": "#" + }, + { + "problemName": "1320. Minimum Distance to Type a Word Using Two Fingers", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers", + "solutionLink": "#" + }, + { + "problemName": "1321. Restaurant Growth", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/restaurant-growth", + "solutionLink": "#" + }, + { + "problemName": "1322. Ads Performance", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/ads-performance", + "solutionLink": "#" + }, + { + "problemName": "1323. Maximum 69 Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-69-number", + "solutionLink": "#" + }, + { + "problemName": "1324. Print Words Vertically", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/print-words-vertically", + "solutionLink": "#" + }, + { + "problemName": "1325. Delete Leaves With a Given Value", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/delete-leaves-with-a-given-value", + "solutionLink": "#" + }, + { + "problemName": "1326. Minimum Number of Taps to Open to Water a Garden", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden", + "solutionLink": "#" + }, + { + "problemName": "1327. List the Products Ordered in a Period", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/list-the-products-ordered-in-a-period", + "solutionLink": "#" + }, + { + "problemName": "1328. Break a Palindrome", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/break-a-palindrome", + "solutionLink": "#" + }, + { + "problemName": "1329. Sort the Matrix Diagonally", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sort-the-matrix-diagonally", + "solutionLink": "#" + }, + { + "problemName": "1330. Reverse Subarray To Maximize Array Value", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/reverse-subarray-to-maximize-array-value", + "solutionLink": "#" + }, + { + "problemName": "1331. Rank Transform of an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/rank-transform-of-an-array", + "solutionLink": "#" + }, + { + "problemName": "1332. Remove Palindromic Subsequences", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/remove-palindromic-subsequences", + "solutionLink": "#" + }, + { + "problemName": "1333. Filter Restaurants by Vegan-Friendly, Price and Distance", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance", + "solutionLink": "#" + }, + { + "problemName": "1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance", + "solutionLink": "#" + }, + { + "problemName": "1335. Minimum Difficulty of a Job Schedule", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule", + "solutionLink": "#" + }, + { + "problemName": "1336. Number of Transactions per Visit", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-transactions-per-visit", + "solutionLink": "#" + }, + { + "problemName": "1337. The K Weakest Rows in a Matrix", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix", + "solutionLink": "#" + }, + { + "problemName": "1338. Reduce Array Size to The Half", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reduce-array-size-to-the-half", + "solutionLink": "#" + }, + { + "problemName": "1339. Maximum Product of Splitted Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-product-of-splitted-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "1340. Jump Game V", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/jump-game-v", + "solutionLink": "#" + }, + { + "problemName": "1341. The K Weakest Rows in a Matrix", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix", + "solutionLink": "#" + }, + { + "problemName": "1342. Reduce Array Size to The Half", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reduce-array-size-to-the-half", + "solutionLink": "#" + }, + { + "problemName": "1343. Maximum Product of Splitted Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-product-of-splitted-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "1344. Jump Game V", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/jump-game-v", + "solutionLink": "#" + }, + { + "problemName": "1345. List the Products Ordered in a Period", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/list-the-products-ordered-in-a-period", + "solutionLink": "#" + }, + { + "problemName": "1346. Break a Palindrome", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/break-a-palindrome", + "solutionLink": "#" + }, + { + "problemName": "1347. Sort the Matrix Diagonally", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sort-the-matrix-diagonally", + "solutionLink": "#" + }, + { + "problemName": "1348. Reverse Subarray To Maximize Array Value", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/reverse-subarray-to-maximize-array-value", + "solutionLink": "#" + }, + { + "problemName": "1349. Rank Transform of an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/rank-transform-of-an-array", + "solutionLink": "#" + }, + { + "problemName": "1350. Remove Palindromic Subsequences", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/remove-palindromic-subsequences", + "solutionLink": "#" + }, + { + "problemName": "1351. Filter Restaurants by Vegan-Friendly, Price and Distance", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance", + "solutionLink": "#" + }, + { + "problemName": "1352. Find the City With the Smallest Number of Neighbors at a Threshold Distance", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance", + "solutionLink": "#" + }, + { + "problemName": "1353. Minimum Difficulty of a Job Schedule", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule", + "solutionLink": "#" + }, + { + "problemName": "1354. Number of Transactions per Visit", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-transactions-per-visit", + "solutionLink": "#" + }, + { + "problemName": "1355. The K Weakest Rows in a Matrix", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix", + "solutionLink": "#" + }, + { + "problemName": "1356. Reduce Array Size to The Half", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reduce-array-size-to-the-half", + "solutionLink": "#" + }, + { + "problemName": "1357. Maximum Product of Splitted Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-product-of-splitted-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "1358. Jump Game V", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/jump-game-v", + "solutionLink": "#" + }, + { + "problemName": "1359. List the Products Ordered in a Period", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/list-the-products-ordered-in-a-period", + "solutionLink": "#" + }, + { + "problemName": "1360. Break a Palindrome", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/break-a-palindrome", + "solutionLink": "#" + }, + { + "problemName": "1361. Sort the Matrix Diagonally", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sort-the-matrix-diagonally", + "solutionLink": "#" + }, + { + "problemName": "1362. Reverse Subarray To Maximize Array Value", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/reverse-subarray-to-maximize-array-value", + "solutionLink": "#" + }, + { + "problemName": "1363. Rank Transform of an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/rank-transform-of-an-array", + "solutionLink": "#" + }, + { + "problemName": "1364. Remove Palindromic Subsequences", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/remove-palindromic-subsequences", + "solutionLink": "#" + }, + { + "problemName": "1365. Filter Restaurants by Vegan-Friendly, Price and Distance", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance", + "solutionLink": "#" + }, + { + "problemName": "1366. Find the City With the Smallest Number of Neighbors at a Threshold Distance", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance", + "solutionLink": "#" + }, + { + "problemName": "1367. Minimum Difficulty of a Job Schedule", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule", + "solutionLink": "#" + }, + { + "problemName": "1368. Number of Transactions per Visit", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-transactions-per-visit", + "solutionLink": "#" + }, + { + "problemName": "1369. The K Weakest Rows in a Matrix", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix", + "solutionLink": "#" + }, + { + "problemName": "1370. Reduce Array Size to The Half", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reduce-array-size-to-the-half", + "solutionLink": "#" + }, + { + "problemName": "1371. Find the Longest Substring Containing Vowels in Even Counts", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts", + "solutionLink": "#" + }, + { + "problemName": "1372. Longest ZigZag Path in a Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "1373. Maximum Sum BST in Binary Tree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-sum-bst-in-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "1374. Generate a String With Characters That Have Odd Counts", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts", + "solutionLink": "#" + }, + { + "problemName": "1375. Bulb Switcher III", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/bulb-switcher-iii", + "solutionLink": "#" + }, + { + "problemName": "1376. Time Needed to Inform All Employees", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/time-needed-to-inform-all-employees", + "solutionLink": "#" + }, + { + "problemName": "1377. Frog Position After T Seconds", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/frog-position-after-t-seconds", + "solutionLink": "#" + }, + { + "problemName": "1378. Replace Elements with Greatest Element on Right Side", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side", + "solutionLink": "#" + }, + { + "problemName": "1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree", + "solutionLink": "#" + }, + { + "problemName": "1380. Lucky Numbers in a Matrix", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/lucky-numbers-in-a-matrix", + "solutionLink": "#" + }, + { + "problemName": "1381. Design a Stack With Increment Operation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-a-stack-with-increment-operation", + "solutionLink": "#" + }, + { + "problemName": "1382. Balance a Binary Search Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/balance-a-binary-search-tree", + "solutionLink": "#" + }, + { + "problemName": "1383. Maximum Performance of a Team", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-performance-of-a-team", + "solutionLink": "#" + }, + { + "problemName": "1384. Count Good Nodes in Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-good-nodes-in-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "1385. Find the Distance Value Between Two Arrays", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-distance-value-between-two-arrays", + "solutionLink": "#" + }, + { + "problemName": "1386. Cinema Seat Allocation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/cinema-seat-allocation", + "solutionLink": "#" + }, + { + "problemName": "1387. Sort Integers by The Power Value", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sort-integers-by-the-power-value", + "solutionLink": "#" + }, + { + "problemName": "1388. Pizza With 3n Slices", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/pizza-with-3n-slices", + "solutionLink": "#" + }, + { + "problemName": "1389. Create Target Array in the Given Order", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/create-target-array-in-the-given-order", + "solutionLink": "#" + }, + { + "problemName": "1390. Four Divisors", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/four-divisors", + "solutionLink": "#" + }, + { + "problemName": "1391. Check if There is a Valid Path in a Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid", + "solutionLink": "#" + }, + { + "problemName": "1392. Longest Happy Prefix", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/longest-happy-prefix", + "solutionLink": "#" + }, + { + "problemName": "1393. Capital Gain/Loss", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/capital-gainloss", + "solutionLink": "#" + }, + { + "problemName": "1394. Find Lucky Integer in an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-lucky-integer-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "1395. Count Number of Teams", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-number-of-teams", + "solutionLink": "#" + }, + { + "problemName": "1396. Design Underground System", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-underground-system", + "solutionLink": "#" + }, + { + "problemName": "1397. Find All Good Strings", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-all-good-strings", + "solutionLink": "#" + }, + { + "problemName": "1398. Customers Who Bought Products A and B but Not C", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/customers-who-bought-products-a-and-b-but-not-c", + "solutionLink": "#" + }, + { + "problemName": "1399. Count Largest Group", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-largest-group", + "solutionLink": "#" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/leetcode-problems/1400-1499.md b/problems/leetcode-problems/1400-1499.md new file mode 100644 index 0000000..222c015 --- /dev/null +++ b/problems/leetcode-problems/1400-1499.md @@ -0,0 +1,622 @@ +--- +id: 1400-1499 +title: LeetCode Problems 1400 - 1499 +sidebar_label: 1400 - 1499 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 1400 - 1499 + - DSA problems +--- + +export const problems = [ + { + "problemName": "1400. Construct K Palindrome Strings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/construct-k-palindrome-strings", + "solutionLink": "#" + }, + { + "problemName": "1401. Circle and Rectangle Overlapping", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/circle-and-rectangle-overlapping", + "solutionLink": "#" + }, + { + "problemName": "1402. Reducing Dishes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/reducing-dishes", + "solutionLink": "/dsa-solutions/lc-solutions/1400-1500/reducing-dishes" + }, + { + "problemName": "1403. Minimum Subsequence in Non-Increasing Order", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order", + "solutionLink": "#" + }, + { + "problemName": "1404. Number of Steps to Reduce a Number in binary representation to one", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one", + "solutionLink": "#" + }, + { + "problemName": "1405. Longest Happy String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-happy-string", + "solutionLink": "#" + }, + { + "problemName": "1406. Stone Game III", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/stone-game-iii", + "solutionLink": "#" + }, + { + "problemName": "1407. Top Travellers", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/top-travellers", + "solutionLink": "#" + }, + { + "problemName": "1408. String Matching in an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/string-matching-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "1409. Queries on a Permutation With Key", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/queries-on-a-permutation-with-key", + "solutionLink": "#" + }, + { + "problemName": "1410. HTML Entity Parser", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/html-entity-parser", + "solutionLink": "#" + }, + { + "problemName": "1411. Number of Ways to Paint N Γ— 3 Grid", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid", + "solutionLink": "#" + }, + { + "problemName": "1412. Find the Quiet Students in All Exams", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-the-quiet-students-in-all-exams", + "solutionLink": "#" + }, + { + "problemName": "1413. Minimum Value to Get Positive Step by Step Sum", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum", + "solutionLink": "#" + }, + { + "problemName": "1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k", + "solutionLink": "#" + }, + { + "problemName": "1415. The k-th Lexicographical String of All Happy Strings of Length n", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n", + "solutionLink": "#" + }, + { + "problemName": "1416. Restore The Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/restore-the-array", + "solutionLink": "#" + }, + { + "problemName": "1417. Reformat The String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/reformat-the-string", + "solutionLink": "#" + }, + { + "problemName": "1418. Display Table of Food Orders in a Restaurants", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant", + "solutionLink": "#" + }, + { + "problemName": "1419. Minimum Number of Frogs Croaking", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-frogs-croaking", + "solutionLink": "#" + }, + { + "problemName": "1420. Build Array Where You Can Find The maximum exactly k comparisons", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons", + "solutionLink": "#" + }, + { + "problemName": "1421. NPV Queries", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/npv-queries", + "solutionLink": "#" + }, + { + "problemName": "1422. Maximum Score After Splitting a String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-score-after-splitting-a-string", + "solutionLink": "#" + }, + { + "problemName": "1423. Maximum Points You Can Obtain from", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards", + "solutionLink": "#" + }, + { + "problemName": "1424. Diagonal Traverse II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/diagonal-traverse-ii", + "solutionLink": "/dsa-solutions/lc-solutions/1400-1499/diagonal-traverse-ii" + }, + { + "problemName": "1425. Constrained Subsequence Sum", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/constrained-subsequence-sum", + "solutionLink": "#" + }, + { + "problemName": "1426. Counting Elements", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/counting-elements", + "solutionLink": "#" + }, + { + "problemName": "1427. Perform String Shifts", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/perform-string-shifts", + "solutionLink": "#" + }, + { + "problemName": "1428. Leftmost Column with at least a one", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/leftmost-column-with-at-least-a-one", + "solutionLink": "#" + }, + { + "problemName": "1429. First Unique Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/first-unique-number", + "solutionLink": "#" + }, + { + "problemName": "1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "1431. Kids With the Greatest Number of Candies", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/kids-with-the-greatest-number-of-candies", + "solutionLink": "#" + }, + { + "problemName": "1432. Max Difference You Can Get From Changing an Integer", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/max-difference-you-can-get-from-changing-an-integer", + "solutionLink": "#" + }, + { + "problemName": "1433. Check If a String Can Break Another String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-a-string-can-break-another-string", + "solutionLink": "#" + }, + { + "problemName": "1434. Number of Ways to Wear Different Hats to each other", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other", + "solutionLink": "#" + }, + { + "problemName": "1435. Create a Session Bar Chart", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/create-a-session-bar-chart", + "solutionLink": "#" + }, + { + "problemName": "1436. Destination City", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/destination-city", + "solutionLink": "#" + }, + { + "problemName": "1437. Check If All 1's Are at Least Length K places away", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away", + "solutionLink": "#" + }, + { + "problemName": "1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit", + "solutionLink": "#" + }, + { + "problemName": "1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows", + "solutionLink": "#" + }, + { + "problemName": "1440. Evaluate Boolean Expression", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/evaluate-boolean-expression", + "solutionLink": "#" + }, + { + "problemName": "1441. Build an Array With Stack Operations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/build-an-array-with-stack-operations", + "solutionLink": "#" + }, + { + "problemName": "1442. Count Triplets That Can Form Two Arrays of Equal XOR", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor", + "solutionLink": "#" + }, + { + "problemName": "1443. Minimum Time to Collect All Apples in a tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree", + "solutionLink": "/dsa-solutions/lc-solutions/1400-1499/minimum-time-to-collect-all-apples-in-a-tree" + }, + { + "problemName": "1444. Number of Ways of Cutting a Pizza", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza", + "solutionLink": "#" + }, + { + "problemName": "1445. Apples & Oranges", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/apples-oranges", + "solutionLink": "#" + }, + { + "problemName": "1446. Consecutive Characters", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/consecutive-characters", + "solutionLink": "#" + }, + { + "problemName": "1447. Simplified Fractions", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/simplified-fractions", + "solutionLink": "#" + }, + { + "problemName": "1448. Count Good Nodes in Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-good-nodes-in-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "1449. Form Largest Integer With Digits That Add up to Target", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target", + "solutionLink": "#" + }, + { + "problemName": "1450. Number of Students Doing Homework at a Given Time", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time", + "solutionLink": "#" + }, + { + "problemName": "1451. Rearrange Words in a Sentence", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/rearrange-words-in-a-sentence", + "solutionLink": "#" + }, + { + "problemName": "1452. People Whose List of Favorite Companies Is Not a Subset of Another List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list", + "solutionLink": "#" + }, + { + "problemName": "1453. Maximum Number of Darts Inside of a Circular Dartboard", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard", + "solutionLink": "#" + }, + { + "problemName": "1454. Active Users", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/active-users", + "solutionLink": "#" + }, + { + "problemName": "1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence", + "solutionLink": "#" + }, + { + "problemName": "1456. Maximum Number of Vowels in a Substring of given length", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length", + "solutionLink": "#" + }, + { + "problemName": "1457. Pseudo-Palindromic Paths in a Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "1458. Max Dot Product of Two Subsequences", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/max-dot-product-of-two-subsequences", + "solutionLink": "#" + }, + { + "problemName": "1459. Rectangles Area", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/rectangles-area", + "solutionLink": "#" + }, + { + "problemName": "1460. Make Two Arrays Equal by Reversing Subarrays", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/make-two-arrays-equal-by-reversing-subarrays", + "solutionLink": "#" + }, + { + "problemName": "1461. Check If a String Contains All Binary codes of size k", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k", + "solutionLink": "#" + }, + { + "problemName": "1462. Course Schedule IV", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/course-schedule-iv", + "solutionLink": "#" + }, + { + "problemName": "1463. Cherry Pickup II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/cherry-pickup-ii", + "solutionLink": "#" + }, + { + "problemName": "1464. Maximum Product of Two Elements in an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "1465. Maximum Area of a Piece of Cake After horizontal and vertical cuts", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts", + "solutionLink": "#" + }, + { + "problemName": "1466. Reorder Routes to Make All Paths Lead to the city zero", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero", + "solutionLink": "#" + }, + { + "problemName": "1467. Probability of a Two Boxes Having The Same Number of Distinct Balls", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls", + "solutionLink": "#" + }, + { + "problemName": "1468. Calculate Salaries", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/calculate-salaries", + "solutionLink": "#" + }, + { + "problemName": "1469. Find All The Lonely Nodes", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-all-the-lonely-nodes", + "solutionLink": "#" + }, + { + "problemName": "1470. Shuffle the Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/shuffle-the-array", + "solutionLink": "#" + }, + { + "problemName": "1471. The k Strongest Values in an Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-k-strongest-values-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "1472. Design Browser History", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-browser-history", + "solutionLink": "#" + }, + { + "problemName": "1473. Paint House III", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/paint-house-iii", + "solutionLink": "#" + }, + { + "problemName": "1474. Delete N Nodes After M Nodes after m node of a linked list", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/delete-n-nodes-after-m-nodes-of-a-linked-list", + "solutionLink": "#" + }, + { + "problemName": "1475. Final Prices With a Special Discount in a Shop", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop", + "solutionLink": "#" + }, + { + "problemName": "1476. Subrectangle Queries", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/subrectangle-queries", + "solutionLink": "#" + }, + { + "problemName": "1477. Find Two Non-overlapping Sub-arrays Each With Target Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum", + "solutionLink": "#" + }, + { + "problemName": "1478. Allocate Mailboxes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/allocate-mailboxes", + "solutionLink": "#" + }, + { + "problemName": "1479. Sales by Day of the Week", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sales-by-day-of-the-week", + "solutionLink": "#" + }, + { + "problemName": "1480. Running Sum of 1d Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/running-sum-of-1d-array", + "solutionLink": "#" + }, + { + "problemName": "1481. Least Number of Unique Integers after k removals", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals", + "solutionLink": "#" + }, + { + "problemName": "1482. Minimum Number of Days to Make m Bouquets", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets", + "solutionLink": "#" + }, + { + "problemName": "1483. Kth Ancestor of a Tree Node", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/kth-ancestor-of-a-tree-node", + "solutionLink": "/dsa-solutions/lc-solutions/1400-1500/kth-ancestor-of-a-tree node" + }, + { + "problemName": "1484. Group Sold Products By The Date", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/group-sold-products-by-the-date", + "solutionLink": "#" + }, + { + "problemName": "1485. Clone Binary Tree With Random Pointer", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/clone-binary-tree-with-random-pointer", + "solutionLink": "#" + }, + { + "problemName": "1486. XOR Operation in an Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/making-file-names-unique", + "solutionLink": "#" + }, + { + "problemName": "1487. Making File Names Unique", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/making-file-names-unique", + "solutionLink": "#" + }, + { + "problemName": "1488. Avoid Flood in The City", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/avoid-flood-in-the-city", + "solutionLink": "#" + }, + { + "problemName": "1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree", + "solutionLink": "#" + }, + { + "problemName": "1490. Clone N-ary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/clone-n-ary-tree", + "solutionLink": "#" + }, + { + "problemName": "1491. Average Salary Excluding the Minimum and maximum salary", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary", + "solutionLink": "#" + }, + { + "problemName": "1492. The kth Factor of n", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-kth-factor-of-n", + "solutionLink": "#" + }, + { + "problemName": "1493. Longest Subarray of 1's After Deleting one element", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element", + "solutionLink": "#" + }, + { + "problemName": "1494. Parallel Courses II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/parallel-courses-ii", + "solutionLink": "#" + }, + { + "problemName": "1495. Friendly Movies Streamed Last Month", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/friendly-movies-streamed-last-month", + "solutionLink": "#" + }, + { + "problemName": "1496. Path Crossing", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/path-crossing", + "solutionLink": "#" + }, + { + "problemName": "1497. Check If Array Pairs Are Divisible by k", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k", + "solutionLink": "/dsa-solutions/lc-solutions/1400-1499/check-if-array-pairs-are-divisible-by-k" + }, + { + "problemName": "1498. Number of Subsequences That Satisfy the given sum condition", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition", + "solutionLink": "#" + }, + { + "problemName": "1499. Max Value of Equation", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/max-value-of-equation", + "solutionLink": "#" + } +] + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/1500-1599.md b/problems/leetcode-problems/1500-1599.md new file mode 100644 index 0000000..a4a3e65 --- /dev/null +++ b/problems/leetcode-problems/1500-1599.md @@ -0,0 +1,622 @@ +--- +id: 1500-1599 +title: LeetCode Problems 1500 - 1599 +sidebar_label: 1500 - 1599 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 1500 - 1599 + - DSA problems +--- + +export const problems = [ + { + "problemName": "1500. Design a File Sharing System", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-a-file-sharing-system", + "solutionLink": "#" + }, + { + "problemName": "1501. Countries You Can Safely Invest In", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/countries-you-can-safely-invest-in", + "solutionLink": "#" + }, + { + "problemName": "1502. Can Make Arithmetic Progression From Sequence", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence", + "solutionLink": "#" + }, + { + "problemName": "1503. Last Moment Before All Ants Fall Out of a Plank", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/last-moment-before-all-ants-fall-out-of-a-plank", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/last-moment-before-all-ants-fall-out-of-a-plank" + }, + { + "problemName": "1504. Count Submatrices With All Ones", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-submatrices-with-all-ones", + "solutionLink": "#" + }, + { + "problemName": "1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits", + "solutionLink": "#" + }, + { + "problemName": "1506. Find Root of N-Ary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-root-of-n-ary-tree", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/find-root-of-n-ary-tree" + }, + { + "problemName": "1507. Reformat Date", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/reformat-date", + "solutionLink": "#" + }, + { + "problemName": "1508. Range Sum of Sorted Subarray Sums", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/range-sum-of-sorted-subarray-sums", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/range-sum-of-sorted-subarray-sums" + }, + { + "problemName": "1509. Minimum Difference Between Largest and Smallest Value in Three Moves", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/minimum-difference-between-largest-and-smallest-value-in-three-moves" + }, + { + "problemName": "1510. Stone Game IV", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/stone-game-iv", + "solutionLink": "#" + }, + { + "problemName": "1511. Customer Order Frequency", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/customer-order-frequency", + "solutionLink": "#" + }, + { + "problemName": "1512. Number of Good Pairs", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-good-pairs", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/number-of-good-pairs" + }, + { + "problemName": "1513. Number of Substrings With Only 1s", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-substrings-with-only-1s", + "solutionLink": "#" + }, + { + "problemName": "1514. Path with Maximum Probability", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/path-with-maximum-probability", + "solutionLink": "/dsa-solutions/lc-solutions/1400-1499/path-with-maximum-probability" + }, + { + "problemName": "1515. Best Position for a Service Centre", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/best-position-for-a-service-centre", + "solutionLink": "#" + }, + { + "problemName": "1516. Move Sub-Tree of N-Ary Tree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/move-sub-tree-of-n-ary-tree", + "solutionLink": "#" + }, + { + "problemName": "1517. Find Users With Valid E-Mails", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-users-with-valid-e-mails", + "solutionLink": "#" + }, + { + "problemName": "1518. Water Bottles", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/water-bottles", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/water-bottles" + }, + { + "problemName": "1519. Number of Nodes in the Sub-Tree With the Same Label", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label", + "solutionLink": "#" + }, + { + "problemName": "1520. Maximum Number of Non-Overlapping Substrings", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-non-overlapping-substrings", + "solutionLink": "#" + }, + { + "problemName": "1521. Find a Value of a Mysterious Function Closest to Target", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-a-value-of-a-mysterious-function-closest-to-target", + "solutionLink": "#" + }, + { + "problemName": "1522. Diameter of N-Ary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/diameter-of-n-ary-tree", + "solutionLink": "#" + }, + { + "problemName": "1523. Count Odd Numbers in an Interval Range", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-odd-numbers-in-an-interval-range", + "solutionLink": "#" + }, + { + "problemName": "1524. Number of Sub-arrays With Odd Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum", + "solutionLink": "#" + }, + { + "problemName": "1525. Number of Good Ways to Split a String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-good-ways-to-split-a-string", + "solutionLink": "#" + }, + { + "problemName": "1526. Minimum Number of Increments on Subarrays to Form a Target Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array", + "solutionLink": "#" + }, + { + "problemName": "1527. Patients With a Condition", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/patients-with-a-condition", + "solutionLink": "#" + }, + { + "problemName": "1528. Shuffle String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/shuffle-string", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/shuffle-string" + }, + { + "problemName": "1529. Bulb Switcher IV", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/bulb-switcher-iv", + "solutionLink": "#" + }, + { + "problemName": "1530. Number of Good Leaf Nodes Pairs", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-good-leaf-nodes-pairs", + "solutionLink": "#" + }, + { + "problemName": "1531. String Compression II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/string-compression-ii", + "solutionLink": "#" + }, + { + "problemName": "1532. The Most Recent Three Orders", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-most-recent-three-orders", + "solutionLink": "#" + }, + { + "problemName": "1533. Find the Index of the Large Integer", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-index-of-the-large-integer", + "solutionLink": "#" + }, + { + "problemName": "1534. Count Good Triplets", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-good-triplets", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/count-good-triplets" + }, + { + "problemName": "1535. Find the Winner of an Array Game", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-winner-of-an-array-game", + "solutionLink": "#" + }, + { + "problemName": "1536. Minimum Swaps to Arrange a Binary Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid", + "solutionLink": "#" + }, + { + "problemName": "1537. Get the Maximum Score", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/get-the-maximum-score", + "solutionLink": "#" + }, + { + "problemName": "1538. Guess the Majority in a Hidden Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/guess-the-majority-in-a-hidden-array", + "solutionLink": "#" + }, + { + "problemName": "1539. Kth Missing Positive Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/kth-missing-positive-number", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/kth-missing-positive-number" + }, + { + "problemName": "1540. Can Convert String in K Moves", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/can-convert-string-in-k-moves", + "solutionLink": "#" + }, + { + "problemName": "1541. Minimum Insertions to Balance a Parentheses String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string", + "solutionLink": "#" + }, + { + "problemName": "1542. Find Longest Awesome Substring", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-longest-awesome-substring", + "solutionLink": "#" + }, + { + "problemName": "1543. Fix Product Name Format", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/fix-product-name-format", + "solutionLink": "#" + }, + { + "problemName": "1544. Make The String Great", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/make-the-string-great", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/make-the-string-great" + }, + { + "problemName": "1545. Find Kth Bit in Nth Binary String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-kth-bit-in-nth-binary-string", + "solutionLink": "#" + }, + { + "problemName": "1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target", + "solutionLink": "#" + }, + { + "problemName": "1547. Minimum Cost to Cut a Stick", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-cut-a-stick", + "solutionLink": "#" + }, + { + "problemName": "1548. The Most Similar Path in a Graph", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/the-most-similar-path-in-a-graph", + "solutionLink": "#" + }, + { + "problemName": "1549. The Most Recent Orders for Each Product", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-most-recent-orders-for-each-product", + "solutionLink": "#" + }, + { + "problemName": "1550. Three Consecutive Odds", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/three-consecutive-odds", + "solutionLink": "#" + }, + { + "problemName": "1551. Minimum Operations to Make Array Equal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-make-array-equal", + "solutionLink": "#" + }, + { + "problemName": "1552. Magnetic Force Between Two Balls", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/magnetic-force-between-two-balls", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/magnetic-force-between-two-balls" + }, + { + "problemName": "1553. Minimum Number of Days to Eat N Oranges", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges", + "solutionLink": "#" + }, + { + "problemName": "1554. Strings Differ by One Character", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/strings-differ-by-one-character", + "solutionLink": "#" + }, + { + "problemName": "1555. Bank Account Summary II", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/bank-account-summary-ii", + "solutionLink": "#" + }, + { + "problemName": "1556. Thousand Separator", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/thousand-separator", + "solutionLink": "#" + }, + { + "problemName": "1557. Minimum Number of Vertices to Reach All Nodes", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes", + "solutionLink": "#" + }, + { + "problemName": "1558. Minimum Numbers of Function Calls to Make Target Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array", + "solutionLink": "#" + }, + { + "problemName": "1559. Detect Cycles in 2D Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/detect-cycles-in-2d-grid", + "solutionLink": "#" + }, + { + "problemName": "1560. Most Visited Sector in a Circular Track", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/most-visited-sector-in-a-circular-track", + "solutionLink": "#" + }, + { + "problemName": "1561. Maximum Number of Coins You Can Get", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-coins-you-can-get", + "solutionLink": "#" + }, + { + "problemName": "1562. Find Latest Group of Size M", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-latest-group-of-size-m", + "solutionLink": "#" + }, + { + "problemName": "1563. Stone Game V", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/stone-game-v", + "solutionLink": "#" + }, + { + "problemName": "1564. Put Boxes Into the Warehouse I", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/put-boxes-into-the-warehouse-i", + "solutionLink": "#" + }, + { + "problemName": "1565. Unique Orders and Customers Per Month", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/unique-orders-and-customers-per-month", + "solutionLink": "#" + }, + { + "problemName": "1566. Detect Pattern of Length M Repeated K or More Times", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/detect-pattern" + }, + { + "problemName": "1567. Maximum Length of Subarray With Positive Product", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/maximum-length-of-subarray-with-positive-product" + }, + { + "problemName": "1568. Minimum Number of Days to Disconnect Island", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island", + "solutionLink": "#" + }, + { + "problemName": "1569. Number of Ways to Reorder Array to Get Same BST", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst", + "solutionLink": "#" + }, + { + "problemName": "1570. Dot Product of Two Sparse Vectors", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/dot-product-of-two-sparse-vectors", + "solutionLink": "#" + }, + { + "problemName": "1571. Warehouse Manager", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/warehouse-manager", + "solutionLink": "#" + }, + { + "problemName": "1572. Matrix Diagonal Sum", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/matrix-diagonal-sum", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/matrix-diagonal-sum" + }, + { + "problemName": "1573. Number of Ways to Split a String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-split-a-string", + "solutionLink": "#" + }, + { + "problemName": "1574. Shortest Subarray to be Removed to Make Array Sorted", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted", + "solutionLink": "#" + }, + { + "problemName": "1575. Count All Possible Routes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-all-possible-routes", + "solutionLink": "#" + }, + { + "problemName": "1576. Replace All ?'s to Avoid Consecutive Repeating Characters", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/replace-all-s-to-avoid-consecutive-repeating-characters" + }, + { + "problemName": "1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers", + "solutionLink": "#" + }, + { + "problemName": "1578. Minimum Deletion Cost to Avoid Repeating Letters", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-deletion-cost-to-avoid-repeating-letters", + "solutionLink": "#" + }, + { + "problemName": "1579. Remove Max Number of Edges to Keep Graph Fully Traversable", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable", + "solutionLink": "#" + }, + { + "problemName": "1580. Put Boxes Into the Warehouse II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/put-boxes-into-the-warehouse-ii", + "solutionLink": "#" + }, + { + "problemName": "1581. Customer Who Visited but Did Not Make Any Transactions", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/customer-who-visited-but-did-not-make-any-transactions", + "solutionLink": "#" + }, + { + "problemName": "1582. Special Positions in a Binary Matrix", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/special-positions-in-a-binary-matrix", + "solutionLink": "#" + }, + { + "problemName": "1583. Count Unhappy Friends", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-unhappy-friends", + "solutionLink": "#" + }, + { + "problemName": "1584. Min Cost to Connect All Points", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/min-cost-to-connect-all-points", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/min-cost-to-connect-all-points" + }, + { + "problemName": "1585. Check If String Is Transformable With Substring Sort Operations", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/check-if-string-is-transformable-with-substring-sort-operations", + "solutionLink": "#" + }, + { + "problemName": "1586. Binary Search Tree Iterator II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/binary-search-tree-iterator-ii", + "solutionLink": "#" + }, + { + "problemName": "1587. Bank Account Summary III", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/bank-account-summary-iii", + "solutionLink": "#" + }, + { + "problemName": "1588. Sum of All Odd Length Subarrays", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sum-of-all-odd-length-subarrays", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/sum-of-all-odd-length-subarrays" + }, + { + "problemName": "1589. Maximum Sum Obtained of Any Permutation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-sum-obtained-of-any-permutation", + "solutionLink": "#" + }, + { + "problemName": "1590. Make Sum Divisible by P", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/make-sum-divisible-by-p", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/make-sum-divisible-by-p" + }, + { + "problemName": "1591. Strange Printer II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/strange-printer-ii", + "solutionLink": "#" + }, + { + "problemName": "1592. Rearrange Spaces Between Words", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/rearrange-spaces-between-words", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/rearrange-spaces-between-words" + }, + { + "problemName": "1593. Split a String Into the Max Number of Unique Substrings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/split-a-string-into-the-max-number-of-unique-substrings" + }, + { + "problemName": "1594. Maximum Non Negative Product in a Matrix", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/maximum-non-negative-product-in-a-matrix" + }, + { + "problemName": "1595. Minimum Cost to Connect Two Groups of Points", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/Minimum Cost to Connect Two Groups of Points" + }, + { + "problemName": "1596. The Most Frequently Ordered Products for Each Customer", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-most-frequently-ordered-products-for-each-customer", + "solutionLink": "#" + }, + { + "problemName": "1597. Build Binary Expression Tree From Infix Expression", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/build-binary-expression-tree-from-infix-expression", + "solutionLink": "#" + }, + { + "problemName": "1598. Crawler Log Folder", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/crawler-log-folder", + "solutionLink": "/dsa-solutions/lc-solutions/1500-1599/crawler-log-folder" + }, + { + "problemName": "1599. Maximum Profit of Operating a Centennial Wheel", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-profit-of-operating-a-centennial-wheel", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/1600-1699.md b/problems/leetcode-problems/1600-1699.md new file mode 100644 index 0000000..5a7814a --- /dev/null +++ b/problems/leetcode-problems/1600-1699.md @@ -0,0 +1,622 @@ +--- +id: 1600-1699 +title: LeetCode Problems 1600 - 1699 +sidebar_label: 1600 - 1699 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 1600 - 1699 + - DSA problems +--- + +export const problems = [ + { + "problemName": "1600. Throne Inheritance", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/throne-inheritance", + "solutionLink": "#" + }, + { + "problemName": "1601. Maximum Number of Achievable Transfer Requests", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests", + "solutionLink": "#" + }, + { + "problemName": "1602. Find Nearest Right Node in Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-nearest-right-node-in-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "1603. Design Parking System", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/design-parking-system", + "solutionLink": "#" + }, + { + "problemName": "1604. Alert Using Same Key-Card Three or More Times in a One Hour Period", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period", + "solutionLink": "#" + }, + { + "problemName": "1605. Find Valid Matrix Given Row and Column Sums", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums", + "solutionLink": "#" + }, + { + "problemName": "1606. Find Servers That Handled Most Number of Requests", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-servers-that-handled-most-number-of-requests", + "solutionLink": "#" + }, + { + "problemName": "1607. Sellers With No Sales", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sellers-with-no-sales", + "solutionLink": "#" + }, + { + "problemName": "1608. Special Array With X Elements Greater Than or Equal X", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x", + "solutionLink": "#" + }, + { + "problemName": "1609. Even Odd Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/even-odd-tree", + "solutionLink": "/dsa-solutions/lc-solutions/1600-1699/even-odd-tree" + }, + { + "problemName": "1610. Maximum Number of Visible Points", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-visible-points", + "solutionLink": "#" + }, + { + "problemName": "1611. Minimum One Bit Operations to Make Integers Zero", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero", + "solutionLink": "#" + }, + { + "problemName": "1612. Check If Two Expression Trees are Equivalent", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-two-expression-trees-are-equivalent", + "solutionLink": "#" + }, + { + "problemName": "1613. Find the Missing IDs", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-missing-ids", + "solutionLink": "#" + }, + { + "problemName": "1614. Maximum Nesting Depth of the Parentheses", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses", + "solutionLink": "#" + }, + { + "problemName": "1615. Maximal Network Rank", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximal-network-rank", + "solutionLink": "#" + }, + { + "problemName": "1616. Split Two Strings to Make Palindrome", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/split-two-strings-to-make-palindrome", + "solutionLink": "#" + }, + { + "problemName": "1617. Count Subtrees With Max Distance Between Cities", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities", + "solutionLink": "#" + }, + { + "problemName": "1618. Maximum Font to Fit a Sentence in a Screen", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-font-to-fit-a-sentence-in-a-screen", + "solutionLink": "#" + }, + { + "problemName": "1619. Mean of Array After Removing Some Elements", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/mean-of-array-after-removing-some-elements", + "solutionLink": "#" + }, + { + "problemName": "1620. Coordinate With Maximum Network Quality", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/coordinate-with-maximum-network-quality", + "solutionLink": "#" + }, + { + "problemName": "1621. Number of Sets of K Non-Overlapping Line Segments", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-sets-of-k-non-overlapping-line-segments", + "solutionLink": "#" + }, + { + "problemName": "1622. Fancy Sequence", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/fancy-sequence", + "solutionLink": "/dsa-solutions/lc-solutions/1600-1699/fancy-sequence" + }, + { + "problemName": "1623. All Valid Triplets That Can Represent a Country", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/all-valid-triplets-that-can-represent-a-country", + "solutionLink": "#" + }, + { + "problemName": "1624. Largest Substring Between Two Equal Characters", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/largest-substring-between-two-equal-characters", + "solutionLink": "#" + }, + { + "problemName": "1625. Lexicographically Smallest String After Applying Operations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations", + "solutionLink": "#" + }, + { + "problemName": "1626. Best Team With No Conflicts", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/best-team-with-no-conflicts", + "solutionLink": "#" + }, + { + "problemName": "1627. Graph Connectivity With Threshold", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/graph-connectivity-with-threshold", + "solutionLink": "#" + }, + { + "problemName": "1628. Design an Expression Tree With Evaluate Function", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-an-expression-tree-with-evaluate-function", + "solutionLink": "#" + }, + { + "problemName": "1629. Slowest Key", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/slowest-key", + "solutionLink": "#" + }, + { + "problemName": "1630. Arithmetic Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/arithmetic-subarrays", + "solutionLink": "#" + }, + { + "problemName": "1631. Path With Minimum Effort", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/path-with-minimum-effort", + "solutionLink": "/dsa-solutions/lc-solutions/1600-1699/path-with-minimum-effort" + }, + { + "problemName": "1632. Rank Transform of a Matrix", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/rank-transform-of-a-matrix", + "solutionLink": "#" + }, + { + "problemName": "1633. Percentage of Users Attended a Contest", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/percentage-of-users-attended-a-contest", + "solutionLink": "#" + }, + { + "problemName": "1634. Add Two Polynomials Represented as Linked Lists", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/add-two-polynomials-represented-as-linked-lists", + "solutionLink": "#" + }, + { + "problemName": "1635. Hopper Company Queries I", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/hopper-company-queries-i", + "solutionLink": "#" + }, + { + "problemName": "1636. Sort Array by Increasing Frequency", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sort-array-by-increasing-frequency", + "solutionLink": "#" + }, + { + "problemName": "1637. Widest Vertical Area Between Two Points Containing No Points", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points", + "solutionLink": "#" + }, + { + "problemName": "1638. Count Substrings That Differ by One Character", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-substrings-that-differ-by-one-character", + "solutionLink": "#" + }, + { + "problemName": "1639. Number of Ways to Form a Target String Given a Dictionary", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary", + "solutionLink": "#" + }, + { + "problemName": "1640. Check Array Formation Through Concatenation", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-array-formation-through-concatenation", + "solutionLink": "#" + }, + { + "problemName": "1641. Count Sorted Vowel Strings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-sorted-vowel-strings", + "solutionLink": "#" + }, + { + "problemName": "1642. Furthest Building You Can Reach", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/furthest-building-you-can-reach", + "solutionLink": "#" + }, + { + "problemName": "1643. Kth Smallest Instructions", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/kth-smallest-instructions", + "solutionLink": "#" + }, + { + "problemName": "1644. Lowest Common Ancestor of a Binary Tree II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-ii", + "solutionLink": "#" + }, + { + "problemName": "1645. Hopper Company Queries II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/hopper-company-queries-ii", + "solutionLink": "#" + }, + { + "problemName": "1646. Get Maximum in Generated Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/get-maximum-in-generated-array", + "solutionLink": "#" + }, + { + "problemName": "1647. Minimum Deletions to Make Character Frequencies Unique", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique", + "solutionLink": "#" + }, + { + "problemName": "1648. Sell Diminishing-Valued Colored Balls", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sell-diminishing-valued-colored-balls", + "solutionLink": "#" + }, + { + "problemName": "1649. Create Sorted Array through Instructions", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/create-sorted-array-through-instructions", + "solutionLink": "#" + }, + { + "problemName": "1650. Lowest Common Ancestor of a Binary Tree III", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-iii", + "solutionLink": "#" + }, + { + "problemName": "1651. Hopper Company Queries III", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/hopper-company-queries-iii", + "solutionLink": "#" + }, + { + "problemName": "1652. Defuse the Bomb", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/defuse-the-bomb", + "solutionLink": "#" + }, + { + "problemName": "1653. Minimum Deletions to Make String Balanced", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-deletions-to-make-string-balanced", + "solutionLink": "#" + }, + { + "problemName": "1654. Minimum Jumps to Reach Home", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-jumps-to-reach-home", + "solutionLink": "#" + }, + { + "problemName": "1655. Distribute Repeating Integers", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/distribute-repeating-integers", + "solutionLink": "#" + }, + { + "problemName": "1656. Design an Ordered Stream", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/design-an-ordered-stream", + "solutionLink": "#" + }, + { + "problemName": "1657. Determine if Two Strings Are Close", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/determine-if-two-strings-are-close", + "solutionLink": "#" + }, + { + "problemName": "1658. Minimum Operations to Reduce X to Zero", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero", + "solutionLink": "#" + }, + { + "problemName": "1659. Maximize Grid Happiness", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximize-grid-happiness", + "solutionLink": "#" + }, + { + "problemName": "1660. Correct a Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/correct-a-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "1661. Average Time of Process per Machine", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/average-time-of-process-per-machine", + "solutionLink": "#" + }, + { + "problemName": "1662. Check If Two String Arrays are Equivalent", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent", + "solutionLink": "#" + }, + { + "problemName": "1663. Smallest String With A Given Numeric Value", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/smallest-string-with-a-given-numeric-value", + "solutionLink": "#" + }, + { + "problemName": "1664. Ways to Make a Fair Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/ways-to-make-a-fair-array", + "solutionLink": "#" + }, + { + "problemName": "1665. Minimum Initial Energy to Finish Tasks", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-initial-energy-to-finish-tasks", + "solutionLink": "#" + }, + { + "problemName": "1666. Change the Root of a Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/change-the-root-of-a-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "1667. Fix Names in a Table", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/fix-names-in-a-table", + "solutionLink": "#" + }, + { + "problemName": "1668. Maximum Repeating Substring", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-repeating-substring", + "solutionLink": "#" + }, + { + "problemName": "1669. Merge In Between Linked Lists", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/merge-in-between-linked-lists", + "solutionLink": "#" + }, + { + "problemName": "1670. Design Front Middle Back Queue", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-front-middle-back-queue", + "solutionLink": "/dsa-solutions/lc-solutions/1600-1699/design-front-middle-back-queue" + }, + { + "problemName": "1671. Minimum Number of Removals to Make Mountain Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array", + "solutionLink": "#" + }, + { + "problemName": "1672. Richest Customer Wealth", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/richest-customer-wealth", + "solutionLink": "#" + }, + { + "problemName": "1673. Find the Most Competitive Subsequence", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-most-competitive-subsequence", + "solutionLink": "#" + }, + { + "problemName": "1674. Minimum Moves to Make Array Complementary", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-moves-to-make-array-complementary", + "solutionLink": "#" + }, + { + "problemName": "1675. Minimize Deviation in Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimize-deviation-in-array", + "solutionLink": "#" + }, + { + "problemName": "1676. Lowest Common Ancestor of a Binary Tree IV", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-iv", + "solutionLink": "#" + }, + { + "problemName": "1677. Product's Worth Over Invoices", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/products-worth-over-invoices", + "solutionLink": "#" + }, + { + "problemName": "1678. Goal Parser Interpretation", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/goal-parser-interpretation", + "solutionLink": "#" + }, + { + "problemName": "1679. Max Number of K-Sum Pairs", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/max-number-of-k-sum-pairs", + "solutionLink": "/dsa-solutions/lc-solutions/1600-1699/design-front-middle-back-queue" + }, + { + "problemName": "1680. Concatenation of Consecutive Binary Numbers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers", + "solutionLink": "#" + }, + { + "problemName": "1681. Minimum Incompatibility", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-incompatibility", + "solutionLink": "#" + }, + { + "problemName": "1682. Longest Palindromic Subsequence II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-palindromic-subsequence-ii", + "solutionLink": "#" + }, + { + "problemName": "1683. Invalid Tweets", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/invalid-tweets", + "solutionLink": "#" + }, + { + "problemName": "1684. Count the Number of Consistent Strings", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-consistent-strings", + "solutionLink": "#" + }, + { + "problemName": "1685. Sum of Absolute Differences in a Sorted Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array", + "solutionLink": "#" + }, + { + "problemName": "1686. Stone Game VI", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/stone-game-vi", + "solutionLink": "#" + }, + { + "problemName": "1687. Delivering Boxes from Storage to Ports", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/delivering-boxes-from-storage-to-ports", + "solutionLink": "#" + }, + { + "problemName": "1688. Count of Matches in Tournament", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-of-matches-in-tournament", + "solutionLink": "#" + }, + { + "problemName": "1689. Partitioning Into Minimum Number Of Deci-Binary Numbers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers", + "solutionLink": "#" + }, + { + "problemName": "1690. Stone Game VII", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/stone-game-vii", + "solutionLink": "#" + }, + { + "problemName": "1691. Maximum Height by Stacking Cuboids", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-height-by-stacking-cuboids", + "solutionLink": "#" + }, + { + "problemName": "1692. Count Ways to Distribute Candies", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-ways-to-distribute-candies", + "solutionLink": "#" + }, + { + "problemName": "1693. Daily Leads and Partners", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/daily-leads-and-partners", + "solutionLink": "#" + }, + { + "problemName": "1694. Reformat Phone Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/reformat-phone-number", + "solutionLink": "#" + }, + { + "problemName": "1695. Maximum Erasure Value", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-erasure-value", + "solutionLink": "#" + }, + { + "problemName": "1696. Jump Game VI", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/jump-game-vi", + "solutionLink": "#" + }, + { + "problemName": "1697. Checking Existence of Edge Length Limited Paths", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths", + "solutionLink": "#" + }, + { + "problemName": "1698. Number of Distinct Substrings in a String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-distinct-substrings-in-a-string", + "solutionLink": "#" + }, + { + "problemName": "1699. Number of Calls Between Two Persons", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-calls-between-two-persons", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/1700-1799.md b/problems/leetcode-problems/1700-1799.md new file mode 100644 index 0000000..4066d04 --- /dev/null +++ b/problems/leetcode-problems/1700-1799.md @@ -0,0 +1,622 @@ +--- +id: 1700-1799 +title: LeetCode Problems 1700 - 1799 +sidebar_label: 1700 - 1799 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 1700 - 1799 + - DSA problems +--- + +export const problems = [ + { + "problemName": "1700. Number of Students Unable to Eat Lunch", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-students-unable-to-eat-lunch", + "solutionLink": "#" + }, + { + "problemName": "1701. Average Waiting Time", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/average-waiting-time", + "solutionLink": "#" + }, + { + "problemName": "1702. Maximum Binary String After Change", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-binary-string-after-change", + "solutionLink": "#" + }, + { + "problemName": "1703. Minimum Adjacent Swaps for K Consecutive Ones", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones", + "solutionLink": "#" + }, + { + "problemName": "1704. Determine if String Halves Are Alike", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/determine-if-string-halves-are-alike", + "solutionLink": "#" + }, + { + "problemName": "1705. Maximum Number of Eaten Apples", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-eaten-apples", + "solutionLink": "#" + }, + { + "problemName": "1706. Where Will the Ball Fall", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/where-will-the-ball-fall", + "solutionLink": "#" + }, + { + "problemName": "1707. Maximum XOR With an Element From Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-xor-with-an-element-from-array", + "solutionLink": "#" + }, + { + "problemName": "1708. Largest Subarray Length K", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/largest-subarray-length-k", + "solutionLink": "#" + }, + { + "problemName": "1709. Biggest Window Between Visits", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/biggest-window-between-visits", + "solutionLink": "#" + }, + { + "problemName": "1710. Maximum Units on a Truck", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-units-on-a-truck", + "solutionLink": "#" + }, + { + "problemName": "1711. Count Good Meals", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-good-meals", + "solutionLink": "#" + }, + { + "problemName": "1712. Ways to Split Array Into Three Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/ways-to-split-array-into-three-subarrays", + "solutionLink": "#" + }, + { + "problemName": "1713. Minimum Operations to Make a Subsequence", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-make-a-subsequence", + "solutionLink": "#" + }, + { + "problemName": "1714. Sum Of Special Evenly-Spaced Elements In Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sum-of-special-evenly-spaced-elements-in-array", + "solutionLink": "#" + }, + { + "problemName": "1715. Count Apples and Oranges", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-apples-and-oranges", + "solutionLink": "#" + }, + { + "problemName": "1716. Calculate Money in Leetcode Bank", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/calculate-money-in-leetcode-bank", + "solutionLink": "#" + }, + { + "problemName": "1717. Maximum Score From Removing Substrings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-score-from-removing-substrings", + "solutionLink": "/dsa-solutions/lc-solutions/1700-1799/maximum-score-from-removing-substrings" + }, + { + "problemName": "1718. Construct the Lexicographically Largest Valid Sequence", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence", + "solutionLink": "#" + }, + { + "problemName": "1719. Number Of Ways To Reconstruct A Tree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-reconstruct-a-tree", + "solutionLink": "#" + }, + { + "problemName": "1720. Decode XORed Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/decode-xored-array", + "solutionLink": "#" + }, + { + "problemName": "1721. Swapping Nodes in a Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/swapping-nodes-in-a-linked-list", + "solutionLink": "#" + }, + { + "problemName": "1722. Minimize Hamming Distance After Swap Operations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations", + "solutionLink": "#" + }, + { + "problemName": "1723. Find Minimum Time to Finish All Jobs", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs", + "solutionLink": "#" + }, + { + "problemName": "1724. Checking Existence of Edge Length Limited Paths II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths-ii", + "solutionLink": "#" + }, + { + "problemName": "1725. Number Of Rectangles That Can Form The Largest Square", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square", + "solutionLink": "#" + }, + { + "problemName": "1726. Tuple with Same Product", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/tuple-with-same-product", + "solutionLink": "/dsa-solutions/lc-solutions/1700-1799/tuple-with-same-product" + }, + { + "problemName": "1727. Largest Submatrix With Rearrangements", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/largest-submatrix-with-rearrangements", + "solutionLink": "#" + }, + { + "problemName": "1728. Cat and Mouse II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/cat-and-mouse-ii", + "solutionLink": "#" + }, + { + "problemName": "1729. Find Followers Count", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-followers-count", + "solutionLink": "#" + }, + { + "problemName": "1730. Shortest Path to Get Food", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shortest-path-to-get-food", + "solutionLink": "#" + }, + { + "problemName": "1731. The Number of Employees Which Report to Each Employee", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/the-number-of-employees-which-report-to-each-employee", + "solutionLink": "#" + }, + { + "problemName": "1732. Find the Highest Altitude", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-highest-altitude", + "solutionLink": "#" + }, + { + "problemName": "1733. Minimum Number of People to Teach", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-people-to-teach", + "solutionLink": "#" + }, + { + "problemName": "1734. Decode XORed Permutation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/decode-xored-permutation", + "solutionLink": "#" + }, + { + "problemName": "1735. Count Ways to Make Array With Product", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-ways-to-make-array-with-product", + "solutionLink": "#" + }, + { + "problemName": "1736. Latest Time by Replacing Hidden Digits", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/latest-time-by-replacing-hidden-digits", + "solutionLink": "#" + }, + { + "problemName": "1737. Change Minimum Characters to Satisfy One of Three Conditions", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/change-minimum-characters-to-satisfy-one-of-three-conditions", + "solutionLink": "#" + }, + { + "problemName": "1738. Find Kth Largest XOR Coordinate Value", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-kth-largest-xor-coordinate-value", + "solutionLink": "#" + }, + { + "problemName": "1739. Building Boxes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/building-boxes", + "solutionLink": "#" + }, + { + "problemName": "1740. Find Distance in a Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-distance-in-a-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "1741. Find Total Time Spent by Each Employee", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-total-time-spent-by-each-employee", + "solutionLink": "#" + }, + { + "problemName": "1742. Maximum Number of Balls in a Box", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-balls-in-a-box", + "solutionLink": "#" + }, + { + "problemName": "1743. Restore the Array From Adjacent Pairs", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/restore-the-array-from-adjacent-pairs", + "solutionLink": "#" + }, + { + "problemName": "1744. Can You Eat Your Favorite Candy on Your Favorite Day?", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day", + "solutionLink": "#" + }, + { + "problemName": "1745. Palindrome Partitioning IV", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/palindrome-partitioning-iv", + "solutionLink": "#" + }, + { + "problemName": "1746. Maximum Subarray Sum After One Operation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-subarray-sum-after-one-operation", + "solutionLink": "#" + }, + { + "problemName": "1747. Leetflex Banned Accounts", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/leetflex-banned-accounts", + "solutionLink": "#" + }, + { + "problemName": "1748. Sum of Unique Elements", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sum-of-unique-elements", + "solutionLink": "#" + }, + { + "problemName": "1749. Maximum Absolute Sum of Any Subarray", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray", + "solutionLink": "#" + }, + { + "problemName": "1750. Minimum Length of String After Deleting Similar Ends", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends", + "solutionLink": "#" + }, + { + "problemName": "1751. Maximum Number of Events That Can Be Attended II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii", + "solutionLink": "#" + }, + { + "problemName": "1752. Check if Array Is Sorted and Rotated", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-array-is-sorted-and-rotated", + "solutionLink": "#" + }, + { + "problemName": "1753. Maximum Score From Removing Stones", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-score-from-removing-stones", + "solutionLink": "#" + }, + { + "problemName": "1754. Largest Merge Of Two Strings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/largest-merge-of-two-strings", + "solutionLink": "#" + }, + { + "problemName": "1755. Closest Subsequence Sum", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/closest-subsequence-sum", + "solutionLink": "#" + }, + { + "problemName": "1756. Design Most Recently Used Queue", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-most-recently-used-queue", + "solutionLink": "#" + }, + { + "problemName": "1757. Recyclable and Low Fat Products", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/recyclable-and-low-fat-products", + "solutionLink": "#" + }, + { + "problemName": "1758. Minimum Changes To Make Alternating Binary String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string", + "solutionLink": "#" + }, + { + "problemName": "1759. Count Number of Homogenous Substrings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-number-of-homogenous-substrings", + "solutionLink": "#" + }, + { + "problemName": "1760. Minimum Limit of Balls in a Bag", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag", + "solutionLink": "#" + }, + { + "problemName": "1761. Minimum Degree of a Connected Trio in a Graph", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph", + "solutionLink": "#" + }, + { + "problemName": "1762. Buildings With an Ocean View", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/buildings-with-an-ocean-view", + "solutionLink": "#" + }, + { + "problemName": "1763. Longest Nice Substring", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/longest-nice-substring", + "solutionLink": "#" + }, + { + "problemName": "1764. Form Array by Concatenating Subarrays of Another Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array", + "solutionLink": "#" + }, + { + "problemName": "1765. Map of Highest Peak", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/map-of-highest-peak", + "solutionLink": "#" + }, + { + "problemName": "1766. Tree of Coprimes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/tree-of-coprimes", + "solutionLink": "#" + }, + { + "problemName": "1767. Find the Subtasks That Did Not Execute", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-the-subtasks-that-did-not-execute", + "solutionLink": "#" + }, + { + "problemName": "1768. Merge Strings Alternately", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/merge-strings-alternately", + "solutionLink": "#" + }, + { + "problemName": "1769. Minimum Number of Operations to Move All Balls to Each Box", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box", + "solutionLink": "#" + }, + { + "problemName": "1770. Maximum Score from Performing Multiplication Operations", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations", + "solutionLink": "#" + }, + { + "problemName": "1771. Maximize Palindrome Length From Subsequences", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximize-palindrome-length-from-subsequences", + "solutionLink": "#" + }, + { + "problemName": "1772. Sort Features by Popularity", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sort-features-by-popularity", + "solutionLink": "#" + }, + { + "problemName": "1773. Count Items Matching a Rule", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-items-matching-a-rule", + "solutionLink": "#" + }, + { + "problemName": "1774. Closest Dessert Cost", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/closest-dessert-cost", + "solutionLink": "#" + }, + { + "problemName": "1775. Equal Sum Arrays With Minimum Number of Operations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations", + "solutionLink": "#" + }, + { + "problemName": "1776. Car Fleet II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/car-fleet-ii", + "solutionLink": "#" + }, + { + "problemName": "1777. Product's Price for Each Store", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/products-price-for-each-store", + "solutionLink": "#" + }, + { + "problemName": "1778. Shortest Path in a Hidden Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shortest-path-in-a-hidden-grid", + "solutionLink": "#" + }, + { + "problemName": "1779. Find Nearest Point That Has the Same X or Y Coordinate", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate", + "solutionLink": "#" + }, + { + "problemName": "1780. Check if Number is a Sum of Powers of Three", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-number-is-a-sum-of-powers-of-three", + "solutionLink": "#" + }, + { + "problemName": "1781. Sum of Beauty of All Substrings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-of-beauty-of-all-substrings", + "solutionLink": "/dsa-solutions/lc-solutions/1700-1799/sum-of-beauty-of-all-substrings" + }, + { + "problemName": "1782. Count Pairs Of Nodes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-pairs-of-nodes", + "solutionLink": "#" + }, + { + "problemName": "1783. Grand Slam Titles", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/grand-slam-titles", + "solutionLink": "#" + }, + { + "problemName": "1784. Check if Binary String Has at Most One Segment of Ones", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones", + "solutionLink": "#" + }, + { + "problemName": "1785. Minimum Elements to Add to Form a Given Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-elements-to-add-to-form-a-given-sum", + "solutionLink": "#" + }, + { + "problemName": "1786. Number of Restricted Paths From First to Last Node", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node", + "solutionLink": "#" + }, + { + "problemName": "1787. Make the XOR of All Segments Equal to Zero", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/make-the-xor-of-all-segments-equal-to-zero", + "solutionLink": "#" + }, + { + "problemName": "1788. Maximize the Beauty of the Garden", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximize-the-beauty-of-the-garden", + "solutionLink": "#" + }, + { + "problemName": "1789. Primary Department for Each Employee", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/primary-department-for-each-employee", + "solutionLink": "#" + }, + { + "problemName": "1790. Check if One String Swap Can Make Strings Equal", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal", + "solutionLink": "#" + }, + { + "problemName": "1791. Find Center of Star Graph", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-center-of-star-graph", + "solutionLink": "/dsa-solutions/lc-solutions/1700-1799/find-center-of-star-graph" + }, + { + "problemName": "1792. Maximum Average Pass Ratio", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-average-pass-ratio", + "solutionLink": "#" + }, + { + "problemName": "1793. Maximum Score of a Good Subarray", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-score-of-a-good-subarray", + "solutionLink": "#" + }, + { + "problemName": "1794. Count Pairs of Equal Substrings With Minimum Difference", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-pairs-of-equal-substrings-with-minimum-difference", + "solutionLink": "#" + }, + { + "problemName": "1795. Rearrange Products Table", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/rearrange-products-table", + "solutionLink": "#" + }, + { + "problemName": "1796. Second Largest Digit in a String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/second-largest-digit-in-a-string", + "solutionLink": "#" + }, + { + "problemName": "1797. Design Authentication Manager", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-authentication-manager", + "solutionLink": "#" + }, + { + "problemName": "1798. Maximum Number of Consecutive Values You Can Make", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make", + "solutionLink": "#" + }, + { + "problemName": "1799. Maximize Score After N Operations", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximize-score-after-n-operations", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/1800-1899.md b/problems/leetcode-problems/1800-1899.md new file mode 100644 index 0000000..c05965d --- /dev/null +++ b/problems/leetcode-problems/1800-1899.md @@ -0,0 +1,622 @@ +--- +id: 1800-1899 +title: LeetCode Problems 1800 - 1899 +sidebar_label: 1800 - 1899 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 1800 - 1899 + - DSA problems +--- + +export const problems = [ + { + "problemName": "1800. Maximum Ascending Subarray Sum", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-ascending-subarray-sum", + "solutionLink": "/dsa-solutions/lc-solutions/1800-1899/maximum-ascending-subarray-sum" + }, + { + "problemName": "1801. Number of Orders in the Backlog", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-orders-in-the-backlog", + "solutionLink": "#" + }, + { + "problemName": "1802. Maximum Value at a Given Index in a Bounded Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array", + "solutionLink": "#" + }, + { + "problemName": "1803. Count Pairs With XOR in a Range", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-pairs-with-xor-in-a-range", + "solutionLink": "#" + }, + { + "problemName": "1804. Implement Trie II (Prefix Tree)", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/implement-trie-ii-prefix-tree", + "solutionLink": "#" + }, + { + "problemName": "1805. Number of Different Integers in a String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-different-integers-in-a-string", + "solutionLink": "#" + }, + { + "problemName": "1806. Minimum Number of Operations to Reinitialize a Permutation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation", + "solutionLink": "#" + }, + { + "problemName": "1807. Evaluate the Bracket Pairs of a String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string", + "solutionLink": "#" + }, + { + "problemName": "1808. Maximize Number of Nice Divisors", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximize-number-of-nice-divisors", + "solutionLink": "#" + }, + { + "problemName": "1809. Ad-Free Sessions", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/ad-free-sessions", + "solutionLink": "#" + }, + { + "problemName": "1810. Minimum Path Cost in a Hidden Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-path-cost-in-a-hidden-grid", + "solutionLink": "#" + }, + { + "problemName": "1811. Find Interview Candidates", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-interview-candidates", + "solutionLink": "#" + }, + { + "problemName": "1812. Determine Color of a Chessboard Square", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/determine-color-of-a-chessboard-square", + "solutionLink": "#" + }, + { + "problemName": "1813. Sentence Similarity III", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sentence-similarity-iii", + "solutionLink": "#" + }, + { + "problemName": "1814. Count Nice Pairs in an Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-nice-pairs-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "1815. Maximum Number of Groups Getting Fresh Donuts", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-groups-getting-fresh-donuts", + "solutionLink": "#" + }, + { + "problemName": "1816. Truncate Sentence", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/truncate-sentence", + "solutionLink": "#" + }, + { + "problemName": "1817. Finding the Users Active Minutes", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/finding-the-users-active-minutes", + "solutionLink": "#" + }, + { + "problemName": "1818. Minimum Absolute Sum Difference", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-absolute-sum-difference", + "solutionLink": "#" + }, + { + "problemName": "1819. Number of Different Subsequences GCDs", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-different-subsequences-gcds", + "solutionLink": "#" + }, + { + "problemName": "1820. Maximum Number of Accepted Invitations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-accepted-invitations", + "solutionLink": "#" + }, + { + "problemName": "1821. Find Customers With Positive Revenue this Year", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-customers-with-positive-revenue-this-year", + "solutionLink": "#" + }, + { + "problemName": "1822. Sign of the Product of an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sign-of-the-product-of-an-array", + "solutionLink": "#" + }, + { + "problemName": "1823. Find the Winner of the Circular Game", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-winner-of-the-circular-game", + "solutionLink": "#" + }, + { + "problemName": "1824. Minimum Sideway Jumps", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-sideway-jumps", + "solutionLink": "#" + }, + { + "problemName": "1825. Finding MK Average", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/finding-mk-average", + "solutionLink": "#" + }, + { + "problemName": "1826. Faulty Sensor", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/faulty-sensor", + "solutionLink": "#" + }, + { + "problemName": "1827. Minimum Operations to Make the Array Increasing", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing", + "solutionLink": "#" + }, + { + "problemName": "1828. Queries on Number of Points Inside a Circle", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle", + "solutionLink": "#" + }, + { + "problemName": "1829. Maximum XOR for Each Query", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-xor-for-each-query", + "solutionLink": "#" + }, + { + "problemName": "1830. Minimum Number of Operations to Make String Sorted", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-operations-to-make-string-sorted", + "solutionLink": "#" + }, + { + "problemName": "1831. Maximum Transaction Each Day", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-transaction-each-day", + "solutionLink": "#" + }, + { + "problemName": "1832. Check if the Sentence Is Pangram", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-the-sentence-is-pangram", + "solutionLink": "/dsa-solutions/lc-solutions/1800-1899/check-if-the-sentence-is-pangram" + }, + { + "problemName": "1833. Maximum Ice Cream Bars", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-ice-cream-bars", + "solutionLink": "#" + }, + { + "problemName": "1834. Single-Threaded CPU", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/single-threaded-cpu", + "solutionLink": "#" + }, + { + "problemName": "1835. Find XOR Sum of All Pairs Bitwise AND", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-xor-sum-of-all-pairs-bitwise-and", + "solutionLink": "#" + }, + { + "problemName": "1836. Remove Duplicates From an Unsorted Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-duplicates-from-an-unsorted-linked-list", + "solutionLink": "#" + }, + { + "problemName": "1837. Sum of Digits in Base K", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sum-of-digits-in-base-k", + "solutionLink": "#" + }, + { + "problemName": "1838. Frequency of the Most Frequent Element", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/frequency-of-the-most-frequent-element", + "solutionLink": "/dsa-solutions/lc-solutions/1800-1899/frequency-of-the-most-frequent-element" + }, + { + "problemName": "1839. Longest Substring Of All Vowels in Order", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-substring-of-all-vowels-in-order", + "solutionLink": "/dsa-solutions/lc-solutions/1800-1899/longest-substring-of-all-vowels-in-order" + }, + { + "problemName": "1840. Maximum Building Height", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-building-height", + "solutionLink": "#" + }, + { + "problemName": "1841. League Statistics", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/league-statistics", + "solutionLink": "#" + }, + { + "problemName": "1842. Next Palindrome Using Same Digits", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/next-palindrome-using-same-digits", + "solutionLink": "#" + }, + { + "problemName": "1843. Suspicious Bank Accounts", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/suspicious-bank-accounts", + "solutionLink": "#" + }, + { + "problemName": "1844. Replace All Digits with Characters", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/replace-all-digits-with-characters", + "solutionLink": "#" + }, + { + "problemName": "1845. Seat Reservation Manager", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/seat-reservation-manager", + "solutionLink": "#" + }, + { + "problemName": "1846. Maximum Element After Decreasing and Rearranging", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging", + "solutionLink": "#" + }, + { + "problemName": "1847. Closest Room", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/closest-room", + "solutionLink": "#" + }, + { + "problemName": "1848. Minimum Distance to the Target Element", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-distance-to-the-target-element", + "solutionLink": "#" + }, + { + "problemName": "1849. Splitting a String Into Descending Consecutive Values", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values", + "solutionLink": "#" + }, + { + "problemName": "1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number", + "solutionLink": "#" + }, + { + "problemName": "1851. Minimum Interval to Include Each Query", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-interval-to-include-each-query", + "solutionLink": "#" + }, + { + "problemName": "1852. Distinct Numbers in Each Subarray", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/distinct-numbers-in-each-subarray", + "solutionLink": "#" + }, + { + "problemName": "1853. Convert Date Format", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/convert-date-format", + "solutionLink": "#" + }, + { + "problemName": "1854. Maximum Population Year", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-population-year", + "solutionLink": "#" + }, + { + "problemName": "1855. Maximum Distance Between a Pair of Values", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-distance-between-a-pair-of-values", + "solutionLink": "#" + }, + { + "problemName": "1856. Maximum Subarray Min-Product", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-subarray-min-product", + "solutionLink": "#" + }, + { + "problemName": "1857. Largest Color Value in a Directed Graph", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/largest-color-value-in-a-directed-graph", + "solutionLink": "#" + }, + { + "problemName": "1858. Longest Word With All Prefixes", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-word-with-all-prefixes", + "solutionLink": "#" + }, + { + "problemName": "1859. Sorting the Sentence", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sorting-the-sentence", + "solutionLink": "#" + }, + { + "problemName": "1860. Incremental Memory Leak", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/incremental-memory-leak", + "solutionLink": "#" + }, + { + "problemName": "1861. Rotating the Box", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/rotating-the-box", + "solutionLink": "#" + }, + { + "problemName": "1862. Sum of Floored Pairs", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sum-of-floored-pairs", + "solutionLink": "#" + }, + { + "problemName": "1863. Sum of All Subset XOR Totals", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sum-of-all-subset-xor-totals", + "solutionLink": "#" + }, + { + "problemName": "1864. Minimum Number of Swaps to Make the Binary String Alternating", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating", + "solutionLink": "#" + }, + { + "problemName": "1865. Finding Pairs With a Certain Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/finding-pairs-with-a-certain-sum", + "solutionLink": "#" + }, + { + "problemName": "1866. Number of Ways to Rearrange Sticks With K Sticks Visible", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible", + "solutionLink": "#" + }, + { + "problemName": "1867. Orders With Maximum Quantity Above Average", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/orders-with-maximum-quantity-above-average", + "solutionLink": "#" + }, + { + "problemName": "1868. Product of Two Run-Length Encoded Arrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/product-of-two-run-length-encoded-arrays", + "solutionLink": "#" + }, + { + "problemName": "1869. Longer Contiguous Segments of Ones than Zeros", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros", + "solutionLink": "#" + }, + { + "problemName": "1870. Minimum Speed to Arrive on Time", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-speed-to-arrive-on-time", + "solutionLink": "#" + }, + { + "problemName": "1871. Jump Game VII", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/jump-game-vii", + "solutionLink": "#" + }, + { + "problemName": "1872. Stone Game VIII", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/stone-game-viii", + "solutionLink": "#" + }, + { + "problemName": "1873. Calculate Special Bonus", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/calculate-special-bonus", + "solutionLink": "#" + }, + { + "problemName": "1874. Minimize Product Sum of Two Arrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimize-product-sum-of-two-arrays", + "solutionLink": "#" + }, + { + "problemName": "1875. Group Employees of the Same Salary", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/group-employees-of-the-same-salary", + "solutionLink": "#" + }, + { + "problemName": "1876. Substrings of Size Three with Distinct Characters", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters", + "solutionLink": "#" + }, + { + "problemName": "1877. Minimize Maximum Pair Sum in Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimize-maximum-pair-sum-in-array", + "solutionLink": "#" + }, + { + "problemName": "1878. Get Biggest Three Rhombus Sums in a Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/get-biggest-three-rhombus-sums-in-a-grid", + "solutionLink": "#" + }, + { + "problemName": "1879. Minimum XOR Sum of Two Arrays", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-xor-sum-of-two-arrays", + "solutionLink": "#" + }, + { + "problemName": "1880. Check if Word Equals Summation of Two Words", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-word-equals-summation-of-two-words", + "solutionLink": "#" + }, + { + "problemName": "1881. Maximum Value after Insertion", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-value-after-insertion", + "solutionLink": "#" + }, + { + "problemName": "1882. Process Tasks Using Servers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/process-tasks-using-servers", + "solutionLink": "#" + }, + { + "problemName": "1883. Minimum Skips to Arrive at Meeting On Time", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-skips-to-arrive-at-meeting-on-time", + "solutionLink": "#" + }, + { + "problemName": "1884. Egg Drop With 2 Eggs and N Floors", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors", + "solutionLink": "#" + }, + { + "problemName": "1885. Count Pairs in Two Arrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-pairs-in-two-arrays", + "solutionLink": "#" + }, + { + "problemName": "1886. Determine Whether Matrix Can Be Obtained By Rotation", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation", + "solutionLink": "#" + }, + { + "problemName": "1887. Reduction Operations to Make the Array Elements Equal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal", + "solutionLink": "#" + }, + { + "problemName": "1888. Minimum Number of Flips to Make the Binary String Alternating", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating", + "solutionLink": "#" + }, + { + "problemName": "1889. Minimum Space Wasted From Packaging", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-space-wasted-from-packaging", + "solutionLink": "#" + }, + { + "problemName": "1890. The Latest Login in 2020", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/the-latest-login-in-2020", + "solutionLink": "#" + }, + { + "problemName": "1891. Cutting Ribbons", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/cutting-ribbons", + "solutionLink": "#" + }, + { + "problemName": "1892. Page Recommendations II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/page-recommendations-ii", + "solutionLink": "#" + }, + { + "problemName": "1893. Check if All the Integers in a Range Are Covered", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered", + "solutionLink": "#" + }, + { + "problemName": "1894. Find the Student that Will Replace the Chalk", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk", + "solutionLink": "#" + }, + { + "problemName": "1895. Largest Magic Square", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/largest-magic-square", + "solutionLink": "#" + }, + { + "problemName": "1896. Minimum Cost to Change the Final Value of Expression", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-change-the-final-value-of-expression", + "solutionLink": "#" + }, + { + "problemName": "1897. Redistribute Characters to Make All Strings Equal", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal", + "solutionLink": "#" + }, + { + "problemName": "1898. Maximum Number of Removable Characters", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-removable-characters", + "solutionLink": "#" + }, + { + "problemName": "1899. Merge Triplets to Form Target Triplet", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/merge-triplets-to-form-target-triplet", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/1900-1999.md b/problems/leetcode-problems/1900-1999.md new file mode 100644 index 0000000..869da85 --- /dev/null +++ b/problems/leetcode-problems/1900-1999.md @@ -0,0 +1,622 @@ +--- +id: 1900-1999 +title: LeetCode Problems 1900 - 1999 +sidebar_label: 1900 - 1999 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 1900 - 1999 + - DSA problems +--- + +export const problems = [ + { + "problemName": "1900. The Earliest and Latest Rounds Where Players Compete", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/the-earliest-and-latest-rounds-where-players-compete", + "solutionLink": "#" + }, + { + "problemName": "1901. Find a Peak Element II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-a-peak-element-ii", + "solutionLink": "#" + }, + { + "problemName": "1902. Depth of BST Given Insertion Order", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/depth-of-bst-given-insertion-order", + "solutionLink": "#" + }, + { + "problemName": "1903. Largest Odd Number in String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/largest-odd-number-in-string", + "solutionLink": "#" + }, + { + "problemName": "1904. The Number of Full Rounds You Have Played", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-number-of-full-rounds-you-have-played", + "solutionLink": "#" + }, + { + "problemName": "1905. Count Sub Islands", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-sub-islands", + "solutionLink": "#" + }, + { + "problemName": "1906. Minimum Absolute Difference Queries", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-absolute-difference-queries", + "solutionLink": "#" + }, + { + "problemName": "1907. Count Salary Categories", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-salary-categories", + "solutionLink": "#" + }, + { + "problemName": "1908. Game of Nim", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/game-of-nim", + "solutionLink": "#" + }, + { + "problemName": "1909. Remove One Element to Make the Array Strictly Increasing", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing", + "solutionLink": "#" + }, + { + "problemName": "1910. Remove All Occurrences of a Substring", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-all-occurrences-of-a-substring", + "solutionLink": "#" + }, + { + "problemName": "1911. Maximum Alternating Subsequence Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-alternating-subsequence-sum", + "solutionLink": "#" + }, + { + "problemName": "1912. Design Movie Rental System", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/design-movie-rental-system", + "solutionLink": "#" + }, + { + "problemName": "1913. Maximum Product Difference Between Two Pairs", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-product-difference-between-two-pairs", + "solutionLink": "#" + }, + { + "problemName": "1914. Cyclically Rotating a Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/cyclically-rotating-a-grid", + "solutionLink": "#" + }, + { + "problemName": "1915. Number of Wonderful Substrings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-wonderful-substrings", + "solutionLink": "#" + }, + { + "problemName": "1916. Count Ways to Build Rooms in an Ant Colony", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony", + "solutionLink": "#" + }, + { + "problemName": "1917. Leetcodify Friends Recommendations", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/leetcodify-friends-recommendations", + "solutionLink": "#" + }, + { + "problemName": "1918. Kth Smallest Subarray Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/kth-smallest-subarray-sum", + "solutionLink": "#" + }, + { + "problemName": "1919. Leetcodify Similar Friends", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/leetcodify-similar-friends", + "solutionLink": "#" + }, + { + "problemName": "1920. Build Array from Permutation", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/build-array-from-permutation", + "solutionLink": "#" + }, + { + "problemName": "1921. Eliminate Maximum Number of Monsters", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/eliminate-maximum-number-of-monsters", + "solutionLink": "#" + }, + { + "problemName": "1922. Count Good Numbers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-good-numbers", + "solutionLink": "#" + }, + { + "problemName": "1923. Longest Common Subpath", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/longest-common-subpath", + "solutionLink": "#" + }, + { + "problemName": "1924. Erect the Fence II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/erect-the-fence-ii", + "solutionLink": "#" + }, + { + "problemName": "1925. Count Square Sum Triples", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-square-sum-triples", + "solutionLink": "#" + }, + { + "problemName": "1926. Nearest Exit from Entrance in Maze", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/nearest-exit-from-entrance-in-maze", + "solutionLink": "/dsa-solutions/lc-solutions/1900-1999/nearest-exit-from-entrance-in-maze" + }, + { + "problemName": "1927. Sum Game", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-game", + "solutionLink": "#" + }, + { + "problemName": "1928. Minimum Cost to Reach Destination in Time", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time", + "solutionLink": "#" + }, + { + "problemName": "1929. Concatenation of Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/concatenation-of-array", + "solutionLink": "#" + }, + { + "problemName": "1930. Unique Length-3 Palindromic Subsequences", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/unique-length-3-palindromic-subsequences", + "solutionLink": "#" + }, + { + "problemName": "1931. Painting a Grid With Three Different Colors", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/painting-a-grid-with-three-different-colors", + "solutionLink": "#" + }, + { + "problemName": "1932. Merge BSTs to Create Single BST", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/merge-bsts-to-create-single-bst", + "solutionLink": "#" + }, + { + "problemName": "1933. Check if String Is Decomposable Into Value-Equal Substrings", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-string-is-decomposable-into-value-equal-substrings", + "solutionLink": "#" + }, + { + "problemName": "1934. Confirmation Rate", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/confirmation-rate", + "solutionLink": "#" + }, + { + "problemName": "1935. Maximum Number of Words You Can Type", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-words-you-can-type", + "solutionLink": "#" + }, + { + "problemName": "1936. Add Minimum Number of Rungs", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/add-minimum-number-of-rungs", + "solutionLink": "#" + }, + { + "problemName": "1937. Maximum Number of Points with Cost", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-points-with-cost", + "solutionLink": "#" + }, + { + "problemName": "1938. Maximum Genetic Difference Query", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-genetic-difference-query", + "solutionLink": "#" + }, + { + "problemName": "1939. Users That Actively Request Confirmation Messages", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/users-that-actively-request-confirmation-messages", + "solutionLink": "#" + }, + { + "problemName": "1940. Longest Common Subsequence Between Sorted Arrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-common-subsequence-between-sorted-arrays", + "solutionLink": "#" + }, + { + "problemName": "1941. Check if All Characters Have Equal Number of Occurrences", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences", + "solutionLink": "#" + }, + { + "problemName": "1942. The Number of the Smallest Unoccupied Chair", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-number-of-the-smallest-unoccupied-chair", + "solutionLink": "#" + }, + { + "problemName": "1943. Describe the Painting", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/describe-the-painting", + "solutionLink": "#" + }, + { + "problemName": "1944. Number of Visible People in a Queue", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-visible-people-in-a-queue", + "solutionLink": "#" + }, + { + "problemName": "1945. Sum of Digits of String After Convert", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sum-of-digits-of-string-after-convert", + "solutionLink": "#" + }, + { + "problemName": "1946. Largest Number After Mutating Substring", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/largest-number-after-mutating-substring", + "solutionLink": "#" + }, + { + "problemName": "1947. Maximum Compatibility Score Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-compatibility-score-sum", + "solutionLink": "#" + }, + { + "problemName": "1948. Delete Duplicate Folders in System", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/delete-duplicate-folders-in-system", + "solutionLink": "#" + }, + { + "problemName": "1949. Strong Friendship", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/strong-friendship", + "solutionLink": "#" + }, + { + "problemName": "1950. Maximum of Minimum Values in All Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-of-minimum-values-in-all-subarrays", + "solutionLink": "#" + }, + { + "problemName": "1951. All the Pairs With the Maximum Number of Common Followers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/all-the-pairs-with-the-maximum-number-of-common-followers", + "solutionLink": "#" + }, + { + "problemName": "1952. Three Divisors", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/three-divisors", + "solutionLink": "#" + }, + { + "problemName": "1953. Maximum Number of Weeks for Which You Can Work", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-weeks-for-which-you-can-work", + "solutionLink": "#" + }, + { + "problemName": "1954. Minimum Garden Perimeter to Collect Enough Apples", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples", + "solutionLink": "#" + }, + { + "problemName": "1955. Count Number of Special Subsequences", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-number-of-special-subsequences", + "solutionLink": "#" + }, + { + "problemName": "1956. Minimum Time For K Virus Variants to Spread", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-for-k-virus-variants-to-spread", + "solutionLink": "#" + }, + { + "problemName": "1957. Delete Characters to Make Fancy String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/delete-characters-to-make-fancy-string", + "solutionLink": "#" + }, + { + "problemName": "1958. Check if Move is Legal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-move-is-legal", + "solutionLink": "#" + }, + { + "problemName": "1959. Minimum Total Space Wasted With K Resizing Operations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-total-space-wasted-with-k-resizing-operations", + "solutionLink": "#" + }, + { + "problemName": "1960. Maximum Product of the Length of Two Palindromic Substrings", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-substrings", + "solutionLink": "#" + }, + { + "problemName": "1961. Check If String Is a Prefix of Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-string-is-a-prefix-of-array", + "solutionLink": "#" + }, + { + "problemName": "1962. Remove Stones to Minimize the Total", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-stones-to-minimize-the-total", + "solutionLink": "/dsa-solutions/lc-solutions/1900-1999/remove-stones-to-minimize-the-total" + }, + { + "problemName": "1963. Minimum Number of Swaps to Make the String Balanced", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced", + "solutionLink": "#" + }, + { + "problemName": "1964. Find the Longest Valid Obstacle Course at Each Position", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position", + "solutionLink": "#" + }, + { + "problemName": "1965. Employees With Missing Information", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/employees-with-missing-information", + "solutionLink": "#" + }, + { + "problemName": "1966. Binary Searchable Numbers in an Unsorted Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/binary-searchable-numbers-in-an-unsorted-array", + "solutionLink": "#" + }, + { + "problemName": "1967. Number of Strings That Appear as Substrings in Word", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-strings-that-appear-as-substrings-in-word", + "solutionLink": "#" + }, + { + "problemName": "1968. Array With Elements Not Equal to Average of Neighbors", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors", + "solutionLink": "#" + }, + { + "problemName": "1969. Minimum Non-Zero Product of the Array Elements", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-non-zero-product-of-the-array-elements", + "solutionLink": "#" + }, + { + "problemName": "1970. Last Day Where You Can Still Cross", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/last-day-where-you-can-still-cross", + "solutionLink": "#" + }, + { + "problemName": "1971. Find if Path Exists in Graph", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-if-path-exists-in-graph", + "solutionLink": "#" + }, + { + "problemName": "1972. First and Last Call On the Same Day", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/first-and-last-call-on-the-same-day", + "solutionLink": "#" + }, + { + "problemName": "1973. Count Nodes Equal to Sum of Descendants", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-nodes-equal-to-sum-of-descendants", + "solutionLink": "#" + }, + { + "problemName": "1974. Minimum Time to Type Word Using Special Typewriter", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter", + "solutionLink": "#" + }, + { + "problemName": "1975. Maximum Matrix Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-matrix-sum", + "solutionLink": "#" + }, + { + "problemName": "1976. Number of Ways to Arrive at Destination", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-arrive-at-destination", + "solutionLink": "#" + }, + { + "problemName": "1977. Number of Ways to Separate Numbers", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-separate-numbers", + "solutionLink": "#" + }, + { + "problemName": "1978. Employees Whose Manager Left the Company", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/employees-whose-manager-left-the-company", + "solutionLink": "#" + }, + { + "problemName": "1979. Find Greatest Common Divisor of Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-greatest-common-divisor-of-array", + "solutionLink": "#" + }, + { + "problemName": "1980. Find Unique Binary String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-unique-binary-string", + "solutionLink": "#" + }, + { + "problemName": "1981. Minimize the Difference Between Target and Chosen Elements", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements", + "solutionLink": "#" + }, + { + "problemName": "1982. Find Array Given Subset Sums", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-array-given-subset-sums", + "solutionLink": "#" + }, + { + "problemName": "1983. Widest Pair of Indices With Equal Range Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/widest-pair-of-indices-with-equal-range-sum", + "solutionLink": "#" + }, + { + "problemName": "1984. Minimum Difference Between Highest and Lowest of K Scores", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores", + "solutionLink": "#" + }, + { + "problemName": "1985. Find the Kth Largest Integer in the Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array", + "solutionLink": "#" + }, + { + "problemName": "1986. Minimum Number of Work Sessions to Finish the Tasks", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-work-sessions-to-finish-the-tasks", + "solutionLink": "#" + }, + { + "problemName": "1987. Number of Unique Good Subsequences", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-unique-good-subsequences", + "solutionLink": "#" + }, + { + "problemName": "1988. Find Cutoff Score for Each School", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-cutoff-score-for-each-school", + "solutionLink": "#" + }, + { + "problemName": "1989. Maximum Number of People That Can Be Caught in Tag", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-people-that-can-be-caught-in-tag", + "solutionLink": "#" + }, + { + "problemName": "1990. Count the Number of Experiments", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-experiments", + "solutionLink": "#" + }, + { + "problemName": "1991. Find the Middle Index in Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-middle-index-in-array", + "solutionLink": "#" + }, + { + "problemName": "1992. Find All Groups of Farmland", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-all-groups-of-farmland", + "solutionLink": "/dsa-solutions/lc-solutions/1900-1999/find-all-groups-of-farmland" + }, + { + "problemName": "1993. Operations on Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/operations-on-tree", + "solutionLink": "#" + }, + { + "problemName": "1994. The Number of Good Subsets", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/the-number-of-good-subsets", + "solutionLink": "#" + }, + { + "problemName": "1995. Count Special Quadruplets", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-special-quadruplets", + "solutionLink": "#" + }, + { + "problemName": "1996. The Number of Weak Characters in the Game", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-number-of-weak-characters-in-the-game", + "solutionLink": "#" + }, + { + "problemName": "1997. First Day Where You Have Been in All the Rooms", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/first-day-where-you-have-been-in-all-the-rooms", + "solutionLink": "#" + }, + { + "problemName": "1998. GCD Sort of an Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/gcd-sort-of-an-array", + "solutionLink": "#" + }, + { + "problemName": "1999. Smallest Greater Multiple Made of Two Digits", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/smallest-greater-multiple-made-of-two-digits", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/2000-2099.md b/problems/leetcode-problems/2000-2099.md new file mode 100644 index 0000000..a0fe12a --- /dev/null +++ b/problems/leetcode-problems/2000-2099.md @@ -0,0 +1,623 @@ +--- +id: 2000-2099 +title: LeetCode Problems 2000 - 2099 +sidebar_label: 2000 - 2099 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 2000 - 2099 + - DSA problems +--- + + +export const problems = [ + { + "problemName": "2000. Reverse Prefix of Word", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/reverse-prefix-of-word", + "solutionLink": "#" + }, + { + "problemName": "2001. Number of Pairs of Interchangeable Rectangles", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-pairs-of-interchangeable-rectangles", + "solutionLink": "#" + }, + { + "problemName": "2002. Maximum Product of the Length of Two Palindromic Subsequences", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences", + "solutionLink": "/dsa-solutions/lc-solutions/2000-2099/maximum-product-of-the-length-of-two-palindromic-subsequences" + }, + { + "problemName": "2003. Smallest Missing Genetic Value in Each Subtree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/smallest-missing-genetic-value-in-each-subtree", + "solutionLink": "#" + }, + { + "problemName": "2004. The Number of Seniors and Juniors to Join the Company", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/the-number-of-seniors-and-juniors-to-join-the-company", + "solutionLink": "#" + }, + { + "problemName": "2005. Subtree Removal Game with Fibonacci Tree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/subtree-removal-game-with-fibonacci-tree", + "solutionLink": "#" + }, + { + "problemName": "2006. Count Number of Pairs With Absolute Difference K", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k", + "solutionLink": "#" + }, + { + "problemName": "2007. Find Original Array From Doubled Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-original-array-from-doubled-array", + "solutionLink": "#" + }, + { + "problemName": "2008. Maximum Earnings From Taxi", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-earnings-from-taxi", + "solutionLink": "#" + }, + { + "problemName": "2009. Minimum Number of Operations to Make Array Continuous", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous", + "solutionLink": "#" + }, + { + "problemName": "2010. The Number of Seniors and Juniors to Join the Company II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/the-number-of-seniors-and-juniors-to-join-the-company-ii", + "solutionLink": "#" + }, + { + "problemName": "2011. Final Value of Variable After Performing Operations", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/final-value-of-variable-after-performing-operations", + "solutionLink": "#" + }, + { + "problemName": "2012. Sum of Beauty in the Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-of-beauty-in-the-array", + "solutionLink": "#" + }, + { + "problemName": "2013. Detect Squares", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/detect-squares", + "solutionLink": "#" + }, + { + "problemName": "2014. Longest Subsequence Repeated k Times", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/longest-subsequence-repeated-k-times", + "solutionLink": "/dsa-solutions/lc-solutions/2000-2099/longest-subsequence-repeated-k-times" + }, + { + "problemName": "2015. Average Height of Buildings in Each Segment", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/average-height-of-buildings-in-each-segment", + "solutionLink": "#" + }, + { + "problemName": "2016. Maximum Difference Between Increasing Elements", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-difference-between-increasing-elements", + "solutionLink": "#" + }, + { + "problemName": "2017. Grid Game", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/grid-game", + "solutionLink": "#" + }, + { + "problemName": "2018. Check if Word Can Be Placed In Crossword", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword", + "solutionLink": "#" + }, + { + "problemName": "2019. The Score of Students Solving Math Expression", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/the-score-of-students-solving-math-expression", + "solutionLink": "#" + }, + { + "problemName": "2020. Number of Accounts That Did Not Stream", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-accounts-that-did-not-stream", + "solutionLink": "#" + }, + { + "problemName": "2021. Brightest Position on Street", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/brightest-position-on-street", + "solutionLink": "#" + }, + { + "problemName": "2022. Convert 1D Array Into 2D Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/convert-1d-array-into-2d-array", + "solutionLink": "#" + }, + { + "problemName": "2023. Number of Pairs of Strings With Concatenation Equal to Target", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target", + "solutionLink": "#" + }, + { + "problemName": "2024. Maximize the Confusion of an Exam", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximize-the-confusion-of-an-exam", + "solutionLink": "#" + }, + { + "problemName": "2025. Maximum Number of Ways to Partition an Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-ways-to-partition-an-array", + "solutionLink": "#" + }, + { + "problemName": "2026. Low-Quality Problems", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/low-quality-problems", + "solutionLink": "#" + }, + { + "problemName": "2027. Minimum Moves to Convert String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-moves-to-convert-string", + "solutionLink": "#" + }, + { + "problemName": "2028. Find Missing Observations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-missing-observations", + "solutionLink": "#" + }, + { + "problemName": "2029. Stone Game IX", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/stone-game-ix", + "solutionLink": "#" + }, + { + "problemName": "2030. Smallest K-Length Subsequence With Occurrences of a Letter", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/smallest-k-length-subsequence-with-occurrences-of-a-letter", + "solutionLink": "#" + }, + { + "problemName": "2031. Count Subarrays With More Ones Than Zeros", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-subarrays-with-more-ones-than-zeros", + "solutionLink": "#" + }, + { + "problemName": "2032. Two Out of Three", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/two-out-of-three", + "solutionLink": "#" + }, + { + "problemName": "2033. Minimum Operations to Make a Uni-Value Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid", + "solutionLink": "#" + }, + { + "problemName": "2034. Stock Price Fluctuation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/stock-price-fluctuation", + "solutionLink": "#" + }, + { + "problemName": "2035. Partition Array Into Two Arrays to Minimize Sum Difference", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference", + "solutionLink": "#" + }, + { + "problemName": "2036. Maximum Alternating Subarray Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-alternating-subarray-sum", + "solutionLink": "#" + }, + { + "problemName": "2037. Minimum Number of Moves to Seat Everyone", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone", + "solutionLink": "#" + }, + { + "problemName": "2038. Remove Colored Pieces if Both Neighbors are the Same Color", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color", + "solutionLink": "/dsa-solutions/lc-solutions/2000-2099/remove-colored-pieces-if-both-neighbors-are-the-same-color" + }, + { + "problemName": "2039. The Time When the Network Becomes Idle", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-time-when-the-network-becomes-idle", + "solutionLink": "#" + }, + { + "problemName": "2040. Kth Smallest Product of Two Sorted Arrays", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/kth-smallest-product-of-two-sorted-arrays", + "solutionLink": "#" + }, + { + "problemName": "2041. Accepted Candidates From the Interviews", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/accepted-candidates-from-the-interviews", + "solutionLink": "#" + }, + { + "problemName": "2042. Check if Numbers Are Ascending in a Sentence", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence", + "solutionLink": "#" + }, + { + "problemName": "2043. Simple Bank System", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/simple-bank-system", + "solutionLink": "#" + }, + { + "problemName": "2044. Count Number of Maximum Bitwise-OR Subsets", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets", + "solutionLink": "#" + }, + { + "problemName": "2045. Second Minimum Time to Reach Destination", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/second-minimum-time-to-reach-destination", + "solutionLink": "#" + }, + { + "problemName": "2046. Sort Linked List Already Sorted Using Absolute Values", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sort-linked-list-already-sorted-using-absolute-values", + "solutionLink": "#" + }, + { + "problemName": "2047. Number of Valid Words in a Sentence", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-valid-words-in-a-sentence", + "solutionLink": "#" + }, + { + "problemName": "2048. Next Greater Numerically Balanced Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/next-greater-numerically-balanced-number", + "solutionLink": "#" + }, + { + "problemName": "2049. Count Nodes With the Highest Score", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-nodes-with-the-highest-score", + "solutionLink": "#" + }, + { + "problemName": "2050. Parallel Courses III", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/parallel-courses-iii", + "solutionLink": "#" + }, + { + "problemName": "2051. The Category of Each Member in the Store", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-category-of-each-member-in-the-store", + "solutionLink": "#" + }, + { + "problemName": "2052. Minimum Cost to Separate Sentence Into Rows", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-separate-sentence-into-rows", + "solutionLink": "#" + }, + { + "problemName": "2053. Kth Distinct String in an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/kth-distinct-string-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "2054. Two Best Non-Overlapping Events", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/two-best-non-overlapping-events", + "solutionLink": "#" + }, + { + "problemName": "2055. Plates Between Candles", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/plates-between-candles", + "solutionLink": "#" + }, + { + "problemName": "2056. Number of Valid Move Combinations On Chessboard", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-valid-move-combinations-on-chessboard", + "solutionLink": "#" + }, + { + "problemName": "2057. Smallest Index With Equal Value", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/smallest-index-with-equal-value", + "solutionLink": "#" + }, + { + "problemName": "2058. Find the Minimum and Maximum Number of Nodes Between Critical Points", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points", + "solutionLink": "#" + }, + { + "problemName": "2059. Minimum Operations to Convert Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-convert-number", + "solutionLink": "#" + }, + { + "problemName": "2060. Check if an Original String Exists Given Two Encoded Strings", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/check-if-an-original-string-exists-given-two-encoded-strings", + "solutionLink": "#" + }, + { + "problemName": "2061. Number of Spaces Cleaning Robot Cleaned", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-spaces-cleaning-robot-cleaned", + "solutionLink": "#" + }, + { + "problemName": "2062. Count Vowel Substrings of a String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-vowel-substrings-of-a-string", + "solutionLink": "#" + }, + { + "problemName": "2063. Vowels of All Substrings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/vowels-of-all-substrings", + "solutionLink": "/dsa-solutions/lc-solutions/2000-2099/vowels-of-all-substrings" + }, + { + "problemName": "2064. Minimized Maximum of Products Distributed to Any Store", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store", + "solutionLink": "#" + }, + { + "problemName": "2065. Maximum Path Quality of a Graph", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-path-quality-of-a-graph", + "solutionLink": "#" + }, + { + "problemName": "2066. Account Balance", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/account-balance", + "solutionLink": "#" + }, + { + "problemName": "2067. Number of Equal Count Substrings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-equal-count-substrings", + "solutionLink": "#" + }, + { + "problemName": "2068. Check Whether Two Strings are Almost Equivalent", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent", + "solutionLink": "#" + }, + { + "problemName": "2069. Walking Robot Simulation II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/walking-robot-simulation-ii", + "solutionLink": "#" + }, + { + "problemName": "2070. Most Beautiful Item for Each Query", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/most-beautiful-item-for-each-query", + "solutionLink": "#" + }, + { + "problemName": "2071. Maximum Number of Tasks You Can Assign", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-tasks-you-can-assign", + "solutionLink": "#" + }, + { + "problemName": "2072. The Winner University", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/the-winner-university", + "solutionLink": "#" + }, + { + "problemName": "2073. Time Needed to Buy Tickets", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/time-needed-to-buy-tickets", + "solutionLink": "#" + }, + { + "problemName": "2074. Reverse Nodes in Even Length Groups", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reverse-nodes-in-even-length-groups", + "solutionLink": "#" + }, + { + "problemName": "2075. Decode the Slanted Ciphertext", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/decode-the-slanted-ciphertext", + "solutionLink": "#" + }, + { + "problemName": "2076. Process Restricted Friend Requests", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/process-restricted-friend-requests", + "solutionLink": "#" + }, + { + "problemName": "2077. Paths in Maze That Lead to Same Room", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/paths-in-maze-that-lead-to-same-room", + "solutionLink": "#" + }, + { + "problemName": "2078. Two Furthest Houses With Different Colors", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/two-furthest-houses-with-different-colors", + "solutionLink": "#" + }, + { + "problemName": "2079. Watering Plants", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/watering-plants", + "solutionLink": "#" + }, + { + "problemName": "2080. Range Frequency Queries", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/range-frequency-queries", + "solutionLink": "#" + }, + { + "problemName": "2081. Sum of k-Mirror Numbers", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sum-of-k-mirror-numbers", + "solutionLink": "#" + }, + { + "problemName": "2082. The Number of Rich Customers", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/the-number-of-rich-customers", + "solutionLink": "#" + }, + { + "problemName": "2083. Substrings That Begin and End With the Same Letter", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/substrings-that-begin-and-end-with-the-same-letter", + "solutionLink": "#" + }, + { + "problemName": "2084. Drop Type 1 Orders for Customers With Type 0 Orders", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/drop-type-1-orders-for-customers-with-type-0-orders", + "solutionLink": "#" + }, + { + "problemName": "2085. Count Common Words With One Occurrence", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-common-words-with-one-occurrence", + "solutionLink": "#" + }, + { + "problemName": "2086. Minimum Number of Food Buckets to Feed the Hamsters", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-food-buckets-to-feed-the-hamsters", + "solutionLink": "#" + }, + { + "problemName": "2087. Minimum Cost Homecoming of a Robot in a Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-homecoming-of-a-robot-in-a-grid", + "solutionLink": "#" + }, + { + "problemName": "2088. Count Fertile Pyramids in a Land", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-fertile-pyramids-in-a-land", + "solutionLink": "#" + }, + { + "problemName": "2089. Find Target Indices After Sorting Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-target-indices-after-sorting-array", + "solutionLink": "#" + }, + { + "problemName": "2090. K Radius Subarray Averages", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/k-radius-subarray-averages", + "solutionLink": "#" + }, + { + "problemName": "2091. Removing Minimum and Maximum From Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/removing-minimum-and-maximum-from-array", + "solutionLink": "#" + }, + { + "problemName": "2092. Find All People With Secret", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-all-people-with-secret", + "solutionLink": "#" + }, + { + "problemName": "2093. Minimum Cost to Reach City With Discounts", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-reach-city-with-discounts", + "solutionLink": "#" + }, + { + "problemName": "2094. Finding 3-Digit Even Numbers", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/finding-3-digit-even-numbers", + "solutionLink": "#" + }, + { + "problemName": "2095. Delete the Middle Node of a Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list", + "solutionLink": "#" + }, + { + "problemName": "2096. Step-By-Step Directions From a Binary Tree Node to Another", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another", + "solutionLink": "/dsa-solutions/lc-solutions/2000-2099/step-by-step-directions-from-a-binary-tree-node-to-another" + }, + { + "problemName": "2097. Valid Arrangement of Pairs", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/valid-arrangement-of-pairs", + "solutionLink": "#" + }, + { + "problemName": "2098. Subsequence of Size K With the Largest Even Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/subsequence-of-size-k-with-the-largest-even-sum", + "solutionLink": "#" + }, + { + "problemName": "2099. Find Subsequence of Length K With the Largest Sum", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/2100-2199.md b/problems/leetcode-problems/2100-2199.md new file mode 100644 index 0000000..046bff7 --- /dev/null +++ b/problems/leetcode-problems/2100-2199.md @@ -0,0 +1,623 @@ +--- +id: 2100-2199 +title: LeetCode Problems 2100 - 2199 +sidebar_label: 2100 - 2199 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 2100 - 2199 + - DSA problems +--- + +export const problems = [ + { + "problemName": "2100. Find Good Days to Rob the Bank", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-good-days-to-rob-the-bank", + "solutionLink": "#" + }, + { + "problemName": "2101. Detonate the Maximum Bombs", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/detonate-the-maximum-bombs", + "solutionLink": "#" + }, + { + "problemName": "2102. Sequentially Ordinal Rank Tracker", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sequentially-ordinal-rank-tracker", + "solutionLink": "#" + }, + { + "problemName": "2103. Rings and Rods", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/rings-and-rods", + "solutionLink": "#" + }, + { + "problemName": "2104. Sum of Subarray Ranges", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-of-subarray-ranges", + "solutionLink": "#" + }, + { + "problemName": "2105. Watering Plants II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/watering-plants-ii", + "solutionLink": "#" + }, + { + "problemName": "2106. Maximum Fruits Harvested After at Most K Steps", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-fruits-harvested-after-at-most-k-steps", + "solutionLink": "#" + }, + { + "problemName": "2107. Number of Unique Flavors After Sharing K Candies", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-unique-flavors-after-sharing-k-candies", + "solutionLink": "#" + }, + { + "problemName": "2108. Find First Palindromic String in the Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-first-palindromic-string-in-the-array", + "solutionLink": "#" + }, + { + "problemName": "2109. Adding Spaces to a String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/adding-spaces-to-a-string", + "solutionLink": "#" + }, + { + "problemName": "2110. Number of Smooth Descent Periods of a Stock", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-smooth-descent-periods-of-a-stock", + "solutionLink": "#" + }, + { + "problemName": "2111. Minimum Operations to Make the Array K-Increasing", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-make-the-array-k-increasing", + "solutionLink": "#" + }, + { + "problemName": "2112. The Airport With the Most Traffic", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-airport-with-the-most-traffic", + "solutionLink": "#" + }, + { + "problemName": "2113. Elements in Array After Removing and Replacing Elements", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/elements-in-array-after-removing-and-replacing-elements", + "solutionLink": "#" + }, + { + "problemName": "2114. Maximum Number of Words Found in Sentences", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-words-found-in-sentences", + "solutionLink": "#" + }, + { + "problemName": "2115. Find All Possible Recipes from Given Supplies", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies", + "solutionLink": "#" + }, + { + "problemName": "2116. Check if a Parentheses String Can Be Valid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid", + "solutionLink": "#" + }, + { + "problemName": "2117. Abbreviating the Product of a Range", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/abbreviating-the-product-of-a-range", + "solutionLink": "#" + }, + { + "problemName": "2118. Build the Equation", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/build-the-equation", + "solutionLink": "#" + }, + { + "problemName": "2119. A Number After a Double Reversal", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/a-number-after-a-double-reversal", + "solutionLink": "#" + }, + { + "problemName": "2120. Execution of All Suffix Instructions Staying in a Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid", + "solutionLink": "#" + }, + { + "problemName": "2121. Intervals Between Identical Elements", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/intervals-between-identical-elements", + "solutionLink": "#" + }, + { + "problemName": "2122. Recover the Original Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/recover-the-original-array", + "solutionLink": "#" + }, + { + "problemName": "2123. Minimum Operations to Remove Adjacent Ones in Matrix", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-remove-adjacent-ones-in-matrix", + "solutionLink": "#" + }, + { + "problemName": "2124. Check if All A's Appears Before All B's", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-all-as-appears-before-all-bs", + "solutionLink": "#" + }, + { + "problemName": "2125. Number of Laser Beams in a Bank", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-laser-beams-in-a-bank", + "solutionLink": "#" + }, + { + "problemName": "2126. Destroying Asteroids", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/destroying-asteroids", + "solutionLink": "#" + }, + { + "problemName": "2127. Maximum Employees to Be Invited to a Meeting", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-employees-to-be-invited-to-a-meeting", + "solutionLink": "#" + }, + { + "problemName": "2128. Remove All Ones With Row and Column Flips", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-all-ones-with-row-and-column-flips", + "solutionLink": "#" + }, + { + "problemName": "2129. Capitalize the Title", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/capitalize-the-title", + "solutionLink": "#" + }, + { + "problemName": "2130. Maximum Twin Sum of a Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list", + "solutionLink": "#" + }, + { + "problemName": "2131. Longest Palindrome by Concatenating Two Letter Words", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words", + "solutionLink": "#" + }, + { + "problemName": "2132. Stamping the Grid", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/stamping-the-grid", + "solutionLink": "#" + }, + { + "problemName": "2133. Check if Every Row and Column Contains All Numbers", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers", + "solutionLink": "#" + }, + { + "problemName": "2134. Minimum Swaps to Group All 1's Together II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii", + "solutionLink": "#" + }, + { + "problemName": "2135. Count Words Obtained After Adding a Letter", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-words-obtained-after-adding-a-letter", + "solutionLink": "#" + }, + { + "problemName": "2136. Earliest Possible Day of Full Bloom", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/earliest-possible-day-of-full-bloom", + "solutionLink": "#" + }, + { + "problemName": "2137. Pour Water Between Buckets to Make Water Levels Equal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/pour-water-between-buckets-to-make-water-levels-equal", + "solutionLink": "#" + }, + { + "problemName": "2138. Divide a String Into Groups of Size k", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/divide-a-string-into-groups-of-size-k", + "solutionLink": "#" + }, + { + "problemName": "2139. Minimum Moves to Reach Target Score", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-moves-to-reach-target-score", + "solutionLink": "#" + }, + { + "problemName": "2140. Solving Questions With Brainpower", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/solving-questions-with-brainpower", + "solutionLink": "#" + }, + { + "problemName": "2141. Maximum Running Time of N Computers", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-running-time-of-n-computers", + "solutionLink": "#" + }, + { + "problemName": "2142. The Number of Passengers in Each Bus I", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-number-of-passengers-in-each-bus-i", + "solutionLink": "#" + }, + { + "problemName": "2143. Choose Numbers From Two Arrays in Range", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/choose-numbers-from-two-arrays-in-range", + "solutionLink": "#" + }, + { + "problemName": "2144. Minimum Cost of Buying Candies With Discount", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-of-buying-candies-with-discount", + "solutionLink": "#" + }, + { + "problemName": "2145. Count the Hidden Sequences", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-the-hidden-sequences", + "solutionLink": "#" + }, + { + "problemName": "2146. K Highest Ranked Items Within a Price Range", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/k-highest-ranked-items-within-a-price-range", + "solutionLink": "#" + }, + { + "problemName": "2147. Number of Ways to Divide a Long Corridor", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-divide-a-long-corridor", + "solutionLink": "#" + }, + { + "problemName": "2148. Count Elements With Strictly Smaller and Greater Elements", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-elements-with-strictly-smaller-and-greater-elements", + "solutionLink": "#" + }, + { + "problemName": "2149. Rearrange Array Elements by Sign", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/rearrange-array-elements-by-sign", + "solutionLink": "#" + }, + { + "problemName": "2150. Find All Lonely Numbers in the Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-all-lonely-numbers-in-the-array", + "solutionLink": "/dsa-solutions/lc-solutions/2100-2199/find-all-lonely-numbers-in-the-array" + }, + { + "problemName": "2151. Maximum Good People Based on Statements", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-good-people-based-on-statements", + "solutionLink": "#" + }, + { + "problemName": "2152. Minimum Number of Lines to Cover Points", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-lines-to-cover-points", + "solutionLink": "#" + }, + { + "problemName": "2153. The Number of Passengers in Each Bus II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/the-number-of-passengers-in-each-bus-ii", + "solutionLink": "#" + }, + { + "problemName": "2154. Keep Multiplying Found Values by Two", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/keep-multiplying-found-values-by-two", + "solutionLink": "#" + }, + { + "problemName": "2155. All Divisions With the Highest Score of a Binary Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/all-divisions-with-the-highest-score-of-a-binary-array", + "solutionLink": "#" + }, + { + "problemName": "2156. Find Substring With Given Hash Value", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-substring-with-given-hash-value", + "solutionLink": "#" + }, + { + "problemName": "2157. Groups of Strings", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/groups-of-strings", + "solutionLink": "#" + }, + { + "problemName": "2158. Amount of New Area Painted Each Day", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/amount-of-new-area-painted-each-day", + "solutionLink": "#" + }, + { + "problemName": "2159. Order Two Columns Independently", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/order-two-columns-independently", + "solutionLink": "#" + }, + { + "problemName": "2160. Minimum Sum of Four Digit Number After Splitting Digits", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits", + "solutionLink": "#" + }, + { + "problemName": "2161. Partition Array According to Given Pivot", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/partition-array-according-to-given-pivot", + "solutionLink": "#" + }, + { + "problemName": "2162. Minimum Cost to Set Cooking Time", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-set-cooking-time", + "solutionLink": "#" + }, + { + "problemName": "2163. Minimum Difference in Sums After Removal of Elements", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-difference-in-sums-after-removal-of-elements", + "solutionLink": "#" + }, + { + "problemName": "2164. Sort Even and Odd Indices Independently", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sort-even-and-odd-indices-independently", + "solutionLink": "#" + }, + { + "problemName": "2165. Smallest Value of the Rearranged Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/smallest-value-of-the-rearranged-number", + "solutionLink": "#" + }, + { + "problemName": "2166. Design Bitset", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-bitset", + "solutionLink": "#" + }, + { + "problemName": "2167. Minimum Time to Remove All Cars Containing Illegal Goods", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-to-remove-all-cars-containing-illegal-goods", + "solutionLink": "#" + }, + { + "problemName": "2168. Unique Substrings With Equal Digit Frequency", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/unique-substrings-with-equal-digit-frequency", + "solutionLink": "#" + }, + { + "problemName": "2169. Count Operations to Obtain Zero", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-operations-to-obtain-zero", + "solutionLink": "#" + }, + { + "problemName": "2170. Minimum Operations to Make the Array Alternating", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-make-the-array-alternating", + "solutionLink": "#" + }, + { + "problemName": "2171. Removing Minimum Number of Magic Beans", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/removing-minimum-number-of-magic-beans", + "solutionLink": "#" + }, + { + "problemName": "2172. Maximum AND Sum of Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-and-sum-of-array", + "solutionLink": "#" + }, + { + "problemName": "2173. Longest Winning Streak", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/longest-winning-streak", + "solutionLink": "#" + }, + { + "problemName": "2174. Remove All Ones With Row and Column Flips II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-all-ones-with-row-and-column-flips-ii", + "solutionLink": "#" + }, + { + "problemName": "2175. The Change in Global Rankings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-change-in-global-rankings", + "solutionLink": "#" + }, + { + "problemName": "2176. Count Equal and Divisible Pairs in an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-equal-and-divisible-pairs-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "2177. Find Three Consecutive Integers That Sum to a Given Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number", + "solutionLink": "/dsa-solutions/lc-solutions/2100-2199/find-three-consecutive-integers-that-sum-to-a-given-number" + }, + { + "problemName": "2178. Maximum Split of Positive Even Integers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-split-of-positive-even-integers", + "solutionLink": "#" + }, + { + "problemName": "2179. Count Good Triplets in an Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-good-triplets-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "2180. Count Integers With Even Digit Sum", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-integers-with-even-digit-sum", + "solutionLink": "#" + }, + { + "problemName": "2181. Merge Nodes in Between Zeros", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/merge-nodes-in-between-zeros", + "solutionLink": "#" + }, + { + "problemName": "2182. Construct String With Repeat Limit", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/construct-string-with-repeat-limit", + "solutionLink": "#" + }, + { + "problemName": "2183. Count Array Pairs Divisible by K", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-array-pairs-divisible-by-k", + "solutionLink": "#" + }, + { + "problemName": "2184. Number of Ways to Build Sturdy Brick Wall", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-build-sturdy-brick-wall", + "solutionLink": "#" + }, + { + "problemName": "2185. Counting Words With a Given Prefix", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/counting-words-with-a-given-prefix", + "solutionLink": "#" + }, + { + "problemName": "2186. Minimum Number of Steps to Make Two Strings Anagram II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram-ii", + "solutionLink": "#" + }, + { + "problemName": "2187. Minimum Time to Complete Trips", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-to-complete-trips", + "solutionLink": "#" + }, + { + "problemName": "2188. Minimum Time to Finish the Race", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-to-finish-the-race", + "solutionLink": "#" + }, + { + "problemName": "2189. Number of Ways to Build House of Cards", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-build-house-of-cards", + "solutionLink": "#" + }, + { + "problemName": "2190. Most Frequent Number Following Key In an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/most-frequent-number-following-key-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "2191. Sort the Jumbled Numbers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sort-the-jumbled-numbers", + "solutionLink": "#" + }, + { + "problemName": "2192. All Ancestors of a Node in a Directed Acyclic Graph", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph", + "solutionLink": "/dsa-solutions/lc-solutions/2100-2199/all-ancestors-of-a-node-in-a-directed-acyclic-graph" + }, + { + "problemName": "2193. Minimum Number of Moves to Make Palindrome", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome", + "solutionLink": "#" + }, + { + "problemName": "2194. Cells in a Range on an Excel Sheet", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet", + "solutionLink": "#" + }, + { + "problemName": "2195. Append K Integers With Minimal Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/append-k-integers-with-minimal-sum", + "solutionLink": "#" + }, + { + "problemName": "2196. Create Binary Tree From Descriptions", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/create-binary-tree-from-descriptions", + "solutionLink": "#" + }, + { + "problemName": "2197. Replace Non-Coprime Numbers in Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/replace-non-coprime-numbers-in-array", + "solutionLink": "#" + }, + { + "problemName": "2198. Number of Single Divisor Triplets", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-single-divisor-triplets", + "solutionLink": "#" + }, + { + "problemName": "2199. Finding the Topic of Each Post", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/finding-the-topic-of-each-post", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. + diff --git a/problems/leetcode-problems/2200-2299.md b/problems/leetcode-problems/2200-2299.md new file mode 100644 index 0000000..bb8121d --- /dev/null +++ b/problems/leetcode-problems/2200-2299.md @@ -0,0 +1,623 @@ +--- +id: 2200-2299 +title: LeetCode Problems 2200 - 2299 +sidebar_label: 2200 - 2299 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 2200 - 2299 + - DSA problems +--- + + +export const problems = [ + { + "problemName": "2200. Find All K-Distant Indices in an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-all-k-distant-indices-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "2201. Count Artifacts That Can Be Extracted", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-artifacts-that-can-be-extracted", + "solutionLink": "#" + }, + { + "problemName": "2202. Maximize the Topmost Element After K Moves", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves", + "solutionLink": "#" + }, + { + "problemName": "2203. Minimum Weighted Subgraph With the Required Paths", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-weighted-subgraph-with-the-required-paths", + "solutionLink": "#" + }, + { + "problemName": "2204. Distance to a Cycle in Undirected Graph", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/distance-to-a-cycle-in-undirected-graph", + "solutionLink": "#" + }, + { + "problemName": "2205. The Number of Users That Are Eligible for Discount", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/the-number-of-users-that-are-eligible-for-discount", + "solutionLink": "#" + }, + { + "problemName": "2206. Divide Array Into Equal Pairs", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/divide-array-into-equal-pairs", + "solutionLink": "#" + }, + { + "problemName": "2207. Maximize Number of Subsequences in a String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string", + "solutionLink": "#" + }, + { + "problemName": "2208. Minimum Operations to Halve Array Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-halve-array-sum", + "solutionLink": "#" + }, + { + "problemName": "2209. Minimum White Tiles After Covering With Carpets", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets", + "solutionLink": "#" + }, + { + "problemName": "2210. Count Hills and Valleys in an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-hills-and-valleys-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "2211. Count Collisions on a Road", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-collisions-on-a-road", + "solutionLink": "#" + }, + { + "problemName": "2212. Maximum Points in an Archery Competition", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-points-in-an-archery-competition", + "solutionLink": "#" + }, + { + "problemName": "2213. Longest Substring of One Repeating Character", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/longest-substring-of-one-repeating-character", + "solutionLink": "#" + }, + { + "problemName": "2214. Minimum Health to Beat Game", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-health-to-beat-game", + "solutionLink": "#" + }, + { + "problemName": "2215. Find the Difference of Two Arrays", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-difference-of-two-arrays", + "solutionLink": "#" + }, + { + "problemName": "2216. Minimum Deletions to Make Array Beautiful", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-deletions-to-make-array-beautiful", + "solutionLink": "#" + }, + { + "problemName": "2217. Find Palindrome With Fixed Length", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-palindrome-with-fixed-length", + "solutionLink": "#" + }, + { + "problemName": "2218. Maximum Value of K Coins From Piles", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-value-of-k-coins-from-piles", + "solutionLink": "#" + }, + { + "problemName": "2219. Maximum Sum Score of Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-sum-score-of-array", + "solutionLink": "#" + }, + { + "problemName": "2220. Minimum Bit Flips to Convert Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-bit-flips-to-convert-number", + "solutionLink": "#" + }, + { + "problemName": "2221. Find Triangular Sum of an Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-triangular-sum-of-an-array", + "solutionLink": "#" + }, + { + "problemName": "2222. Number of Ways to Select Buildings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-select-buildings", + "solutionLink": "#" + }, + { + "problemName": "2223. Sum of Scores of Built Strings", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sum-of-scores-of-built-strings", + "solutionLink": "#" + }, + { + "problemName": "2224. Minimum Number of Operations to Convert Time", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-operations-to-convert-time", + "solutionLink": "#" + }, + { + "problemName": "2225. Find Players With Zero or One Losses", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-players-with-zero-or-one-losses", + "solutionLink": "#" + }, + { + "problemName": "2226. Maximum Candies Allocated to K Children", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-candies-allocated-to-k-children", + "solutionLink": "#" + }, + { + "problemName": "2227. Encrypt and Decrypt Strings", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/encrypt-and-decrypt-strings", + "solutionLink": "#" + }, + { + "problemName": "2228. Users With Two Purchases Within Seven Days", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/users-with-two-purchases-within-seven-days", + "solutionLink": "#" + }, + { + "problemName": "2229. Check if an Array Is Consecutive", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-an-array-is-consecutive", + "solutionLink": "#" + }, + { + "problemName": "2230. The Users That Are Eligible for Discount", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/the-users-that-are-eligible-for-discount", + "solutionLink": "#" + }, + { + "problemName": "2231. Largest Number After Digit Swaps by Parity", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity", + "solutionLink": "#" + }, + { + "problemName": "2232. Minimize Result by Adding Parentheses to Expression", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression", + "solutionLink": "#" + }, + { + "problemName": "2233. Maximum Product After K Increments", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-product-after-k-increments", + "solutionLink": "#" + }, + { + "problemName": "2234. Maximum Total Beauty of the Gardens", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-total-beauty-of-the-gardens", + "solutionLink": "#" + }, + { + "problemName": "2235. Add Two Integers", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/add-two-integers", + "solutionLink": "/dsa-solutions/lc-solutions/2200-2299/add-two-integers" + }, + { + "problemName": "2236. Root Equals Sum of Children", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/root-equals-sum-of-children", + "solutionLink": "#" + }, + { + "problemName": "2237. Count Positions on Street With Required Brightness", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-positions-on-street-with-required-brightness", + "solutionLink": "#" + }, + { + "problemName": "2238. Number of Times a Driver Was a Passenger", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-times-a-driver-was-a-passenger", + "solutionLink": "#" + }, + { + "problemName": "2239. Find Closest Number to Zero", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-closest-number-to-zero", + "solutionLink": "#" + }, + { + "problemName": "2240. Number of Ways to Buy Pens and Pencils", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils", + "solutionLink": "#" + }, + { + "problemName": "2241. Design an ATM Machine", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-an-atm-machine", + "solutionLink": "#" + }, + { + "problemName": "2242. Maximum Score of a Node Sequence", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-score-of-a-node-sequence", + "solutionLink": "#" + }, + { + "problemName": "2243. Calculate Digit Sum of a String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/calculate-digit-sum-of-a-string", + "solutionLink": "#" + }, + { + "problemName": "2244. Minimum Rounds to Complete All Tasks", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks", + "solutionLink": "#" + }, + { + "problemName": "2245. Maximum Trailing Zeros in a Cornered Path", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-trailing-zeros-in-a-cornered-path", + "solutionLink": "#" + }, + { + "problemName": "2246. Longest Path With Different Adjacent Characters", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/longest-path-with-different-adjacent-characters", + "solutionLink": "#" + }, + { + "problemName": "2247. Maximum Cost of Trip With K Highways", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-cost-of-trip-with-k-highways", + "solutionLink": "#" + }, + { + "problemName": "2248. Intersection of Multiple Arrays", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/intersection-of-multiple-arrays", + "solutionLink": "#" + }, + { + "problemName": "2249. Count Lattice Points Inside a Circle", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-lattice-points-inside-a-circle", + "solutionLink": "#" + }, + { + "problemName": "2250. Count Number of Rectangles Containing Each Point", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-number-of-rectangles-containing-each-point", + "solutionLink": "#" + }, + { + "problemName": "2251. Number of Flowers in Full Bloom", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-flowers-in-full-bloom", + "solutionLink": "#" + }, + { + "problemName": "2252. Dynamic Pivoting of a Table", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/dynamic-pivoting-of-a-table", + "solutionLink": "#" + }, + { + "problemName": "2253. Dynamic Unpivoting of a Table", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/dynamic-unpivoting-of-a-table", + "solutionLink": "#" + }, + { + "problemName": "2254. Design Video Sharing Platform", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/design-video-sharing-platform", + "solutionLink": "#" + }, + { + "problemName": "2255. Count Prefixes of a Given String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-prefixes-of-a-given-string", + "solutionLink": "#" + }, + { + "problemName": "2256. Minimum Average Difference", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-average-difference", + "solutionLink": "#" + }, + { + "problemName": "2257. Count Unguarded Cells in the Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-unguarded-cells-in-the-grid", + "solutionLink": "#" + }, + { + "problemName": "2258. Escape the Spreading Fire", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/escape-the-spreading-fire", + "solutionLink": "#" + }, + { + "problemName": "2259. Remove Digit From Number to Maximize Result", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/remove-digit-from-number-to-maximize-result", + "solutionLink": "#" + }, + { + "problemName": "2260. Minimum Consecutive Cards to Pick Up", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up", + "solutionLink": "/dsa-solutions/lc-solutions/2200-2299/minimum-consecutive-cards-to-pick-up" + }, + { + "problemName": "2261. K Divisible Elements Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/k-divisible-elements-subarrays", + "solutionLink": "#" + }, + { + "problemName": "2262. Total Appeal of A String", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/total-appeal-of-a-string", + "solutionLink": "/dsa-solutions/lc-solutions/2200-2300/total-appeal-of-a-string" + }, + { + "problemName": "2263. Make Array Non-decreasing or Non-increasing", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/make-array-non-decreasing-or-non-increasing", + "solutionLink": "#" + }, + { + "problemName": "2264. Largest 3-Same-Digit Number in String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/largest-3-same-digit-number-in-string", + "solutionLink": "#" + }, + { + "problemName": "2265. Count Nodes Equal to Average of Subtree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree", + "solutionLink": "#" + }, + { + "problemName": "2266. Count Number of Texts", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-number-of-texts", + "solutionLink": "#" + }, + { + "problemName": "2267. Check if There Is a Valid Parentheses String Path", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path", + "solutionLink": "#" + }, + { + "problemName": "2268. Minimum Number of Keypresses", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-keypresses", + "solutionLink": "#" + }, + { + "problemName": "2269. Find the K-Beauty of a Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-k-beauty-of-a-number", + "solutionLink": "#" + }, + { + "problemName": "2270. Number of Ways to Split Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-split-array", + "solutionLink": "#" + }, + { + "problemName": "2271. Maximum White Tiles Covered by a Carpet", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-white-tiles-covered-by-a-carpet", + "solutionLink": "#" + }, + { + "problemName": "2272. Substring With Largest Variance", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/substring-with-largest-variance", + "solutionLink": "#" + }, + { + "problemName": "2273. Find Resultant Array After Removing Anagrams", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-resultant-array-after-removing-anagrams", + "solutionLink": "#" + }, + { + "problemName": "2274. Maximum Consecutive Floors Without Special Floors", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-consecutive-floors-without-special-floors", + "solutionLink": "#" + }, + { + "problemName": "2275. Largest Combination With Bitwise AND Greater Than Zero", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/largest-combination-with-bitwise-and-greater-than-zero", + "solutionLink": "#" + }, + { + "problemName": "2276. Count Integers in Intervals", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-integers-in-intervals", + "solutionLink": "#" + }, + { + "problemName": "2277. Closest Node to Path in Tree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/closest-node-to-path-in-tree", + "solutionLink": "#" + }, + { + "problemName": "2278. Percentage of Letter in String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/percentage-of-letter-in-string", + "solutionLink": "#" + }, + { + "problemName": "2279. Maximum Bags With Full Capacity of Rocks", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks", + "solutionLink": "#" + }, + { + "problemName": "2280. Minimum Lines to Represent a Line Chart", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-lines-to-represent-a-line-chart", + "solutionLink": "#" + }, + { + "problemName": "2281. Sum of Total Strength of Wizards", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sum-of-total-strength-of-wizards", + "solutionLink": "#" + }, + { + "problemName": "2282. Number of People That Can Be Seen in a Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-people-that-can-be-seen-in-a-grid", + "solutionLink": "#" + }, + { + "problemName": "2283. Check if Number Has Equal Digit Count and Digit Value", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value", + "solutionLink": "#" + }, + { + "problemName": "2284. Sender With Largest Word Count", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sender-with-largest-word-count", + "solutionLink": "#" + }, + { + "problemName": "2285. Maximum Total Importance of Roads", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-total-importance-of-roads", + "solutionLink": "#" + }, + { + "problemName": "2286. Booking Concert Tickets in Groups", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/booking-concert-tickets-in-groups", + "solutionLink": "/dsa-solutions/lc-solutions/2200-2300/Booking-concert-tickets-in-groups" + }, + { + "problemName": "2287. Rearrange Characters to Make Target String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/rearrange-characters-to-make-target-string", + "solutionLink": "#" + }, + { + "problemName": "2288. Apply Discount to Prices", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/apply-discount-to-prices", + "solutionLink": "#" + }, + { + "problemName": "2289. Steps to Make Array Non-decreasing", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/steps-to-make-array-non-decreasing", + "solutionLink": "#" + }, + { + "problemName": "2290. Minimum Obstacle Removal to Reach Corner", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner", + "solutionLink": "#" + }, + { + "problemName": "2291. Maximum Profit From Trading Stocks", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-profit-from-trading-stocks", + "solutionLink": "#" + }, + { + "problemName": "2292. Products With Three or More Orders in Two Consecutive Years", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/products-with-three-or-more-orders-in-two-consecutive-years", + "solutionLink": "#" + }, + { + "problemName": "2293. Min Max Game", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/min-max-game", + "solutionLink": "#" + }, + { + "problemName": "2294. Partition Array Such That Maximum Difference Is K", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k", + "solutionLink": "#" + }, + { + "problemName": "2295. Replace Elements in an Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/replace-elements-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "2296. Design a Text Editor", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/design-a-text-editor", + "solutionLink": "#" + }, + { + "problemName": "2297. Jump Game VIII", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/jump-game-viii", + "solutionLink": "#" + }, + { + "problemName": "2298. Tasks Count in the Weekend", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/tasks-count-in-the-weekend", + "solutionLink": "#" + }, + { + "problemName": "2299. Strong Password Checker II", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/strong-password-checker-ii", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/2300-2399.md b/problems/leetcode-problems/2300-2399.md new file mode 100644 index 0000000..cc9325d --- /dev/null +++ b/problems/leetcode-problems/2300-2399.md @@ -0,0 +1,622 @@ +--- +id: 2300-2399 +title: LeetCode Problems 2300 - 2399 +sidebar_label: 2300 - 2399 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 2300 - 2399 + - DSA problems +--- + +export const problems = [ + { + "problemName": "2300. Successful Pairs of Spells and Potions", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/successful-pairs-of-spells-and-potions", + "solutionLink": "#" + }, + { + "problemName": "2301. Match Substring After Replacement", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/match-substring-after-replacement", + "solutionLink": "#" + }, + { + "problemName": "2302. Count Subarrays With Score Less Than K", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-subarrays-with-score-less-than-k", + "solutionLink": "#" + }, + { + "problemName": "2303. Calculate Amount Paid in Taxes", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/calculate-amount-paid-in-taxes", + "solutionLink": "#" + }, + { + "problemName": "2304. Minimum Path Cost in a Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-path-cost-in-a-grid", + "solutionLink": "#" + }, + { + "problemName": "2305. Fair Distribution of Cookies", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/fair-distribution-of-cookies", + "solutionLink": "#" + }, + { + "problemName": "2306. Naming a Company", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/naming-a-company", + "solutionLink": "#" + }, + { + "problemName": "2307. Check for Contradictions in Equations", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/check-for-contradictions-in-equations", + "solutionLink": "#" + }, + { + "problemName": "2308. Arrange Table by Gender", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/arrange-table-by-gender", + "solutionLink": "#" + }, + { + "problemName": "2309. Greatest English Letter in Upper and Lower Case", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case", + "solutionLink": "#" + }, + { + "problemName": "2310. Sum of Numbers With Units Digit K", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-of-numbers-with-units-digit-k", + "solutionLink": "#" + }, + { + "problemName": "2311. Longest Binary Subsequence Less Than or Equal to K", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-binary-subsequence-less-than-or-equal-to-k", + "solutionLink": "#" + }, + { + "problemName": "2312. Selling Pieces of Wood", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/selling-pieces-of-wood", + "solutionLink": "#" + }, + { + "problemName": "2313. Minimum Flips in Binary Tree to Get Result", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-flips-in-binary-tree-to-get-result", + "solutionLink": "#" + }, + { + "problemName": "2314. The First Day of the Maximum Recorded Degree in Each City", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-first-day-of-the-maximum-recorded-degree-in-each-city", + "solutionLink": "#" + }, + { + "problemName": "2315. Count Asterisks", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-asterisks", + "solutionLink": "#" + }, + { + "problemName": "2316. Count Unreachable Pairs of Nodes in an Undirected Graph", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph", + "solutionLink": "#" + }, + { + "problemName": "2317. Maximum XOR After Operations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-xor-after-operations", + "solutionLink": "#" + }, + { + "problemName": "2318. Number of Distinct Roll Sequences", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-distinct-roll-sequences", + "solutionLink": "#" + }, + { + "problemName": "2319. Check if Matrix Is X-Matrix", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-matrix-is-x-matrix", + "solutionLink": "#" + }, + { + "problemName": "2320. Count Number of Ways to Place Houses", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-number-of-ways-to-place-houses", + "solutionLink": "#" + }, + { + "problemName": "2321. Maximum Score Of Spliced Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-score-of-spliced-array", + "solutionLink": "#" + }, + { + "problemName": "2322. Minimum Score After Removals on a Tree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-score-after-removals-on-a-tree", + "solutionLink": "#" + }, + { + "problemName": "2323. Find Minimum Time to Finish All Jobs II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs-ii", + "solutionLink": "#" + }, + { + "problemName": "2324. Product Sales Analysis IV", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/product-sales-analysis-iv", + "solutionLink": "#" + }, + { + "problemName": "2325. Decode the Message", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/decode-the-message", + "solutionLink": "#" + }, + { + "problemName": "2326. Spiral Matrix IV", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/spiral-matrix-iv", + "solutionLink": "#" + }, + { + "problemName": "2327. Number of People Aware of a Secret", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-people-aware-of-a-secret", + "solutionLink": "#" + }, + { + "problemName": "2328. Number of Increasing Paths in a Grid", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-increasing-paths-in-a-grid", + "solutionLink": "#" + }, + { + "problemName": "2329. Product Sales Analysis V", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/product-sales-analysis-v", + "solutionLink": "#" + }, + { + "problemName": "2330. Valid Palindrome IV", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/valid-palindrome-iv", + "solutionLink": "#" + }, + { + "problemName": "2331. Evaluate Boolean Binary Tree", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/evaluate-boolean-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "2332. The Latest Time to Catch a Bus", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-latest-time-to-catch-a-bus", + "solutionLink": "#" + }, + { + "problemName": "2333. Minimum Sum of Squared Difference", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-sum-of-squared-difference", + "solutionLink": "#" + }, + { + "problemName": "2334. Subarray With Elements Greater Than Varying Threshold", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/subarray-with-elements-greater-than-varying-threshold", + "solutionLink": "#" + }, + { + "problemName": "2335. Minimum Amount of Time to Fill Cups", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups", + "solutionLink": "#" + }, + { + "problemName": "2336. Smallest Number in Infinite Set", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/smallest-number-in-infinite-set", + "solutionLink": "#" + }, + { + "problemName": "2337. Move Pieces to Obtain a String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/move-pieces-to-obtain-a-string", + "solutionLink": "#" + }, + { + "problemName": "2338. Count the Number of Ideal Arrays", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-ideal-arrays", + "solutionLink": "#" + }, + { + "problemName": "2339. All the Matches of the League", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/all-the-matches-of-the-league", + "solutionLink": "#" + }, + { + "problemName": "2340. Minimum Adjacent Swaps to Make a Valid Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-adjacent-swaps-to-make-a-valid-array", + "solutionLink": "#" + }, + { + "problemName": "2341. Maximum Number of Pairs in Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-pairs-in-array", + "solutionLink": "#" + }, + { + "problemName": "2342. Max Sum of a Pair With Equal Sum of Digits", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits", + "solutionLink": "#" + }, + { + "problemName": "2343. Query Kth Smallest Trimmed Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/query-kth-smallest-trimmed-number", + "solutionLink": "#" + }, + { + "problemName": "2344. Minimum Deletions to Make Array Divisible", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-deletions-to-make-array-divisible", + "solutionLink": "#" + }, + { + "problemName": "2345. Finding the Number of Visible Mountains", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/finding-the-number-of-visible-mountains", + "solutionLink": "#" + }, + { + "problemName": "2346. Compute the Rank as a Percentage", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/compute-the-rank-as-a-percentage", + "solutionLink": "#" + }, + { + "problemName": "2347. Best Poker Hand", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/best-poker-hand", + "solutionLink": "#" + }, + { + "problemName": "2348. Number of Zero-Filled Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-zero-filled-subarrays", + "solutionLink": "/dsa-solutions/lc-solutions/2300-2399/number-of-zero-filled-subarrays" + }, + { + "problemName": "2349. Design a Number Container System", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-a-number-container-system", + "solutionLink": "#" + }, + { + "problemName": "2350. Shortest Impossible Sequence of Rolls", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/shortest-impossible-sequence-of-rolls", + "solutionLink": "#" + }, + { + "problemName": "2351. First Letter to Appear Twice", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/first-letter-to-appear-twice", + "solutionLink": "#" + }, + { + "problemName": "2352. Equal Row and Column Pairs", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/equal-row-and-column-pairs", + "solutionLink": "#" + }, + { + "problemName": "2353. Design a Food Rating System", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-a-food-rating-system", + "solutionLink": "/dsa-solutions/lc-solutions/2300-2399/design-a-food-rating-system" + }, + { + "problemName": "2354. Number of Excellent Pairs", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-excellent-pairs", + "solutionLink": "#" + }, + { + "problemName": "2355. Maximum Number of Books You Can Take", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-books-you-can-take", + "solutionLink": "#" + }, + { + "problemName": "2356. Number of Unique Subjects Taught by Each Teacher", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-unique-subjects-taught-by-each-teacher", + "solutionLink": "#" + }, + { + "problemName": "2357. Make Array Zero by Subtracting Equal Amounts", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts", + "solutionLink": "#" + }, + { + "problemName": "2358. Maximum Number of Groups Entering a Competition", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition", + "solutionLink": "#" + }, + { + "problemName": "2359. Find Closest Node to Given Two Nodes", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-closest-node-to-given-two-nodes", + "solutionLink": "#" + }, + { + "problemName": "2360. Longest Cycle in a Graph", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/longest-cycle-in-a-graph", + "solutionLink": "#" + }, + { + "problemName": "2361. Minimum Costs Using the Train Line", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-costs-using-the-train-line", + "solutionLink": "#" + }, + { + "problemName": "2362. Generate the Invoice", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/generate-the-invoice", + "solutionLink": "#" + }, + { + "problemName": "2363. Merge Similar Items", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/merge-similar-items", + "solutionLink": "#" + }, + { + "problemName": "2364. Count Number of Bad Pairs", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-number-of-bad-pairs", + "solutionLink": "#" + }, + { + "problemName": "2365. Task Scheduler II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/task-scheduler-ii", + "solutionLink": "#" + }, + { + "problemName": "2366. Minimum Replacements to Sort the Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-replacements-to-sort-the-array", + "solutionLink": "#" + }, + { + "problemName": "2367. Number of Arithmetic Triplets", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-arithmetic-triplets", + "solutionLink": "/dsa-solutions/lc-solutions/2300-2399/number-of-arithmetic-triples" + }, + { + "problemName": "2368. Reachable Nodes With Restrictions", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reachable-nodes-with-restrictions", + "solutionLink": "#" + }, + { + "problemName": "2369. Check if There is a Valid Partition For The Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array", + "solutionLink": "#" + }, + { + "problemName": "2370. Longest Ideal Subsequence", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-ideal-subsequence", + "solutionLink": "#" + }, + { + "problemName": "2371. Minimize Maximum Value in a Grid", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimize-maximum-value-in-a-grid", + "solutionLink": "#" + }, + { + "problemName": "2372. Calculate the Influence of Each Salesperson", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/calculate-the-influence-of-each-salesperson", + "solutionLink": "#" + }, + { + "problemName": "2373. Largest Local Values in a Matrix", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/largest-local-values-in-a-matrix", + "solutionLink": "#" + }, + { + "problemName": "2374. Node With Highest Edge Score", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/node-with-highest-edge-score", + "solutionLink": "#" + }, + { + "problemName": "2375. Construct Smallest Number From DI String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/construct-smallest-number-from-di-string", + "solutionLink": "#" + }, + { + "problemName": "2376. Count Special Integers", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-special-integers", + "solutionLink": "#" + }, + { + "problemName": "2377. Sort the Olympic Table", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sort-the-olympic-table", + "solutionLink": "#" + }, + { + "problemName": "2378. Choose Edges to Maximize Score in a Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/choose-edges-to-maximize-score-in-a-tree", + "solutionLink": "#" + }, + { + "problemName": "2379. Minimum Recolors to Get K Consecutive Black Blocks", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks", + "solutionLink": "#" + }, + { + "problemName": "2380. Time Needed to Rearrange a Binary String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string", + "solutionLink": "#" + }, + { + "problemName": "2381. Shifting Letters II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shifting-letters-ii", + "solutionLink": "#" + }, + { + "problemName": "2382. Maximum Segment Sum After Removals", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-segment-sum-after-removals", + "solutionLink": "#" + }, + { + "problemName": "2383. Minimum Hours of Training to Win a Competition", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition", + "solutionLink": "#" + }, + { + "problemName": "2384. Largest Palindromic Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/largest-palindromic-number", + "solutionLink": "#" + }, + { + "problemName": "2385. Amount of Time for Binary Tree to Be Infected", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected", + "solutionLink": "#" + }, + { + "problemName": "2386. Find the K-Sum of an Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-the-k-sum-of-an-array", + "solutionLink": "#" + }, + { + "problemName": "2387. Median of a Row Wise Sorted Matrix", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/median-of-a-row-wise-sorted-matrix", + "solutionLink": "#" + }, + { + "problemName": "2388. Change Null Values in a Table to the Previous Value", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/change-null-values-in-a-table-to-the-previous-value", + "solutionLink": "#" + }, + { + "problemName": "2389. Longest Subsequence With Limited Sum", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/longest-subsequence-with-limited-sum", + "solutionLink": "#" + }, + { + "problemName": "2390. Removing Stars From a String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/removing-stars-from-a-string", + "solutionLink": "#" + }, + { + "problemName": "2391. Minimum Amount of Time to Collect Garbage", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage", + "solutionLink": "#" + }, + { + "problemName": "2392. Build a Matrix With Conditions", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/build-a-matrix-with-conditions", + "solutionLink": "#" + }, + { + "problemName": "2393. Count Strictly Increasing Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-strictly-increasing-subarrays", + "solutionLink": "#" + }, + { + "problemName": "2394. Employees With Deductions", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/employees-with-deductions", + "solutionLink": "#" + }, + { + "problemName": "2395. Find Subarrays With Equal Sum", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-subarrays-with-equal-sum", + "solutionLink": "#" + }, + { + "problemName": "2396. Strictly Palindromic Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/strictly-palindromic-number", + "solutionLink": "#" + }, + { + "problemName": "2397. Maximum Rows Covered by Columns", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-rows-covered-by-columns", + "solutionLink": "#" + }, + { + "problemName": "2398. Maximum Number of Robots Within Budget", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-robots-within-budget", + "solutionLink": "#" + }, + { + "problemName": "2399. Check Distances Between Same Letters", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-distances-between-same-letters", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/2400-2499.md b/problems/leetcode-problems/2400-2499.md new file mode 100644 index 0000000..f7376a1 --- /dev/null +++ b/problems/leetcode-problems/2400-2499.md @@ -0,0 +1,622 @@ +--- +id: 2400-2499 +title: LeetCode Problems 2400 - 2499 +sidebar_label: 2400 - 2499 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 2400 - 2499 + - DSA problems +--- + +export const problems = [ + { + "problemName": "2400. Number of Ways to Reach a Position After Exactly k Steps", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps", + "solutionLink": "#" + }, + { + "problemName": "2401. Longest Nice Subarray", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-nice-subarray", + "solutionLink": "#" + }, + { + "problemName": "2402. Meeting Rooms III", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/meeting-rooms-iii", + "solutionLink": "#" + }, + { + "problemName": "2403. Minimum Time to Kill All Monsters", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-to-kill-all-monsters", + "solutionLink": "#" + }, + { + "problemName": "2404. Most Frequent Even Element", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/most-frequent-even-element", + "solutionLink": "#" + }, + { + "problemName": "2405. Optimal Partition of String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/optimal-partition-of-string", + "solutionLink": "#" + }, + { + "problemName": "2406. Divide Intervals Into Minimum Number of Groups", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups", + "solutionLink": "#" + }, + { + "problemName": "2407. Longest Increasing Subsequence II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/longest-increasing-subsequence-ii", + "solutionLink": "#" + }, + { + "problemName": "2408. Design SQL", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-sql", + "solutionLink": "#" + }, + { + "problemName": "2409. Count Days Spent Together", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-days-spent-together", + "solutionLink": "#" + }, + { + "problemName": "2410. Maximum Matching of Players With Trainers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-matching-of-players-with-trainers", + "solutionLink": "#" + }, + { + "problemName": "2411. Smallest Subarrays With Maximum Bitwise OR", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/smallest-subarrays-with-maximum-bitwise-or", + "solutionLink": "#" + }, + { + "problemName": "2412. Minimum Money Required Before Transactions", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-money-required-before-transactions", + "solutionLink": "#" + }, + { + "problemName": "2413. Smallest Even Multiple", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/smallest-even-multiple", + "solutionLink": "#" + }, + { + "problemName": "2414. Length of the Longest Alphabetical Continuous Substring", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring", + "solutionLink": "/dsa-solutions/lc-solutions/2400-2499/length-of-the-longest-alphabetical-continuous-substring" + }, + { + "problemName": "2415. Reverse Odd Levels of Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reverse-odd-levels-of-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "2416. Sum of Prefix Scores of Strings", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sum-of-prefix-scores-of-strings", + "solutionLink": "#" + }, + { + "problemName": "2417. Closest Fair Integer", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/closest-fair-integer", + "solutionLink": "#" + }, + { + "problemName": "2418. Sort the People", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sort-the-people", + "solutionLink": "#" + }, + { + "problemName": "2419. Longest Subarray With Maximum Bitwise AND", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and", + "solutionLink": "#" + }, + { + "problemName": "2420. Find All Good Indices", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-all-good-indices", + "solutionLink": "#" + }, + { + "problemName": "2421. Number of Good Paths", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-good-paths", + "solutionLink": "#" + }, + { + "problemName": "2422. Merge Operations to Turn Array Into a Palindrome", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/merge-operations-to-turn-array-into-a-palindrome", + "solutionLink": "#" + }, + { + "problemName": "2423. Remove Letter To Equalize Frequency", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/remove-letter-to-equalize-frequency", + "solutionLink": "#" + }, + { + "problemName": "2424. Longest Uploaded Prefix", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-uploaded-prefix", + "solutionLink": "#" + }, + { + "problemName": "2425. Bitwise XOR of All Pairings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/bitwise-xor-of-all-pairings", + "solutionLink": "#" + }, + { + "problemName": "2426. Number of Pairs Satisfying Inequality", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-pairs-satisfying-inequality", + "solutionLink": "#" + }, + { + "problemName": "2427. Number of Common Factors", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-common-factors", + "solutionLink": "#" + }, + { + "problemName": "2428. Maximum Sum of an Hourglass", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-sum-of-an-hourglass", + "solutionLink": "#" + }, + { + "problemName": "2429. Minimize XOR", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimize-xor", + "solutionLink": "#" + }, + { + "problemName": "2430. Maximum Deletions on a String", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-deletions-on-a-string", + "solutionLink": "#" + }, + { + "problemName": "2431. Maximize Total Tastiness of Purchased Fruits", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximize-total-tastiness-of-purchased-fruits", + "solutionLink": "#" + }, + { + "problemName": "2432. The Employee That Worked on the Longest Task", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/the-employee-that-worked-on-the-longest-task", + "solutionLink": "#" + }, + { + "problemName": "2433. Find The Original Array of Prefix Xor", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-original-array-of-prefix-xor", + "solutionLink": "#" + }, + { + "problemName": "2434. Using a Robot to Print the Lexicographically Smallest String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string", + "solutionLink": "#" + }, + { + "problemName": "2435. Paths in Matrix Whose Sum Is Divisible by K", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k", + "solutionLink": "#" + }, + { + "problemName": "2436. Minimum Split Into Subarrays With GCD Greater Than One", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-split-into-subarrays-with-gcd-greater-than-one", + "solutionLink": "#" + }, + { + "problemName": "2437. Number of Valid Clock Times", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-valid-clock-times", + "solutionLink": "#" + }, + { + "problemName": "2438. Range Product Queries of Powers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/range-product-queries-of-powers", + "solutionLink": "#" + }, + { + "problemName": "2439. Minimize Maximum of Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimize-maximum-of-array", + "solutionLink": "#" + }, + { + "problemName": "2440. Create Components With Same Value", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/create-components-with-same-value", + "solutionLink": "#" + }, + { + "problemName": "2441. Largest Positive Integer That Exists With Its Negative", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative", + "solutionLink": "#" + }, + { + "problemName": "2442. Count Number of Distinct Integers After Reverse Operations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-number-of-distinct-integers-after-reverse-operations", + "solutionLink": "#" + }, + { + "problemName": "2443. Sum of Number and Its Reverse", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-of-number-and-its-reverse", + "solutionLink": "#" + }, + { + "problemName": "2444. Count Subarrays With Fixed Bounds", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-subarrays-with-fixed-bounds", + "solutionLink": "#" + }, + { + "problemName": "2445. Number of Nodes With Value One", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-nodes-with-value-one", + "solutionLink": "#" + }, + { + "problemName": "2446. Determine if Two Events Have Conflict", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/determine-if-two-events-have-conflict", + "solutionLink": "#" + }, + { + "problemName": "2447. Number of Subarrays With GCD Equal to K", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-subarrays-with-gcd-equal-to-k", + "solutionLink": "#" + }, + { + "problemName": "2448. Minimum Cost to Make Array Equal", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-make-array-equal", + "solutionLink": "#" + }, + { + "problemName": "2449. Minimum Number of Operations to Make Arrays Similar", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-operations-to-make-arrays-similar", + "solutionLink": "#" + }, + { + "problemName": "2450. Number of Distinct Binary Strings After Applying Operations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-distinct-binary-strings-after-applying-operations", + "solutionLink": "#" + }, + { + "problemName": "2451. Odd String Difference", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/odd-string-difference", + "solutionLink": "#" + }, + { + "problemName": "2452. Words Within Two Edits of Dictionary", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/words-within-two-edits-of-dictionary", + "solutionLink": "#" + }, + { + "problemName": "2453. Destroy Sequential Targets", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/destroy-sequential-targets", + "solutionLink": "#" + }, + { + "problemName": "2454. Next Greater Element IV", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/next-greater-element-iv", + "solutionLink": "#" + }, + { + "problemName": "2455. Average Value of Even Numbers That Are Divisible by Three", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/average-value-of-even-numbers-that-are-divisible-by-three", + "solutionLink": "#" + }, + { + "problemName": "2456. Most Popular Video Creator", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/most-popular-video-creator", + "solutionLink": "#" + }, + { + "problemName": "2457. Minimum Addition to Make Integer Beautiful", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-addition-to-make-integer-beautiful", + "solutionLink": "#" + }, + { + "problemName": "2458. Height of Binary Tree After Subtree Removal Queries", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/height-of-binary-tree-after-subtree-removal-queries", + "solutionLink": "#" + }, + { + "problemName": "2459. Sort Array by Moving Items to Empty Space", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sort-array-by-moving-items-to-empty-space", + "solutionLink": "#" + }, + { + "problemName": "2460. Apply Operations to an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/apply-operations-to-an-array", + "solutionLink": "#" + }, + { + "problemName": "2461. Maximum Sum of Distinct Subarrays With Length K", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k", + "solutionLink": "#" + }, + { + "problemName": "2462. Total Cost to Hire K Workers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/total-cost-to-hire-k-workers", + "solutionLink": "#" + }, + { + "problemName": "2463. Minimum Total Distance Traveled", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-total-distance-traveled", + "solutionLink": "#" + }, + { + "problemName": "2464. Minimum Subarrays in a Valid Split", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-subarrays-in-a-valid-split", + "solutionLink": "#" + }, + { + "problemName": "2465. Number of Distinct Averages", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-distinct-averages", + "solutionLink": "#" + }, + { + "problemName": "2466. Count Ways To Build Good Strings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-ways-to-build-good-strings", + "solutionLink": "#" + }, + { + "problemName": "2467. Most Profitable Path in a Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/most-profitable-path-in-a-tree", + "solutionLink": "#" + }, + { + "problemName": "2468. Split Message Based on Limit", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/split-message-based-on-limit", + "solutionLink": "#" + }, + { + "problemName": "2469. Convert the Temperature", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/convert-the-temperature", + "solutionLink": "#" + }, + { + "problemName": "2470. Number of Subarrays With LCM Equal to K", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k", + "solutionLink": "#" + }, + { + "problemName": "2471. Minimum Number of Operations to Sort a Binary Tree by Level", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level", + "solutionLink": "#" + }, + { + "problemName": "2472. Maximum Number of Non-overlapping Palindrome Substrings", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings", + "solutionLink": "#" + }, + { + "problemName": "2473. Minimum Cost to Buy Apples", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-buy-apples", + "solutionLink": "#" + }, + { + "problemName": "2474. Customers With Strictly Increasing Purchases", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/customers-with-strictly-increasing-purchases", + "solutionLink": "#" + }, + { + "problemName": "2475. Number of Unequal Triplets in Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-unequal-triplets-in-array", + "solutionLink": "#" + }, + { + "problemName": "2476. Closest Nodes Queries in a Binary Search Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree", + "solutionLink": "#" + }, + { + "problemName": "2477. Minimum Fuel Cost to Report to the Capital", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital", + "solutionLink": "#" + }, + { + "problemName": "2478. Number of Beautiful Partitions", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-beautiful-partitions", + "solutionLink": "#" + }, + { + "problemName": "2479. Maximum XOR of Two Non-Overlapping Subtrees", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-xor-of-two-non-overlapping-subtrees", + "solutionLink": "#" + }, + { + "problemName": "2480. Form a Chemical Bond", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/form-a-chemical-bond", + "solutionLink": "#" + }, + { + "problemName": "2481. Minimum Cuts to Divide a Circle", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-cuts-to-divide-a-circle", + "solutionLink": "#" + }, + { + "problemName": "2482. Difference Between Ones and Zeros in Row and Column", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/difference-between-ones-and-zeros-in-row-and-column", + "solutionLink": "#" + }, + { + "problemName": "2483. Minimum Penalty for a Shop", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-penalty-for-a-shop", + "solutionLink": "#" + }, + { + "problemName": "2484. Count Palindromic Subsequences", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-palindromic-subsequences", + "solutionLink": "#" + }, + { + "problemName": "2485. Find the Pivot Integer", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-pivot-integer", + "solutionLink": "#" + }, + { + "problemName": "2486. Append Characters to String to Make Subsequence", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/append-characters-to-string-to-make-subsequence", + "solutionLink": "#" + }, + { + "problemName": "2487. Remove Nodes From Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-nodes-from-linked-list", + "solutionLink": "#" + }, + { + "problemName": "2488. Count Subarrays With Median K", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-subarrays-with-median-k", + "solutionLink": "#" + }, + { + "problemName": "2489. Number of Substrings With Fixed Ratio", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-substrings-with-fixed-ratio", + "solutionLink": "#" + }, + { + "problemName": "2490. Circular Sentence", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/circular-sentence", + "solutionLink": "#" + }, + { + "problemName": "2491. Divide Players Into Teams of Equal Skill", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/divide-players-into-teams-of-equal-skill", + "solutionLink": "#" + }, + { + "problemName": "2492. Minimum Score of a Path Between Two Cities", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-score-of-a-path-between-two-cities", + "solutionLink": "#" + }, + { + "problemName": "2493. Divide Nodes Into the Maximum Number of Groups", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/divide-nodes-into-the-maximum-number-of-groups", + "solutionLink": "#" + }, + { + "problemName": "2494. Merge Overlapping Events in the Same Hall", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/merge-overlapping-events-in-the-same-hall", + "solutionLink": "#" + }, + { + "problemName": "2495. Number of Subarrays Having Even Product", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-subarrays-having-even-product", + "solutionLink": "#" + }, + { + "problemName": "2496. Maximum Value of a String in an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-value-of-a-string-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "2497. Maximum Star Sum of a Graph", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-star-sum-of-a-graph", + "solutionLink": "#" + }, + { + "problemName": "2498. Frog Jump II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/frog-jump-ii", + "solutionLink": "#" + }, + { + "problemName": "2499. Minimum Total Cost to Make Arrays Unequal", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-total-cost-to-make-arrays-unequal", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/2500-2599.md b/problems/leetcode-problems/2500-2599.md new file mode 100644 index 0000000..373438d --- /dev/null +++ b/problems/leetcode-problems/2500-2599.md @@ -0,0 +1,622 @@ +--- +id: 2500-2599 +title: LeetCode Problems 2500 - 2599 +sidebar_label: 2500 - 2599 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 2500 - 2599 + - DSA problems +--- + +export const problems = [ + { + "problemName": "2500. Delete Greatest Value in Each Row", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/delete-greatest-value-in-each-row", + "solutionLink": "#" + }, + { + "problemName": "2501. Longest Square Streak in an Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-square-streak-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "2502. Design Memory Allocator", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-memory-allocator", + "solutionLink": "#" + }, + { + "problemName": "2503. Maximum Number of Points From Grid Queries", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-points-from-grid-queries", + "solutionLink": "#" + }, + { + "problemName": "2504. Concatenate the Name and the Profession", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/concatenate-the-name-and-the-profession", + "solutionLink": "#" + }, + { + "problemName": "2505. Bitwise OR of All Subsequence Sums", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/bitwise-or-of-all-subsequence-sums", + "solutionLink": "#" + }, + { + "problemName": "2506. Count Pairs Of Similar Strings", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-pairs-of-similar-strings", + "solutionLink": "#" + }, + { + "problemName": "2507. Smallest Value After Replacing With Sum of Prime Factors", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/smallest-value-after-replacing-with-sum-of-prime-factors", + "solutionLink": "#" + }, + { + "problemName": "2508. Add Edges to Make Degrees of All Nodes Even", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/add-edges-to-make-degrees-of-all-nodes-even", + "solutionLink": "#" + }, + { + "problemName": "2509. Cycle Length Queries in a Tree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/cycle-length-queries-in-a-tree", + "solutionLink": "#" + }, + { + "problemName": "2510. Check if There is a Path With Equal Number of 0's And 1's", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-there-is-a-path-with-equal-number-of-0s-and-1s", + "solutionLink": "#" + }, + { + "problemName": "2511. Maximum Enemy Forts That Can Be Captured", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-enemy-forts-that-can-be-captured", + "solutionLink": "#" + }, + { + "problemName": "2512. Reward Top K Students", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/reward-top-k-students", + "solutionLink": "#" + }, + { + "problemName": "2513. Minimize the Maximum of Two Arrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimize-the-maximum-of-two-arrays", + "solutionLink": "#" + }, + { + "problemName": "2514. Count Anagrams", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-anagrams", + "solutionLink": "#" + }, + { + "problemName": "2515. Shortest Distance to Target String in a Circular Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/shortest-distance-to-target-string-in-a-circular-array", + "solutionLink": "#" + }, + { + "problemName": "2516. Take K of Each Character From Left and Right", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/take-k-of-each-character-from-left-and-right", + "solutionLink": "#" + }, + { + "problemName": "2517. Maximum Tastiness of Candy Basket", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-tastiness-of-candy-basket", + "solutionLink": "#" + }, + { + "problemName": "2518. Number of Great Partitions", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-great-partitions", + "solutionLink": "#" + }, + { + "problemName": "2519. Count the Number of K-Big Indices", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-k-big-indices", + "solutionLink": "#" + }, + { + "problemName": "2520. Count the Digits That Divide a Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-the-digits-that-divide-a-number", + "solutionLink": "#" + }, + { + "problemName": "2521. Distinct Prime Factors of Product of Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/distinct-prime-factors-of-product-of-array", + "solutionLink": "#" + }, + { + "problemName": "2522. Partition String Into Substrings With Values at Most K", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/partition-string-into-substrings-with-values-at-most-k", + "solutionLink": "#" + }, + { + "problemName": "2523. Closest Prime Numbers in Range", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/closest-prime-numbers-in-range", + "solutionLink": "#" + }, + { + "problemName": "2524. Maximum Frequency Score of a Subarray", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-frequency-score-of-a-subarray", + "solutionLink": "#" + }, + { + "problemName": "2525. Categorize Box According to Criteria", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/categorize-box-according-to-criteria", + "solutionLink": "#" + }, + { + "problemName": "2526. Find Consecutive Integers from a Data Stream", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-consecutive-integers-from-a-data-stream", + "solutionLink": "#" + }, + { + "problemName": "2527. Find Xor-Beauty of Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-xor-beauty-of-array", + "solutionLink": "#" + }, + { + "problemName": "2528. Maximize the Minimum Powered City", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximize-the-minimum-powered-city", + "solutionLink": "#" + }, + { + "problemName": "2529. Maximum Count of Positive Integer and Negative Integer", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-count-of-positive-integer-and-negative-integer", + "solutionLink": "#" + }, + { + "problemName": "2530. Maximal Score After Applying K Operations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximal-score-after-applying-k-operations", + "solutionLink": "#" + }, + { + "problemName": "2531. Make Number of Distinct Characters Equal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/make-number-of-distinct-characters-equal", + "solutionLink": "#" + }, + { + "problemName": "2532. Time to Cross a Bridge", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/time-to-cross-a-bridge", + "solutionLink": "#" + }, + { + "problemName": "2533. Number of Good Binary Strings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-good-binary-strings", + "solutionLink": "#" + }, + { + "problemName": "2534. Time Taken to Cross the Door", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/time-taken-to-cross-the-door", + "solutionLink": "#" + }, + { + "problemName": "2535. Difference Between Element Sum and Digit Sum of an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/difference-between-element-sum-and-digit-sum-of-an-array", + "solutionLink": "/dsa-solutions/lc-solutions/2500-2599/difference-between-element-sum-and-digit-sum-of-an-array" + }, + { + "problemName": "2536. Increment Submatrices by One", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/increment-submatrices-by-one", + "solutionLink": "#" + }, + { + "problemName": "2537. Count the Number of Good Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-good-subarrays", + "solutionLink": "#" + }, + { + "problemName": "2538. Difference Between Maximum and Minimum Price Sum", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/difference-between-maximum-and-minimum-price-sum", + "solutionLink": "#" + }, + { + "problemName": "2539. Count the Number of Good Subsequences", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-good-subsequences", + "solutionLink": "#" + }, + { + "problemName": "2540. Minimum Common Value", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-common-value", + "solutionLink": "#" + }, + { + "problemName": "2541. Minimum Operations to Make Array Equal II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-make-array-equal-ii", + "solutionLink": "#" + }, + { + "problemName": "2542. Maximum Subsequence Score", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-subsequence-score", + "solutionLink": "#" + }, + { + "problemName": "2543. Check if Point Is Reachable", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/check-if-point-is-reachable", + "solutionLink": "/dsa-solutions/lc-solutions/2500-3000/check-if-point-is-reachable" + }, + { + "problemName": "2544. Alternating Digit Sum", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/alternating-digit-sum", + "solutionLink": "#" + }, + { + "problemName": "2545. Sort the Students by Their Kth Score", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sort-the-students-by-their-kth-score", + "solutionLink": "#" + }, + { + "problemName": "2546. Apply Bitwise Operations to Make Strings Equal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/apply-bitwise-operations-to-make-strings-equal", + "solutionLink": "#" + }, + { + "problemName": "2547. Minimum Cost to Split an Array", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-split-an-array", + "solutionLink": "#" + }, + { + "problemName": "2548. Maximum Price to Fill a Bag", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-price-to-fill-a-bag", + "solutionLink": "#" + }, + { + "problemName": "2549. Count Distinct Numbers on Board", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-distinct-numbers-on-board", + "solutionLink": "#" + }, + { + "problemName": "2550. Count Collisions of Monkeys on a Polygon", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-collisions-of-monkeys-on-a-polygon", + "solutionLink": "#" + }, + { + "problemName": "2551. Put Marbles in Bags", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/put-marbles-in-bags", + "solutionLink": "#" + }, + { + "problemName": "2552. Count Increasing Quadruplets", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-increasing-quadruplets", + "solutionLink": "#" + }, + { + "problemName": "2553. Separate the Digits in an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/separate-the-digits-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "2554. Maximum Number of Integers to Choose From a Range I", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-integers-to-choose-from-a-range-i", + "solutionLink": "#" + }, + { + "problemName": "2555. Maximize Win From Two Segments", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximize-win-from-two-segments", + "solutionLink": "#" + }, + { + "problemName": "2556. Disconnect Path in a Binary Matrix by at Most One Flip", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/disconnect-path-in-a-binary-matrix-by-at-most-one-flip", + "solutionLink": "#" + }, + { + "problemName": "2557. Maximum Number of Integers to Choose From a Range II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-integers-to-choose-from-a-range-ii", + "solutionLink": "#" + }, + { + "problemName": "2558. Take Gifts From the Richest Pile", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/take-gifts-from-the-richest-pile", + "solutionLink": "#" + }, + { + "problemName": "2559. Count Vowel Strings in Ranges", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-vowel-strings-in-ranges", + "solutionLink": "#" + }, + { + "problemName": "2560. House Robber IV", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/house-robber-iv", + "solutionLink": "#" + }, + { + "problemName": "2561. Rearranging Fruits", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/rearranging-fruits", + "solutionLink": "#" + }, + { + "problemName": "2562. Find the Array Concatenation Value", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-array-concatenation-value", + "solutionLink": "#" + }, + { + "problemName": "2563. Count the Number of Fair Pairs", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-fair-pairs", + "solutionLink": "#" + }, + { + "problemName": "2564. Substring XOR Queries", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/substring-xor-queries", + "solutionLink": "#" + }, + { + "problemName": "2565. Subsequence With the Minimum Score", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/subsequence-with-the-minimum-score", + "solutionLink": "#" + }, + { + "problemName": "2566. Maximum Difference by Remapping a Digit", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-difference-by-remapping-a-digit", + "solutionLink": "#" + }, + { + "problemName": "2567. Minimum Score by Changing Two Elements", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-score-by-changing-two-elements", + "solutionLink": "#" + }, + { + "problemName": "2568. Minimum Impossible OR", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-impossible-or", + "solutionLink": "#" + }, + { + "problemName": "2569. Handling Sum Queries After Update", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/handling-sum-queries-after-update", + "solutionLink": "#" + }, + { + "problemName": "2570. Merge Two 2D Arrays by Summing Values", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/merge-two-2d-arrays-by-summing-values", + "solutionLink": "#" + }, + { + "problemName": "2571. Minimum Operations to Reduce an Integer to 0", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-reduce-an-integer-to-0", + "solutionLink": "#" + }, + { + "problemName": "2572. Count the Number of Square-Free Subsets", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-square-free-subsets", + "solutionLink": "#" + }, + { + "problemName": "2573. Find the String with LCP", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-the-string-with-lcp", + "solutionLink": "#" + }, + { + "problemName": "2574. Left and Right Sum Differences", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/left-and-right-sum-differences", + "solutionLink": "#" + }, + { + "problemName": "2575. Find the Divisibility Array of a String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-divisibility-array-of-a-string", + "solutionLink": "#" + }, + { + "problemName": "2576. Find the Maximum Number of Marked Indices", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-maximum-number-of-marked-indices", + "solutionLink": "#" + }, + { + "problemName": "2577. Minimum Time to Visit a Cell In a Grid", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-to-visit-a-cell-in-a-grid", + "solutionLink": "#" + }, + { + "problemName": "2578. Split With Minimum Sum", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/split-with-minimum-sum", + "solutionLink": "#" + }, + { + "problemName": "2579. Count Total Number of Colored Cells", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-total-number-of-colored-cells", + "solutionLink": "#" + }, + { + "problemName": "2580. Count Ways to Group Overlapping Ranges", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-ways-to-group-overlapping-ranges", + "solutionLink": "#" + }, + { + "problemName": "2581. Count Number of Possible Root Nodes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-number-of-possible-root-nodes", + "solutionLink": "#" + }, + { + "problemName": "2582. Pass the Pillow", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/pass-the-pillow", + "solutionLink": "#" + }, + { + "problemName": "2583. Kth Largest Sum in a Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "2584. Split the Array to Make Coprime Products", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/split-the-array-to-make-coprime-products", + "solutionLink": "#" + }, + { + "problemName": "2585. Number of Ways to Earn Points", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-earn-points", + "solutionLink": "#" + }, + { + "problemName": "2586. Count the Number of Vowel Strings in Range", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-vowel-strings-in-range", + "solutionLink": "#" + }, + { + "problemName": "2587. Rearrange Array to Maximize Prefix Score", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/rearrange-array-to-maximize-prefix-score", + "solutionLink": "#" + }, + { + "problemName": "2588. Count the Number of Beautiful Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-beautiful-subarrays", + "solutionLink": "#" + }, + { + "problemName": "2589. Minimum Time to Complete All Tasks", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-to-complete-all-tasks", + "solutionLink": "#" + }, + { + "problemName": "2590. Design a Todo List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/design-a-todo-list", + "solutionLink": "#" + }, + { + "problemName": "2591. Distribute Money to Maximum Children", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/distribute-money-to-maximum-children", + "solutionLink": "#" + }, + { + "problemName": "2592. Maximize Greatness of an Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximize-greatness-of-an-array", + "solutionLink": "#" + }, + { + "problemName": "2593. Find Score of an Array After Marking All Elements", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-score-of-an-array-after-marking-all-elements", + "solutionLink": "#" + }, + { + "problemName": "2594. Minimum Time to Repair Cars", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-to-repair-cars", + "solutionLink": "#" + }, + { + "problemName": "2595. Number of Even and Odd Bits", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-even-and-odd-bits", + "solutionLink": "#" + }, + { + "problemName": "2596. Check Knight Tour Configuration", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-knight-tour-configuration", + "solutionLink": "#" + }, + { + "problemName": "2597. The Number of Beautiful Subsets", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-number-of-beautiful-subsets", + "solutionLink": "#" + }, + { + "problemName": "2598. Smallest Missing Non-negative Integer After Operations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/smallest-missing-non-negative-integer-after-operations", + "solutionLink": "#" + }, + { + "problemName": "2599. Make the Prefix Sum Non-negative", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/make-the-prefix-sum-non-negative", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/2600-2699.md b/problems/leetcode-problems/2600-2699.md new file mode 100644 index 0000000..3fb9d5b --- /dev/null +++ b/problems/leetcode-problems/2600-2699.md @@ -0,0 +1,622 @@ +--- +id: 2600-2699 +title: LeetCode Problems 2600 - 2699 +sidebar_label: 2600 - 2699 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 2600 - 2699 + - DSA problems +--- + +export const problems = [ + { + "problemName": "2600. K Items With the Maximum Sum", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/k-items-with-the-maximum-sum", + "solutionLink": "#" + }, + { + "problemName": "2601. Prime Subtraction Operation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/prime-subtraction-operation", + "solutionLink": "#" + }, + { + "problemName": "2602. Minimum Operations to Make All Array Elements Equal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-make-all-array-elements-equal", + "solutionLink": "#" + }, + { + "problemName": "2603. Collect Coins in a Tree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/collect-coins-in-a-tree", + "solutionLink": "#" + }, + { + "problemName": "2604. Minimum Time to Eat All Grains", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-to-eat-all-grains", + "solutionLink": "#" + }, + { + "problemName": "2605. Form Smallest Number From Two Digit Arrays", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/form-smallest-number-from-two-digit-arrays", + "solutionLink": "#" + }, + { + "problemName": "2606. Find the Substring With Maximum Cost", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-substring-with-maximum-cost", + "solutionLink": "#" + }, + { + "problemName": "2607. Make K-Subarray Sums Equal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/make-k-subarray-sums-equal", + "solutionLink": "#" + }, + { + "problemName": "2608. Shortest Cycle in a Graph", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/shortest-cycle-in-a-graph", + "solutionLink": "#" + }, + { + "problemName": "2609. Find the Longest Balanced Substring of a Binary String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-longest-balanced-substring-of-a-binary-string", + "solutionLink": "#" + }, + { + "problemName": "2610. Convert an Array Into a 2D Array With Conditions", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/convert-an-array-into-a-2d-array-with-conditions", + "solutionLink": "/dsa-solutions/lc-solutions/2500-3000/convert-an-array-into-a-2d-array-with-conditions" + }, + { + "problemName": "2611. Mice and Cheese", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/mice-and-cheese", + "solutionLink": "#" + }, + { + "problemName": "2612. Minimum Reverse Operations", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-reverse-operations", + "solutionLink": "#" + }, + { + "problemName": "2613. Beautiful Pairs", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/beautiful-pairs", + "solutionLink": "#" + }, + { + "problemName": "2614. Prime In Diagonal", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/prime-in-diagonal", + "solutionLink": "#" + }, + { + "problemName": "2615. Sum of Distances", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-of-distances", + "solutionLink": "#" + }, + { + "problemName": "2616. Minimize the Maximum Difference of Pairs", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimize-the-maximum-difference-of-pairs", + "solutionLink": "#" + }, + { + "problemName": "2617. Minimum Number of Visited Cells in a Grid", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-visited-cells-in-a-grid", + "solutionLink": "#" + }, + { + "problemName": "2618. Check if Object Instance of Class", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-object-instance-of-class", + "solutionLink": "#" + }, + { + "problemName": "2619. Array Prototype Last", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/array-prototype-last", + "solutionLink": "#" + }, + { + "problemName": "2620. Counter", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/counter", + "solutionLink": "#" + }, + { + "problemName": "2621. Sleep", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sleep", + "solutionLink": "#" + }, + { + "problemName": "2622. Cache With Time Limit", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/cache-with-time-limit", + "solutionLink": "#" + }, + { + "problemName": "2623. Memoize", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/memoize", + "solutionLink": "#" + }, + { + "problemName": "2624. Snail Traversal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/snail-traversal", + "solutionLink": "#" + }, + { + "problemName": "2625. Flatten Deeply Nested Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/flatten-deeply-nested-array", + "solutionLink": "#" + }, + { + "problemName": "2626. Array Reduce Transformation", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/array-reduce-transformation", + "solutionLink": "#" + }, + { + "problemName": "2627. Debounce", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/debounce", + "solutionLink": "#" + }, + { + "problemName": "2628. JSON Deep Equal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/json-deep-equal", + "solutionLink": "#" + }, + { + "problemName": "2629. Function Composition", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/function-composition", + "solutionLink": "#" + }, + { + "problemName": "2630. Memoize II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/memoize-ii", + "solutionLink": "#" + }, + { + "problemName": "2631. Group By", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/group-by", + "solutionLink": "#" + }, + { + "problemName": "2632. Curry", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/curry", + "solutionLink": "#" + }, + { + "problemName": "2633. Convert Object to JSON String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/convert-object-to-json-string", + "solutionLink": "#" + }, + { + "problemName": "2634. Filter Elements from Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/filter-elements-from-array", + "solutionLink": "#" + }, + { + "problemName": "2635. Apply Transform Over Each Element in Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/apply-transform-over-each-element-in-array", + "solutionLink": "#" + }, + { + "problemName": "2636. Promise Pool", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/promise-pool", + "solutionLink": "#" + }, + { + "problemName": "2637. Promise Time Limit", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/promise-time-limit", + "solutionLink": "#" + }, + { + "problemName": "2638. Count the Number of K-Free Subsets", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-k-free-subsets", + "solutionLink": "#" + }, + { + "problemName": "2639. Find the Width of Columns of a Grid", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-width-of-columns-of-a-grid", + "solutionLink": "#" + }, + { + "problemName": "2640. Find the Score of All Prefixes of an Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-score-of-all-prefixes-of-an-array", + "solutionLink": "#" + }, + { + "problemName": "2641. Cousins in Binary Tree II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/cousins-in-binary-tree-ii", + "solutionLink": "#" + }, + { + "problemName": "2642. Design Graph With Shortest Path Calculator", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/design-graph-with-shortest-path-calculator", + "solutionLink": "#" + }, + { + "problemName": "2643. Row With Maximum Ones", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/row-with-maximum-ones", + "solutionLink": "#" + }, + { + "problemName": "2644. Find the Maximum Divisibility Score", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-maximum-divisibility-score", + "solutionLink": "#" + }, + { + "problemName": "2645. Minimum Additions to Make Valid String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-additions-to-make-valid-string", + "solutionLink": "#" + }, + { + "problemName": "2646. Minimize the Total Price of the Trips", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimize-the-total-price-of-the-trips", + "solutionLink": "#" + }, + { + "problemName": "2647. Color the Triangle Red", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/color-the-triangle-red", + "solutionLink": "#" + }, + { + "problemName": "2648. Generate Fibonacci Sequence", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/generate-fibonacci-sequence", + "solutionLink": "#" + }, + { + "problemName": "2649. Nested Array Generator", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/nested-array-generator", + "solutionLink": "#" + }, + { + "problemName": "2650. Design Cancellable Function", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/design-cancellable-function", + "solutionLink": "#" + }, + { + "problemName": "2651. Calculate Delayed Arrival Time", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/calculate-delayed-arrival-time", + "solutionLink": "#" + }, + { + "problemName": "2652. Sum Multiples", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sum-multiples", + "solutionLink": "#" + }, + { + "problemName": "2653. Sliding Subarray Beauty", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sliding-subarray-beauty", + "solutionLink": "/dsa-solutions/lc-solutions/2600-2699/sliding-subarray-beauty" + }, + { + "problemName": "2654. Minimum Number of Operations to Make All Array Elements Equal to 1", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-operations-to-make-all-array-elements-equal-to-1", + "solutionLink": "#" + }, + { + "problemName": "2655. Find Maximal Uncovered Ranges", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-maximal-uncovered-ranges", + "solutionLink": "#" + }, + { + "problemName": "2656. Maximum Sum With Exactly K Elements", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-sum-with-exactly-k-elements", + "solutionLink": "#" + }, + { + "problemName": "2657. Find the Prefix Common Array of Two Arrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-prefix-common-array-of-two-arrays", + "solutionLink": "#" + }, + { + "problemName": "2658. Maximum Number of Fish in a Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-fish-in-a-grid", + "solutionLink": "#" + }, + { + "problemName": "2659. Make Array Empty", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/make-array-empty", + "solutionLink": "#" + }, + { + "problemName": "2660. Determine the Winner of a Bowling Game", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/determine-the-winner-of-a-bowling-game", + "solutionLink": "#" + }, + { + "problemName": "2661. First Completely Painted Row or Column", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/first-completely-painted-row-or-column", + "solutionLink": "#" + }, + { + "problemName": "2662. Minimum Cost of a Path With Special Roads", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-of-a-path-with-special-roads", + "solutionLink": "#" + }, + { + "problemName": "2663. Lexicographically Smallest Beautiful String", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/lexicographically-smallest-beautiful-string", + "solutionLink": "#" + }, + { + "problemName": "2664. The KnightοΏ½s Tour", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/the-knights-tour", + "solutionLink": "#" + }, + { + "problemName": "2665. Counter II", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/counter-ii", + "solutionLink": "#" + }, + { + "problemName": "2666. Allow One Function Call", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/allow-one-function-call", + "solutionLink": "#" + }, + { + "problemName": "2667. Create Hello World Function", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/create-hello-world-function", + "solutionLink": "#" + }, + { + "problemName": "2668. Find Latest Salaries", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-latest-salaries", + "solutionLink": "#" + }, + { + "problemName": "2669. Count Artist Occurrences On Spotify Ranking List", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-artist-occurrences-on-spotify-ranking-list", + "solutionLink": "#" + }, + { + "problemName": "2670. Find the Distinct Difference Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-distinct-difference-array", + "solutionLink": "#" + }, + { + "problemName": "2671. Frequency Tracker", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/frequency-tracker", + "solutionLink": "#" + }, + { + "problemName": "2672. Number of Adjacent Elements With the Same Color", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-adjacent-elements-with-the-same-color", + "solutionLink": "#" + }, + { + "problemName": "2673. Make Costs of Paths Equal in a Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/make-costs-of-paths-equal-in-a-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "2674. Split a Circular Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/split-a-circular-linked-list", + "solutionLink": "#" + }, + { + "problemName": "2675. Array of Objects to Matrix", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/array-of-objects-to-matrix", + "solutionLink": "#" + }, + { + "problemName": "2676. Throttle", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/throttle", + "solutionLink": "#" + }, + { + "problemName": "2677. Chunk Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/chunk-array", + "solutionLink": "#" + }, + { + "problemName": "2678. Number of Senior Citizens", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-senior-citizens", + "solutionLink": "#" + }, + { + "problemName": "2679. Sum in a Matrix", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-in-a-matrix", + "solutionLink": "#" + }, + { + "problemName": "2680. Maximum OR", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-or", + "solutionLink": "#" + }, + { + "problemName": "2681. Power of Heroes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/power-of-heroes", + "solutionLink": "#" + }, + { + "problemName": "2682. Find the Losers of the Circular Game", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-losers-of-the-circular-game", + "solutionLink": "#" + }, + { + "problemName": "2683. Neighboring Bitwise XOR", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/neighboring-bitwise-xor", + "solutionLink": "#" + }, + { + "problemName": "2684. Maximum Number of Moves in a Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-moves-in-a-grid", + "solutionLink": "#" + }, + { + "problemName": "2685. Count the Number of Complete Components", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-complete-components", + "solutionLink": "#" + }, + { + "problemName": "2686. Immediate Food Delivery III", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/immediate-food-delivery-iii", + "solutionLink": "#" + }, + { + "problemName": "2687. Bikes Last Time Used", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/bikes-last-time-used", + "solutionLink": "#" + }, + { + "problemName": "2688. Find Active Users", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-active-users", + "solutionLink": "#" + }, + { + "problemName": "2689. Extract Kth Character From The Rope Tree", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/extract-kth-character-from-the-rope-tree", + "solutionLink": "#" + }, + { + "problemName": "2690. Infinite Method Object", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/infinite-method-object", + "solutionLink": "#" + }, + { + "problemName": "2691. Immutability Helper", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/immutability-helper", + "solutionLink": "#" + }, + { + "problemName": "2692. Make Object Immutable", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/make-object-immutable", + "solutionLink": "#" + }, + { + "problemName": "2693. Call Function with Custom Context", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/call-function-with-custom-context", + "solutionLink": "#" + }, + { + "problemName": "2694. Event Emitter", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/event-emitter", + "solutionLink": "#" + }, + { + "problemName": "2695. Array Wrapper", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/array-wrapper", + "solutionLink": "#" + }, + { + "problemName": "2696. Minimum String Length After Removing Substrings", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-string-length-after-removing-substrings", + "solutionLink": "#" + }, + { + "problemName": "2697. Lexicographically Smallest Palindrome", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/lexicographically-smallest-palindrome", + "solutionLink": "#" + }, + { + "problemName": "2698. Find the Punishment Number of an Integer", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-punishment-number-of-an-integer", + "solutionLink": "#" + }, + { + "problemName": "2699. Modify Graph Edge Weights", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/modify-graph-edge-weights", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/2700-2799.md b/problems/leetcode-problems/2700-2799.md new file mode 100644 index 0000000..7e4a45c --- /dev/null +++ b/problems/leetcode-problems/2700-2799.md @@ -0,0 +1,622 @@ +--- +id: 2700-2799 +title: LeetCode Problems 2700 - 2799 +sidebar_label: 2700 - 2799 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 2700 - 2799 + - DSA problems +--- + +export const problems = [ + { + "problemName": "2700. Differences Between Two Objects", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/differences-between-two-objects", + "solutionLink": "#" + }, + { + "problemName": "2701. Consecutive Transactions with Increasing Amounts", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/consecutive-transactions-with-increasing-amounts", + "solutionLink": "#" + }, + { + "problemName": "2702. Minimum Operations to Make Numbers Non-positive", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-make-numbers-non-positive", + "solutionLink": "#" + }, + { + "problemName": "2703. Return Length of Arguments Passed", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/return-length-of-arguments-passed", + "solutionLink": "/dsa-solutions/lc-solutions/2700-2799/return-length-of-arguments-passed" + }, + { + "problemName": "2704. To Be Or Not To Be", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/to-be-or-not-to-be", + "solutionLink": "#" + }, + { + "problemName": "2705. Compact Object", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/compact-object", + "solutionLink": "#" + }, + { + "problemName": "2706. Buy Two Chocolates", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/buy-two-chocolates", + "solutionLink": "#" + }, + { + "problemName": "2707. Extra Characters in a String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/extra-characters-in-a-string", + "solutionLink": "#" + }, + { + "problemName": "2708. Maximum Strength of a Group", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-strength-of-a-group", + "solutionLink": "#" + }, + { + "problemName": "2709. Greatest Common Divisor Traversal", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/greatest-common-divisor-traversal", + "solutionLink": "#" + }, + { + "problemName": "2710. Remove Trailing Zeros From a String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/remove-trailing-zeros-from-a-string", + "solutionLink": "#" + }, + { + "problemName": "2711. Difference of Number of Distinct Values on Diagonals", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/difference-of-number-of-distinct-values-on-diagonals", + "solutionLink": "#" + }, + { + "problemName": "2712. Minimum Cost to Make All Characters Equal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-make-all-characters-equal", + "solutionLink": "#" + }, + { + "problemName": "2713. Maximum Strictly Increasing Cells in a Matrix", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-strictly-increasing-cells-in-a-matrix", + "solutionLink": "#" + }, + { + "problemName": "2714. Find Shortest Path with K Hops", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-shortest-path-with-k-hops", + "solutionLink": "#" + }, + { + "problemName": "2715. Timeout Cancellation", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/timeout-cancellation", + "solutionLink": "#" + }, + { + "problemName": "2716. Minimize String Length", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimize-string-length", + "solutionLink": "#" + }, + { + "problemName": "2717. Semi-Ordered Permutation", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/semi-ordered-permutation", + "solutionLink": "#" + }, + { + "problemName": "2718. Sum of Matrix After Queries", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-of-matrix-after-queries", + "solutionLink": "#" + }, + { + "problemName": "2719. Count of Integers", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-of-integers", + "solutionLink": "#" + }, + { + "problemName": "2720. Popularity Percentage", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/popularity-percentage", + "solutionLink": "#" + }, + { + "problemName": "2721. Execute Asynchronous Functions in Parallel", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/execute-asynchronous-functions-in-parallel", + "solutionLink": "#" + }, + { + "problemName": "2722. Join Two Arrays by ID", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/join-two-arrays-by-id", + "solutionLink": "#" + }, + { + "problemName": "2723. Add Two Promises", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/add-two-promises", + "solutionLink": "#" + }, + { + "problemName": "2724. Sort By", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sort-by", + "solutionLink": "#" + }, + { + "problemName": "2725. Interval Cancellation", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/interval-cancellation", + "solutionLink": "#" + }, + { + "problemName": "2726. Calculator with Method Chaining", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/calculator-with-method-chaining", + "solutionLink": "#" + }, + { + "problemName": "2727. Is Object Empty", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/is-object-empty", + "solutionLink": "#" + }, + { + "problemName": "2728. Count Houses in a Circular Street", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-houses-in-a-circular-street", + "solutionLink": "#" + }, + { + "problemName": "2729. Check if The Number is Fascinating", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-the-number-is-fascinating", + "solutionLink": "#" + }, + { + "problemName": "2730. Find the Longest Semi-Repetitive Substring", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-longest-semi-repetitive-substring", + "solutionLink": "#" + }, + { + "problemName": "2731. Movement of Robots", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/movement-of-robots", + "solutionLink": "#" + }, + { + "problemName": "2732. Find a Good Subset of the Matrix", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-a-good-subset-of-the-matrix", + "solutionLink": "#" + }, + { + "problemName": "2733. Neither Minimum nor Maximum", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/neither-minimum-nor-maximum", + "solutionLink": "#" + }, + { + "problemName": "2734. Lexicographically Smallest String After Substring Operation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/lexicographically-smallest-string-after-substring-operation", + "solutionLink": "#" + }, + { + "problemName": "2735. Collecting Chocolates", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/collecting-chocolates", + "solutionLink": "#" + }, + { + "problemName": "2736. Maximum Sum Queries", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-sum-queries", + "solutionLink": "#" + }, + { + "problemName": "2737. Find the Closest Marked Node", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-closest-marked-node", + "solutionLink": "#" + }, + { + "problemName": "2738. Count Occurrences in Text", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-occurrences-in-text", + "solutionLink": "#" + }, + { + "problemName": "2739. Total Distance Traveled", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/total-distance-traveled", + "solutionLink": "#" + }, + { + "problemName": "2740. Find the Value of the Partition", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-value-of-the-partition", + "solutionLink": "#" + }, + { + "problemName": "2741. Special Permutations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/special-permutations", + "solutionLink": "#" + }, + { + "problemName": "2742. Painting the Walls", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/painting-the-walls", + "solutionLink": "#" + }, + { + "problemName": "2743. Count Substrings Without Repeating Character", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-substrings-without-repeating-character", + "solutionLink": "#" + }, + { + "problemName": "2744. Find Maximum Number of String Pairs", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-maximum-number-of-string-pairs", + "solutionLink": "#" + }, + { + "problemName": "2745. Construct the Longest New String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/construct-the-longest-new-string", + "solutionLink": "#" + }, + { + "problemName": "2746. Decremental String Concatenation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/decremental-string-concatenation", + "solutionLink": "#" + }, + { + "problemName": "2747. Count Zero Request Servers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-zero-request-servers", + "solutionLink": "#" + }, + { + "problemName": "2748. Number of Beautiful Pairs", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-beautiful-pairs", + "solutionLink": "#" + }, + { + "problemName": "2749. Minimum Operations to Make the Integer Zero", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-make-the-integer-zero", + "solutionLink": "#" + }, + { + "problemName": "2750. Ways to Split Array Into Good Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/ways-to-split-array-into-good-subarrays", + "solutionLink": "#" + }, + { + "problemName": "2751. Robot Collisions", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/robot-collisions", + "solutionLink": "#" + }, + { + "problemName": "2752. Customers with Maximum Number of Transactions on Consecutive Days", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/customers-with-maximum-number-of-transactions-on-consecutive-days", + "solutionLink": "#" + }, + { + "problemName": "2753. Count Houses in a Circular Street II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-houses-in-a-circular-street-ii", + "solutionLink": "#" + }, + { + "problemName": "2754. Bind Function to Context", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/bind-function-to-context", + "solutionLink": "#" + }, + { + "problemName": "2755. Deep Merge of Two Objects", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/deep-merge-of-two-objects", + "solutionLink": "#" + }, + { + "problemName": "2756. Query Batching", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/query-batching", + "solutionLink": "#" + }, + { + "problemName": "2757. Generate Circular Array Values", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/generate-circular-array-values", + "solutionLink": "#" + }, + { + "problemName": "2758. Next Day", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/next-day", + "solutionLink": "#" + }, + { + "problemName": "2759. Convert JSON String to Object", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/convert-json-string-to-object", + "solutionLink": "#" + }, + { + "problemName": "2760. Longest Even Odd Subarray With Threshold", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/longest-even-odd-subarray-with-threshold", + "solutionLink": "#" + }, + { + "problemName": "2761. Prime Pairs With Target Sum", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/prime-pairs-with-target-sum", + "solutionLink": "#" + }, + { + "problemName": "2762. Continuous Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/continuous-subarrays", + "solutionLink": "#" + }, + { + "problemName": "2763. Sum of Imbalance Numbers of All Subarrays", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/sum-of-imbalance-numbers-of-all-subarrays", + "solutionLink": "#" + }, + { + "problemName": "2764. Is Array a Preorder of Some β€ŒBinary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/is-array-a-preorder-of-some-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "2765. Longest Alternating Subarray", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/longest-alternating-subarray/", + "solutionLink": "#" + }, + { + "problemName": "2766. Relocate Marbles", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/relocate-marbles/", + "solutionLink": "#" + }, + { + "problemName": "2767. Partition String Into Minimum Beautiful Substrings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/partition-string-into-minimum-beautiful-substrings/", + "solutionLink": "#" + }, + { + "problemName": "2768. Number of Black Blocks", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-black-blocks/", + "solutionLink": "#" + }, + { + "problemName": "2769. Find the Maximum Achievable Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-maximum-achievable-number/", + "solutionLink": "#" + }, + { + "problemName": "2770. Maximum Number of Jumps to Reach the Last Index", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-jumps-to-reach-the-last-index", + "solutionLink": "#" + }, + { + "problemName": "2771. Longest Non-decreasing Subarray From Two Arrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-non-decreasing-subarray-from-two-arrays/", + "solutionLink": "#" + }, + { + "problemName": "2772. Apply Operations to Make All Array Elements Equal to Zero", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/apply-operations-to-make-all-array-elements-equal-to-zero/", + "solutionLink": "#" + }, + { + "problemName": "2773. Height of Special Binary Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/height-of-special-binary-tree", + "solutionLink": "#" + }, + { + "problemName": "2774. Array Upper Bound", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/array-upper-bound", + "solutionLink": "#" + }, + { + "problemName": "2775. Undefined to Null", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/undefined-to-null", + "solutionLink": "#" + }, + { + "problemName": "2776. Convert Callback Based Function to Promise Based Function", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/convert-callback-based-function-to-promise-based-function", + "solutionLink": "#" + }, + { + "problemName": "2777. Date Range Generator", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/date-range-generator", + "solutionLink": "#" + }, + { + "problemName": "2778. Sum of Squares of Special Elements", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sum-of-squares-of-special-elements", + "solutionLink": "#" + }, + { + "problemName": "2779. Maximum Beauty of an Array After Applying Operation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-beauty-of-an-array-after-applying-operation", + "solutionLink": "#" + }, + { + "problemName": "2780. Minimum Index of a Valid Split", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-index-of-a-valid-split", + "solutionLink": "#" + }, + { + "problemName": "2781. Length of the Longest Valid Substring", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/length-of-the-longest-valid-substring/", + "solutionLink": "#" + }, + { + "problemName": "2782. Number of Unique Categories", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-unique-categories/", + "solutionLink": "#" + }, + { + "problemName": "2783. Flight Occupancy and Waitlist Analysis", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/flight-occupancy-and-waitlist-analysis", + "solutionLink": "#" + }, + { + "problemName": "2784. Check if Array is Good", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-array-is-good/", + "solutionLink": "#" + }, + { + "problemName": "2785. Sort Vowels in a String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sort-vowels-in-a-string/", + "solutionLink": "#" + }, + { + "problemName": "2786. Visit Array Positions to Maximize Score", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/visit-array-positions-to-maximize-score/", + "solutionLink": "#" + }, + { + "problemName": "2787. Ways to Express an Integer as Sum of Powers", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/ways-to-express-an-integer-as-sum-of-powers/", + "solutionLink": "#" + }, + { + "problemName": "2788. Split Strings by Separator", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/split-strings-by-separator/", + "solutionLink": "#" + }, + { + "problemName": "2789. Largest Element in an Array after Merge Operations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/largest-element-in-an-array-after-merge-operations/", + "solutionLink": "#" + }, + { + "problemName": "2790. Maximum Number of Groups With Increasing Length", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-groups-with-increasing-length/", + "solutionLink": "#" + }, + { + "problemName": "2791. Count Paths That Can Form a Palindrome in a Tree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-paths-that-can-form-a-palindrome-in-a-tree/", + "solutionLink": "#" + }, + { + "problemName": "2792. Count Nodes That Are Great Enough", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-nodes-that-are-great-enough", + "solutionLink": "#" + }, + { + "problemName": "2793. Status of Flight Tickets", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/status-of-flight-tickets", + "solutionLink": "#" + }, + { + "problemName": "2794. Create Object from Two Arrays", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/create-object-from-two-arrays", + "solutionLink": "#" + }, + { + "problemName": "2795. Parallel Execution of Promises for Individual Results Retrieval", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/parallel-execution-of-promises-for-individual-results-retrieval", + "solutionLink": "#" + }, + { + "problemName": "2796. Repeat String", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/repeat-string", + "solutionLink": "#" + }, + { + "problemName": "2797. Partial Function with Placeholders", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/partial-function-with-placeholders", + "solutionLink": "#" + }, + { + "problemName": "2798. Number of Employees Who Met the Target", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/number-of-employees-who-met-the-target/", + "solutionLink": "#" + }, + { + "problemName": "2799. Count Complete Subarrays in an Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-complete-subarrays-in-an-array/", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/2800-2899.md b/problems/leetcode-problems/2800-2899.md new file mode 100644 index 0000000..d5cc65e --- /dev/null +++ b/problems/leetcode-problems/2800-2899.md @@ -0,0 +1,622 @@ +--- +id: 2800-2899 +title: LeetCode Problems 2800 - 2899 +sidebar_label: 2800 - 2899 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 2800 - 2899 + - DSA problems +--- + +export const problems = [ + { + "problemName": "2800. Shortest String That Contains Three Strings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shortest-string-that-contains-three-strings/", + "solutionLink": "#" + }, + { + "problemName": "2801. Count Stepping Numbers in Range", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-stepping-numbers-in-range", + "solutionLink": "#" + }, + { + "problemName": "2802. Find The K-th Lucky Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-k-th-lucky-number", + "solutionLink": "#" + }, + { + "problemName": "2803. Factorial Generator", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/factorial-generator", + "solutionLink": "#" + }, + { + "problemName": "2804. Array Prototype ForEach", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/array-prototype-foreach", + "solutionLink": "#" + }, + { + "problemName": "2805. Custom Interval", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/custom-interval", + "solutionLink": "#" + }, + { + "problemName": "2806. Account Balance After Rounded Purchase", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/account-balance-after-rounded-purchase", + "solutionLink": "#" + }, + { + "problemName": "2807. Insert Greatest Common Divisors in Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/insert-greatest-common-divisors-in-linked-list", + "solutionLink": "/dsa-solutions/lc-solutions/2500-3000/insert-greatest-common-divisors-in-linked-list" + }, + { + "problemName": "2808. Minimum Seconds to Equalize a Circular Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-seconds-to-equalize-a-circular-array", + "solutionLink": "#" + }, + { + "problemName": "2809. Minimum Time to Make Array Sum At Most x", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-to-make-array-sum-at-most-x", + "solutionLink": "#" + }, + { + "problemName": "2810. Faulty Keyboard", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/faulty-keyboard", + "solutionLink": "#" + }, + { + "problemName": "2811. Check if it is Possible to Split Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-it-is-possible-to-split-array", + "solutionLink": "#" + }, + { + "problemName": "2812. Find the Safest Path in a Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-safest-path-in-a-grid", + "solutionLink": "#" + }, + { + "problemName": "2813. Maximum Elegance of a K-Length Subsequence", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-elegance-of-a-k-length-subsequence", + "solutionLink": "#" + }, + { + "problemName": "2814. Minimum Time Takes to Reach Destination Without Drowning", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-time-takes-to-reach-destination-without-drowning", + "solutionLink": "#" + }, + { + "problemName": "2815. Max Pair Sum in an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/max-pair-sum-in-an-array", + "solutionLink": "#" + }, + { + "problemName": "2816. Double a Number Represented as a Linked List", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/double-a-number-represented-as-a-linked-list", + "solutionLink": "#" + }, + { + "problemName": "2817. Minimum Absolute Difference Between Elements With Constraint", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-absolute-difference-between-elements-with-constraint", + "solutionLink": "#" + }, + { + "problemName": "2818. Apply Operations to Maximize Score", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/apply-operations-to-maximize-score", + "solutionLink": "#" + }, + { + "problemName": "2819. Minimum Relative Loss After Buying Chocolates", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-relative-loss-after-buying-chocolates", + "solutionLink": "#" + }, + { + "problemName": "2820. Election Results", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/election-results", + "solutionLink": "#" + }, + { + "problemName": "2821. Delay the Resolution of Each Promise", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/delay-the-resolution-of-each-promise", + "solutionLink": "#" + }, + { + "problemName": "2822. Inversion of Object", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/inversion-of-object", + "solutionLink": "#" + }, + { + "problemName": "2823. Deep Object Filter", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/deep-object-filter", + "solutionLink": "#" + }, + { + "problemName": "2824. Count Pairs Whose Sum is Less than Target", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-pairs-whose-sum-is-less-than-target", + "solutionLink": "#" + }, + { + "problemName": "2825. Make String a Subsequence Using Cyclic Increments", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/make-string-a-subsequence-using-cyclic-increments", + "solutionLink": "#" + }, + { + "problemName": "2826. Sorting Three Groups", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sorting-three-groups", + "solutionLink": "#" + }, + { + "problemName": "2827. Number of Beautiful Integers in the Range", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-beautiful-integers-in-the-range", + "solutionLink": "#" + }, + { + "problemName": "2828. Check if a String Is an Acronym of Words", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-a-string-is-an-acronym-of-words", + "solutionLink": "#" + }, + { + "problemName": "2829. Determine the Minimum Sum of a k-avoiding Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/determine-the-minimum-sum-of-a-k-avoiding-array", + "solutionLink": "#" + }, + { + "problemName": "2830. Maximize the Profit as the Salesman", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximize-the-profit-as-the-salesman", + "solutionLink": "#" + }, + { + "problemName": "2831. Find the Longest Equal Subarray", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-longest-equal-subarray", + "solutionLink": "#" + }, + { + "problemName": "2832. Maximal Range That Each Element Is Maximum in It", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximal-range-that-each-element-is-maximum-in-it", + "solutionLink": "#" + }, + { + "problemName": "2833. Furthest Point From Origin", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/furthest-point-from-origin", + "solutionLink": "#" + }, + { + "problemName": "2834. Find the Minimum Possible Sum of a Beautiful Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-the-minimum-possible-sum-of-a-beautiful-array", + "solutionLink": "#" + }, + { + "problemName": "2835. Minimum Operations to Form Subsequence With Target Sum", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-form-subsequence-with-target-sum", + "solutionLink": "#" + }, + { + "problemName": "2836. Maximize Value of Function in a Ball Passing Game", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximize-value-of-function-in-a-ball-passing-game", + "solutionLink": "#" + }, + { + "problemName": "2837. Total Traveled Distance", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/total-traveled-distance", + "solutionLink": "#" + }, + { + "problemName": "2838. Maximum Coins Heroes Can Collect", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-coins-heroes-can-collect", + "solutionLink": "#" + }, + { + "problemName": "2839. Check if Strings Can be Made Equal With Operations I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-strings-can-be-made-equal-with-operations-i", + "solutionLink": "#" + }, + { + "problemName": "2840. Check if Strings Can be Made Equal With Operations II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/check-if-strings-can-be-made-equal-with-operations-ii", + "solutionLink": "#" + }, + { + "problemName": "2841. Maximum Sum of Almost Unique Subarray", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-sum-of-almost-unique-subarray", + "solutionLink": "#" + }, + { + "problemName": "2842. Count K-Subsequences of a String With Maximum Beauty", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-k-subsequences-of-a-string-with-maximum-beauty", + "solutionLink": "#" + }, + { + "problemName": "2843. Count Symmetric Integers", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-symmetric-integers", + "solutionLink": "#" + }, + { + "problemName": "2844. Minimum Operations to Make a Special Number", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-make-a-special-number", + "solutionLink": "#" + }, + { + "problemName": "2845. Count of Interesting Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-of-interesting-subarrays", + "solutionLink": "#" + }, + { + "problemName": "2846. Minimum Edge Weight Equilibrium Queries in a Tree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-edge-weight-equilibrium-queries-in-a-tree", + "solutionLink": "#" + }, + { + "problemName": "2847. Smallest Number With Given Digit Product", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/smallest-number-with-given-digit-product", + "solutionLink": "#" + }, + { + "problemName": "2848. Points That Intersect With Cars", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/points-that-intersect-with-cars", + "solutionLink": "#" + }, + { + "problemName": "2849. Determine if a Cell Is Reachable at a Given Time", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/determine-if-a-cell-is-reachable-at-a-given-time", + "solutionLink": "#" + }, + { + "problemName": "2850. Minimum Moves to Spread Stones Over Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-moves-to-spread-stones-over-grid", + "solutionLink": "#" + }, + { + "problemName": "2851. String Transformation", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/string-transformation", + "solutionLink": "#" + }, + { + "problemName": "2852. Sum of Remoteness of All Cells", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/sum-of-remoteness-of-all-cells", + "solutionLink": "#" + }, + { + "problemName": "2853. Highest Salaries Difference", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/highest-salaries-difference", + "solutionLink": "#" + }, + { + "problemName": "2854. Rolling Average Steps", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/rolling-average-steps", + "solutionLink": "#" + }, + { + "problemName": "2855. Minimum Right Shifts to Sort the Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-right-shifts-to-sort-the-array", + "solutionLink": "#" + }, + { + "problemName": "2856. Minimum Array Length After Pair Removals", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-array-length-after-pair-removals", + "solutionLink": "#" + }, + { + "problemName": "2857. Count Pairs of Points With Distance k", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-pairs-of-points-with-distance-k", + "solutionLink": "#" + }, + { + "problemName": "2858. Minimum Edge Reversals So Every Node Is Reachable", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-edge-reversals-so-every-node-is-reachable", + "solutionLink": "#" + }, + { + "problemName": "2859. Sum of Values at Indices With K Set Bits", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/sum-of-values-at-indices-with-k-set-bits", + "solutionLink": "#" + }, + { + "problemName": "2860. Happy Students", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/happy-students", + "solutionLink": "#" + }, + { + "problemName": "2861. Maximum Number of Alloys", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-alloys", + "solutionLink": "#" + }, + { + "problemName": "2862. Maximum Element-Sum of a Complete Subset of Indices", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-element-sum-of-a-complete-subset-of-indices", + "solutionLink": "#" + }, + { + "problemName": "2863. Maximum Length of Semi-Decreasing Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-length-of-semi-decreasing-subarrays", + "solutionLink": "#" + }, + { + "problemName": "2864. Maximum Odd Binary Number", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-odd-binary-number", + "solutionLink": "#" + }, + { + "problemName": "2865. Beautiful Towers I", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/beautiful-towers-i", + "solutionLink": "#" + }, + { + "problemName": "2866. Beautiful Towers II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/beautiful-towers-ii", + "solutionLink": "#" + }, + { + "problemName": "2867. Count Valid Paths in a Tree", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-valid-paths-in-a-tree", + "solutionLink": "#" + }, + { + "problemName": "2868. The Wording Game", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/the-wording-game", + "solutionLink": "#" + }, + { + "problemName": "2869. Minimum Operations to Collect Elements", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-collect-elements", + "solutionLink": "#" + }, + { + "problemName": "2870. Minimum Number of Operations to Make Array Empty", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-operations-to-make-array-empty", + "solutionLink": "#" + }, + { + "problemName": "2871. Split Array Into Maximum Number of Subarrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/split-array-into-maximum-number-of-subarrays", + "solutionLink": "#" + }, + { + "problemName": "2872. Maximum Number of K-Divisible Components", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-number-of-k-divisible-components", + "solutionLink": "#" + }, + { + "problemName": "2873. Maximum Value of an Ordered Triplet I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-value-of-an-ordered-triplet-i", + "solutionLink": "#" + }, + { + "problemName": "2874. Maximum Value of an Ordered Triplet II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-value-of-an-ordered-triplet-ii", + "solutionLink": "#" + }, + { + "problemName": "2875. Minimum Size Subarray in Infinite Array", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-size-subarray-in-infinite-array", + "solutionLink": "#" + }, + { + "problemName": "2876. Count Visited Nodes in a Directed Graph", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-visited-nodes-in-a-directed-graph", + "solutionLink": "#" + }, + { + "problemName": "2877. Create a DataFrame from List", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/create-a-dataframe-from-list", + "solutionLink": "#" + }, + { + "problemName": "2878. Get the Size of a DataFrame", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/get-the-size-of-a-dataframe", + "solutionLink": "#" + }, + { + "problemName": "2879. Display the First Three Rows", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/display-the-first-three-rows", + "solutionLink": "#" + }, + { + "problemName": "2880. Select Data", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/select-data", + "solutionLink": "/dsa-solutions/lc-solutions/2500-3000/2880-select-data" + }, + { + "problemName": "2881. Create a New Column", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/create-a-new-column", + "solutionLink": "/dsa-solutions/lc-solutions/2500-3000/Create-a-New-Column" + }, + { + "problemName": "2882. Drop Duplicate Rows", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/drop-duplicate-rows", + "solutionLink": "/dsa-solutions/lc-solutions/2500-3000/Drop-Duplicate-Rows" + }, + { + "problemName": "2883. Drop Missing Data", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/drop-missing-data", + "solutionLink": "#" + }, + { + "problemName": "2884. Modify Columns", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/modify-columns", + "solutionLink": "#" + }, + { + "problemName": "2885. Rename Columns", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/rename-columns", + "solutionLink": "#" + }, + { + "problemName": "2886. Change Data Type", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/change-data-type", + "solutionLink": "#" + }, + { + "problemName": "2887. Fill Missing Data", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/fill-missing-data", + "solutionLink": "#" + }, + { + "problemName": "2888. Reshape Data: Concatenate", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/reshape-data-concatenate", + "solutionLink": "#" + }, + { + "problemName": "2889. Reshape Data: Pivot", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/reshape-data-pivot", + "solutionLink": "#" + }, + { + "problemName": "2890. Reshape Data: Melt", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/reshape-data-melt", + "solutionLink": "#" + }, + { + "problemName": "2891. Method Chaining", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/method-chaining", + "solutionLink": "#" + }, + { + "problemName": "2892. Minimizing Array After Replacing Pairs With Their Product", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimizing-array-after-replacing-pairs-with-their-product", + "solutionLink": "#" + }, + { + "problemName": "2893. Calculate Orders Within Each Interval", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/calculate-orders-within-each-interval", + "solutionLink": "#" + }, + { + "problemName": "2894. Divisible and Non-divisible Sums Difference", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/divisible-and-non-divisible-sums-difference", + "solutionLink": "#" + }, + { + "problemName": "2895. Minimum Processing Time", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-processing-time", + "solutionLink": "#" + }, + { + "problemName": "2896. Apply Operations to Make Two Strings Equal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/apply-operations-to-make-two-strings-equal", + "solutionLink": "#" + }, + { + "problemName": "2897. Apply Operations on Array to Maximize Sum of Squares", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/apply-operations-on-array-to-maximize-sum-of-squares", + "solutionLink": "#" + }, + { + "problemName": "2898. Maximum Linear Stock Score", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-linear-stock-score", + "solutionLink": "#" + }, + { + "problemName": "2899. Last Visited Integers", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/last-visited-integers", + "solutionLink": "#" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. \ No newline at end of file diff --git a/problems/leetcode-problems/2900-2999.md b/problems/leetcode-problems/2900-2999.md new file mode 100644 index 0000000..e3d8257 --- /dev/null +++ b/problems/leetcode-problems/2900-2999.md @@ -0,0 +1,622 @@ +--- +id: 2900-2999 +title: LeetCode Problems 2900 - 2999 +sidebar_label: 2900 - 2999 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 2900 - 2999 + - DSA problems +--- + +export const problems = [ + { + "problemName": "2900. Longest Unequal Adjacent Groups Subsequence I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/longest-unequal-adjacent-groups-subsequence-i", + "solutionLink": "/dsa-solutions/lc-solutions/2900-2999/longest-unequal-adjacent-groups-subsequence-i" + }, + { + "problemName": "2901. Longest Unequal Adjacent Groups Subsequence II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/longest-unequal-adjacent-groups-subsequence-ii", + "solutionLink": "/dsa-solutions/lc-solutions/2900-2999/2901-longest-unequal-adjacent-groups-subsequence-ii.md" + }, + { + "problemName": "2902. Count of Sub-Multisets With Bounded Sum", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-of-sub-multisets-with-bounded-sum", + "solutionLink": "/dsa-solutions/lc-solutions/2900-2999/2902-count-of-sub-multisets-with-bounded-sum.md" + }, + { + "problemName": "2903. Find Indices With Index and Value Difference I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-indices-with-index-and-value-difference-i", + "solutionLink": "#" + }, + { + "problemName": "2904. Shortest and Lexicographically Smallest Beautiful String", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/shortest-and-lexicographically-smallest-beautiful-string", + "solutionLink": "#" + }, + { + "problemName": "2905. Find Indices With Index and Value Difference II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-indices-with-index-and-value-difference-ii", + "solutionLink": "#" + }, + { + "problemName": "2906. Construct Product Matrix", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/construct-product-matrix", + "solutionLink": "#" + }, + { + "problemName": "2907. Maximum Profitable Triplets With Increasing Prices I", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-profitable-triplets-with-increasing-prices-i", + "solutionLink": "#" + }, + { + "problemName": "2908. Minimum Sum of Mountain Triplets I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-sum-of-mountain-triplets-i", + "solutionLink": "#" + }, + { + "problemName": "2909. Minimum Sum of Mountain Triplets II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-sum-of-mountain-triplets-ii", + "solutionLink": "/dsa-solutions/lc-solutions/2900-2999/2909-minimum-sum-of-mountain-triplets-ii.md" + }, + { + "problemName": "2910. Minimum Number of Groups to Create a Valid Assignment", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-groups-to-create-a-valid-assignment", + "solutionLink": "#" + }, + { + "problemName": "2911. Minimum Changes to Make K Semi-palindromes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-changes-to-make-k-semi-palindromes", + "solutionLink": "#" + }, + { + "problemName": "2912. Number of Ways to Reach Destination in the Grid", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-ways-to-reach-destination-in-the-grid", + "solutionLink": "#" + }, + { + "problemName": "2913. Subarrays Distinct Element Sum of Squares I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/subarrays-distinct-element-sum-of-squares-i", + "solutionLink": "#" + }, + { + "problemName": "2914. Minimum Number of Changes to Make Binary String Beautiful", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-changes-to-make-binary-string-beautiful", + "solutionLink": "#" + }, + { + "problemName": "2915. Length of the Longest Subsequence That Sums to Target", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/length-of-the-longest-subsequence-that-sums-to-target", + "solutionLink": "#" + }, + { + "problemName": "2916. Subarrays Distinct Element Sum of Squares II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/subarrays-distinct-element-sum-of-squares-ii", + "solutionLink": "#" + }, + { + "problemName": "2917. Find the K-or of an Array", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-k-or-of-an-array", + "solutionLink": "#" + }, + { + "problemName": "2918. Minimum Equal Sum of Two Arrays After Replacing Zeros", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-equal-sum-of-two-arrays-after-replacing-zeros", + "solutionLink": "#" + }, + { + "problemName": "2919. Minimum Increment Operations to Make Array Beautiful", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-increment-operations-to-make-array-beautiful", + "solutionLink": "#" + }, + { + "problemName": "2920. Maximum Points After Collecting Coins From All Nodes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-points-after-collecting-coins-from-all-nodes", + "solutionLink": "#" + }, + { + "problemName": "2921. Maximum Profitable Triplets With Increasing Prices II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-profitable-triplets-with-increasing-prices-ii", + "solutionLink": "#" + }, + { + "problemName": "2922. Market Analysis III", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/market-analysis-iii", + "solutionLink": "#" + }, + { + "problemName": "2923. Find Champion I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-champion-i", + "solutionLink": "#" + }, + { + "problemName": "2924. Find Champion II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-champion-ii", + "solutionLink": "#" + }, + { + "problemName": "2925. Maximum Score After Applying Operations on a Tree", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-score-after-applying-operations-on-a-tree", + "solutionLink": "#" + }, + { + "problemName": "2926. Maximum Balanced Subsequence Sum", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-balanced-subsequence-sum", + "solutionLink": "#" + }, + { + "problemName": "2927. Distribute Candies Among Children III", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/distribute-candies-among-children-iii", + "solutionLink": "#" + }, + { + "problemName": "2928. Distribute Candies Among Children I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/distribute-candies-among-children-i", + "solutionLink": "#" + }, + { + "problemName": "2929. Distribute Candies Among Children II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/distribute-candies-among-children-ii", + "solutionLink": "#" + }, + { + "problemName": "2930. Number of Strings Which Can Be Rearranged to Contain Substring", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-strings-which-can-be-rearranged-to-contain-substring", + "solutionLink": "#" + }, + { + "problemName": "2931. Maximum Spending After Buying Items", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-spending-after-buying-items", + "solutionLink": "#" + }, + { + "problemName": "2932. Maximum Strong Pair XOR I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/maximum-strong-pair-xor-i", + "solutionLink": "#" + }, + { + "problemName": "2933. High-Access Employees", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/high-access-employees", + "solutionLink": "#" + }, + { + "problemName": "2934. Minimum Operations to Maximize Last Elements in Arrays", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-maximize-last-elements-in-arrays", + "solutionLink": "#" + }, + { + "problemName": "2935. Maximum Strong Pair XOR II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-strong-pair-xor-ii", + "solutionLink": "#" + }, + { + "problemName": "2936. Number of Equal Numbers Blocks", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-equal-numbers-blocks", + "solutionLink": "#" + }, + { + "problemName": "2937. Make Three Strings Equal", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/make-three-strings-equal", + "solutionLink": "#" + }, + { + "problemName": "2938. Separate Black and White Balls", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/separate-black-and-white-balls", + "solutionLink": "#" + }, + { + "problemName": "2939. Maximum Xor Product", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-xor-product", + "solutionLink": "#" + }, + { + "problemName": "2940. Find Building Where Alice and Bob Can Meet", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-building-where-alice-and-bob-can-meet", + "solutionLink": "#" + }, + { + "problemName": "2941. Maximum GCD-Sum of a Subarray", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/maximum-gcd-sum-of-a-subarray", + "solutionLink": "#" + }, + { + "problemName": "2942. Find Words Containing Character", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-words-containing-character", + "solutionLink": "#" + }, + { + "problemName": "2943. Maximize Area of Square Hole in Grid", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximize-area-of-square-hole-in-grid", + "solutionLink": "#" + }, + { + "problemName": "2944. Minimum Number of Coins for Fruits", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-coins-for-fruits", + "solutionLink": "#" + }, + { + "problemName": "2945. Find Maximum Non-decreasing Array Length", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-maximum-non-decreasing-array-length", + "solutionLink": "#" + }, + { + "problemName": "2946. Matrix Similarity After Cyclic Shifts", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/matrix-similarity-after-cyclic-shifts", + "solutionLink": "#" + }, + { + "problemName": "2947. Count Beautiful Substrings I", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-beautiful-substrings-i", + "solutionLink": "#" + }, + { + "problemName": "2948. Make Lexicographically Smallest Array by Swapping Elements", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/make-lexicographically-smallest-array-by-swapping-elements", + "solutionLink": "#" + }, + { + "problemName": "2949. Count Beautiful Substrings II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-beautiful-substrings-ii", + "solutionLink": "#" + }, + { + "problemName": "2950. Number of Divisible Substrings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-divisible-substrings", + "solutionLink": "#" + }, + { + "problemName": "2951. Find the Peaks", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-the-peaks", + "solutionLink": "#" + }, + { + "problemName": "2952. Minimum Number of Coins to be Added", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-coins-to-be-added", + "solutionLink": "#" + }, + { + "problemName": "2953. Count Complete Substrings", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-complete-substrings", + "solutionLink": "#" + }, + { + "problemName": "2954. Count the Number of Infection Sequences", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-infection-sequences", + "solutionLink": "#" + }, + { + "problemName": "2955. Number of Same-End Substrings", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-same-end-substrings", + "solutionLink": "#" + }, + { + "problemName": "2956. Find Common Elements Between Two Arrays", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-common-elements-between-two-arrays", + "solutionLink": "#" + }, + { + "problemName": "2957. Remove Adjacent Almost-Equal Characters", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/remove-adjacent-almost-equal-characters", + "solutionLink": "#" + }, + { + "problemName": "2958. Length of Longest Subarray With at Most K Frequency", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/length-of-longest-subarray-with-at-most-k-frequency", + "solutionLink": "#" + }, + { + "problemName": "2959. Number of Possible Sets of Closing Branches", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/number-of-possible-sets-of-closing-branches", + "solutionLink": "#" + }, + { + "problemName": "2960. Count Tested Devices After Test Operations", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-tested-devices-after-test-operations", + "solutionLink": "#" + }, + { + "problemName": "2961. Double Modular Exponentiation", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/double-modular-exponentiation", + "solutionLink": "#" + }, + { + "problemName": "2962. Count Subarrays Where Max Element Appears at Least K Times", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/count-subarrays-where-max-element-appears-at-least-k-times", + "solutionLink": "#" + }, + { + "problemName": "2963. Count the Number of Good Partitions", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-good-partitions", + "solutionLink": "#" + }, + { + "problemName": "2964. Number of Divisible Triplet Sums", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-divisible-triplet-sums", + "solutionLink": "#" + }, + { + "problemName": "2965. Find Missing and Repeated Values", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-missing-and-repeated-values", + "solutionLink": "#" + }, + { + "problemName": "2966. Divide Array Into Arrays With Max Difference", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/divide-array-into-arrays-with-max-difference", + "solutionLink": "#" + }, + { + "problemName": "2967. Minimum Cost to Make Array Equalindromic", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-make-array-equalindromic", + "solutionLink": "#" + }, + { + "problemName": "2968. Apply Operations to Maximize Frequency Score", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/apply-operations-to-maximize-frequency-score", + "solutionLink": "#" + }, + { + "problemName": "2969. Minimum Number of Coins for Fruits II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-coins-for-fruits-ii", + "solutionLink": "#" + }, + { + "problemName": "2970. Count the Number of Incremovable Subarrays I", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-incremovable-subarrays-i", + "solutionLink": "#" + }, + { + "problemName": "2971. Find Polygon With the Largest Perimeter", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-polygon-with-the-largest-perimeter", + "solutionLink": "#" + }, + { + "problemName": "2972. Count the Number of Incremovable Subarrays II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-incremovable-subarrays-ii", + "solutionLink": "#" + }, + { + "problemName": "2973. Find Number of Coins to Place in Tree Nodes", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/find-number-of-coins-to-place-in-tree-nodes", + "solutionLink": "#" + }, + { + "problemName": "2974. Minimum Number Game", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-game", + "solutionLink": "#" + }, + { + "problemName": "2975. Maximum Square Area by Removing Fences From a Field", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/maximum-square-area-by-removing-fences-from-a-field", + "solutionLink": "#" + }, + { + "problemName": "2976. Minimum Cost to Convert String I", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-convert-string-i", + "solutionLink": "#" + }, + { + "problemName": "2977. Minimum Cost to Convert String II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-convert-string-ii", + "solutionLink": "#" + }, + { + "problemName": "2978. Symmetric Coordinates", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/symmetric-coordinates", + "solutionLink": "#" + }, + { + "problemName": "2979. Most Expensive Item That Can Not Be Bought", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/most-expensive-item-that-can-not-be-bought", + "solutionLink": "#" + }, + { + "problemName": "2980. Check if Bitwise OR Has Trailing Zeros", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/check-if-bitwise-or-has-trailing-zeros", + "solutionLink": "#" + }, + { + "problemName": "2981. Find Longest Special Substring That Occurs Thrice I", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i", + "solutionLink": "#" + }, + { + "problemName": "2982. Find Longest Special Substring That Occurs Thrice II", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-ii", + "solutionLink": "#" + }, + { + "problemName": "2983. Palindrome Rearrangement Queries", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/palindrome-rearrangement-queries", + "solutionLink": "#" + }, + { + "problemName": "2984. Find Peak Calling Hours for Each City", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-peak-calling-hours-for-each-city", + "solutionLink": "#" + }, + { + "problemName": "2985. Calculate Compressed Mean", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/calculate-compressed-mean", + "solutionLink": "#" + }, + { + "problemName": "2986. Find Third Transaction", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/find-third-transaction", + "solutionLink": "#" + }, + { + "problemName": "2987. Find Expensive Cities", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/find-expensive-cities", + "solutionLink": "#" + }, + { + "problemName": "2988. Manager of the Largest Department", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/manager-of-the-largest-department", + "solutionLink": "#" + }, + { + "problemName": "2989. Class Performance", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/class-performance", + "solutionLink": "#" + }, + { + "problemName": "2990. Loan Types", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/loan-types", + "solutionLink": "#" + }, + { + "problemName": "2991. Top Three Wineries", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/top-three-wineries", + "solutionLink": "#" + }, + { + "problemName": "2992. Number of Self-Divisible Permutations", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/number-of-self-divisible-permutations", + "solutionLink": "#" + }, + { + "problemName": "2993. Friday Purchases I", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/friday-purchases-i", + "solutionLink": "#" + }, + { + "problemName": "2994. Friday Purchases II", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/friday-purchases-ii", + "solutionLink": "#" + }, + { + "problemName": "2995. Viewers Turned Streamers", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/viewers-turned-streamers", + "solutionLink": "#" + }, + { + "problemName": "2996. Smallest Missing Integer Greater Than Sequential Prefix Sum", + "difficulty": "Easy", + "leetCodeLink": "https://leetcode.com/problems/smallest-missing-integer-greater-than-sequential-prefix-sum", + "solutionLink": "#" + }, + { + "problemName": "2997. Minimum Number of Operations to Make Array XOR Equal to K", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-operations-to-make-array-xor-equal-to-k", + "solutionLink": "#" + }, + { + "problemName": "2998. Minimum Number of Operations to Make X and Y Equal", + "difficulty": "Medium", + "leetCodeLink": "https://leetcode.com/problems/minimum-number-of-operations-to-make-x-and-y-equal", + "solutionLink": "#" + }, + { + "problemName": "2999. Count the Number of Powerful Integers", + "difficulty": "Hard", + "leetCodeLink": "https://leetcode.com/problems/count-the-number-of-powerful-integers", + "solutionLink": "/dsa-solutions/lc-solutions/2900-2999/2999-count-the-number-of-powerful-integers.md" + } +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/leetcode-problems/3000-3099.md b/problems/leetcode-problems/3000-3099.md new file mode 100644 index 0000000..21416c8 --- /dev/null +++ b/problems/leetcode-problems/3000-3099.md @@ -0,0 +1,628 @@ +--- +id: 3000-3099 +title: LeetCode Problems 3000 - 3099 +sidebar_label: 3000 - 3099 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 3000 - 3099 + - DSA problems +--- + +export const problems = [ +{ +"problemName": "3000. Maximum Area of Longest Diagonal Rectangle", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/maximum-area-of-longest-diagonal-rectangle", +"solutionLink": "/dsa-solutions/lc-solutions/3000-3099/3000-maximum-area-of-diagonal-rectangle" +}, +{ +"problemName": "3001. Minimum Moves to Capture The Queen", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-moves-to-capture-the-queen", +"solutionLink": "#" +}, +{ +"problemName": "3002. Maximum Size of a Set After Removals", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximum-size-of-a-set-after-removals", +"solutionLink": "/dsa-solutions/lc-solutions/3000-3099/maximum-size-of-a-set-after-removals" +}, +{ +"problemName": "3003. Maximize the Number of Partitions After Operations", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/maximize-the-number-of-partitions-after-operations", +"solutionLink": "#" +}, +{ +"problemName": "3004. Maximum Subtree of the Same Color", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximum-subtree-of-the-same-color", +"solutionLink": "#" +}, +{ +"problemName": "3005. Count Elements With Maximum Frequency", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/count-elements-with-maximum-frequency", +"solutionLink": "/dsa-solutions/lc-solutions/3000-3099/count-elements-with-maximum-frequency" +}, +{ +"problemName": "3006. Find Beautiful Indices in the Given Array I", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-beautiful-indices-in-the-given-array-i", +"solutionLink": "/dsa-solutions/lc-solutions/3000-3099/" +}, +{ +"problemName": "3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximum-number-that-sum-of-the-prices-is-less-than-or-equal-to-k", +"solutionLink": "#" +}, +{ +"problemName": "3008. Find Beautiful Indices in the Given Array II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-beautiful-indices-in-the-given-array-ii", +"solutionLink": "#" +}, +{ +"problemName": "3009. Maximum Number of Intersections on the Chart", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/maximum-number-of-intersections-on-the-chart", +"solutionLink": "#" +}, +{ +"problemName": "3010. Divide an Array Into Subarrays With Minimum Cost I", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/divide-an-array-into-subarrays-with-minimum-cost-i", +"solutionLink": "/dsa-solutions/lc-solutions/3000-3099/divide-an-array-into-subarrays-with-minimum-cost-i" +}, +{ +"problemName": "3011. Find if Array Can Be Sorted", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-if-array-can-be-sorted", +"solutionLink": "#" +}, +{ +"problemName": "3012. Minimize Length of Array Using Operations", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimize-length-of-array-using-operations", +"solutionLink": "#" +}, +{ +"problemName": "3013. Divide an Array Into Subarrays With Minimum Cost II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/divide-an-array-into-subarrays-with-minimum-cost-ii", +"solutionLink": "#" +}, +{ +"problemName": "3014. Minimum Number of Pushes to Type Word I", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/minimum-number-of-pushes-to-type-word-i", +"solutionLink": "#" +}, +{ +"problemName": "3015. Count the Number of Houses at a Certain Distance I", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/count-the-number-of-houses-at-a-certain-distance-i", +"solutionLink": "#" +}, +{ +"problemName": "3016. Minimum Number of Pushes to Type Word II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-number-of-pushes-to-type-word-ii", +"solutionLink": "#" +}, +{ +"problemName": "3017. Count the Number of Houses at a Certain Distance II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/count-the-number-of-houses-at-a-certain-distance-ii", +"solutionLink": "#" +}, +{ +"problemName": "3018. Maximum Number of Removal Queries That Can Be Processed I", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/maximum-number-of-removal-queries-that-can-be-processed-i", +"solutionLink": "#" +}, +{ +"problemName": "3019. Number of Changing Keys", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/number-of-changing-keys", +"solutionLink": "/dsa-solutions/lc-solutions/3000-3099/number-of-changing-keys" +}, +{ +"problemName": "3020. Find the Maximum Number of Elements in Subset", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-the-maximum-number-of-elements-in-subset", +"solutionLink": "#" +}, +{ +"problemName": "3021. Alice and Bob Playing Flower Game", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/alice-and-bob-playing-flower-game", +"solutionLink": "/dsa-solutions/lc-solutions/3000-3099/alice-and-bob-playing-flower-game" +}, +{ +"problemName": "3022. Minimize OR of Remaining Elements Using Operations", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/minimize-or-of-remaining-elements-using-operations", +"solutionLink": "#" +}, +{ +"problemName": "3023. Find Pattern in Infinite Stream I", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-pattern-in-infinite-stream-i", +"solutionLink": "#" +}, +{ +"problemName": "3024. Type of Triangle", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/type-of-triangle", +"solutionLink": "/dsa-solutions/lc-solutions/3000-3099/type-of-triangle" +}, +{ +"problemName": "3025. Find the Number of Ways to Place People I", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-the-number-of-ways-to-place-people-i", +"solutionLink": "#" +}, +{ +"problemName": "3026. Maximum Good Subarray Sum", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximum-good-subarray-sum", +"solutionLink": "#" +}, +{ +"problemName": "3027. Find the Number of Ways to Place People II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-the-number-of-ways-to-place-people-ii", +"solutionLink": "#" +}, +{ +"problemName": "3028. Ant on the Boundary", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/ant-on-the-boundary", +"solutionLink": "/dsa-solutions/lc-solutions/3000-3099/ant-on-the-boundary" +}, +{ +"problemName": "3029. Minimum Time to Revert Word to Initial State I", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-time-to-revert-word-to-initial-state-i", +"solutionLink": "#" +}, +{ +"problemName": "3030. Find the Grid of Region Average", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-the-grid-of-region-average", +"solutionLink": "#" +}, +{ +"problemName": "3031. Minimum Time to Revert Word to Initial State II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/minimum-time-to-revert-word-to-initial-state-ii", +"solutionLink": "#" +}, +{ +"problemName": "3032. Count Numbers With Unique Digits II", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/count-numbers-with-unique-digits-ii", +"solutionLink": "#" +}, +{ +"problemName": "3033. Modify the Matrix", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/modify-the-matrix", +"solutionLink": "/dsa-solutions/lc-solutions/3000-3099/modify-the-matrix" +}, +{ +"problemName": "3034. Number of Subarrays That Match a Pattern I", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/number-of-subarrays-that-match-a-pattern-i", +"solutionLink": "/dsa-solutions/lc-solutions/3000-3099/number-of-subarrays-that-match-a-pattern-i" +}, +{ +"problemName": "3035. Maximum Palindromes After Operations", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximum-palindromes-after-operations", +"solutionLink": "/dsa-solutions/lc-solutions/3000-3099/maximum-palindromes-after-operations" +}, +{ +"problemName": "3036. Number of Subarrays That Match a Pattern II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/number-of-subarrays-that-match-a-pattern-ii", +"solutionLink": "#" +}, +{ +"problemName": "3037. Find Pattern in Infinite Stream II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-pattern-in-infinite-stream-ii", +"solutionLink": "#" +}, +{ +"problemName": "3038. Maximum Number of Operations With the Same Score I", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/maximum-number-of-operations-with-the-same-score-i", +"solutionLink": "/dsa-solutions/lc-solutions/3000-3099/maximum-number-of-operations-with-the-same-score-i" +}, +{ +"problemName": "3039. Apply Operations to Make String Empty", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/apply-operations-to-make-string-empty", +"solutionLink": "#" +}, +{ +"problemName": "3040. Maximum Number of Operations With the Same Score II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximum-number-of-operations-with-the-same-score-ii", +"solutionLink": "#" +}, +{ +"problemName": "3041. Maximize Consecutive Elements in an Array After Modification", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/maximize-consecutive-elements-in-an-array-after-modification", +"solutionLink": "#" +}, +{ +"problemName": "3042. Count Prefix and Suffix Pairs I", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/count-prefix-and-suffix-pairs-i", +"solutionLink": "#" +}, +{ +"problemName": "3043. Find the Length of the Longest Common Prefix", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-the-length-of-the-longest-common-prefix", +"solutionLink": "#" +}, +{ +"problemName": "3044. Most Frequent Prime", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/most-frequent-prime", +"solutionLink": "#" +}, +{ +"problemName": "3045. Count Prefix and Suffix Pairs II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/count-prefix-and-suffix-pairs-ii", +"solutionLink": "#" +}, +{ +"problemName": "3046. Split the Array", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/split-the-array", +"solutionLink": "#" +}, +{ +"problemName": "3047. Find the Largest Area of Square Inside Two Rectangles", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-the-largest-area-of-square-inside-two-rectangles", +"solutionLink": "#" +}, +{ +"problemName": "3048. Earliest Second to Mark Indices I", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/earliest-second-to-mark-indices-i", +"solutionLink": "#" +}, +{ +"problemName": "3049. Earliest Second to Mark Indices II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/earliest-second-to-mark-indices-ii", +"solutionLink": "#" +}, +{ +"problemName": "3050. Pizza Toppings Cost Analysis", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/pizza-toppings-cost-analysis", +"solutionLink": "#" +}, +{ +"problemName": "3051. Find Candidates for Data Scientist Position", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/find-candidates-for-data-scientist-position", +"solutionLink": "#" +}, +{ +"problemName": "3052. Maximize Items", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/maximize-items", +"solutionLink": "#" +}, +{ +"problemName": "3053. Classifying Triangles by Lengths", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/classifying-triangles-by-lengths", +"solutionLink": "#" +}, +{ +"problemName": "3054. Binary Tree Nodes", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/binary-tree-nodes", +"solutionLink": "#" +}, +{ +"problemName": "3055. Top Percentile Fraud", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/top-percentile-fraud", +"solutionLink": "#" +}, +{ +"problemName": "3056. Snaps Analysis", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/snaps-analysis", +"solutionLink": "#" +}, +{ +"problemName": "3057. Employees Project Allocation", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/employees-project-allocation", +"solutionLink": "#" +}, +{ +"problemName": "3058. Friends With No Mutual Friends", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/friends-with-no-mutual-friends", +"solutionLink": "#" +}, +{ +"problemName": "3059. Find All Unique Email Domains", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/find-all-unique-email-domains", +"solutionLink": "#" +}, +{ +"problemName": "3060. User Activities within Time Bounds", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/user-activities-within-time-bounds", +"solutionLink": "#" +}, +{ +"problemName": "3061. Calculate Trapping Rain Water", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/calculate-trapping-rain-water", +"solutionLink": "#" +}, +{ +"problemName": "3062. Winner of the Linked List Game", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/winner-of-the-linked-list-game", +"solutionLink": "#" +}, +{ +"problemName": "3063. Linked List Frequency", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/linked-list-frequency", +"solutionLink": "#" +}, +{ +"problemName": "3064. Guess the Number Using Bitwise Questions I", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/guess-the-number-using-bitwise-questions-i", +"solutionLink": "#" +}, +{ +"problemName": "3065. Minimum Operations to Exceed Threshold Value I", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-exceed-threshold-value-i", +"solutionLink": "#" +}, +{ +"problemName": "3066. Minimum Operations to Exceed Threshold Value II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-exceed-threshold-value-ii", +"solutionLink": "#" +}, +{ +"problemName": "3067. Count Pairs of Connectable Servers in a Weighted Tree Network", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/count-pairs-of-connectable-servers-in-a-weighted-tree-network", +"solutionLink": "#" +}, +{ +"problemName": "3068. Find the Maximum Sum of Node Values", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-the-maximum-sum-of-node-values", +"solutionLink": "#" +}, +{ +"problemName": "3069. Distribute Elements Into Two Arrays I", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/distribute-elements-into-two-arrays-i", +"solutionLink": "#" +}, +{ +"problemName": "3070. Count Submatrices with Top-Left Element and Sum Less Than k", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/count-submatrices-with-top-left-element-and-sum-less-than-k", +"solutionLink": "#" +}, +{ +"problemName": "3071. Minimum Operations to Write the Letter Y on a Grid", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-write-the-letter-y-on-a-grid", +"solutionLink": "#" +}, +{ +"problemName": "3072. Distribute Elements Into Two Arrays II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/distribute-elements-into-two-arrays-ii", +"solutionLink": "#" +}, +{ +"problemName": "3073. Maximum Increasing Triplet Value", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximum-increasing-triplet-value", +"solutionLink": "#" +}, +{ +"problemName": "3074. Apple Redistribution into Boxes", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/apple-redistribution-into-boxes", +"solutionLink": "#" +}, +{ +"problemName": "3075. Maximize Happiness of Selected Children", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximize-happiness-of-selected-children", +"solutionLink": "/dsa-solutions/lc-solutions/3000-3099/maximize happiness of selected children" +}, +{ +"problemName": "3076. Shortest Uncommon Substring in an Array", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/shortest-uncommon-substring-in-an-array", +"solutionLink": "#" +}, +{ +"problemName": "3077. Maximum Strength of K Disjoint Subarrays", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/maximum-strength-of-k-disjoint-subarrays", +"solutionLink": "#" +}, +{ +"problemName": "3078. Match Alphanumerical Pattern in Matrix I", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/match-alphanumerical-pattern-in-matrix-i", +"solutionLink": "#" +}, +{ +"problemName": "3079. Find the Sum of Encrypted Integers", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/find-the-sum-of-encrypted-integers", +"solutionLink": "#" +}, +{ +"problemName": "3080. Mark Elements on Array by Performing Queries", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/mark-elements-on-array-by-performing-queries", +"solutionLink": "#" +}, +{ +"problemName": "3081. Replace Question Marks in String to Minimize Its Value", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/replace-question-marks-in-string-to-minimize-its-value", +"solutionLink": "#" +}, +{ +"problemName": "3082. Find the Sum of the Power of All Subsequences", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-the-sum-of-the-power-of-all-subsequences", +"solutionLink": "#" +}, +{ +"problemName": "3083. Existence of a Substring in a String and Its Reverse", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/existence-of-a-substring-in-a-string-and-its-reverse", +"solutionLink": "#" +}, +{ +"problemName": "3084. Count Substrings Starting and Ending with Given Character", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/count-substrings-starting-and-ending-with-given-character", +"solutionLink": "#" +}, +{ +"problemName": "3085. Minimum Deletions to Make String K-Special", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-deletions-to-make-string-k-special", +"solutionLink": "#" +}, +{ +"problemName": "3086. Minimum Moves to Pick K Ones", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/minimum-moves-to-pick-k-ones", +"solutionLink": "#" +}, +{ +"problemName": "3087. Find Trending Hashtags", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-trending-hashtags", +"solutionLink": "#" +}, +{ +"problemName": "3088. Make String Anti-palindrome", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/make-string-anti-palindrome", +"solutionLink": "#" +}, +{ +"problemName": "3089. Find Bursty Behavior", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-bursty-behavior", +"solutionLink": "#" +}, +{ +"problemName": "3090. Maximum Length Substring With Two Occurrences", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/maximum-length-substring-with-two-occurrences", +"solutionLink": "#" +}, +{ +"problemName": "3091. Apply Operations to Make Sum of Array Greater Than or Equal to k", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k", +"solutionLink": "#" +}, +{ +"problemName": "3092. Most Frequent IDs", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/most-frequent-ids", +"solutionLink": "#" +}, +{ +"problemName": "3093. Longest Common Suffix Queries", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/longest-common-suffix-queries", +"solutionLink": "#" +}, +{ +"problemName": "3094. Guess the Number Using Bitwise Questions II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/guess-the-number-using-bitwise-questions-ii", +"solutionLink": "#" +}, +{ +"problemName": "3095. Shortest Subarray With OR at Least K I", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/shortest-subarray-with-or-at-least-k-i", +"solutionLink": "#" +}, +{ +"problemName": "3096. Minimum Levels to Gain More Points", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-levels-to-gain-more-points", +"solutionLink": "#" +}, +{ +"problemName": "3097. Shortest Subarray With OR at Least K II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/shortest-subarray-with-or-at-least-k-ii", +"solutionLink": "#" +}, +{ +"problemName": "3098. Find the Sum of Subsequence Powers", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-the-sum-of-subsequence-powers", +"solutionLink": "#" +}, +{ +"problemName": "3099. Harshad Number", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/harshad-number", +"solutionLink": "/dsa-solutions/lc-solutions/3000-3099/Harshad-Number" +}, +{ +"problemName": "3001. Minimum Moves To Capture The Queen", +"difficulty": "medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-moves-to-capture-the-queen/description/", +"solutionLink": "dsa-solutions/lc-solutions/3000-3099/3001-Minimum-Moves-To-Capture-The-Queen.md" +} +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/leetcode-problems/3100-3199.md b/problems/leetcode-problems/3100-3199.md new file mode 100644 index 0000000..7ab0138 --- /dev/null +++ b/problems/leetcode-problems/3100-3199.md @@ -0,0 +1,478 @@ +--- +id: 3100-3199 +title: LeetCode Problems 3100 - 3199 +sidebar_label: 3100 - 3199 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems 3100 - 3199 + - DSA problems +--- + +export const problems = [ +{ +"problemName": "3100. Water Bottles II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/water-bottles-ii", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/water-bottles-II" +}, +{ +"problemName": "3101. Count Alternating Subarrays", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/count-alternating-subarrays", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/Count-Alternating-subarrays" +}, +{ +"problemName": "3102. Minimize Manhattan Distances", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/minimize-manhattan-distances", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/Minimize-Manhattan-Distances" +}, +{ +"problemName": "3103. Find Trending Hashtags II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-trending-hashtags-ii", +"solutionLink": "#" +}, +{ +"problemName": "3104. Find Longest Self-Contained Substring", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-longest-self-contained-substring", +"solutionLink": "#" +}, +{ +"problemName": "3105. Longest Strictly Increasing or Strictly Decreasing Subarray", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/longest-strictly-subarray" +}, +{ +"problemName": "3106. Lexicographically Smallest String After Operations With Constraint", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/lexicographically-smallest-string-after-operations-with-constraint", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/Lexicographically-Smallest-String-After-Operations-With-Constraint" +}, +{ +"problemName": "3107. Minimum Operations to Make Median of Array Equal to K", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-operations-to-make-median-of-array-equal-to-k", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/Minimum-operation-to-make-median-of-array-equal-to-k" +}, +{ +"problemName": "3108. Minimum Cost Walk in Weighted Graph", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/minimum-cost-walk-in-weighted-graph", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/Minimum-cost-walk-in-weighted-graph" +}, +{ +"problemName": "3109. Find the Index of Permutation", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-the-index-of-permutation", +"solutionLink": "#" +}, +{ +"problemName": "3110. Score of a String", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/score-of-a-string", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/score-of-a-string" +}, +{ +"problemName": "3111. Minimum Rectangles to Cover Points", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-rectangles-to-cover-points", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/minimum-rectangle-to-cover-point" +}, +{ +"problemName": "3112. Minimum Time to Visit Disappearing Nodes", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-time-to-visit-disappearing-nodes", +"solutionLink": "#" +}, +{ +"problemName": "3113. Find the Number of Subarrays Where Boundary Elements Are Maximum", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-the-number-of-subarrays-where-boundary-elements-are-maximum", +"solutionLink": "#" +}, +{ +"problemName": "3114. Latest Time You Can Obtain After Replacing Characters", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/latest-time-you-can-obtain-after-replacing-characters", +"solutionLink": "#" +}, +{ +"problemName": "3115. Maximum Prime Difference", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximum-prime-difference", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/maximum-prime-difference" +}, +{ +"problemName": "3116. Kth Smallest Amount With Single Denomination Combination", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/kth-smallest-amount-with-single-denomination-combination", +"solutionLink": "#" +}, +{ +"problemName": "3117. Minimum Sum of Values by Dividing Array", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/minimum-sum-of-values-by-dividing-array", +"solutionLink": "#" +}, +{ +"problemName": "3118. Friday Purchase III", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/friday-purchase-iii", +"solutionLink": "#" +}, +{ +"problemName": "3119. Maximum Number of Potholes That Can Be Fixed", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximum-number-of-potholes-that-can-be-fixed", +"solutionLink": "#" +}, +{ +"problemName": "3120. Count the Number of Special Characters I", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/count-the-number-of-special-characters-i", +"solutionLink": "#" +}, +{ +"problemName": "3121. Count the Number of Special Characters II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/count-the-number-of-special-characters-ii", +"solutionLink": "#" +}, +{ +"problemName": "3122. Minimum Number of Operations to Satisfy Conditions", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-number-of-operations-to-satisfy-conditions", +"solutionLink": "#" +}, +{ +"problemName": "3123. Find Edges in Shortest Paths", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-edges-in-shortest-paths", +"solutionLink": "#" +}, +{ +"problemName": "3124. Find Longest Calls", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-longest-calls", +"solutionLink": "#" +}, +{ +"problemName": "3125. Maximum Number That Makes Result of Bitwise AND Zero", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximum-number-that-makes-result-of-bitwise-and-zero", +"solutionLink": "#" +}, +{ +"problemName": "3126. Server Utilization Time", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/server-utilization-time", +"solutionLink": "#" +}, +{ +"problemName": "3127. Make a Square with the Same Color", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/make-a-square-with-the-same-color", +"solutionLink": "#" +}, +{ +"problemName": "3128. Right Triangles", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/right-triangles", +"solutionLink": "#" +}, +{ +"problemName": "3129. Find All Possible Stable Binary Arrays I", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-all-possible-stable-binary-arrays-i", +"solutionLink": "#" +}, +{ +"problemName": "3130. Find All Possible Stable Binary Arrays II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-all-possible-stable-binary-arrays-ii", +"solutionLink": "#" +}, +{ +"problemName": "3131. Find the Integer Added to Array I", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/find-the-integer-added-to-array-i", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/find-integer-added-to-array" +}, +{ +"problemName": "3132. Find the Integer Added to Array II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-the-integer-added-to-array-ii", +"solutionLink": "#" +}, +{ +"problemName": "3133. Minimum Array End", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-array-end", +"solutionLink": "#" +}, +{ +"problemName": "3134. Find the Median of the Uniqueness Array", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-the-median-of-the-uniqueness-array", +"solutionLink": "#" +}, +{ +"problemName": "3135. Equalize Strings by Adding or Removing Characters at Ends", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/equalize-strings-by-adding-or-removing-characters-at-ends", +"solutionLink": "#" +}, +{ +"problemName": "3136. Valid Word", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/valid-word", +"solutionLink": "#" +}, +{ +"problemName": "3137. Minimum Number of Operations to Make Word K-Periodic", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-number-of-operations-to-make-word-k-periodic", +"solutionLink": "#" +}, +{ +"problemName": "3138. Minimum Length of Anagram Concatenation", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-length-of-anagram-concatenation", +"solutionLink": "#" +}, +{ +"problemName": "3139. Minimum Cost to Equalize Array", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/minimum-cost-to-equalize-array", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/minimum-cost-to-equalize-array" +}, +{ +"problemName": "3140. Consecutive Available Seats II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/consecutive-available-seats-ii", +"solutionLink": "#" +}, +{ +"problemName": "3141. Maximum Hamming Distances", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/maximum-hamming-distances", +"solutionLink": "#" +}, +{ +"problemName": "3142. Check if Grid Satisfies Conditions", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/check-if-grid-satisfies-conditions", +"solutionLink": "#" +}, +{ +"problemName": "3143. Maximum Points Inside the Square", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximum-points-inside-the-square", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/maximum-points-inside-square" +}, +{ +"problemName": "3144. Minimum Substring Partition of Equal Character Frequency", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/minimum-substring-partition-of-equal-character-frequency", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/minimum-substring-partition-of-equal-charater-frequency" +}, +{ +"problemName": "3145. Find Products of Elements of Big Array", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-products-of-elements-of-big-array", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/find-product-of-element-of-big-array" +}, +{ +"problemName": "3146. Permutation Difference between Two Strings", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/permutation-difference-between-two-strings", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/permutation-difference-between-two-string" +}, +{ +"problemName": "3147. Taking Maximum Energy From the Mystic Dungeon", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/taking-maximum-energy-from-the-mystic-dungeon", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/Taking-Maximum-Energy-From-the-Mystic-Dungeon" +}, +{ +"problemName": "3148. Maximum Difference Score in a Grid", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximum-difference-score-in-a-grid", +"solutionLink": "#" +}, +{ +"problemName": "3149. Find the Minimum Cost Array Permutation", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-the-minimum-cost-array-permutation", +"solutionLink": "#" +}, +{ +"problemName": "3150. Invalid Tweets II", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/invalid-tweets-ii", +"solutionLink": "#" +}, +{ +"problemName": "3151. Special Array I", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/special-array-i", +"solutionLink": "#" +}, +{ +"problemName": "3152. Special Array II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/special-array-ii", +"solutionLink": "#" +}, +{ +"problemName": "3153. Sum of Digit Differences of All Pairs", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/sum-of-digit-differences-of-all-pairs", +"solutionLink": "#" +}, +{ +"problemName": "3154. Find Number of Ways to Reach the K-th Stair", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/find-number-of-ways-to-reach-the-k-th-stair", +"solutionLink": "#" +}, +{ +"problemName": "3155. Maximum Number of Upgradable Servers", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximum-number-of-upgradable-servers", +"solutionLink": "#" +}, +{ +"problemName": "3156. Employee Task Duration and Concurrent Tasks", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/employee-task-duration-and-concurrent-tasks", +"solutionLink": "#" +}, +{ +"problemName": "3157. Find the Level of Tree with Minimum Sum", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-the-level-of-tree-with-minimum-sum", +"solutionLink": "#" +}, +{ +"problemName": "3158. Find the XOR of Numbers Which Appear Twice", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/find-the-xor-of-numbers-which-appear-twice", +"solutionLink": "#" +}, +{ +"problemName": "3159. Find Occurrences of an Element in an Array", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-occurrences-of-an-element-in-an-array", +"solutionLink": "#" +}, +{ +"problemName": "3160. Find the Number of Distinct Colors Among the Balls", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-the-number-of-distinct-colors-among-the-balls", +"solutionLink": "#" +}, +{ +"problemName": "3161. Block Placement Queries", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/block-placement-queries", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/fenwick-tree-solution" +}, +{ +"problemName": "3162. Find the Number of Good Pairs I", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/find-the-number-of-good-pairs-i", +"solutionLink": "#" +}, +{ +"problemName": "3163. String Compression III", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/string-compression-iii", +"solutionLink": "#" +}, +{ +"problemName": "3164. Find the Number of Good Pairs II", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-the-number-of-good-pairs-ii", +"solutionLink": "#" +}, +{ +"problemName": "3165. Maximum Sum of Subsequence With Non-adjacent Elements", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/maximum-sum-of-subsequence-with-non-adjacent-elements", +"solutionLink": "#" +}, +{ +"problemName": "3166. Calculate Parking Fees and Duration", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/calculate-parking-fees-and-duration", +"solutionLink": "#" +}, +{ +"problemName": "3167. Better Compression of String", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/better-compression-of-string", +"solutionLink": "#" +}, +{ +"problemName": "3169. Count Days Without Meetings", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/count-days-without-meetings/description/", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/count-days-without-meetings" +}, +{ +"problemName": "3170. Lexicographically Minimum String After Removing Stars", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/lexicographically-minimum-string-after-removing-stars/description/", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/lexicographically-minimum-string-after-removing-stars" +}, +{ +"problemName": "3179.Find the N-th Value After K Seconds", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-the-n-th-value-after-k-seconds/", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/find-the-n-th-value-after-k-seconds" +}, +{ +"problemName": "3180. Maximum Total Reward Using Operations I", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/maximum-total-reward-using-operations-i", +"solutionLink": "#" +}, +{ +"problemName": "3181. Maximum Total Reward Using Operations II", +"difficulty": "Hard", +"leetCodeLink": "https://leetcode.com/problems/maximum-total-reward-using-operations-ii", +"solutionLink": "#" +}, +{ +"problemName": "3182. Find Top Scoring Students", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-top-scoring-students", +"solutionLink": "#" +}, +{ +"problemName": "3183. The Number of Ways To Make The Sum", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/the-number-of-ways-to-make-the-sum", +"solutionLink": "#" +}, +{ +"problemName": "3195. Find the Minimum Area to Cover All Ones I", +"difficulty": "Medium", +"leetCodeLink": "https://leetcode.com/problems/find-the-minimum-area-to-cover-all-ones-i/description/", +"solutionLink": "/dsa-solutions/lc-solutions/3100-3199/find-the-minimum-area-to-cover-all-ones-i" +}, +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/leetcode-problems/3200-3299.md b/problems/leetcode-problems/3200-3299.md new file mode 100644 index 0000000..dedcc4c --- /dev/null +++ b/problems/leetcode-problems/3200-3299.md @@ -0,0 +1,28 @@ +--- +id: 3200-3299 +title: LeetCode Problems 3200-3299 +sidebar_label: 3200-3299 +keywords: + - LeetCode + - LeetCode Problems + - LeetCode Problems3200-3299 + - DSA problems +--- + +export const problems = [ +{ +"problemName": "3216.Lexicographically Smallest String After a Swap", +"difficulty": "Easy", +"leetCodeLink": "https://leetcode.com/problems/lexicographically-smallest-string-after-a-swap/description/", +"solutionLink": "/dsa-solutions/lc-solutions/3200-3299/lexicographically-smallest-string-after-a-swap" +}, +]; + +
+ +Now, you can see the list of problems in a table format. You can click on the problem link to view the problem on the LeetCode website. You can also click on the solution link to view the solution of the problem. diff --git a/problems/leetcode-problems/_category_.json b/problems/leetcode-problems/_category_.json new file mode 100644 index 0000000..574bfe1 --- /dev/null +++ b/problems/leetcode-problems/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "LeetCode Problems", + "position": 2, + "link": { + "type": "generated-index", + "description": "You will learn about the LeetCode Problems of Data Structures and Algorithms." + } + } \ No newline at end of file diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000..3161e78 --- /dev/null +++ b/renovate.json @@ -0,0 +1,24 @@ +{ + "extends": [ + "config:base", + "config:recommended", + ":dependencyDashboard" + ], + "schedule": [ + "at any time" + ], + "packageRules": [ + { + "packagePatterns": ["*"], + "groupName": "all dependencies", + "groupSlug": "all" + } + ], + "automerge": false, + "automergeType": "pr", + "prHourlyLimit": 24, + "prConcurrentLimit": 10, + "labels": ["dependencies"], + "reviewers": ["Ajay-Dhangar"], + "assignees": ["Ajay-Dhangar"] +} diff --git a/service-app.yml b/service-app.yml new file mode 100644 index 0000000..85ab090 --- /dev/null +++ b/service-app.yml @@ -0,0 +1,14 @@ +apiVersion: v1 +kind: Service +metadata: + name: service-my-node-app +spec: + ports: + - name: http + port: 8080 + targetPort: 3000 + selector: + # Loadbalance traffic across Pods matching + # this label selector + app: node-app + type: LoadBalancer diff --git a/sidebar.js b/sidebar.js new file mode 100644 index 0000000..2d46b5f --- /dev/null +++ b/sidebar.js @@ -0,0 +1,10 @@ +// @ts-check + +/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ +const sidebars = { + tutorialSidebar: [ + { type: "autogenerated", dirName: "." }, + ], +}; + +export default sidebars; diff --git a/sidebars.js b/sidebars.js new file mode 100644 index 0000000..7e66303 --- /dev/null +++ b/sidebars.js @@ -0,0 +1,20 @@ +// @ts-check + +/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ +const sidebars = { + tutorialSidebar: [ + { type: "autogenerated", dirName: "." }, + { + type: "link", + label: "DSA Problems", + href: "/dsa-problems", + }, + { + type: "link", + label: "DSA Solutions", + href: "/dsa-solutions", + }, + ], +}; + +export default sidebars; diff --git a/solutions/Searching-Algorithms/01-Linear-Search.md b/solutions/Searching-Algorithms/01-Linear-Search.md new file mode 100644 index 0000000..1f6dd37 --- /dev/null +++ b/solutions/Searching-Algorithms/01-Linear-Search.md @@ -0,0 +1,168 @@ +--- +id: Linear-Search +title: Linear Search (Geeks for Geeks) +sidebar_label: Linear Search +tags: + - Beginner + - Search Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Linear Search problem on Geeks for Geeks." +--- + +## What is Linear Search? + +Linear Search is a simple search algorithm used to find the presence of a target element within a list. It sequentially checks each element of the list until the target element is found or the list ends. + +## Algorithm for Linear Search + +1. Start from the leftmost element of the list and move towards the right. +2. Compare the target element with each element of the list. +3. If the target element matches with an element, return the index. +4. If the target element does not match any element, return -1. + +## How does Linear Search work? + +- It starts from the first element and compares the target element with each element in the list. +- If a match is found, it returns the index of the matching element. +- If no match is found after checking all elements, it returns -1 indicating the target is not present in the list. + + + +## Problem Description + +Given a list and a target element, implement the Linear Search algorithm to find the index of the target element in the list. If the element is not present, return -1. + +## Examples + +**Example 1:** +``` +Input: +list = [1, 3, 5, 7, 9] +target = 5 +Output: 2 +``` + +**Example 2:** +``` +Input: +list = [2, 4, 6, 8, 10] +target = 7 +Output: -1 +``` +## Your task + +Complete the function search() which takes two integers n , k and an array arr, as input parameters and returns an integer denoting the answer. Return -1 if the number is not found in the array. You don't have to print answers or take inputs. + +Expected Time Complexity: $O(n)$ +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- $1 <= n <= 10^6$ +- $1 <= k <= 10^6$ +- $1 <= arr[i] <= 10^9$ + +## Implementation + + + + + ```python + def linear_search(lst, target): + for i in range(len(lst)): + if lst[i] == target: + return i + return -1 + ``` + + + + + ```cpp + #include + #include + + int linear_search(const std::vector& lst, int target) { + for (int i = 0; i < lst.size(); i++) { + if (lst[i] == target) { + return i; + } + } + return -1; + } + + int main() { + std::vector lst = {1, 3, 5, 7, 9}; + int target = 5; + std::cout << "Index: " << linear_search(lst, target) << std::endl; + return 0; + } + ``` + + + + + ```java + public class LinearSearch { + public static int linearSearch(int[] lst, int target) { + for (int i = 0; i < lst.length; i++) { + if (lst[i] == target) { + return i; + } + } + return -1; + } + + public static void main(String[] args) { + int[] lst = {1, 3, 5, 7, 9}; + int target = 5; + System.out.println("Index: " + linearSearch(lst, target)); + } + } + ``` + + + + + ```javascript + function linearSearch(lst, target) { + for (let i = 0; i < lst.length; i++) { + if (lst[i] === target) { + return i; + } + } + return -1; + } + + const lst = [1, 3, 5, 7, 9]; + const target = 5; + console.log("Index:", linearSearch(lst, target)); + ``` + + + +## Complexity Analysis + +- **Time Complexity**: $O(n)$, where $n$ is the number of elements in the list. In the worst case, it will search through the entire list. +- **Space Complexity**: $O(1)$, as no extra space is required apart from the input list. + +## Advantages and Disadvantages + +**Advantages:** +- Simple and easy to implement. +- Does not require the list to be sorted. + +**Disadvantages:** +- Inefficient for large lists as it has a linear time complexity. +- Better alternatives exist for sorted lists or when multiple searches are required. + +## References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/linear-search/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/linear-search/problem) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) \ No newline at end of file diff --git a/solutions/Searching-Algorithms/02-Binary-Search.md b/solutions/Searching-Algorithms/02-Binary-Search.md new file mode 100644 index 0000000..2bcd9da --- /dev/null +++ b/solutions/Searching-Algorithms/02-Binary-Search.md @@ -0,0 +1,200 @@ +--- +id: Binary-Search +title: Binary Search (Geeks for Geeks) +sidebar_label: Binary Search +tags: + - Beginner + - Search Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Binary Search problem on Geeks for Geeks." +--- + +## What is Binary Search? + +Binary Search is a highly efficient search algorithm used to find the position of a target element within a sorted list. It works by repeatedly dividing the search interval in half and comparing the target value to the middle element of the interval. + +## Algorithm for Binary Search + +1. Start with the left pointer at the beginning of the list and the right pointer at the end. +2. Calculate the middle index of the current search interval. +3. Compare the target value with the middle element: + - If the target value equals the middle element, return the middle index. + - If the target value is less than the middle element, move the right pointer to $middle - 1$. + - If the target value is greater than the middle element, move the left pointer to $middle + 1$. +4. Repeat steps 2-3 until the left pointer exceeds the right pointer. +5. If the target value is not found, return -1. + +## How does Binary Search work? + +- It starts by comparing the target value to the middle element of the list. +- If the target value matches the middle element, the search is complete. +- If the target value is less than the middle element, the search continues in the left half of the list. +- If the target value is greater than the middle element, the search continues in the right half of the list. +- This process continues until the target value is found or the search interval is empty. + +![Example for Binary Search(GFG)](../../assets/binnary-search-.webp) + +## Problem Description + +Given a sorted list and a target element, implement the Binary Search algorithm to find the index of the target element in the list. If the element is not present, return -1. + +## Examples + +**Example 1:** +``` +Input: +list = [1, 3, 5, 7, 9] +target = 5 +Output: 2 +``` + +**Example 2:** +``` +Input: +list = [2, 4, 6, 8, 10] +target = 7 +Output: -1 +``` + +## Your Task: + +You dont need to read input or print anything. Complete the function binarysearch() which takes arr[], N and K as input parameters and returns the index of K in the array. If K is not present in the array, return -1. + + +Expected Time Complexity: $O(LogN)$ +Expected Auxiliary Space: $O(LogN)$ if solving recursively and O(1) otherwise. + +## Constraints + +- $1 <= N <= 10^5$ +- $1 <= arr[i] <= 10^6$ +- $1 <= K <= 10^6$ + +## Implementation + + + + + ```python + def binary_search(lst, target): + left, right = 0, len(lst) - 1 + while left <= right: + mid = left + (right - left) // 2 + if lst[mid] == target: + return mid + elif lst[mid] < target: + left = mid + 1 + else: + right = mid - 1 + return -1 + ``` + + + + + ```cpp + #include + #include + + int binary_search(const std::vector& lst, int target) { + int left = 0, right = lst.size() - 1; + while (left <= right) { + int mid = left + (right - left) / 2; + if (lst[mid] == target) { + return mid; + } else if (lst[mid] < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + return -1; + } + + int main() { + std::vector lst = {1, 3, 5, 7, 9}; + int target = 5; + std::cout << "Index: " << binary_search(lst, target) << std::endl; + return 0; + } + ``` + + + + + ```java + public class BinarySearch { + public static int binarySearch(int[] lst, int target) { + int left = 0, right = lst.length - 1; + while (left <= right) { + int mid = left + (right - left) / 2; + if (lst[mid] == target) { + return mid; + } else if (lst[mid] < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + return -1; + } + + public static void main(String[] args) { + int[] lst = {1, 3, 5, 7, 9}; + int target = 5; + System.out.println("Index: " + binarySearch(lst, target)); + } + } + ``` + + + + + ```javascript + function binarySearch(lst, target) { + let left = 0, right = lst.length - 1; + while (left <= right) { + const mid = left + Math.floor((right - left) / 2); + if (lst[mid] === target) { + return mid; + } else if (lst[mid] < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + return -1; + } + + const lst = [1, 3, 5, 7, 9]; + const target = 5; + console.log("Index:", binarySearch(lst, target)); + ``` + + + +## Complexity Analysis + +- **Time Complexity**: $O(log n)$, where $n$ is the number of elements in the list. The list is divided in half at each step, leading to logarithmic time complexity. +- **Space Complexity**: $O(1)$, as no extra space is required apart from the input list. + +## Advantages and Disadvantages + +**Advantages:** +- Highly efficient for large sorted lists. +- Fast search time due to logarithmic time complexity. + +**Disadvantages:** +- Requires the list to be sorted. +- Less efficient for small lists compared to linear search. + +## References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/binary-search/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/binary-search/problem) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) \ No newline at end of file diff --git a/solutions/Searching-Algorithms/03-Breadth-First-Search (BFS).md b/solutions/Searching-Algorithms/03-Breadth-First-Search (BFS).md new file mode 100644 index 0000000..644b2f1 --- /dev/null +++ b/solutions/Searching-Algorithms/03-Breadth-First-Search (BFS).md @@ -0,0 +1,249 @@ +--- +id: Breadth-First-Search-BFS +title: Breadth First Search (BFS) (Geeks for Geeks) +sidebar_label: Breadth First Search (BFS) +tags: + - Beginner + - Graph Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Breadth First Search (BFS) problem on Geeks for Geeks." +--- + +## 1. What is Breadth First Search (BFS)? + +Breadth First Search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree's root (or an arbitrary node in the graph) and explores the neighbor nodes at the present depth prior to moving on to nodes at the next depth level. + +## 2. Algorithm for Breadth First Search (BFS) + +1. Initialize a queue and enqueue the starting node. +2. Mark the starting node as visited. +3. While the queue is not empty: + - Dequeue a node from the queue. + - Process the dequeued node (e.g., print its value). + - Enqueue all unvisited adjacent nodes of the dequeued node. + - Mark the newly enqueued nodes as visited. + +## 3. How does Breadth First Search (BFS) work? + +- BFS explores all nodes at the present depth level before moving on to nodes at the next depth level. +- It uses a queue data structure to keep track of nodes to be explored. +- Nodes are marked as visited to prevent reprocessing. + +## 4. Problem Description + +Given a graph represented as an adjacency list, implement the Breadth First Search (BFS) algorithm to traverse the graph starting from a given source node. + +## 5. Examples + +**Example 1:** +``` +Input: +graph = { + 0: [1, 2], + 1: [2], + 2: [0, 3], + 3: [3] +} +start_node = 2 +Output: 2 0 3 1 +``` + +**Example 2:** +``` +Input: +graph = { + 0: [1, 3], + 1: [0, 2], + 2: [1, 3], + 3: [0, 2] +} +start_node = 0 +Output: 0 1 3 2 +``` + +## 6. Constraints + +- $The graph can have any number of nodes.$ +- $The graph can be directed or undirected.$ + +## 7. Implementation + + + + + ```python + from collections import deque + + def bfs(graph, start_node): + visited = set() + queue = deque([start_node]) + result = [] + + while queue: + node = queue.popleft() + if node not in visited: + visited.add(node) + result.append(node) + queue.extend(neighbor for neighbor in graph[node] if neighbor not in visited) + return result + + # Example usage: + graph = { + 0: [1, 2], + 1: [2], + 2: [0, 3], + 3: [3] + } + start_node = 2 + print(bfs(graph, start_node)) + ``` + + + + + ```cpp + #include + #include + #include + #include + + std::vector bfs(const std::vector>& graph, int start_node) { + std::vector result; + std::queue queue; + std::unordered_set visited; + + queue.push(start_node); + visited.insert(start_node); + + while (!queue.empty()) { + int node = queue.front(); + queue.pop(); + result.push_back(node); + + for (int neighbor : graph[node]) { + if (visited.find(neighbor) == visited.end()) { + queue.push(neighbor); + visited.insert(neighbor); + } + } + } + return result; + } + + int main() { + std::vector> graph = { + {1, 2}, + {2}, + {0, 3}, + {3} + }; + int start_node = 2; + std::vector traversal = bfs(graph, start_node); + + for (int node : traversal) { + std::cout << node << " "; + } + return 0; + } + ``` + + + + + ```java + import java.util.*; + + public class BFS { + public static List bfs(Map> graph, int startNode) { + List result = new ArrayList<>(); + Queue queue = new LinkedList<>(); + Set visited = new HashSet<>(); + + queue.add(startNode); + visited.add(startNode); + + while (!queue.isEmpty()) { + int node = queue.poll(); + result.add(node); + + for (int neighbor : graph.get(node)) { + if (!visited.contains(neighbor)) { + queue.add(neighbor); + visited.add(neighbor); + } + } + } + return result; + } + + public static void main(String[] args) { + Map> graph = new HashMap<>(); + graph.put(0, Arrays.asList(1, 2)); + graph.put(1, Arrays.asList(2)); + graph.put(2, Arrays.asList(0, 3)); + graph.put(3, Arrays.asList(3)); + + int startNode = 2; + List traversal = bfs(graph, startNode); + System.out.println(traversal); + } + } + ``` + + + + + ```javascript + function bfs(graph, startNode) { + const visited = new Set(); + const queue = [startNode]; + const result = []; + + while (queue.length > 0) { + const node = queue.shift(); + if (!visited.has(node)) { + visited.add(node); + result.push(node); + queue.push(...graph[node].filter(neighbor => !visited.has(neighbor))); + } + } + return result; + } + + const graph = { + 0: [1, 2], + 1: [2], + 2: [0, 3], + 3: [3] + }; + const startNode = 2; + console.log(bfs(graph, startNode)); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: $O(V + E)$, where $V$ is the number of vertices and $E$ is the number of edges. Each vertex and edge is processed once. +- **Space Complexity**: $O(V)$, where $V$ is the number of vertices. This is for the queue and the visited set. + +## 9. Advantages and Disadvantages + +**Advantages:** +- Finds the shortest path in unweighted graphs. +- Simple and easy to understand and implement. + +**Disadvantages:** +- Can be memory intensive as it stores all vertices in the queue. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/breadth-first-search/problem) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) + diff --git a/solutions/Searching-Algorithms/04-Depth-First-Search (DFS).md b/solutions/Searching-Algorithms/04-Depth-First-Search (DFS).md new file mode 100644 index 0000000..1a42a7e --- /dev/null +++ b/solutions/Searching-Algorithms/04-Depth-First-Search (DFS).md @@ -0,0 +1,220 @@ +--- +id: Depth-First-Search-DFS +title: Depth First Search (DFS) (Geeks for Geeks) +sidebar_label: Depth First Search (DFS) +tags: + - Beginner + - Graph Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Depth First Search (DFS) problem on Geeks for Geeks." +--- + +## 1. What is Depth First Search (DFS)? + +Depth First Search (DFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the root (or an arbitrary node in the graph) and explores as far as possible along each branch before backtracking. + +## 2. Algorithm for Depth First Search (DFS) + +1. Start with the root node (or an arbitrary node in the graph). +2. Mark the node as visited. +3. For each adjacent node, recursively apply the DFS algorithm if the node has not been visited. + +## 3. How does Depth First Search (DFS) work? + +- DFS explores as far as possible along each branch before backtracking. +- It uses a stack data structure, either implicitly through recursion or explicitly through an iterative approach. +- Nodes are marked as visited to prevent reprocessing. + +## 4. Problem Description + +Given a graph represented as an adjacency list, implement the Depth First Search (DFS) algorithm to traverse the graph starting from a given source node. + +## 5. Examples + +**Example 1:** +``` +Input: +graph = { + 0: [1, 2], + 1: [2], + 2: [0, 3], + 3: [3] +} +start_node = 2 +Output: 2 0 1 3 +``` + +**Example 2:** +``` +Input: +graph = { + 0: [1, 3], + 1: [0, 2], + 2: [1, 3], + 3: [0, 2] +} +start_node = 0 +Output: 0 1 2 3 +``` + +## 6. Constraints + +- $The graph can have any number of nodes.$ +- $The graph can be directed or undirected.$ + +## 7. Implementation + + + + + ```python + def dfs(graph, start_node, visited=None): + if visited is None: + visited = set() + visited.add(start_node) + result = [start_node] + for neighbor in graph[start_node]: + if neighbor not in visited: + result.extend(dfs(graph, neighbor, visited)) + return result + + # Example usage: + graph = { + 0: [1, 2], + 1: [2], + 2: [0, 3], + 3: [3] + } + start_node = 2 + print(dfs(graph, start_node)) + ``` + + + + + ```cpp + #include + #include + #include + + void dfsUtil(int node, const std::vector>& graph, std::unordered_set& visited, std::vector& result) { + visited.insert(node); + result.push_back(node); + for (int neighbor : graph[node]) { + if (visited.find(neighbor) == visited.end()) { + dfsUtil(neighbor, graph, visited, result); + } + } + } + + std::vector dfs(const std::vector>& graph, int start_node) { + std::unordered_set visited; + std::vector result; + dfsUtil(start_node, graph, visited, result); + return result; + } + + int main() { + std::vector> graph = { + {1, 2}, + {2}, + {0, 3}, + {3} + }; + int start_node = 2; + std::vector traversal = dfs(graph, start_node); + + for (int node : traversal) { + std::cout << node << " "; + } + return 0; + } + ``` + + + + + ```java + import java.util.*; + + public class DFS { + public static List dfs(Map> graph, int startNode, Set visited) { + List result = new ArrayList<>(); + visited.add(startNode); + result.add(startNode); + + for (int neighbor : graph.get(startNode)) { + if (!visited.contains(neighbor)) { + result.addAll(dfs(graph, neighbor, visited)); + } + } + return result; + } + + public static void main(String[] args) { + Map> graph = new HashMap<>(); + graph.put(0, Arrays.asList(1, 2)); + graph.put(1, Arrays.asList(2)); + graph.put(2, Arrays.asList(0, 3)); + graph.put(3, Arrays.asList(3)); + + int startNode = 2; + Set visited = new HashSet<>(); + List traversal = dfs(graph, startNode, visited); + System.out.println(traversal); + } + } + ``` + + + + + ```javascript + function dfs(graph, startNode, visited = new Set()) { + visited.add(startNode); + const result = [startNode]; + for (const neighbor of graph[startNode]) { + if (!visited.has(neighbor)) { + result.push(...dfs(graph, neighbor, visited)); + } + } + return result; + } + + const graph = { + 0: [1, 2], + 1: [2], + 2: [0, 3], + 3: [3] + }; + const startNode = 2; + console.log(dfs(graph, startNode)); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: $O(V + E)$, where $V$ is the number of vertices and $E$ is the number of edges. Each vertex and edge is processed once. +- **Space Complexity**: $O(V)$, where $V$ is the number of vertices. This is for the visited set and the recursive stack space. + +## 9. Advantages and Disadvantages + +**Advantages:** +- Can be easily implemented with recursion. +- Useful for problems that involve exploring all paths, like puzzles and mazes. + +**Disadvantages:** +- Can be memory intensive due to the stack space in recursion. +- Not optimal for finding the shortest path in unweighted graphs. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/depth-first-search/problem) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) diff --git a/solutions/Searching-Algorithms/05-AVL-Tree-Search.md b/solutions/Searching-Algorithms/05-AVL-Tree-Search.md new file mode 100644 index 0000000..08781c3 --- /dev/null +++ b/solutions/Searching-Algorithms/05-AVL-Tree-Search.md @@ -0,0 +1,195 @@ +--- +id: avl-tree-search +title: AVL Tree Search (Geeks for Geeks) +sidebar_label: AVL Tree Search +tags: + - Beginner + - Search Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the AVL Tree Search problem on Geeks for Geeks." +--- + +## What is AVL Tree Search? + +AVL Tree Search is a search operation performed on an AVL tree, a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by no more than one, ensuring O(log N) time complexity for search operations. + +## Algorithm for AVL Tree Search + +1. Start at the root node of the AVL tree. +2. Compare the target value with the value of the current node: +- If the target value equals the current node's value, return the node. +- If the target value is less than the current node's value, move to the left child. +- If the target value is greater than the current node's value, move to the right child. +3. Repeat step 2 until the target value is found or the current node becomes null. +4. If the target value is not found, return null. + +## How does AVL Tree Search work? + +- It begins by comparing the target value to the value of the root node. +- If the target value matches the root node's value, the search is complete. +- If the target value is less than the root node's value, the search continues in the left subtree. +- If the target value is greater than the root node's value, the search continues in the right subtree. +- This process continues until the target value is found or a leaf node is reached without finding the target value. + +![Example for AVL Tree Search(GFG)](../../assets/Avl-Tree.png) + +## Problem Description + +Given an AVL tree and a target element, implement the AVL Tree Search algorithm to find the node containing the target value in the tree. If the element is not present, return null. + +## Examples + +**Example 1:** +``` +Input: +AVL Tree: + 9 + / \ + 5 12 + / \ \ + 2 7 15 + +Target: 7 +Output: Node with value 7 + +``` + +## Your Task: + +You don't need to read input or print anything. Complete the function avlTreeSearch() which takes the root of the AVL tree and a target value as input parameters and returns the node containing the target value. If the target value is not present in the tree, return null. + +Expected Time Complexity: $O(LogN)$ +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- $1 <= Number of nodes <= 10^5$ +- $1 <= Node value <= 10^6$ +- $1 <= Target value <= 10^6$ + +## Implementation + + + + + + ```cpp + #include + +struct AVLNode { + int value; + AVLNode* left; + AVLNode* right; + AVLNode(int val) : value(val), left(nullptr), right(nullptr) {} +}; + +AVLNode* avlTreeSearch(AVLNode* root, int target) { + AVLNode* current = root; + while (current) { + if (current->value == target) { + return current; + } else if (current->value < target) { + current = current->right; + } else { + current = current->left; + } + } + return nullptr; +} + +int main() { + AVLNode* root = new AVLNode(9); + root->left = new AVLNode(5); + root->right = new AVLNode(12); + root->left->left = new AVLNode(2); + root->left->right = new AVLNode(7); + root->right->right = new AVLNode(15); + + int target = 7; + AVLNode* result = avlTreeSearch(root, target); + if (result) { + std::cout << "Node with value " << result->value << " found." << std::endl; + } else { + std::cout << "Node not found." << std::endl; + } + + return 0; +} + + + + + + ```java + class AVLNode { + int value; + AVLNode left, right; + AVLNode(int value) { + this.value = value; + left = right = null; + } +} + +public class AVLTreeSearch { + public static AVLNode avlTreeSearch(AVLNode root, int target) { + AVLNode current = root; + while (current != null) { + if (current.value == target) { + return current; + } else if (current.value < target) { + current = current.right; + } else { + current = current.left; + } + } + return null; + } + + public static void main(String[] args) { + AVLNode root = new AVLNode(9); + root.left = new AVLNode(5); + root.right = new AVLNode(12); + root.left.left = new AVLNode(2); + root.left.right = new AVLNode(7); + root.right.right = new AVLNode(15); + + int target = 7; + AVLNode result = avlTreeSearch(root, target); + if (result != null) { + System.out.println("Node with value " + result.value + " found."); + } else { + System.out.println("Node not found."); + } + } +} + + ``` + + + +## Complexity Analysis + +- **Time Complexity**:$O(log n)$, where $n$ is the number of nodes in the AVL tree. The height of the tree is kept balanced, leading to logarithmic time complexity. +- **Space Complexity**: $O(1)$, as no extra space is required apart from the input tree. + +## Advantages and Disadvantages + +**Advantages:** +- Ensures balanced tree structure for efficient search, insert, and delete operations. +- Fast search time due to logarithmic time complexity. + +**Disadvantages:** +- Requires additional rotations to maintain balance during insert and delete operations. +- More complex to implement compared to simple binary search trees. + + +## References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/practice-questions-height-balancedavl-tree//) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) + diff --git a/solutions/Searching-Algorithms/Adaptive-Search.md b/solutions/Searching-Algorithms/Adaptive-Search.md new file mode 100644 index 0000000..fa5ed02 --- /dev/null +++ b/solutions/Searching-Algorithms/Adaptive-Search.md @@ -0,0 +1,227 @@ +--- +id: Adaptive-Segment-Search +title: Adaptive Segment Search Algorithm (Geeks for Geeks) +sidebar_label: Adaptive Segment Search +tags: + - Advanced + - Search Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Adaptive Segment Search algorithm problem." +--- + +## What is Adaptive Segment Search? + +Adaptive Segment Search is a sophisticated search algorithm designed to efficiently locate an element in a sorted array. It adapts its search strategy based on the distribution of the elements, making it more efficient than traditional search algorithms in certain scenarios. + +## Algorithm for Adaptive Segment Search + +1. **Initialization:** + - Divide the array into segments of varying sizes based on the distribution of the elements. + - Start with the first segment. + +2. **Segment Search:** + - Check if the target element falls within the current segment. + - If it does, perform a linear or binary search within the segment. + - If not, move to the next segment and repeat the process. + +3. **Adaptation:** + - Adjust the segment sizes dynamically based on the distribution of the elements encountered during the search. + +4. **Termination:** + - If the target element is found, return its index. + - If the end of the array is reached without finding the target, return -1. + +## How does Adaptive Segment Search work? + +- The algorithm starts by dividing the array into segments. +- It then adapts its search strategy based on the segments and the distribution of elements within the segments. +- By adjusting the segment sizes dynamically, the algorithm can achieve better performance compared to static segment sizes. + +## Problem Description + +Given a sorted list and a target element, implement the Adaptive Segment Search algorithm to find the index of the target element in the list. If the element is not present, return -1. + +## Examples + +**Example 1:** +Input: +list = [3, 6, 8, 12, 14, 17, 19, 23, 25, 29] +target = 17 +Output: 5 + +**Example 2:** +Input: +list = [3, 6, 8, 12, 14, 17, 19, 23, 25, 29] +target = 10 +Output: -1 + +## Your Task: + +You don't need to read input or print anything. Complete the function adaptive_segment_search() which takes arr[], N and K as input parameters and returns the index of K in the array. If K is not present in the array, return -1. + +Expected Time Complexity: $O(\log n)$ in the best case +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- $1 <= N <= 10^5$ +- $1 <= arr[i] <= 10^6$ +- $1 <= K <= 10^6$ + +## Implementation + + + + +```python + +def adaptive_segment_search(arr, n, x): + segment_size = 1 + while segment_size < n: + segment_size *= 2 + + start = 0 + while start < n: + end = min(start + segment_size, n) + if arr[end - 1] >= x: + for i in range(start, end): + if arr[i] == x: + return i + return -1 + start = end + return -1 +``` + + + + +```cpp + +#include +#include + +int adaptive_segment_search(const std::vector& arr, int n, int x) { + int segment_size = 1; + while (segment_size < n) { + segment_size *= 2; + } + + int start = 0; + while (start < n) { + int end = std::min(start + segment_size, n); + if (arr[end - 1] >= x) { + for (int i = start; i < end; ++i) { + if (arr[i] == x) { + return i; + } + } + return -1; + } + start = end; + } + return -1; +} + +int main() { + std::vector arr = {3, 6, 8, 12, 14, 17, 19, 23, 25, 29}; + int target = 17; + std::cout << "Index: " << adaptive_segment_search(arr, arr.size(), target) << std::endl; + return 0; +} +``` + + + + +```java + +public class AdaptiveSegmentSearch { + public static int adaptiveSegmentSearch(int[] arr, int n, int x) { + int segment_size = 1; + while (segment_size < n) { + segment_size *= 2; + } + + int start = 0; + while (start < n) { + int end = Math.min(start + segment_size, n); + if (arr[end - 1] >= x) { + for (int i = start; i < end; i++) { + if (arr[i] == x) { + return i; + } + } + return -1; + } + start = end; + } + return -1; + } + + public static void main(String[] args) { + int[] arr = {3, 6, 8, 12, 14, 17, 19, 23, 25, 29}; + int target = 17; + System.out.println("Index: " + adaptiveSegmentSearch(arr, arr.length, target)); + } +} +``` + + + + +```javascript + +function adaptiveSegmentSearch(arr, n, x) { + let segment_size = 1; + while (segment_size < n) { + segment_size *= 2; + } + + let start = 0; + while (start < n) { + let end = Math.min(start + segment_size, n); + if (arr[end - 1] >= x) { + for (let i = start; i < end; i++) { + if (arr[i] === x) { + return i; + } + } + return -1; + } + start = end; + } + return -1; +} + +const arr = [3, 6, 8, 12, 14, 17, 19, 23, 25, 29]; +const target = 17; +console.log("Index:", adaptiveSegmentSearch(arr, arr.length, target)); + +``` + + + + +# Complexity Analysis +## Time Complexity: +$O(\log n)$ in the best case, where $n$ is the number of elements in the list. + +## Space Complexity: +$O(1)$, as no extra space is required apart from the input list. + +# Advantages and Disadvantages +## Advantages: + +Adapts to the distribution of elements in the array. + +Can achieve better performance than traditional search algorithms for certain data distributions. + +## Disadvantages: + +Requires the list to be sorted. +Complexity may vary based on the distribution of the elements. diff --git a/solutions/Searching-Algorithms/Backward-Search.md b/solutions/Searching-Algorithms/Backward-Search.md new file mode 100644 index 0000000..0c968e2 --- /dev/null +++ b/solutions/Searching-Algorithms/Backward-Search.md @@ -0,0 +1,146 @@ +--- +id: Backward-Search-Algorithm +title: Backward Search Algorithm +sidebar_label: Backward Search Algorithm +tags: + - Advanced + - Search Algorithms + - Text Processing + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Backward Search Algorithm problem." +--- + +## What is the Backward Search Algorithm? + +The Backward Search Algorithm is a search method typically used in text processing and pattern matching. It works by searching for a pattern in a text from right to left, which can be more efficient in certain contexts compared to traditional left-to-right search algorithms. + +## Algorithm Steps + +1. **Preprocessing**: + - Construct a rightmost occurrence function that maps each character in the pattern to its rightmost position. + +2. **Searching**: + - Align the pattern with the beginning of the text. + - Compare characters from right to left. + - If a mismatch is found, use the rightmost occurrence function to determine the next alignment. + - If the entire pattern matches, record the position of the match. + +## Complexity Analysis + +- **Time Complexity**: The average-case time complexity is \(O(n/m)\) where \(n\) is the length of the text and \(m\) is the length of the pattern. +- **Space Complexity**: The space complexity is \(O(k)\) where \(k\) is the size of the character set. + +## Example + +Given a pattern and a text: + +``` +pattern = "ABC" +text = "AABCABCDABC" +``` + + +Using the Backward Search Algorithm: + +- The algorithm will search the pattern "ABC" in the text "AABCABCDABC" from right to left. + +## Implementation + + + + +```python +def rightmost_occurrence_function(pattern): + rightmost = {} + for i in range(len(pattern)): + rightmost[pattern[i]] = i + return rightmost + +def backward_search(text, pattern): + rightmost = rightmost_occurrence_function(pattern) + m, n = len(pattern), len(text) + i = m - 1 + j = m - 1 + + while i < n: + if text[i] == pattern[j]: + if j == 0: + return i + else: + i -= 1 + j -= 1 + else: + lo = rightmost.get(text[i], -1) + i += m - min(j, 1 + lo) + j = m - 1 + + return -1 + +# Example usage: +pattern = "ABC" +text = "AABCABCDABC" +result = backward_search(text, pattern) +print(f"Pattern found at index: {result}") +``` + + + + +```cpp + +#include +#include +#include + +std::unordered_map rightmost_occurrence_function(const std::string &pattern) { + std::unordered_map rightmost; + for (int i = 0; i < pattern.size(); ++i) { + rightmost[pattern[i]] = i; + } + return rightmost; +} + +int backward_search(const std::string &text, const std::string &pattern) { + auto rightmost = rightmost_occurrence_function(pattern); + int m = pattern.size(); + int n = text.size(); + int i = m - 1; + int j = m - 1; + + while (i < n) { + if (text[i] == pattern[j]) { + if (j == 0) { + return i; + } else { + --i; + --j; + } + } else { + int lo = rightmost.find(text[i]) != rightmost.end() ? rightmost[text[i]] : -1; + i += m - std::min(j, 1 + lo); + j = m - 1; + } + } + + return -1; +} + +int main() { + std::string pattern = "ABC"; + std::string text = "AABCABCDABC"; + int result = backward_search(text, pattern); + std::cout << "Pattern found at index: " << result << std::endl; + return 0; +} + +``` + + + + +# Conclusion +The Backward Search Algorithm is a powerful method for pattern matching in text processing. By searching from right to left and leveraging the rightmost occurrence function, it provides efficient searching capabilities, especially useful in specific contexts where this directionality offers advantages over traditional approaches. diff --git a/solutions/Searching-Algorithms/Beam-Search.md b/solutions/Searching-Algorithms/Beam-Search.md new file mode 100644 index 0000000..a493d7c --- /dev/null +++ b/solutions/Searching-Algorithms/Beam-Search.md @@ -0,0 +1,79 @@ +--- +id: beam-search +title: Beam Search Algorithm +sidebar_label: Beam Search +tags: + - Algorithms + - Search + - Machine Learning + - Natural Language Processing + - AI +description: "Explanation and implementation of the Beam Search algorithm." +--- + +Beam Search is a heuristic search algorithm commonly used in the context of sequence-to-sequence models in Natural Language Processing (NLP) and other AI applications. It explores multiple paths simultaneously, aiming to find the optimal sequence based on a scoring function. + +## Introduction + +Beam Search is an extension of Breadth-First Search (BFS) and Depth-First Search (DFS) algorithms, designed to handle sequences where the number of possible combinations is too large to explore exhaustively. + +## How Beam Search Works + +1. **Initialization**: Start with an initial sequence or state. +2. **Expansion**: Generate multiple successors (or next states) from the current set of sequences. +3. **Scoring**: Rank or score each successor based on a predefined scoring function. +4. **Pruning**: Keep only the top-scoring successors (typically a fixed number known as the beam width). +5. **Repeat**: Repeat steps 2-4 for each successor until a termination condition is met (e.g., reaching a maximum sequence length or finding a terminal state). + +## Key Concepts + +- **Beam Width**: The number of top candidates (sequences) to keep at each step. +- **Scoring Function**: Determines how successors are evaluated and ranked. +- **Termination Condition**: Criteria to stop the search, such as reaching a maximum length or achieving a desired score. + +## Advantages + +- **Efficiency**: Reduces computational cost compared to exhaustive search methods. +- **Flexibility**: Can handle variable-length sequences and large search spaces. +- **Parallelism**: Easily parallelizable due to independent scoring of successors. + +## Implementation Example + +### Pseudocode + +```python +def beam_search(initial_state, beam_width, max_length): + sequences = [[initial_state]] + for _ in range(max_length): + next_sequences = [] + for sequence in sequences: + successors = generate_successors(sequence) + scored_successors = score(successors) + top_successors = select_top(scored_successors, beam_width) + next_sequences.extend(top_successors) + sequences = next_sequences + return sequences + +# Example usage +initial_state = "start" +beam_width = 3 +max_length = 5 +result = beam_search(initial_state, beam_width, max_length) +print(result) +``` + +### Explanation + +- **generate_successors**: Function to generate possible next states or sequences. +- **score**: Function to evaluate and assign a score to each successor. +- **select_top**: Function to select the top-ranked successors based on the beam width. + +## Applications + +- **Machine Translation**: Finding the best translation from source to target language. +- **Text Summarization**: Generating concise summaries from lengthy documents. +- **Speech Recognition**: Decoding spoken language into text sequences. + +## Conclusion + +Beam Search is a powerful algorithm for searching through large, complex search spaces in AI applications. By balancing exploration and exploitation, it efficiently finds near-optimal solutions for sequence-based problems. diff --git a/solutions/Searching-Algorithms/Block-Search.md b/solutions/Searching-Algorithms/Block-Search.md new file mode 100644 index 0000000..99da355 --- /dev/null +++ b/solutions/Searching-Algorithms/Block-Search.md @@ -0,0 +1,204 @@ +--- +id: Block-Search +title: Block Search +sidebar_label: Block Search +tags: + - Intermediate + - Search Algorithms + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Block Search problem." +--- + +## What is Block Search? + +Block Search is a search algorithm that divides the array into fixed-size blocks and performs linear searches within these blocks. It combines the principles of linear search and blocking to improve efficiency. + +## Algorithm for Block Search + +1. Divide the array into fixed-size blocks. +2. Search for the block where the target element might be present. +3. Perform a linear search within the identified block. +4. If the target element is found, return its index. +5. If the target element is not found, return -1. + +## How does Block Search work? + +- It divides the array into smaller blocks of fixed size. +- It determines the block where the target element might be present. +- It performs a linear search within the identified block. + +## Problem Description + +Given a list and a target element, implement the Block Search algorithm to find the index of the target element in the list. If the element is not present, return -1. + +## Examples + +**Example 1:** +Input: +list = [1, 3, 5, 7, 9, 11, 13, 15] +target = 7 +Output: 3 + +**Example 2:** +Input: +list = [2, 4, 6, 8, 10, 12, 14, 16] +target = 5 +Output: -1 + +## Your task + +Complete the function block_search() which takes two integers n , k and an array arr, as input parameters and returns an integer denoting the answer. Return -1 if the number is not found in the array. You don't have to print answers or take inputs. + +Expected Time Complexity: $O(\sqrt{n})$ +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- $1 <= n <= 10^6$ +- $1 <= k <= 10^6$ +- $1 <= arr[i] <= 10^9$ + +## Implementation + + + + +```python + + import math + + def block_search(lst, target): + n = len(lst) + block_size = int(math.sqrt(n)) + block_start = 0 + + while block_start < n and lst[min(block_start + block_size, n) - 1] < target: + block_start += block_size + + for i in range(block_start, min(block_start + block_size, n)): + if lst[i] == target: + return i + + return -1 +``` + + + + +```cpp + + #include + #include + #include + + int block_search(const std::vector& lst, int target) { + int n = lst.size(); + int block_size = std::sqrt(n); + int block_start = 0; + + while (block_start < n && lst[std::min(block_start + block_size, n) - 1] < target) { + block_start += block_size; + } + + for (int i = block_start; i < std::min(block_start + block_size, n); ++i) { + if (lst[i] == target) { + return i; + } + } + + return -1; + } + + int main() { + std::vector lst = {1, 3, 5, 7, 9, 11, 13, 15}; + int target = 7; + std::cout << "Index: " << block_search(lst, target) << std::endl; + return 0; + } +``` + + + + +```java + + public class BlockSearch { + public static int blockSearch(int[] lst, int target) { + int n = lst.length; + int block_size = (int) Math.sqrt(n); + int block_start = 0; + + while (block_start < n && lst[Math.min(block_start + block_size, n) - 1] < target) { + block_start += block_size; + } + + for (int i = block_start; i < Math.min(block_start + block_size, n); i++) { + if (lst[i] == target) { + return i; + } + } + + return -1; + } + + public static void main(String[] args) { + int[] lst = {1, 3, 5, 7, 9, 11, 13, 15}; + int target = 7; + System.out.println("Index: " + blockSearch(lst, target)); + } + } +``` + + + + +```javascript + + function blockSearch(lst, target) { + let n = lst.length; + let block_size = Math.floor(Math.sqrt(n)); + let block_start = 0; + + while (block_start < n && lst[Math.min(block_start + block_size, n) - 1] < target) { + block_start += block_size; + } + + for (let i = block_start; i < Math.min(block_start + block_size, n); i++) { + if (lst[i] === target) { + return i; + } + } + + return -1; + } + + const lst = [1, 3, 5, 7, 9, 11, 13, 15]; + const target = 7; + console.log("Index:", blockSearch(lst, target)); +``` + + + +## Complexity Analysis + +- **Time Complexity**: $O(\sqrt{n})$, where $n$ is the number of elements in the list. The list is divided into blocks, leading to a root-time complexity. +- **Space Complexity**: $O(1)$, as no extra space is required apart from the input list. + +## Advantages and Disadvantages + +**Advantages:** +- Efficient for large lists with fixed-size blocks. +- Simple implementation with linear search within blocks. + +**Disadvantages:** +- Less efficient compared to other search algorithms for certain cases. +- Performance depends on the block size chosen. + +## References + +- **Geeks for Geeks:** [Block Search](https://www.geeksforgeeks.org/block-search/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/block-search/problem) diff --git a/solutions/Searching-Algorithms/Exponential-Search.md b/solutions/Searching-Algorithms/Exponential-Search.md new file mode 100644 index 0000000..bb7d27f --- /dev/null +++ b/solutions/Searching-Algorithms/Exponential-Search.md @@ -0,0 +1,239 @@ +--- +id: Exponential-Search +title: Exponential Search +sidebar_label: Exponential Search +tags: + - Intermediate + - Search Algorithms + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Exponential Search problem." +--- + +## What is Exponential Search? + +Exponential Search is a search algorithm for sorted arrays. It works by finding a range where the target element is likely to be and then performing a binary search within that range. This makes it more efficient than a simple binary search when the target element is expected to be close to the beginning of the array. + +## Algorithm for Exponential Search + +1. If the first element is the target, return its index. +2. Find the range for binary search by repeated doubling. Start with the range [1]. +3. Double the range size until the target is within the range or the range exceeds the size of the list. +4. Perform a binary search within the identified range. +5. If the target element is found, return its index. +6. If the target element is not found, return -1. + +## How does Exponential Search work? + +- It starts by checking if the first element is the target. +- Then, it repeatedly doubles the range to find a suitable interval where the target element might be located. +- Finally, it performs a binary search within the identified range. + +## Problem Description + +Given a sorted list and a target element, implement the Exponential Search algorithm to find the index of the target element in the list. If the element is not present, return -1. + +## Examples + +**Example 1:** +Input: +list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +target = 6 +Output: 5 + + +**Example 2:** +Input: +list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] +target = 25 +Output: -1 + + +## Your Task: + +You don't need to read input or print anything. Complete the function `exponential_search()` which takes `arr[]`, `N` and `K` as input parameters and returns the index of `K` in the array. If `K` is not present in the array, return -1. + +Expected Time Complexity: $O(\log i)$, where $i$ is the index of the target element. +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- $1 <= N <= 10^5$ +- $1 <= arr[i] <= 10^6$ +- $1 <= K <= 10^6$ + +## Implementation + + + + +```python +def binary_search(arr, left, right, target): + while left <= right: + mid = left + (right - left) // 2 + if arr[mid] == target: + return mid + elif arr[mid] < target: + left = mid + 1 + else: + right = mid - 1 + return -1 + +def exponential_search(arr, target): + if arr[0] == target: + return 0 + + n = len(arr) + i = 1 + while i < n and arr[i] <= target: + i *= 2 + + return binary_search(arr, i // 2, min(i, n - 1), target) +``` + + + + +```cpp +#include +#include +#include + +int binary_search(const std::vector& arr, int left, int right, int target) { + while (left <= right) { + int mid = left + (right - left) / 2; + if (arr[mid] == target) { + return mid; + } else if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + return -1; +} + +int exponential_search(const std::vector& arr, int target) { + if (arr[0] == target) { + return 0; + } + + int n = arr.size(); + int i = 1; + while (i < n && arr[i] <= target) { + i *= 2; + } + + return binary_search(arr, i / 2, std::min(i, n - 1), target); +} + +int main() { + std::vector arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + int target = 6; + std::cout << "Index: " << exponential_search(arr, target) << std::endl; + return 0; +} +``` + + + + +```java + +import java.util.Arrays; + +public class ExponentialSearch { + public static int binarySearch(int[] arr, int left, int right, int target) { + while (left <= right) { + int mid = left + (right - left) / 2; + if (arr[mid] == target) { + return mid; + } else if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + return -1; + } + + public static int exponentialSearch(int[] arr, int target) { + if (arr[0] == target) { + return 0; + } + + int n = arr.length; + int i = 1; + while (i < n && arr[i] <= target) { + i *= 2; + } + + return binarySearch(arr, i / 2, Math.min(i, n - 1), target); + } + + public static void main(String[] args) { + int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + int target = 6; + System.out.println("Index: " + exponentialSearch(arr, target)); + } +} +``` + + + + +```javascript + +function binarySearch(arr, left, right, target) { + while (left <= right) { + let mid = left + Math.floor((right - left) / 2); + if (arr[mid] === target) { + return mid; + } else if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + return -1; +} + +function exponentialSearch(arr, target) { + if (arr[0] === target) { + return 0; + } + + let n = arr.length; + let i = 1; + while (i < n && arr[i] <= target) { + i *= 2; + } + + return binarySearch(arr, Math.floor(i / 2), Math.min(i, n - 1), target); +} + +const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +const target = 6; +console.log("Index:", exponentialSearch(arr, target)); +``` + + + + +# Complexity Analysis +### Time Complexity: $O(\log i)$, where $i$ is the index of the target element. The doubling step takes logarithmic time, and the binary search within the range also takes logarithmic time. +### Space Complexity: $O(1)$, as no extra space is required apart from the input list. +# Advantages and Disadvantages +## Advantages: + +Efficient for searching in sorted arrays, especially when the target element is close to the beginning. + +Combines the benefits of both linear and binary search. +## Disadvantages: + +Requires the list to be sorted. + +Slightly more complex to implement compared to binary search alone. diff --git a/solutions/Searching-Algorithms/Fibonacci-Search.md b/solutions/Searching-Algorithms/Fibonacci-Search.md new file mode 100644 index 0000000..237dace --- /dev/null +++ b/solutions/Searching-Algorithms/Fibonacci-Search.md @@ -0,0 +1,283 @@ +--- +id: Fibonacci-Search +title: Fibonacci Search (Geeks for Geeks) +sidebar_label: Fibonacci Search +tags: + - Intermediate + - Search Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Fibonacci Search algorithm problem." +--- + +## What is Fibonacci Search? + +Fibonacci Search is an efficient search algorithm for sorted arrays. It uses Fibonacci numbers to divide the array into smaller subarrays, reducing the search space at each step. This algorithm is particularly useful when the size of the input array is large. + +## Algorithm for Fibonacci Search + +1. Find the smallest Fibonacci number greater than or equal to the length of the array. +2. Use the Fibonacci number to divide the array into two parts. +3. Compare the target element with the element at the division point. +4. If the target element is equal to the element at the division point, return the index. +5. If the target element is less than the element at the division point, repeat the process for the left subarray. +6. If the target element is greater than the element at the division point, repeat the process for the right subarray. + +## How does Fibonacci Search work? + +- It calculates Fibonacci numbers and uses them to divide the array into smaller subarrays. +- The search process is repeated within the appropriate subarray based on comparisons. +- The algorithm reduces the search space at each step, making the search efficient. + + +## Problem Description + +Given a sorted list and a target element, implement the Fibonacci Search algorithm to find the index of the target element in the list. If the element is not present, return -1. + +## Examples + +**Example 1:** +Input: +list = [10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100] +target = 85 +Output: 8 + +**Example 2:** +Input: +list = [10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100] +target = 55 +Output: -1 + +## Your Task: + +You don't need to read input or print anything. Complete the function fibonacci_search() which takes arr[], N and K as input parameters and returns the index of K in the array. If K is not present in the array, return -1. + +Expected Time Complexity: $O(\log N)$ +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- $1 <= N <= 10^5$ +- $1 <= arr[i] <= 10^6$ +- $1 <= K <= 10^6$ + +## Implementation + + + + +```python +def fibonacci_search(arr, x): + n = len(arr) + fib_mm2 = 0 # (m-2)'th Fibonacci No. + fib_mm1 = 1 # (m-1)'th Fibonacci No. + fib_m = fib_mm1 + fib_mm2 # m'th Fibonacci + + while (fib_m < n): + fib_mm2 = fib_mm1 + fib_mm1 = fib_m + fib_m = fib_mm2 + fib_mm1 + + offset = -1 + + while (fib_m > 1): + i = min(offset + fib_mm2, n - 1) + + if (arr[i] < x): + fib_m = fib_mm1 + fib_mm1 = fib_mm2 + fib_mm2 = fib_m - fib_mm1 + offset = i + elif (arr[i] > x): + fib_m = fib_mm2 + fib_mm1 = fib_mm1 - fib_mm2 + fib_mm2 = fib_m - fib_mm1 + else: + return i + + if (fib_mm1 and arr[offset + 1] == x): + return offset + 1 + + return -1 +``` + + + + +```cpp + +#include +#include +#include + +int fibonacci_search(const std::vector& arr, int x) { + int n = arr.size(); + int fib_mm2 = 0; + int fib_mm1 = 1; + int fib_m = fib_mm2 + fib_mm1; + + while (fib_m < n) { + fib_mm2 = fib_mm1; + fib_mm1 = fib_m; + fib_m = fib_mm2 + fib_mm1; + } + + int offset = -1; + + while (fib_m > 1) { + int i = std::min(offset + fib_mm2, n - 1); + + if (arr[i] < x) { + fib_m = fib_mm1; + fib_mm1 = fib_mm2; + fib_mm2 = fib_m - fib_mm1; + offset = i; + } else if (arr[i] > x) { + fib_m = fib_mm2; + fib_mm1 = fib_mm1 - fib_mm2; + fib_mm2 = fib_m - fib_mm1; + } else { + return i; + } + } + + if (fib_mm1 && arr[offset + 1] == x) { + return offset + 1; + } + + return -1; +} + +int main() { + std::vector arr = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100}; + int target = 85; + std::cout << "Index: " << fibonacci_search(arr, target) << std::endl; + return 0; +} +``` + + + + +```java + +public class FibonacciSearch { + public static int fibonacciSearch(int[] arr, int x) { + int n = arr.length; + int fibMMm2 = 0; // (m-2)'th Fibonacci No. + int fibMMm1 = 1; // (m-1)'th Fibonacci No. + int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci + + while (fibM < n) { + fibMMm2 = fibMMm1; + fibMMm1 = fibM; + fibM = fibMMm2 + fibMMm1; + } + + int offset = -1; + + while (fibM > 1) { + int i = Math.min(offset + fibMMm2, n - 1); + + if (arr[i] < x) { + fibM = fibMMm1; + fibMMm1 = fibMMm2; + fibMMm2 = fibM - fibMMm1; + offset = i; + } else if (arr[i] > x) { + fibM = fibMMm2; + fibMMm1 = fibMMm1 - fibMMm2; + fibMMm2 = fibM - fibMMm1; + } else { + return i; + } + } + + if (fibMMm1 == 1 && arr[offset + 1] == x) { + return offset + 1; + } + + return -1; + } + + public static void main(String[] args) { + int[] arr = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100}; + int target = 85; + System.out.println("Index: " + fibonacciSearch(arr, target)); + } +} +``` + + + + +```javascript + +function fibonacciSearch(arr, x) { + let n = arr.length; + let fibMMm2 = 0; + let fibMMm1 = 1; + let fibM = fibMMm2 + fibMMm1; + + while (fibM < n) { + fibMMm2 = fibMMm1; + fibMMm1 = fibM; + fibM = fibMMm2 + fibMMm1; + } + + let offset = -1; + + while (fibM > 1) { + let i = Math.min(offset + fibMMm2, n - 1); + + if (arr[i] < x) { + fibM = fibMMm1; + fibMMm1 = fibMMm2; + fibMMm2 = fibM - fibMMm1; + offset = i; + } else if (arr[i] > x) { + fibM = fibMMm2; + fibMMm1 = fibMMm1 - fibMMm2; + fibMMm2 = fibM - fibMMm1; + } else { + return i; + } + } + + if (fibMMm1 && arr[offset + 1] == x) { + return offset + 1; + } + + return -1; +} + +const arr = [10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100]; +const target = 85; +console.log("Index:", fibonacciSearch(arr, target)); + +``` + + + + +# Complexity Analysis +## Time Complexity: +$O(\log N)$, where $N$ is the number of elements in the list. The Fibonacci numbers are used to reduce the search space efficiently. +## Space Complexity: +$O(1)$, as no extra space is required apart from the input list. +# Advantages and Disadvantages +## Advantages: + +Efficient for large sorted arrays. + +Reduces the search space efficiently using Fibonacci numbers. + +## Disadvantages: + +Requires the list to be sorted. + +May not be as intuitive as other search algorithms like binary search. diff --git a/solutions/Searching-Algorithms/Fractal-Search.md b/solutions/Searching-Algorithms/Fractal-Search.md new file mode 100644 index 0000000..5613055 --- /dev/null +++ b/solutions/Searching-Algorithms/Fractal-Search.md @@ -0,0 +1,215 @@ +--- +id: Fractal-Search-Algorithm +title: Fractal Search Algorithm +sidebar_label: Fractal Search Algorithm +tags: + - Advanced + - Search Algorithms + - Fractals + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a detailed explanation and implementation of the Fractal Search Algorithm." + +--- + +## What is the Fractal Search Algorithm? + +The Fractal Search Algorithm (FSA) is an advanced search algorithm inspired by the fractal nature of various processes and patterns in nature. It leverages the self-similarity and recursive properties of fractals to efficiently search through complex spaces. + +## Algorithm for Fractal Search + +1. **Initialization**: Define the search space and initialize the fractal pattern. +2. **Recursive Division**: Recursively divide the search space into smaller subspaces following the fractal pattern. +3. **Search Subspaces**: Evaluate the subspaces to find the target element. +4. **Merge Results**: Combine the results from the subspaces to determine the final position of the target element. + +## How does Fractal Search work? + +- FSA divides the search space into self-similar subspaces recursively. +- It searches each subspace individually, combining results to identify the target element. +- This approach reduces the search space significantly, improving efficiency. + + +## Problem Description + +Given a complex search space, implement the Fractal Search Algorithm to find the target element. If the element is not present, the algorithm should indicate that as well. + +## Examples + +**Example 1:** +Input: +search_space = [1, 3, 5, 7, 9] +target = 5 +Output: 2 + +**Example 2:** +Input: +search_space = [2, 4, 6, 8, 10] +target = 7 +Output: -1 + +## Your Task + +Complete the function `fractal_search()` which takes a list `search_space` and an integer `target` as input parameters and returns the index of the target element. If the element is not present, return -1. + +Expected Time Complexity: $O(\log n)$ +Expected Auxiliary Space: $O(n)$ + +## Constraints + +- $1 <= n <= 10^6$ +- $1 <= search_space[i] <= 10^9$ +- $1 <= target <= 10^9$ + +## Implementation + +```python +import numpy as np + +def fractal_search(search_space, target): + def recursive_search(subspace, depth): + if len(subspace) == 0: + return -1 + + mid_index = len(subspace) // 2 + mid_value = subspace[mid_index] + + if mid_value == target: + return mid_index + + if target < mid_value: + return recursive_search(subspace[:mid_index], depth + 1) + else: + result = recursive_search(subspace[mid_index + 1:], depth + 1) + return mid_index + 1 + result if result != -1 else -1 + + return recursive_search(search_space, 0) + +# Example usage: +search_space = [1, 3, 5, 7, 9] +target = 5 +print(fractal_search(search_space, target)) # Output: 2 +``` + +```cpp +#include +#include + +int fractal_search(const std::vector& search_space, int target) { + int recursive_search(const std::vector& subspace, int depth) { + if (subspace.empty()) { + return -1; + } + + int mid_index = subspace.size() / 2; + int mid_value = subspace[mid_index]; + + if (mid_value == target) { + return mid_index; + } + + if (target < mid_value) { + return recursive_search({subspace.begin(), subspace.begin() + mid_index}, depth + 1); + } else { + int result = recursive_search({subspace.begin() + mid_index + 1, subspace.end()}, depth + 1); + return result != -1 ? mid_index + 1 + result : -1; + } + } + + return recursive_search(search_space, 0); +} + +// Example usage: +int main() { + std::vector search_space = {1, 3, 5, 7, 9}; + int target = 5; + std::cout << fractal_search(search_space, target) << std::endl; // Output: 2 + return 0; +} +``` + +```java +import java.util.List; + +public class FractalSearch { + public static int fractalSearch(List search_space, int target) { + int recursiveSearch(List subspace, int depth) { + if (subspace.isEmpty()) { + return -1; + } + + int midIndex = subspace.size() / 2; + int midValue = subspace.get(midIndex); + + if (midValue == target) { + return midIndex; + } + + if (target < midValue) { + return recursiveSearch(subspace.subList(0, midIndex), depth + 1); + } else { + int result = recursiveSearch(subspace.subList(midIndex + 1, subspace.size()), depth + 1); + return result != -1 ? midIndex + 1 + result : -1; + } + } + + return recursiveSearch(search_space, 0); + } + + public static void main(String[] args) { + List search_space = List.of(1, 3, 5, 7, 9); + int target = 5; + System.out.println(fractalSearch(search_space, target)); // Output: 2 + } +} +``` + +```javascript +function fractalSearch(search_space, target) { + function recursiveSearch(subspace, depth) { + if (subspace.length === 0) { + return -1; + } + + const midIndex = Math.floor(subspace.length / 2); + const midValue = subspace[midIndex]; + + if (midValue === target) { + return midIndex; + } + + if (target < midValue) { + return recursiveSearch(subspace.slice(0, midIndex), depth + 1); + } else { + const result = recursiveSearch(subspace.slice(midIndex + 1), depth + 1); + return result !== -1 ? midIndex + 1 + result : -1; + } + } + + return recursiveSearch(search_space, 0); +} + +// Example usage: +const search_space = [1, 3, 5, 7, 9]; +const target = 5; +console.log(fractalSearch(search_space, target)); // Output: 2 +``` + +# Complexity Analysis +### Time Complexity: $O(\log n)$, where $n$ is the number of elements in the search space. The recursive division reduces the search space exponentially. +### Space Complexity: $O(n)$, due to the additional space required for recursive function calls and subspaces. +# Advantages and Disadvantages +## Advantages: + +Efficient for large and complex search spaces due to the recursive division. +Exploits the self-similarity of fractals, making it suitable for certain types of data structures. +## Disadvantages: + +More complex to implement compared to traditional search algorithms. +Performance may vary depending on the nature of the search space and fractal pattern used. +### References +Wikipedia: Fractal +Research Paper: Fractal Search Algorithm diff --git a/solutions/Searching-Algorithms/Heuristic-Search.md b/solutions/Searching-Algorithms/Heuristic-Search.md new file mode 100644 index 0000000..d5a3c74 --- /dev/null +++ b/solutions/Searching-Algorithms/Heuristic-Search.md @@ -0,0 +1,190 @@ +--- +id: Heuristic-Search +title: Heuristic Search +sidebar_label: Heuristic Search +tags: + - Advanced + - Search Algorithms + - Heuristics + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Heuristic Search problem." +--- + +## What is Heuristic Search? + +Heuristic Search is a search algorithm that uses heuristic functions to guide the search process. The heuristic function estimates the cost to reach the goal from a given state, allowing the algorithm to prioritize which paths to explore. This approach is commonly used in AI and optimization problems. + +## Algorithm Steps + +1. **Initialization**: + - Define the heuristic function that estimates the cost to reach the goal. + - Initialize the search from the starting state. + +2. **Search Process**: + - Use a priority queue to manage the states to be explored, prioritizing states with lower heuristic costs. + - At each step, expand the state with the lowest estimated cost. + - If the goal state is reached, return the path or the solution. + +## Complexity Analysis + +- **Time Complexity**: Depends on the heuristic function. In the best case, it can be $O(\log n)$, but in the worst case, it can approach $O(n)$ where $n$ is the number of states. +- **Space Complexity**: $O(n)$ for storing the priority queue and explored states. + + +## Example + +Given a graph representing a map: + +``` +graph = { +'A': [('B', 1), ('C', 3)], +'B': [('D', 5)], +'C': [('D', 2)], +'D': [] +} +start = 'A' + +goal = 'D' +``` + + + +Using Heuristic Search: + +- Define a heuristic function that estimates the distance from each state to the goal. +- Use the heuristic to guide the search from the start state to the goal state. + +## Implementation + + + + +```python +import heapq + +def heuristic(node, goal): + # Example heuristic: distance to goal + heuristics = { + 'A': 4, + 'B': 2, + 'C': 2, + 'D': 0 + } + return heuristics[node] + +def heuristic_search(graph, start, goal): + priority_queue = [(0 + heuristic(start, goal), start)] + explored = set() + + while priority_queue: + cost, current = heapq.heappop(priority_queue) + if current == goal: + return cost + + if current not in explored: + explored.add(current) + for neighbor, weight in graph[current]: + if neighbor not in explored: + total_cost = cost + weight + heapq.heappush(priority_queue, (total_cost + heuristic(neighbor, goal), neighbor)) + + return float('inf') + +# Example usage: +graph = { + 'A': [('B', 1), ('C', 3)], + 'B': [('D', 5)], + 'C': [('D', 2)], + 'D': [] +} +start = 'A' +goal = 'D' + +result = heuristic_search(graph, start, goal) +print(f"Minimum cost from {start} to {goal}: {result}") +``` + + + + +```cpp + +#include +#include +#include +#include +#include + +struct Node { + std::string name; + int cost; + bool operator>(const Node& other) const { + return cost > other.cost; + } +}; + +int heuristic(const std::string& node, const std::string& goal) { + std::unordered_map heuristics = { + {"A", 4}, + {"B", 2}, + {"C", 2}, + {"D", 0} + }; + return heuristics[node]; +} + +int heuristic_search(const std::unordered_map>>& graph, const std::string& start, const std::string& goal) { + std::priority_queue, std::greater> priority_queue; + std::unordered_set explored; + + priority_queue.push({start, heuristic(start, goal)}); + + while (!priority_queue.empty()) { + Node current = priority_queue.top(); + priority_queue.pop(); + + if (current.name == goal) { + return current.cost; + } + + if (explored.find(current.name) == explored.end()) { + explored.insert(current.name); + for (const auto& neighbor : graph.at(current.name)) { + if (explored.find(neighbor.first) == explored.end()) { + int total_cost = current.cost + neighbor.second; + priority_queue.push({neighbor.first, total_cost + heuristic(neighbor.first, goal)}); + } + } + } + } + + return INT_MAX; +} + +int main() { + std::unordered_map>> graph = { + {"A", {{"B", 1}, {"C", 3}}}, + {"B", {{"D", 5}}}, + {"C", {{"D", 2}}}, + {"D", {}} + }; + std::string start = "A"; + std::string goal = "D"; + + int result = heuristic_search(graph, start, goal); + std::cout << "Minimum cost from " << start << " to " << goal << ": " << result << "\n"; + + return 0; +} + +``` + + + + +# Conclusion +The Heuristic Search algorithm efficiently searches for a target state by leveraging heuristic functions to guide the search process. It is widely used in AI, optimization problems, and various applications where informed search strategies are beneficial. diff --git a/solutions/Searching-Algorithms/Hierarchical-Binary-Search.md b/solutions/Searching-Algorithms/Hierarchical-Binary-Search.md new file mode 100644 index 0000000..8d7b2d9 --- /dev/null +++ b/solutions/Searching-Algorithms/Hierarchical-Binary-Search.md @@ -0,0 +1,161 @@ +--- +id: Hierarchical-Binary-Search +title: Hierarchical Binary Search +sidebar_label: Hierarchical Binary Search +tags: + - Advanced + - Search Algorithms + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Hierarchical Binary Search problem." +--- + +## What is Hierarchical Binary Search? + +Hierarchical Binary Search is a search algorithm designed to search for a target element in a large sorted dataset by recursively dividing the dataset into hierarchical levels and applying binary search at each level. This approach can be particularly useful for distributed databases or filesystems where data is naturally partitioned. + +## Algorithm Steps + +1. **Initialization**: + - Start from the top level of the hierarchy. + - Define boundaries for the current level: `left` and `right`. + +2. **Binary Search at Current Level**: + - Apply binary search to the current level. + - If the target is found, return its position. + - If the target is less than the middle element, move to the next lower level on the left side. + - If the target is greater than the middle element, move to the next lower level on the right side. + +3. **Recursive Search**: + - Recursively apply binary search at each level of the hierarchy until the target is found or the search space is exhausted. + +4. **Base Case**: + - If the search space at the current level is exhausted, return -1 indicating the target is not found. + +## Complexity Analysis + +- **Time Complexity**: $O(\log(n))$ where $n$ is the total number of elements in the dataset. This is due to the binary search applied at each hierarchical level. +- **Space Complexity**: $O(\log(n))$ due to the recursive calls on the call stack. + +## Example + +Given a hierarchical dataset: + +level 0: [1, 4, 7, 10] +level 1 (left of 1): [] +level 1 (right of 1): [2, 3] +level 1 (left of 4): [] +level 1 (right of 4): [5, 6] +level 1 (left of 7): [] +level 1 (right of 7): [8, 9] +level 1 (left of 10): [] +level 1 (right of 10): [11, 12] + + +Using Hierarchical Binary Search: + +- Start from the top level: `level 0`. +- Apply binary search at each level, moving to the next lower level based on comparisons with the target. + +## Implementation + + + + +```python +def hierarchical_binary_search(levels, target, level=0, left=0, right=None): + if right is None: + right = len(levels[level]) - 1 + + if left > right: + return -1 + + mid = (left + right) // 2 + if levels[level][mid] == target: + return (level, mid) + elif levels[level][mid] > target: + return hierarchical_binary_search(levels, target, level + 1, left, mid - 1) + else: + return hierarchical_binary_search(levels, target, level + 1, mid + 1, right) + +# Example usage: +levels = [ + [1, 4, 7, 10], + [], + [2, 3], + [], + [5, 6], + [], + [8, 9], + [], + [11, 12] +] +target = 5 + +result = hierarchical_binary_search(levels, target) +if result != -1: + print(f"Target {target} found at position: {result}") +else: + print(f"Target {target} not found in the dataset") +``` + + + + +```cpp + +#include +#include +#include + +std::pair hierarchical_binary_search(std::vector>& levels, int target, int level = 0, int left = 0, int right = -1) { + if (right == -1) { + right = levels[level].size() - 1; + } + + if (left > right) { + return {-1, -1}; + } + + int mid = (left + right) / 2; + if (levels[level][mid] == target) { + return {level, mid}; + } else if (levels[level][mid] > target) { + return hierarchical_binary_search(levels, target, level + 1, left, mid - 1); + } else { + return hierarchical_binary_search(levels, target, level + 1, mid + 1, right); + } +} + +int main() { + std::vector> levels = { + {1, 4, 7, 10}, + {}, + {2, 3}, + {}, + {5, 6}, + {}, + {8, 9}, + {}, + {11, 12} + }; + int target = 5; + + std::pair result = hierarchical_binary_search(levels, target); + if (result.first != -1) { + std::cout << "Target " << target << " found at position: (" << result.first << ", " << result.second << ")\n"; + } else { + std::cout << "Target " << target << " not found in the dataset\n"; + } + return 0; +} +``` + + + + +# Conclusion +The Hierarchical Binary Search algorithm is a unique and efficient way to search for a target element in a large, hierarchically structured dataset. It leverages the divide-and-conquer approach of binary search across multiple levels, making it well-suited for distributed or partitioned data systems. diff --git a/solutions/Searching-Algorithms/Hybrid-Jump-Binary-Search.md b/solutions/Searching-Algorithms/Hybrid-Jump-Binary-Search.md new file mode 100644 index 0000000..029edfb --- /dev/null +++ b/solutions/Searching-Algorithms/Hybrid-Jump-Binary-Search.md @@ -0,0 +1,250 @@ +--- +id: Hybrid-Jump-Binary-Search +title: Hybrid Jump Binary Search (Geeks for Geeks) +sidebar_label: Hybrid Jump Binary Search +tags: + - Advanced + - Search Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Hybrid Jump Binary Search algorithm problem." +--- + +## What is Hybrid Jump Binary Search? + +Hybrid Jump Binary Search is an advanced search algorithm that combines the features of Jump Search and Binary Search. It first uses a jump step to find a block where the target element might be present and then performs a binary search within that block to find the target element. + +## Algorithm for Hybrid Jump Binary Search + +1. Calculate the optimal step size $\sqrt{N}$, where $N$ is the length of the list. +2. Start from the first element and jump ahead by the step size until the target element is greater than or equal to the current element. +3. Once the block where the target might be located is identified, perform a binary search within that block. +4. If the target element is found, return its index. +5. If the target element is not found, return -1. + +## How does Hybrid Jump Binary Search work? + +- It combines jump search and binary search to efficiently locate the target element. +- Jump search quickly narrows down the possible range of the target element. +- Binary search is then used within the identified range to find the target element efficiently. + + +## Problem Description + +Given a sorted list and a target element, implement the Hybrid Jump Binary Search algorithm to find the index of the target element in the list. If the element is not present, return -1. + +## Examples + +**Example 1:** +Input: +list = [10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100] +target = 85 +Output: 8 + +**Example 2:** +Input: +list = [10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100] +target = 55 +Output: -1 + +## Your Task: + +You don't need to read input or print anything. Complete the function hybrid_jump_binary_search() which takes arr[], N and K as input parameters and returns the index of K in the array. If K is not present in the array, return -1. + +Expected Time Complexity: $O(\log N)$ +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- $1 <= N <= 10^5$ +- $1 <= arr[i] <= 10^6$ +- $1 <= K <= 10^6$ + +## Implementation + + + + +```python + +import math + +def binary_search(arr, low, high, x): + while low <= high: + mid = low + (high - low) // 2 + if arr[mid] == x: + return mid + elif arr[mid] < x: + low = mid + 1 + else: + high = mid - 1 + return -1 + +def hybrid_jump_binary_search(arr, x): + n = len(arr) + step = int(math.sqrt(n)) + prev = 0 + + while arr[min(step, n) - 1] < x: + prev = step + step += int(math.sqrt(n)) + if prev >= n: + return -1 + + return binary_search(arr, prev, min(step, n) - 1, x) +``` + + + + +```cpp + +#include +#include +#include + +int binary_search(const std::vector& arr, int low, int high, int x) { + while (low <= high) { + int mid = low + (high - low) / 2; + if (arr[mid] == x) { + return mid; + } else if (arr[mid] < x) { + low = mid + 1; + } else { + high = mid - 1; + } + } + return -1; +} + +int hybrid_jump_binary_search(const std::vector& arr, int x) { + int n = arr.size(); + int step = sqrt(n); + int prev = 0; + + while (arr[std::min(step, n) - 1] < x) { + prev = step; + step += sqrt(n); + if (prev >= n) { + return -1; + } + } + + return binary_search(arr, prev, std::min(step, n) - 1, x); +} + +int main() { + std::vector arr = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100}; + int target = 85; + std::cout << "Index: " << hybrid_jump_binary_search(arr, target) << std::endl; + return 0; +} +``` + + + + +```java + +public class HybridJumpBinarySearch { + public static int binarySearch(int[] arr, int low, int high, int x) { + while (low <= high) { + int mid = low + (high - low) / 2; + if (arr[mid] == x) { + return mid; + } else if (arr[mid] < x) { + low = mid + 1; + } else { + high = mid - 1; + } + } + return -1; + } + + public static int hybridJumpBinarySearch(int[] arr, int x) { + int n = arr.length; + int step = (int) Math.sqrt(n); + int prev = 0; + + while (arr[Math.min(step, n) - 1] < x) { + prev = step; + step += (int) Math.sqrt(n); + if (prev >= n) { + return -1; + } + } + + return binarySearch(arr, prev, Math.min(step, n) - 1, x); + } + + public static void main(String[] args) { + int[] arr = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100}; + int target = 85; + System.out.println("Index: " + hybridJumpBinarySearch(arr, target)); + } +} +``` + + + + +```javascript + +function binarySearch(arr, low, high, x) { + while (low <= high) { + let mid = Math.floor(low + (high - low) / 2); + if (arr[mid] === x) { + return mid; + } else if (arr[mid] < x) { + low = mid + 1; + } else { + high = mid - 1; + } + } + return -1; +} + +function hybridJumpBinarySearch(arr, x) { + let n = arr.length; + let step = Math.floor(Math.sqrt(n)); + let prev = 0; + + while (arr[Math.min(step, n) - 1] < x) { + prev = step; + step += Math.floor(Math.sqrt(n)); + if (prev >= n) { + return -1; + } + } + + return binarySearch(arr, prev, Math.min(step, n) - 1, x); +} + +const arr = [10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100]; +const target = 85; +console.log("Index:", hybridJumpBinarySearch(arr, target)); +``` + + + + +# Complexity Analysis +## Time Complexity: +$O(\log N)$, where $N$ is the number of elements in the list. The combination of jump search and binary search reduces the search space efficiently. +## Space Complexity: +$O(1)$, as no extra space is required apart from the input list. +# Advantages and Disadvantages +## Advantages: + +Efficient for large sorted arrays. + +Combines the advantages of both jump search and binary search. +## Disadvantages: + +Requires the list to be sorted. + +Slightly more complex to implement compared to individual search algorithms. diff --git a/solutions/Searching-Algorithms/Interpolation-Search.md b/solutions/Searching-Algorithms/Interpolation-Search.md new file mode 100644 index 0000000..8c9a81f --- /dev/null +++ b/solutions/Searching-Algorithms/Interpolation-Search.md @@ -0,0 +1,223 @@ +--- +id: Interpolation-Search +title: Interpolation Search (Geeks for Geeks) +sidebar_label: Interpolation Search +tags: + - Intermediate + - Search Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Interpolation Search problem." +--- + +## What is Interpolation Search? + +Interpolation Search is an efficient search algorithm for uniformly distributed sorted arrays. It works by estimating the position of the target value based on the value's distribution, making it faster than linear search and in some cases more efficient than binary search. + +## Algorithm for Interpolation Search + +1. Initialize the low and high indices to 0 and N-1, respectively. +2. While the target value is within the range defined by the current low and high indices: + - Calculate the probe position using the formula: + $$ + \text{pos} = \text{low} + \left( \frac{(x - \text{arr}[low]) \times (\text{high} - \text{low})}{\text{arr}[high] - \text{arr}[low]} \right) + $$ +3. Check the value at the probe position: + - If `arr[pos]` is equal to the target value, return `pos`. + - If `arr[pos]` is less than the target value, update `low` to `pos + 1`. + - If `arr[pos]` is greater than the target value, update `high` to `pos - 1`. +4. If the target value is not found, return -1. + +## How does Interpolation Search work? + +- It calculates a probe position using a formula that considers the distribution of values within the array. +- The probe position is used to narrow down the search range, making the search process more efficient compared to a linear search. + +## Problem Description + +Given a sorted list and a target element, implement the Interpolation Search algorithm to find the index of the target element in the list. If the element is not present, return -1. + +## Examples + +**Example 1:** +Input: +list = [10, 12, 13, 16, 18, 19, 20, 21, 22, 23] +target = 18 +Output: 4 + + +**Example 2:** +Input: +list = [10, 12, 13, 16, 18, 19, 20, 21, 22, 23] +target = 25 +Output: -1 + + +## Your Task: + +You don't need to read input or print anything. Complete the function interpolation_search() which takes arr[], N and K as input parameters and returns the index of K in the array. If K is not present in the array, return -1. + +Expected Time Complexity: $O(\log \log N)$ +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- $1 <= N <= 10^5$ +- $1 <= arr[i] <= 10^6$ +- $1 <= K <= 10^6$ + +## Implementation + + + + +```python + +def interpolation_search(arr, n, x): + low = 0 + high = n - 1 + + while low <= high and x >= arr[low] and x <= arr[high]: + if low == high: + if arr[low] == x: + return low + return -1 + + pos = low + ((x - arr[low]) * (high - low) // (arr[high] - arr[low])) + + if arr[pos] == x: + return pos + if arr[pos] < x: + low = pos + 1 + else: + high = pos - 1 + return -1 +``` + + + +```cpp + +#include +#include + +int interpolation_search(const std::vector& arr, int n, int x) { + int low = 0, high = n - 1; + + while (low <= high && x >= arr[low] && x <= arr[high]) { + if (low == high) { + if (arr[low] == x) return low; + return -1; + } + + int pos = low + ((x - arr[low]) * (high - low) / (arr[high] - arr[low])); + + if (arr[pos] == x) + return pos; + if (arr[pos] < x) + low = pos + 1; + else + high = pos - 1; + } + return -1; +} + +int main() { + std::vector arr = {10, 12, 13, 16, 18, 19, 20, 21, 22, 23}; + int target = 18; + std::cout << "Index: " << interpolation_search(arr, arr.size(), target) << std::endl; + return 0; +} +``` + + + + +```java + +public class InterpolationSearch { + public static int interpolationSearch(int[] arr, int n, int x) { + int low = 0, high = n - 1; + + while (low <= high && x >= arr[low] && x <= arr[high]) { + if (low == high) { + if (arr[low] == x) return low; + return -1; + } + + int pos = low + ((x - arr[low]) * (high - low) / (arr[high] - arr[low])); + + if (arr[pos] == x) + return pos; + if (arr[pos] < x) + low = pos + 1; + else + high = pos - 1; + } + return -1; + } + + public static void main(String[] args) { + int[] arr = {10, 12, 13, 16, 18, 19, 20, 21, 22, 23}; + int target = 18; + System.out.println("Index: " + interpolationSearch(arr, arr.length, target)); + } +} +``` + + + + +```javascript + +function interpolationSearch(arr, n, x) { + let low = 0, high = n - 1; + + while (low <= high && x >= arr[low] && x <= arr[high]) { + if (low === high) { + if (arr[low] === x) return low; + return -1; + } + + let pos = low + Math.floor(((x - arr[low]) * (high - low) / (arr[high] - arr[low]))); + + if (arr[pos] === x) + return pos; + if (arr[pos] < x) + low = pos + 1; + else + high = pos - 1; + } + return -1; +} + +const arr = [10, 12, 13, 16, 18, 19, 20, 21, 22, 23]; +const target = 18; +console.log("Index:", interpolationSearch(arr, arr.length, target)); +``` + + + + +# Complexity Analysis +## Time Complexity: +$O(\log \log n)$ for uniformly distributed data, where $n$ is the number of elements in the list. +## Space Complexity: +$O(1)$, as no extra space is required apart from the input list. + +# Advantages and Disadvantages +## Advantages: + +Faster than linear search and binary search for uniformly distributed sorted lists. + +Efficient for large datasets. + +## Disadvantages: + +Requires the list to be sorted. + +Performance degrades if the distribution of elements is not uniform. diff --git a/solutions/Searching-Algorithms/Inverted-Index-Search.md b/solutions/Searching-Algorithms/Inverted-Index-Search.md new file mode 100644 index 0000000..b67ceaa --- /dev/null +++ b/solutions/Searching-Algorithms/Inverted-Index-Search.md @@ -0,0 +1,124 @@ +--- +id: Inverted-Index-Search +title: Inverted Index Search +sidebar_label: Inverted Index Search +tags: + - Advanced + - Search Algorithms + - Information Retrieval + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Inverted Index Search problem." +--- + +## What is Inverted Index Search? + +Inverted Index Search is an advanced search algorithm used primarily in information retrieval systems. It involves creating an inverted index, which maps each unique element (or keyword) to the list of positions (or documents) in which it appears. This allows for efficient searches and is widely used in search engines and document retrieval systems. + +## Algorithm Steps + +1. **Inverted Index Creation**: + - Iterate through the dataset and create a mapping of each unique element to its positions. + +2. **Search Using Inverted Index**: + - Query the inverted index to quickly retrieve the positions of the target element. + +## Complexity Analysis + +- **Time Complexity**: + - Inverted Index Creation: $O(n)$ where $n$ is the total number of elements in the dataset. + - Search Using Inverted Index: $O(1)$ average case for retrieving the list of positions of the target element. + +- **Space Complexity**: $O(n)$ for storing the inverted index. + +## Example + +Given a dataset: + +dataset = [3, 5, 7, 3, 9, 1, 5, 7] +target = 5 + + +Using Inverted Index Search: + +- Create an inverted index: `{3: [0, 3], 5: [1, 6], 7: [2, 7], 9: [4], 1: [5]}` +- Search for `5` in the inverted index to retrieve positions `[1, 6]`. + +## Implementation + + + + +```python +def create_inverted_index(dataset): + inverted_index = {} + for idx, value in enumerate(dataset): + if value in inverted_index: + inverted_index[value].append(idx) + else: + inverted_index[value] = [idx] + return inverted_index + +def inverted_index_search(inverted_index, target): + return inverted_index.get(target, []) + +# Example usage: +dataset = [3, 5, 7, 3, 9, 1, 5, 7] +target = 5 + +inverted_index = create_inverted_index(dataset) +result = inverted_index_search(inverted_index, target) +print(f"Target {target} found at positions: {result}") +``` + + + + +```cpp + +#include +#include +#include + +std::unordered_map> create_inverted_index(const std::vector& dataset) { + std::unordered_map> inverted_index; + for (int i = 0; i < dataset.size(); ++i) { + inverted_index[dataset[i]].push_back(i); + } + return inverted_index; +} + +std::vector inverted_index_search(const std::unordered_map>& inverted_index, int target) { + auto it = inverted_index.find(target); + if (it != inverted_index.end()) { + return it->second; + } else { + return {}; + } +} + +int main() { + std::vector dataset = {3, 5, 7, 3, 9, 1, 5, 7}; + int target = 5; + + std::unordered_map> inverted_index = create_inverted_index(dataset); + std::vector result = inverted_index_search(inverted_index, target); + + std::cout << "Target " << target << " found at positions: "; + for (int pos : result) { + std::cout << pos << " "; + } + std::cout << "\n"; + + return 0; +} +``` + + + + +# Conclusion +The Inverted Index Search algorithm is a powerful and efficient way to search for elements in a dataset, especially when dealing with large datasets and frequent queries. It is widely used in search engines and information retrieval systems to quickly locate documents containing specific keywords. diff --git a/solutions/Searching-Algorithms/Jump-Search.md b/solutions/Searching-Algorithms/Jump-Search.md new file mode 100644 index 0000000..444b941 --- /dev/null +++ b/solutions/Searching-Algorithms/Jump-Search.md @@ -0,0 +1,212 @@ +--- +id: Jump-Search +title: Jump Search (Geeks for Geeks) +sidebar_label: Jump Search +tags: + - Intermediate + - Search Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Jump Search problem." +--- + +## What is Jump Search? + +Jump Search is an efficient search algorithm for sorted arrays. It works by jumping ahead by fixed steps and then performing a linear search within a block, making it faster than linear search but less complex than binary search. + +## Algorithm for Jump Search + +1. Calculate the optimal step size $\sqrt{N}$, where $N$ is the length of the list. +2. Start from the first element and jump ahead by the step size until the target element is greater than or equal to the current element. +3. Perform a linear search within the identified block. +4. If the target element is found, return its index. +5. If the target element is not found, return -1. + +## How does Jump Search work? + +- It calculates a jump step based on the length of the list. +- It jumps ahead in blocks, comparing the target value with the current element at each step. +- Once the block where the target might be located is identified, a linear search within the block is performed. + +![Example for Jump Search](../../assets/Jump_Search.jpg) + +## Problem Description + +Given a sorted list and a target element, implement the Jump Search algorithm to find the index of the target element in the list. If the element is not present, return -1. + +## Examples + +**Example 1:** +Input: +list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +target = 6 +Output: 6 + + +**Example 2:** +Input: +list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +target = 15 +Output: -1 + + +## Your Task: + +You don't need to read input or print anything. Complete the function jump_search() which takes arr[], N and K as input parameters and returns the index of K in the array. If K is not present in the array, return -1. + +Expected Time Complexity: $O(\sqrt{N})$ +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- $1 <= N <= 10^5$ +- $1 <= arr[i] <= 10^6$ +- $1 <= K <= 10^6$ + +## Implementation + + + + +```python + import math + + def jump_search(lst, target): + length = len(lst) + step = int(math.sqrt(length)) + prev = 0 + + while lst[min(step, length) - 1] < target: + prev = step + step += int(math.sqrt(length)) + if prev >= length: + return -1 + + for i in range(prev, min(step, length)): + if lst[i] == target: + return i + return -1 + ``` + + + + ```cpp + #include + #include + #include +int jump_search(const std::vector& lst, int target) { +int length = lst.size(); +int step = sqrt(length); +int prev = 0; + while (lst[std::min(step, length) - 1] < target) { + prev = step; + step += sqrt(length); + if (prev >= length) { + return -1; + } + } + + for (int i = prev; i < std::min(step, length); ++i) { + if (lst[i] == target) { + return i; + } + } + return -1; +} + +int main() { +std::vector lst = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; +int target = 6; +std::cout << "Index: " << jump_search(lst, target) << std::endl; +return 0; +} + +``` + + + + +```java +import java.util.Arrays; + +public class JumpSearch { + public static int jumpSearch(int[] lst, int target) { + int length = lst.length; + int step = (int) Math.sqrt(length); + int prev = 0; + + while (lst[Math.min(step, length) - 1] < target) { + prev = step; + step += (int) Math.sqrt(length); + if (prev >= length) { + return -1; + } + } + + for (int i = prev; i < Math.min(step, length); i++) { + if (lst[i] == target) { + return i; + } + } + return -1; + } + + public static void main(String[] args) { + int[] lst = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + int target = 6; + System.out.println("Index: " + jumpSearch(lst, target)); + } +} + +``` + + + + + ```javascript + function jumpSearch(lst, target) { + let length = lst.length; + let step = Math.floor(Math.sqrt(length)); + let prev = 0; + while (lst[Math.min(step, length) - 1] < target) { + prev = step; + step += Math.floor(Math.sqrt(length)); + if (prev >= length) { + return -1; + } + } + + for (let i = prev; i < Math.min(step, length); i++) { + if (lst[i] === target) { + return i; + } + } + return -1; +} + +const lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; +const target = 6; +console.log("Index:", jumpSearch(lst, target)); +``` + + + + +## Complexity Analysis + +- **Time Complexity**: $O(\sqrt{n})$, where $n$ is the number of elements in the list. The list is divided into blocks, leading to a root-time complexity. +- **Space Complexity**: $O(1)$, as no extra space is required apart from the input list. + +## Advantages and Disadvantages + +**Advantages:** +- Faster than linear search for large sorted lists. +- Simpler than binary search while still being efficient. + +**Disadvantages:** +- Requires the list to be sorted. +- Less efficient compared to binary search in terms of time complexity. diff --git a/solutions/Searching-Algorithms/Pattern-Matching-with-Wildcards.md b/solutions/Searching-Algorithms/Pattern-Matching-with-Wildcards.md new file mode 100644 index 0000000..3c014fc --- /dev/null +++ b/solutions/Searching-Algorithms/Pattern-Matching-with-Wildcards.md @@ -0,0 +1,147 @@ +--- +id: Pattern-Matching-Wildcards +title: Pattern Matching with Wildcards +sidebar_label: Pattern Matching with Wildcards +tags: + - Advanced + - Search Algorithms + - Pattern Matching + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Pattern Matching with Wildcards problem." +--- + +## What is Pattern Matching with Wildcards? + +Pattern Matching with Wildcards is an advanced search algorithm that extends traditional pattern matching by allowing wildcard characters ('*') to represent any sequence of characters (including empty sequence) during the search process. This approach is useful for flexible and efficient text searching in various applications. + +## Algorithm Steps + +1. **Initialization**: + - Prepare the pattern with wildcards and the text to search within. + +2. **Pattern Matching**: + - Iterate through the pattern and text character by character. + - Handle wildcard characters ('*') to match any sequence of characters or positions. + +3. **Matching Strategy**: + - Use dynamic programming or a recursive approach to efficiently handle wildcard expansion and pattern matching. + +## Complexity Analysis + +- **Time Complexity**: Depends on the specific implementation. It can range from $O(m \times n) )$ to $ O(m + n) $, where $m$ is the length of the pattern and $n$ is the length of the text. +- **Space Complexity**: $O(m \times n) )$ in worst cases due to the potential recursion depth or dynamic programming table. + +## Example + +Given a pattern with wildcards and a text: + +``` + +pattern = "acd" +text = "abcd" + +``` + +Using Pattern Matching with Wildcards: + +- Match the pattern against the text, considering '*' as a wildcard that matches any sequence of characters. + +## Implementation + + + + +```python +def pattern_matching_with_wildcards(pattern, text): + # Dynamic programming approach + m, n = len(pattern), len(text) + dp = [[False] * (n + 1) for _ in range(m + 1)] + dp[0][0] = True + + # Handle initial wildcard characters + for i in range(1, m + 1): + if pattern[i - 1] == '*': + dp[i][0] = dp[i - 1][0] + + # Fill dp table + for i in range(1, m + 1): + for j in range(1, n + 1): + if pattern[i - 1] == '*': + dp[i][j] = dp[i - 1][j] or dp[i][j - 1] + elif pattern[i - 1] == '?' or pattern[i - 1] == text[j - 1]: + dp[i][j] = dp[i - 1][j - 1] + + return dp[m][n] + +# Example usage: +pattern = "a*c*d" +text = "abcd" + +if pattern_matching_with_wildcards(pattern, text): + print(f"Pattern '{pattern}' matches text '{text}'") +else: + print(f"Pattern '{pattern}' does not match text '{text}'") +``` + + + + +```cpp + +#include +#include +#include + +bool pattern_matching_with_wildcards(const std::string& pattern, const std::string& text) { + int m = pattern.size(); + int n = text.size(); + + std::vector> dp(m + 1, std::vector(n + 1, false)); + dp[0][0] = true; + + // Handle initial wildcard characters + for (int i = 1; i <= m; ++i) { + if (pattern[i - 1] == '*') { + dp[i][0] = dp[i - 1][0]; + } + } + + // Fill dp table + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (pattern[i - 1] == '*') { + dp[i][j] = dp[i - 1][j] || dp[i][j - 1]; + } else if (pattern[i - 1] == '?' || pattern[i - 1] == text[j - 1]) { + dp[i][j] = dp[i - 1][j - 1]; + } + } + } + + return dp[m][n]; +} + +int main() { + std::string pattern = "a*c*d"; + std::string text = "abcd"; + + if (pattern_matching_with_wildcards(pattern, text)) { + std::cout << "Pattern '" << pattern << "' matches text '" << text << "'\n"; + } else { + std::cout << "Pattern '" << pattern << "' does not match text '" << text << "'\n"; + } + + return 0; +} + +``` + + + + +# Conclusion +Pattern Matching with Wildcards is a versatile algorithm that allows for flexible matching of patterns containing wildcard characters ('*') against text sequences. It is useful in various applications such as text processing, file search utilities, and more where flexible and efficient pattern matching is required. + diff --git a/solutions/Searching-Algorithms/Quantum-Walk-Search.md b/solutions/Searching-Algorithms/Quantum-Walk-Search.md new file mode 100644 index 0000000..2cf3ec2 --- /dev/null +++ b/solutions/Searching-Algorithms/Quantum-Walk-Search.md @@ -0,0 +1,148 @@ +--- +id: Quantum-Walk-Search +title: Quantum Walk Search +sidebar_label: Quantum Walk Search +tags: + - Advanced + - Search Algorithms + - Quantum Computing + - CPP + - Python +description: "This is a solution to the Quantum Walk Search problem." + +--- + +## What is Quantum Walk Search? + +Quantum Walk Search is a search algorithm that leverages quantum computing principles, specifically quantum walks, to search through an unstructured database or graph more efficiently than classical algorithms. Quantum walks are the quantum analog of classical random walks and can achieve quadratic speedup in search tasks. + +## Algorithm for Quantum Walk Search + +1. **Initialization**: Initialize the quantum state representing the search space. +2. **Quantum Walk Operator**: Apply the quantum walk operator that evolves the quantum state according to the structure of the search space. +3. **Marking**: Mark the target states by applying a phase shift to the target elements. +4. **Amplitude Amplification**: Use amplitude amplification to increase the probability of measuring the target state. +5. **Measurement**: Measure the quantum state to obtain the target element with high probability. + +## How does Quantum Walk Search work? + +- Quantum Walk Search utilizes the principles of superposition and interference to explore the search space efficiently. +- The quantum walk operator spreads the probability amplitude over the search space, while the marking and amplitude amplification steps increase the probability of finding the target element. + + +## Problem Description + +Given an unstructured database or graph, implement the Quantum Walk Search algorithm to find the target element. If the element is not present, the algorithm should indicate that as well. + +## Examples + +**Example 1:** +Input: +database = [1, 3, 5, 7, 9] +target = 5 +Output: 2 + +**Example 2:** +Input: +database = [2, 4, 6, 8, 10] +target = 7 +Output: -1 + +## Your Task + +Complete the function `quantum_walk_search()` which takes a list `database` and an integer `target` as input parameters and returns the index of the target element. If the element is not present, return -1. + +Expected Time Complexity: $O(\sqrt{n})$ +Expected Auxiliary Space: $O(n)$ + +## Constraints + +- $1 <= n <= 10^5$ +- $1 <= database[i] <= 10^6$ +- $1 <= target <= 10^6$ + +## Implementation + + + + +```python +import numpy as np + +def quantum_walk_search(database, target): + n = len(database) + steps = int(np.sqrt(n)) + + # Initialize quantum state + state = np.zeros(n) + state.fill(1 / np.sqrt(n)) + + # Quantum walk operator + for step in range(steps): + for i in range(n): + if database[i] == target: + state[i] *= -1 + + # Amplitude amplification + for i in range(n): + state[i] *= -1 + state.fill(2 / n * np.sum(state)) + + # Measurement + probabilities = state ** 2 + index = np.argmax(probabilities) + return index if database[index] == target else -1 + +# Example usage: +database = [1, 3, 5, 7, 9] +target = 5 +print(quantum_walk_search(database, target)) # Output: 2 +``` + + + + +```cpp +#include +#include +#include +#include + +int quantum_walk_search(std::vector& database, int target) { + int n = database.size(); + int steps = static_cast(std::sqrt(n)); + + // Initialize quantum state + std::vector state(n, 1.0 / std::sqrt(n)); + + // Quantum walk operator + for (int step = 0; step < steps; ++step) { + for (int i = 0; i < n; ++i) { + if (database[i] == target) { + state[i] *= -1; + } + } + } + + // Amplitude amplification + double sum = std::accumulate(state.begin(), state.end(), 0.0); + for (int i = 0; i < n; ++i) { + state[i] = (2.0 / n) * sum - state[i]; + } + + // Measurement + auto max_it = std::max_element(state.begin(), state.end()); + int index = std::distance(state.begin(), max_it); + return (database[index] == target) ? index : -1; +} + +int main() { + std::vector database = {1, 3, 5, 7, 9}; + int target = 5; + std::cout << quantum_walk_search(database, target) << std::endl; // Output: 2 + return 0; +} +``` + + + diff --git a/solutions/Searching-Algorithms/Quantum-Wave-Search.md b/solutions/Searching-Algorithms/Quantum-Wave-Search.md new file mode 100644 index 0000000..326cc5b --- /dev/null +++ b/solutions/Searching-Algorithms/Quantum-Wave-Search.md @@ -0,0 +1,183 @@ +--- +id: Quantum-Wave-Search +title: Quantum Wave Search +sidebar_label: Quantum Wave Search +tags: + - Advanced + - Search Algorithms + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Quantum Wave Search problem." +--- + +## What is Quantum Wave Search? + +Quantum Wave Search is an advanced search algorithm inspired by quantum computing principles. It leverages the concept of quantum superposition and wave interference to efficiently search an unsorted list. + +## Algorithm for Quantum Wave Search + +1. Initialize the system in a superposition of all possible states. +2. Apply a sequence of quantum gates to evolve the state of the system. +3. Measure the state of the system, collapsing the superposition to a specific state. +4. If the target element is found, return the index; otherwise, repeat the process. + +## How does Quantum Wave Search work? + +- It uses quantum superposition to represent all possible states simultaneously. +- Quantum gates manipulate the superposition state. +- Measurement collapses the superposition to a single state, potentially revealing the target element. + +## Problem Description + +Given a list and a target element, implement the Quantum Wave Search algorithm to find the index of the target element in the list. If the element is not present, return -1. + +## Examples + +**Example 1:** +Input: +list = [1, 3, 5, 7, 9, 11, 13, 15] +target = 7 +Output: 3 + +**Example 2:** +Input: +list = [2, 4, 6, 8, 10, 12, 14, 16] +target = 5 +Output: -1 + +## Your task + +Complete the function quantum_wave_search() which takes two integers n , k and an array arr, as input parameters and returns an integer denoting the answer. Return -1 if the number is not found in the array. You don't have to print answers or take inputs. + +Expected Time Complexity: $O(\sqrt{n})$ +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- $1 <= n <= 10^6$ +- $1 <= k <= 10^6$ +- $1 <= arr[i] <= 10^9$ + +## Implementation + + + + +```python + import random + + def quantum_wave_search(lst, target): + n = len(lst) + for _ in range(int(n ** 0.5)): + index = random.randint(0, n - 1) + if lst[index] == target: + return index + return -1 +``` + + + + + +```cpp + #include + #include + #include + #include + #include + + int quantum_wave_search(const std::vector& lst, int target) { + int n = lst.size(); + std::srand(std::time(0)); + for (int i = 0; i < std::sqrt(n); i++) { + int index = std::rand() % n; + if (lst[index] == target) { + return index; + } + } + return -1; + } + + int main() { + std::vector lst = {1, 3, 5, 7, 9, 11, 13, 15}; + int target = 7; + std::cout << "Index: " << quantum_wave_search(lst, target) << std::endl; + return 0; + } +``` + + + + + +```java + import java.util.Random; + + public class QuantumWaveSearch { + public static int quantumWaveSearch(int[] lst, int target) { + int n = lst.length; + Random rand = new Random(); + for (int i = 0; i < Math.sqrt(n); i++) { + int index = rand.nextInt(n); + if (lst[index] == target) { + return index; + } + } + return -1; + } + + public static void main(String[] args) { + int[] lst = {1, 3, 5, 7, 9, 11, 13, 15}; + int target = 7; + System.out.println("Index: " + quantumWaveSearch(lst, target)); + } + } +``` + + + + + +```javascript + function quantumWaveSearch(lst, target) { + let n = lst.length; + for (let i = 0; i < Math.sqrt(n); i++) { + let index = Math.floor(Math.random() * n); + if (lst[index] === target) { + return index; + } + } + return -1; + } + + const lst = [1, 3, 5, 7, 9, 11, 13, 15]; + const target = 7; + console.log("Index:", quantumWaveSearch(lst, target)); +``` + + + + +## Complexity Analysis + +- **Time Complexity**: $O(\sqrt{n})$, where $n$ is the number of elements in the list. Quantum Wave Search leverages the principles of quantum mechanics to achieve sublinear time complexity. +- **Space Complexity**: $O(1)$, as no extra space is required apart from the input list. + +## Advantages and Disadvantages + +**Advantages:** +- Utilizes quantum principles for efficient search. +- Sublinear time complexity. + +**Disadvantages:** +- Requires quantum computing concepts. +- Performance is probabilistic and may require multiple iterations. + +## References + +- **Quantum Computing:** [Quantum Computing](https://en.wikipedia.org/wiki/Quantum_computing) +- **Geeks for Geeks:** [Quantum Search](https://www.geeksforgeeks.org/quantum-search/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/quantum-wave-search/problem) diff --git a/solutions/Searching-Algorithms/Recursive-Matrix-Search.md b/solutions/Searching-Algorithms/Recursive-Matrix-Search.md new file mode 100644 index 0000000..ce32590 --- /dev/null +++ b/solutions/Searching-Algorithms/Recursive-Matrix-Search.md @@ -0,0 +1,96 @@ +# Recursive Matrix Search Algorithm + +## Overview + +Recursive Matrix Search is an algorithm designed to search for a target element in a 2D matrix. It uses a recursive approach to divide and conquer the search space, similar to binary search but applied in a matrix context. + +## Algorithm Steps + +1. **Initialization**: + - Start from the top-left corner of the matrix. + - Define boundaries: `left`, `right`, `top`, and `bottom`. + +2. **Recursive Search**: + - Divide the matrix into sub-matrices recursively. + - Compare the middle element of the current sub-matrix with the target. + - If the middle element matches the target, return its coordinates. + - If the target is less than the middle element, search the sub-matrix to the left or above recursively. + - If the target is greater than the middle element, search the sub-matrix to the right or below recursively. + +3. **Base Case**: + - If the boundaries (`left`, `right`, `top`, `bottom`) converge or cross over (indicating no more search space), terminate the recursion. + +4. **Complexity**: + - Time Complexity: \( O(\log(n)) \) in the average case, where \( n \) is the total number of elements in the matrix. This is achieved due to the divide-and-conquer nature of the search. + - Space Complexity: \( O(\log(n)) \) due to the recursive calls on the call stack. + +## Example + +Given a 2D matrix: + +matrix = [ +[1, 4, 7, 11, 15], +[2, 5, 8, 12, 19], +[3, 6, 9, 16, 22], +[10, 13, 14, 17, 24], +[18, 21, 23, 26, 30] +] + +target = 14 + +Using Recursive Matrix Search: + +- Start from the top-left corner: `matrix[0][0]`. +- Check against the target `14`. +- Recursive steps narrow down the search until the target is found or deemed absent. + +## Implementation Note + +The algorithm can be implemented in various programming languages using a recursive function that navigates through the matrix based on comparisons with the target element. + +```python +def recursive_matrix_search(matrix, target, left, right, top, bottom): + if left > right or top > bottom: + return None + + mid_row = (top + bottom) // 2 + mid_col = (left + right) // 2 + + mid_element = matrix[mid_row][mid_col] + if mid_element == target: + return (mid_row, mid_col) + elif mid_element > target: + # Search in top-left and bottom sub-matrices + result = recursive_matrix_search(matrix, target, left, mid_col-1, top, bottom) + if result is None: + result = recursive_matrix_search(matrix, target, left, right, top, mid_row-1) + return result + else: + # Search in top-right and bottom sub-matrices + result = recursive_matrix_search(matrix, target, mid_col+1, right, top, bottom) + if result is None: + result = recursive_matrix_search(matrix, target, left, right, mid_row+1, bottom) + return result +``` + +# Example usage: +matrix = [ + [1, 4, 7, 11, 15], + [2, 5, 8, 12, 19], + [3, 6, 9, 16, 22], + [10, 13, 14, 17, 24], + [18, 21, 23, 26, 30] +] +target = 14 + +# Initial search starts from top-left corner (0, 0) to (4, 4) +``` +result = recursive_matrix_search(matrix, target, 0, len(matrix[0])-1, 0, len(matrix)-1) +if result: + print(f"Target {target} found at position: {result}") +else: + print(f"Target {target} not found in the matrix") + +``` + +This algorithm uniquely combines the concepts of binary search with matrix traversal using recursion, offering efficient search capabilities in 2D matrices. diff --git a/solutions/Searching-Algorithms/Skip-List-Search.md b/solutions/Searching-Algorithms/Skip-List-Search.md new file mode 100644 index 0000000..e2d52db --- /dev/null +++ b/solutions/Searching-Algorithms/Skip-List-Search.md @@ -0,0 +1,247 @@ +--- +id: Skip-List-Search +title: Skip List Search +sidebar_label: Skip List Search +tags: + - Advanced + - Search Algorithms + - Data Structures + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Skip List Search problem." + +--- + +## What is Skip List Search? + +Skip List Search is an advanced search algorithm that combines elements of linked lists and binary search trees to efficiently search through sorted data. Skip Lists use multiple levels of linked lists with increasingly sparse elements, allowing for fast search, insertion, and deletion operations. + +## Algorithm for Skip List Search + +1. **Start at the top level**: Begin the search at the highest level of the skip list. +2. **Traverse horizontally**: Move forward until the next element is greater than or equal to the target. +3. **Move down a level**: If the target is not found, move down to the next level and repeat the horizontal traversal. +4. **Repeat**: Continue the process until the lowest level is reached. +5. **Check for the target**: If the target is found at any level, return its position. If the target is not found after reaching the lowest level, return -1. + +## How does Skip List Search work? + +- Skip Lists are constructed with multiple layers where each layer is a subset of the layer below it. +- The top layer is the sparsest, while the bottom layer contains all the elements. +- Searching starts from the top layer and progresses horizontally and vertically, narrowing down the search range efficiently. + +## Problem Description + +Given a skip list and a target element, implement the Skip List Search algorithm to find the position of the target element. If the element is not present, return -1. + +## Examples + +**Example 1:** +Input: +skip_list = [[1, 3, 5, 7, 9], [1, 3, 7], [1]] +target = 5 +Output: 2 + +**Example 2:** +Input: +skip_list = [[2, 4, 6, 8, 10], [2, 6], [2]] +target = 7 +Output: -1 + +## Your Task + +Complete the function `skip_list_search()` which takes a 2D array `skip_list` and an integer `target` as input parameters and returns the index of the target element. If the element is not present, return -1. + +Expected Time Complexity: $O(\log n)$ +Expected Auxiliary Space: $O(n)$ + +## Constraints + +- $1 <= n <= 10^5$ +- $1 <= skip_list[i] <= 10^6$ +- $1 <= target <= 10^6$ + +## Implementation + + + + +```python +class Node: + def __init__(self, value=None, right=None, down=None): + self.value = value + self.right = right + self.down = down + +class SkipList: + def __init__(self): + self.head = Node() + + def search(self, target): + current = self.head + while current: + while current.right and current.right.value < target: + current = current.right + if current.right and current.right.value == target: + return True + current = current.down + return False + +# Example usage: +skip_list = SkipList() +# Add elements to skip_list... +print(skip_list.search(5)) # Output: True or False +``` + + + + +```cpp +#include +#include + +struct Node { + int value; + Node* right; + Node* down; + Node(int val) : value(val), right(nullptr), down(nullptr) {} +}; + +class SkipList { +public: + SkipList() { + head = new Node(-1); + } + + bool search(int target) { + Node* current = head; + while (current) { + while (current->right && current->right->value < target) { + current = current->right; + } + if (current->right && current->right->value == target) { + return true; + } + current = current->down; + } + return false; + } + +private: + Node* head; +}; + +// Example usage: +int main() { + SkipList skip_list; + // Add elements to skip_list... + std::cout << skip_list.search(5) << std::endl; // Output: 1 or 0 + return 0; +} +``` + + + + +```java +class Node { + int value; + Node right, down; + Node(int val) { + value = val; + right = down = null; + } +} + +class SkipList { + private Node head; + + public SkipList() { + head = new Node(-1); + } + + public boolean search(int target) { + Node current = head; + while (current != null) { + while (current.right != null && current.right.value < target) { + current = current.right; + } + if (current.right != null && current.right.value == target) { + return true; + } + current = current.down; + } + return false; + } + + public static void main(String[] args) { + SkipList skipList = new SkipList(); + // Add elements to skipList... + System.out.println(skipList.search(5)); // Output: true or false + } +} +``` + + + + +```javascript +class Node { + constructor(value = null, right = null, down = null) { + this.value = value; + this.right = right; + this.down = down; + } +} + +class SkipList { + constructor() { + this.head = new Node(); + } + + search(target) { + let current = this.head; + while (current) { + while (current.right && current.right.value < target) { + current = current.right; + } + if (current.right && current.right.value === target) { + return true; + } + current = current.down; + } + return false; + } +} + +// Example usage: +const skipList = new SkipList(); +// Add elements to skipList... +console.log(skipList.search(5)); // Output: true or false +``` + + + + +# Complexity Analysis +### Time Complexity: $O(\log n)$, where $n$ is the number of elements in the list. Skip List Search provides a logarithmic time complexity by reducing the number of elements to check at each level. +### Space Complexity: $O(n)$, as it requires additional space to store the multiple levels of linked lists. +# Advantages and Disadvantages +## Advantages: + +Faster search times compared to linear search. + +Easier to implement and maintain compared to balanced trees like AVL or Red-Black trees. + +Allows for efficient insertion and deletion operations. +## Disadvantages: + +Requires extra space to maintain the skip list levels. + +Performance can degrade if the levels are not well-balanced. +References +Wikipedia: Skip List +Geeks for Geeks: Skip List diff --git a/solutions/Searching-Algorithms/Spiral-Matrix-Search.md b/solutions/Searching-Algorithms/Spiral-Matrix-Search.md new file mode 100644 index 0000000..f88d7fb --- /dev/null +++ b/solutions/Searching-Algorithms/Spiral-Matrix-Search.md @@ -0,0 +1,195 @@ +--- +id: Spiral-Matrix-Search +title: Spiral Matrix Search +sidebar_label: Spiral Matrix Search +tags: + - Advanced + - Search Algorithms + - Matrix + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Spiral Matrix Search problem." +--- + +## What is Spiral Matrix Search? + +Spiral Matrix Search is a search algorithm designed to search for a target element in a 2D matrix by traversing the matrix in a spiral order. The traversal starts from the top-left corner and proceeds in a spiral (clockwise) fashion until the entire matrix is covered or the target element is found. + +## Algorithm Steps + +1. **Initialization**: + - Start from the top-left corner of the matrix. + - Define boundaries: `top`, `bottom`, `left`, and `right`. + +2. **Spiral Traversal**: + - Move from left to right across the topmost untraversed row. + - Move from top to bottom down the rightmost untraversed column. + - Move from right to left across the bottommost untraversed row. + - Move from bottom to top up the leftmost untraversed column. + - Adjust the boundaries accordingly after each move. + +3. **Check Element**: + - At each position during the traversal, check if the current element matches the target. + - If a match is found, return the coordinates of the target element. + +4. **End Condition**: + - The traversal continues until the entire matrix is covered or the target element is found. + +## Complexity Analysis + +- **Time Complexity**: \( O(n) \) where \( n \) is the total number of elements in the matrix. Each element is visited exactly once. +- **Space Complexity**: \( O(1) \) as no extra space is used other than variables for traversal and boundaries. + +## Example + +Given a 2D matrix: + +matrix = [ +[1, 2, 3, 4], +[5, 6, 7, 8], +[9, 10, 11, 12], +[13, 14, 15, 16] +] + +target = 7 + + +Using Spiral Matrix Search: + +- Start from the top-left corner: `matrix[0][0]`. +- Traverse in a spiral order until the target `7` is found. + +## Implementation + + + + +```python +def spiral_matrix_search(matrix, target): + if not matrix or not matrix[0]: + return None + + rows, cols = len(matrix), len(matrix[0]) + top, bottom, left, right = 0, rows - 1, 0, cols - 1 + + while top <= bottom and left <= right: + # Traverse from left to right + for col in range(left, right + 1): + if matrix[top][col] == target: + return (top, col) + top += 1 + + # Traverse from top to bottom + for row in range(top, bottom + 1): + if matrix[row][right] == target: + return (row, right) + right -= 1 + + # Traverse from right to left + if top <= bottom: + for col in range(right, left - 1, -1): + if matrix[bottom][col] == target: + return (bottom, col) + bottom -= 1 + + # Traverse from bottom to top + if left <= right: + for row in range(bottom, top - 1, -1): + if matrix[row][left] == target: + return (row, left) + left += 1 + + return None + +# Example usage: +matrix = [ + [1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16] +] +target = 7 + +result = spiral_matrix_search(matrix, target) +if result: + print(f"Target {target} found at position: {result}") +else: + print(f"Target {target} not found in the matrix") +``` + + + + +```cpp + +#include +#include + +std::pair spiral_matrix_search(std::vector>& matrix, int target) { + if (matrix.empty() || matrix[0].empty()) return {-1, -1}; + + int rows = matrix.size(); + int cols = matrix[0].size(); + int top = 0, bottom = rows - 1; + int left = 0, right = cols - 1; + + while (top <= bottom && left <= right) { + // Traverse from left to right + for (int col = left; col <= right; ++col) { + if (matrix[top][col] == target) return {top, col}; + } + top++; + + // Traverse from top to bottom + for (int row = top; row <= bottom; ++row) { + if (matrix[row][right] == target) return {row, right}; + } + right--; + + // Traverse from right to left + if (top <= bottom) { + for (int col = right; col >= left; --col) { + if (matrix[bottom][col] == target) return {bottom, col}; + } + bottom--; + } + + // Traverse from bottom to top + if (left <= right) { + for (int row = bottom; row >= top; --row) { + if (matrix[row][left] == target) return {row, left}; + } + left++; + } + } + + return {-1, -1}; +} + +int main() { + std::vector> matrix = { + {1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12}, + {13, 14, 15, 16} + }; + int target = 7; + + std::pair result = spiral_matrix_search(matrix, target); + if (result.first != -1) { + std::cout << "Target " << target << " found at position: (" << result.first << ", " << result.second << ")\n"; + } else { + std::cout << "Target " << target << " not found in the matrix\n"; + } + return 0; +} +``` + + + + +# Conclusion +The Spiral Matrix Search algorithm is an efficient way to traverse a 2D matrix in a spiral order to find a target element. It ensures each element is visited exactly once, maintaining a linear time complexity and constant space complexity. diff --git a/solutions/Searching-Algorithms/Ternary-search.md b/solutions/Searching-Algorithms/Ternary-search.md new file mode 100644 index 0000000..3a3daa9 --- /dev/null +++ b/solutions/Searching-Algorithms/Ternary-search.md @@ -0,0 +1,239 @@ +--- +id: Ternary-Search +title: Ternary Search (Geeks for Geeks) +sidebar_label: Ternary Search +tags: + - Intermediate + - Search Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Ternary Search problem on Geeks for Geeks." +--- + +## What is Ternary Search? + +Ternary Search is a divide-and-conquer search algorithm used to find the position of a target value within a sorted array. It divides the array into three parts and determines which part the target value belongs to, reducing the search space by one third each time. + +## Algorithm for Ternary Search + +1. Divide the array into three parts by calculating two midpoints. +2. Compare the target value with the values at these midpoints. +3. If the target value matches either midpoint, return the index. +4. If the target value is less than the first midpoint, repeat the process on the left third. +5. If the target value is greater than the first midpoint but less than the second midpoint, repeat the process on the middle third. +6. If the target value is greater than the second midpoint, repeat the process on the right third. +7. If the target value is not found, return -1. + +## How does Ternary Search work? + +- It calculates two midpoints to divide the array into three parts. +- It compares the target value with the elements at the midpoints. +- Based on the comparison, it reduces the search space to one of the three parts and repeats the process. + +## Problem Description + +Given a sorted array and a target element, implement the Ternary Search algorithm to find the index of the target element in the array. If the element is not present, return -1. + +## Examples + +**Example 1:** +Input: +list = [1, 2, 3, 4, 5, 6, 7, 8, 9] +target = 5 +Output: 4 + +**Example 2:** +Input: +list = [1, 2, 3, 4, 5, 6, 7, 8, 9] +target = 10 +Output: -1 + +## Your task + +Complete the function ternary_search() which takes two integers n, k and an array arr, as input parameters and returns an integer denoting the answer. Return -1 if the number is not found in the array. You don't have to print answers or take inputs. + +Expected Time Complexity: $O(\log_3 n)$ +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- $1 <= n <= 10^6$ +- $1 <= k <= 10^6$ +- $1 <= arr[i] <= 10^9$ + +## Implementation + + + + + +```python + def ternary_search(arr, target): + left, right = 0, len(arr) - 1 + + while left <= right: + mid1 = left + (right - left) // 3 + mid2 = right - (right - left) // 3 + + if arr[mid1] == target: + return mid1 + if arr[mid2] == target: + return mid2 + + if target < arr[mid1]: + right = mid1 - 1 + elif target > arr[mid2]: + left = mid2 + 1 + else: + left = mid1 + 1 + right = mid2 - 1 + + return -1 +``` + + + + +```cpp + + #include + #include + + int ternary_search(const std::vector& arr, int target) { + int left = 0, right = arr.size() - 1; + + while (left <= right) { + int mid1 = left + (right - left) / 3; + int mid2 = right - (right - left) / 3; + + if (arr[mid1] == target) { + return mid1; + } + if (arr[mid2] == target) { + return mid2; + } + + if (target < arr[mid1]) { + right = mid1 - 1; + } else if (target > arr[mid2]) { + left = mid2 + 1; + } else { + left = mid1 + 1; + right = mid2 - 1; + } + } + + return -1; + } + + int main() { + std::vector arr = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + int target = 5; + std::cout << "Index: " << ternary_search(arr, target) << std::endl; + return 0; + } +``` + + + + +```java + public class TernarySearch { + public static int ternarySearch(int[] arr, int target) { + int left = 0, right = arr.length - 1; + + while (left <= right) { + int mid1 = left + (right - left) / 3; + int mid2 = right - (right - left) / 3; + + if (arr[mid1] == target) { + return mid1; + } + if (arr[mid2] == target) { + return mid2; + } + + if (target < arr[mid1]) { + right = mid1 - 1; + } else if (target > arr[mid2]) { + left = mid2 + 1; + } else { + left = mid1 + 1; + right = mid2 - 1; + } + } + + return -1; + } + + public static void main(String[] args) { + int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + int target = 5; + System.out.println("Index: " + ternarySearch(arr, target)); + } + } +``` + + + + +```javascript + function ternarySearch(arr, target) { + let left = 0, right = arr.length - 1; + + while (left <= right) { + let mid1 = left + Math.floor((right - left) / 3); + let mid2 = right - Math.floor((right - left) / 3); + + if (arr[mid1] === target) { + return mid1; + } + if (arr[mid2] === target) { + return mid2; + } + + if (target < arr[mid1]) { + right = mid1 - 1; + } else if (target > arr[mid2]) { + left = mid2 + 1; + } else { + left = mid1 + 1; + right = mid2 - 1; + } + } + + return -1; + } + + const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; + const target = 5; + console.log("Index:", ternarySearch(arr, target)); +``` + + + +## Complexity Analysis + +- **Time Complexity**: $O(\log_3 n)$, where $n$ is the number of elements in the array. The search space is divided into three parts each time, leading to a logarithmic time complexity base 3. +- **Space Complexity**: $O(1)$, as no extra space is required apart from the input array. + +## Advantages and Disadvantages + +**Advantages:** +- Faster than binary search for large arrays due to reducing the search space by one third each time. +- Efficient for large datasets. + +**Disadvantages:** +- Requires the array to be sorted. +- More complex to implement compared to binary search. +- Not significantly faster than binary search for small datasets. + +## References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/ternary-search/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/ternary-search/problem) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) diff --git a/solutions/Sorting-Algorithms/Bitonic-Sort.md b/solutions/Sorting-Algorithms/Bitonic-Sort.md new file mode 100644 index 0000000..14a4a38 --- /dev/null +++ b/solutions/Sorting-Algorithms/Bitonic-Sort.md @@ -0,0 +1,132 @@ +--- +id: Bitonic-Sort-Algorithm +title: Bitonic Sort Algorithm +sidebar_label: Bitonic Sort Algorithm +tags: + - Sorting Algorithms + - Simple + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Bitonic Sort Algorithm problem." +--- + +## What is the Bitonic Sort Algorithm? + +Bitonic Sort is a parallel sorting algorithm that is efficient for hardware implementation. It works by recursively sorting two halves of the array into a bitonic sequence (one half in ascending order and the other in descending order) and then merging them into a single sorted sequence. + +## Algorithm Steps + +1. **Bitonic Sequence**: + - Divide the array into two halves. + - Recursively sort one half in ascending order and the other half in descending order to form a bitonic sequence. + +2. **Bitonic Merge**: + - Compare and swap elements to merge the bitonic sequence into a single sorted sequence. + +3. **Recursive Sorting**: + - Apply the bitonic sequence and bitonic merge steps recursively until the entire array is sorted. + +## Complexity Analysis + +- **Time Complexity**: $O(n \log^2 n)$ in the worst case. +- **Space Complexity**: $O(n)$ auxiliary space due to the recursive calls. + +## Example + +Given an unsorted array: + +``` +array = [4, 3, 2, 1] +``` + +Using the Bitonic Sort Algorithm: + +- Create bitonic sequences: `[4, 3]` (ascending), `[2, 1]` (descending) +- Merge bitonic sequences: `[3, 4]` and `[1, 2]` to `[1, 2, 3, 4]` + +## Implementation + + + + +```python +def bitonic_sort(arr, low, cnt, direction): + if cnt > 1: + k = cnt // 2 + bitonic_sort(arr, low, k, 1) + bitonic_sort(arr, low + k, k, 0) + bitonic_merge(arr, low, cnt, direction) + +def bitonic_merge(arr, low, cnt, direction): + if cnt > 1: + k = cnt // 2 + for i in range(low, low + k): + if (direction == 1 and arr[i] > arr[i + k]) or (direction == 0 and arr[i] < arr[i + k]): + arr[i], arr[i + k] = arr[i + k], arr[i] + bitonic_merge(arr, low, k, direction) + bitonic_merge(arr, low + k, k, direction) + +def sort(arr, N, up): + bitonic_sort(arr, 0, N, up) + +# Example usage: +array = [4, 3, 2, 1] +sort(array, len(array), 1) +print(array) # Output: [1, 2, 3, 4] +``` + + + + +```cpp +#include +#include + +void bitonicMerge(std::vector& arr, int low, int cnt, bool dir) { + if (cnt > 1) { + int k = cnt / 2; + for (int i = low; i < low + k; i++) { + if (dir == (arr[i] > arr[i + k])) { + std::swap(arr[i], arr[i + k]); + } + } + bitonicMerge(arr, low, k, dir); + bitonicMerge(arr, low + k, k, dir); + } +} + +void bitonicSort(std::vector& arr, int low, int cnt, bool dir) { + if (cnt > 1) { + int k = cnt / 2; + bitonicSort(arr, low, k, true); + bitonicSort(arr, low + k, k, false); + bitonicMerge(arr, low, cnt, dir); + } +} + +void sort(std::vector& arr, int N, bool up) { + bitonicSort(arr, 0, N, up); +} + +int main() { + std::vector array = {4, 3, 2, 1}; + sort(array, array.size(), true); + + for (int num : array) { + std::cout << num << " "; + } + std::cout << std::endl; // Output: 1 2 3 4 + + return 0; +} +``` + + + + +## Conclusion + +Bitonic Sort is an efficient parallel sorting algorithm with a consistent \( O(n \log^2 n) \) time complexity. It is well-suited for hardware implementations and can be useful in parallel computing environments. diff --git a/solutions/Sorting-Algorithms/Bubble-Sort.md b/solutions/Sorting-Algorithms/Bubble-Sort.md new file mode 100644 index 0000000..71a012e --- /dev/null +++ b/solutions/Sorting-Algorithms/Bubble-Sort.md @@ -0,0 +1,183 @@ +--- +id: Bubble-Sort +title: Bubble Sort (Geeks for Geeks) +sidebar_label: Bubble Sort +tags: + - Beginner + - Sorting Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Bubble Sort problem on Geeks for Geeks." +--- + +## 1. What is Bubble Sort? + +Bubble Sort is a simple comparison-based sorting algorithm. It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The process is repeated until the list is sorted. + +## 2. Algorithm for Bubble Sort + +1. Start with the first element and compare it with the second element. +2. If the first element is greater than the second element, swap them. +3. Move to the next pair and repeat the process until the end of the list. +4. Repeat steps 1-3 for all elements in the list until no swaps are needed. + +## 3. How does Bubble Sort work? + +- Bubble Sort works by repeatedly swapping adjacent elements if they are in the wrong order. +- The largest element "bubbles up" to its correct position in each iteration. + +## 4. Problem Description + +Given an array of integers, implement the Bubble Sort algorithm to sort the array in ascending order. + +## 5. Examples + +**Example 1:** +``` +Input: [64, 34, 25, 12, 22, 11, 90] +Output: [11, 12, 22, 25, 34, 64, 90] +``` + +**Example 2:** +``` +Input: [5, 1, 4, 2, 8] +Output: [1, 2, 4, 5, 8] +``` + +**Explanation of Example 1:** +- The initial array is [64, 34, 25, 12, 22, 11, 90]. +- First pass: [34, 25, 12, 22, 11, 64, 90]. +- Second pass: [25, 12, 22, 11, 34, 64, 90]. +- Continue until the array is sorted: [11, 12, 22, 25, 34, 64, 90]. + +## 6. Constraints + +- $The array can have any number of elements.$ +- $All elements in the array are integers.$ + +## 7. Implementation + + + + + ```python + def bubble_sort(arr): + n = len(arr) + for i in range(n): + for j in range(0, n-i-1): + if arr[j] > arr[j+1]: + arr[j], arr[j+1] = arr[j+1], arr[j] + return arr + + # Example usage: + arr = [64, 34, 25, 12, 22, 11, 90] + bubble_sort(arr) + print(arr) + ``` + + + + + ```cpp + #include + #include + + void bubbleSort(std::vector& arr) { + int n = arr.size(); + for (int i = 0; i < n - 1; i++) { + for (int j = 0; j < n - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + std::swap(arr[j], arr[j + 1]); + } + } + } + } + + int main() { + std::vector arr = {64, 34, 25, 12, 22, 11, 90}; + bubbleSort(arr); + for (int num : arr) + std::cout << num << " "; + return 0; + } + ``` + + + + + ```java + public class BubbleSort { + public static void bubbleSort(int[] arr) { + int n = arr.length; + for (int i = 0; i < n - 1; i++) { + for (int j = 0; j < n - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + int temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } + } + + public static void main(String[] args) { + int[] arr = {64, 34, 25, 12, 22, 11, 90}; + bubbleSort(arr); + for (int num : arr) + System.out.print(num + " "); + } + } + ``` + + + + + ```javascript + function bubbleSort(arr) { + let n = arr.length; + for (let i = 0; i < n - 1; i++) { + for (let j = 0; j < n - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; + } + } + } + return arr; + } + + // Example usage: + let arr = [64, 34, 25, 12, 22, 11, 90]; + bubbleSort(arr); + console.log(arr); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: + - Best case: $O(n)$ (when the array is already sorted) + - Average case: $O(n^2)$ + - Worst case: $O(n^2)$ + +- **Space Complexity**: $O(1)$ (in-place sorting) + +## 9. Advantages and Disadvantages + +**Advantages:** +- Simple to understand and implement. +- Works well with small datasets. + +**Disadvantages:** +- Inefficient for large datasets due to $O(n^2)$ time complexity. +- Requires multiple passes through the list. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/bubble-sort/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/bubble-sort/problem) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) \ No newline at end of file diff --git a/solutions/Sorting-Algorithms/Cocktail-Sort.md b/solutions/Sorting-Algorithms/Cocktail-Sort.md new file mode 100644 index 0000000..28ebe75 --- /dev/null +++ b/solutions/Sorting-Algorithms/Cocktail-Sort.md @@ -0,0 +1,146 @@ +-- +id: Cocktail-Sort +title: Cocktail Sort (Geeks for Geeks) +sidebar_label: Cocktail Sort +tags: + - Intermediate + - Sorting Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Cocktail Sort problem on Geeks for Geeks." +--- + +## 1. What is Cocktail Sort? + +Cocktail Sort is a variation of Bubble Sort. It traverses the list in both directions alternatively. This algorithm is also known as Bidirectional Bubble Sort or Shaker Sort. + +## 2. Algorithm for Cocktail Sort + +1. Start at the beginning of the list. +2. Traverse the list from left to right, swapping adjacent items if they are in the wrong order. +3. When the end of the list is reached, reverse the direction and traverse from right to left, again swapping adjacent items if they are in the wrong order. +4. Repeat steps 2 and 3 until the list is sorted. + +## 3. How does Cocktail Sort work? + +- It sorts in both directions in each pass through the list, which can help elements move into place faster. +- This bidirectional approach allows earlier elements to "bubble up" and later elements to "bubble down" in the same pass, potentially reducing the number of overall passes needed. + +## 4. Problem Description + +Given an array of integers, implement the Cocktail Sort algorithm to sort the array. + +## 5. Examples + +**Example 1:** + +``` +Input: [5, 1, 4, 2, 8, 0, 2] +Output: [0, 1, 2, 2, 4, 5, 8] +``` +**Example 2:** +``` +Input: [5, 1, 4, 2, 9, 8] +Output: [1, 2, 4, 5, 8, 9] +``` + +## 6. Constraints + +- The array should contain at least one element. + +## 7. Implementation + +**Python** +```python +def cocktail_sort(arr): + n = len(arr) + swapped = True + start = 0 + end = n - 1 + while swapped: + swapped = False + for i in range(start, end): + if arr[i] > arr[i + 1]: + arr[i], arr[i + 1] = arr[i + 1], arr[i] + swapped = True + if not swapped: + break + swapped = False + end -= 1 + for i in range(end - 1, start - 1, -1): + if arr[i] > arr[i + 1]: + arr[i], arr[i + 1] = arr[i + 1], arr[i] + swapped = True + start += 1 + return arr +``` +```java +import java.util.Arrays; + +public class CocktailSort { + public static void cocktailSort(int[] arr) { + boolean swapped = true; + int start = 0; + int end = arr.length - 1; + + while (swapped) { + swapped = false; + for (int i = start; i < end; i++) { + if (arr[i] > arr[i + 1]) { + int temp = arr[i]; + arr[i] = arr[i + 1]; + arr[i + 1] = temp; + swapped = true; + } + } + if (!swapped) break; + swapped = false; + end--; + for (int i = end - 1; i >= start; i--) { + if (arr[i] > arr[i + 1]) { + int temp = arr[i]; + arr[i] = arr[i + 1]; + arr[i + 1] = temp; + swapped = true; + } + } + start++; + } + } + + public static void main(String[] args) { + int[] arr = {5, 1, 4, 2, 8, 0, 2}; + cocktailSort(arr); + System.out.println(Arrays.toString(arr)); + } +} + +``` + +## 8. Complexity Analysis + +- **Time Complexity**: + - Best case: $O(n)$ (when the array is already sorted) + Average case: $O(n^2)$ + Worst case: $O(n^2)$ + +- **Space Complexity**: $O(1)$ (in-place sorting) + +## 9. Advantages and Disadvantages + +**Advantages:** +- Cocktail Sort can be more efficient than Bubble Sort for certain types of input because it can address issues where small elements are initially near the end of the list. +- Simple to understand and implement. + +**Disadvantages:** +- Still has a worst-case time complexity of $O(n^2)$, making it inefficient on large lists compared to more advanced algorithms like Quick Sort, Merge Sort, or Heap Sort. +- The bidirectional approach does not significantly improve performance for most input cases. + +## 10. References + +- **GFG Article on Cocktail Sort:** [Geeks for Geeks Cocktail Sort](https://www.geeksforgeeks.org/cocktail-sort/) +- **Wikipedia Article on Cocktail Sort:** [Cocktail Sort - Wikipedia](https://en.wikipedia.org/wiki/cocktail_sort) diff --git a/solutions/Sorting-Algorithms/Counting-Sort.md b/solutions/Sorting-Algorithms/Counting-Sort.md new file mode 100644 index 0000000..cee8807 --- /dev/null +++ b/solutions/Sorting-Algorithms/Counting-Sort.md @@ -0,0 +1,122 @@ +--- +id: Counting-Sort +title: Counting Sort (Geeks for Geeks) +sidebar_label: Counting Sort +tags: + - Beginner + - Sorting Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Counting Sort problem on Geeks for Geeks." +--- + +## 1. What is Counting Sort? + +Counting Sort is a non-comparison-based sorting algorithm. It works by counting the number of occurrences of each unique element in the input array. The algorithm uses this count information to place the elements in their correct positions in the output array. + +## 2. Algorithm for Counting Sort + +1. Find the maximum element in the input array. +2. Create a count array of size (maximum element + 1) and initialize all elements to 0. +3. Count the occurrences of each element in the input array and store it in the count array. +4. Modify the count array such that each element at each index stores the sum of previous counts. +5. Output each element from the input array into the correct sorted position in the output array. + +## 3. How does Counting Sort work? + +- Counting Sort calculates the position of each element in the sorted array by using the count array. +- The count array stores the count of each unique element. +- By iterating through the input array and the count array, elements are placed into their correct positions in the output array. + +## 4. Problem Description + +Given an array of integers, implement the Counting Sort algorithm to sort the array in ascending order. + +## 5. Examples + +**Example 1:** +```markdown +Input: [4, 2, 2, 8, 3, 3, 1] +Output: [1, 2, 2, 3, 3, 4, 8] + +**Example 2:** +```markdown +Input: [7, 4, 4, 6, 2, 1, 5, 3, 8, 5] +Output: [1, 2, 3, 4, 4, 5, 5, 6, 7, 8] +``` + +**Explanation of Example 1:** +- The initial array is [4, 2, 2, 8, 3, 3, 1]. +- Count array: [0, 1, 2, 2, 1, 0, 0, 0, 1] +- Sorted array: [1, 2, 2, 3, 3, 4, 8] + +## 6. Constraints + +- The array can have any number of elements. +- All elements in the array are non-negative integers. + +## 7. Implementation + +```java +public class CountingSort { + public static void countingSort(int arr[]) { + int largest = Integer.MIN_VALUE; + for (int i = 0; i < arr.length; i++) { + largest = Math.max(largest, arr[i]); + } + + int count[] = new int[largest + 1]; + + for (int i = 0; i < arr.length; i++) { + count[arr[i]]++; + } + + int j = 0; + for (int i = 0; i < count.length; i++) { + while (count[i] > 0) { + arr[j] = i; + j++; + count[i]--; + } + } + } + + public static void main(String[] args) { + int[] arr = {4, 2, 2, 8, 3, 3, 1}; + countingSort(arr); + for (int num : arr) { + System.out.print(num + " "); + } + } +} +``` + +## 8. Complexity Analysis + +- **Time Complexity**: + - Best case: $O(n + k)$ + - Average case: $O(n + k)$ + - Worst case: $O(n + k)$ + - where (n) is the number of elements in the input array and (k) is the range of the input. + +- **Space Complexity**: $O(n + k)$ + +## 9. Advantages and Disadvantages + +**Advantages:** +- Simple to implement. +- Efficient for sorting integers when the range of the input values is not significantly greater than the number of elements. + +**Disadvantages:** +- Not suitable for sorting strings or floating-point numbers. +- The space complexity can be high if the range of input values is very large. + +## 10. References + +- **GFG Article on Counting Sort:** [Geeks for Geeks Counting Sort](https://www.geeksforgeeks.org/counting-sort/) +- **GFG Problem** [Counting Sort Problem](https://www.geeksforgeeks.org/problems/counting-sort/1) +- **Wikipedia Article on Counting Sort:** [Counting Sort - Wikipedia](https://en.wikipedia.org/wiki/Counting_sort) diff --git a/solutions/Sorting-Algorithms/Cycle-Sort.md b/solutions/Sorting-Algorithms/Cycle-Sort.md new file mode 100644 index 0000000..7308e69 --- /dev/null +++ b/solutions/Sorting-Algorithms/Cycle-Sort.md @@ -0,0 +1,208 @@ +--- +id: Cycle-Sort +title: Cycle Sort (Geeks for Geeks) +sidebar_label: Cycle Sort +tags: + - Beginner + - Sorting Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Cycle Sort problem on Geeks for Geeks." +--- + +## 1. What is Cycle Sort? + +Cycle Sort is a comparison-based sorting algorithm that is particularly efficient when memory writes are a costly operation. The algorithm minimizes the number of memory writes to sort the array. The idea is to write each element to its correct position and hence reduce the number of write operations. + +## 2. Algorithm for Cycle Sort + +*Cycle Start:* Begin from the first element of the array. + +*Find Position:* For the current element, find the position where it should be placed by counting the number of elements smaller than it. + +*Place the Element:* Place the element in its correct position. If the element is already in its correct position, continue to the next element. + +*Cycle:* If the element is not in its correct position, put the displaced element to its correct position, creating a cycle of swaps until all elements are in their correct positions. + +*Repeat:* Repeat the process for all elements of the array. + +## 3. How does Cycle Sort work? + +Cycle Sort works by ensuring that each element is placed directly into its correct position. + +This is achieved by counting the number of elements smaller than the current element and placing it at the corresponding index. + +If an element is already in its correct position, it is skipped. + +The displaced element is then placed in its correct position, creating a cycle until all elements are sorted. + +## 4. Problem Description + +Given an array of integers, implement the Cycle Sort algorithm to sort the array in ascending order. + + +## 5. Examples + +**Example 1:** +``` +Input: [20, 40, 50, 10, 30] +Output: [10, 20, 30, 40, 50] +``` +**Example 2:** +``` +Input: [64, 25, 12, 22, 11] +Output: [11, 12, 22, 25, 64] +``` + +**Explanation of Example 1:** + +-The initial array is [20, 40, 50, 10, 30] +-First cycle: Place 20 at index 1 (correct position).[10, 20, 50, 40, 30] +-Second cycle: 40 is already in the correct position. +-Third cycle: Place 50 at index 4 (correct position).[10, 20, 30, 40, 50] +-Fourth and fifth cycles: Remaining elements are already in the correct position. +-Final sorted array: [10, 20, 30, 40, 50]. + +## 6. key constraints and characteristics of Cycle Sort: + +- **Memory Writes**: Minimizes the number of write operations, making it efficient where write operations are costly. +- **Stability**: Maintains the relative order of equal elements, making it a stable sorting algorithm. +- **Performance**: + - Time Complexity: $O(n^2)$ in the worst case. + - Space Complexity: $O(1)$ additional space, as it sorts in-place. +- **Data Type**: Can be applied to any data type supporting comparison and swap operations. +- **Use Cases**: Suitable for small datasets or scenarios requiring stable sorting with minimal writes, like embedded systems. +- **Performance Issues**: + - Inefficient for large datasets due to its quadratic time complexity. + - May not perform well on datasets with many duplicates or pre-sorted data. + +## 7. Implementation + +**Java Implementation** +```java +public class CycleSort { + public static void cycleSort(int[] arr) { + int n = arr.length; + for (int cycleStart = 0; cycleStart <= n - 2; cycleStart++) { + int item = arr[cycleStart]; + int pos = cycleStart; + for (int i = cycleStart + 1; i < n; i++) { + if (arr[i] < item) + pos++; + } + while (item == arr[pos]) + pos++; + if (pos != cycleStart) { + int temp = item; + item = arr[pos]; + arr[pos] = temp; + } + while (pos != cycleStart) { + pos = cycleStart; + for (int i = cycleStart + 1; i < n; i++) { + if (arr[i] < item) + pos++; + } + while (item == arr[pos]) + pos++; + if (item != arr[pos]) { + int temp = item; + item = arr[pos]; + arr[pos] = temp; + } + } + } + } + + public static void main(String[] args) { + int[] arr = {20, 40, 50, 10, 30}; + cycleSort(arr); + for (int num : arr) { + System.out.print(num + " "); + } + } +} +``` + +**Python** +```python +def cycle_sort(arr): + writes = 0 + + for cycleStart in range(0, len(arr) - 1): + item = arr[cycleStart] + pos = cycleStart + + for i in range(cycleStart + 1, len(arr)): + if arr[i] < item: + pos += 1 + + while item == arr[pos]: + pos += 1 + + if pos != cycleStart: + arr[pos], item = item, arr[pos] + writes += 1 + + while pos != cycleStart: + pos = cycleStart + for i in range(cycleStart + 1, len(arr)): + if arr[i] < item: + pos += 1 + + while item == arr[pos]: + pos += 1 + + if item != arr[pos]: + arr[pos], item = item, arr[pos] + writes += 1 + + return writes + +arr = [20, 40, 50, 10, 30] +cycle_sort(arr) +print(arr) +``` + +## 8. Complexity + +-**Time Complexity** + - Best Case: $O(n^2)$ + - Average Case: $O(n^2)$ + - Worst Case: $O(n^2)$ + Cycle Sort typically exhibits quadratic time complexity, where n is the number of elements in the array. This arises because each element may need to be moved multiple times to its correct position, especially in the presence of duplicates or when the array is in reverse order. + +-**Space Complexity** + - $O(1)$ + - Cycle Sort is an in-place sorting algorithm, meaning it requires only a constant amount of extra space for auxiliary variables such as loops and temporary variables used for swaps. + + +## 9. Advantages and disadvantages +### Advantages: + +- **Minimizes Writes:** Cycle Sort reduces memory writes, making it efficient where write operations are costly. + +- **Stable Sorting:** Preserves the order of equal elements, ensuring stability in sorting results. + +- **In-Place Algorithm:** Sorts elements directly within the input array, requiring minimal extra space. + +- **Suitable for Small Data Sets:** Efficient for small datasets or nearly sorted arrays due to direct placement of elements. + +### Disadvantages: + +- **Quadratic Time Complexity:** Has $O(n^2)$ time complexity in the worst-case scenario, limiting efficiency for large datasets. + +- **Not Adaptive:** Performs the same number of operations regardless of initial data order, lacking adaptability. + +- **May Perform Poorly with Duplicates:** Can require additional operations to handle datasets with many duplicate values. + +- **Limited Use Cases:** Less suitable for large or dynamic datasets where faster algorithms are more efficient, such as Quick Sort or Merge Sort. + +## 10. References + +- **GFG Article on Cycle Sort:** [Geeks for Geeks Cycle Sort](https://www.geeksforgeeks.org/cycle-sort/) +- **Wikipedia Article on Cycle Sort:** [Cycle Sort - Wikipedia](https://en.wikipedia.org/wiki/Cycle_sort) diff --git a/solutions/Sorting-Algorithms/Gnome_Sort.md b/solutions/Sorting-Algorithms/Gnome_Sort.md new file mode 100644 index 0000000..1ff3738 --- /dev/null +++ b/solutions/Sorting-Algorithms/Gnome_Sort.md @@ -0,0 +1,143 @@ +--- +id: Gnome-Sort +title: Gnome Sort (Geeks for Geeks) +sidebar_label: Gnome Sort +tags: + - Beginner + - Sorting Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Gnome Sort problem on Geeks for Geeks." +--- + +## 1. What is Gnome Sort? + +Gnome Sort is a straightforward comparison-based sorting algorithm. It iteratively steps through the list, compares each pair of adjacent elements, and swaps them if they are in the wrong order. The algorithm moves forward if elements are in the correct order, but steps backward and continues swapping until the elements are ordered correctly when a pair is out of order. This process is repeated until the entire list is sorted. + +## 2. Algorithm for Gnome Sort + +1. Start with the first element. +2. If the current element is in the correct order (greater than or equal to the previous element), move to the next element. +3. If the current element is in the wrong order (less than the previous element), swap them and move one step back. +4. Repeat steps 2-3 until the end of the list is reached. +5. If the beginning of the list is reached, move forward and continue the process. + +## 3. How does Gnome Sort work? + +- Gnome Sort works by repeatedly comparing and swapping adjacent elements if they are in the wrong order. +- If a swap is made, it steps backward to ensure the order of all previous elements. +- It progresses forward only when elements are in the correct order, sorting the list step by step. + +## 4. Problem Description + +Given an array of integers, implement the Gnome Sort algorithm to sort the array in ascending order. + +## 5. Examples + +**Example 1:** +``` +Input: [64, 34, 25, 12, 22, 11, 90] +Output: [11, 12, 22, 25, 34, 64, 90] +``` + +**Example 2:** +``` +Input: [5, 1, 4, 2, 8] +Output: [1, 2, 4, 5, 8] +``` + +**Explanation of Example 1:** +- The initial array is [64, 34, 25, 12, 22, 11, 90]. +- First pass: [34, 64, 25, 12, 22, 11, 90]. +- After correcting: [34, 25, 64, 12, 22, 11, 90]. +- Continue until the array is sorted: [11, 12, 22, 25, 34, 64, 90]. + +## 6. Constraints + +- The input array can contain any integers, positive or negative. +- The size of the array can range from 1 to $10^5$ elements. +- The sorting should be done in-place with $O(1)$ additional space. +- The algorithm should maintain stability, meaning the relative order of equal elements should be preserved. + + +## 7. Implementation +### Gnome Sort in Java + +```java +public class GnomeSort { + public static void gnomeSort(int[] arr) { + int index = 0; + int n = arr.length; + + while (index < n) { + if (index == 0 || arr[index] >= arr[index - 1]) { + index++; + } else { + int temp = arr[index]; + arr[index] = arr[index - 1]; + arr[index - 1] = temp; + index--; + } + } + } + + public static void main(String[] args) { + int[] arr = {64, 34, 25, 12, 22, 11, 90}; + gnomeSort(arr); + for (int num : arr) { + System.out.print(num + " "); + } + } +} +``` + +### Gnome Sort in Python + +```python +def gnome_sort(arr): + index = 0 + n = len(arr) + + while index < n: + if index == 0 or arr[index] >= arr[index - 1]: + index += 1 + else: + arr[index], arr[index - 1] = arr[index - 1], arr[index] + index -= 1 + +# Example usage +arr = [64, 34, 25, 12, 22, 11, 90] +gnome_sort(arr) +print(arr) +``` + +## 8. Complexity Analysis + +- **Time Complexity**: + - Best case: $O(n)$ (when the array is already sorted) + - Average case: $O(n^2)$ + - Worst case: $O(n^2)$ + +- **Space Complexity**: $O(1)$ (in-place sorting) + +## 9. Advantages and Disadvantages + +**Advantages:** +- Simple to understand and implement. +- Requires minimal additional space, making it space-efficient. +- Suitable for small datasets or nearly sorted arrays. + +**Disadvantages:** +- Inefficient for large datasets due to $O(n^2)$ time complexity. +- Can perform poorly with datasets containing many duplicate values. +- Requires multiple backward steps when elements are out of order. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/gnome-sort-a-stupid-one/) +- **Wikipedia Article on Gnome Sort:** [Gnome Sort - Wikipedia](https://en.wikipedia.org/wiki/Gnome_sort) + diff --git a/solutions/Sorting-Algorithms/Heap-Sort.md b/solutions/Sorting-Algorithms/Heap-Sort.md new file mode 100644 index 0000000..9c3082b --- /dev/null +++ b/solutions/Sorting-Algorithms/Heap-Sort.md @@ -0,0 +1,295 @@ +--- +id: Heap-Sort +title: Heap Sort (Geeks for Geeks) +sidebar_label: Heap Sort +tags: + - Beginner + - Sorting Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Heap Sort problem on Geeks for Geeks." +--- + +## 1. What is Heap Sort? + +Heap sort is a comparison-based sorting technique based on Binary Heap data structure. It is similar to the selection sort where we first find the minimum element and place the minimum element at the beginning. Repeat the same process for the remaining elements. + +## 2. Algorithm for Heap Sort + +First convert the array into heap data structure using heapify, then one by one delete the root node of the Max-heap and replace it with the last node in the heap and then heapify the root of the heap. Repeat this process until size of heap is greater than 1. + +1. Build a heap from the given input array. +2. Repeat the following steps until the heap contains only one element: + +- Swap the root element of the heap (which is the largest element) with the last element of the heap. +- Remove the last element of the heap (which is now in the correct position). +- Heapify the remaining elements of the heap. + +3. The sorted array is obtained by reversing the order of the elements in the input array. + +## 3. How does Heap Sort work? + +To understand heap sort more clearly, let’s take an unsorted array and try to sort it using heap sort. + +1. Build Complete Binary Tree: Build a complete binary tree from the array. + +2. Transform into max heap: After that, the task is to construct a tree from that unsorted array and try to convert it into max heap. + +3. To transform a heap into a max-heap, the parent node should always be greater than or equal to the child nodes + +4. Perform heap sort: Remove the maximum element in each step (i.e., move it to the end position and remove that) and then consider the remaining elements and transform it into a max heap. + +5. Delete the root element (10) from the max heap. In order to delete this node, try to swap it with the last node. After removing the root element, again heapify it to convert it into max heap. + +6. Repeat the above steps. Now remove the root again and perform heapify. + Now when the root is removed once again it is sorted + +## 4. Problem Description + +Given an array of integers, implement the Heap Sort algorithm to sort the array in ascending order. + +## 5. Examples + +**Example 1:** + +``` +Input: [64, 34, 25, 12, 22, 11, 90] +Output: [11, 12, 22, 25, 34, 64, 90] +``` + +**Example 2:** + +``` +Input: [5, 1, 4, 2, 8] +Output: [1, 2, 4, 5, 8] +``` + +## 6. Constraints + +- The array can have any number of elements. +- All elements in the array are integers. + +## 7. Implementation + +## Python + + + + ```python + +def heapify(arr, N, i): +largest = i # Initialize largest as root +l = 2 * i + 1 # left = 2*i + 1 +r = 2 * i + 2 # right = 2*i + 2 + + # See if left child of root exists and is + # greater than root + if l < N and arr[largest] < arr[l]: + largest = l + + # See if right child of root exists and is + # greater than root + if r < N and arr[largest] < arr[r]: + largest = r + + # Change root, if needed + if largest != i: + arr[i], arr[largest] = arr[largest], arr[i] # swap + + # Heapify the root. + heapify(arr, N, largest) + +# The main function to sort an array of given size + +def heapSort(arr): +N = len(arr) + + # Build a maxheap. + for i in range(N//2 - 1, -1, -1): + heapify(arr, N, i) + + # One by one extract elements + for i in range(N-1, 0, -1): + arr[i], arr[0] = arr[0], arr[i] # swap + heapify(arr, i, 0) + + +``` +## C++ + + + + + +```cpp + +#include +using namespace std; +void heapify(int arr[], int N, int i) +{ + int largest = i; + int l = 2 * i + 1; + int r = 2 * i + 2; + + + if (l < N && arr[l] > arr[largest]) + largest = l; + + if (r < N && arr[r] > arr[largest]) + largest = r; + + + if (largest != i) { + swap(arr[i], arr[largest]); + + heapify(arr, N, largest); + } +} + +// Main function to do heap sort +void heapSort(int arr[], int N) +{ + + for (int i = N / 2 - 1; i >= 0; i--) + heapify(arr, N, i); + for (int i = N - 1; i > 0; i--) { + swap(arr[0], arr[i]); + heapify(arr, i, 0); + } +} + +``` +## Java + + + +```java + +public class HeapSort { + public void sort(int arr[]) + { + int N = arr.length; + + // Build heap (rearrange array) + for (int i = N / 2 - 1; i >= 0; i--) + heapify(arr, N, i); + + // One by one extract an element from heap + for (int i = N - 1; i > 0; i--) { + // Move current root to end + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // call max heapify on the reduced heap + heapify(arr, i, 0); + } + } + void heapify(int arr[], int N, int i) + { + int largest = i; // Initialize largest as root + int l = 2 * i + 1; // left = 2*i + 1 + int r = 2 * i + 2; // right = 2*i + 2 + + // If left child is larger than root + if (l < N && arr[l] > arr[largest]) + largest = l; + + // If right child is larger than largest so far + if (r < N && arr[r] > arr[largest]) + largest = r; + + // If largest is not root + if (largest != i) { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + + // Recursively heapify the affected sub-tree + heapify(arr, N, largest); + } + } +} + +``` +## JavaScript + + + + +```javascript +function sort( arr) + { + var N = arr.length; + + // Build heap (rearrange array) + for (var i = Math.floor(N / 2) - 1; i >= 0; i--) + heapify(arr, N, i); + + // One by one extract an element from heap + for (var i = N - 1; i > 0; i--) { + // Move current root to end + var temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // call max heapify on the reduced heap + heapify(arr, i, 0); + } + } + + // To heapify a subtree rooted with node i which is + // an index in arr[]. n is size of heap + function heapify(arr, N, i) + { + var largest = i; // Initialize largest as root + var l = 2 * i + 1; // left = 2*i + 1 + var r = 2 * i + 2; // right = 2*i + 2 + + // If left child is larger than root + if (l < N && arr[l] > arr[largest]) + largest = l; + + // If right child is larger than largest so far + if (r < N && arr[r] > arr[largest]) + largest = r; + + // If largest is not root + if (largest != i) { + var swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + + // Recursively heapify the affected sub-tree + heapify(arr, N, largest); + } + } +```` + + + + +## 8. Complexity Analysis + +- Time Complexity: $O(N log N)$ +- Auxiliary Space: $O(log n)$, due to the recursive call stack. However, auxiliary space can be $O(1)$ for iterative implementation. + +## 9. Advantages and Disadvantages + +**Advantages:** +- **Efficient Time Complexity**: Heap Sort has a time complexity of $O(n log n)$ in all cases. This makes it efficient for sorting large datasets. The log n factor comes from the height of the binary heap, and it ensures that the algorithm maintains good performance even with a large number of elements. +- **Memory Usage** – Memory usage can be minimal (by writing an iterative heapify() instead of a recursive one). So apart from what is necessary to hold the initial list of items to be sorted, it needs no additional memory space to work +- **Simplicity** – It is simpler to understand than other equally efficient sorting algorithms because it does not use advanced computer science concepts such as recursion. + +**Disadvantages:** +- **Costly**: Heap sort is costly as the constants are higher compared to merge sort even if the time complexity is $O(n Log n)$ for both. +- **Unstable**: Heap sort is unstable. It might rearrange the relative order. +- **Efficiency**: Heap Sort is not very efficient when working with highly complex data. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/Heap-sort/) diff --git a/solutions/Sorting-Algorithms/Insertion-Sort.md b/solutions/Sorting-Algorithms/Insertion-Sort.md new file mode 100644 index 0000000..d156b4b --- /dev/null +++ b/solutions/Sorting-Algorithms/Insertion-Sort.md @@ -0,0 +1,192 @@ +--- +id: Insertion-Sort +title: Insertion Sort (Geeks for Geeks) +sidebar_label: Insertion Sort +tags: + - Beginner + - Sorting Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Insertion Sort problem on Geeks for Geeks." +--- + +## 1. What is Insertion Sort? + +Insertion Sort is a simple comparison-based sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. + +## 2. Algorithm for Insertion Sort + +1. Start with the first element (consider it as sorted). +2. Pick the next element. +3. Compare the picked element with the elements in the sorted part of the array. +4. Shift all the elements in the sorted part that are greater than the picked element to one position to their right. +5. Insert the picked element at its correct position. +6. Repeat steps 2-5 until the entire array is sorted. + +## 3. How does Insertion Sort work? + +- Insertion Sort works by dividing the list into a sorted and an unsorted part. +- It iteratively takes one element from the unsorted part and inserts it into the correct position in the sorted part. + +## 4. Problem Description + +Given an array of integers, implement the Insertion Sort algorithm to sort the array in ascending order. + +## 5. Examples + +**Example 1:** +``` +Input: [12, 11, 13, 5, 6] +Output: [5, 6, 11, 12, 13] +``` + +**Example 2:** +``` +Input: [31, 41, 59, 26, 41, 58] +Output: [26, 31, 41, 41, 58, 59] +``` + +**Explanation of Example 1:** +- The initial array is [12, 11, 13, 5, 6]. +- First pass: [11, 12, 13, 5, 6]. +- Second pass: [11, 12, 13, 5, 6]. +- Third pass: [5, 11, 12, 13, 6]. +- Fourth pass: [5, 6, 11, 12, 13]. + +## 6. Constraints + +- $The array can have any number of elements.$ +- $All elements in the array are integers.$ + +## 7. Implementation + + + + + ```python + def insertion_sort(arr): + for i in range(1, len(arr)): + key = arr[i] + j = i - 1 + while j >= 0 and key < arr[j]: + arr[j + 1] = arr[j] + j -= 1 + arr[j + 1] = key + return arr + + # Example usage: + arr = [12, 11, 13, 5, 6] + insertion_sort(arr) + print(arr) + ``` + + + + + ```cpp + #include + #include + + void insertionSort(std::vector& arr) { + int n = arr.size(); + for (int i = 1; i < n; i++) { + int key = arr[i]; + int j = i - 1; + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j--; + } + arr[j + 1] = key; + } + } + + int main() { + std::vector arr = {12, 11, 13, 5, 6}; + insertionSort(arr); + for (int num : arr) + std::cout << num << " "; + return 0; + } + ``` + + + + + ```java + public class InsertionSort { + public static void insertionSort(int[] arr) { + int n = arr.length; + for (int i = 1; i < n; i++) { + int key = arr[i]; + int j = i - 1; + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } + } + + public static void main(String[] args) { + int[] arr = {12, 11, 13, 5, 6}; + insertionSort(arr); + for (int num : arr) + System.out.print(num + " "); + } + } + ``` + + + + + ```javascript + function insertionSort(arr) { + let n = arr.length; + for (let i = 1; i < n; i++) { + let key = arr[i]; + let j = i - 1; + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } + return arr; + } + + // Example usage: + let arr = [12, 11, 13, 5, 6]; + insertionSort(arr); + console.log(arr); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: + - Best case: $O(n)$ (when the array is already sorted) + - Average case: $O(n^2)$ + - Worst case: $O(n^2)$ + +- **Space Complexity**: $O(1)$ (in-place sorting) + +## 9. Advantages and Disadvantages + +**Advantages:** +- Simple to understand and implement. +- Efficient for small datasets. +- Adaptive: Efficient for data sets that are already substantially sorted. + +**Disadvantages:** +- Inefficient for large datasets due to $O(n^2)$ time complexity. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/insertion-sort/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/insertionsort1/problem) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) \ No newline at end of file diff --git a/solutions/Sorting-Algorithms/Merge-Sort.md b/solutions/Sorting-Algorithms/Merge-Sort.md new file mode 100644 index 0000000..c95f24e --- /dev/null +++ b/solutions/Sorting-Algorithms/Merge-Sort.md @@ -0,0 +1,304 @@ +--- +id: Merge-Sort +title: Merge Sort (Geeks for Geeks) +sidebar_label: Merge Sort +tags: + - Beginner + - Sorting Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Merge Sort problem on Geeks for Geeks." +--- + +## 1. What is Merge Sort? + +Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves, calls itself for the two halves, and then merges the two sorted halves. The merge() function is used for merging two halves. The $merge(arr, l, m, r)$ is a key process that assumes that $arr[l..m]$ and $arr[m+1..r]$ are sorted and merges the two sorted sub-arrays into one. + +## 2. Algorithm for Merge Sort + +1. If the array has more than one element: + - Find the middle point to divide the array into two halves. + - Call mergeSort for the first half. + - Call mergeSort for the second half. + - Merge the two halves sorted in the previous steps. + +## 3. How does Merge Sort work? + +- Merge Sort repeatedly divides the array into halves until it can no more be divided. +- It then combines the smaller sorted arrays into larger ones until the whole array is merged and sorted. + +## 4. Problem Description + +Given an array of integers, implement the Merge Sort algorithm to sort the array in ascending order. + +## 5. Examples + +**Example 1:** +``` +Input: [12, 11, 13, 5, 6, 7] +Output: [5, 6, 7, 11, 12, 13] +``` + +**Example 2:** +``` +Input: [38, 27, 43, 3, 9, 82, 10] +Output: [3, 9, 10, 27, 38, 43, 82] +``` +## Your Task: + +You don't need to take the input or print anything. Your task is to complete the function merge() which takes arr[], l, m, r as its input parameters and modifies arr[] in-place such that it is sorted from position l to position r, and function mergeSort() which uses merge() to sort the array in ascending order using merge sort algorithm. + +Expected Time Complexity: $O(nlogn)$ +Expected Auxiliary Space: $O(n)$ + +**Explanation of Example 1:** +- The initial array is $[12, 11, 13, 5, 6, 7]$. +- The array is divided into two halves: $[12, 11, 13] and [5, 6, 7]$. +- The first half $[12, 11, 13]$ is further divided into $[12]$ and $[11, 13]$. +- $[11, 13]$ is divided into $[11]$ and $[13]$, and then merged to $[11, 13]$. +- $[12]$ and $[11, 13]$ are merged to form $[11, 12, 13]$. +- Similarly, $[5, 6, 7]$ is divided and merged to form $[5, 6, 7]$. +- Finally, $[11, 12, 13]$ and $[5, 6, 7]$ are merged to form the sorted array $[5, 6, 7, 11, 12, 13]$. + +## 6. Constraints + +- $1 <= N <= 10^5$ +- $1 <= arr[i] <= 10^5$ + +## 7. Implementation + + + + + ```python + def merge_sort(arr): + if len(arr) > 1: + mid = len(arr) // 2 + L = arr[:mid] + R = arr[mid:] + + merge_sort(L) + merge_sort(R) + + i = j = k = 0 + + while i < len(L) and j < len(R): + if L[i] < R[j]: + arr[k] = L[i] + i += 1 + else: + arr[k] = R[j] + j += 1 + k += 1 + + while i < len(L): + arr[k] = L[i] + i += 1 + k += 1 + + while j < len(R): + arr[k] = R[j] + j += 1 + k += 1 + + # Example usage: + arr = [12, 11, 13, 5, 6, 7] + merge_sort(arr) + print(arr) + ``` + + + + + ```cpp + #include + #include + + void merge(std::vector& arr, int left, int mid, int right) { + int n1 = mid - left + 1; + int n2 = right - mid; + + std::vector L(n1), R(n2); + + for (int i = 0; i < n1; ++i) + L[i] = arr[left + i]; + for (int j = 0; j < n2; ++j) + R[j] = arr[mid + 1 + j]; + + int i = 0, j = 0, k = left; + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { + arr[k] = L[i]; + i++; + } else { + arr[k] = R[j]; + j++; + } + k++; + } + + while (i < n1) { + arr[k] = L[i]; + i++; + k++; + } + + while (j < n2) { + arr[k] = R[j]; + j++; + k++; + } + } + + void mergeSort(std::vector& arr, int left, int right) { + if (left < right) { + int mid = left + (right - left) / 2; + + mergeSort(arr, left, mid); + mergeSort(arr, mid + 1, right); + + merge(arr, left, mid, right); + } + } + + int main() { + std::vector arr = {12, 11, 13, 5, 6, 7}; + mergeSort(arr, 0, arr.size() - 1); + + for (int num : arr) + std::cout << num << " "; + return 0; + } + ``` + + + + + ```java + public class MergeSort { + public static void merge(int[] arr, int left, int mid, int right) { + int n1 = mid - left + 1; + int n2 = right - mid; + + int[] L = new int[n1]; + int[] R = new int[n2]; + + for (int i = 0; i < n1; ++i) + L[i] = arr[left + i]; + for (int j = 0; j < n2; ++j) + R[j] = arr[mid + 1 + j]; + + int i = 0, j = 0, k = left; + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { + arr[k] = L[i]; + i++; + } else { + arr[k] = R[j]; + j++; + } + k++; + } + + while (i < n1) { + arr[k] = L[i]; + i++; + k++; + } + + while (j < n2) { + arr[k] = R[j]; + j++; + k++; + } + } + + public static void mergeSort(int[] arr, int left, int right) { + if (left < right) { + int mid = left + (right - left) / 2; + + mergeSort(arr, left, mid); + mergeSort(arr, mid + 1, right); + + merge(arr, left, mid, right); + } + } + + public static void main(String[] args) { + int[] arr = {12, 11, 13, 5, 6, 7}; + mergeSort(arr, 0, arr.length - 1); + + for (int num : arr) + System.out.print(num + " "); + } + } + ``` + + + + + ```javascript + function merge(left, right) { + let result = []; + let i = 0; + let j = 0; + + while (i < left.length && j < right.length) { + if (left[i] < right[j]) { + result.push(left[i]); + i++; + } else { + result.push(right[j]); + j++; + } + } + + return result.concat(left.slice(i)).concat(right.slice(j)); + } + + function mergeSort(arr) { + if (arr.length <= 1) { + return arr; + } + + const mid = Math.floor(arr.length / 2); + const left = mergeSort(arr.slice(0, mid)); + const right = mergeSort(arr.slice(mid)); + + return merge(left, right); + } + + // Example usage: + const arr = [12, 11, 13, 5, 6, 7]; + console.log(mergeSort(arr)); + ``` + + + +## 8. Complexity Analysis + +- + + **Time Complexity**: $O(n log n)$ in all cases (best, average, and worst) due to the divide and conquer approach. +- **Space Complexity**: $O(n)$ due to the additional arrays used for merging. + +## 9. Advantages and Disadvantages + +**Advantages:** +- Guarantees $O(n log n)$ time complexity for all cases. +- Stable sort (does not change the relative order of equal elements). +- Efficient for large datasets. + +**Disadvantages:** +- Requires $O(n)$ additional space, which can be significant for large arrays. +- The recursive implementation may lead to a large call stack for very large arrays. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/merge-sort/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/merge-sort/problem) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) \ No newline at end of file diff --git a/solutions/Sorting-Algorithms/Odd-even-sort.md b/solutions/Sorting-Algorithms/Odd-even-sort.md new file mode 100644 index 0000000..e277e5c --- /dev/null +++ b/solutions/Sorting-Algorithms/Odd-even-sort.md @@ -0,0 +1,127 @@ +--- +id: Odd-Even-Sort-Algorithm +title: Odd-Even Sort Algorithm +sidebar_label: Odd-Even Sort Algorithm +tags: + - Sorting Algorithms + - Simple + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Odd-Even Sort Algorithm problem." +--- + +## What is the Odd-Even Sort Algorithm? + +Odd-Even Sort, also known as Brick Sort, is a simple comparison-based sorting algorithm. It works by repeatedly comparing and swapping adjacent elements, alternating between odd and even indexed pairs. This process continues until the array is sorted. + +## Algorithm Steps + +1. **Initialize**: + - Start with an unsorted array of elements. + +2. **Odd Phase**: + - Compare all odd-indexed elements with their next even-indexed elements and swap them if necessary. + +3. **Even Phase**: + - Compare all even-indexed elements with their next odd-indexed elements and swap them if necessary. + +4. **Repeat**: + - Continue alternating between the odd and even phases until no swaps are needed in a complete pass through the array. + +## Complexity Analysis + +- **Time Complexity**: The worst-case time complexity is $O(n^2)$, where $n$ is the number of elements in the array. +- **Space Complexity**: The space complexity is $O(1)$ since it is an in-place sorting algorithm. + +## Example + +Given an unsorted array: + +``` +array = [5, 3, 2, 8, 1, 4] +``` + + +Using the Odd-Even Sort Algorithm: + +- Perform the odd and even phases alternately until the array is sorted. + +## Implementation + + + + +```python +def odd_even_sort(arr): + n = len(arr) + is_sorted = False + while not is_sorted: + is_sorted = True + for i in range(1, n-1, 2): + if arr[i] > arr[i + 1]: + arr[i], arr[i + 1] = arr[i + 1], arr[i] + is_sorted = False + for i in range(0, n-1, 2): + if arr[i] > arr[i + 1]: + arr[i], arr[i + 1] = arr[i + 1], arr[i] + is_sorted = False + return arr + +# Example usage: +array = [5, 3, 2, 8, 1, 4] +sorted_array = odd_even_sort(array) +print(sorted_array) # Output: [1, 2, 3, 4, 5, 8] +``` + + + + +```cpp + +#include +#include + +void oddEvenSort(std::vector& arr) { + int n = arr.size(); + bool isSorted = false; + + while (!isSorted) { + isSorted = true; + + for (int i = 1; i <= n - 2; i += 2) { + if (arr[i] > arr[i + 1]) { + std::swap(arr[i], arr[i + 1]); + isSorted = false; + } + } + + for (int i = 0; i <= n - 2; i += 2) { + if (arr[i] > arr[i + 1]) { + std::swap(arr[i], arr[i + 1]); + isSorted = false; + } + } + } +} + +int main() { + std::vector array = {5, 3, 2, 8, 1, 4}; + oddEvenSort(array); + + for (int i : array) { + std::cout << i << " "; + } + std::cout << std::endl; // Output: 1 2 3 4 5 8 + + return 0; +} +``` + + + + +# Conclusion +The Odd-Even Sort Algorithm is a simple and intuitive sorting technique that alternates between comparing odd and even indexed pairs. While it has a quadratic time complexity, it can be useful for small datasets or educational purposes to understand the basics of sorting algorithms. diff --git a/solutions/Sorting-Algorithms/Pigeonhole-Sort.md b/solutions/Sorting-Algorithms/Pigeonhole-Sort.md new file mode 100644 index 0000000..1b4a499 --- /dev/null +++ b/solutions/Sorting-Algorithms/Pigeonhole-Sort.md @@ -0,0 +1,160 @@ +--- +id: Pigeonhole-Sort +title: Pigeonhole Sort (Geeks for Geeks) +sidebar_label: Pigeonhole Sort +tags: + - Beginner + - Sorting Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Pigeonhole Sort problem on Geeks for Geeks." +--- + +## 1. What is Pigeonhole Sort? + +Pigeonhole Sort is a non-comparison-based sorting algorithm that is efficient when the range of possible key values is close to the number of elements to be sorted. It works by placing each element into a corresponding "pigeonhole" based on its value and then collecting the elements in order. + +## 2. Algorithm for Pigeonhole Sort + +1. Find the minimum and maximum values in the array. +2. Calculate the range of values and create an array of pigeonholes. +3. Iterate through the input array and place each element into its corresponding pigeonhole. +4. Collect the elements from the pigeonholes in order, overwriting the original array. + +## 3. How does Pigeonhole Sort work? + +- Pigeonhole Sort distributes the elements into a number of buckets (pigeonholes) equal to the range of values. +- Each element is placed in its respective bucket based on its value. +- The elements are then collected from the buckets in order to produce a sorted array. + +## 4. Problem Description + +Given an array of integers with a known and limited range, implement the Pigeonhole Sort algorithm to sort the array in ascending order. + +## 5. Examples + +**Example 1:** +``` +Input: [8, 3, 2, 7, 4, 6, 8] +Output: [2, 3, 4, 6, 7, 8, 8] +``` + +**Example 2:** +``` +Input: [5, 9, 1, 2, 8, 3, 7, 6, 4] +Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] +``` + +**Explanation of Example 1:** +- The initial array is [8, 3, 2, 7, 4, 6, 8]. +- Create pigeonholes for each value in the range [2, 8]. +- Place each element in its corresponding pigeonhole: + - 8 -> pigeonhole 8 + - 3 -> pigeonhole 3 + - 2 -> pigeonhole 2 + - 7 -> pigeonhole 7 + - 4 -> pigeonhole 4 + - 6 -> pigeonhole 6 + - 8 -> pigeonhole 8 +- Collect the elements from the pigeonholes in order: [2, 3, 4, 6, 7, 8, 8]. + +## 6. Constraints + +- The input array can contain any integers within a known and limited range. +- The size of the array can range from 1 to $10^5$ elements. +- The sorting should be done in-place with O(1) additional space. +- The algorithm should maintain stability, meaning the relative order of equal elements should be preserved. + +### Pigeonhole Sort in Java + +```java +import java.util.Arrays; + +public class PigeonholeSort { + public static void pigeonholeSort(int[] arr) { + int min = Arrays.stream(arr).min().orElse(Integer.MIN_VALUE); + int max = Arrays.stream(arr).max().orElse(Integer.MAX_VALUE); + int range = max - min + 1; + + // Create pigeonholes + int[] holes = new int[range]; + + // Populate the pigeonholes + for (int num : arr) { + holes[num - min]++; + } + + // Collect elements from pigeonholes + int index = 0; + for (int i = 0; i < range; i++) { + while (holes[i]-- > 0) { + arr[index++] = i + min; + } + } + } + + public static void main(String[] args) { + int[] arr = {8, 3, 2, 7, 4, 6, 8}; + pigeonholeSort(arr); + System.out.println(Arrays.toString(arr)); + } +} +``` + +### Pigeonhole Sort in Python + +```python +def pigeonhole_sort(arr): + min_val = min(arr) + max_val = max(arr) + range_of_values = max_val - min_val + 1 + + # Create pigeonholes + holes = [0] * range_of_values + + # Populate the pigeonholes + for num in arr: + holes[num - min_val] += 1 + + # Collect elements from pigeonholes + index = 0 + for i in range(range_of_values): + while holes[i] > 0: + arr[index] = i + min_val + index += 1 + holes[i] -= 1 + +# Example usage +arr = [8, 3, 2, 7, 4, 6, 8] +pigeonhole_sort(arr) +print(arr) +``` + +## 8. Complexity Analysis + +- **Time Complexity**: + - Best case: $O(n + k)$ where $k$ is the range of values (when the array is nearly sorted or uniformly distributed) + - Average case: $O(n + k)$ + - Worst case: $O(n + k)$ (when all elements fall into the same pigeonhole) + +- **Space Complexity**: $O(n + k)$ where $n$ is the number of elements and $k$ is the range of values + +## 9. Advantages and Disadvantages + +**Advantages:** +- Efficient for sorting when the range of possible key values $k$ is not significantly larger than the number of elements $n$. +- Simple to implement and understand. + +**Disadvantages:** +- Space complexity can be an issue for large ranges of values. +- Not suitable for datasets where the range $k$ is much larger than $n$, as it would lead to inefficient memory usage. +- Performs poorly with highly skewed or clustered distributions of elements. + +## 10. References + +- **GFG Article on Pigeonhole Sort:** [Geeks for Geeks Cocktail Sort](https://www.geeksforgeeks.org/pigeonhole-sort/) +- **Wikipedia Article on Pigeonhole Sort:** [Pigeonhole Sort - Wikipedia](https://en.wikipedia.org/wiki/Pigeonhole_sort) diff --git a/solutions/Sorting-Algorithms/Quick-Sort.md b/solutions/Sorting-Algorithms/Quick-Sort.md new file mode 100644 index 0000000..297a815 --- /dev/null +++ b/solutions/Sorting-Algorithms/Quick-Sort.md @@ -0,0 +1,226 @@ +--- +id: Quick-Sort +title: Quick Sort (Geeks for Geeks) +sidebar_label: Quick Sort +tags: + - Beginner + - Sorting Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Quick Sort problem on Geeks for Geeks." +--- + +## 1. What is Quick Sort? + +Quick Sort is a Divide and Conquer algorithm. It picks an element as a pivot and partitions the given array around the picked pivot. There are different versions of Quick Sort that pick the pivot in different ways: +- Always pick the first element as the pivot. +- Always pick the last element as the pivot. +- Pick a random element as the pivot. +- Pick the median as the pivot. + +## 2. Algorithm for Quick Sort + +1. Choose a pivot element from the array. +2. Partition the array into two sub-arrays: elements less than the pivot and elements greater than the pivot. +3. Recursively apply the above steps to the sub-arrays. +4. Combine the results to get the sorted array. + +## 3. How does Quick Sort work? + +- Quick Sort recursively sorts elements before and after partition. +- It selects a pivot and partitions the array such that elements less than the pivot come before it, and elements greater than the pivot come after it. + +## 4. Problem Description + +Given an array of integers, implement the Quick Sort algorithm to sort the array in ascending order. + +## 5. Examples + +**Example 1:** +``` +Input: [10, 7, 8, 9, 1, 5] +Output: [1, 5, 7, 8, 9, 10] +``` + +**Example 2:** +``` +Input: [38, 27, 43, 3, 9, 82, 10] +Output: [3, 9, 10, 27, 38, 43, 82] +``` + +**Explanation of Example 1:** +- The initial array is [10, 7, 8, 9, 1, 5]. +- Select 5 as the pivot. +- Partition the array: [1, 5, 8, 9, 10, 7]. +- Recursively sort the left part [1] and the right part [8, 9, 10, 7]. +- The final sorted array is [1, 5, 7, 8, 9, 10]. + +## 6. Constraints + +- $The array can have any number of elements.$ +- $All elements in the array are integers.$ + +## 7. Implementation + + + + + ```python + def partition(arr, low, high): + pivot = arr[high] + i = low - 1 + for j in range(low, high): + if arr[j] < pivot: + i += 1 + arr[i], arr[j] = arr[j], arr[i] + arr[i + 1], arr[high] = arr[high], arr[i + 1] + return i + 1 + + def quick_sort(arr, low, high): + if low < high: + pi = partition(arr, low, high) + quick_sort(arr, low, pi - 1) + quick_sort(arr, pi + 1, high) + + # Example usage: + arr = [10, 7, 8, 9, 1, 5] + quick_sort(arr, 0, len(arr) - 1) + print(arr) + ``` + + + + + ```cpp + #include + #include + + int partition(std::vector& arr, int low, int high) { + int pivot = arr[high]; + int i = low - 1; + for (int j = low; j < high; j++) { + if (arr[j] < pivot) { + i++; + std::swap(arr[i], arr[j]); + } + } + std::swap(arr[i + 1], arr[high]); + return i + 1; + } + + void quickSort(std::vector& arr, int low, int high) { + if (low < high) { + int pi = partition(arr, low, high); + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } + } + + int main() { + std::vector arr = {10, 7, 8, 9, 1, 5}; + quickSort(arr, 0, arr.size() - 1); + for (int num : arr) + std::cout << num << " "; + return 0; + } + ``` + + + + + ```java + public class QuickSort { + public static int partition(int[] arr, int low, int high) { + int pivot = arr[high]; + int i = (low - 1); + for (int j = low; j < high; j++) { + if (arr[j] < pivot) { + i++; + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + int temp = arr[i + 1]; + arr[i + 1] = arr[high]; + arr[high] = temp; + return i + 1; + } + + public static void quickSort(int[] arr, int low, int high) { + if (low < high) { + int pi = partition(arr, low, high); + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } + } + + public static void main(String[] args) { + int[] arr = {10, 7, 8, 9, 1, 5}; + quickSort(arr, 0, arr.length - 1); + for (int num : arr) + System.out.print(num + " "); + } + } + ``` + + + + + ```javascript + function partition(arr, low, high) { + let pivot = arr[high]; + let i = low - 1; + for (let j = low; j < high; j++) { + if (arr[j] < pivot) { + i++; + [arr[i], arr[j]] = [arr[j], arr[i]]; + } + } + [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]]; + return i + 1; + } + + function quickSort(arr, low, high) { + if (low < high) { + let pi = partition(arr, low, high); + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } + } + + // Example usage: + let arr = [10, 7, 8, 9, 1, 5]; + quickSort(arr, 0, arr.length - 1); + console.log(arr); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: + - Best case: $O(n log n)$ + - Average case: $O(n log n)$ + - Worst case: $O(n^2)$ (occurs when the smallest or largest element is always chosen as the pivot) + +- **Space Complexity**: $O(log n)$ for the recursive stack space. + +## 9. Advantages and Disadvantages + +**Advantages:** +- In-place sorting algorithm. +- Average-case time complexity is $O(n log n)$. + +**Disadvantages:** +- Worst-case time complexity is $O(n^2)$, although this can be mitigated with good pivot selection strategies like randomized or median-of-three. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/quick-sort/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/quicksort1/problem) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) \ No newline at end of file diff --git a/solutions/Sorting-Algorithms/Radix-Sort.md b/solutions/Sorting-Algorithms/Radix-Sort.md new file mode 100644 index 0000000..a9c3902 --- /dev/null +++ b/solutions/Sorting-Algorithms/Radix-Sort.md @@ -0,0 +1,257 @@ +--- +id: Radix-Sort +title: Radix Sort (Geeks for Geeks) +sidebar_label: Radix Sort +tags: + - Intermediate + - Sorting Algorithm + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Radix Sort problem" +--- + +## 1. What is Radix Sort? + +Radix Sort is a non-comparative integer sorting algorithm that sorts numbers by processing individual digits. It processes digits starting from the least significant digit to the most significant digit (LSD Radix Sort). + +## 2. Algorithm for Radix Sort + +1. Find the maximum number in the array to determine the number of digits. +2. Start from the least significant digit and use a stable sorting algorithm to sort the array based on the current digit. +3. Repeat the process for each digit until all digits are processed. + +## 3. How does Radix Sort work? + +- Radix Sort processes each digit of the numbers starting from the least significant digit. +- It uses Counting Sort as a subroutine to sort the digits, ensuring the algorithm remains stable. +- By processing each digit and leveraging the stability of Counting Sort, Radix Sort ensures the overall order is maintained. + +## 4. Problem Description + +Given an array of integers, implement the Radix Sort algorithm to sort the array in ascending order. + +## 5. Examples + +**Example 1:** +Input: [170, 45, 75, 90, 802, 24, 2, 66] +Output: [2, 24, 45, 66, 75, 90, 170, 802] + +**Example 2:** +Input: [3, 6, 9, 1, 4, 7, 8, 2, 5] +Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] + + +## 6. Constraints + +- The array can have any number of elements. +- All elements in the array are non-negative integers. + +## 7. Implementation + + + + +```python + + def counting_sort(arr, exp): + n = len(arr) + output = [0] * n + count = [0] * 10 + + for i in range(n): + index = arr[i] // exp + count[index % 10] += 1 + + for i in range(1, 10): + count[i] += count[i - 1] + + i = n - 1 + while i >= 0: + index = arr[i] // exp + output[count[index % 10] - 1] = arr[i] + count[index % 10] -= 1 + i -= 1 + + for i in range(n): + arr[i] = output[i] + + def radix_sort(arr): + max_val = max(arr) + exp = 1 + while max_val // exp > 0: + counting_sort(arr, exp) + exp *= 10 + return arr + + # Example usage: + arr = [170, 45, 75, 90, 802, 24, 2, 66] + radix_sort(arr) + print(arr) +``` + + + + +```cpp +#include +#include +#include +void countingSort(std::vector& arr, int exp) { +int n = arr.size(); +std::vector output(n); +int count[10] = {0}; +for (int i = 0; i < n; i++) { + int index = (arr[i] / exp) % 10; + count[index]++; +} +for (int i = 1; i < 10; i++) { + count[i] += count[i - 1]; +} + +for (int i = n - 1; i >= 0; i--) { + int index = (arr[i] / exp) % 10; + output[count[index] - 1] = arr[i]; + count[index]--; +} + +for (int i = 0; i < n; i++) { + arr[i] = output[i]; +} +} + +void radixSort(std::vector& arr) { +int maxVal = *max_element(arr.begin(), arr.end()); +for (int exp = 1; maxVal / exp > 0; exp *= 10) { +countingSort(arr, exp); +} +} + +int main() { +std::vector arr = {170, 45, 75, 90, 802, 24, 2, 66}; +radixSort(arr); +for (int num : arr) { +std::cout << num << " "; +} +return 0; +} +``` + + + + + +```java + + import java.util.Arrays; + + public class RadixSort { + public static void countingSort(int[] arr, int exp) { + int n = arr.length; + int[] output = new int[n]; + int[] count = new int[10]; + Arrays.fill(count, 0); + + for (int i = 0; i < n; i++) { + int index = (arr[i] / exp) % 10; + count[index]++; + } + + for (int i = 1; i < 10; i++) { + count[i] += count[i - 1]; + } + + for (int i = n - 1; i >= 0; i--) { + int index = (arr[i] / exp) % 10; + output[count[index] - 1] = arr[i]; + count[index]--; + } + + for (int i = 0; i < n; i++) { + arr[i] = output[i]; + } + } + + public static void radixSort(int[] arr) { + int maxVal = Arrays.stream(arr).max().getAsInt(); + for (int exp = 1; maxVal / exp > 0; exp *= 10) { + countingSort(arr, exp); + } + } + + public static void main(String[] args) { + int[] arr = {170, 45, 75, 90, 802, 24, 2, 66}; + radixSort(arr); + for (int num : arr) { + System.out.print(num + " "); + } + } +} + +``` + + + +```javascript + function countingSort(arr, exp) { + let n = arr.length; + let output = new Array(n).fill(0); + let count = new Array(10).fill(0); + for (let i = 0; i < n; i++) { + let index = Math.floor(arr[i] / exp) % 10; + count[index]++; + } + + for (let i = 1; i < 10; i++) { + count[i] += count[i - 1]; + } + + for (let i = n - 1; i >= 0; i--) { + let index = Math.floor(arr[i] / exp) % 10; + output[count[index] - 1] = arr[i]; + count[index]--; + } + + for (let i = 0; i < n; i++) { + arr[i] = output[i]; + } +} + +function radixSort(arr) { +let maxVal = Math.max(...arr); +for (let exp = 1; Math.floor(maxVal / exp) > 0; exp *= 10) { +countingSort(arr, exp); +} +return arr; +} + +// Example usage: +let arr = [170, 45, 75, 90, 802, 24, 2, 66]; +radixSort(arr); +console.log(arr); +``` + + + + +## 8. Complexity Analysis + +- **Time Complexity**: +- Best case: $O(nk)$ +- Average case: $O(nk)$ +- Worst case: $O(nk)$ +- where n is the number of elements and k is the number of digits in the largest number. + +- **Space Complexity**: $O(n + k)$ + +## 9. Advantages and Disadvantages + +**Advantages:** +- Radix Sort is efficient for sorting large lists of numbers. +- It is not comparison-based and can outperform comparison-based algorithms for large datasets with small keys. + +**Disadvantages:** +- Radix Sort requires additional memory for sorting. +- It is less flexible as it is designed specifically for integers and strings. diff --git a/solutions/Sorting-Algorithms/Selection-Sort.md b/solutions/Sorting-Algorithms/Selection-Sort.md new file mode 100644 index 0000000..3cc14f5 --- /dev/null +++ b/solutions/Sorting-Algorithms/Selection-Sort.md @@ -0,0 +1,193 @@ +--- +id: Selection-Sort +title: Selection Sort (Geeks for Geeks) +sidebar_label: Selection Sort +tags: + - Beginner + - Sorting Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Selection Sort problem on Geeks for Geeks." +--- + +## 1. What is Selection Sort? + +Selection Sort is a simple comparison-based sorting algorithm. It works by dividing the input list into two parts: a sorted sublist of items which is built up from left to right, and a sublist of the remaining unsorted items. The algorithm repeatedly selects the smallest (or largest) element from the unsorted sublist, swaps it with the leftmost unsorted element, and moves the sublist boundaries one element to the right. + +## 2. Algorithm for Selection Sort + +1. Start with the first element as the minimum. +2. Traverse through the list to find the minimum element in the unsorted part. +3. Swap the found minimum element with the first element. +4. Move the boundary of the sorted part one element to the right. +5. Repeat steps 2-4 for all elements in the list until the entire array is sorted. + +## 3. How does Selection Sort work? + +- Selection Sort works by repeatedly finding the minimum element from the unsorted part of the list and placing it at the beginning. +- This process is repeated for each position in the list until it is completely sorted. + +## 4. Problem Description + +Given an array of integers, implement the Selection Sort algorithm to sort the array in ascending order. + +## 5. Examples + +**Example 1:** +``` +Input: [64, 25, 12, 22, 11] +Output: [11, 12, 22, 25, 64] +``` + +**Example 2:** +``` +Input: [29, 10, 14, 37, 13] +Output: [10, 13, 14, 29, 37] +``` + +**Explanation of Example 1:** +- The initial array is [64, 25, 12, 22, 11]. +- First pass: [11, 25, 12, 22, 64]. +- Second pass: [11, 12, 25, 22, 64]. +- Third pass: [11, 12, 22, 25, 64]. +- Continue until the array is sorted: [11, 12, 22, 25, 64]. + +## 6. Constraints + +- $The array can have any number of elements.$ +- $All elements in the array are integers.$ + +## 7. Implementation + + + + + ```python + def selection_sort(arr): + n = len(arr) + for i in range(n): + min_idx = i + for j in range(i + 1, n): + if arr[j] < arr[min_idx]: + min_idx = j + arr[i], arr[min_idx] = arr[min_idx], arr[i] + return arr + + # Example usage: + arr = [64, 25, 12, 22, 11] + selection_sort(arr) + print(arr) + ``` + + + + + ```cpp + #include + #include + + void selectionSort(std::vector& arr) { + int n = arr.size(); + for (int i = 0; i < n - 1; i++) { + int min_idx = i; + for (int j = i + 1; j < n; j++) { + if (arr[j] < arr[min_idx]) { + min_idx = j; + } + } + std::swap(arr[min_idx], arr[i]); + } + } + + int main() { + std::vector arr = {64, 25, 12, 22, 11}; + selectionSort(arr); + for (int num : arr) + std::cout << num << " "; + return 0; + } + ``` + + + + + ```java + public class SelectionSort { + public static void selectionSort(int[] arr) { + int n = arr.length; + for (int i = 0; i < n - 1; i++) { + int min_idx = i; + for (int j = i + 1; j < n; j++) { + if (arr[j] < arr[min_idx]) { + min_idx = j; + } + } + int temp = arr[min_idx]; + arr[min_idx] = arr[i]; + arr[i] = temp; + } + } + + public static void main(String[] args) { + int[] arr = {64, 25, 12, 22, 11}; + selectionSort(arr); + for (int num : arr) + System.out.print(num + " "); + } + } + ``` + + + + + ```javascript + function selectionSort(arr) { + let n = arr.length; + for (let i = 0; i < n - 1; i++) { + let min_idx = i; + for (let j = i + 1; j < n; j++) { + if (arr[j] < arr[min_idx]) { + min_idx = j; + } + } + [arr[i], arr[min_idx]] = [arr[min_idx], arr[i]]; + } + return arr; + } + + // Example usage: + let arr = [64, 25, 12, 22, 11]; + selectionSort(arr); + console.log(arr); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: + - Best case: $O(n^2)$ + - Average case: $O(n^2)$ + - Worst case: $O(n^2)$ + +- **Space Complexity**: $O(1)$ (in-place sorting) + +## 9. Advantages and Disadvantages + +**Advantages:** +- Simple to understand and implement. +- Performs well on small datasets. + +**Disadvantages:** +- Inefficient for large datasets due to $O(n^2)$ time complexity. +- Does not adapt to the existing order of elements. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/selection-sort/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/insertionsort1/problem) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) \ No newline at end of file diff --git a/solutions/Sorting-Algorithms/Shell-Sort.md b/solutions/Sorting-Algorithms/Shell-Sort.md new file mode 100644 index 0000000..a48c202 --- /dev/null +++ b/solutions/Sorting-Algorithms/Shell-Sort.md @@ -0,0 +1,194 @@ +--- +id: Shell-Sort +title: Shell Sort (Geeks for Geeks) +sidebar_label: Shell Sort +tags: + - Beginner + - Sorting Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Shell Sort problem on Geeks for Geeks." +--- + +## 1. What is Shell Sort? + +Shell Sort is an in-place comparison-based sorting algorithm. It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort). The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared. + +## 2. Algorithm for Shell Sort + +1. Start with a large gap between elements and reduce the gap until there is no gap. +2. Perform a gapped insertion sort for each gap size. The algorithm uses insertion sort to sort elements that are a certain gap distance apart. +3. Reduce the gap and repeat the process until the gap becomes zero. + +## 3. How does Shell Sort work? + +- Shell Sort works by comparing elements that are far apart, then progressively reducing the gap between elements. +- This allows elements to move quickly towards their correct position. + +## 4. Problem Description + +Given an array of integers, implement the Shell Sort algorithm to sort the array in ascending order. + +## 5. Examples + +**Example 1:** +``` +Input: [12, 34, 54, 2, 3] +Output: [2, 3, 12, 34, 54] +``` + +**Example 2:** +``` +Input: [37, 45, 29, 8, 12, 88, -3] +Output: [-3, 8, 12, 29, 37, 45, 88] +``` + +**Explanation of Example 1:** +- The initial array is [12, 34, 54, 2, 3]. +- With a gap of 2, the array becomes [12, 34, 2, 3, 54]. +- With a gap of 1, the array becomes [2, 3, 12, 34, 54]. + +## 6. Constraints + +- $The array can have any number of elements.$ +- $All elements in the array are integers.$ + +## 7. Implementation + + + + + ```python + def shell_sort(arr): + n = len(arr) + gap = n // 2 + while gap > 0: + for i in range(gap, n): + temp = arr[i] + j = i + while j >= gap and arr[j - gap] > temp: + arr[j] = arr[j - gap] + j -= gap + arr[j] = temp + gap //= 2 + return arr + + # Example usage: + arr = [12, 34, 54, 2, 3] + shell_sort(arr) + print(arr) + ``` + + + + + ```cpp + #include + #include + + void shellSort(std::vector& arr) { + int n = arr.size(); + for (int gap = n / 2; gap > 0; gap /= 2) { + for (int i = gap; i < n; i++) { + int temp = arr[i]; + int j; + for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) { + arr[j] = arr[j - gap]; + } + arr[j] = temp; + } + } + } + + int main() { + std::vector arr = {12, 34, 54, 2, 3}; + shellSort(arr); + for (int num : arr) + std::cout << num << " "; + return 0; + } + ``` + + + + + ```java + public class ShellSort { + public static void shellSort(int[] arr) { + int n = arr.length; + for (int gap = n / 2; gap > 0; gap /= 2) { + for (int i = gap; i < n; i++) { + int temp = arr[i]; + int j; + for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) { + arr[j] = arr[j - gap]; + } + arr[j] = temp; + } + } + } + + public static void main(String[] args) { + int[] arr = {12, 34, 54, 2, 3}; + shellSort(arr); + for (int num : arr) + System.out.print(num + " "); + } + } + ``` + + + + + ```javascript + function shellSort(arr) { + let n = arr.length; + for (let gap = Math.floor(n / 2); gap > 0; gap = Math.floor(gap / 2)) { + for (let i = gap; i < n; i++) { + let temp = arr[i]; + let j; + for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) { + arr[j] = arr[j - gap]; + } + arr[j] = temp; + } + } + return arr; + } + + // Example usage: + let arr = [12, 34, 54, 2, 3]; + shellSort(arr); + console.log(arr); + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity**: + - Best case: $O(n log n)$ + - Average case: $O(n^(3/2))$ + - Worst case: $O(n^2)$ + +- **Space Complexity**: $O(1)$ (in-place sorting) + +## 9. Advantages and Disadvantages + +**Advantages:** +- More efficient than bubble sort and insertion sort for large lists. +- Simple to understand and implement. + +**Disadvantages:** +- More complex than bubble sort and insertion sort. +- The performance depends on the gap sequence used. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/shellsort/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/sorting/problem) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) diff --git a/solutions/Sorting-Algorithms/Stooge-Sort.md b/solutions/Sorting-Algorithms/Stooge-Sort.md new file mode 100644 index 0000000..8ccf610 --- /dev/null +++ b/solutions/Sorting-Algorithms/Stooge-Sort.md @@ -0,0 +1,124 @@ +--- +id: Stooge-Sort-Algorithm +title: Stooge Sort Algorithm +sidebar_label: Stooge Sort Algorithm +tags: + - Sorting Algorithms + - Simple + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Stooge Sort Algorithm problem." +--- + +## What is the Stooge Sort Algorithm? + +Stooge Sort is a simple and recursive sorting algorithm. It is known for its high time complexity and is mostly used for educational purposes to understand recursive sorting techniques. + +## Algorithm Steps + +1. **Base Case**: + - If the array has only one element or the first element is less than or equal to the last element, return. + +2. **Swapping**: + - If the first element is greater than the last element, swap them. + +3. **Recursive Sort**: + - Recursively sort the first two-thirds of the array. + - Recursively sort the last two-thirds of the array. + - Recursively sort the first two-thirds of the array again. + +## Complexity Analysis + +- **Time Complexity**: $O(n^{\log_3 2})$ which is approximately $O(n^{2.7095})$. +- **Space Complexity**: $O(n)$ due to the recursive call stack. + +## Example + +Given an unsorted array: + +``` +array = [4, 3, 2, 1] +``` + + +Using the Stooge Sort Algorithm: + +- Sort the first two-thirds: `[4, 3, 2]` -> `[3, 4, 2]` -> `[3, 2, 4]` -> `[2, 3, 4]` +- Sort the last two-thirds: `[3, 2, 1]` -> `[2, 1, 3]` -> `[1, 2, 3]` +- Sort the first two-thirds again: `[4, 3, 2]` -> `[3, 4, 2]` -> `[3, 2, 4]` -> `[2, 3, 4]` +- The array becomes `[1, 2, 3, 4]`. + +## Implementation + + + + +```python +def stooge_sort(arr, l, h): + if l >= h: + return + + # Swap if the first element is greater than the last element + if arr[l] > arr[h]: + arr[l], arr[h] = arr[h], arr[l] + + # Recursively sort the first two-thirds, last two-thirds, and first two-thirds again + if h - l + 1 > 2: + t = (h - l + 1) // 3 + stooge_sort(arr, l, h - t) + stooge_sort(arr, l + t, h) + stooge_sort(arr, l, h - t) + +# Example usage: +array = [4, 3, 2, 1] +stooge_sort(array, 0, len(array) - 1) +print(array) # Output: [1, 2, 3, 4] +``` + + + + +```cpp + +#include +#include + +void stoogeSort(std::vector& arr, int l, int h) { + if (l >= h) + return; + + // Swap if the first element is greater than the last element + if (arr[l] > arr[h]) { + std::swap(arr[l], arr[h]); + } + + // Recursively sort the first two-thirds, last two-thirds, and first two-thirds again + if (h - l + 1 > 2) { + int t = (h - l + 1) / 3; + stoogeSort(arr, l, h - t); + stoogeSort(arr, l + t, h); + stoogeSort(arr, l, h - t); + } +} + +int main() { + std::vector array = {4, 3, 2, 1}; + stoogeSort(array, 0, array.size() - 1); + + for (int num : array) { + std::cout << num << " "; + } + std::cout << std::endl; // Output: 1 2 3 4 + + return 0; +} +``` + + + + +## Conclusion +Stooge Sort is a straightforward but inefficient sorting algorithm. It is not practical for large datasets due to its high time complexity but can be useful for educational purposes to understand recursive sorting techniques. diff --git a/solutions/Sorting-Algorithms/Topological-sort.md b/solutions/Sorting-Algorithms/Topological-sort.md new file mode 100644 index 0000000..69e51aa --- /dev/null +++ b/solutions/Sorting-Algorithms/Topological-sort.md @@ -0,0 +1,264 @@ +--- +id: Topological-Sort +title: Topological Sort (Geeks for Geeks) +sidebar_label: Topological Sort +tags: + - Intermediate + - Sorting Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Topological Sort problem on Geeks for Geeks." +--- + +## 1. What is Topological Sort? + +Topological Sort is a linear ordering of vertices in a Directed Acyclic Graph (DAG) such that for every directed edge `u -> v`, vertex `u` comes before `v` in the ordering. + +## 2. Algorithm for Topological Sort + +1. Identify vertices with no incoming edges (indegree 0). +2. Remove these vertices and their outgoing edges from the graph. +3. Repeat steps 1 and 2 until all vertices are removed. +4. If the graph has a cycle, topological sort is not possible. + +## 3. How does Topological Sort work? + +- It repeatedly removes nodes with no incoming edges, adding them to the sorted list. +- It ensures that each node is processed only after all its dependencies are processed. + +## 4. Problem Description + +Given a Directed Acyclic Graph (DAG), implement the Topological Sort algorithm to order the vertices. + +## 5. Examples + +**Example 1:** +``` +Input: Graph with edges [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)] +Output: [5, 4, 2, 3, 1, 0] or [4, 5, 2, 3, 1, 0] +``` + + +**Example 2:** +``` +Input: Graph with edges [(1, 2), (2, 3), (3, 4)] +Output: [1, 2, 3, 4] +``` + + +**Explanation of Example 1:** +- The graph can be visualized as: +``` +5 β†’ 2 β†’ 3 β†’ 1 +5 β†’ 0 +4 β†’ 0 +4 β†’ 1 +``` +- One valid topological ordering is [5, 4, 2, 3, 1, 0]. + +## 6. Constraints + +- The graph must be a Directed Acyclic Graph (DAG). + +## 7. Implementation + +**Python** +```python +from collections import defaultdict, deque + +def topological_sort(vertices, edges): + graph = defaultdict(list) + indegree = {i: 0 for i in range(vertices)} + + for u, v in edges: + graph[u].append(v) + indegree[v] += 1 + + queue = deque([v for v in range(vertices) if indegree[v] == 0]) + topo_order = [] + + while queue: + node = queue.popleft() + topo_order.append(node) + for neighbor in graph[node]: + indegree[neighbor] -= 1 + if indegree[neighbor] == 0: + queue.append(neighbor) + + if len(topo_order) == vertices: + return topo_order + else: + return [] +``` +**C++** + + + ```cpp + #include + #include + #include + + void topologicalSort(int vertices, const std::vector>& edges) { + std::vector indegree(vertices, 0); + std::vector> graph(vertices); + + // Build the graph and compute indegrees of all vertices + for (const auto& edge : edges) { + graph[edge.first].push_back(edge.second); + indegree[edge.second]++; + } + + std::queue q; + // Enqueue all vertices with indegree 0 + for (int i = 0; i < vertices; i++) { + if (indegree[i] == 0) { + q.push(i); + } + } + + std::vector topo_order; + while (!q.empty()) { + int node = q.front(); + q.pop(); + topo_order.push_back(node); + + // Reduce the indegree of the neighbors + for (int neighbor : graph[node]) { + indegree[neighbor]--; + if (indegree[neighbor] == 0) { + q.push(neighbor); + } + } + } + + // Check if there was a cycle + if (topo_order.size() == vertices) { + for (int node : topo_order) { + std::cout << node << " "; + } + } else { + std::cout << "Cycle detected, topological sort not possible."; + } +} + +int main() { + int vertices = 6; + std::vector> edges = {{5, 2}, {5, 0}, {4, 0}, {4, 1}, {2, 3}, {3, 1}}; + topologicalSort(vertices, edges); + return 0; +} + +``` + +**Java** + +```java +import java.util.*; + +public class TopologicalSort { + public static List topologicalSort(int vertices, int[][] edges) { + List> graph = new ArrayList<>(); + int[] indegree = new int[vertices]; + for (int i = 0; i < vertices; i++) { + graph.add(new ArrayList<>()); + } + + for (int[] edge : edges) { + graph.get(edge[0]).add(edge[1]); + indegree[edge[1]]++; + } + + Queue queue = new LinkedList<>(); + for (int i = 0; i < vertices; i++) { + if (indegree[i] == 0) { + queue.add(i); + } + } + + List topo_order = new ArrayList<>(); + while (!queue.isEmpty()) { + int node = queue.poll(); + topo_order.add(node); + for (int neighbor : graph.get(node)) { + indegree[neighbor]--; + if (indegree[neighbor] == 0) { + queue.add(neighbor); + } + } + } + + if (topo_order.size() == vertices) { + return topo_order; + } else { + return Collections.emptyList(); // Cycle detected + } + } +``` + +**JavaScript** + +```javascript + function topologicalSort(vertices, edges) { + let graph = Array.from({ length: vertices }, () => []); + let indegree = Array(vertices).fill(0); + for (let [u, v] of edges) { + graph[u].push(v); + indegree[v]++; + } + + let queue = []; + for (let i = 0; i < vertices; i++) { + if (indegree[i] === 0) { + queue.push(i); + } + } + + let topoOrder = []; + while (queue.length > 0) { + let node = queue.shift(); + topoOrder.push(node); + + for (let neighbor of graph[node]) { + indegree[neighbor]--; + if (indegree[neighbor] === 0) { + queue.push(neighbor); + } + } + } + + return topoOrder.length === vertices ? topoOrder : []; // Return empty array if cycle detected +} + +``` + +## 8. Complexity Analysis + +- **Time Complexity**: +- Best case: $O(V + E)$ +- Average case: $O(V + E)$ +- Worst case: $O(V + E)$ + +- **Space Complexity**: $O(V + E)$ (for the graph representation and auxiliary data structures) + +## 9. Advantages and Disadvantages + +**Advantages:** +- Provides a linear ordering of vertices in a DAG. +- Useful in scenarios such as task scheduling, resolving symbol dependencies in linkers, etc. + +**Disadvantages:** +- Not applicable if the graph contains cycles. +- Requires graph to be a DAG. + +## 10. References + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/topological-sorting/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/torque-and-development/problem) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) + + + diff --git a/solutions/Sorting-Algorithms/Tree-Sort.md b/solutions/Sorting-Algorithms/Tree-Sort.md new file mode 100644 index 0000000..b5ebf23 --- /dev/null +++ b/solutions/Sorting-Algorithms/Tree-Sort.md @@ -0,0 +1,177 @@ +-- +id: Tree-Sort +title: Tree Sort (Geeks for Geeks) +sidebar_label: Tree Sort +tags: + - Intermediate + - Sorting Algorithms + - Geeks for Geeks + - CPP + - Python + - Java + - JavaScript + - DSA +description: "This is a solution to the Tree Sort problem on Geeks for Geeks." +--- + +## 1. What is Tree Sort? + +Tree Sort is a sorting algorithm that uses a Binary Search Tree (BST) to sort elements. The elements are inserted into a BST and then an in-order traversal is performed to retrieve them in sorted order. + +## 2. Algorithm for Tree Sort + +1. Create an empty Binary Search Tree (BST). +2. Insert all elements from the array into the BST. +3. Perform an in-order traversal of the BST to retrieve the elements in sorted order. + +## 3. How does Tree Sort work? + +- Each element from the array is inserted into a BST. +- During the in-order traversal of the BST, elements are retrieved in ascending order because the left subtree is visited first, followed by the root, and then the right subtree. + +## 4. Problem Description + +Given an array of integers, implement the Tree Sort algorithm to sort the array. + +## 5. Examples + +**Example 1:** + +``` +Input: [10, 7, 8, 9, 1, 5] +Output: [1, 5, 7, 8, 9, 10] +``` + +**Example 2:** +``` +Input: [38, 27, 43, 3, 9, 82, 10] +Output: [3, 9, 10, 27, 38, 43, 82] + +``` + +## 6. Constraints + +- The array should contain at least one element. + +## 7. Implementation + +**Python** +```python +class TreeNode: + def __init__(self, key): + self.left = None + self.right = None + self.val = key + +def insert(root, key): + if root is None: + return TreeNode(key) + else: + if key < root.val: + root.left = insert(root.left, key) + else: + root.right = insert(root.right, key) + return root + +def inorder_traversal(root, res): + if root: + inorder_traversal(root.left, res) + res.append(root.val) + inorder_traversal(root.right, res) + +def tree_sort(arr): + if not arr: + return [] + root = TreeNode(arr[0]) + for key in arr[1:]: + insert(root, key) + sorted_array = [] + inorder_traversal(root, sorted_array) + return sorted_array + +``` +```java +import java.util.*; + +class TreeNode { + int val; + TreeNode left, right; + TreeNode(int item) { + val = item; + left = right = null; + } +} + +public class TreeSort { + TreeNode root; + + void insert(int key) { + root = insertRec(root, key); + } + + TreeNode insertRec(TreeNode root, int key) { + if (root == null) { + root = new TreeNode(key); + return root; + } + if (key < root.val) { + root.left = insertRec(root.left, key); + } else if (key > root.val) { + root.right = insertRec(root.right, key); + } + return root; + } + + void inorderRec(TreeNode root, List res) { + if (root != null) { + inorderRec(root.left, res); + res.add(root.val); + inorderRec(root.right, res); + } + } + + public static List treeSort(int[] arr) { + TreeSort tree = new TreeSort(); + for (int num : arr) { + tree.insert(num); + } + List sortedArray = new ArrayList<>(); + tree.inorderRec(tree.root, sortedArray); + return sortedArray; + } + + public static void main(String[] args) { + int[] arr = {5, 1, 4, 2, 8, 0, 2}; + List sortedArr = treeSort(arr); + for (int num : sortedArr) { + System.out.print(num + " "); + } + } +} + +``` + +## 8. Complexity Analysis + +- **Time Complexity**: + -Best case: $O(n \log n)$ (balanced BST) +Average case: $O(n \log n)$ (balanced BST) +Worst case: $O(n^2)$ (unbalanced BST) + +- **Space Complexity**: $O(n)$ (for the BST and recursion stack) + +## 9. Advantages and Disadvantages + +**Advantages:** +- Can achieve $O(n \log n)$ time complexity if the BST remains balanced. +- Simple to understand and implement. + +**Disadvantages:** +- In the worst case (unbalanced BST), the time complexity degrades to $O(n^2)$. +- Requires additional memory for the tree structure, which is $O(n)$. +- The bidirectional approach does not significantly improve performance for most input cases. + +## 10. References + +- **GFG Article on Tree Sort:** [Geeks for Geeks Counting Sort](https://www.geeksforgeeks.org/cartesian-tree-sorting/) +- **Wikipedia Article on Tree Sort:** [Counting Sort - Wikipedia](https://en.wikipedia.org/wiki/Tree_sort) diff --git a/solutions/gfg-solutions/0001-Matchstick-Game.md b/solutions/gfg-solutions/0001-Matchstick-Game.md new file mode 100644 index 0000000..a024696 --- /dev/null +++ b/solutions/gfg-solutions/0001-Matchstick-Game.md @@ -0,0 +1,181 @@ +--- + +id: matchsticks-game +title: Matchsticks Game +sidebar_label: 0001-Matchsticks Game +tags: + - Game Theory + - Mathematics + - Strategy + - Python + - JavaScript + - TypeScript + - Java + - C++ +description: "This is a solution to the problem of determining the number of matchsticks the first player should pick to guarantee a win in the matchsticks game." + +--- + +In this page, we will solve the problem of determining the number of matchsticks the first player should pick to guarantee a win in the matchsticks game using different approaches. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, and C++. + +## Problem Description + +Two friends, A and B, are playing the game of matchsticks. In this game, a group of N matchsticks is placed on the table. The players can pick any number of matchsticks from 1 to 4 (both inclusive) during their chance. The player who takes the last matchstick wins the game. If A starts first, how many matchsticks should he pick on his first turn such that he is guaranteed to win the game, or determine if it's impossible for him to win. Return -1 if it's impossible for A to win the game, else return the number of matchsticks he should pick on his first turn to guarantee a win. Note: Consider both A and B play the game optimally. + +### Examples + +**Example 1:** + +```plaintext +Input: +N = 48 +Output: +3 +Explanation: +Player A is guaranteed a win if he picks 3 matchsticks first. +``` + +**Example 2:** + +```plaintext +Input: +N = 15 +Output: +-1 +Explanation: +Player A is guaranteed a loss no matter how many matches he picks at first. +``` + +### Constraints + +- `1 <= N <= 10^18` + +--- + +## Solution for Matchsticks Game Problem + +### Intuition and Approach + +The problem can be solved using game theory and mathematical analysis. The key insight is to notice the pattern based on the modulo operation. + +When A starts the game, he needs to ensure that after his turn, the number of matchsticks left is such that B cannot force a win. This means A needs to leave B with a number of matchsticks that is a multiple of 5, because if $( N \% 5 = 0 )$, B will always have the advantage. Therefore, A's winning strategy is based on the remainder when $( N )$ is divided by 5. + +- If $( N \% 5 = 0 )$, then no matter how many matchsticks A picks (1 to 4), B can always pick a number of matchsticks to maintain the advantage and eventually win. Hence, it's impossible for A to guarantee a win, and the answer is -1. +- If $( N \% 5 \neq 0 )$, A should pick $( N \% 5 )$ matchsticks to leave B with a multiple of 5 matchsticks, ensuring A's winning position. + + + + + +### Approach: Game Theory + +The key observation is that if the number of matchsticks \( N \) modulo 5 is 0, then player A will lose if both players play optimally. Otherwise, player A can always pick \( N \% 5 \) matchsticks to ensure a win. + +#### Implementation + +```jsx live +function matchGame() { + const N = 48; + + const matchGame = (N) => { + return N % 5 === 0 ? -1 : N % 5; + }; + + const result = matchGame(N); + return ( +
+

+ Input: N = {N} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function matchGame(N) { + return N % 5 === 0 ? -1 : N % 5; + } + + + ``` + + + + + ```typescript + function matchGame(N: number): number { + return N % 5 === 0 ? -1 : N % 5; + } + + + ``` + + + + + ```python + def matchGame(N): + return -1 if N % 5 == 0 else N % 5 + + ``` + + + + + ```java + public class Solution { + public int matchGame(long N) { + return N % 5 == 0 ? -1 : (int)(N % 5); + } + + + } + ``` + + + + + ```cpp + #include + + using namespace std; + + int matchGame(long long N) { + return N % 5 == 0 ? -1 : N % 5; + } + + + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(1)$$ +- Space Complexity: $$O(1)$$ + +
+
+ +:::tip +The key insight is recognizing the modulo operation's role in determining the game's outcome. +::: + +## References + +- **GeeksforGeeks Problem:** [GeeksforGeeks Problem](https://www.geeksforgeeks.org/problems/-matchsticks-game4906/0) +- **GeeksforGeeks Problem:** [GeeksforGeeks solution](https://www.geeksforgeeks.org/problems/-matchsticks-game4906/0) +- **Solution Author:** [Manish Kumar Gupta](https://www.geeksforgeeks.org/user/manishd5hla) + +--- + diff --git a/solutions/gfg-solutions/0001-value-equal-to-index-value.md b/solutions/gfg-solutions/0001-value-equal-to-index-value.md new file mode 100644 index 0000000..3d35d9d --- /dev/null +++ b/solutions/gfg-solutions/0001-value-equal-to-index-value.md @@ -0,0 +1,124 @@ +--- +id: value-equal-to-index-value +title: Value Equal to Index Value Problem (Geeks for Geeks) +sidebar_label: 0001 - Value Equal to Index Value +tags: + - Beginner + - Index Values + - Array + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Value Equal to Index Value problem on Geeks for Geeks." +--- + +## Problem Description + +Given an array Arr of N positive integers. Your task is to find the elements whose value is equal to that of its index value (Consider 1-based indexing). + +Note: There can be more than one element in the array which have the same value as its index. You need to include every such element's index. Follows 1-based indexing of the array. + +## Examples + +Example 1: + +``` +Input: +N = 5 +Arr[] = {15, 2, 45, 12, 7} +Output: 2 +Explanation: Only Arr[2] = 2 exists here. +``` + +Example 2: + +``` +Input: +N = 1 +Arr[] = {1} +Output: 1 +Explanation: Here Arr[1] = 1 exists. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function valueEqualToIndex() which takes the array of integers arr[] and n as parameters and returns an array of indices where the given conditions are satisfied. When there is no such element exists then return an empty array of length 0. For C users, you need to modify the array(arr), in place such that the indices not in the final answer should be marked 0. + +## Constraints + +* `1 ≀ N ≀ 105` +* `1 ≀ Arr[i] ≀ 106` + +## Problem Explanation + +The problem involves finding elements in an array whose values match their index positions, considering 1-based indexing. This means if an element's value matches its position in the array when counting from 1 (not 0), it should be included in the result. + +Example: + +* Given an array [15, 2, 45, 12, 7]: + - At 1-based index 1, the value is 15 (not equal to 1) + - At 1-based index 2, the value is 2 (equal to 2) + - At 1-based index 3, the value is 45 (not equal to 3) + - At 1-based index 4, the value is 12 (not equal to 4) + - At 1-based index 5, the value is 7 (not equal to 5) + +The only element that matches its index is 2 at index 2. + +## Python Solution Code + +```py +class Solution: + + def valueEqualToIndex(self, arr, n): + result = [] + for i in range(n): + if (arr[i] == i + 1): + result.append(arr[i]); + return result +``` + +## C++ Solution Code + +```cpp +class Solution { + public: + vector valueEqualToIndex(int arr[], int n) { + vector result; + for(int i = 0; i < n; i++) { + if(arr[i] == i + 1) + result.push_back(arr[i]); + } return result; + } +}; +``` + +## Solution Logic + +1. Initialize an empty result list: This will store the elements that satisfy the condition. +2. Iterate through the array: Use a loop to go through each element in the array. +3. Check the condition: For each element, check if the element's value matches its 1-based index. Since array indexing typically starts at 0 in most programming languages, you adjust by adding 1 to the index. +4. Store matching elements: If an element's value matches its 1-based index, add it to the result list. +5. Return the result list: After checking all elements, return the list of elements that met the condition. + +## Example Walkthrough + +For the array `[15, 2, 45, 12, 7]` with length `n = 5`: + +* Initialize an empty list: `result = []` +* Loop through the array with indices from 0 to 4: + - Check element at index 0 (1-based index 1): 15 β‰  1 + - Check element at index 1 (1-based index 2): 2 = 2 (add to result) + - Check element at index 2 (1-based index 3): 45 β‰  3 + - Check element at index 3 (1-based index 4): 12 β‰  4 + - Check element at index 4 (1-based index 5): 7 β‰  5 + +Final `result` list: `[2]` + +## Time Complexity + +The time complexity of this solution is $O(N)$ where N is the number of elements in the array. This is because the solution involves a single pass through the array to check each element against its 1-based index. + +## Space Complexity + +The space complexity is $O(1)$ for the input space, and $O(K)$ for the output space, where K is the number of elements matching the condition. In the worst case, if all elements match, the space used by the result list will be $O(N)$. \ No newline at end of file diff --git a/solutions/gfg-solutions/0002-fascinating-number.md b/solutions/gfg-solutions/0002-fascinating-number.md new file mode 100644 index 0000000..77c3646 --- /dev/null +++ b/solutions/gfg-solutions/0002-fascinating-number.md @@ -0,0 +1,144 @@ +--- +id: fascinating-number +title: Fascinating Number Problem (Geeks for Geeks) +sidebar_label: 0002 - Fascinating Number +tags: + - Beginner + - String + - Find + - Multiplication + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Fascinating Number problem on Geeks for Geeks." +--- + +This tutorial contains a complete walk-through of the Fascinating Number problem from the Geeks for Geeks website. It features the implementation of the solution code in two programming languages: Python and C++. + +## Problem Description + +Given a number N. Your task is to check whether it is fascinating or not. + +Fascinating Number: When a number(should contain 3 digits or more) is multiplied by 2 and 3, and when both these products are concatenated with the original number, then it results in all digits from 1 to 9 present exactly once. + +## Examples + +**Example 1:** + +``` +Input: N = 192 +Output: Fascinating +Explanation: After multiplication with 2 and 3, and concatenating with original number, number will become 192384576 which contains all digits from 1 to 9. +``` + +**Example 2:** + +``` +Input: N = 853 +Output: Not Fascinating +Explanation: It's not a fascinating number. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `fascinating()` which takes the integer n parameters and returns boolean (True or False) denoting the answer. + +Expected Time Complexity: $O(1)$ +Expected Auxiliary Space: $O(1)$ + +## Constraints + +`100 <= N <= 2*10^9` + +## Problem Explanation + +The problem is to determine if a given number N is a fascinating number. A fascinating number is defined as follows: + +1. The number must have at least three digits. +2. Multiply the number by 2 and 3 to get two products. +3. Concatenate the original number, the product of the number and 2, and the product of the number and 3 into a single string. +4. The concatenated string should contain all digits from 1 to 9 exactly once, with no other digits present (e.g., no zeros). + +## Code Implementation + + + + + ```py + class Solution: + + def fascinating(self, n): + m2 = n * 2 + m3 = n * 3 + num = str(n) + str(m2) + str(m3) + num = "".join(sorted(num)) + zero_count = num.count("0") + if (num.find("123456789") == -1): + return False + elif (len(num) - zero_count > 9): + return False + else: + return True + ``` + + + + + + ```cpp + class Solution { + public: + bool fascinating(int n) { + int m2 = n * 2; + int m3 = n * 3; + string num = to_string(n) + to_string(m2) + to_string(m3); + sort(num.begin(), num.end()); + if (num.find("123456789") == string::npos) + return false; + else if (num.length() - num.find("123456789") > 9) + return false; + else return true; + } +}; +``` + + + + + +## Example Walkthrough + +For N = 192: +1. Original number: 192 +2. Multiply by 2: 192 Γ— 2 = 384 +3. Multiply by 3: 192 Γ— 3 = 576 +4. Concatenate: "192" + "384" + "576" = "192384576" +5. Check if the concatenated string contains all digits from 1 to 9 exactly once: "192384576" contains each digit from 1 to 9 exactly once. + +Therefore, 192 is a fascinating number. + +## Solution Logic: + +1. Compute the Products: Multiply the number N by 2 and 3 to get two new numbers. +2. Concatenate the Results: Convert the original number and the two products to strings and concatenate them. +3. Sort and Check Digits: Sort the concatenated string and check if it contains the sequence "123456789" exactly once. +4. Verify Length: Ensure there are no extra digits (like zero or repetitions). The total length of digits should be exactly 9, excluding any zeros. + +## Time Complexity + +The time complexity is $O(1)$ because the operations involve a fixed number of steps regardless of the size of N: + +* Multiplication and string concatenation are constant time operations. +* Sorting a string of fixed length (at most 9 characters) is a constant time operation. +* Checking for the sequence "123456789" in a fixed-length string is also a constant time operation. + +## Space Complexity + +The space complexity is $O(1)$ as well since the operations use a constant amount of extra space for storing the products and concatenated strings. + +## References + +- **Geeks for Geeks Problem:** [Geeks for Geeks Problem](https://www.geeksforgeeks.org/problems/fascinating-number3751/1?page=1&difficulty=School&sortBy=difficulty) +- **Solution Link:** [Fascinating Number on Geeks for Geeks](https://www.geeksforgeeks.org/problems/fascinating-number3751/1?page=1&difficulty=School&sortBy=difficulty) +- **Authors LeetCode Profile:** [Anoushka](https://www.geeksforgeeks.org/user/iamanolive/) \ No newline at end of file diff --git a/solutions/gfg-solutions/0003-Count-the-subarrays-having-product-less-than-k.md b/solutions/gfg-solutions/0003-Count-the-subarrays-having-product-less-than-k.md new file mode 100644 index 0000000..4945a73 --- /dev/null +++ b/solutions/gfg-solutions/0003-Count-the-subarrays-having-product-less-than-k.md @@ -0,0 +1,399 @@ +--- + +id: count-subarrays-product-less-than-k +title: Count Subarrays with Product Less Than K +sidebar_label: 0003- Count Subarrays with Product Less Than K +tags: + - Array + - Sliding Window + - Two Pointers + - Mathematics + - Python + - JavaScript + - TypeScript + - Java + - C++ +description: "This is a solution to the problem of counting subarrays with product less than a given value K." + +--- + +In this page, we will solve the problem of counting subarrays with a product less than a given number K using different approaches. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, and C++. + +## Problem Description + +Given an array of positive numbers, the task is to find the number of possible contiguous subarrays having a product less than a given number k. + +### Examples + +**Example 1:** + +```plaintext +Input: n = 4, k = 10, a[] = {1, 2, 3, 4} +Output: 7 +Explanation: The contiguous subarrays are {1}, {2}, {3}, {4}, {1, 2}, {1, 2, 3}, and {2, 3}, all of which have products less than 10. There are 7 such subarrays in total. +``` + +**Example 2:** + +```plaintext +Input: n = 7, k = 100, a[] = {1, 9, 2, 8, 6, 4, 3} +Output: 16 +Explanation: The contiguous subarrays are all subarrays of length 1, 2, and 3 with products less than 100. There are 16 such subarrays in total. +``` + +### Constraints + +- `1 <= n <= 10^6` +- `1 <= k <= 10^15` +- `1 <= a[i] <= 10^5` + +--- + +## Solution for Count Subarrays with Product Less Than K Problem + +### Intuition and Approach + +The problem can be solved using the sliding window (or two pointers) approach to efficiently find the number of subarrays whose product is less than k. + + + + +### Approach: Brute Force + +This approach involves using binary search to find the right boundary for each left boundary, counting subarrays with a product less than k. + +#### Implementation + +```jsx live +function countSubarraysWithProductLessThanK() { + const n = 4; + const k = 10; + const a = [1, 2, 3, 4]; + + const countSubArrayProductLessThanK = (a, n, k) => { + if (k <= 1) return 0; + let count = 0; + for (let i = 0; i < n; i++) { + let product = 1; + for (let j = i; j < n; j++) { + product *= a[j]; + if (product < k) count++; + else break; + } + } + return count; + }; + + const result = countSubArrayProductLessThanK(a, n, k); + return ( +
+

+ Input: n = {n}, k = {k}, a = [{a.join(", ")}] + + +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function countSubArrayProductLessThanK(a, n, k) { + if (k <= 1) return 0; + let count = 0; + for (let i = 0; i < n; i++) { + let product = 1; + for (let j = i; j < n; j++) { + product *= a[j]; + if (product < k) count++; + else break; + } + } + return count; + } + + ``` + + + + + ```typescript + function countSubArrayProductLessThanK(a: number[], n: number, k: number): number { + if (k <= 1) return 0; + let count = 0; + for (let i = 0; i < n; i++) { + let product = 1; + for (let j = i; j < n; j++) { + product *= a[j]; + if (product < k) count++; + else break; + } + } + return count; + } + + + ``` + + + + + ```python + def count_subarray_product_less_than_k(a, n, k): + if k <= 1: + return 0 + count = 0 + for i in range(n): + product = 1 + for j in range(i, n): + product *= a[j] + if product < k: + count += 1 + else: + break + return count + + + ``` + + + + + ```java + public class Solution { + public int countSubArrayProductLessThanK(int[] a, int n, int k) { + if (k <= 1) return 0; + int count = 0; + + for (int i = 0; i < n; i++) { + int product = 1; + for (int j = i; j < n; j++) { + product *= a[j]; + if (product < k) count++; + else break; + } + } + return count; + } + + + } + ``` + + + + + ```cpp + #include + #include + + using namespace std; + + int countSubArrayProductLessThanK(vector& a, int n, int k) { + if (k <= 1) return 0; + int count = 0; + + for (int i = 0; i < n; i++) { + int product = 1; + for (int j = i; j < n; j++) { + product *= a[j]; + if (product < k) count++; + else break; + } + } + return count; + } + + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n^2)$$ +- Space Complexity: $$O(1)$$ + +
+ + + + +### Approach: Sliding Window + +The sliding window approach involves maintaining a window of elements with a product less than k and expanding or shrinking the window as necessary. + +#### Implementation + +```jsx live +function countSubarraysWithProductLessThanK() { + const n = 4; + const k = 10; + const a = [1, 2, 3, 4]; + + const countSubArrayProductLessThanK = (a, n, k) => { + if (k <= 1) return 0; + let count = 0, product = 1, left = 0; + + for (let right = 0; right < n; right++) { + product *= a[right]; + while (product >= k) product /= a[left++]; + count += right - left + 1; + } + + return count; + }; + + const result = countSubArrayProductLessThanK(a, n, k); + return ( +
+

+ Input: n = {n}, k = {k}, a = [{a.join(", ")}] +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function countSubArrayProductLessThanK(a, n, k) { + if (k <= 1) return 0; + let count = 0, product = 1, left = 0; + + for (let right = 0; right < n; right++) { + product *= a[right]; + while (product >= k) product /= a[left++]; + count += right - left + 1; + } + + return count; + } + + ``` + + + + + ```typescript + function countSubArrayProductLessThanK(a: number[], n: number, k: number): number { + if (k <= 1) return 0; + let count = 0, product = 1, left = 0; + + for (let right = 0; right < n; right++) { + product *= a[right]; + while (product >= k) product /= a[left++]; + count += right - left + 1; + } + + return count; + } + + ``` + + + + + ```python + def count_subarray_product_less_than_k(a, n, k): + if k <= 1: + return 0 + count, product, left = 0, 1, 0 + + for right in range(n): + product *= a[right] + while product >= k: + product /= a[left] + left += 1 + count += right - left + 1 + + return count + + + ``` + + + + + ```java + public class Solution { + public int countSubArrayProductLessThanK(int[] a, int n, int k) { + if (k <= 1) return 0; + int count = 0, product = 1, left = 0; + + for (int right = 0; right < n; right++) { + product *= a[right]; + while (product >= k) product /= a[left++]; + count += right - left + 1; + } + + return count; + } + + + } + ``` + + + + + ```cpp + #include + #include + + using namespace std; + + int countSubArrayProductLessThanK(vector& a, int n, int k) { + if (k <= 1) return 0; + int count = 0, product = 1, left = 0; + + for (int right = 0; right < n; right++) { + product *= a[right]; + while (product >= k) product /= a[left++]; + count += right - left + 1; + } + + return count; + } + + + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(1)$$ + +
+
+ + +:::tip +The sliding window approach efficiently counts subarrays with product less than k in linear time. +::: + +## References + +- **GeeksforGeeks Problem:** [GeeksforGeeks Problem](https://www.geeksforgeeks.org/problems/count-the-subarrays-having-product-less-than-k1708/0) +- **GeeksforGeeks Problem:** [GeeksforGeeks Solution](https://www.geeksforgeeks.org/problems/count-the-subarrays-having-product-less-than-k1708/0) +- **Solution Author:** [Manish Kumar Gupta](https://www.geeksforgeeks.org/user/manishd5hla) + +--- \ No newline at end of file diff --git a/solutions/gfg-solutions/0003-at-least-two-greater-elements.md b/solutions/gfg-solutions/0003-at-least-two-greater-elements.md new file mode 100644 index 0000000..d0018ea --- /dev/null +++ b/solutions/gfg-solutions/0003-at-least-two-greater-elements.md @@ -0,0 +1,141 @@ +--- +id: at-least-two-greater-elements +title: At Least Two Greater Elements Problem (Geeks for Geeks) +sidebar_label: 0003 - At Least Two Greater Elements +tags: + - Beginner + - Array + - Slicing + - Sort + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the At Least Two Greater Elements problem on Geeks for Geeks." +--- + +This tutorial contains a complete walk-through of the At Least Two Greater Elements problem from the Geeks for Geeks website. It features the implementation of the solution code in two programming languages: Python and C++. + +## Problem Description + +Given an array of N distinct elements, the task is to find all elements in array except two greatest elements in sorted order. + +## Examples + +**Example 1:** + +``` +Input : a[] = {2, 8, 7, 1, 5} +Output : 1 2 5 +Explanation : The output three elements have two or more greater elements. +``` + +**Example 2:** + +``` +Input : a[] = {7, -2, 3, 4, 9, -1} +Output : -2 -1 3 4 + +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `findElements()` which takes the array `A[]` and its size N as inputs and return the vector sorted values denoting the elements in array which have at-least two greater elements than themselves. + + +Expected Time Complexity: $O(N*Log(N)$ +Expected Auxiliary Space: $O(N)$ + +## Constraints + +* `3 ≀ N ≀ 10^5` +* `-10^6 ≀ Ai ≀ 10^6` + +## Problem Explanation + +The problem is to find all elements in an array except the two greatest elements and return them in sorted order. In simpler terms, you want to remove the two largest elements from the array and sort the remaining elements. + +## Code Implementation + + + + + ```py + class Solution: + def findElements(self, a, n): + a.sort(); return a[0 : -2] + ``` + + + + + + ```cpp + class Solution { + public: + vector findElements(int a[], int n) { + sort(a, a + n); + vector result; + for (int i = 0; i < n - 2; i++) + result.push_back(a[i]); + return result; + } +}; +``` + + + + ```Java + class Solution { + public long[] findElements( long a[], long n) + { + // Your code goes here + long[] ans=new long[a.length-2]; + Arrays.sort(a); + for(int i=0;i + + + +## Example Walkthrough + +For the array `[2, 8, 7, 1, 5]`: + +1. The two greatest elements are 8 and 7. +2. Removing these two, the remaining elements are `[2, 1, 5]`. +3. Sorting these remaining elements gives `[1, 2, 5]`. + +For the array `[7, βˆ’2, 3, 4, 9, βˆ’1]`: +1. The two greatest elements are 9 and 7 +2. Removing these two, the remaining elements are `[βˆ’2, 3, 4, βˆ’1]`. +3. Sorting these remaining elements gives `[βˆ’2, βˆ’1, 3, 4]`. + + +## Solution Logic: + +1. Sort the Array: First, sort the entire array. +2. Remove the Last Two Elements: After sorting, the last two elements will be the greatest. Removing these will leave us with the elements that have at least two greater elements. +3. Return the Result: The remaining sorted elements are the desired result. + +## Time Complexity + +* Sorting the Array: The primary operation is sorting the array, which has a time complexity of $O(N*Log(N)$, where N is the number of elements in the array. +* Slicing the Array: Extracting the elements excluding the last two elements has a time complexity of $O(1)$. + + +## Space Complexity + +Auxiliary Space: The auxiliary space complexity is $O(N)$ because the sorting algorithm typically requires additional space proportional to the size of the input array. + + +## References + +- **Geeks for Geeks Problem:** [Geeks for Geeks Problem](https://www.geeksforgeeks.org/problems/at-least-two-greater-elements4625/1?page=1&difficulty=School&sortBy=difficulty) +- **Solution Link:** [At Least Two Greater Elements on Geeks for Geeks](https://www.geeksforgeeks.org/problems/at-least-two-greater-elements4625/1?page=1&difficulty=School&sortBy=difficulty) +- **Authors LeetCode Profile:** [Anoushka](https://www.geeksforgeeks.org/user/iamanolive/) diff --git a/solutions/gfg-solutions/0003-kadane's-algorithm.md b/solutions/gfg-solutions/0003-kadane's-algorithm.md new file mode 100644 index 0000000..12ee2ec --- /dev/null +++ b/solutions/gfg-solutions/0003-kadane's-algorithm.md @@ -0,0 +1,270 @@ +--- +id: kadane's-algorithm +title: Kadane's Alogrithm (Geeks for Geeks) +sidebar_label: 0003 - Kadane's Algorithm +tags: + - intermediate + - Array + - Dynamic Programming + - Data Structure + - Algorithms + +description: "This is a solution to the Kadane's Algorithm problem on Geeks for Geeks." +--- + +This tutorial contains a complete walk-through of the Kadane's Algorithm problem from the Geeks for Geeks website. It features the implementation of the solution code in three programming languages: Python ,C++ ,java. + +## Problem Description + +Given an array Arr[] of N integers, find the contiguous sub-array (containing at least one number) which has the maximum sum and return its sum. + +## Examples + +**Example 1:** + +``` +Input: +N = 5 +Arr[] = {1,2,3,-2,5} +Output: +9 +Explanation: +Max subarray sum is 9 +of elements (1, 2, 3, -2, 5) which +is a contiguous subarray. +``` + +**Example 2:** + +``` +Input: +N = 4 +Arr[] = {-1,-2,-3,-4} +Output: +-1 +Explanation: +Max subarray sum is -1 +of element (-1) +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `maxSubarraySum()` which takes Arr[] and N as input parameters and returns the sum of subarray with maximum sum. + +Expected Time Complexity: $O(N)$ +Expected Auxiliary Space: $O(1)$ + +## Constraints + +1. $(1 \leq N \leq 10^6)$ +2. $(-10^7 \leq A[i] \leq 10^7)$ + +## Solution Approach + +### Brute Force Approach + +#### Intuition: +Try all possible subarrays by using nested loops and pick the subarray which has the maximum sum. + +#### Implementation: +1. Keep an answer variable to store the maximum subarray sum. +2. Run a loop(i). +3. Run a nested loop from i till the end of the array. +4. Generate all subarrays starting from the ith index and compare its sum with the answer and update the answer with the maximum one. +5. Return the answer. + +#### Code (C++): + +```cpp +class Solution{ + public: + // arr: input array + // n: size of array + //Function to find the sum of contiguous subarray with maximum sum. + long long maxSubarraySum(int arr[], int n){ + + // Your code here + long long ans=arr[0]; + for(int i=0;i + + +### Approach 1: Iterative + +The iterative approach involves iterating through each number in the range and counting the occurrences of the digit `X`. + +#### Implementation + +```jsx live +function countXs() { + const L = 10; + const R = 20; + const X = 1; + + const countDigitOccurrences = (L, R, X) => { + let count = 0; + for (let i = L+1; i < R; i++) { + let num = i; + while (num > 0) { + if (num % 10 === X) count++; + num = Math.floor(num / 10); + } + } + return count; + }; + + const result = countDigitOccurrences(L, R, X); + return ( +
+

+ Input: L = {L}, R = {R}, X = {X} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function countDigitOccurrences(L, R, X) { + let count = 0; + for (let i = L+1; i < R; i++) { + let num = i; + while (num > 0) { + if (num % 10 === X) count++; + num = Math.floor(num / 10); + } + } + return count; + } + ``` + + + + + ```typescript + function countDigitOccurrences(L: number, R: number, X: number): number { + let count = 0; + for (let i = L+1; i < R; i++) { + let num = i; + while (num > 0) { + if (num % 10 === X) count++; + num = Math.floor(num / 10); + } + } + return count; + } + ``` + + + + + ```python + def count_digit_occurrences(L, R, X): + count = 0 + for i in range(L+1, R): + num = i + while num > 0: + if num % 10 == X: + count += 1 + num //= 10 + return count + ``` + + + + + ```java + class Solution { + public int countDigitOccurrences(int L, int R, int X) { + int count = 0; + for (int i = L+1; i < R; i++) { + int num = i; + while (num > 0) { + if (num % 10 == X) { + count++; + } + num /= 10; + } + } + return count; + } + } + ``` + + + + + ```cpp + #include + + using namespace std; + + int countDigitOccurrences(int L, int R, int X) { + int count = 0; + for (int i = L+1; i < R; i++) { + int num = i; + while (num > 0) { + if (num % 10 == X) { + count++; + } + num /= 10; + } + } + return count; + } + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O((R - L)*logR)$$ +- Space Complexity: $$O(1)$$ + +
+ + +### Approach 2: Mathematical + +The mathematical approach involves counting the occurrences of the digit `X` in the range without iterating through each number. + +#### Implementation + +```jsx live +function countXs() { + const L = 10; + const R = 20; + const X = 1; + + const countOccurrences = (num, X) => { + let count = 0, factor = 1, nextNum = 0, currentNum = 0; + while (num / factor > 0) { + currentNum = Math.floor((num / factor) % 10); + nextNum = Math.floor(num / (factor * 10)); + count += nextNum * factor; + if (currentNum > X) count += factor; + else if (currentNum === X) count += num % factor + 1; + factor *= 10; + } + return count; + }; + + const countX = (L, R, X) => { + return countOccurrences(R - 1, X) - countOccurrences(L, X); + }; + + const result = countX(L, R, X); + return ( +
+

+ Input: L = {L}, R = {R}, X = {X} +

+

+ Output: {result} +

+
+ ); +} + +``` + +#### Code in Different Languages + + + + + ```javascript + function countDigitOccurrences(num, X) { + let count = 0, factor = 1, nextNum = 0, currentNum = 0; + while (num / factor > 0) { + currentNum = Math.floor((num / factor) % 10); + nextNum = Math.floor(num / (factor * 10)); + count += nextNum * factor; + if (currentNum > X) count += factor; + else if (currentNum === X) count += num % factor + 1; + factor *= 10; + } + return count; + } + + function countX(L, R, X) { + return countDigitOccurrences(R - 1, X) - countDigitOccurrences(L, X); + } + ``` + + + + + ```typescript + function countDigitOccurrences(num: number, X: number): number { + let count = 0, factor = 1, nextNum = 0, currentNum = 0; + while (num / factor > 0) { + currentNum = Math.floor((num / factor) % 10); + nextNum = Math.floor(num / (factor * 10)); + count += nextNum * factor; + if (currentNum > X) count += factor; + else if (currentNum === X) count += num % factor + 1; + factor *= 10; + } + return count; + } + + function countX(L: number, R: number, X: number): number { + return countDigitOccurrences(R - 1, X) - countDigitOccurrences(L, X); + } + ``` + + + + + ```python + def count_digit_occurrences(num, X): + count = 0 + factor = 1 + while num // factor > 0: + current_num = (num // factor) % 10 + next_num = num // (factor * 10) + count + + += next_num * factor + if current_num > X: + count += factor + elif current_num == X: + count += num % factor + 1 + factor *= 10 + return count + + def count_X(L, R, X): + return count_digit_occurrences(R - 1, X) - count_digit_occurrences(L , X) + ``` + + + + + ```java + class Solution { + public int countDigitOccurrences(int num, int X) { + int count = 0, factor = 1, nextNum = 0, currentNum = 0; + while (num / factor > 0) { + currentNum = (num / factor) % 10; + nextNum = num / (factor * 10); + count += nextNum * factor; + if (currentNum > X) { + count += factor; + } else if (currentNum == X) { + count += num % factor + 1; + } + factor *= 10; + } + return count; + } + + public int countX(int L, int R, int X) { + return countDigitOccurrences(R - 1, X) - countDigitOccurrences(L , X); + } + } + ``` + + + + + ```cpp + #include + + using namespace std; + + int countDigitOccurrences(int num, int X) { + int count = 0, factor = 1, nextNum = 0, currentNum = 0; + while (num / factor > 0) { + currentNum = (num / factor) % 10; + nextNum = num / (factor * 10); + count += nextNum * factor; + if (currentNum > X) { + count += factor; + } else if (currentNum == X) { + count += num % factor + 1; + } + factor *= 10; + } + return count; + } + + int countX(int L, int R, int X) { + return countDigitOccurrences(R - 1, X) - countDigitOccurrences(L , X); + } + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(\log_{10}(R))$$ +- Space Complexity: $$O(1)$$ + +
+ + +:::tip +The mathematical approach is more efficient for large ranges. Choose the method that best suits the given constraints. +::: +## References + +- **GeeksforGeeks Problem:** [GeeksforGeeks Problem](https://www.geeksforgeeks.org/problems/how-many-xs4514/0) +- **Solution Link:** [How Many X's Solution on GeeksforGeeks](https://www.geeksforgeeks.org/problems/how-many-xs4514/0) +- **Authors GeeksforGeeks Profile:** [Manish Kumar Gupta](https://www.geeksforgeeks.org/user/manishd5hla) + +--- diff --git a/solutions/gfg-solutions/0004-fibbonacci-sum.md b/solutions/gfg-solutions/0004-fibbonacci-sum.md new file mode 100644 index 0000000..8735833 --- /dev/null +++ b/solutions/gfg-solutions/0004-fibbonacci-sum.md @@ -0,0 +1,267 @@ +--- +id: fibonacci-sum +title: Fibonacci Sum (Geeks for Geeks) +sidebar_label: 0004 - Fibonacci Sum +tags: + - intermediate + - Fibonacci + - Dynamic Programming + - Mathematics + - Algorithms +--- + +This tutorial contains a complete walk-through of the Fibonacci Sum problem from the Geeks for Geeks website. It features the implementation of the solution code in three programming languages: Python, C++, and Java. + +## Problem Description + +Given a positive number N, find the value of $f0 + f1 + f2 + ... + fN$ where fi indicates the ith Fibonacci number. Note that $f0 = 0, f1 = 1, f2 = 1, f3 = 2, f4 = 3, f5 = 5,$ and so on. Since the answer can be very large, return the result modulo $1000000007$. + +## Examples + +**Example 1:** + +``` +Input: +N = 3 +Output: +4 +Explanation: +0 + 1 + 1 + 2 = 4 +``` + +**Example 2:** + +``` +Input: +N = 4 +Output: +7 +Explanation: +0 + 1 + 1 + 2 + 3 = 7 +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `fibSum()` which takes an integer N as input parameter and returns the sum of all the Fibonacci numbers from f0 to fN. + +Expected Time Complexity: $O(LogN)$ +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- $(1 \leq N \leq 100000)$ + +## Solution Approach + +### Brute Force Approach + +#### Intuition: + +We can compute the sum of Fibonacci numbers from f0 to fN using a simple iterative method by adding up all Fibonacci numbers up to N. + +#### Implementation: + +1. Initialize `sum` to 0. +2. Use a loop to compute Fibonacci numbers up to N. +3. Add each Fibonacci number to `sum`. +4. Return the sum modulo $1000000007$. + +#### Code (C++): + +```cpp +#include +#define MOD 1000000007 +using namespace std; + +class Solution { +public: + int fibSum(int N) { + if (N == 0) return 0; + long long f0 = 0, f1 = 1, sum = 1; + for (int i = 2; i <= N; ++i) { + long long f2 = (f0 + f1) % MOD; + sum = (sum + f2) % MOD; + f0 = f1; + f1 = f2; + } + return sum; + } +}; +``` + +### Complexity + +- Time Complexity: $O(N)$, as we are iterating from 0 to N. +- Space Complexity: $O(1)$, as we are using a constant amount of extra space. + +## Matrix Exponentiation Approach + +#### Intuition: + +To efficiently find the sum of the first N Fibonacci numbers, we use matrix exponentiation. By utilizing the transformation matrix and its properties, we can compute the required sum in logarithmic time. + +#### Implementation: + +1. Define a function to multiply two matrices. +2. Define a function to compute the power of a matrix. +3. Use the power function to compute the matrix exponentiation result. +4. Extract the result from the matrix to get the sum of the first N Fibonacci numbers. + +#### Code (C++): + +```cpp +#include +using namespace std; + +class Solution { +public: + const int mod = 1e9 + 7; + + vector> multiply(vector>& a, vector>& b) { + long long int n = a.size(); + vector> ans(n, vector(n, 0)); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + for (int k = 0; k < n; k++) { + ans[i][j] = (ans[i][j] + (a[i][k] * b[k][j]) % mod) % mod; + } + } + } + return ans; + } + + vector> power(vector>& F, long long int n) { + if (n == 0) { + long long int s = F.size(); + vector> ans(s, vector(s, 0)); + for (int i = 0; i < s; i++) { + ans[i][i] = 1; + } + return ans; + } + if (n == 1) { + return F; + } + vector> temp = power(F, n / 2); + vector> ans = multiply(temp, temp); + if (n % 2 != 0) { + ans = multiply(ans, F); + } + return ans; + } + + long long int fibSum(long long int N) { + vector> a = {{1, 1, 1}, {0, 1, 1}, {0, 1, 0}}; + vector> ans = power(a, N); + return ans[0][2]; + } +}; +``` + +#### Code (Python): + +```python +class Solution: + MOD = int(1e9 + 7) + + def multiply(self, a, b): + n = len(a) + ans = [[0] * n for _ in range(n)] + for i in range(n): + for j in range(n): + for k in range(n): + ans[i][j] = (ans[i][j] + a[i][k] * b[k][j]) % self.MOD + return ans + + def power(self, F, n): + if n == 0: + s = len(F) + ans = [[0] * s for _ in range(s)] + for i in range(s): + ans[i][i] = 1 + return ans + if n == 1: + return F + temp = self.power(F, n // 2) + ans = self.multiply(temp, temp) + if n % 2 != 0: + ans = self.multiply(ans, F) + return ans + + def fibSum(self, N): + a = [[1, 1, 1], [0, 1, 1], [0, 1, 0]] + ans = self.power(a, N) + return ans[0][2] + +# Example usage: +solution = Solution() +print(solution.fibSum(5)) # Output the sum of the first 5 Fibonacci numbers +``` + +#### Code (Java): + +```java +import java.util.Arrays; + +class Solution { + private static final int MOD = 1000000007; + + private long[][] multiply(long[][] a, long[][] b) { + int n = a.length; + long[][] ans = new long[n][n]; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + for (int k = 0; k < n; k++) { + ans[i][j] = (ans[i][j] + a[i][k] * b[k][j]) % MOD; + } + } + } + return ans; + } + + private long[][] power(long[][] F, long n) { + int size = F.length; + long[][] ans = new long[size][size]; + for (int i = 0; i < size; i++) { + ans[i][i] = 1; + } + if (n == 0) return ans; + if (n == 1) return F; + + long[][] temp = power(F, n / 2); + ans = multiply(temp, temp); + if (n % 2 != 0) { + ans = multiply(ans, F); + } + return ans; + } + + public long fibSum(long N) { + long[][] a = {{1, 1, 1}, {0, 1, 1}, {0, 1, 0}}; + long[][] ans = power(a, N); + return ans[0][2]; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.fibSum(5)); // Output the sum of the first 5 Fibonacci numbers + } +} +``` + +#### Complexity: + +- Time Complexity: $O(logN)$, due to matrix exponentiation. +- Space Complexity: $O(logN)$, for recursive stack + +## Conclusion + +The problem of finding the sum of the first N Fibonacci numbers can be efficiently solved using matrix exponentiation, reducing the time complexity to logarithmic time $O(\log N)$. This approach ensures that even for large values of N, the computation remains feasible and efficient. The provided implementations in C++, Java, and Python demonstrate the versatility of the matrix exponentiation technique across different programming languages. + +By leveraging the properties of Fibonacci numbers and matrix multiplication, we can achieve optimal performance for this problem, making it suitable for large input sizes as specified in the constraints. + +## References + +- **GeeksforGeeks Problem:** [Geeks for Geeks Problem](https://www.geeksforgeeks.org/problems/fibonacci-sum/0) +- **Solution Link:** [Fibonacci Sum on Geeks for Geeks](https://www.geeksforgeeks.org/problems/fibonacci-sum/0) +- **Authors GeeksforGeeks Profile:** [Vipul](https://www.geeksforgeeks.org/user/lakumvipwjge/) diff --git a/solutions/gfg-solutions/0005-Pascal-Triangle.md b/solutions/gfg-solutions/0005-Pascal-Triangle.md new file mode 100644 index 0000000..f6bd809 --- /dev/null +++ b/solutions/gfg-solutions/0005-Pascal-Triangle.md @@ -0,0 +1,416 @@ +--- + +id: pascal-triangle +title: Pascal Triangle Solution +sidebar_label: 0005 - Pascal Triangle +tags: + - Pascal Triangle + - Dynamic Programming + - Mathematics + - Binomial Coefficient + - JavaScript + - TypeScript + - Python + - Java + - C++ +description: "This is a solution to the Pascal Triangle Row problem." + +--- + +In this page, we will solve the Pascal Triangle Row problem using different approaches: dynamic programming and mathematical. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +Given a positive integer N, return the Nth row of Pascal's triangle. Pascal's triangle is a triangular array of the binomial coefficients formed by summing up the elements of the previous row. The elements can be large so return it modulo $(10^9 + 7)$. + +### Examples + +**Example 1:** + +```plaintext +Input: N = 4 +Output: 1 3 3 1 +Explanation: 4th row of Pascal's triangle is 1 3 3 1. +``` + +**Example 2:** + +```plaintext +Input: N = 5 +Output: 1 4 6 4 1 +Explanation: 5th row of Pascal's triangle is 1 4 6 4 1. +``` + +### Constraints + +- `1 <= N <= 10^3` + +--- + +## Solution for Pascal Triangle Row Problem + +### Intuition and Approach + +The problem can be solved using dynamic programming or a mathematical approach. The dynamic programming approach is more intuitive and builds the entire triangle row by row. The mathematical approach leverages the properties of binomial coefficients. + + + + +### Approach 1: Dynamic Programming + +The dynamic programming approach involves building the Pascal's triangle row by row until the desired row is reached. + +#### Implementation + +```jsx live +function nthRowOfPascalTriangle() { + const N = 4; + const MOD = 1000000007; + + const generate = function(N) { + const row = [1]; + for (let i = 1; i < N; i++) { + row[i] = (row[i - 1] * (N - i) / i) % MOD; + } + return row; + }; + + const result = generate(N); + return ( +
+

+ Input: N = {N} +

+

+ Output: {JSON.stringify(result)} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function nthRowOfPascalTriangle(N) { + const MOD = 1000000007; + const row = [1]; + for (let i = 1; i < N; i++) { + row[i] = (row[i - 1] * (N - i) / i) % MOD; + } + return row; + } + ``` + + + + + ```typescript + function nthRowOfPascalTriangle(N: number): number[] { + const MOD = 1000000007; + const row: number[] = [1]; + for (let i = 1; i < N; i++) { + row[i] = (row[i - 1] * (N - i) / i) % MOD; + } + return row; + } + ``` + + + + + ```python + class Solution: + def nthRowOfPascalTriangle(self, N: int) -> List[int]: + MOD = 1000000007 + row = [1] + for i in range(1, N): + row.append((row[-1] * (N - i) // i) % MOD) + return row + ``` + + + + + ```java + import java.util.ArrayList; + import java.util.List; + + class Solution { + public List nthRowOfPascalTriangle(int N) { + final int MOD = 1000000007; + List row = new ArrayList<>(); + row.add(1); + for (int i = 1; i < N; i++) { + row.add((int)((long)row.get(i - 1) * (N - i) / i % MOD)); + } + return row; + } + } + ``` + + + + + ```cpp + #include + + using namespace std; + + class Solution { + public: + vector nthRowOfPascalTriangle(int N) { + const int MOD = 1000000007; + vector row(1, 1); + for (int i = 1; i < N; i++) { + row.push_back((long long)row[i - 1] * (N - i) / i % MOD); + } + return row; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(N^2)$$ +- Space Complexity: $$O(N)$$ + +
+ + +### Approach 2: Mathematical (Binomial Coefficient) + +The mathematical approach leverages the properties of binomial coefficients to directly compute each element in the Nth row of Pascal's triangle. The value of the element at the ith position is calculated using the formula: + +$[ +\text{Value} = \binom{i}{j} = \frac{i!}{j! \cdot (i - j)!} +]$ +#### Implementation + +```jsx live +function nthRowOfPascalTriangle() { + const N = 5; + const MOD = 1000000007; + + const generate = function(N) { + const row = []; + const factorial = (n) => { + if (n === 0) return 1; + let fact = 1; + for (let i = 1; i <= n; i++) { + fact = (fact * i) % MOD; + } + return fact; + }; + + const binomialCoeff = (n, k) => { + return (factorial(n) / (factorial(k) * factorial(n - k))) % MOD; + }; + + for (let i = 0; i < N; i++) { + row.push(binomialCoeff(N - 1, i)); + } + + return row; + }; + + const result = generate(N); + return ( +
+

+ Input: N = {N} +

+

+ Output: {JSON.stringify(result)} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function nthRowOfPascalTriangle(N) { + const MOD = 1000000007; + const row = []; + const factorial = (n) => { + if (n === 0) return 1; + let fact = 1; + for (let i = 1; i <= n; i++) { + fact = (fact * i) % MOD; + } + return fact; + }; + + const binomialCoeff = (n, k) => { + return (factorial(n) / (factorial(k) * factorial(n - k))) % MOD; + }; + + for (let i = 0; i < N; i++) { + row.push(binomialCoeff(N - 1, i)); + } + + return row; + } + ``` + + + + + ```typescript + function nthRowOfPascalTriangle(N: number): number[] { + const MOD = 1000000007; + const row: number[] = []; + const factorial = (n: number): number => { + if (n === 0) return 1; + let fact = 1; + for (let i = 1; i <= n; i++) { + fact = (fact * i) % MOD; + } + return fact; + }; + + const binomialCoeff = (n: number, k: number): number => { + return (factorial(n) / (factorial(k) * factorial(n - k))) % MOD; + }; + + for (let i = 0; i < N; i++) { + row.push(binomialCoeff(N - 1, i)); + } + + return row; + } + ``` + + + + + ```python + import math + + class Solution: + def nthRowOfPascalTriangle(self, N: int) -> List[int]: + MOD = 1000000007 + + def factorial(n): + if n == 0: + return 1 + fact = 1 + for i in range(1, n + 1): + fact = (fact * i) % MOD + return fact + + def binomialCoeff(n, k): + return (factorial(n) // (factorial(k) * factorial(n - k))) % MOD + + row = [] + for i in range(N): + row.append(binomialCoeff(N - 1, i)) + + return row + ``` + + + + + ```java + import java.util.ArrayList; + import java.util.List; + + class Solution { + private static final int MOD = 1000000007; + + public List nthRowOfPascalTriangle(int N) { + List row = new ArrayList<>(); + for (int i = 0; i < N; i++) { + row.add(binomialCoeff(N - 1, i)); + } + return row; + } + + private int factorial(int n) { + if (n == 0) return 1; + long fact = 1; + for (int i = 1; i <= n; i++) { + fact = (fact * i) % MOD; + } + return (int) fact; + } + + private int binomialCoeff(int n, int k) { + return (int) ((factorial(n) / (factorial(k) * factorial(n - k))) % MOD); + } + } + ``` + + + + + ```cpp + #include + #include + + using namespace std; + + class Solution { + public: + vector nthRowOfPascalTriangle(int N) { + const int MOD = 1000000007; + vector row; + for (int i = 0; i < N; i++) { + row.push_back(binomialCoeff(N - 1, i, MOD)); + } + return row; + } + + private: + int factorial(int n, const int MOD) { + if (n == 0) return 1; + long long fact = 1; + for (int i = 1; i <= n; i++) { + fact = (fact * i) % MOD; + } + return fact; + } + + int binomialCoeff(int n, int k, const int MOD) { + return (factorial(n, MOD) / (factorial(k, MOD) * factorial(n - k, MOD))) % MOD; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(N^2)$$ +- Space Complexity: $$O(N^2)$$ + +
+
+ +--- + +These are the two approaches to solve the Pascal's Triangle Row problem. Each approach has its own advantages and trade-offs in terms of time and space complexity. You can choose the one that best fits your requirements. + + +## References + +- **GeeksforGeeks Problem:** [GeeksforGeeks Problem](https://www.geeksforgeeks.org/problems/pascal-triangle0652/0) +- **Solution Link:** [Pascal's Triangle Solution on GeeksforGeeks](https://www.geeksforgeeks.org/problems/pascal-triangle0652/0) +- **Authors GeeksforGeeks Profile:** [Manish Kumar Gupta](https://www.geeksforgeeks.org/user/manishd5hla/) + +--- diff --git a/solutions/gfg-solutions/0006-next-happy-number.md b/solutions/gfg-solutions/0006-next-happy-number.md new file mode 100644 index 0000000..afd8310 --- /dev/null +++ b/solutions/gfg-solutions/0006-next-happy-number.md @@ -0,0 +1,259 @@ +--- +id: next-happy-number +title: Next Happy Number (Geeks for Geeks) +sidebar_label: 0004 - Next Happy Number +tags: + - intermediate + - Fibonacci + - Dynamic Programming + - Mathematics + - Algorithms +--- + +This tutorial contains a complete walk-through of the Next Happy Number problem from the Geeks for Geeks website. It features the implementation of the solution code in three programming languages: Python, C++, and Java. + +## Problem Statement + +For a given non-negative integer N, find the next smallest Happy Number. A number is called Happy if it leads to 1 after a sequence of steps, where at each step the number is replaced by the sum of squares of its digits. If we start with a Happy Number and keep replacing it with the sum of squares of its digits, we eventually reach 1. + +## Examples + +**Example 1:** + +``` +input: +N = 8 + +Output: +10 +``` + +Explanation: +Next happy number after 8 is 10 since +$[ 1 * 1 + 0 * 0 = 1]$ + +**Example 2** + +``` +Input: +N = 10 + +Output: +13 +``` + +Explanation: + +After 10, 13 is the smallest happy number because +$[1 * 1 + 3 * 3 = 10]$, so we replace 13 by 10 and $[1 * 1 + 0 * 0 = 1]$. + +## Task + +You don't need to read input or print anything. Your task is to complete the function `nextHappy()` which takes an integer N as input parameters and returns an integer, the next Happy number after N. + +## Constraints + +- $(1 \leq N \leq 10^5)$ + + +## Solution Approach + +### Intuition + +To solve the problem, we need to: + +1. Identify the next number greater than N. +2. Check if it is a Happy Number. +3. Repeat the process until we find the next Happy Number. + +A number is identified as Happy if, by repeatedly replacing it with the sum of squares of its digits, we eventually reach 1. + +### Steps + +1. Implement a helper function to determine if a number is Happy. +2. Start checking numbers greater than N, using the helper function to identify the next Happy Number. + +### Detailed Explanation + +The numbers that, when you repeatedly sum the squares of their digits, eventually result in 1 are known as "happy numbers." + +Here are examples of how to determine if numbers less than 10 are happy numbers: + +- **Number 1:** + + $[1 ^ 2 = 1]$ + Since we have already reached 1, the process stops here. 1 is a happy number. + +- **Number 2:** + + $[2^2 = 4]$ + $[4^2 = 16]$ + $[1^2 + 6^2 = 37]$ + $[3^2 + 7^2 = 58]$ + $[5^2 + 8^2 = 89]$ + $[8^2 + 9^2 = 145]$ + $[1^2 + 4^2 + 5^2 = 42]$ + $[4^2 + 2^2 = 20]$ + $[2^2 + 0^2 = 4]$ + + Since we have reached 4 again, the process will continue in an infinite loop. 2 is not a happy number. + +- **Number 3:** + + Similar to the above steps, 3 will also enter a loop and is not a happy number. + +- **Number 4:** + + Similar to the above steps, 4 will also enter a loop and is not a happy number. + +- **Number 5:** + + Similar to the above steps, 5 will also enter a loop and is not a happy number. + +- **Number 6:** + + Similar to the above steps, 6 will also enter a loop and is not a happy number. + +- **Number 7:** + + $[7^2 = 49]$ + $[4^2 + 9^2 = 97]$ + $[9^2 + 7^2 = 130]$ + $[1^2 + 3^2 + 0^2 = 10]$ + $[1^2 + 0^2 = 1]$ + + Since we have reached 1, the process stops here. 7 is a happy number. + +- **Number 8:** + + Similar to the above steps, 8 will also enter a loop and is not a happy number. + +- **Number 9:** + + Similar to the above steps, 9 will also enter a loop and is not a happy number. + +Based on this analysis, the numbers less than 10 that result in 1 when you repeatedly sum the squares of their digits are: 1 and 7. + +### Implementation + +#### Code (C++): + +```cpp +#include + +class Solution { +public: + bool solve(int n) { + if (n == 1 || n == 7) return true; + if (n == 2 || n == 4 || n == 8 || n == 3 || n == 9 || n == 5 || n == 6) return false; + int sq_sum = 0; + while (n) { + int x = n % 10; + sq_sum += (x * x); + n /= 10; + } + return solve(sq_sum); + } + + int nextHappy(int n) { + while (true) { + n++; + if (solve(n)) return n; + } + } +}; + +int main() { + Solution sol; + int N = 8; + std::cout << "Next happy number after " << N << " is: " << sol.nextHappy(N) << std::endl; + return 0; +} + +``` + +#### Code(Python) + +```python +class Solution: + def solve(self, n: int) -> bool: + if n == 1 or n == 7: + return True + if n in {2, 4, 8, 3, 9, 5, 6}: + return False + sq_sum = 0 + while n > 0: + x = n % 10 + sq_sum += (x * x) + n //= 10 + return self.solve(sq_sum) + + def nextHappy(self, n: int) -> int: + while True: + n += 1 + if self.solve(n): + return n + +# Example usage +sol = Solution() +N = 8 +print(f"Next happy number after {N} is: {sol.nextHappy(N)}") + +``` + +#### Code (Java) + +```java +public class Solution { + public boolean solve(int n) { + if (n == 1 || n == 7) return true; + if (n == 2 || n == 4 || n == 8 || n == 3 || n == 9 || n == 5 || n == 6) return false; + int sq_sum = 0; + while (n > 0) { + int x = n % 10; + sq_sum += (x * x); + n /= 10; + } + return solve(sq_sum); + } + + public int nextHappy(int n) { + while (true) { + n++; + if (solve(n)) return n; + } + } + + public static void main(String[] args) { + Solution sol = new Solution(); + int N = 8; + System.out.println("Next happy number after " + N + " is: " + sol.nextHappy(N)); + } +} + +``` + +### Complexity + +- **Time Complexity:** $O(klog_{10}N)$ due to the operations on digits of the numbers. + +#### Explanation : + +- We will be able to determine whether a number is happy or not after recursively calling the solve function and adding the square of its digits for a maximum of 15-20 times (you can check for any random value less than 10^5). Let's denote this value as x. +- The time taken to add the square of the digits is log10(n). Furthermore, as we are checking until we find the happy number, let's denote the number of iterations as c = (happy number>n) -n +- Let's denote x\*c=k; + Therefore, TC: (klog10(n)) +- The value of k won't even reach 10^4 or 10^5. You can try this approach with any random value. + +- **Space Complexity:** $O(1)$ since we only use a fixed amount of extra space for the set to store seen numbers. + +## Conclusion + +To find the next Happy Number after a given integer N, we can implement a solution that iteratively checks each number greater than N until a Happy Number is found. This solution efficiently identifies Happy Numbers using a helper function to compute the sum of squares of digits and a set to track previously seen numbers to avoid infinite loops. + +## References + +- **GeeksforGeeks Problem:** [Geeks for Geeks Problem](https://www.geeksforgeeks.org/problems/fibonacci-sum/0) +- **Solution Link:** [Fibonacci Sum on Geeks for Geeks](https://www.geeksforgeeks.org/problems/fibonacci-sum/0) +- **Authors GeeksforGeeks Profile:** [Vipul](https://www.geeksforgeeks.org/user/lakumvipwjge/) + diff --git a/solutions/gfg-solutions/0009-Two-repeated-elements.md b/solutions/gfg-solutions/0009-Two-repeated-elements.md new file mode 100644 index 0000000..b449557 --- /dev/null +++ b/solutions/gfg-solutions/0009-Two-repeated-elements.md @@ -0,0 +1,752 @@ +--- + +id: two-repeated-elements +title: Two Repeated Elements Solution +sidebar_label: 0009 - Two Repeated Elements +tags: + - Array + - Hashing + - Mathematics + - Bit Manipulation + - JavaScript + - TypeScript + - Python + - Java + - C++ +description: "This is a solution to the Two Repeated Elements problem." + +--- + +In this page, we will solve the Two Repeated Elements problem using different approaches: hashing, mathematical, and bit manipulation. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, and C++. + +## Problem Description + +You are given an integer `n` and an integer array `arr` of size `n+2`. All elements of the array are in the range from `1` to `n`. Also, all elements occur once except two numbers which occur twice. Find the two repeating numbers. + +### Examples + +**Example 1:** + +```plaintext +Input: n = 4, arr = [4, 2, 4, 5, 2, 3, 1] +Output: [4, 2] +Explanation: 4 and 2 occur twice. +``` + +**Example 2:** + +```plaintext +Input: n = 2, arr = [1, 2, 1, 2] +Output: [1, 2] +Explanation: 1 and 2 occur twice. +``` + +### Constraints + +- `1 <= n <= 10^5` +- The array `arr` has a length of `n + 2`. + +--- + +## Solution for Two Repeated Elements Problem + +### Intuition and Approach + +The problem can be solved using different approaches such as hashing, mathematical properties, and bit manipulation. + + + + +### Approach 1: Hashing + +The hashing approach involves using a hash set to keep track of the elements that have been seen so far. + +#### Implementation + +```jsx live +function findTwoRepeatedElements() { + const n = 4; + const arr = [4, 2, 4,2, 3, 1]; + + const findRepeating = (n, arr) => { + const seen = new Set(); + const result = []; + + for (let i = 0; i < arr.length; i++) { + if (seen.has(arr[i])) { + result.push(arr[i]); + if (result.length === 2) break; + } else { + seen.add(arr[i]); + } + } + + return result; + }; + + const result = findRepeating(n, arr); + return ( +
+

+ Input: n = {n}, arr = [{arr.join(", ")}] +

+

+ Output: [{result.join(", ")}] +

+
+ ); +} + +``` + +#### Codes in Different Languages + + + + + ```javascript + function findTwoRepeated(arr) { + const n = arr.length - 2; + const seen = new Set(); + const result = []; + + for (let i = 0; i < arr.length; i++) { + if (seen.has(arr[i])) { + result.push(arr[i]); + if (result.length === 2) break; + } else { + seen.add(arr[i]); + } + } + + return result; + } + ``` + + + + + ```typescript + function findTwoRepeated(arr: number[]): number[] { + const n = arr.length - 2; + const seen = new Set(); + const result: number[] = []; + + for (let i = 0; i < arr.length; i++) { + if (seen.has(arr[i])) { + result.push(arr[i]); + if (result.length === 2) break; + } else { + seen.add(arr[i]); + } + } + + return result; + } + ``` + + + + + ```python + def findTwoRepeated(arr): + seen = set() + result = [] + + for num in arr: + if num in seen: + result.append(num) + if len(result) == 2: + break + else: + seen.add(num) + + return result + ``` + + + + + ```java + import java.util.*; + + class Solution { + public int[] findTwoRepeated(int[] arr) { + Set seen = new HashSet<>(); + int[] result = new int[2]; + int index = 0; + + for (int num : arr) { + if (seen.contains(num)) { + result[index++] = num; + if (index == 2) break; + } else { + seen.add(num); + } + } + + return result; + } + } + ``` + + + + + ```cpp + #include + #include + + using namespace std; + + class Solution { + public: + vector findTwoRepeated(vector& arr) { + unordered_set seen; + vector result; + + for (int num : arr) { + if (seen.count(num)) { + result.push_back(num); + if (result.size() == 2) break; + } else { + seen.insert(num); + } + } + + return result; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(n)$$ + +
+ + +### Approach 2: Mathematical + +The mathematical approach involves using the sum and sum of squares formulas to find the repeating numbers. + +#### Implementation + +```jsx live +function findTwoRepeatedElements() { + const n = 4; + const arr = [4, 2, 4, 2, 3, 1]; + + const findRepeating = (n, arr) => { + const totalSum = (n * (n + 1)) / 2; + const totalSumSquare = (n * (n + 1) * (2 * n + 1)) / 6; + + let sum = 0; + let sumSquare = 0; + + for (let i = 0; i < arr.length; i++) { + sum += arr[i]; + sumSquare += arr[i] * arr[i]; + } + + const sumDiff = sum - totalSum; // x + y + const sumSquareDiff = sumSquare - totalSumSquare; // x^2 + y^2 + + const sumProduct = (sumDiff * sumDiff - sumSquareDiff) / 2; // xy + const discriminant = Math.sqrt(sumDiff * sumDiff - 4 * sumProduct); + + const x = (sumDiff + discriminant) / 2; + const y = (sumDiff - discriminant) / 2; + + return [x, y]; + }; + + const result = findRepeating(n, arr); + return ( +
+

+ Input: n = {n}, arr = [{arr.join(", ")}] +

+

+ Output: [{result.join(", ")}] +

+
+ ); +} + + + +``` + +#### Code in Different Languages + + + + + ```javascript + function findTwoRepeatedElements(n, arr) { + const totalSum = (n * (n + 1)) / 2; + const totalSumSquare = (n * (n + 1) * (2 * n + 1)) / 6; + + let sum = 0; + let sumSquare = 0; + + for (let i = 0; i < arr.length; i++) { + sum += arr[i]; + sumSquare += arr[i] * arr[i]; + } + + const sumDiff = sum - totalSum; // x + y + const sumSquareDiff = sumSquare - totalSumSquare; // x^2 + y^2 + + const sumProduct = (sumDiff * sumDiff - sumSquareDiff) / 2; // xy + const discriminant = Math.sqrt(sumDiff * sumDiff - 4 * sumProduct); + + const x = (sumDiff + discriminant) / 2; + const y = (sumDiff - discriminant) / 2; + + return [x, y]; +} +``` + + + + + ```typescript + function findTwoRepeatedElements(n: number, arr: number[]): number[] { + const totalSum: number = (n * (n + 1)) / 2; + const totalSumSquare: number = (n * (n + 1) * (2 * n + 1)) / 6; + + let sum: number = 0; + let sumSquare: number = 0; + + for (let i = 0; i < arr.length; i++) { + sum += arr[i]; + sumSquare += arr[i] * arr[i]; + } + + const sumDiff: number = sum - totalSum; // x + y + const sumSquareDiff: number = sumSquare - totalSumSquare; // x^2 + y^2 + + const sumProduct: number = (sumDiff * sumDiff - sumSquareDiff) / 2; // xy + const discriminant: number = Math.sqrt(sumDiff * sumDiff - 4 * sumProduct); + + const x: number = (sumDiff + discriminant) / 2; + const y: number = (sumDiff - discriminant) / 2; + + return [x, y]; +} + ``` + + + + + ```python + from math import sqrt + +def findTwoRepeatedElements(n, arr): + totalSum = (n * (n + 1)) // 2 + totalSumSquare = (n * (n + 1) * (2 * n + 1)) // 6 + + sumVal = 0 + sumSquare = 0 + + for i in arr: + sumVal += i + sumSquare += i * i + + sumDiff = sumVal - totalSum # x + y + sumSquareDiff = sumSquare - totalSumSquare # x^2 + y^2 + + sumProduct = (sumDiff * sumDiff - sumSquareDiff) // 2 # xy + discriminant = int(sqrt(sumDiff * sumDiff - 4 * sumProduct)) + + x = (sumDiff + discriminant) // 2 + y = (sumDiff - discriminant) // 2 + + return [x, y] + + ``` + + + + + ```java + import java.util.*; + +class Main { + public static List findTwoRepeatedElements(int n, int[] arr) { + int totalSum = (n * (n + 1)) / 2; + int totalSumSquare = (n * (n + 1) * (2 * n + 1)) / 6; + + int sum = 0; + int sumSquare = 0; + + for (int i : arr) { + sum += i; + sumSquare += i * i; + } + + int sumDiff = sum - totalSum; // x + y + int sumSquareDiff = sumSquare - totalSumSquare; // x^2 + y^2 + + int sumProduct = (sumDiff * sumDiff - sumSquareDiff) / 2; // xy + int discriminant = (int) Math.sqrt(sumDiff * sumDiff - 4 * sumProduct); + + int x = (sumDiff + discriminant) / 2; + int y = (sumDiff - discriminant) / 2; + + List result = new ArrayList<>(); + result.add(x); + result.add(y); + return result; + } + + + + ``` + + + + + ```cpp +#include +#include +#include + +using namespace std; + +vector findTwoRepeatedElements(int n, vector& arr) { + const int totalSum = (n * (n + 1)) / 2; + const int totalSumSquare = (n * (n + 1) * (2 * n + 1)) / 6; + + int sum = 0; + int sumSquare = 0; + + for (int i = 0; i < arr.size(); i++) { + sum += arr[i]; + sumSquare += arr[i] * arr[i]; + } + + const int sumDiff = sum - totalSum; // x + y + const int sumSquareDiff = sumSquare - totalSumSquare; // x^2 + y^2 + + const int sumProduct = (sumDiff * sumDiff - sumSquareDiff) / 2; // xy + const int discriminant = sqrt(sumDiff * sumDiff - 4 * sumProduct); + + const int x = (sumDiff + discriminant) / 2; + const int y = (sumDiff - discriminant) / 2; + + return {x, y}; +} + + + + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(1)$$ + +
+ + +### Approach 3: Bit Manipulation + +The bit manipulation approach uses XOR to find the two repeating numbers. + +#### Implementation + +```jsx live +function findTwoRepeatedElements() { + const n = 4; + const arr = [4, 2, 4, 2, 3, 1]; + + const findRepeating = (n, arr) => { + let xor = 0; + for (let i = 0; i < arr.length; i++) { + xor ^= arr[i]; + } + for (let i = 1; i <= n; i++) { + xor ^= i; + } + + const setBit = xor & ~(xor - 1); + let x = 0, y = 0; + for (let i = 0; i < arr.length; i++) { + if (arr[i] & setBit) { + x ^= arr[i]; + } else { + y ^= arr[i]; + } + } + for (let i = 1; i <= n; i++) { + if (i & setBit) { + x ^= i; + } else { + y ^= i; + } + } + + let first = 0, second = 0; + for (let i = 0; i < arr.length; i++) { + if (arr[i] === x) { + first = x; + second = y; + break; + } + if (arr[i] === y) { + first = y; + second = x; + break; + } + } + + return [first, second]; + }; + + const result = findRepeating(n, arr); + return ( +
+

+ Input: n = {n}, arr = [{arr.join(", ")}] +

+

+ Output: [{result.join(", ")}] +

+
+ ); +} + +``` + +#### Code in Different Languages + + + + + ```javascript + function findTwoRepeated(arr) { + const n = arr.length - 2; + let xor = 0; + + for (let i = 0; i < arr.length; i++) { + xor ^= arr[i]; + } + + for (let i = 1; i <= n; i++) { + xor ^= i; + } + + const setBit = xor & -xor; + let x = 0, y = 0; + + for (let i = 0; i < arr.length; i++) { + if (arr[i] & setBit) { + x ^= arr[i]; + } else { + y ^= arr[i]; + } + } + + for (let i = 1; i <= n; i++) { + if (i & setBit) { + x ^= i; + } else { + y ^= i; + } + } + + return [x, y]; + } + ``` + + + + + ```typescript + function findTwoRepeated(arr: number[]): number[] { + const n = arr.length - 2; + let xor = 0; + + for (let i = 0; i < arr.length; i++) { + xor ^= arr[i]; + } + + for (let i = 1; i <= n; i++) { + xor ^= i; + } + + const setBit = xor & -xor; + let x = 0, y = 0; + + for (let i = 0; i < arr.length; i++) { + if (arr[i] & setBit) { + x ^= arr[i]; + } else { + y ^= arr[i]; + } + } + + for (let i = 1; i <= n; i++) { + if (i & setBit) { + x ^= i; + } else { + y ^= i; + } + } + + return [x, y]; + } + ``` + + + + + ```python + def findTwoRepeated(arr): + n = len(arr) - 2 + xor = 0 + + for num in arr: + xor ^= num + + for i in range(1, n + 1): + xor ^= i + + set_bit = xor & -xor + x = y = 0 + + for num in arr: + if num & set_bit: + x ^= num + else: + y ^= num + + for i in range(1, n + 1): + if i & set_bit: + x ^= i + else: + y ^= i + + return [x, y] + ``` + + + + + ```java + class Solution { + public int[] findTwoRepeated(int[] arr) { + int n = arr.length - 2; + int xor = 0; + + for (int num : arr) { + xor ^= num; + } + + for (int i = 1; i <= n; i++) { + xor ^= i; + } + + int setBit = xor & -xor; + int x = 0, y = 0; + + for (int num : arr) { + if ((num & setBit) != 0) { + x ^= num; + } else { + y ^= num; + } + } + + for (int i = 1; i <= n; i++) { + if ((i & setBit) != 0) { + x ^= i; + } else { + y ^= i; + } + } + + return new int[]{x, y}; + } + } + ``` + + + + + ```cpp + #include + + using namespace std; + + class Solution { + public: + vector findTwoRepeated(vector& arr) { + int n = arr.size() - 2; + int xorAll = 0; + + for (int num : arr) { + xorAll ^= num; + } + + for (int i = 1; i <= n; i++) { + xorAll ^= i; + } + + int setBit = xorAll & -xorAll; + int x = 0, y = 0; + + for (int num : arr) { + if (num & setBit) { + x ^= num; + } else { + y ^= num; + } + } + + for (int i = 1; i <= n; i++) { + if (i & setBit) { + x ^= i; + } else { + y ^= i; + } + } + + return {x, y}; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(1)$$ + +
+
+ +:::tip + +These are the three approaches to solve the Two Repeated Elements problem. Each approach has its own advantages and trade-offs in terms of time and space complexity. You can choose the one that best fits your requirements. + +::: +## References + +- **GeeksforGeeks Problem:** [GeeksforGeeks Problem](https://www.geeksforgeeks.org/problems/two-repeated-elements-1587115621/0) +- **Solution Link:** [Two Repeated Elements Solution on GeeksforGeeks](https://www.geeksforgeeks.org/problems/two-repeated-elements-1587115621/0) +- **Authors GeeksforGeeks Profile:** [Manish Kumar Gupta](https://www.geeksforgeeks.org/user/manishd5hla) + +--- \ No newline at end of file diff --git a/solutions/gfg-solutions/0010-paths-to-reach-origin.md b/solutions/gfg-solutions/0010-paths-to-reach-origin.md new file mode 100644 index 0000000..c592144 --- /dev/null +++ b/solutions/gfg-solutions/0010-paths-to-reach-origin.md @@ -0,0 +1,608 @@ +--- + +id: paths-to-reach-origin +title: Paths to Reach Origin +sidebar_label: 0010 Paths to Reach Origin +tags: +- Dynamic Programming +- Backtracking +- Recursion +- Combinatorics +- JavaScript +- Python +- Java +- C++ +description: "This document explores finding the number of paths to reach the origin (0, 0) on a grid." + +--- + +## Problem Description + +Imagine you are standing on a grid at point (`x`, `y`). You can only move down (y decreases) or right (x increases). Your goal is to reach the origin (0, 0). This document discusses how to find the total number of unique paths you can take to reach the origin. + +### Example + +**Input:** x = 3, y = 2 (Starting at point (3, 2)) + +**Output:** 3 + +There are three unique paths to reach the origin: + +1. Down, Down, Right (D-D-R) +2. Down, Right, Down (D-R-D) +3. Right, Down, Down (R-D-D) + +--- + +## Solutions for Finding Paths + +There are multiple approaches to solve this problem. Here, we will explore four common techniques: + + + + +### Approach 1: Recursive + +A recursive approach solves the problem by breaking down the larger problem into smaller subproblems. + +#### Implementation + +```javascript +class Solution { + ways(x, y) { + return this.help(x, y); + } + + help(i, j) { + // Base case + if (i === 0 && j === 0) return 1; + if (i < 0 || j < 0) return 0; + + // Recursive calls + const down = this.help(i - 1, j); + const right = this.help(i, j - 1); + + return down + right; + } +} +``` + +#### Codes in Different Languages + + + + + ```javascript + class Solution { + ways(x, y) { + return this.help(x, y); + } + + help(i, j) { + // Base case + if (i === 0 && j === 0) return 1; + if (i < 0 || j < 0) return 0; + + // Recursive calls + const down = this.help(i - 1, j); + const right = this.help(i, j - 1); + + return down + right; + } + } + ``` + + + + + + ```python + class Solution: + def ways(self, x, y): + return self.help(x, y) + + def help(self, i, j): + # Base case + if i == 0 and j == 0: + return 1 + if i < 0 or j < 0: + return 0 + + # Recursive calls + down = self.help(i - 1, j) + right = self.help(i, j - 1) + + return down + right + ``` + + + + ```java + class Solution { + public int ways(int x, int y) { + return help(x, y); + } + + private int help(int i, int j) { + // Base case + if (i == 0 && j == 0) return 1; + if (i < 0 || j < 0) return 0; + + // Recursive calls + int down = help(i - 1, j); + int right = help(i, j - 1); + + return down + right; + } + } + ``` + + + + + ```cpp + class Solution { + public: + int ways(int x, int y) { + return help(x, y); + } + + int help(int i, int j) { + // Base case + if (i == 0 && j == 0) return 1; + if (i < 0 || j < 0) return 0; + + // Recursive calls + int down = help(i - 1, j); + int right = help(i, j - 1); + + return down + right; + } + }; + ``` + + + +#### Complexity Analysis + +**Time Complexity:** $O(2^{x+y})$ +- In the worst case, each move (left or down) results in two recursive calls, leading to an exponential number of calls. + +**Space Complexity:** $O(x + y)$ +- The space complexity is due to the maximum depth of the recursion stack. + + + + +### Approach 2: Memoization + +Memoization is an optimization technique where we store the results of expensive function calls and reuse them when the same inputs occur again. + +#### Implementation + +```javascript +class Solution { + constructor() { + this.memo = {}; + } + + ways(x, y) { + return this.help(x, y); + } + + help(i, j) { + // Base case + if (i === 0 && j === 0) return 1; + if (i < 0 || j < 0) return 0; + + const key = `${i},${j}`; + if (this.memo[key] !== undefined) return this.memo[key]; + + // Recursive calls + const down = this.help(i - 1, j); + const right = this.help(i, j - 1); + + this.memo[key] = down + right; + return this.memo[key]; + } +} +``` + +#### Codes in Different Languages + + + + + ```javascript + class Solution { + constructor() { + this.memo = {}; + } + + ways(x, y) { + return this.help(x, y); + } + + help(i, j) { + // Base case + if (i === 0 && j === 0) return 1; + if (i < 0 || j < 0) return 0; + + const key = `${i},${j}`; + if (this.memo[key] !== undefined) return this.memo[key]; + + // Recursive calls + const down = this.help(i - 1, j); + const right = this.help(i, j - 1); + + this.memo[key] = down + right; + return this.memo[key]; + } + } + ``` + + + + + + ```python + class Solution: + def __init__(self): + self.memo = {} + + def ways(self, x, y): + return self.help(x, y) + + def help(self, i, j): + # Base case + if i == 0 and j == 0: + return 1 + if i < 0 or j < 0: + return 0 + + key = (i, j) + if key in self.memo: + return self.memo[key] + + # Recursive calls + down = self.help(i - 1, j) + right = self.help(i, j - 1) + + self.memo[key] = down + right + return self.memo[key] + ``` + + + + + ```java + import java.util.HashMap; + import java.util.Map; + + class Solution { + private Map memo = new HashMap<>(); + + public int ways(int x, int y) { + return help(x, y); + } + + private int help(int i, int j) { + // Base case + if (i == 0 && j == 0) return 1; + if (i < 0 || j < 0) return 0; + + String key = i + "," + j; + if (memo.containsKey(key)) return memo.get(key); + + // Recursive calls + int down = help(i - 1, j); + int right = help(i, j - 1); + + memo.put(key, down + right); + return memo.get(key); + } + } + ``` + + + + ```cpp + #include + #include + using namespace std; + + class Solution { + unordered_map memo; + + public: + int ways(int x, int y) { + return help(x, y); + } + + int help(int i, int j) { + // Base case + if (i == 0 && j == 0) return 1; + if (i < 0 || j < 0) return 0; + + string key = to_string(i) + "," + to_string(j); + if (memo.find(key) != memo.end()) return memo[key]; + + // Recursive calls + int down = help(i - 1, j); + int right = help(i, j - 1); + + memo[key] = down + right; + return + + memo[key]; + } + }; + ``` + + + +#### Complexity Analisys + +**Time Complexity:** $O(x \cdot y)$ +- Each subproblem is solved once and stored in the memoization table. + +**Space Complexity:** $O(x \cdot y)$ +- Space is used for the memoization table. + + + + +### Approach 3: Tabulation + +Tabulation is a bottom-up dynamic programming technique where we solve smaller subproblems first and use their results to build up solutions to larger subproblems. + +#### Implementation + +```javascript +class Solution { + ways(x, y) { + const dp = Array.from({ length: x + 1 }, () => Array(y + 1).fill(0)); + dp[0][0] = 1; + + for (let i = 0; i <= x; i++) { + for (let j = 0; j <= y; j++) { + if (i > 0) dp[i][j] += dp[i - 1][j]; + if (j > 0) dp[i][j] += dp[i][j - 1]; + } + } + + return dp[x][y]; + } +} +``` + +#### Codes in Different Languages + + + + + ```javascript + class Solution { + ways(x, y) { + const dp = Array.from({ length: x + 1 }, () => Array(y + 1).fill(0)); + dp[0][0] = 1; + + for (let i = 0; i <= x; i++) { + for (let j = 0; j <= y; j++) { + if (i > 0) dp[i][j] += dp[i - 1][j]; + if (j > 0) dp[i][j] += dp[i][j - 1]; + } + } + + return dp[x][y]; + } + } + ``` + + + + + ```python + class Solution: + def ways(self, x, y): + dp = [[0] * (y + 1) for _ in range(x + 1)] + dp[0][0] = 1 + + for i in range(x + 1): + for j in range(y + 1): + if i > 0: + dp[i][j] += dp[i - 1][j] + if j > 0: + dp[i][j] += dp[i][j - 1] + + return dp[x][y] + ``` + + + + ```java + class Solution { + public int ways(int x, int y) { + int[][] dp = new int[x + 1][y + 1]; + dp[0][0] = 1; + + for (int i = 0; i <= x; i++) { + for (int j = 0; j <= y; j++) { + if (i > 0) dp[i][j] += dp[i - 1][j]; + if (j > 0) dp[i][j] += dp[i][j - 1]; + } + } + + return dp[x][y]; + } + } + ``` + + + + ```cpp + #include + using namespace std; + + class Solution { + public: + int ways(int x, int y) { + vector> dp(x + 1, vector(y + 1, 0)); + dp[0][0] = 1; + + for (int i = 0; i <= x; i++) { + for (int j = 0; j <= y; j++) { + if (i > 0) dp[i][j] += dp[i - 1][j]; + if (j > 0) dp[i][j] += dp[i][j - 1]; + } + } + + return dp[x][y]; + } + }; + ``` + + + +#### Complexity Analysis + +**Time Complexity:** $O(x \cdot y)$ +- Filling up the table involves computing values for $x \times y$ cells. + +**Space Complexity:** $O(x \cdot y)$ +- Space is used for the 2D table. + + + + +### Approach 4: Space Optimization + +Space optimization improves the efficiency of the tabulation method by reducing the amount of space used. + +#### Implementation + +```javascript +class Solution { + ways(x, y) { + const dp = Array(y + 1).fill(0); + dp[0] = 1; + + for (let i = 0; i <= x; i++) { + for (let j = 1; j <= y; j++) { + dp[j] += dp[j - 1]; + } + } + + return dp[y]; + } +} +``` + +#### Codes in Different Languages + + + + + ```javascript + class Solution { + ways(x, y) { + const dp = Array(y + 1).fill(0); + dp[0] = 1; + + for (let i = 0; i <= x; i++) { + for (let j = 1; j <= y; j++) { + dp[j] += dp[j - 1]; + } + } + + return dp[y]; + } + } + ``` + + + + + ```python + class Solution: + def ways(self, x, y): + dp = [0] * (y + 1) + dp[0] = 1 + + for i in range(x + 1): + for j in range(1, y + 1): + dp[j] += dp[j - 1] + + return dp[y] + ``` + + + + ```java + class Solution { + public int ways(int x, int y) { + int[] dp = new int[y + 1]; + dp[0] = 1; + + for (int i = 0; i <= x; i++) { + for (int j = 1; j <= y; j++) { + dp[j] += dp[j - 1]; + } + } + + return dp[y]; + } + } + ``` + + + + ```cpp + #include + using namespace std; + + class Solution { + public: + int ways(int x, int y) { + vector dp(y + 1, 0); + dp[0] = 1; + + for (int i = 0; i <= x; i++) { + for (int j = 1; j <= y; j++) { + dp[j] += dp[j - 1]; + } + } + + return dp[y]; + } + }; + ``` + + + +#### Complexity Analysis + +**Time Complexity:** $O(x \cdot y)$ +- The same number of computations as in tabulation. + +**Space Complexity:** $O(y)$ +- Only a single array of size $y + 1$ is used. + + + + +:::tip + +When choosing an approach, consider both time and space complexities. For smaller inputs, simpler approaches like recursion might be sufficient, but for larger inputs, optimized solutions like memoization, tabulation, or space-optimized tabulation are more efficient and practical. Always analyze the constraints and requirements of your problem to select the most appropriate method. + +Would you like any additional information or another example? + +::: + +--- + +## References + +- **LeetCode Problem**: [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/maximum-depth-of-binary-tree/solution/) +- **Authors GeeksforGeeks Profile:** [Vipul](https://www.geeksforgeeks.org/user/lakumvipwjge/) diff --git a/solutions/gfg-solutions/0020-climbing-stairs.md b/solutions/gfg-solutions/0020-climbing-stairs.md new file mode 100644 index 0000000..7031582 --- /dev/null +++ b/solutions/gfg-solutions/0020-climbing-stairs.md @@ -0,0 +1,531 @@ +--- +id: climbing-stairs +title: Climbing Stairs +sidebar_label: 0020 Climbing Stairs +tags: +- Dynamic Programming +- Recursion +- Memoization +- Tabulation +- Space Optimization +- JavaScript +- TypeScript +- Python +- Java +- C++ +description: "This document explores different approaches to solving the climbing stairs problem, including recursion, memoization, tabulation, and space optimization." +--- +## Problem + +You are climbing a staircase. It takes `n` steps to reach the top. + +Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? + +### Examples + +**Example 1:** + +Input: `n = 2` +Output: `2` +Explanation: There are two ways to climb to the top: +1. 1 step + 1 step +2. 2 steps + +**Example 2:** + +Input: `n = 3` +Output: `3` +Explanation: There are three ways to climb to the top: +1. 1 step + 1 step + 1 step +2. 1 step + 2 steps +3. 2 steps + 1 step + +### Constraints + +- $ 1 \leq n \leq 45 $ + +## Solution + +### Intuition + +To calculate the number of ways to climb the stairs, we can observe that when we are on the nth stair, we have two options: + +- Either we climbed one stair from the (n-1)th stair +- Or we climbed two stairs from the (n-2)th stair + +By leveraging this observation, we can break down the problem into smaller subproblems and apply the concept of the Fibonacci series. The base cases are when we are on the 1st stair (only one way to reach it) and the 2nd stair (two ways to reach it). By summing up the number of ways to reach the (n-1)th and (n-2)th stairs, we can compute the total number of ways to climb the stairs. This allows us to solve the problem efficiently using various dynamic programming techniques such as recursion, memoization, tabulation, or space optimization. + + + + +### Approach 1: Recursive + +A recursive approach solves the problem by breaking down the larger problem into smaller subproblems. + +#### Implementation + +```javascript +class Solution { + climbStairs(n) { + if (n === 0 || n === 1) { + return 1; + } + return this.climbStairs(n - 1) + this.climbStairs(n - 2); + } +} +``` + +#### Codes in Different Languages + + + + + ```javascript + class Solution { + climbStairs(n) { + if (n === 0 || n === 1) { + return 1; + } + return this.climbStairs(n - 1) + this.climbStairs(n - 2); + } + } + ``` + + + + + + ```python + class Solution: + def climbStairs(self, n: int) -> int: + if n == 0 or n == 1: + return 1 + return self.climbStairs(n-1) + self.climbStairs(n-2) + ``` + + + + ```java + class Solution { + public int climbStairs(int n) { + if (n == 0 || n == 1) { + return 1; + } + return climbStairs(n-1) + climbStairs(n-2); + } + } + ``` + + + + + ```cpp + class Solution { + public: + int ways(int x, int y) { + return help(x, y); + } + + int help(int i, int j) { + // Base case + if (i == 0 && j == 0) return 1; + if (i < 0 || j < 0) return 0; + + // Recursive calls + int down = help(i - 1, j); + int right = help(i, j - 1); + + return down + right; + } + }; + ``` + + + +#### Complexity Analysis + +**Time Complexity:** $O(2^{x+y})$ +- In the worst case, each move (left or down) results in two recursive calls, leading to an exponential number of calls. + +**Space Complexity:** $O(x + y)$ +- The space complexity is due to the maximum depth of the recursion stack. + + + + +### Approach 2: Memoization + +The memoization approach optimizes the recursive solution by caching previously computed results to avoid redundant calculations. + +#### Implementation + +```javascript +class Solution { + climbStairs(n, memo = new Map()) { + if (n === 0 || n === 1) { + return 1; + } + + if (!memo.has(n)) { + memo.set(n, this.climbStairs(n - 1, memo) + this.climbStairs(n - 2, memo)); + } + + return memo.get(n); + } + + climbStairs(n) { + const memo = new Map(); + return this.climbStairs(n, memo); + } +} +``` + +#### Codes in Different Languages + + + + + ```javascript + class Solution { + climbStairs(n, memo = new Map()) { + if (n === 0 || n === 1) { + return 1; + } + + if (!memo.has(n)) { + memo.set(n, this.climbStairs(n - 1, memo) + this.climbStairs(n - 2, memo)); + } + + return memo.get(n); + } + + climbStairs(n) { + const memo = new Map(); + return this.climbStairs(n, memo); + } + } + ``` + + + + + + ```python + class Solution: + def climbStairs(self, n: int) -> int: + memo = {} + return self.helper(n, memo) + + def helper(self, n: int, memo: dict[int, int]) -> int: + if n == 0 or n == 1: + return 1 + if n not in memo: + memo[n] = self.helper(n-1, memo) + self.helper(n-2, memo) + return memo[n] + ``` + + + + ```java + class Solution { + public int climbStairs(int n) { + Map memo = new HashMap<>(); + return climbStairs(n, memo); + } + + private int climbStairs(int n, Map memo) { + if (n == 0 || n == 1) { + return 1; + } + if (!memo.containsKey(n)) { + memo.put(n, climbStairs(n-1, memo) + climbStairs(n-2, memo)); + } + return memo.get(n); + } + } + ``` + + + + + ```cpp + class Solution { + public: + int climbStairs(int n, unordered_map& memo) { + if (n == 0 || n == 1) { + return 1; + } + if (memo.find(n) == memo.end()) { + memo[n] = climbStairs(n-1, memo) + climbStairs(n-2, memo); + } + return memo[n]; + } + + int climbStairs(int n) { + unordered_map memo; + return climbStairs(n, memo); + } + }; + ``` + + + +#### Complexity Analysis + +**Time Complexity:** $O(x * y)$ +- The memoization approach reduces the time complexity to linear by caching previously computed results. + +**Space Complexity:** $O(x * y)$ +- The space complexity is determined by the size of the memoization table. + +Here is the content for the 'Tabulation' and 'Space Optimization' approaches in the 'climb-stair.md' file: + + + +### Approach 3: Tabulation + +The tabulation approach solves the problem iteratively using dynamic programming. It builds a DP table to store the number of ways to reach each step from the base cases (0 and 1 steps) up to the target step. By iterating through the table and filling in values based on the results of previous steps, we compute the total number of ways to climb the stairs. + +#### Implementation + +```javascript +class Solution { + climbStairs(n) { + if (n === 0 || n === 1) { + return 1; + } + + const dp = new Array(n + 1).fill(0); + dp[0] = dp[1] = 1; + + for (let i = 2; i <= n; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; + } +} +``` + +#### Codes in Different Languages + + + + + ```javascript + class Solution { + climbStairs(n) { + if (n === 0 || n === 1) { + return 1; + } + + const dp = new Array(n + 1).fill(0); + dp[0] = dp[1] = 1; + + for (let i = 2; i <= n; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; + } + } + ``` + + + + ```python + class Solution: + def climbStairs(self, n: int) -> int: + if n == 0 or n == 1: + return 1 + + dp = [0] * (n+1) + dp[0] = dp[1] = 1 + + for i in range(2, n+1): + dp[i] = dp[i-1] + dp[i-2] + return dp[n] + ``` + + + + ```java + class Solution { + public int climbStairs(int n) { + if (n == 0 || n == 1) { + return 1; + } + + int[] dp = new int[n+1]; + dp[0] = dp[1] = 1; + + for (int i = 2; i <= n; i++) { + dp[i] = dp[i-1] + dp[i-2]; + } + return dp[n]; + } + } + ``` + + + + ```cpp + class Solution { + public: + int climbStairs(int n) { + if (n == 0 || n == 1) { + return 1; + } + + vector dp(n+1); + dp[0] = dp[1] = 1; + + for (int i = 2; i <= n; i++) { + dp[i] = dp[i-1] + dp[i-2]; + } + return dp[n]; + } + }; + ``` + + + +#### Complexity Analysis + +**Time Complexity:** $O(n)$ +- The tabulation approach iterates through the DP table once, filling in each cell with constant time operations, resulting in linear time complexity. + +**Space Complexity:** $O(n)$ +- The space complexity is determined by the size of the DP table, which stores values for each step up to the target step. + + + + +### Approach 4: Space Optimization + +The space-optimized approach improves upon the tabulation method by reducing the space complexity. Instead of storing the entire DP table, we only keep track of the previous two values since they are sufficient to compute the current value. By updating these values in each iteration, we compute the total number of ways to climb the stairs with constant space usage. + +#### Implementation + +```javascript +class Solution { + climbStairs(n) { + if (n === 0 || n === 1) { + return 1; + } + + let prev = 1, curr = 1; + for (let i = 2; i <= n; i++) { + let temp = curr; + curr = prev + curr; + prev = temp; + } + + return curr; + } +} +``` + +#### Codes in Different Languages + + + + + ```javascript + class Solution { + climbStairs(n) { + if (n === 0 || n === 1) { + return 1; + } + + let prev = 1, curr = 1; + for (let i = 2; i <= n; i++) { + let temp = curr; + curr = prev + curr; + prev = temp; + } + + return curr; + } +} + ``` + + + + ```python + class Solution: + def climbStairs(self, n: int) -> int: + if n == 0 or n == 1: + return 1 + prev, curr = 1, 1 + for i in range(2, n+1): + temp = curr + curr = prev + curr + prev = temp + return curr + ``` + + + + ```java + class Solution { + public int climbStairs(int n) { + if (n == 0 || n == 1) { + return 1; + } + int prev = 1, curr = 1; + for (int i = 2; i <= n; i++) { + int temp = curr; + curr = prev + curr; + prev = temp; + } + return curr; + } + } + ``` + + + + ```cpp + class Solution { + public: + int climbStairs(int n) { + if (n == 0 || n == 1) { + return 1; + } + int prev = 1, curr = 1; + for (int i = 2; i <= n; i++) { + int temp = curr; + curr = prev + curr; + prev = temp; + } + return curr; + } + }; + ``` + + + +#### Complexity Analysis + +**Time Complexity:** $O(n)$ +- The space-optimized approach iterates through the steps once, updating only two variables in constant time per iteration, resulting in linear time complexity. + +**Space Complexity:** $O(1)$ +- The space complexity is constant since we only use two variables to store the previous two values. + + + +:::tip + +When choosing an approach, consider both time and space complexities. For smaller inputs, simpler approaches like recursion might be sufficient, but for larger inputs, optimized solutions like memoization, tabulation, or space-optimized tabulation are more efficient and practical. Always analyze the constraints and requirements of your problem to select the most appropriate method. + +::: + +--- + +## References + +- **LeetCode Problem**: [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/maximum-depth-of-binary-tree/solution/) +- **Authors GeeksforGeeks Profile:** [Vipul](https://www.geeksforgeeks.org/user/lakumvipwjge/) \ No newline at end of file diff --git a/solutions/gfg-solutions/0021-gray-to-binary-equivalent.md b/solutions/gfg-solutions/0021-gray-to-binary-equivalent.md new file mode 100644 index 0000000..068a2d2 --- /dev/null +++ b/solutions/gfg-solutions/0021-gray-to-binary-equivalent.md @@ -0,0 +1,848 @@ +--- +id: gray-to-binary-equivalent +title: Gray to Binary Equivalent +sidebar_label: 0021 Gray to Binary Equivalent +tags: + - Bit Manipulation + - Brute Force + - Optimization + - Space Complexity + - Time Complexity + - JavaScript + - TypeScript + - Python + - Java + - C++ +description: "This document explores different approaches to solving the Gray to Binary Equivalent problem, including brute force, bit manipulation, and optimization techniques, in various programming languages." +--- + +## Problem + +Given an integer number `n`, which is a decimal representation of Gray Code, find the binary equivalent of the Gray Code and return the decimal representation of the binary equivalent. + +![table](https://media.geeksforgeeks.org/img-practice/ScreenShot2021-08-27at10-1630039200.png) + +### Example + +**Example 1:** + +``` +Input: +n = 4 + +Output: +7 + +Explanation: +Given 4, its gray code = 110. +Binary equivalent of the gray code 110 is 100. +Return 7 representing gray code 100. +``` + +**Example 2:** + +``` +Input: +n = 15 + +Output: +10 +Explanation: + +Given 15 representing gray code 1000. +Binary equivalent of gray code 1000 is 1111. +Return 10 representing gray code 1111 (binary 1010). +``` + + +**Your Task:** You don't need to read input or print anything. Your task is to complete the function `grayToBinary()` which accepts an integer `n` as an input parameter and returns the decimal representation of the binary equivalent of the given gray code. + +- Expected Time Complexity: $ O(log (n)) $. +- Expected Auxiliary Space: $O(1)$ . + +### Constraints: +- $ 0 <= n <= 10^9$ + +## Solutions + + + + +### Brute Force + + This approach uses brute force by first converting the decimal number to binary and then applying Gray Code logic to find the decimal representation of the binary equivalent. + +#### Implementation +- Convert decimal to binary. +- Apply Gray Code logic to get binary equivalent. +- Convert binary back to decimal. + +```jsx live +function GrayToBinaryBruteForce() { + const decimalInput = 15; // Sample input + + const grayToBinaryBruteForce = function (n) { + let binary = []; + while (n) { + binary.push(n % 2); + n = Math.floor(n / 2); + } + while (binary.length < 32) { + binary.push(0); + } + binary.reverse(); + + let grayCode = []; + let j = 0; + while (binary[j] === 0) { + j++; + } + grayCode[j] = binary[j]; + for (let i = j + 1; i < 32; i++) { + grayCode[i] = grayCode[i - 1] ^ binary[i]; + } + + let grayCodeNum = 0; + for (let i = 31; i >= 0; i--) { + if (grayCode[i]) { + grayCodeNum += Math.pow(2, 31 - i); + } + } + + return grayCodeNum; + }; + + const result = grayToBinaryBruteForce(decimalInput); + + return ( +
+

+ Input: n = {decimalInput} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Code Snippets + + + + + + ```javascript +class Solution { + decimalToBinary(binary, n) { + while (n) { + if (n % 2) binary.push(1); + else binary.push(0); + n = Math.floor(n / 2); + } + + while (binary.length < 32) binary.push(0); + + binary.reverse(); + } + + help(binary) { + const grayCode = new Array(32).fill(0); + + let j = 0; + while (binary[j] === 0) j++; + + grayCode[j] = binary[j]; + for (let i = j + 1; i < 32; i++) { + grayCode[i] = grayCode[i - 1] ^ binary[i]; + } + + let grayCodeNum = 0; + for (let i = 31; i >= 0; i--) { + if (grayCode[i]) grayCodeNum += 2 ** (31 - i); + } + + return grayCodeNum; + } + + grayToBinary(n) { + const binary = []; + this.decimalToBinary(binary, n); + return this.help(binary); + } +} + + ``` + + + + + ```typescript +class Solution { + decimalToBinary(binary: number[], n: number): void { + while (n) { + if (n % 2) binary.push(1); + else binary.push(0); + n = Math.floor(n / 2); + } + + while (binary.length < 32) binary.push(0); + + binary.reverse(); + } + + help(binary: number[]): number { + const grayCode: number[] = new Array(32).fill(0); + + let j = 0; + while (binary[j] === 0) j++; + + grayCode[j] = binary[j]; + for (let i = j + 1; i < 32; i++) { + grayCode[i] = grayCode[i - 1] ^ binary[i]; + } + + let grayCodeNum = 0; + for (let i = 31; i >= 0; i--) { + if (grayCode[i]) grayCodeNum += 2 ** (31 - i); + } + + return grayCodeNum; + } + + grayToBinary(n: number): number { + const binary: number[] = []; + this.decimalToBinary(binary, n); + return this.help(binary); + } +} + + ``` + + + + + ```cpp +class Solution{ + public: + void decimalToBinary(vector& binary,int n) + { + while(n) + { + if((n%2)) + binary.push_back(1); + else + binary.push_back(0); + + n/=2; + } + + while(binary.size()<32) + binary.push_back(0); + + reverse(binary.begin(),binary.end()); + } + int help(vector& binary) + { + vector grayCode(32,0); + + int j=0; + while(binary[j]==0) + j++; + + grayCode[j]=binary[j]; + for(int i=j+1;i<32;i++) + grayCode[i]=grayCode[i-1]^binary[i]; + + int grayCodeNum=0; + for(int i=31;i>=0;i--) + { + if(grayCode[i]) + grayCodeNum+=pow(2,31-i); + } + return grayCodeNum; + } + int grayToBinary(int n) + { + vector binary; + decimalToBinary(binary,n); + return help(binary); + } +}; + ``` + + + + + ```python +class Solution: + def decimalToBinary(self, binary, n): + while n: + if n % 2: + binary.append(1) + else: + binary.append(0) + n //= 2 + + while len(binary) < 32: + binary.append(0) + + binary.reverse() + + def help(self, binary): + grayCode = [0] * 32 + + j = 0 + while binary[j] == 0: + j += 1 + + grayCode[j] = binary[j] + for i in range(j + 1, 32): + grayCode[i] = grayCode[i - 1] ^ binary[i] + + grayCodeNum = 0 + for i in range(31, -1, -1): + if grayCode[i]: + grayCodeNum += 2 ** (31 - i) + + return grayCodeNum + + def grayToBinary(self, n): + binary = [] + self.decimalToBinary(binary, n) + return self.help(binary) + + ``` + + + + + ```java +import java.util.*; + +class Solution { + void decimalToBinary(ArrayList binary, int n) { + while (n > 0) { + if (n % 2 == 1) binary.add(1); + else binary.add(0); + n /= 2; + } + + while (binary.size() < 32) binary.add(0); + + Collections.reverse(binary); + } + + int help(ArrayList binary) { + int[] grayCode = new int[32]; + + int j = 0; + while (binary.get(j) == 0) j++; + + grayCode[j] = binary.get(j); + for (int i = j + 1; i < 32; i++) { + grayCode[i] = grayCode[i - 1] ^ binary.get(i); + } + + int grayCodeNum = 0; + for (int i = 31; i >= 0; i--) { + if (grayCode[i] == 1) grayCodeNum += Math.pow(2, 31 - i); + } + + return grayCodeNum; + } + + int grayToBinary(int n) { + ArrayList binary = new ArrayList<>(); + decimalToBinary(binary, n); + return help(binary); + } +} + ``` + + + + +#### Complexity Analysis +- Time complexity: O(logN) +- Space complexity: O(32) (constant) + +
+ + + +### Bit Manipulation + + This approach utilizes bit manipulation to directly compute the Gray Code's binary equivalent without converting to binary first. + +#### Implementation + +- Use bit manipulation to apply Gray Code logic directly. + +```jsx live +function GrayToBinaryBitManipulation() { + const decimalInput = 15; // Sample input + + const grayToBinaryBitManipulation = function (n) { + let grayCodeDecimal = 0; + let mask = 0; + let i = 0; + while (n > 0) { + if (i % 2 === 0) { + grayCodeDecimal ^= n; + } else { + mask ^= n; + } + n >>= 1; + i++; + } + grayCodeDecimal ^= mask; + return grayCodeDecimal; + }; + + const result = grayToBinaryBitManipulation(decimalInput); + + return ( +
+

+ Input: n = {decimalInput} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Code Snippets + + + + + ```javascript +class Solution { + help(n) { + const grayCode = new Array(32).fill(0); + + let j = 0; + while (j <= 31 && (n & (1 << (31 - j))) === 0) { + j++; + } + + grayCode[j] = !!(n & (1 << (31 - j))); + for (let i = j + 1; i < 32; i++) { + const bin = !!(n & (1 << (31 - i))); + const gray = grayCode[i - 1]; + grayCode[i] = bin ^ gray; + } + + let grayCodeDecimal = 0; + for (let i = 31; i >= 0; i--) { + if (grayCode[i]) { + grayCodeDecimal |= (1 << (31 - i)); + } + } + + return grayCodeDecimal; + } + + grayToBinary(n) { + return this.help(n); + } +} + ``` + + + + + ```typescript +class Solution { + help(n: number): number { + const grayCode: number[] = new Array(32).fill(0); + + let j = 0; + while (j <= 31 && (n & (1 << (31 - j))) === 0) { + j++; + } + + grayCode[j] = !!(n & (1 << (31 - j))); + for (let i = j + 1; i < 32; i++) { + const bin = !!(n & (1 << (31 - i))); + const gray = grayCode[i - 1]; + grayCode[i] = bin ^ gray; + } + + let grayCodeDecimal = 0; + for (let i = 31; i >= 0; i--) { + if (grayCode[i]) { + grayCodeDecimal |= (1 << (31 - i)); + } + } + + return grayCodeDecimal; + } + + grayToBinary(n: number): number { + return this.help(n); + } +} + ``` + + + + + ```cpp +class Solution{ + public: + int help(int n) + { + vector grayCode(32,0); + + int j=0; + while(j<=31 and (n&(1<<(31-j)))==0) + j++; + + grayCode[j]=bool(n&(1<<(31-j))); + for(int i=j+1;i<32;i++) + { + int bin=bool(n&(1<<(31-i))); + int gray=grayCode[i-1]; + grayCode[i]=bin^gray; + } + + int grayCodeDecimal=0; + for(int i=31;i>=0;i--) + { + if(grayCode[i]) + grayCodeDecimal|=(1<<31-i); + } + + return grayCodeDecimal; + } + int grayToBinary(int n) + { + return help(n); + } +}; + ``` + + + + + ```python +class Solution: + def help(self, n): + grayCode = [0] * 32 + + j = 0 + while j <= 31 and (n & (1 << (31 - j))) == 0: + j += 1 + + grayCode[j] = bool(n & (1 << (31 - j))) + for i in range(j + 1, 32): + bin_val = bool(n & (1 << (31 - i))) + gray_val = grayCode[i - 1] + grayCode[i] = bin_val ^ gray_val + + grayCodeDecimal = 0 + for i in range(31, -1, -1): + if grayCode[i]: + grayCodeDecimal |= (1 << (31 - i)) + + return grayCodeDecimal + + def grayToBinary(self, n): + return self.help(n) + ``` + + + + + ```java + import java.util.*; + +class Solution { + int help(int n) { + int[] grayCode = new int[32]; + + int j = 0; + while (j <= 31 && (n & (1 << (31 - j))) == 0) { + j++; + } + + grayCode[j] = (n & (1 << (31 - j))) == 0 ? 0 : 1; + for (int i = j + 1; i < 32; i++) { + int bin = (n & (1 << (31 - i))) == 0 ? 0 : 1; + int gray = grayCode[i - 1]; + grayCode[i] = bin ^ gray; + } + + int grayCodeDecimal = 0; + for (int i = 31; i >= 0; i--) { + if (grayCode[i] == 1) { + grayCodeDecimal |= (1 << (31 - i)); + } + } + + return grayCodeDecimal; + } + + int grayToBinary(int n) { + return help(n); + } +} + ``` + + + + +#### Complexity Analysis: +- Time complexity: O(32) (constant) +- Space complexity: O(32) (constant) + +
+ + + +### Optimized + + This approach optimizes the bit manipulation approach by directly calculating the Gray Code's binary equivalent without using extra storage. + +#### Implementation + +- Use bit manipulation without extra storage. + +```jsx live +function GrayToBinaryOptimized() { + const decimalInput = 15; // Sample input + + const grayToBinaryOptimized = function (n) { + let ans = 0; + while (n > 0) { + ans ^= n; + n >>= 1; + } + return ans; + }; + + const result = grayToBinaryOptimized(decimalInput); + + return ( +
+

+ Input: n = {decimalInput} +

+

+ Output: {result} +

+
+ ); +} +``` + + +#### Code Snippets + + + + + ```javascript +class Solution { + help(n) { + const grayCode = new Array(32).fill(0); + + let j = 0; + while (j <= 31 && (n & (1 << (31 - j))) === 0) { + j++; + } + + grayCode[j] = !!(n & (1 << (31 - j))); + for (let i = j + 1; i < 32; i++) { + const bin = !!(n & (1 << (31 - i))); + const gray = grayCode[i - 1]; + grayCode[i] = bin ^ gray; + } + + let grayCodeDecimal = 0; + for (let i = 31; i >= 0; i--) { + if (grayCode[i]) { + grayCodeDecimal |= (1 << (31 - i)); + } + } + + return grayCodeDecimal; + } + + grayToBinary(n) { + return this.help(n); + } +} + ``` + + + + + ```typescript +class Solution { + help(n: number): number { + const grayCode: number[] = new Array(32).fill(0); + + let j = 0; + while (j <= 31 && (n & (1 << (31 - j))) === 0) { + j++; + } + + grayCode[j] = !!(n & (1 << (31 - j))); + for (let i = j + 1; i < 32; i++) { + const bin = !!(n & (1 << (31 - i))); + const gray = grayCode[i - 1]; + grayCode[i] = bin ^ gray; + } + + let grayCodeDecimal = 0; + for (let i = 31; i >= 0; i--) { + if (grayCode[i]) { + grayCodeDecimal |= (1 << (31 - i)); + } + } + + return grayCodeDecimal; + } + + grayToBinary(n: number): number { + return this.help(n); + } +} + ``` + + + + + ```cpp +class Solution{ + public: + int help(int n) + { + vector grayCode(32,0); + + int j=0; + while(j<=31 and (n&(1<<(31-j)))==0) + j++; + + grayCode[j]=bool(n&(1<<(31-j))); + for(int i=j+1;i<32;i++) + { + int bin=bool(n&(1<<(31-i))); + int gray=grayCode[i-1]; + grayCode[i]=bin^gray; + } + + int grayCodeDecimal=0; + for(int i=31;i>=0;i--) + { + if(grayCode[i]) + grayCodeDecimal|=(1<<31-i); + } + + return grayCodeDecimal; + } + int grayToBinary(int n) + { + return help(n); + } +}; + ``` + + + + + ```python + class Solution: + def help(self, n): + grayCode = [0] * 32 + + j = 0 + while j <= 31 and (n & (1 << (31 - j))) == 0: + j += 1 + + grayCode[j] = bool(n & (1 << (31 - j))) + for i in range(j + 1, 32): + bin_val = bool(n & (1 << (31 - i))) + gray_val = grayCode[i - 1] + grayCode[i] = bin_val ^ gray_val + + grayCodeDecimal = 0 + for i in range(31, -1, -1): + if grayCode[i]: + grayCodeDecimal |= (1 << (31 - i)) + + return grayCodeDecimal + + def grayToBinary(self, n): + return self.help(n) + ``` + + + + + ```java +import java.util.*; + +class Solution { + int help(int n) { + int[] grayCode = new int[32]; + + int j = 0; + while (j <= 31 && (n & (1 << (31 - j))) == 0) { + j++; + } + + grayCode[j] = (n & (1 << (31 - j))) == 0 ? 0 : 1; + for (int i = j + 1; i < 32; i++) { + int bin = (n & (1 << (31 - i))) == 0 ? 0 : 1; + int gray = grayCode[i - 1]; + grayCode[i] = bin ^ gray; + } + + int grayCodeDecimal = 0; + for (int i = 31; i >= 0; i--) { + if (grayCode[i] == 1) { + grayCodeDecimal |= (1 << (31 - i)); + } + } + + return grayCodeDecimal; + } + + int grayToBinary(int n) { + return help(n); + } +} + ``` + + + + +#### Complexity Analysis + +- Time complexity: O(32) (constant) +- Space complexity: O(1) (constant) + +
+
+ +:::tip Note + +To convert Gray code to binary efficiently, consider using bit manipulation techniques. Bitwise operations such as XOR (^) can be particularly useful in simplifying the conversion process, leading to optimized solutions with constant time complexity. + +::: + +--- + +## References + +- **LeetCode Problem:** [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) +- **Solution Link:** [Best Time to Buy and Sell Stock Solution on LeetCode](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/solutions/) +- **Authors GeeksforGeeks Profile:** [Vipul lakum](https://www.geeksforgeeks.org/user/lakumvipwjge/) diff --git a/solutions/gfg-solutions/0022-lemonade-change.md b/solutions/gfg-solutions/0022-lemonade-change.md new file mode 100644 index 0000000..2bd5a14 --- /dev/null +++ b/solutions/gfg-solutions/0022-lemonade-change.md @@ -0,0 +1,254 @@ +--- +id: lemonade-change +title: Lemonade Change +sidebar_label: 0022 Lemonade Change +tags: +- Greedy Algorithm +- JavaScript +- TypeScript +- Python +- Java +- C++ +description: "This document explores different approaches to solving the lemonade change problem, including an easy C++ solution with a greedy algorithm approach." +--- + +## Problem + +You are an owner of lemonade island, each lemonade costs \$5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by given array `bills[]`). Each customer will only buy one lemonade and pay with either a \$5, \$10, or \$20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays \$5. + +**Note:** At first, you do not have any bill to provide changes with. You can provide changes from the bills that you get from the previous customers. + +Given an integer array bills of size N where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise. + +### Examples + +**Example 1:** + +``` +Input: +N = 5 +bills[] = {5, 5, 5, 10, 20} + +Output: +True +``` + +**Explanation:** +From the first 3 customers, we collect three \$5 bills in order. +From the fourth customer, we collect a \$10 bill and give back a \$5. +From the fifth customer, we give a \$10 bill and a \$5 bill. +Since all customers got correct change we return true. + +**Example 2:** + +``` +Input: +N = 5 +bills[] = {5, 5, 10, 10, 20} + +Output: +False +``` + +**Explanation:** +From the first two customers in order, we collect two \$5 bills. +For the next two customers in order, we collect a \$10 bill and give back a \$5 bill. +For the last customer, we can not give the change of \$15 back because we only have two \$10 bills. +Since not every customer received the correct change, the answer is false. + +### Your Task +You don't need to read input or print anything. Your task is to complete the function `lemonadeChange()` which takes the integer `N` and integer array `bills[]` as parameters and returns true if it is possible to provide change to every customer otherwise false. + +**Expected Time Complexity:** $O(N)$ +**Expected Auxiliary Space:** $O(1)$ + +### Constraints +- $1 ≀ N ≀ 10^5$ +- $bills[i]$ contains only {5, 10, 20} + +## Solution + +### Approach + +We can solve this problem using a greedy algorithm. Here's a step-by-step approach: + +1. Initialize two variables `five` and `ten` to keep count of the number of \$5 and \$10 bills available. +2. Iterate through the bills array using a for loop. +3. For each bill: + - If the customer pays \$20, we need to return \$15. We first check if we have 1 * \$10 + 1 * \$5. If not, we check for 3 * \$5. If neither combination is available, we return false. + - If the customer pays \$10, we need to return \$5. We check if we have any \$5 bills. If not, we return false. + - If the customer pays \$5, we simply increase the count of \$5 bills. +4. Finally, return true if we can provide the correct change for all customers. + +### Implementation + + + + +```cpp +class Solution { +public: + bool lemonadeChange(int n, vector &bills) { + int five = 0, ten = 0; + for (int i = 0; i < n; i++) { + if (bills[i] == 20) { + if (ten && five) { + ten--; + five--; + } else if (five >= 3) { + five -= 3; + } else { + return false; + } + } else if (bills[i] == 10) { + ten++; + if (five) { + five--; + } else { + return false; + } + } else { + five++; + } + } + return true; + } +}; +``` + + + + +```javascript +function lemonadeChange(bills) { + let five = 0, ten = 0; + for (let bill of bills) { + if (bill === 20) { + if (ten > 0 && five > 0) { + ten--; + five--; + } else if (five >= 3) { + five -= 3; + } else { + return false; + } + } else if (bill === 10) { + ten++; + if (five > 0) { + five--; + } else { + return false; + } + } else { + five++; + } + } + return true; +} +``` + + + + +```typescript +function lemonadeChange(bills: number[]): boolean { + let five = 0, ten = 0; + for (let bill of bills) { + if (bill === 20) { + if (ten > 0 && five > 0) { + ten--; + five--; + } else if (five >= 3) { + five -= 3; + } else { + return false; + } + } else if (bill === 10) { + ten++; + if (five > 0) { + five--; + } else { + return false; + } + } else { + five++; + } + } + return true; +} +``` + + + + +```python +class Solution: + def lemonadeChange(self, bills: List[int]) -> bool: + five, ten = 0, 0 + for bill in bills: + if bill == 20: + if ten > 0 and five > 0: + ten -= 1 + five -= 1 + elif five >= 3: + five -= 3 + else: + return False + elif bill == 10: + ten += 1 + if five > 0: + five -= 1 + else: + return False + else: + five += 1 + return True +``` + + + + +```java +class Solution { + public boolean lemonadeChange(int[] bills) { + int five = 0, ten = 0; + for (int bill : bills) { + if (bill == 20) { + if (ten > 0 && five > 0) { + ten--; + five--; + } else if (five >= 3) { + five -= 3; + } else { + return false; + } + } else if (bill == 10) { + ten++; + if (five > 0) { + five--; + } else { + return false; + } + } else { + five++; + } + } + return true; + } +} +``` + + + + +### Complexity Analysis + +- **Time Complexity:** $O(N)$, where N is the length of the bills array. We iterate through the array once. +- **Space Complexity:** $O(1)$, as we only use a constant amount of extra space for variables `five` and `ten`. + +--- + +## References + +- **LeetCode Problem:** [Lemonade Change](https://www.geeksforgeeks.org/problems/lemonade-change/0) +- **Authors GeeksforGeeks Profile:** [Vipul lakum](https://www.geeksforgeeks.org/user/lakumvipwjge/) diff --git a/solutions/gfg-solutions/0022-minimum-number-of-jumps.md b/solutions/gfg-solutions/0022-minimum-number-of-jumps.md new file mode 100644 index 0000000..03b7070 --- /dev/null +++ b/solutions/gfg-solutions/0022-minimum-number-of-jumps.md @@ -0,0 +1,349 @@ +--- +id: minimum-number-of-jumps +title: Minimum number of jumps +sidebar_label: 0022 Minimum number of jumps +tags: +- Arrays +- greedy +- Data Structure +- Algorithms +description: "find the minimum number of jumps required to reach the end of an array, given that each element represents the maximum length of the jump that can be made from that position." + +--- +## Problem Description + +The problem is to find the minimum number of jumps required to reach the end of an array. Each element in the array represents the maximum length of the jump that can be made from that element. If an element is 0, it means no movement can be made through that element. The task is to return the minimum number of jumps to reach the end of the array starting from the first element. If reaching the end is not possible, the function should return -1. + +## Example + +Consider an array of 9 elements starting from 1 to 9 . +The minimum number of jumps required would be 3: +1. Jump from the 1st element to the 2nd element (value 3). +2. From the 2nd element, jump to the 5th element (value 9). +3. Finally, jump to the last element. + +## Expected Complexity + +- Time Complexity: $(O(N))$ +- Space Complexity: $(O(1))$ + +## Solutions + +### Brute Force Approach + +#### Intuition + +The brute force approach involves recursively checking all possible jumps from each element, calculating the minimum number of jumps needed to reach the end from reachable elements. + +#### Implementation + +The implementation recursively checks all possible jumps from each element, updating the minimum number of jumps needed. + +```cpp +class Solution { +public: + int minimumJumps(int arr[], int n) { + if (n == 1) + return 0; + + int ans = INT_MAX; + for (int i = n - 2; i >= 0; i--) { + if (i + arr[i] >= n - 1) { + int sub_ans = minimumJumps(arr, i + 1); + if (sub_ans != INT_MAX) + ans = min(ans, sub_ans + 1); + } + } + return (ans==INT_MAX ? -1 : ans); + } +}; +``` + +### Brute Optimized Approach + +#### Intuition + +In this approach, we use dynamic programming to store the minimum number of jumps required to reach each index from the start. + +#### Implementation + +The code initializes an array to store the minimum jumps required and iterates through the array to calculate the minimum jumps. + +```cpp +class Solution { +public: + int minimumJumps(int arr[], int n) { + int jumps[n]; + if (arr[0] == 0) + return -1; + + jumps[0] = 0; + for (int i = 1; i < n; i++) { + jumps[i] = INT_MAX; + for (int j = 0; j < i; j++) { + if (i <= j + arr[j] && jumps[j] != INT_MAX) { + jumps[i] = min(jumps[i], jumps[j] + 1); + break; + } + } + } + return (jumps[n - 1] == INT_MAX ? -1 : jumps[n-1]); + } +}; +``` + +#### Python Implementation + +```python +class Solution: + def minJumps(self, arr, n): + if len(arr) <= 1 : + return 0 + + # Return -1 if not possible to jump + if arr[0] == 0 : + return -1 + + # initialization + maxReach = arr[0]; + step = arr[0]; + jump = 1; + + + # Start traversing array + for i in range(1,len(arr)): + + # Check if we have reached the end of the array + if i == len(arr) - 1 : + return jump + + # updating maxReach + maxReach = max(maxReach, i+arr[i]) + + # we use a step to get to the current index + step-=1; + + # If no further steps left + if step == 0 : + # we must have used a jump + jump+=1 + + #Check if the current index/position or lesser index + #is the maximum reach point from the previous indexes + if i>=maxReach : + return -1 + + #re-initialize the steps to the amount + #of steps to reach maxReach from position i. + step = maxReach - i + + return -1 +``` + +#### Java Implementation + +```java +class Solution { + static int minJumps(int arr[]) + { + if (arr.length <= 1) + return 0; + + // Return -1 if not possible to jump + if (arr[0] == 0) + return -1; + + // initialization + int maxReach = arr[0]; + int step = arr[0]; + int jump = 1; + + + // Start traversing array + for (int i = 1; i < arr.length; i++) + { + // Check if we have reached the end of the array + if (i == arr.length - 1) + return jump; + + // updating maxReach + maxReach = Math.max(maxReach, i+arr[i]); + + // we use a step to get to the current index + step--; + + // If no further steps left + if (step == 0) + { + // we must have used a jump + jump++; + + //Check if the current index/position or lesser index + // is the maximum reach point from the previous indexes + if(i>=maxReach) + return -1; + + // re-initialize the steps to the amount + // of steps to reach maxReach from position i. + step = maxReach - i; + } + } + + return -1; + } +} +``` + +### Expected Approach + +#### Intuition + +This approach involves maintaining the maximum reachable index from the current index and the number of steps we can jump if we jump from the current index. By iterating through the array, we update these values accordingly. + +#### Implementation + +The implementation traverses the array, updating the maximum reachable index and the number of steps at each iteration. + +```cpp +class Solution { +public: + int minJumps(int arr[], int n) { + if (n <= 1) + return 0; + if (arr[0] == 0) + return -1; + + int maxReach = arr[0]; + int step = arr[0]; + int jump = 1; + + for (int i = 1; i < n; i++) { + if (i == n - 1) + return jump; + maxReach = max(maxReach, i+arr[i]); + step--; + if (step ==0) { + jump++; + if (i >= maxReach) + return -1; + step = maxReach - i; + } + } + return -1; + } +}; +``` + +#### Python Implementation + +```python +class Solution: + def minJumps(self, arr, n): + if len(arr) <= 1 : + return 0 + + # Return -1 if not possible to jump + if arr[0] == 0 : + return -1 + + # initialization + maxReach = arr[0]; + step = arr[0]; + jump = 1; + + + # Start traversing array + for i in range(1,len(arr)): + + # Check if we have reached the end of the array + if i == len(arr) - 1 : + return jump + + # updating maxReach + maxReach = max(maxReach, i+arr[i]) + + # we use a step to get to the current index + step-=1; + + # If no further steps left + if step == 0 : + # we must have used a jump + jump+=1 + + #Check if the current index/position or lesser index + #is the maximum reach point from the previous indexes + if i>=maxReach : + return -1 + + #re-initialize the steps to the amount + #of steps to reach maxReach from position i. + step = maxReach - i + + return -1 +``` + +#### Java Implementation + +```java +class Solution { + static int minJumps(int arr[]) + { + if (arr.length <= 1) + return 0; + + // Return -1 if not possible to jump + if (arr[0] == 0) + return -1; + + // initialization + int maxReach = arr[0]; + int step = arr[0]; + int jump = 1; + + + // Start traversing array + for (int i = 1; i < arr.length; i++) + { + // Check if we have reached the end of the array + if (i == arr.length - 1) + return jump; + + // updating maxReach + maxReach = Math.max(maxReach, i+arr[i]); + + // we use a step to get to the current index + step--; + + // If no further steps left + if (step == 0) + { + // we must have used a jump + jump++; + + //Check if the current index/position or lesser index + // is the maximum reach point from the previous indexes + if(i>=maxReach) + return -1; + + // re-initialize the steps to the amount + // of steps to reach maxReach from position i. + step = maxReach - i; + } + } + + return -1; + } +} +``` + +## Conclusion + +In conclusion, the problem of finding the minimum number of jumps to reach the end of an array can be efficiently solved using dynamic programming or an optimized approach that tracks the maximum reachable index and the number of steps available. The expected approach offers the best time complexity of $(O(N))$ and space complexity of $(O(1))$, making it the most efficient solution for large input sizes. + +By implementing these solutions, we can effectively solve the problem with minimal time and space complexity, providing a scalable solution for real-world applications. + +## References + +- **GeeksforGeeks Problem:** [Geeks for Geeks Problem](https://www.geeksforgeeks.org/problems/minimum-number-of-jumps-1587115620/1) +- **Solution Link:** [Minimum Number of jumps on Geeks for Geeks](https://www.geeksforgeeks.org/problems/minimum-number-of-jumps-1587115620/1) +- **Authors GeeksforGeeks Profile:** [Yash](https://www.geeksforgeeks.org/user/gabaniyxn26/) \ No newline at end of file diff --git a/solutions/gfg-solutions/0023-Find-triplet-with-zero-sum.md b/solutions/gfg-solutions/0023-Find-triplet-with-zero-sum.md new file mode 100644 index 0000000..6f4d0d9 --- /dev/null +++ b/solutions/gfg-solutions/0023-Find-triplet-with-zero-sum.md @@ -0,0 +1,196 @@ +--- +id: Find-triplet-with-zero-sum +title: Find Triplet with Zero Sum +sidebar_label: 0023 Find Triplet with Zero Sum +tags: +- Array +- Sorting +- Two Pointers +- JavaScript +- TypeScript +- Python +- Java +- C++ +description: "This document explores different approaches to solving the problem of finding a triplet in an array that sums up to zero, including solutions in JavaScript, TypeScript, Python, Java, and C++." +--- + +## Problem Statement + +Given an array `arr[]` of distinct integers of size N, the task is to find if there are any three elements in `arr[]` whose sum is equal to zero. + +### Examples + +**Example 1:** + +``` +Input: +N = 5 +arr[] = {-1, 0, 1, 2, -1, -4} + +Output: +True + +Explanation: +The triplets {-1, 0, 1} and {-1, -1, 2} both have a sum of zero. +``` + +**Example 2:** + +``` +Input: +N = 3 +arr[] = {1, 2, 3} + +Output: +False + +Explanation: +No triplet has a sum of zero. +``` + +### Your Task +You don't need to read input or print anything. Your task is to complete the function `findTriplet()` which takes the integer `N` and integer array `arr[]` as parameters and returns true if there is a triplet with a sum of zero, otherwise false. + +**Expected Time Complexity:** $O(N^2)$ +**Expected Auxiliary Space:** $O(1)$ + +### Constraints + + +- $1 ≀ N ≀ 10^5$ +- $-10^3 ≀ arr[i] ≀ 10^3$ + +## Solution + +### Approach + +We can solve this problem using sorting and the two-pointer technique. Here's a step-by-step approach: + +1. Sort the array. +2. Iterate through the array using a for loop, fixing one element at a time. +3. Use two pointers to find the other two elements that sum up to zero with the fixed element: + - One pointer starts from the next element after the fixed element. + - The other pointer starts from the end of the array. +4. Adjust the pointers based on the sum of the three elements: + - If the sum is zero, return true. + - If the sum is less than zero, move the left pointer to the right. + - If the sum is greater than zero, move the right pointer to the left. +5. If no triplet is found, return false. + +### Implementation + + + + +```cpp +class Solution { +public: + bool findTriplet(int arr[], int n) { + sort(arr, arr + n); + for (int i = 0; i < n - 2; i++) { + int left = i + 1, right = n - 1; + while (left < right) { + int sum = arr[i] + arr[left] + arr[right]; + if (sum == 0) return true; + if (sum < 0) left++; + else right--; + } + } + return false; + } +}; +``` + + + + +```javascript +function findTriplet(arr) { + arr.sort((a, b) => a - b); + for (let i = 0; i < arr.length - 2; i++) { + let left = i + 1, right = arr.length - 1; + while (left < right) { + const sum = arr[i] + arr[left] + arr[right]; + if (sum === 0) return true; + if (sum < 0) left++; + else right--; + } + } + return false; +} +``` + + + + +```typescript +function findTriplet(arr: number[]): boolean { + arr.sort((a, b) => a - b); + for (let i = 0; i < arr.length - 2; i++) { + let left = i + 1, right = arr.length - 1; + while (left < right) { + const sum = arr[i] + arr[left] + arr[right]; + if (sum === 0) return true; + if (sum < 0) left++; + else right--; + } + } + return false; +} +``` + + + + +```python +class Solution: + def findTriplet(self, arr: List[int], n: int) -> bool: + arr.sort() + for i in range(n - 2): + left, right = i + 1, n - 1 + while left < right: + total = arr[i] + arr[left] + arr[right] + if total == 0: + return True + if total < 0: + left += 1 + else: + right -= 1 + return False +``` + + + + +```java +class Solution { + public boolean findTriplet(int[] arr, int n) { + Arrays.sort(arr); + for (int i = 0; i < n - 2; i++) { + int left = i + 1, right = n - 1; + while (left < right) { + int sum = arr[i] + arr[left] + arr[right]; + if (sum == 0) return true; + if (sum < 0) left++; + else right--; + } + } + return false; + } +} +``` + + + + +### Complexity Analysis + +- **Time Complexity:** $O(N^2)$, where N is the length of the array. We iterate through the array and for each element, we use the two-pointer technique which takes linear time. +- **Space Complexity:** $O(1)$, as we only use a constant amount of extra space for variables. + +--- + +## References + +- **GeeksforGeeks Problem:** [Find Triplet with Zero Sum](https://www.geeksforgeeks.org/find-triplet-sum-zero/) +- **Authors GeeksforGeeks Profile:** [Vipul lakum](https://www.geeksforgeeks.org/user/lakumvipwjge/) \ No newline at end of file diff --git a/solutions/gfg-solutions/0024-minimum-indexed-character.md b/solutions/gfg-solutions/0024-minimum-indexed-character.md new file mode 100644 index 0000000..2d1b5ac --- /dev/null +++ b/solutions/gfg-solutions/0024-minimum-indexed-character.md @@ -0,0 +1,181 @@ +--- +id: minimum-indexed-character +title: Minimum Indexed Character +sidebar_label: 0024 Minimum Indexed Character +tags: +- String +- Hashing +- JavaScript +- TypeScript +- Python +- Java +- C++ +description: "This document explores different approaches to solving the problem of finding the minimum index of a character in a string that is also present in another string, including solutions in JavaScript, TypeScript, Python, Java, and C++." +--- + +## Problem + +Given a string `str` and another string `patt`, find the minimum index of the character in `str` that is also present in `patt`. + +### Examples + +**Example 1:** + +``` +Input: +str = "geeksforgeeks" +patt = "set" + +Output: +1 + +Explanation: +'e' is the character which is present in the given string "geeksforgeeks" and is also present in "set". The minimum index of 'e' is 1. +``` + +**Example 2:** + +``` +Input: +str = "adcffaet" +patt = "onkl" + +Output: +-1 + +Explanation: +There are no characters that are common in "patt" and "str". +``` + +### Your Task +You only need to complete the function `minIndexChar()` that returns the index of the answer in `str` or returns `-1` if no character of `patt` is present in `str`. + +**Expected Time Complexity:** $O(N)$ +**Expected Auxiliary Space:** $O(Number of distinct characters)$ + +### Constraints + +- $1 ≀ |str|,|patt| ≀ 10^5$ +- $'a' ≀ str[i], patt[i] ≀ 'z'$ + +## Solution + +### Approach + +To solve this problem, we can follow these steps: + +1. Iterate through the characters in the `patt` string. +2. For each character in `patt`, find its index in the `str` string using the `find` method. +3. Store the indices in a vector. +4. Iterate through the vector to find the minimum index that is not `-1` (indicating the character is found in `str`). +5. If no valid index is found, return `-1`; otherwise, return the minimum index. + +### Implementation + + + + +```cpp +class Solution +{ + public: + int minIndexChar(string str, string patt) + { + int res = INT_MAX; + vector v1; + for (int i = 0; i < patt.length(); i++) + { + int p = str.find(patt[i]); + v1.push_back(p); + } + int min = INT_MAX; + for (int i = 0; i < v1.size(); i++) + { + if (min > v1[i] && v1[i] != -1) + min = v1[i]; + } + if (min == INT_MAX) + return -1; + return min; + } +}; +``` + + + + +```javascript +function minIndexChar(str, patt) { + let minIndex = Infinity; + for (let char of patt) { + let index = str.indexOf(char); + if (index !== -1 && index < minIndex) { + minIndex = index; + } + } + return minIndex === Infinity ? -1 : minIndex; +} +``` + + + + +```typescript +function minIndexChar(str: string, patt: string): number { + let minIndex = Infinity; + for (let char of patt) { + let index = str.indexOf(char); + if (index !== -1 && index < minIndex) { + minIndex = index; + } + } + return minIndex === Infinity ? -1 : minIndex; +} +``` + + + + +```python +class Solution: + def minIndexChar(self, str: str, patt: str) -> int: + min_index = float('inf') + for char in patt: + index = str.find(char) + if index != -1 and index < min_index: + min_index = index + return -1 if min_index == float('inf') else min_index +``` + + + + +```java +class Solution { + public int minIndexChar(String str, String patt) { + int minIndex = Integer.MAX_VALUE; + for (char ch : patt.toCharArray()) { + int index = str.indexOf(ch); + if (index != -1 && index < minIndex) { + minIndex = index; + } + } + return minIndex == Integer.MAX_VALUE ? -1 : minIndex; + } +} +``` + + + + +### Complexity Analysis + +- **Time Complexity:** $O(N)$, where N is the length of the string `str`. We iterate through each character in `patt` and use the `find` or `indexOf` method, which runs in $O(N)$ time. +- **Space Complexity:** $O(1)$, as we only use a constant amount of extra space for variables. + +--- + +## References + +- **GeeksforGeeks Problem:** [Minimum Indexed Character](https://www.geeksforgeeks.org/minimum-indexed-character/) +- **Authors GeeksforGeeks Profile:** [Vipul lakum](https://www.geeksforgeeks.org/user/lakumvipwjge/) \ No newline at end of file diff --git a/solutions/gfg-solutions/0025-K-Nearest Neighbor.md b/solutions/gfg-solutions/0025-K-Nearest Neighbor.md new file mode 100644 index 0000000..6f4438d --- /dev/null +++ b/solutions/gfg-solutions/0025-K-Nearest Neighbor.md @@ -0,0 +1,230 @@ +--- +id: K-Nearest-Neighbor +title: K-Nearest Neighbor (Geeks for Geeks) +sidebar_label: 0025 K-Nearest Neighbor +tags: + - Intermediate + - Machine Learning + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the K-Nearest Neighbor problem on Geeks for Geeks." +--- + + +## What is the K-Nearest Neighbors Algorithm? + +KNN is one of the most basic yet essential classification algorithms in machine learning. It belongs to the supervised learning domain and finds intense application in pattern recognition, data mining, and intrusion detection. + +It is widely disposable in real-life scenarios since it is non-parametric, meaning it does not make any underlying assumptions about the distribution of data (as opposed to other algorithms such as GMM, which assume a Gaussian distribution of the given data). We are given some prior data (also called training data), which classifies coordinates into groups identified by an attribute. + +![This image explains the Basic](../../assets/knnclassifier.png) + +## Intuition Behind KNN Algorithm + +If we plot these points on a graph, we may be able to locate some clusters or groups. Now, given an unclassified point, we can assign it to a group by observing what group its nearest neighbors belong to. This means a point close to a cluster of points classified as β€˜Red’ has a higher probability of getting classified as β€˜Red’. + +Intuitively, we can see that the first point (2.5, 7) should be classified as β€˜Green’, and the second point (5.5, 4.5) should be classified as β€˜Red’. + +## How to select the value of K in the K-NN Algorithm? + +The value of K is critical in the K-NN algorithm. A small K can make the model sensitive to noise, while a large K can smooth out the predictions too much. Typically, K is chosen by experimenting with different values and using cross-validation to evaluate the performance. A common approach is to start with K = sqrt(n), where n is the number of data points, and adjust based on the model’s performance. + + +### How does K-NN work? + +K-Nearest Neighbor (K-NN) is a simple, supervised machine learning algorithm used for classification and regression tasks. It works by finding the K closest data points (neighbors) to the query point and using them to make predictions. For classification, it assigns the class most common among the neighbors. For regression, it averages the values of the neighbors. + + +![Here you can see](../../assets/kthNearest.png) + +## Problem Description + +Given a dataset and a query point, implement the K-Nearest Neighbor (KNN) algorithm to find the k points in the dataset that are closest to the query point. + +## Examples + +**Example 1:** +``` +Input: +dataset = [(2, 4), (4, 4), (4, 2), (2, 2)] +query_point = (3, 3) +k = 2 +Output: [(2, 4), (4, 4)] +``` + +**Example 2:** +``` +Input: +dataset = [(1, 2), (2, 3), (3, 4), (4, 5)] +query_point = (2, 2) +k = 3 +Output: [(1, 2), (2, 3), (3, 4)] +``` + +## Your Task + +Implement the function $knn()$ that takes in a dataset, a query point, and an integer k. The function should return the k points in the dataset that are closest to the query point based on Euclidean distance. + +Expected Time Complexity: $O(n log n)$ for sorting the dataset. + +Expected Auxiliary Space: $O(n)$ for storing the distances. + +## Constraints + +- $1 <= len(dataset) <= 10^4$ +- $1 <= k <= len(dataset)$ +- Each point in the dataset is a tuple of integers $(x, y)$. +- The query point is a tuple of integers $(x, y)$. + +## Problem Explanation + +Here's the step-by-step breakdown of the K-Nearest Neighbor algorithm: + +1. **Calculate Distances**: Compute the Euclidean distance between the query point and each point in the dataset. +2. **Sort Distances**: Sort the points based on their distances from the query point. +3. **Select Neighbors**: Select the first k points from the sorted list as the nearest neighbors. + +### Code Implementation + + + + + ```python + import math + + def euclidean_distance(point1, point2): + return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) + + def knn(dataset, query_point, k): + distances = [] + for point in dataset: + distance = euclidean_distance(point, query_point) + distances.append((point, distance)) + distances.sort(key=lambda x: x[1]) + nearest_neighbors = [distances[i][0] for i in range(k)] + return nearest_neighbors + ``` + + + + + ```cpp + #include + #include + #include + #include + + using namespace std; + + double euclidean_distance(pair point1, pair point2) { + return sqrt(pow(point1.first - point2.first, 2) + pow(point1.second - point2.second, 2)); + } + + vector> knn(vector> dataset, pair query_point, int k) { + vector, double>> distances; + for (auto point : dataset) { + double distance = euclidean_distance(point, query_point); + distances.push_back(make_pair(point, distance)); + } + sort(distances.begin(), distances.end(), [](auto &left, auto &right) { + return left.second < right.second; + }); + vector> nearest_neighbors; + for (int i = 0; i < k; i++) { + nearest_neighbors.push_back(distances[i].first); + } + return nearest_neighbors; + } + ``` + + + + + ```java + import java.util.*; + + public class KNN { + public static double euclideanDistance(int[] point1, int[] point2) { + return Math.sqrt(Math.pow(point1[0] - point2[0], 2) + Math.pow(point1[1] - point2[1], 2)); + } + + public static List knn(List dataset, int[] queryPoint, int k) { + List result = new ArrayList<>(); + PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> + Double.compare(euclideanDistance(b, queryPoint), euclideanDistance(a, queryPoint)) + ); + + for (int[] point : dataset) { + maxHeap.offer(point); + if (maxHeap.size() > k) { + maxHeap.poll(); + } + } + + while (!maxHeap.isEmpty()) { + result.add(maxHeap.poll()); + } + + return result; + } + } + ``` + + + + + ```javascript + function euclideanDistance(point1, point2) { + return Math.sqrt(Math.pow(point1[0] - point2[0], 2) + Math.pow(point1[1] - point2[1], 2)); + } + + function knn(dataset, queryPoint, k) { + let distances = dataset.map(point => { + return { point: point, distance: euclideanDistance(point, queryPoint) }; + }); + + distances.sort((a, b) => a.distance - b.distance); + + return distances.slice(0, k).map(d => d.point); + } + ``` + + + +## Solution Logic + +1. **Calculate Distances**: Iterate through each point in the dataset and compute the Euclidean distance to the query point. +2. **Sort Distances**: Use the sorting algorithm to sort the points by their distance. +3. **Select Neighbors**: Extract the k closest points from the sorted list. + +## Time Complexity + +$O(n log n)$, where n is the number of points in the dataset. This is due to the sorting step. + +## Space Complexity + +$O(n)$, for storing the distances of all points in the dataset. + +## Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/k-nearest-neighbors/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/k-nearest-neighbors/problem) +- **FreeCodeCamp Article:** [Freecodecamp](https://www.freecodecamp.org/news/k-nearest-neighbors-algorithm-classifiers-and-model-example/) +- **GFG Article** [GFG Article](https://www.geeksforgeeks.org/k-nearest-neighbours/) +- **Authors Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) + +## Additional Topics + +### Advantages and Disadvantages + +**Advantages:** +- Simple to understand and implement. +- No training phase, making it fast for small datasets. +- Effective with a well-distributed dataset. + +**Disadvantages:** +- Computationally intensive for large datasets as it requires calculating the distance of each data point. +- Performance degrades with high-dimensional data due to the curse of dimensionality. +- Sensitive to irrelevant or redundant features, requiring feature scaling and selection. diff --git a/solutions/gfg-solutions/Basic/0001.md b/solutions/gfg-solutions/Basic/0001.md new file mode 100644 index 0000000..b8fc5bb --- /dev/null +++ b/solutions/gfg-solutions/Basic/0001.md @@ -0,0 +1,192 @@ +--- +id: binary-search +title: Binary Search +sidebar_label: 0001 Binary Search +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to the problem of performing Binary Search in a sorted array." +--- + +## Problem + +Given a sorted array of size N and an integer K, find the position(0-based indexing) at which K is present in the array using binary search. + +### Examples +**Example 1:** +``` +Input: +N = 5 +arr[] = {1 2 3 4 5} +K = 4 +Output: 3 +Explanation: 4 appears at index 3. +``` + +**Example 2:** +``` +Input: +N = 5 +arr[] = {11 22 33 44 55} +K = 445 +Output: -1 +Explanation: 445 is not present. +``` + +### Your Task: +You dont need to read input or print anything. Complete the function **binarysearch()** which takes **arr[]**, **N** and **K** as input parameters and returns the index of **K** in the array. If **K** is not present in the array, return -1. + +- **Expected Time Complexity:** $O(LogN)$ +- **Expected Auxiliary Space:** $O(LogN)$ if solving recursively and $O(1)$ otherwise. + +### Constraints: + +- $1 <= N <= 10^5$ +- $1 <= arr[i] <= 10^6$ +- $1 <= K <= 10^6$ + +## Solution: +### Iterative Approach: + +**Python** +```python +def binarysearch(self, arr, n, k): + low = 0 + high = n-1 + while low<=high: + mid = low + (high-low)//2 + if arr[mid]==k: + return mid + elif arr[mid]= arr[1]) : + return 0 + if (arr[n - 1] >= arr[n - 2]) : + return n - 1 + for i in range(1, n - 1) : + if (arr[i] >= arr[i - 1] and arr[i] >= arr[i + 1]) : + return i +``` + +**Java** +```java +public int peakElement(int[] arr,int n) { + if (n == 1) + return 0; + if (arr[0] >= arr[1]) + return 0; + if (arr[n - 1] >= arr[n - 2]) + return n - 1; + for (int i = 1; i < n - 1; i++) { + if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) + return i; + } + return 0; +} +``` + +**C++** +```cpp +public: +int peakElement(int arr[], int n) { + if (n == 1) + return 0; + if (arr[0] >= arr[1]) + return 0; + if (arr[n - 1] >= arr[n - 2]) + return n - 1; + for (int i = 1; i < n - 1; i++) { + if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) + return i; + } +} +``` + +**C** +```c +int peakElement(int arr[], int n) { + if (n == 1) + return 0; + if (arr[0] >= arr[1]) + return 0; + if (arr[n - 1] >= arr[n - 2]) + return n - 1; + for (int i = 1; i < n - 1; i++) { + if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) + return i; + } +} +``` + +- **Time complexity:** $O(n)$ +- **Space complexity:**: $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0003.md b/solutions/gfg-solutions/Basic/0003.md new file mode 100644 index 0000000..3642bc1 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0003.md @@ -0,0 +1,101 @@ +--- +id: power-of-2 +title: Power Of 2 +sidebar_label: 0003 Power Of 2 +tags: +- C +- Python +- Java +- C++ +description: "This document provides solutions to the problem of checking whether a non-negative number is a power of 2." +--- + +## Problem + +Given a non-negative integer n. The task is to check if it is a power of 2. + +### Examples: +**Example 1:** +``` +Input: n = 8 +Output: true +Explanation: 8 is equal to 2 raised to 3 (2^3 = 8). +``` + +**Example 2:** +``` +Input: n = 98 +Output: false +Explanation: 98 cannot be obtained by any power of 2. +``` + +**Example 3:** +``` +Input: n = 1 +Output: true +Explanation: (2^0 = 1). +``` + +- **Expected Time Complexity:** $O(log n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: +$0 ≀ n < 10^{20}$ + +## Solution +**Python** +```python +def isPowerofTwo(self,n : int ) -> bool: + if (n == 0): + return False + while (n != 1): + if (n % 2 != 0): + return False + n = n // 2 + return True +``` + +**Java** +```java +public static boolean isPowerofTwo(long n) { + if (n == 0) + return false; + while (n != 1) { + if (n % 2 != 0) + return false; + n = n / 2; + } + return true; +} +``` + +**C** +```c +bool isPowerofTwo(long long n) { + if (n == 0) + return 0; + while (n != 1) { + if (n % 2 != 0) + return 0; + n = n / 2; + } + return 1; +} +``` + +**C++** +```cpp +bool isPowerofTwo(long long n) { + if (n == 0) + return 0; + while (n != 1) { + if (n % 2 != 0) + return 0; + n = n / 2; + } + return 1; +} +``` + +- **Time Complexity:** $O(log n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0004.md b/solutions/gfg-solutions/Basic/0004.md new file mode 100644 index 0000000..f9873f2 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0004.md @@ -0,0 +1,133 @@ +--- +id: union-of-two-arrays +title: Union Of Two Arrays +sidebar_label: 0004 Union Of Two Arrays +tags: +- Array +- Set +- C +- Python +- Java +- C++ +description: "This document provides solutions to the problem of finding the number of elements in the union between two arrays." +--- + +## Problem + +Given two arrays **a[]** and **b[]** of size **n** and **m** respectively. The task is to find the number of elements in the union between these two arrays. + +Union of the two arrays can be defined as the set containing distinct elements from both the arrays. If there are repetitions, then only one occurrence of element should be printed in the union. + +**Note:** Elements are not necessarily distinct. + +### Examples: +**Example 1:** +``` +Input: +5 3 +1 2 3 4 5 +1 2 3 +Output: +5 +Explanation: +1, 2, 3, 4 and 5 are the +elements which comes in the union set +of both arrays. So count is 5. +``` + +**Example 2:** +``` +Input: +6 2 +85 25 1 32 54 6 +85 2 +Output: +7 +Explanation: +85, 25, 1, 32, 54, 6, and +2 are the elements which comes in the +union set of both arrays. So count is 7. +``` + +### Your Task: + +Complete **doUnion** function that takes **a, n, b, m as parameters and returns** the count of union elements of the two arrays. The **printing** is done by the **driver** code. + +- **Expected Time Complexity:** $O(n+m)$ +- **Expected Auxilliary Space:** $O(n+m)$ + + +### Constraints: + +- $1 ≀ n, m ≀ 10^5$ +- $0 ≀ a[i], b[i] < 10^5$ + +## Solution + +### Python +```python +def doUnion(self,a,n,b,m): + set1 = set(a) + set2 = set(b) + result = list(set1.union(set2)) + return len(result) +``` + +### Java +```java +public static int doUnion(int a[], int n, int b[], int m) { + TreeSet set = new TreeSet<>(); + for (int i : a) + set.add(i); + for (int i : b) + set.add(i); + ArrayList list = new ArrayList<>(); + for (int i : set) + list.add(i); + return list.size(); +} +``` + +### C++ +```cpp +int doUnion(int a[], int n, int b[], int m) { + set s; + for (int i = 0; i < n; i++) { + s.insert(a[i]); + } + for (int i = 0; i < m; i++) { + s.insert(b[i]); + } + vector vec(s.begin(), s.end()); + return vec.size(); +} +``` + +### C +```c +int doUnion(int a[], int n, int b[], int m) { + int *unionSet = (int *)malloc((n + m) * sizeof(int)); + int i, j; + int unionSize = 0; + for (i = 0; i < n; i++) { + unionSet[unionSize++] = a[i]; + } + for (i = 0; i < m; i++) { + int found = 0; + for (j = 0; j < unionSize; j++) { + if (b[i] == unionSet[j]) { + found = 1; + break; + } + } + if (!found) { + unionSet[unionSize++] = b[i]; + } + } + free(unionSet); + return unionSize; +} +``` + +- **Time Complexity:** $O(m*log(m) + n*log(n))$ +- **Auxiliary Space:** $O(m + n)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0005.md b/solutions/gfg-solutions/Basic/0005.md new file mode 100644 index 0000000..3657cca --- /dev/null +++ b/solutions/gfg-solutions/Basic/0005.md @@ -0,0 +1,97 @@ +--- +id: reverse-a-string +title: Reverse a String +sidebar_label: 0005 Reverse a String +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to the problem of reversing a string." +--- + +## Problem + +You are given a string s. You need to reverse the string. + +### Examples: +**Example 1:** +``` +Input: +s = Geeks +Output: skeeG +``` + +**Example 2:** +``` +Input: +s = for +Output: rof +``` + +### Your Task: + +You only need to complete the function **reverseWord()** that takes s as parameter and returns the reversed string. + +- **Expected Time Complexity:** $O(|S|)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +$1 <= |s| <= 10000$ + +## Solution +### Python +```python +def reverseWord(self, str: str) -> str: + str = str[::-1] + return str +``` + +### Java +```java +public static String reverseWord(String str) { + char ch; + String nstr = ""; + for (int i=0; i map = new HashMap<>(); + for (int i = 0; i < N; i++) { + long key = A[i]; + map.put(key, map.getOrDefault(key, 0) + 1); + } + for (int i = 0; i < N; i++) { + long key = B[i]; + if (!map.containsKey(key)) + return false; + if (map.get(key) == 0) + return false; + int count = map.get(key); + map.put(key, count - 1); + } + return true; +} +``` + +### C++ +```cpp +bool check(vector A, vector B, int N) { + if (A.size() != static_cast(N) || B.size() != static_cast(N)) + return false; + unordered_map map; + for (int i = 0; i < N; ++i) { + ll key = A[i]; + map[key]++; + } + for (int i = 0; i < N; ++i) { + ll key = B[i]; + if (map.find(key) == map.end()) + return false; + if (map[key] == 0) + return false; + map[key]--; + } + return true; +} +``` + +### C +```c +bool check(long long A[], long long B[], int N) { + long long *map = (long long *)calloc(1000001, sizeof(long long)); + for (int i = 0; i < N; ++i) { + long long key = A[i]; + map[key]++; + } + for (int i = 0; i < N; ++i) { + long long key = B[i]; + if (map[key] == 0) + return false; + map[key]--; + } + free(map); + return true; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxilliary Space:** $O(N)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0008.md b/solutions/gfg-solutions/Basic/0008.md new file mode 100644 index 0000000..80093fe --- /dev/null +++ b/solutions/gfg-solutions/Basic/0008.md @@ -0,0 +1,151 @@ +--- +id: array-subset-of-another-array +title: Array Subset of another array +sidebar_label: 0008 Array Subset of another array +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to whether an array is the subset of another." +--- + +## Problem + +Given two arrays: **a1[0..n-1]** of size **n** and **a2[0..m-1]** of size **m**, where both arrays may contain duplicate elements. The task is to determine whether array a2 is a subset of array a1. It's important to note that both arrays can be sorted or unsorted. Additionally, each occurrence of a duplicate element within an array is considered as a separate element of the set. + + +### Examples +**Example 1:** +``` +Input: +a1[] = {11, 7, 1, 13, 21, 3, 7, 3} +a2[] = {11, 3, 7, 1, 7} +Output: +Yes +Explanation: +a2[] is a subset of a1[] +``` + +**Example 2:** +``` +Input: +a1[] = {1, 2, 3, 4, 4, 5, 6} +a2[] = {1, 2, 4} +Output: +Yes +Explanation: +a2[] is a subset of a1[] +``` + +**Example 3:** +``` +Input: +a1[] = {10, 5, 2, 23, 19} +a2[] = {19, 5, 3} +Output: +No +Explanation: +a2[] is not a subset of a1[] +``` + +### Your Task: + +You don't need to read input or print anything. Your task is to complete the function **isSubset()** which takes the array **a1[]**, **a2[]**, its size **n** and **m** as inputs and return "Yes" if arr2 is subset of arr1 else return "No" if arr2 is not subset of arr1. + + + +- **Expected Time Complexity:** $O(max(n,m))$ +- **Expected Auxiliary Space:** $O(n)$ + +### Constraints: + +- $1 <= n,m <= 10^5$ +- $1 <= a1[i], a2[j] <= 10^6$ + +## Solution + +### Python +```python +def isSubset(a1, a2, n, m): + count_a1 = {} + count_a2 = {} + for num in a1: + count_a1[num] = count_a1.get(num, 0) + 1 + for num in a2: + count_a2[num] = count_a2.get(num, 0) + 1 + for num in count_a2: + if num not in count_a1 or count_a1[num] < count_a2[num]: + return "No" + return "Yes" +``` + +### Java +```java +public String isSubset( long a1[], long a2[], long n, long m) { + Map count_a1 = new HashMap<>(); + Map count_a2 = new HashMap<>(); + for (long num : a1) { + count_a1.put(num, count_a1.getOrDefault(num, 0) + 1); + } + for (long num : a2) { + count_a2.put(num, count_a2.getOrDefault(num, 0) + 1); + } + for (long num : count_a2.keySet()) { + if (!count_a1.containsKey(num) || count_a1.get(num) < count_a2.get(num)) { + return "No"; + } + } + return "Yes"; +} +``` + +### C++ +```cpp +string isSubset(int a1[], int a2[], int n, int m) { + unordered_map count_a1; + unordered_map count_a2; + for (int i = 0; i < n; ++i) { + count_a1[a1[i]]++; + } + for (int i = 0; i < m; ++i) { + count_a2[a2[i]]++; + } + for (const auto& pair : count_a2) { + int num = pair.first; + int count_in_a2 = pair.second; + if (count_a1.find(num) == count_a1.end() || count_a1[num] < count_in_a2) { + return "No"; + } + } + return "Yes"; +} +``` + +### C +```c +char* isSubset(int a1[], int a2[], int n, int m) { + int *count_a1 = (int *)calloc(1001, sizeof(int)); + int *count_a2 = (int *)calloc(1001, sizeof(int)); + for (int i = 0; i < n; ++i) { + count_a1[a1[i]]++; + } + for (int i = 0; i < m; ++i) { + count_a2[a2[i]]++; + } + for (int i = 0; i < 1001; ++i) { + if (count_a2[i] > 0 && count_a1[i] < count_a2[i]) { + free(count_a1); + free(count_a2); + return "No"; + } + } + free(count_a1); + free(count_a2); + return "Yes"; +} +``` + +- **Time Complexity:** $O(n+m)$ +- **Auxiliary Space:** $O(n+m)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0009.md b/solutions/gfg-solutions/Basic/0009.md new file mode 100644 index 0000000..8e48c18 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0009.md @@ -0,0 +1,117 @@ +--- +id: reverse-array-in-groups +title: Reverse array in groups +sidebar_label: 0009 Reverse array in groups +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to reverse an array in groups." +--- + +## Problem + +Given an array arr[] of positive integers of size N. Reverse every sub-array group of size K. + +**Note:** If at any instance, there are no more subarrays of size greater than or equal to K, then reverse the last subarray (irrespective of its size). You shouldn't return any array, modify the given array in-place. + +### Examples: +**Example 1:** +``` +Input: +N = 5, K = 3 +arr[] = {1,2,3,4,5} +Output: 3 2 1 5 4 +Explanation: First group consists of elements 1, 2, 3. Second group consists of 4,5. +``` + +**Example 2:** +``` +Input: +N = 4, K = 3 +arr[] = {5,6,8,9} +Output: 8 6 5 9 +``` + +### Your Task: + +You don't need to read input or print anything. The task is to complete the function **reverseInGroups()** which takes the array, N and K as input parameters and modifies the array in-place. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + + ### Constraints: + +- $1 ≀ N, K ≀ 10^7$ +- $1 ≀ A[i] ≀ 10^{18}$ + +## Solution + +### Python +```python +def reverseInGroups(self, arr, N, K): + i = 0 + while(i arr, int n, int k) { + for (int i = 0; i < n; i += k) { + int left = i; + int right = Math.min(i + k - 1, n - 1); + while (left < right) { + int temp = arr.get(left); + arr.set(left, arr.get(right)); + arr.set(right, temp); + left++; + right--; + } + } +} +``` + +### C++ +```cpp +void reverseInGroups(vector& arr, int n, int k){ + for (int i = 0; i < n; i += k) { + int left = i; + int right = min(i + k - 1, n - 1); + while (left < right) + swap(arr[left++], arr[right--]); + } +} +``` + +### C +```c +void reverse(int arr[], int n, int k) { + for (int i = 0; i < n; i += k) { + int left = i; + int right; + if(i+k-1 0; i--) + arr[i] = arr[i - 1]; + arr[0] = last_el; +} +``` + +### C++ +```cpp +void rotate(int arr[], int n) { + int last_el = arr[n - 1]; + for (int i = n - 1; i > 0; i--) { + arr[i] = arr[i - 1]; + } + arr[0] = last_el; +} +``` + +### C +```c +void rotate(int arr[], int n) { + int last_el = arr[n - 1]; + for (int i = n - 1; i > 0; i--) + arr[i] = arr[i - 1]; + arr[0] = last_el; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0011.md b/solutions/gfg-solutions/Basic/0011.md new file mode 100644 index 0000000..7d56f71 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0011.md @@ -0,0 +1,140 @@ +--- +id: find-minimum-and-maximum-element-in-an-array +title: Find minimum and maximum element in an array +sidebar_label: 0011 Find minimum and maximum element in an array +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to finding the minimum and maximum element in an array." +--- + +## Problem + +Given an array **A** of size **N** of integers. Your task is to find the **minimum and maximum** elements in the array. + +Note: Return an array that contains 2 elements the first one will be a minimum element and the second will be a maximum of an array. + +### Examples: +**Example 1:** +``` +Input: +N = 6 +A[] = {3, 2, 1, 56, 10000, 167} +Output: 1 10000 +Explanation: minimum and maximum elements of array are 1 and 10000. +``` + +**Example 2:** +``` +Input: +N = 5 +A[] = {1, 345, 234, 21, 56789} +Output: 1 56789 +Explanation: minimum and maximum element of array are 1 and 56789. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **getMinMax()** which takes the array **A[]** and its size **N** as inputs and returns the **minimum and maximum** element of the array. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= N <= 10^5$ +- $1 <= A_i <=10^{12}$ + +## Solution +### Python +```python +def getMinMax( a, n): + if n == 0: + return None + min_value = float('inf') + max_value = float('-inf') + for num in a: + if num < min_value: + min_value = num + if num > max_value: + max_value = num + minmax = [min_value, max_value] + return minmax +``` + +### Java +```java +static Pair getMinMax(long a[], long n) { + if (n == 0) { + return null; + } + long min_value = Long.MAX_VALUE; + long max_value = Long.MIN_VALUE; + for (long num : a) { + if (num < min_value) { + min_value = num; + } + if (num > max_value) { + max_value = num; + } + } + return new Pair(min_value, max_value); +} +``` + +### C++ +```cpp +public: + pair getMinMax(long long a[], int n) { + if (n == 0) { + return {0, 0}; + } + long long min_value = LLONG_MAX; + long long max_value = LLONG_MIN; + for (int i = 0; i < n; ++i) { + if (a[i] < min_value) { + min_value = a[i]; + } + if (a[i] > max_value) { + max_value = a[i]; + } + } + return {min_value, max_value}; + } +}; +``` + +### C +```c +struct pair getMinMax(long long int arr[], long long int n) { + struct pair minmax; + int i; + if (n == 1) { + minmax.max = arr[0]; + minmax.min = arr[0]; + return minmax; + } + if (arr[0] > arr[1]) { + minmax.max = arr[0]; + minmax.min = arr[1]; + } + else { + minmax.max = arr[1]; + minmax.min = arr[0]; + } + + for (i = 2; i minmax.max) + minmax.max = arr[i]; + else if (arr[i] < minmax.min) + minmax.min = arr[i]; + } + return minmax; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0012.md b/solutions/gfg-solutions/Basic/0012.md new file mode 100644 index 0000000..21d4467 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0012.md @@ -0,0 +1,106 @@ +--- +id: prime-number +title: Prime Number +sidebar_label: 0012 Prime Number +tags: +- C +- Python +- Java +- C++ +description: "This document provides solutions to checking whether a number is prime or not." +--- + +## Problem + +For a given number **N** check if it is prime or not. A prime number is a number which is only **divisible by 1 and itself**. + +### Examples: +**Example 1:** +``` +Input: +N = 5 +Output: +1 +Explanation: +5 has 2 factors 1 and 5 only. +``` + +**Example 2:** +``` +Input: +N = 25 +Output: +0 +Explanation: +25 has 3 factors 1, 5, 25 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **isPrime()** which takes an integer **N** as input parameters and returns an integer, 1 if N is a prime number or 0 otherwise. + +- **Expected Time Complexity:** $O(sqrt(N))$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^9$ + +## Solution +### Python +```python +def isPrime (self, N): + if (N <= 1): + return 0 + for i in range(2, int(math.sqrt(N))+1): + if (N % i == 0): + return 0 + return 1 +``` + +### Java +```java +static int isPrime(int N){ + if (N <= 1) + return 0; + else if (N == 2) + return 1; + else if (N % 2 == 0) + return 0; + for (int i = 3; i <= Math.sqrt(N); i += 2) { + if (N % i == 0) + return 0; + } + return 1; +} +``` + +### C++ +```cpp +public: + int isPrime(int N){ + if (N <= 1) + return 0; + for (int i = 2; i <= sqrt(N); i++) + if (N % i == 0) + return 0; + return 1; + } +}; +``` + +### C +```c +int isPrime(int N) { + if (N <= 1) + return 0; + for (int i = 2; i <= sqrt(N); i++) { + if (N % i == 0) + return 0; + } + return 1; +} +``` + +- **Time Complexity:** $O(sqrt(N))$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0013.md b/solutions/gfg-solutions/Basic/0013.md new file mode 100644 index 0000000..f62bc38 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0013.md @@ -0,0 +1,110 @@ +--- +id: largest-element-in-array +title: Largest Element in Array +sidebar_label: 0013 Largest Element in Array +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to find the largest element in an array." +--- + +## Problem + +Given an array **A[]** of size **n**. The task is to find the largest element in it. + +### Examples: +**Example 1:** +``` +Input: +n = 5 +A[] = {1, 8, 7, 56, 90} +Output: +90 +Explanation: +The largest element of given array is 90. +``` + +**Example 2:** +``` +Input: +n = 7 +A[] = {1, 2, 0, 3, 2, 4, 5} +Output: +5 +Explanation: +The largest element of given array is 5. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **largest()** which takes the array **A[]** and its size **n** as inputs and returns the maximum element in the array + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=n<=10^3$ +- $0<=A[i]<=10^3$ + +Array may contain duplicate elements. + + + +## Solution +### Python +```python +def largest( arr, n): + mx = arr[0] + for i in range(1, n): + if arr[i] > mx: + mx = arr[i] + return mx +``` + +### Java +```java +public int largest(int arr[], int n) { + int mx = arr[0]; + for (int i = 1; i < n; i++) { + if (arr[i] > mx) { + mx = arr[i]; + } + } + return mx; +} +``` + +### C++ +```cpp +public: + int largest(vector &arr, int n) { + int mx = arr[0]; + for (int i = 1; i < n; i++) { + if (arr[i] > mx) { + mx = arr[i]; + } + } + return mx; + } +}; +``` + +### C +```c +int largest(int arr[], int n) { + int mx = arr[0]; + for (int i = 1; i < n; i++) { + if (arr[i] > mx) { + mx = arr[i]; + } + } + return mx; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0014.md b/solutions/gfg-solutions/Basic/0014.md new file mode 100644 index 0000000..2b07a96 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0014.md @@ -0,0 +1,126 @@ +--- +id: print-first-n-fibonacci-numbers +title: Print first n Fibonacci Numbers +sidebar_label: 0014 Print first n Fibonacci Numbers +tags: +- C +- Python +- Java +- C++ +description: "This document provides solutions to printing first N Fibonacci number." +--- + +## Problem + +Given a number **N**, find the first N Fibonacci numbers. The first two number of the series are 1 and 1. + +### Examples: +**Example 1:** +``` +Input: +N = 5 +Output: 1 1 2 3 5 +``` + +**Example 2:** +``` +Input: +N = 7 +Output: 1 1 2 3 5 8 13 +``` + +### Your task: + +Your task is to complete **printFibb()** which takes single argument N and returns a list of first N Fibonacci numbers. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(N)$ + +Note: This space is used to store and return the answer for printing purpose. + +### Constraints: + +- $1<=N<=84$ + +## Solution +### Python +```python +def printFibb(self,n): + fib_list = [] + f1, f2 = 1, 1 + if n < 1: + return fib_list + fib_list.append(f1) + for _ in range(1, n): + fib_list.append(f2) + next_fib = f1 + f2 + f1 = f2 + f2 = next_fib + return fib_list +``` + +### Java +```java +public static long[] printFibb(int n) { + long[] fibArray = new long[n]; + if (n < 1) { + return fibArray; + } + fibArray[0] = 1; + if (n > 1) { + fibArray[1] = 1; + } + for (int i = 2; i < n; i++) { + fibArray[i] = fibArray[i - 1] + fibArray[i - 2]; + } + return fibArray; +} +``` + +### C++ +```cpp +public: +vector printFibb(int n) { + vector fibVector(n); + if (n < 1) { + return fibVector; + } + fibVector[0] = 1; + if (n > 1) { + fibVector[1] = 1; + } + for (int i = 2; i < n; i++) { + fibVector[i] = fibVector[i - 1] + fibVector[i - 2]; + } + return fibVector; +} +``` + +### C +```c +int* printFibb(int n) { + if (n < 1) { + return NULL; + } + int* fibArray = (int*) malloc(n * sizeof(int)); + if (fibArray == NULL) { + fprintf(stderr, "Memory allocation failed\n"); + exit(1); + } + int f1 = 0, f2 = 1; + fibArray[0] = f1; + if (n > 1) { + fibArray[1] = f2; + } + for (int i = 2; i < n; i++) { + int next_fib = f1 + f2; + fibArray[i] = next_fib; + f1 = f2; + f2 = next_fib; + } + return fibArray; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0015.md b/solutions/gfg-solutions/Basic/0015.md new file mode 100644 index 0000000..ac48f1b --- /dev/null +++ b/solutions/gfg-solutions/Basic/0015.md @@ -0,0 +1,131 @@ +--- +id: searching-an-element-in-a-sorted-array +title: Searching an element in a sorted array +sidebar_label: 0015 Searching an element in a sorted array +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions for searching an element in a sorted array." +--- + +## Problem + +Given an array **arr[]** sorted in ascending order of size **N** and an integer **K**. Check if K is present in the array or not. + +### Examples: +**Example 1:** +``` +Input: +N = 5, K = 6 +arr[] = {1,2,3,4,6} +Output: 1 +Exlpanation: Since, 6 is present in the array at index 4(0-based indexing), output is 1. +``` + +**Example 2:** +``` +Input: +N = 5, K = 2 +arr[] = {1,3,4,5,6} +Output: -1 +Exlpanation: Since, 2 is not present in the array, output is -1. +``` + +### Your task: + +You don't need to read input or print anything. Complete the function **searchInSorted()** which takes the sorted array arr[], its size N and the element K as input parameters and returns 1 if K is present in the array, else it returns -1. + +- **Expected Time Complexity:** $O(log N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^6$ +- $1<=K<=10^6$ +- $1<=arr[i]<=10^6$ + +## Solution +### Python +```python +def searchInSorted(self,arr, N, K): + low = 0 + high = N-1 + while low <= high: + mid = low + (high - low) // 2 + if arr[mid] == K: + return 1 + elif arr[mid] < K: + low = mid + 1 + else: + high = mid - 1 + return -1 +``` + +### Java +```java +static int searchInSorted(int arr[], int N, int K) { + int low = 0; + int high = N - 1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (arr[mid] == K) { + return 1; + } + else if (arr[mid] < K) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + return -1; +} +``` + +### C++ +```cpp +int searchInSorted(int arr[], int N, int K) { + int low = 0; + int high = N - 1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (arr[mid] == K) { + return 1; + } + else if (arr[mid] < K) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + return -1; + } +``` + +### C +```c +int searchInSorted(int arr[], int N, int K) { +int low = 0; +int high = N - 1; +while (low <= high) { + int mid = low + (high - low) / 2; + if (arr[mid] == K) { + return 1; + } + else if (arr[mid] < K) { + low = mid + 1; + } + else { + high = mid - 1; + } +} +return -1; +} +``` + +- **Time Complexity:** $O(log N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0016.md b/solutions/gfg-solutions/Basic/0016.md new file mode 100644 index 0000000..f557904 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0016.md @@ -0,0 +1,172 @@ +--- +id: linked-list-insertion +title: Linked List Insertion +sidebar_label: 0016 Linked List Insertion +tags: +- Linked List +- C +- Python +- Java +- C++ +description: "This document provides solutions to inserting an element in the linked list." +--- + +## Problem + +Create a link list of size N according to the given input literals. Each integer input is accompanied by an indicator which can either be 0 or 1. If it is 0, insert the integer in the beginning of the link list. If it is 1, insert the integer at the end of the link list. + +**Hint:** When inserting at the end, make sure that you handle NULL explicitly. + +### Examples: +**Example 1:** +``` +Input: +LinkedList: 9->0->5->1->6->1->2->0->5->0 +Output: 5 2 9 5 6 +Explanation: +Length of Link List = N = 5 +9 0 indicated that 9 should be +inserted in the beginning. Modified +Link List = 9. +5 1 indicated that 5 should be +inserted in the end. Modified Link +List = 9,5. +6 1 indicated that 6 should be +inserted in the end. Modified Link +List = 9,5,6. +2 0 indicated that 2 should be +inserted in the beginning. Modified +Link List = 2,9,5,6. +5 0 indicated that 5 should be +inserted in the beginning. Modified +Link List = 5,2,9,5,6. +Final linked list = 5, 2, 9, 5, 6. +``` + +**Example 2:** +``` +Input: +LinkedList: 5->1->6->1->9->1 +Output: 5 6 9 +``` + +### Your task: + +You only need to complete the functions **insertAtBeginning()** and **insertAtEnd()** that takes the head of link list and integer value of the data to be inserted as inputs and returns the head of the modified link list. + +- **Expected Time Complexity:** $O(1)$ for **insertAtBeginning()** and $O(N)$ for **insertAtEnd()** +- **Expected Auxiliary Space:** $O(1)$ for both + +### Constraints: + +- $1<=N<=10^4$ + +## Solution +### Python +```python +def insertAtBegining(self,head,x): + new_node = Node(x) + new_node.next = head + head = new_node + return head + +def insertAtEnd(self,head,x): + new_node = Node(x) + if head is None: + head = new_node + else: + temp = head + while temp.next is not None: + temp = temp.next + temp.next = new_node + return head +``` + +### Java +```java +Node insertAtBeginning(Node head, int x) { + Node new_node = new Node(x); + new_node.next = head; + head = new_node; + return head; +} + +Node insertAtEnd(Node head, int x) { + Node new_node = new Node(x); + if (head == null) { + head = new_node; + } + else { + Node temp = head; + while (temp.next != null) { + temp = temp.next; + } + temp.next = new_node; + } + return head; +} +``` + +### C++ +```cpp +Node *insertAtBegining(Node *head, int x) { + Node *new_node = new Node(x); + new_node->next = head; + head = new_node; + return head; +} + +Node *insertAtEnd(Node *head, int x) { + Node *new_node = new Node(x); + if (head == nullptr) { + head = new_node; + } + else { + Node *temp = head; + while (temp->next != nullptr) { + temp = temp->next; + } + temp->next = new_node; + } + return head; +} +``` + +### C +```c +struct Node *insertAtBegining(struct Node *head, int x) { + struct Node *new_node = (struct Node*) malloc(sizeof(struct Node)); + if (new_node == NULL) { + printf("Memory allocation failed.\n"); + return head; + } + new_node->data = x; + new_node->next = head; + head = new_node; + return head; +} + +struct Node *insertAtEnd(struct Node *head, int x) { + struct Node *new_node = (struct Node*) malloc(sizeof(struct Node)); + if (new_node == NULL) { + printf("Memory allocation failed.\n"); + return head; + } + new_node->data = x; + new_node->next = NULL; + if (head == NULL) { + head = new_node; + } + else { + struct Node *temp = head; + while (temp->next != NULL) { + temp = temp->next; + } + temp->next = new_node; + } + return head; +} +``` + +- **Time Complexity:** $O(1)$ for **insertAtBeginning()** and $O(N)$ for **insertAtEnd()** +- **Auxiliary Space:** $O(1)$ for both \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0017.md b/solutions/gfg-solutions/Basic/0017.md new file mode 100644 index 0000000..a924c3f --- /dev/null +++ b/solutions/gfg-solutions/Basic/0017.md @@ -0,0 +1,99 @@ +--- +id: minimum-element-in-bst +title: Minimum element in BST +sidebar_label: 0017 Minimum element in BST +tags: +- Binary Search Tree +- Linked List +- C +- Python +- Java +- C++ +description: "This document provides solutions to finding the minimum element in a binary search tree." +--- + +## Problem + +Given the root of a **Binary Search Tree**. The task is to find the minimum valued element in this given BST. + +### Examples: +**Example 1:** +``` +Input: + 5 + / \ + 4 6 + / \ + 3 7 + / + 1 +Output: 1 +``` + +**Example 2:** +``` +Input: + 9 + \ + 10 + \ + 11 +Output: 9 +``` + +### Your task: + +The task is to complete the function **minValue()** which takes root as the argument and returns the minimum element of BST. If the tree is empty, there is no minimum element, so return **-1** in that case. + +- **Expected Time Complexity:** $O$(Height of the BST) +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $0<=n<=10^4$ + +## Solution +### Python +```python +def minValue(self, root): + current = root + while(current.left is not None): + current = current.left + return current.data +``` + +### Java +```java +int minValue(Node root) { + Node current = root; + while (current.left != null) { + current = current.left; + } + return current.data; +} +``` + +### C++ +```cpp +int minValue(Node* root) { + Node* current = root; + while (current->left != nullptr) { + current = current->left; + } + return current->data; +} +``` + +### C +```c +int minValue(struct Node *root) { + struct Node* current = root; + while (current->left != NULL) { + current = current->left; + } + return current->data; +} +``` + +- **Time Complexity:** $O$(Height of the BST) +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0018.md b/solutions/gfg-solutions/Basic/0018.md new file mode 100644 index 0000000..2576102 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0018.md @@ -0,0 +1,106 @@ +--- +id: immediate-smaller-element +title: Immediate Smaller Element +sidebar_label: 0018 Immediate Smaller Element +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to finding the intermediate smaller element in an array." +--- + +## Problem + +Given an integer array **Arr** of size **N**. For each element in the array, check whether the right adjacent element (on the next immediate position) of the array is smaller. If next element is smaller, update the current index to that element. If not, then **-1**. + +### Examples: +**Example 1:** +``` +Input: +N = 5 +Arr[] = {4, 2, 1, 5, 3} +Output: +2 1 -1 3 -1 +Explanation: Array elements are 4, 2, 1, 5, 3. Next to 4 is 2 which is smaller, so we print 2. Next of 2 is 1 which is smaller, so we print 1. Next of 1 is 5 which is greater, so we print -1. Next of 5 is 3 which is smaller, so we print 3. Note that for last element, output is always going to be -1 because there is no element on right. +``` + +**Example 2:** +``` +Input: +N = 6 +Arr[] = {5, 6, 2, 3, 1, 7} +Output: +-1 2 -1 1 -1 -1 +Explanation: Next to 5 is 6 which is greater, so we print -1. Next of 6 is 2 which is smaller, so we print 2. Next of 2 is 3 which is greater, so we print -1. Next of 3 is 1 which is smaller, so we print 1. Next of 1 is 7 which is greater, so we print -1. Note that for last element, output is always going to be -1 because there is no element on right. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **immediateSmaller()** which takes the array of integers **arr** and **n** as parameters. You need to change the array itself. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^7$ +- $1<=Arr[i]<=10^5$ + +## Solution +### Python +```python +def immediateSmaller(self,arr,n): + for i in range(n - 1) : + if (arr[i] > arr[i + 1]) : + arr[i] = arr[i + 1] + else : + arr[i] = -1 + arr[n - 1] = -1 +``` + +### Java +```java +void immediateSmaller(int arr[], int n) { + for (int i = 0; i < n - 1; i++) { + if (arr[i] > arr[i + 1]) { + arr[i] = arr[i + 1]; + } + else + arr[i] = -1; + } + arr[n - 1] = -1; +} +``` + +### C++ +```cpp +void immediateSmaller(vector&arr, int n) { + for (int i = 0; i < n - 1; i++) { + if (arr[i] > arr[i + 1]) { + arr[i] = arr[i + 1]; + } + else + arr[i] = -1; + } + arr[n - 1] = -1; +} +``` + +### C +```c +void immediateSmaller(int arr[], int n) { + for (int i = 0; i < n - 1; i++) { + if (arr[i] > arr[i + 1]) { + arr[i] = arr[i + 1]; + } else { + arr[i] = -1; + } + } + arr[n - 1] = -1; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0019.md b/solutions/gfg-solutions/Basic/0019.md new file mode 100644 index 0000000..4182c3d --- /dev/null +++ b/solutions/gfg-solutions/Basic/0019.md @@ -0,0 +1,122 @@ +--- +id: implement-strstr +title: Implement strstr +sidebar_label: 0019 Implement strstr +tags: +- String +- C +- Python +- Java +- C++ +description: "This document provides solutions to check if a string is a substring of another." +--- + +## Problem + +Your task is to implement the function **strstr**. The function takes two strings as arguments **(s,x)** and locates the occurrence of the string **x** in the string **s**. The function returns an integer denoting the **first occurrence** of the string **x** in s (0 based indexing). + +**Note:** You are not allowed to use inbuilt function. + +### Examples: +**Example 1:** +``` +Input: +s = GeeksForGeeks, x = Fr +Output: -1 +Explanation: Fr is not present in the string GeeksForGeeks as substring. +``` + +**Example 2:** +``` +Input: +s = GeeksForGeeks, x = For +Output: 5 +Explanation: For is present as substring in GeeksForGeeks from index 5 (0 based indexing). +``` + +### Your task: + +You don't have to take any input. Just complete the **strstr()** function which takes two strings **str**, **target** as an input parameter. The function returns -1 if no match if found else it returns an integer denoting the first occurrence of the x in the string s. + +- **Expected Time Complexity:** $O(|s|*|x|)$ +- **Expected Auxiliary Space:** $O(1)$ + +Note : Try to solve the question in constant space complexity. + +### Constraints: + +- $1 <= |s|,|x| <= 100$ + +## Solution +### Python +```python +def strstr(s,x): + n, m = len(s), len(x) + if m == 0: + return 0 + for i in range(n - m + 1): + if s[i:i + m] == x: + return i + return -1 +``` + +### Java +```java +int strstr(String s, String x) { + int n = s.length(); + int m = x.length(); + if (m == 0) { + return 0; + } + for (int i = 0; i <= n - m; i++) { + if (s.substring(i, i + m).equals(x)) { + return i; + } + } + return -1; +} +``` + +### C++ +```cpp +int strstr(string s, string x) { + int n = s.length(); + int m = x.length(); + if (m == 0) { + return 0; + } + for (int i = 0; i <= n - m; i++) { + if (s.substr(i, m) == x) { + return i; + } + } + return -1; +} +``` + +### C +```c +int strstr_c(const char *s, const char *x) { + int n = strlen(s); + int m = strlen(x); + if (m == 0) { + return 0; + } + for (int i = 0; i <= n - m; i++) { + int match = 1; + for (int j = 0; j < m; j++) { + if (s[i + j] != x[j]) { + match = 0; + break; + } + } + if (match) { + return i; + } + } + return -1; +} +``` + +- **Time Complexity:** $O(|s|*|x|)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0020.md b/solutions/gfg-solutions/Basic/0020.md new file mode 100644 index 0000000..aa03874 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0020.md @@ -0,0 +1,136 @@ +--- +id: implement-stack-using-array +title: Implement stack using array +sidebar_label: 0020 Implement stack using array +tags: +- Array +- Stack +- C +- Python +- Java +- C++ +description: "This document provides solutions to implement a stack using array." +--- + +## Problem + +Write a program to implement a Stack using Array. Your task is to use the class as shown in the comments in the code editor and complete the functions push() and pop() to implement a stack. + +### Examples: +**Example 1:** +``` +Input: +push(2) +push(3) +pop() +push(4) +pop() +Output: 3, 4 +Explanation: +push(2) the stack will be {2} +push(3) the stack will be {2 3} +pop() poped element will be 3, + the stack will be {2} +push(4) the stack will be {2 4} +pop() poped element will be 4 +``` + +**Example 2:** +``` +Input: +pop() +push(4) +push(5) +pop() +Output: -1, 5 +``` + +### Your task: + +You are required to complete two methods **push()** and **pop()**. The push() method takes one argument, an integer '**x**' to be pushed into the stack and **pop()** which returns an integer present at the top and popped out from the stack. If the stack is empty then return **-1** from the pop() method. + +- **Expected Time Complexity:** $O(1)$ for both **push()** and **pop()** +- **Expected Auxiliary Space:** $O(1)$ for both **push()** and **pop()** + +### Constraints: + +- $1 <= Q <= 100$ +- $1 <= x <= 100$ + +## Solution +### Python +```python +def push(self,data): + self.arr.append(data) + return self.arr + +def pop(self): + if len(self.arr) == 0: + return -1 + else: + return self.arr.pop() +``` + +### Java +```java +void push(int a) { + if (top < 999) { + top++; + arr[top] = a; + } +} + +int pop() { + if (top >= 0) { + int poppedElement = arr[top]; + top--; + return poppedElement; + } + else { + return -1; + } +} +``` + +### C++ +```cpp +void MyStack :: push(int x) { + if (top < 999) { + top++; + arr[top] = x; + } +} + +int MyStack :: pop() { + if (top >= 0) { + int poppedElement = arr[top]; + top--; + return poppedElement; + } + else { + return -1; + } +} +``` + +### C +```c +void push(struct Stack* stack, int item) { + if (stack->top != stack->capacity - 1) { + stack->top++; + stack->array[stack->top] = item; + } +} + +int pop(struct Stack* stack) { + if (stack->top == -1) { + return -1; + } + int item = stack->array[stack->top]; + stack->top--; + return item; +} +``` + +- **Time Complexity:** $O(1)$, for both **push()** and **pop()** +- **Auxiliary Space:** $O(1)$, for both **push()** and **pop()** \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0021.md b/solutions/gfg-solutions/Basic/0021.md new file mode 100644 index 0000000..08c05e3 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0021.md @@ -0,0 +1,99 @@ +--- +id: count-linked-list-nodes +title: Count Linked List Nodes +sidebar_label: 0021 Count Linked List Nodes +tags: +- Linked List +- C +- Python +- Java +- C++ +description: "This document provides solutions to counting the nodes in a linked list." +--- + +## Problem + +Given a singly linked list. The task is to find the length of the linked list, where length is defined as the number of nodes in the linked list. + +### Examples: +**Example 1:** +``` +Input: +LinkedList: 1->2->3->4->5 +Output: 5 +Explanation: Count of nodes in the linked list is 5, which is its length. +``` + +**Example 2:** +``` +Input: +LinkedList: 2->4->6->7->5->1->0 +Output: 7 +Explanation: Count of nodes in the linked list is 7. Hence, the output is 7. +``` + +### Your task: + +Your task is to complete the given function **getCount()**, which takes a head reference as an argument and should return the length of the linked list. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1<=value<=10^3$ + +## Solution +### Python +```python +def getCount(self, head_node): + temp = head_node + count = 0 + while temp is not None: + count+=1 + temp = temp.next + return count +``` + +### Java +```java +public static int getCount(Node head) { + Node temp = head; + int count = 0; + while(temp!=null) { + count++; + temp = temp.next; + } + return count; +} +``` + +### C++ +```cpp +int getCount(struct Node* head){ + struct Node* temp = head; + int count = 0; + while (temp != NULL) { + count++; + temp = temp->next; + } + return count; +} +``` + +### C +```c +int getCount(struct Node* head) { + struct Node* temp = head; + int count = 0; + while (temp != NULL) { + count++; + temp = temp->next; + } + return count; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0022.md b/solutions/gfg-solutions/Basic/0022.md new file mode 100644 index 0000000..c4d3997 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0022.md @@ -0,0 +1,105 @@ +--- +id: preorder-traversal +title: Preorder Traversal +sidebar_label: 0022 Preorder Traversal +tags: +- Array +- Vector +- Python +- Java +- C++ +description: "This document provides solutions to preorder traversal of a binary tree." +--- + +## Problem + +Given a binary tree, find its preorder traversal. + +### Examples: +**Example 1:** +``` +Input: + 1 + / + 4 + / \ +4 2 +Output: 1 4 4 2 +``` + +**Example 2:** +``` +Input: + 6 + / \ + 3 2 + \ / + 1 2 +Output: 6 3 1 2 2 +``` + +### Your task: + +You just have to complete the function **preorder()** which takes the root node of the tree as input and returns an array containing the preorder traversal of the tree. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(N)$ + +### Constraints: + +- $1 <=$ Number of nodes $<= 10^4$ +- $0 <=$ Data of a node $<= 10^5$ + +## Solution +### Python +```python +def preorder(root): + arr = [] + def traverse(node): + if node is None: + return + arr.append(node.data) + traverse(node.left) + traverse(node.right) + traverse(root) + return arr +``` + +### Java +```java +static ArrayList preorder(Node root) { + ArrayList arr = new ArrayList<>(); + traverse(root, arr); + return arr; +} + +static void traverse(Node node, ArrayList arr) { + if (node == null) + return; + arr.add(node.data); + traverse(node.left, arr); + traverse(node.right, arr); +} +``` + +### C++ +```cpp +void traverse(Node* node, std::vector& result); + +vector preorder(Node* root) { + vector result; + traverse(root, result); + return result; +} + +void traverse(Node* node, vector& result) { + if (node == nullptr) + return; + result.push_back(node->data); + traverse(node->left, result); + traverse(node->right, result); +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(N)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0023.md b/solutions/gfg-solutions/Basic/0023.md new file mode 100644 index 0000000..a80767a --- /dev/null +++ b/solutions/gfg-solutions/Basic/0023.md @@ -0,0 +1,120 @@ +--- +id: check-if-circular-linked-list +title: Check If Circular Linked List +sidebar_label: 0010 Check If Circular Linked List +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to whether a linked list is circular or not." +--- + +## Problem + +Given **head**, the head of a singly linked list, find if the linked list is circular or not. A linked list is called circular if it not NULL terminated and all nodes are connected in the form of a cycle. An empty linked list is considered as circular. + +**Note:** The linked list does not contains any inner loop. + +### Examples: +**Example 1:** +``` +Input: +LinkedList: 1->2->3->4->5 (the first and last node is connected, i.e. 5 --> 1) +Output: 1 +``` + +**Example 2:** +``` +Input: +LinkedList: 2->4->6->7->5->1 +Output: 0 +``` + +### Your task: + +The task is to complete the function isCircular() which checks if the given linked list is circular or not. It should return true or false accordingly. (the driver code prints 1 if the returned values is true, otherwise 0) + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <=$Number of nodes$<= 100$ + +## Solution +### Python +```python +def isCircular(head): + if head is None: + return False + slow = head + fast = head.next + while fast is not None and fast.next is not None: + if slow == fast: + return True + slow = slow.next + fast = fast.next.next + return False +``` + +### Java +```java +boolean isCircular(Node head) { + if (head == null) { + return false; + } + Node slow = head; + Node fast = head.next; + while (fast != null && fast.next != null) { + if (slow == fast) { + return true; + } + slow = slow.next; + fast = fast.next.next; + } + return false; +} +``` + +### C++ +```cpp +bool isCircular(Node *head) { + if (head == NULL) { + return false; + } + Node* slow = head; + Node* fast = head->next; + while (fast != nullptr && fast->next != nullptr) { + if (slow == fast) { + return true; + } + slow = slow->next; + fast = fast->next->next; + } + return false; +} +``` + +### C +```c +bool isCircular(struct Node *head){ + if (head == NULL) { + return false; + } + struct Node *slow = head; + struct Node *fast = head->next; + while (fast != NULL && fast->next != NULL) { + if (slow == fast) { + return true; + } + slow = slow->next; + fast = fast->next->next; + } + return false; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0024.md b/solutions/gfg-solutions/Basic/0024.md new file mode 100644 index 0000000..bcb52dd --- /dev/null +++ b/solutions/gfg-solutions/Basic/0024.md @@ -0,0 +1,101 @@ +--- +id: inorder-traversal +title: Inorder Traversal +sidebar_label: 0024 Inorder Traversal +tags: +- Array +- Binary tree +- Python +- Java +- C++ +description: "This document provides solutions for inorder traversal of a tree." +--- + +## Problem + +Given a Binary Tree, find the In-Order Traversal of it. + +### Examples: +**Example 1:** +``` +Input: + 1 + / \ + 3 2 +Output: 3 1 2 +``` + +**Example 2:** +``` +Input: + 10 + / \ + 20 30 + / \ / + 40 60 50 +Output: 40 20 60 10 50 30 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **inOrder()** that takes root node of the tree as input and returns a list containing the In-Order Traversal of the given Binary Tree. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(N)$ + +### Constraints: + +- $1 <=$Number of nodes $<= 10^5$ +- $0 <=$Data of a node $<= 10^5$ + +## Solution +### Python +```python +def InOrder(self,root): + arr = [] + def traverse(node): + if node is None: + return + traverse(node.left) + arr.append(node.data) + traverse(node.right) + traverse(root) + return arr +``` + +### Java +```java +ArrayList inOrder(Node root) { + ArrayList arr = new ArrayList<>(); + traverse(root, arr); + return arr; +} + +void traverse(Node node, ArrayList arr) { + if (node == null) + return; + traverse(node.left, arr); + arr.add(node.data); + traverse(node.right, arr); +} +``` + +### C++ +```cpp +vector inOrder(Node* root) { + vector result; + traverse(root, result); + return result; +} + +void traverse(Node* node, vector& result) { + if (node == nullptr) + return; + traverse(node->left, result); + result.push_back(node->data); + traverse(node->right, result); +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(N)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0025.md b/solutions/gfg-solutions/Basic/0025.md new file mode 100644 index 0000000..00c7804 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0025.md @@ -0,0 +1,144 @@ +--- +id: implement-queue-using-array +title: Implement Queue using array +sidebar_label: 0010 Implement Queue using array +tags: +- Array +- Queue +- C +- Python +- Java +- C++ +description: "This document provides solutions to implement a queue using an array." +--- + +## Problem + +Implement a Queue using an Array. Queries in the Queue are of the following type: +- 1 x (a query of this type means pushing 'x' into the queue) +- 2 (a query of this type means to pop element from queue and print the poped element) + +### Examples: +**Example 1:** +``` +Input: +Q = 5 +Queries = 1 2 1 3 2 1 4 2 +Output: 2 3 +Explanation: +In the first test case for query +1 2 the queue will be {2} +1 3 the queue will be {2 3} +2 poped element will be 2 the + queue will be {3} +1 4 the queue will be {3 4} +2 poped element will be 3 +``` + +**Example 2:** +``` +Input: +Q = 4 +Queries = 1 3 2 2 1 4 +Output: 3 -1 +Explanation: +In the second testcase for query +1 3 the queue will be {3} +2 poped element will be 3 the + queue will be empty +2 there is no element in the + queue and hence -1 +1 4 the queue will be {4}. +``` + +- **Expected Time Complexity:** $O(1)$ for both **push()** and **pop()** +- **Expected Auxiliary Space:** $O(1)$ for both **push()** and **pop()** + +### Constraints: + +- $1 ≀ Q ≀ 10^5$ +- $0 ≀ x ≀ 10^5$ + +## Solution +### Python +```python +def __init__(self): + self.q = [] + +def push(self, x): + self.q.append(x) + +def pop(self): + if self.q: + return self.q.pop(0) + else: + return -1 +``` + +### Java +```java +void push(int x) { + if (rear == arr.length) { + return; + } + arr[rear] = x; + rear++; +} + +int pop() { + if (front == rear) { + return -1; + } + int element = arr[front]; + for (int i = 0; i < rear - 1; i++) { + arr[i] = arr[i + 1]; + } + rear--; + return element; +} +``` + +### C++ +```cpp +void MyQueue :: push(int x) { + if ((rear + 1) % 100005 == front) { + return; + } + arr[rear] = x; + rear = (rear + 1) % 100005; +} + +int MyQueue :: pop() { + if (front == rear) { + return -1; + } + int element = arr[front]; + front = (front + 1) % 100005; + + return element; +} +``` + +### C +```c +void push(struct MyQueue *queue, int x) { + if ((queue->rear + 1) % MAX_SIZE == queue->front) { + return; + } + queue->arr[queue->rear] = x; + queue->rear = (queue->rear + 1) % MAX_SIZE; +} + +int pop(struct MyQueue *queue) { + if (queue->front == queue->rear) { + printf("Queue is empty. Cannot pop element.\n"); + return -1; + } + int element = queue->arr[queue->front]; + queue->front = (queue->front + 1) % MAX_SIZE; + return element; +} +``` + +- **Time Complexity:** $O(1)$ for both **push()** and **pop()** +- **Auxiliary Space:** $O(1)$ for both **push()** and **pop()** \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0026.md b/solutions/gfg-solutions/Basic/0026.md new file mode 100644 index 0000000..7f32263 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0026.md @@ -0,0 +1,78 @@ +--- +id: count-squares +title: Count Squares +sidebar_label: 0026 Count Squares +tags: +- C +- Python +- Java +- C++ +description: "This document provides solutions for calculating perfect squares." +--- + +## Problem + +Consider a sample space S consisting of all perfect squares starting from 1, 4, 9 and so on. You are given a number **N**, you have to output the number of integers less than N in the sample space S. + +### Examples: +**Example 1:** +``` +Input : +N = 9 +Output: +2 +Explanation: +1 and 4 are the only Perfect Squares less than 9. So, the Output is 2. +``` + +**Example 2:** +``` +Input : +N = 3 +Output: +1 +Explanation: +1 is the only Perfect Square less than 3. So, the Output is 1. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **countSquares()** which takes an Integer N as input and returns the answer. + +- **Expected Time Complexity:** $O(sqrt(N))$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^8$ + +## Solution +### Python +```python +def countSquares(self, N): + return (math.floor(math.sqrt(N-1)) - math.ceil(math.sqrt(1)) + 1) +``` + +### Java +```java +static int countSquares(int N) { + return (int)(Math.floor(Math.sqrt(N - 1)) - Math.ceil(Math.sqrt(1)) + 1); +} +``` + +### C++ +```cpp +int countSquares(int N) { + return (floor(sqrt(N - 1)) - ceil(sqrt(1)) + 1); +} +``` + +### C +```c +int countSquares(int N) { + return (int)(floor(sqrt(N - 1)) - ceil(sqrt(1)) + 1); +} +``` + +- **Time Complexity:** $O(sqrt(N))$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0027.md b/solutions/gfg-solutions/Basic/0027.md new file mode 100644 index 0000000..eea9abb --- /dev/null +++ b/solutions/gfg-solutions/Basic/0027.md @@ -0,0 +1,97 @@ +--- +id: print-linked-list-elements +title: Print Linked List elements +sidebar_label: 0027 Print Linked List elements +tags: +- Linked list +- C +- Python +- Java +- C++ +description: "This document provides solutions to cyclically rotate the array by one." +--- + +## Problem + +Given a linked list. Print all the elements of the linked list. + +**Note:** End of Line is handled by driver code itself. You just have to end with a single space. + +### Examples: +**Example 1:** +``` +Input: +LinkedList : 1 -> 2 +Output: +1 2 +Explanation: +The linked list contains two elements 1 and 2.The elements are printed in a single line. +``` + +**Example 2:** +``` +Input: +Linked List : 49 -> 10 -> 30 +Output: +49 10 30 +Explanation: +The linked list contains 3 elements 49, 10 and 30. The elements are printed in a single line. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **display()** which takes the head of the linked list as input and prints the linked list in a single line. + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= n <=10^5$ +- $1 <=$ node values $<= 10^6$ + +## Solution +### Python +```python +def display(self,head): + temp = head + while temp is not None: + print(temp.data, end = " ") + temp = temp.next +``` + +### Java +```java +void display(Node head) { + Node temp = head; + while (temp != null) { + System.out.print(temp.data + " "); + temp = temp.next; + } +} +``` + +### C++ +```cpp +void display(Node *head) { + Node* temp = head; + while (temp != nullptr) { + cout << temp->data << " "; + temp = temp->next; + } +} +``` + +### C +```c +void display(struct Node *head) { + struct Node* temp = head; + while (temp != NULL) { + printf("%d ", temp->data); + temp = temp->next; + } +} +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0028.md b/solutions/gfg-solutions/Basic/0028.md new file mode 100644 index 0000000..4747402 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0028.md @@ -0,0 +1,139 @@ +--- +id: implement-stack-using-linked-list +title: Implement Stack using Linked List +sidebar_label: 0028 Implement Stack using Linked List +tags: +- Array +- Linked List +- C +- Python +- Java +- C++ +description: "This document provides solutions to implementing a stack using linked list." +--- + +## Problem + +You have a linked list and you have to implement the functionalities push and pop of stack using this given linked list. Your task is to use the class as shown in the comments in the code editor and complete the functions push() and pop() to implement a stack. + +### Examples: +**Example 1:** +``` +Input: +push(2) +push(3) +pop() +push(4) +pop() +Output: 3 4 +Explanation: +push(2) the stack will be {2} +push(3) the stack will be {2 3} +pop() poped element will be 3, + the stack will be {2} +push(4) the stack will be {2 4} +pop() poped element will be 4 +``` + +**Example 2:** +``` +Input: +pop() +push(4) +push(5) +pop() +Output: -1 5 +``` + +### Your task: + +You are required to complete two methods **push()** and **pop()**. The **push()** method takes one argument, an integer '**x**' to be pushed into the stack and **pop()** which returns an integer present at the top and popped out from the stack. If the stack is empty then return -1 from the **pop()** method. + +- **Expected Time Complexity:** $O(1)$ for both **push()** and **pop()** +- **Expected Auxiliary Space:** $O(1)$ for both **push()** and **pop()** + +### Constraints: + +- $1 <= Q <= 100$ +- $1 <= x <= 100$ + +## Solution +### Python +```python +def __init__(self): + self.head = None + +def push(self, data): + new_node = StackNode(data) + new_node.next = self.head + self.head = new_node + +def pop(self): + if self.head is None: + return -1 + else: + ele = self.head.data + self.head = self.head.next + return ele +``` + +### Java +```java +void push(int a) { + StackNode new_node = new StackNode(a); + new_node.next = top; + top = new_node; +} + +int pop() { + if (top == null) { + return -1; + } else { + int element = top.data; + top = top.next; + return element; + } +} +``` + +### C++ +```cpp +void MyStack ::push(int x) { + StackNode* new_node = new StackNode(x); + new_node->next = top; + top = new_node; +} + +int MyStack ::pop() { + if (top == nullptr) { + return -1; + } + else { + int element = top->data; + StackNode* temp = top; + top = top->next; + delete temp; + return element; + } +} +``` + +### C +```c +void push(struct Stack* stack, int item) { + if (stack->top == stack->capacity - 1) { + return; + } + stack->array[++stack->top] = item; +} + +int pop(struct Stack* stack) { + if (stack->top == -1) { + return -1; + } + return stack->array[stack->top--]; +} +``` + +- **Time Complexity:** $O(1)$ for both **push()** and **pop()** +- **Auxiliary Space:** $O(1)$ for both **push()** and **pop()** \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0029.md b/solutions/gfg-solutions/Basic/0029.md new file mode 100644 index 0000000..56cf487 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0029.md @@ -0,0 +1,90 @@ +--- +id: factorial +title: Factorial +sidebar_label: 0029 Factorial +tags: +- C +- Python +- Java +- C++ +description: "This document provides solutions to finding the factorial of a number." +--- + +## Problem + +Given a positive integer, **N**. Find the factorial of **N**. + +### Examples: +**Example 1:** +``` +Input: +N = 5 +Output: +120 +Explanation: +5*4*3*2*1 = 120 +``` + +**Example 2:** +``` +Input: +N = 4 +Output: +24 +Explanation: +4*3*2*1 = 24 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **factorial()** which takes an integer **N** as input parameters and returns an integer, the factorial of N. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $0 <= N <= 18$ + +## Solution +### Python +```python +def factorial (self, N): + fact = 1 + for i in range(1, N+1): + fact = fact*i + return fact +``` + +### Java +```java +static long factorial(int N){ + long fact = 1; + for (int i = 1; i<=N; i++) + fact = fact*i; + return fact; +} +``` + +### C++ +```cpp +long long int factorial(int N){ + long fact = 1; + for (int i = 1; i<=N; i++) + fact = fact*i; + return fact; +} +``` + +### C +```c +long long int factorial(int N){ + long fact = 1; + for (int i = 1; i<=N; i++) + fact = fact*i; + return fact; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0030.md b/solutions/gfg-solutions/Basic/0030.md new file mode 100644 index 0000000..42edec0 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0030.md @@ -0,0 +1,103 @@ +--- +id: identical-linked-lists +title: Identical Linked Lists +sidebar_label: 0029 Identical Linked Lists +tags: +- C +- Python +- Java +- C++ +description: "This document provides solutions for checking whether two linked lists are identical or not." +--- + +## Problem + +Given the two singly **Linked Lists** respectively. The task is to check whether two linked lists are **identical** or not. + +Two Linked Lists are identical when they have the same data and with the same arrangement too. If both Linked Lists are identical then return true otherwise return false. + +### Examples: +**Example 1:** +``` +Input: +LinkedList1: 1->2->3->4->5->6 +LinkedList2: 99->59->42->20 +Output: Not identical +``` + +**Example 2:** +``` +Input: +LinkedList1: 1->2->3->4->5 +LinkedList2: 1->2->3->4->5 +Output: Identical +``` + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= n <= 10^3$ + +## Solution +### Python +```python +def areIdentical(head1, head2): + temp1 = head1 + temp2 = head2 + while temp1 is not None and temp2 is not None: + if temp1.data!=temp2.data: + return False + temp1 = temp1.next + temp2 = temp2.next + return True +``` + +### Java +```java +public boolean isIdentical (Node head1, Node head2){ + Node temp1 = head1; + Node temp2 = head2; + while (temp1!=null && temp2!=null) { + if (temp1.data!=temp2.data) + return false; + temp1 = temp1.next; + temp2 = temp2.next; + } + return temp1 == null && temp2 == null; +} +``` + +### C++ +```cpp +bool areIdentical(struct Node *head1, struct Node *head2) { + struct Node* temp1 = head1; + struct Node* temp2 = head2; + while (temp1 != nullptr && temp2 != nullptr) { + if (temp1->data != temp2->data) + return false; + temp1 = temp1->next; + temp2 = temp2->next; + } + return temp1 == nullptr && temp2 == nullptr; +} +``` + +### C +```c +bool areIdentical(struct Node *head1, struct Node *head2) { + struct Node* temp1 = head1; + struct Node* temp2 = head2; + while (temp1 != NULL && temp2 != NULL) { + if (temp1->data != temp2->data) + return false; + temp1 = temp1->next; + temp2 = temp2->next; + } + return temp1 == NULL && temp2 == NULL; +} +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0031.md b/solutions/gfg-solutions/Basic/0031.md new file mode 100644 index 0000000..5293dc8 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0031.md @@ -0,0 +1,98 @@ +--- +id: searching-a-number +title: Searching a number +sidebar_label: 0031 Searching a number +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to finding the position of an element in the array." +--- + +## Problem + +Given an array **arr** of **n** elements and a integer **k**. Your task is to return the position of **first occurence** of **k** in the given array and if element k is not present in the array then return **-1** . + +**Note:** Position of first element is considered as 1. + +### Examples: +**Example 1:** +``` +Input: +n = 5 +k = 16 +arr = {9, 7, 2, 16, 4} +Output: 4 +Explanation: k = 16 is found in the given array at position 4. +``` + +**Example 2:** +``` +Input: +n = 7 +k = 98 +arr = {1, 22, 57, 47, 34, 18, 66} +Output: -1 +Explanation: k = 98 isn't found in the given array. +``` + +### Your task: + +Complete the function **search()** which takes two integers **n** , **k** and an array **arr**, as input parameters and returns an integer denoting the answer. Return **-1** if the number is not found in the array. You don't have to print answers or take inputs. + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= n <= 10^6$ +- $1 <= k <= 10^6$ +- $1 <= arr[i] <= 10^9$ + +## Solution +### Python +```python +def search(self, n : int, k : int, arr : List[int]) -> int: + for i in range(0, n-1): + if k==arr[i]: + return i+1 + return -1 +``` + +### Java +```java +public static int search(int n, int k, int[] arr) { + for(int i = 0; i &arr) { + for(int i = 0; i sortArr(vectorarr, int n){ + sort(arr.begin(), arr.end()); + return arr; +} +``` + +### C +```c +int compare(const void* a, const void* b) { + return (*(int*)a - *(int*)b); +} + +void sortArr(int arr[], int n) { + qsort(arr, n, sizeof(int), compare); +} +``` + +- **Time Complexity:** $O(n * log n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0033.md b/solutions/gfg-solutions/Basic/0033.md new file mode 100644 index 0000000..bcc31d1 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0033.md @@ -0,0 +1,114 @@ +--- +id: postorder-traversal +title: Postorder Traversal +sidebar_label: 0033 Postorder Traversal +tags: +- Binary Tree +- Python +- Java +- C++ +description: "This document provides solutions postorder traversal of a binary tree." +--- + +## Problem + +Given a binary tree, find the Postorder Traversal of it. + +For Example, the postorder traversal of the following tree is: +5 10 39 1 +``` + 1 + / \ + 10 39 + / +5 +``` + +### Examples: +**Example 1:** +``` +Input: + 19 + / \ + 10 8 + / \ + 11 13 +Output: 11 13 10 8 19 +``` + +**Example 2:** +``` +Input: + 11 + / + 15 + / + 7 +Output: 7 15 11 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **postOrder()** that takes **root node** as input and returns an array containing the postorder traversal of the given Binary Tree. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(N)$ + +### Constraints: + +- $1 <=$ Number of nodes $<= 10^5$ +- $0 <=$ Data of a node $<= 10^5$ + +## Solution +### Python +```python +def postOrder(root): + arr = [] + def traverse(node): + if node is None: + return + traverse(node.left) + traverse(node.right) + arr.append(node.data) + traverse(root) + return arr +``` + +### Java +```java +ArrayList postOrder(Node root) { + ArrayList arr = new ArrayList<>(); + traverse(root, arr); + return arr; +} + +void traverse(Node node, ArrayList arr) { + if (node == null) + return; + traverse(node.left, arr); + traverse(node.right, arr); + arr.add(node.data); +} +``` + +### C++ +```cpp +void traverse(Node* node, vector& result); + +vector postOrder(Node* root) { + vector result; + traverse(root, result); + return result; +} + +void traverse(Node* node, vector& result) { + if (node == nullptr) + return; + traverse(node->left, result); + traverse(node->right, result); + result.push_back(node->data); +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(N)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0034.md b/solutions/gfg-solutions/Basic/0034.md new file mode 100644 index 0000000..baa9eb4 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0034.md @@ -0,0 +1,112 @@ +--- +id: lcm-and-gcd +title: LCM and GCD +sidebar_label: 0034 LCM and GCD +tags: +- Mathematics +- Number Theory +- C +- Python +- Java +- C++ +description: "This document provides solutions for finding the Least Common Multiple (LCM) and Greatest Common Divisor (GCD) of integers." +--- + +## Problem + +Given two integers a and b, write a function lcmAndGcd() to compute their LCM and GCD. The function takes two integers b and b as input and returns a list containing their LCM and GCD. + +### Examples: +**Example 1:** +``` +Input: a = 5 , b = 10 +Output: 10 5 +Explanation: LCM of 5 and 10 is 10, while thier GCD is 5. +``` + +**Example 2:** +``` +Input: a = 14 , b = 8 +Output: 56 2 +Explanation: LCM of 14 and 8 is 56, while thier GCD is 2. +``` + +- **Expected Time Complexity:** $O(log(min(a, b))$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= a, b <=10^9$ + +## Solution +### Python +```python +def lcmAndGcd(self, A , B): + def g(a,b): + if (b == 0): + return a + return g(b, a%b) + + gcd = g(A, B) + lcm = A*B//gcd + return lcm, gcd +``` + +### Java +```java +static Long[] lcmAndGcd(Long A , Long B) { + long gcd = calculateGCD(A, B); + long lcm = (A * B) / gcd; + return new Long[] {lcm, gcd}; +} + +static long calculateGCD(long a, long b) { + if (b == 0) { + return a; + } + return calculateGCD(b, a % b); +} +``` + +### C++ +```cpp +public: +vector lcmAndGcd(long long A , long long B) { + long long gcd_val = gcd(A, B); + long long lcm_val = (A / gcd_val) * B; + return {lcm_val, gcd_val}; +} + +private: +long long gcd(long long a, long long b) { + if (b == 0) { + return a; + } + return gcd(b, a % b); +} +``` + +### C +```c +long long gcd(long long a, long long b) { + while (b != 0) { + long long temp = b; + b = a % b; + a = temp; + } + return a; +} + +long long lcm(long long a, long long b) { + return (a / gcd(a, b)) * b; +} + +void lcmAndGcd(long long A, long long B, long long *lcm_result, long long *gcd_result) { + *gcd_result = gcd(A, B); + *lcm_result = lcm(A, B); +} + +``` + +- **Time Complexity:** $O(log(min(a, b))$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0035.md b/solutions/gfg-solutions/Basic/0035.md new file mode 100644 index 0000000..440b6d2 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0035.md @@ -0,0 +1,135 @@ +--- +id: rotating-an-array +title: Rotating an Array +sidebar_label: 0035 Rotating an Array +tags: +- Array +- Rotation +- C +- Python +- Java +- C++ +description: "This document provides solutions for rotating an array to the left or right by a specified number of positions." +--- + +## Problem + +Given an array of size n. The task is to rotate array by d elements where d ≀ n. + +### Examples: +**Example 1:** +``` +Input: +n = 7 +arr[] = {-1, -2, -3, 4, 5, 6, 7} +d = 2 +Output: {-3, 4, 5, 6, 7, -1, -2} +Explanation: +Rotate by 1: [-2, -3, 4, 5, 6, 7, -1] +Rotate by 2: [-3, 4, 5, 6, 7, -1, -2] +``` + +**Example 2:** +``` +Input: +n = 4 +arr[] = {1, 3, 4, 2} +d = 3 +Output: {2, 1, 3, 4} +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **leftRotate()** which takes the array of integers **arr[]**, its size **n** and **d** as input parameters and rotates arr[] in-place without using any extra memory. + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 ≀ n ≀ 10^6$ +- $-10^9 ≀ arr[i] ≀ 10^9$ +- $0 ≀ d ≀ n$ + +## Solution +### Python +```python +def reverse(self, arr, start, end): + while start < end: + arr[start], arr[end] = arr[end], arr[start] + start += 1 + end -= 1 + +def leftRotate(self, arr, n, d): + d = d % n + self.reverse(arr, 0, d - 1) + self.reverse(arr, d, n - 1) + self.reverse(arr, 0, n - 1) +``` + +### Java +```java +void leftRotate(int[] arr, int n, int d) { + d = d % n; + reverse(arr, 0, d - 1); + reverse(arr, d, n - 1); + reverse(arr, 0, n - 1); +} + +void reverse(int[] arr, int start, int end) { + while (start < end) { + int temp = arr[start]; + arr[start] = arr[end]; + arr[end] = temp; + start++; + end--; + } +} +``` + +### C++ +```cpp +public: +void reverse(int arr[], int start, int end) { + while (start < end) { + swap(arr[start], arr[end]); + start++; + end--; + } +} + +public: +void leftRotate(int arr[], int n, int d) { + d = d % n; + reverse(arr, 0, d - 1); + reverse(arr, d, n - 1); + reverse(arr, 0, n - 1); +} +``` + +### C +```c +void swap(int *a, int *b) { + int temp = *a; + *a = *b; + *b = temp; +} + +void reverse(int arr[], int start, int end) { + while (start < end) { + swap(&arr[start], &arr[end]); + start++; + end--; + } +} + +void leftRotate(int arr[], int n, int d) { + d = d % n; + reverse(arr, 0, d - 1); + reverse(arr, d, n - 1); + reverse(arr, 0, n - 1); +} +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0036.md b/solutions/gfg-solutions/Basic/0036.md new file mode 100644 index 0000000..e3b2aa5 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0036.md @@ -0,0 +1,118 @@ +--- +id: binary-array-sorting +title: Binary Array Sorting +sidebar_label: 0036 Binary Array Sorting +tags: +- Array +- Sorting +- Binary Array +- C +- Python +- Java +- C++ +description: "This document provides solutions for sorting a binary array, where elements are either 0 or 1." +--- + +## Problem + +Given a binary array **A[]** of size **N**. The task is to arrange the array in increasing order. + +**Note:** The binary array contains only 0 and 1. + +### Examples: +**Example 1:** +``` +Input: +5 +1 0 1 1 0 + +Output: +0 0 1 1 1 + +Explanation: +After arranging the elements in increasing order, elements will be as 0 0 1 1 1. +``` + +**Example 2:** +``` +Input: +10 +1 0 1 1 1 1 1 0 0 0 + +Output: +0 0 0 0 1 1 1 1 1 1 + +Explanation: +After arranging the elements in increasing order, elements will be 0 0 0 0 1 1 1 1 1 1. +``` + +### Your task: + +This is a function problem. You only need to complete the function **binSort()** that takes the array **A[]** and it's size **N** as parameters and sorts the array. The printing is done automatically by the driver code. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^6$ +- $0<=A[i]<=1$ + +## Solution +### Python +```python +def binSort(self, A, N): + j = -1 + for i in range(N): + if A[i] < 1: + j = j + 1 + A[i], A[j] = A[j], A[i] +``` + +### Java +```java +static void binSort(int A[], int N) { + int j = -1; + for (int i = 0; i < N; i++) { + if (A[i] < 1) { + j++; + int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } + } +} +``` + +### C++ +```cpp +void binSort(int A[], int N) { + int j = -1; + for (int i = 0; i < N; i++) { + if (A[i] < 1) { + j++; + int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } + } +} +``` + +### C +```c +void binSort(int A[], int N) { + int j = -1; + for (int i = 0; i < N; i++) { + if (A[i] < 1) { + j++; + int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } + } +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0037.md b/solutions/gfg-solutions/Basic/0037.md new file mode 100644 index 0000000..d401329 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0037.md @@ -0,0 +1,125 @@ +--- +id: count-leaves-binary-tree +title: Count Leaves in Binary Tree +sidebar_label: 0037 Count Leaves in Binary Tree +tags: +- Binary Tree +- Tree Traversal +- Depth-First Search +- C +- Python +- Java +- C++ +description: "This document provides solutions for counting the number of leaf nodes in a binary tree." +--- + +## Problem + +Given a Binary Tree of size N, You have to count leaves in it. For example, there are two leaves in following tree. + +``` + 1 + / \ + 10 39 + / +5 +``` + +### Examples: +**Example 1:** +``` +Input: +Given Tree is + 4 + / \ + 8 10 + / / \ + 7 5 1 + / + 3 +Output: +3 +Explanation: +Three leaves are 3 , 5 and 1. +``` + +### Your task: + +You don't have to take input. Complete the function **countLeaves()** that takes root node of the given tree as parameter and returns the count of leaves in tree. The printing is done by the driver code. + +### Constraints: + +- $1<=N<=10^4$ + +## Solution +### Python +```python +def countLeaves(root): + q = [] + q.append(root) + count = 0 + while(len(q) > 0): + temp = q.pop(0) + if(temp.left is None and temp.right is None): + count += 1 + if(temp.left is not None): + q.append(temp.left) + if(temp.right is not None): + q.append(temp.right) + return count +``` + +### Java +```java +int countLeaves(Node node) { + Queue q = new LinkedList(); + q.add(node); + int count = 0; + while(!q.isEmpty()){ + Node temp = q.poll(); + if(temp.left == null && temp.right == null) count++; + if(temp.left != null) q.add(temp.left); + if(temp.right != null) q.add(temp.right); + } + return count; +} +``` + +### C++ +```cpp +int countLeaves(Node* root) { + queue q; + q.push(root); + int count = 0; + while(!q.empty()){ + Node* temp = q.front(); + q.pop(); + if(temp->left == NULL && temp->right == NULL) + count++; + if(temp->left) q.push(temp->left); + if(temp->right) q.push(temp->right); + } + return count; +} +``` + +### C +```c +int countLeaves(struct Node* root) { + struct Node** queue = (struct Node**) malloc(1000 * sizeof(struct Node*)); + int front = 0, rear = 0; + queue[rear++] = root; + int count = 0; + while (front < rear) { + struct Node* temp = queue[front++]; + if (temp->left == NULL && temp->right == NULL) + count++; + if (temp->left) + queue[rear++] = temp->left; + if (temp->right) + queue[rear++] = temp->right; + } + free(queue); + return count; +} +``` \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0038.md b/solutions/gfg-solutions/Basic/0038.md new file mode 100644 index 0000000..260cc23 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0038.md @@ -0,0 +1,110 @@ +--- +id: third-largest-element +title: Third Largest Element +sidebar_label: 0038 Third Largest Element +tags: +- Array +- Sorting +- C +- Python +- Java +- C++ +description: "This document provides solutions for finding the third largest element in an array." +--- + + +## Problem + +Given an array of distinct elements. Find the third largest element in it. + +Suppose you have A[] = {1, 2, 3, 4, 5, 6, 7}, its output will be 5 because it is the 3 largest element in the array A. + +### Examples: +**Example 1:** +``` +Input: +N = 5 +A[] = {2,4,1,3,5} +Output: 3 +``` + +**Example 2:** +``` +Input: +N = 2 +A[] = {10,2} +Output: -1 +``` + +### Your task: + +Complete the function **thirdLargest()** which takes the array a[] and the size of the array, n, as input parameters and returns the third largest element in the array. It return -1 if there are less than 3 elements in the given array. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1<=A[i]<=10^5$ + +## Solution +### Python +```python +def thirdLargest(self,a, n): + if (n < 3): + return -1 + else: + a = sorted(a) + return a[-3] +``` + +### Java +```java +int thirdLargest(int a[], int n) { + if (n < 3) { + return -1; + } + else { + Arrays.sort(a); + return a[n - 3]; + } +} +``` + +### C++ +```cpp +int thirdLargest(int a[], int n) { + if (n < 3) { + return -1; + } + else { + std::sort(a, a + n); + return a[n - 3]; + } +} +``` + +### C +```c +int thirdLargest(int* a, int n) { + if (n < 3) { + return -1; + } + else { + for (int i = 0; i < n - 1; i++) { + for (int j = 0; j < n - i - 1; j++) { + if (a[j] > a[j + 1]) { + int temp = a[j]; + a[j] = a[j + 1]; + a[j + 1] = temp; + } + } + } + return a[n - 3]; + } +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0039.md b/solutions/gfg-solutions/Basic/0039.md new file mode 100644 index 0000000..d4d85f1 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0039.md @@ -0,0 +1,125 @@ +--- +id: insert-middle-linked-list +title: Insert in Middle of Linked List +sidebar_label: 0039 Insert in Middle of Linked List +tags: +- Linked List +- Insertion +- C +- Python +- Java +- C++ +description: "This document provides solutions for inserting a node in the middle of a linked list." +--- + +## Problem + +Given a linked list of size **N** and a **key**. The task is to insert the key in the middle of the linked list. + +### Examples: +**Example 1:** +``` +Input: +LinkedList = 1->2->4 +key = 3 +Output: 1 2 3 4 +Explanation: The new element is inserted after the current middle element in the linked list. +``` + +**Example 2:** +``` +Input: +LinkedList = 10->20->40->50 +key = 30 +Output: 10 20 30 40 50 +Explanation: The new element is inserted after the current middle element in the linked list and Hence, the output is 10 20 30 40 50. +``` + +### Your task: + +The task is to complete the function **insertInMiddle()** which takes head reference and element to be inserted as the arguments. The printing is done automatically by the driver code. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^4$ + +## Solution +### Python +```python +def insertInMid(head, node): + if head is None: + return node + slow = head + fast = head + while fast.next is not None and fast.next.next is not None: + slow = slow.next + fast = fast.next.next + node.next = slow.next + slow.next = node + return head +``` + +### Java +```java +public Node insertInMid(Node head, int data){ + Node newNode = new Node(data); + if (head == null) { + return newNode; + } + Node slow = head; + Node fast = head; + while (fast.next != null && fast.next.next != null) { + slow = slow.next; + fast = fast.next.next; + } + newNode.next = slow.next; + slow.next = newNode; + return head; +} +``` + +### C++ +```cpp +Node* insertInMiddle(Node* head, int x) { + Node* newNode = new Node(x); + if (head == nullptr) { + return newNode; + } + Node* slow = head; + Node* fast = head; + while (fast->next != nullptr && fast->next->next != nullptr) { + slow = slow->next; + fast = fast->next->next; + } + newNode->next = slow->next; + slow->next = newNode; + return head; +} +``` + +### C +```c +struct Node* insertInMiddle(struct Node* head, int x) { + struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); + newNode->data = x; + newNode->next = NULL; + if (head == NULL) { + return newNode; + } + struct Node* slow = head; + struct Node* fast = head; + while (fast->next != NULL && fast->next->next != NULL) { + slow = slow->next; + fast = fast->next->next; + } + newNode->next = slow->next; + slow->next = newNode; + return head; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0040.md b/solutions/gfg-solutions/Basic/0040.md new file mode 100644 index 0000000..4450ded --- /dev/null +++ b/solutions/gfg-solutions/Basic/0040.md @@ -0,0 +1,122 @@ +--- +id: maximum-occurring-character +title: Maximum Occurring Character +sidebar_label: Maximum Occurring Character +tags: +- Strings +- C +- Python +- Java +- C++ +description: "This document explores algorithms to find the maximum occurring character in a string." +--- + +## Problem + +Given a string **str** of lowercase alphabets. The task is to find the maximum occurring character in the string **str**. If more than one character occurs the maximum number of time then print the lexicographically smaller character. + +### Examples: +**Example 1:** +``` +Input: +str = testsample +Output: e +Explanation: e is the character which is having the highest frequency. +``` + +**Example 2:** +``` +Input: +str = output +Output: t +Explanation: t and u are the characters with the same frequency, but t is lexicographically smaller. +``` + +### Your task: + +The task is to complete the function **getMaxOccuringChar()** which returns the character which is most occurring. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O$(Number of distinct characters) + +**Note:** N = |s| + +### Constraints: + +- $1 ≀ |s| ≀ 100$ + +## Solution +### Python +```python +def getMaxOccurringChar(self,s): + mp = {} + n = len(s) + ans = '' + cnt = 0 + + for i in range(n): + if s[i] in mp: + mp[s[i]] += 1 + else: + mp[s[i]] = 1 + if mp[s[i]] > cnt or (mp[s[i]] == cnt and s[i] < ans): + ans = s[i] + cnt = mp[s[i]] + return ans +``` + +### Java +```java +public static char getMaxOccuringChar(String line) { + Map mp = new HashMap<>(); + int n = line.length(); + char ans = '\0'; + int cnt = 0; + for (int i = 0; i < n; i++) { + char ch = line.charAt(i); + mp.put(ch, mp.getOrDefault(ch, 0) + 1); + if (mp.get(ch) > cnt || (mp.get(ch) == cnt && ch < ans)) { + ans = ch; + cnt = mp.get(ch); + } + } + return ans; +} +``` + +### C++ +```cpp +char getMaxOccuringChar(string str) { + unordered_map mp; + char ans = '\0'; + int cnt = 0; + for (char ch : str) { + mp[ch]++; + if (mp[ch] > cnt || (mp[ch] == cnt && ch < ans)) { + ans = ch; + cnt = mp[ch]; + } + } + return ans; +} +``` + +### C +```c +char getMaxOccuringChar(const char* str) { + int freq[256] = {0}; + char ans = '\0'; + int cnt = 0; + for (int i = 0; str[i] != '\0'; i++) { + freq[(int)str[i]]++; + if (freq[(int)str[i]] > cnt || (freq[(int)str[i]] == cnt && str[i] < ans)) { + ans = str[i]; + cnt = freq[(int)str[i]]; + } + } + return ans; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O$(Number of distinct characters) \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0041.md b/solutions/gfg-solutions/Basic/0041.md new file mode 100644 index 0000000..8793dfb --- /dev/null +++ b/solutions/gfg-solutions/Basic/0041.md @@ -0,0 +1,103 @@ +--- +id: count-odd-even +title: Count Odd Even +sidebar_label: 0041 Count Odd Even +tags: +- Arrays +- C +- Python +- Java +- C++ +description: "This document covers methods to count the number of odd and even integers in an array." +--- + +## Problem + +Given an array **A[]** of **N** elements. The task is to return the count of the number of **odd** and **even** elements in the array. + +### Examples: +**Example 1:** +``` +Input: +N = 5 +A[] = 1 2 3 4 5 +Output: +3 2 +Explanation: +There are 3 odd elements (1, 3, 5) and 2 even elements (2 and 4). +``` + +### Your task: + +Your task is to complete the function **countOddEven()** which should return the count of odd and even elements of the array. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^6$ +- $1<=A_j<=10^6$ + +## Solution +### Python +```python +def countOddEven(self, arr, n): + odd, even = 0,0 + for i in range(0, n): + if arr[i]%2==0: + even+=1 + else: + odd+=1 + return odd, even +``` + +### Java +```java +public int[] countOddEven(int[] arr, int n) { + int odd = 0, even = 0; + for (int i = 0; i < n; i++) { + if (arr[i] % 2 == 0) { + even++; + } else { + odd++; + } + } + int[] result = { odd, even }; + return result; +} +``` + +### C++ +```cpp +vector countOddEven(int arr[], int sizeof_array) { + int odd = 0, even = 0; + for (int i = 0; i < sizeof_array; i++) { + if (arr[i] % 2 == 0) { + even++; + } else { + odd++; + } + } + vector result = { odd, even }; + return result; +} +``` + +### C +```c +void countOddEven(int arr[], int sizeof_array, int *odd, int *even) { + *odd = 0; + *even = 0; + for (int i = 0; i < sizeof_array; i++) { + if (arr[i] % 2 == 0) { + (*even)++; + } else { + (*odd)++; + } + } +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0042.md b/solutions/gfg-solutions/Basic/0042.md new file mode 100644 index 0000000..3e54b74 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0042.md @@ -0,0 +1,167 @@ +--- +id: implement-queue-linked-list +title: Implement Queue using Linked List +sidebar_label: 0042 Implement Queue with Linked List +tags: +- Queue +- Linked List +- Data Structures +- Implementation +- C +- Python +- Java +- C++ +description: "This document covers the implementation of a Queue data structure using a Linked List in various programming languages." +--- + +## Problem + +Implement a Queue using Linked List. +A Query Q is of 2 Types +- 1 x (a query of this type means pushing 'x' into the queue) +- 2 (a query of this type means to pop an element from the queue and print the poped element) + +### Examples: +**Example 1:** +``` +Input: +Q = 5 +Queries = 1 2 1 3 2 1 4 2 +Output: 2 3 +Explanation: n the first testcase +1 2 the queue will be {2} +1 3 the queue will be {2 3} +2 poped element will be 2 the + queue will be {3} +1 4 the queue will be {3 4} +2 poped element will be 3. +``` + +**Example 2:** +``` +Input: +Q = 4 +Queries = 1 2 2 2 1 3 +Output: 2 -1 +Explanation: In the second testcase +1 2 the queue will be {2} +2 poped element will be {2} then + the queue will be empty. +2 the queue is empty and hence -1 +1 3 the queue will be {3}. +``` + +### Your task: + +Complete the function **push()** which takes an integer as input parameter and **pop()** which will remove and return an element(-1 if queue is empty). + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $0<=a[i]<=10^5$ + +## Solution +### Python +```python +def __init__(self): + self.stack1 = [] + self.stack2 = [] + +def push(self, item): + self.stack1.append(item) + +def pop(self): + if not self.stack2: + while self.stack1: + self.stack2.append(self.stack1.pop()) + if self.stack2: + return self.stack2.pop() + else: + return -1 +``` + +### Java +```java +public MyQueue() { + this.front = null; + this.rear = null; +} + +void push(int a) { + QueueNode newNode = new QueueNode(a); + if (this.rear == null) { + this.front = newNode; + this.rear = newNode; + } + else { + this.rear.next = newNode; + this.rear = newNode; + } +} + +int pop() { + if (this.front == null) + return -1; + int poppedValue = this.front.data; + this.front = this.front.next; + if (this.front == null) + this.rear = null; + return poppedValue; +} +``` + +### C++ +```cpp +void MyQueue:: push(int x) { + QueueNode* newNode = new QueueNode(x); + if (rear == nullptr) { + front = newNode; + rear = newNode; + } + else { + rear->next = newNode; + rear = newNode; + } +} + +int MyQueue :: pop() { + if (front == nullptr) + return -1; + int poppedValue = front->data; + QueueNode* temp = front; + front = front->next; + delete temp; + if (front == nullptr) + rear = nullptr; + return poppedValue; +} +``` + +### C +```c +void push(struct Queue* q, int k) { + struct Node* newnode = newNode(k); + if (q->rear == NULL) { + q->front = q->rear = newnode; + return; + } + q->rear->next = newnode; + q->rear = newnode; +} + +void pop(struct Queue* q) { + if (q->front == NULL) + return -1; + struct Node* temp = q->front; + q->front = q->front->next; + if (q->front == NULL) + q->rear = NULL; + free(temp); +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ diff --git a/solutions/gfg-solutions/Basic/0043.md b/solutions/gfg-solutions/Basic/0043.md new file mode 100644 index 0000000..2fd65e9 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0043.md @@ -0,0 +1,87 @@ +--- +id: max-min +title: Max Min +sidebar_label: 0043 Max Min +tags: +- Arrays +- Python +- Java +- C++ +- C +description: "This document covers methods to find the maximum and minimum elements in an array using various programming languages." +--- + +## Problem + +Given an array **A** of size **N** of integers. Your task is to find the sum of minimum and maximum element in the array. + +### Examples: +**Example 1:** +``` +Input: +N = 5 +A[] = {-2, 1, -4, 5, 3} +Output: 1 +Explanation: min = -4, max = 5. Sum = -4 + 5 = 1 +``` + +**Example 2:** +``` +Input: +N = 4 +A[] = {1, 3, 4, 1} +Output: 5 +Explanation: min = 1, max = 4. Sum = 1 + 4 = 5 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **findSum()** which takes the array **A[]** and its size **N** as inputs and returns the summation of minimum and maximum element of the array. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $-10^9 <= A_i <= 10^9$ + +## Solution +### Python +```python +def findSum(self,A,N): + A.sort() + minmax = A[0]+A[-1] + return minmax +``` + +### Java +```java +public static int findSum(int A[],int N) { + Arrays.sort(A); + int minmax = A[0] + A[N - 1]; + return minmax; +} +``` + +### C++ +```cpp +int findSum(int A[], int N) { + sort(A, A + N); + int minmax = A[0] + A[N - 1]; + return minmax; +} +``` + +### C +```c +void rotate(int arr[], int n) { + int last_el = arr[n - 1]; + for (int i = n - 1; i > 0; i--) + arr[i] = arr[i - 1]; + arr[0] = last_el; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0044.md b/solutions/gfg-solutions/Basic/0044.md new file mode 100644 index 0000000..d7c83a3 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0044.md @@ -0,0 +1,102 @@ +--- +id: bit-difference +title: Bit Difference +sidebar_label: 0044 Bit Difference +tags: +- Bit Manipulation +- C +- Python +- Java +- C++ +description: "This document explains how to convert A to B using bit manipulation." +--- + +## Problem + +You are given two numbers **A** and **B**. The task is to count the number of bits needed to be flipped to convert A to B. + +### Examples: +**Example 1:** +``` +Input: A = 10, B = 20 +Output: 4 +Explanation: +A = 01010 +B = 10100 +As we can see, the bits of A that need to be flipped are 01010. If we flip these bits, we get 10100, which is B. +``` + +**Example 2:** +``` +Input: A = 20, B = 25 +Output: 3 +Explanation: +A = 10100 +B = 11001 +As we can see, the bits of A that need to be flipped are 10100. If we flip these bits, we get 11001, which is B. +``` + +### Your task: + +The task is to complete the function **countBitsFlip()** that takes **A** and **B** as parameters and returns the count of the number of bits to be flipped to convert A to B. + +- **Expected Time Complexity:** $O(log N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=A,B<=10^6$ + +## Solution +### Python +```python +def countBitsFlip(self,a,b): + xor_result = a ^ b + count = 0 + while xor_result != 0: + xor_result = xor_result & (xor_result - 1) + count += 1 + return count +``` + +### Java +```java +public static int countBitsFlip(int a, int b){ + int xorResult = a ^ b; + int count = 0; + while (xorResult != 0) { + xorResult = xorResult & (xorResult - 1); + count++; + } + return count; +} +``` + +### C++ +```cpp +int countBitsFlip(int a, int b){ + int xorResult = a ^ b; + int count = 0; + while (xorResult != 0) { + xorResult = xorResult & (xorResult - 1); + count++; + } + return count; +} +``` + +### C +```c +int countBitsFlip(int a, int b) { + int xorResult = a ^ b; + int count = 0; + while (xorResult != 0) { + xorResult = xorResult & (xorResult - 1); + count++; + } + return count; +} +``` + +- **Time Complexity:** $O(log N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0045.md b/solutions/gfg-solutions/Basic/0045.md new file mode 100644 index 0000000..d61a1bc --- /dev/null +++ b/solutions/gfg-solutions/Basic/0045.md @@ -0,0 +1,158 @@ +--- +id: find-smallest-second-smallest-element-in-array +title: Find the Smallest and Second Smallest Element in an Array +sidebar_label: 0045 Find the Smallest and Second Smallest Element in an Array +tags: +- Arrays +- Python +- Java +- C++ +- C +description: "This document covers methods to find the smallest and second smallest elements in an array using various programming languages." +--- + +## Problem + +Given an array of integers, your task is to find the smallest and second smallest element in the array. If smallest and second smallest do not exist, print **-1**. + +### Examples: +**Example 1:** +``` +Input : +5 +2 4 3 5 6 +Output : +2 3 +Explanation: +2 and 3 are respectively the smallest and second smallest elements in the array. +``` + +**Example 2:** +``` +Input : +6 +1 2 1 3 6 7 +Output : +1 2 +Explanation: +1 and 2 are respectively the smallest and second smallest elements in the array. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **minAnd2ndMin()** which takes the array **A[]** and its size **N** as inputs and returns a vector containing the smallest and second smallest element if possible, else return **{-1,-1}**. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1<=A[i]<=10^5$ + +## Solution +### Python +```python +def minAnd2ndMin(a, n): + if n < 2: + return [-1, -1] + + first_min = float('inf') + second_min = float('inf') + + for num in a: + if num < first_min: + second_min = first_min + first_min = num + elif num < second_min and num != first_min: + second_min = num + + if second_min == float('inf'): + return [-1, -1] + else: + return [first_min, second_min] +``` + +### Java +```java +public long[] minAnd2ndMin(long a[], long n) { + if (n < 2) { + return new long[]{-1, -1}; + } + long first_min = Long.MAX_VALUE; + long second_min = Long.MAX_VALUE; + for (long num : a) { + if (num < first_min) { + second_min = first_min; + first_min = num; + } + else if (num < second_min && num != first_min) { + second_min = num; + } + } + if (second_min == Long.MAX_VALUE) { + return new long[]{-1, -1}; + } + else { + return new long[]{first_min, second_min}; + } +} +``` + +### C++ +```cpp +vector minAnd2ndMin(int a[], int n) { + if (n < 2) { + return {-1, -1}; + } + int first_min = INT_MAX; + int second_min = INT_MAX; + for (int i = 0; i < n; ++i) { + if (a[i] < first_min) { + second_min = first_min; + first_min = a[i]; + } else if (a[i] < second_min && a[i] != first_min) { + second_min = a[i]; + } + } + if (second_min == INT_MAX) { + return {-1, -1}; + } + else { + return {first_min, second_min}; + } +} +``` + +### C +```c +void minAnd2ndMin(int a[], int n, int result[2]) { + if (n < 2) { + result[0] = -1; + result[1] = -1; + return; + } + int first_min = INT_MAX; + int second_min = INT_MAX; + for (int i = 0; i < n; ++i) { + if (a[i] < first_min) { + second_min = first_min; + first_min = a[i]; + } + else if (a[i] < second_min && a[i] != first_min) { + second_min = a[i]; + } + } + if (second_min == INT_MAX) { + result[0] = -1; + result[1] = -1; + } + else { + result[0] = first_min; + result[1] = second_min; + } +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0046.md b/solutions/gfg-solutions/Basic/0046.md new file mode 100644 index 0000000..5b4d985 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0046.md @@ -0,0 +1,42 @@ +--- +id: cpp-hello-world +title: C++ Hello World +sidebar_label: 0046 C++ Hello World +tags: +- C++ +- Programming +- Basics +- Hello World +description: "This document demonstrates how to write a 'Hello, World!' program in C++." +--- + +## Problem + +Let's begin your journey towards coding with the very first question of the coding world. Your task is to write code that prints **Hello World**. + +### Examples: +**Example 1:** +``` +Input: +No Input +Output: +Hello World +``` + +### Your task: + +In the function **helloWorld()**, output a line "Hello World" (without quotes). + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +## Solution +### C++ +```cpp +void helloWorld() { + cout<<"Hello World"< int: + total_sum = n * (n + 1) // 2 + array_sum = sum(arr) + return total_sum - array_sum +``` + +### Java +```java +public static int missingNumber(int n, int[] arr) { + int total_sum = n * (n + 1) / 2; + int array_sum = 0; + for(int i = 0; i &arr) { + int total_sum = n * (n + 1) / 2; + int array_sum = 0; + for (int i = 0; i < arr.size(); i++) { + array_sum += arr[i]; + } + int result = total_sum - array_sum; + return result; +} +``` + +### C +```c +int missingNumber(int n, int arr[], int size) { + int total_sum = n * (n + 1) / 2; + int array_sum = 0; + for (int i = 0; i < size; i++) { + array_sum += arr[i]; + } + int result = total_sum - array_sum; + return result; +} +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0049.md b/solutions/gfg-solutions/Basic/0049.md new file mode 100644 index 0000000..ac307aa --- /dev/null +++ b/solutions/gfg-solutions/Basic/0049.md @@ -0,0 +1,115 @@ +--- +id: closest-number +title: Closest Number +sidebar_label: 0049 Closest Number +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to find the closest number to a given target in an array in various programming languages." +--- + +## Problem + +Given two integers **N** and **M**. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having **maximum absolute value**. + +### Examples: +**Example 1:** +``` +Input: +N = 13 , M = 4 +Output: +12 +Explanation: +12 is the Closest Number to 13 which is divisible by 4. +``` + +**Example 2:** +``` +Input: +N = -15 , M = 6 +Output: +-18 +Explanation: +-12 and -18 are both similarly close to -15 and divisible by 6. but -18 has the maximum absolute value. So, Output is -18 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **closestNumber()** which takes an Integer n as input and returns the answer. + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $-10^5 <= N <= 10^5$ + +## Solution +### Python +```python +def closestNumber(self, N , M): + if M == 0: + return None + quotient = N // M + lower_multiple = M * quotient + upper_multiple = M * (quotient + 1) + if abs(N - lower_multiple) < abs(N - upper_multiple): + return lower_multiple + elif abs(N - upper_multiple) < abs(N - lower_multiple): + return upper_multiple + else: + return max(lower_multiple, upper_multiple, key=abs) +``` + +### Java +```java +static int closestNumber(int N , int M) { + int i=0; + while(true){ + if((N-i)%M==0) + return N-i; + else if((N+i)%M==0) + return N+i; + else + i++; + } +} +``` + +### C++ +```cpp +int closestNumber(int N, int M) { + int r = N % M; + if (r == 0) { + return N; + } + else if (r <= M / 2) { + return N - r; + } + else { + return N + (M - r); + } +} +``` + +### C +```c +int closestNumber(int N, int M) { + int r = N % M; + if (r == 0) { + return N; + } + else if (r <= M / 2) { + return N - r; + } + else { + return N + (M - r); + } +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0050.md b/solutions/gfg-solutions/Basic/0050.md new file mode 100644 index 0000000..6c2116e --- /dev/null +++ b/solutions/gfg-solutions/Basic/0050.md @@ -0,0 +1,97 @@ +--- +id: node-at-given-index-linked-list +title: Node at Given Index in Linked List +sidebar_label: 0047 Node at Given Index in Linked List +tags: +- Linked List +- Python +- Java +- C++ +- C +description: "This document covers methods to find the node at a given index in a linked list in various programming languages." +--- + +## Problem + +Given a singly linked list with N nodes and a number X. The task is to find the node at the given index (X)(1 based index) of linked list. + +### Input: + +First line of input contains number of testcases T. For each testcase, first line of input contains space seperated two integers, length of linked list and X. + +### Output: + +For each testcase, there will be single line of output containing data at Xth node. + +### Examples: + +**Input:** +``` +2 +6 5 +1 2 3 4 657 76 +10 2 +8 7 10 8 6 1 20 91 21 2 +``` + +**Output:** +``` +657 +7 +``` + +**Explanation:** +Testcase 1: Element at 5th index in the linked list is 657 (1-based indexing). + +### Your task: + +The task is to complete the function **GetNth()** which takes head reference and index as arguments and should return the data at Xth position in the linked list. + +### Constraints: + +- $1 <= T <= 30$ +- $1 <= N <= 100$ +- $X <= N$ +- $1 <= value <= 10^3$ + +## Solution +### Python +```python +def getNth(head, k): + temp = head + for _ in range(0,k-1): + temp = temp.next + return temp.data +``` + +### Java +```java +public static int getNth(Node node, int ind) { + Node temp = node; + for(int i=0; inext; + } + return current->data; +} +``` + +### C +```c +int GetNth(struct node* head, int index) { + struct node* current = head; + for (int i = 0; i < index; i++) { + current = current->next; + } + return current->data; +} +``` diff --git a/solutions/gfg-solutions/Basic/0051.md b/solutions/gfg-solutions/Basic/0051.md new file mode 100644 index 0000000..8d2e74e --- /dev/null +++ b/solutions/gfg-solutions/Basic/0051.md @@ -0,0 +1,171 @@ +--- +id: uncommon-characters +title: Uncommon Characters +sidebar_label: 0051 Uncommon Characters +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to find uncommon characters between two strings in various programming languages." +--- + +## Problem + +Given two strings A and B consisting of lowercase english characters. Find the characters that are not common in the two strings. + +**Note:** Return the string in sorted order. + +### Examples: +**Example 1:** +``` +Input: +A = geeksforgeeks +B = geeksquiz +Output: fioqruz +Explanation: +The characters 'f', 'i', 'o', 'q', 'r', 'u','z' are either present in A or B, but not in both. +``` + +**Example 2:** +``` +Input: +A = characters +B = alphabets +Output: bclpr +Explanation: The characters 'b','c','l','p','r' are either present in A or B, but not in both. +``` + +### Your task: + +You dont need to read input or print anything. Complete the function **UncommonChars()** which takes strings A and B as input parameters and returns a string that contains all the uncommon characters in sorted order. If no such character exists return "-1". + +- **Expected Time Complexity:** $O(M+N)$, where M and N are the sizes of A and B respectively. +- **Expected Auxiliary Space:** $O(M+N)$ + +### Constraints: + +- $1<=M,N<=10^4$ + +String may contain duplicate characters. + +## Solution +### Python +```python +def UncommonChars(self, A, B): + count_A = Counter(A) + count_B = Counter(B) + uncommon_chars = [ + for char in count_A: + if char not in count_B: + uncommon_chars.append(char) + for char in count_B: + if char not in count_A: + uncommon_chars.append(char) + uncommon_chars.sort() + if not uncommon_chars: + return "-1" + else: + return ''.join(uncommon_chars) +``` + +### Java +```java +String UncommonChars(String A, String B) { + Set setA = new HashSet<>(); + Set setB = new HashSet<>(); + for (char ch : A.toCharArray()) { + setA.add(ch); + } + for (char ch : B.toCharArray()) { + setB.add(ch); + Set uniqueChars = new HashSet<>(); + for (char ch : setA) { + if (!setB.contains(ch)) { + uniqueChars.add(ch); + } + } + for (char ch : setB) { + if (!setA.contains(ch)) { + uniqueChars.add(ch); + } + } + List sortedList = new ArrayList<>(uniqueChars); + Collections.sort(sortedList); + StringBuilder builder = new StringBuilder(); + for (char ch : sortedList) { + builder.append(ch); + } + String result = builder.toString(); + if (result.isEmpty()) { + return "-1"; + } + return result; +} +``` + +### C++ +```cpp +string UncommonChars(string A, string B) { + unordered_set setA; + unordered_set setB; + for (char ch : A) { + setA.insert(ch); + for (char ch : B) { + setB.insert(ch); + } + unordered_set uniqueChars; + for (char ch : setA) { + if (setB.find(ch) == setB.end()) { + uniqueChars.insert(ch); + } + } + for (char ch : setB) { + if (setA.find(ch) == setA.end()) { + uniqueChars.insert(ch); + } + } + vector sortedList(uniqueChars.begin(), uniqueChars.end()); + sort(sortedList.begin(), sortedList.end()); + string result(sortedList.begin(), sortedList.end()); + if (result.empty()) { + return "-1"; + } + return result; +} +``` + +### C +```c +char* UncommonChars(const char* A, const char* B) { + int map[26] = {0}; + for (int i = 0; A[i] != '\0'; ++i) { + map[A[i] - 'a'] = 1; + } + for (int i = 0; B[i] != '\0'; ++i) { + if (map[B[i] - 'a'] == 1 || map[B[i] - 'a'] == -1) { + map[B[i] - 'a'] = -1; + } else { + map[B[i] - 'a'] = 2; + } + } + char* result = (char*)malloc(27 * sizeof(char)); + int index = 0; + for (int i = 0; i < 26; ++i) { + if (map[i] > 0) { + result[index++] = 'a' + i; + } + } + result[index] = '\0'; + if (index == 0) { + free(result); + result = (char*)malloc(3 * sizeof(char)); + strcpy(result, "-1"); + } + return result; +} +``` + +- **Time Complexity:** $O(M+N)$ +- **Auxiliary Space:** $O(M+N)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0052.md b/solutions/gfg-solutions/Basic/0052.md new file mode 100644 index 0000000..ca3152a --- /dev/null +++ b/solutions/gfg-solutions/Basic/0052.md @@ -0,0 +1,117 @@ +--- +id: search-node-bst +title: Search a Node in BST +sidebar_label: 0052 Search a Node in BST +tags: +- Binary Search Tree +- Python +- Java +- C++ +- C +description: "This document covers methods to search for a node in a Binary Search Tree (BST) in various programming languages." +--- + +## Problem + +Given a **Binary Search Tree** and a node value X, find if the node with value X is present in the BST or not. + +### Examples: +**Example 1:** +``` +Input: + 2 + \ + 81 + / \ + 42 87 + \ \ + 66 90 + / + 45 +X = 87 +Output: 1 +Explanation: As 87 is present in the given nodes , so the output will be 1. +``` + +**Example 2:** +``` +Input: + 6 + \ + 8 + / \ + 7 9 +X = 11 +Output: 0 +Explanation: As 11 is not present in the given nodes , so the output will be 0. +``` + +### Your task: + +You don't need to read input or print anything. Complete the function **search()** which returns true if the node with value x is present in the BSTelse returns false. + +- **Expected Time Complexity:** $O$(Height of the BST) +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=$Number of Nodes$<=10^5$ + +## Solution +### Python +```python +def search(self, node, x): + if node is None: + return False + if x == node.data: + return True + elif x < node.data: + return self.search(node.left, x) + else: + return self.search(node.right, x) +``` + +### Java +```java +boolean search(Node root, int x) { + if (root == null) + return false; + if (x == root.data) + return true; + else if (x < root.data) + return search(root.left, x); + else + return search(root.right, x); +} +``` + +### C++ +```cpp +bool search(Node* root, int x) { + if (root == nullptr) + return false; + if (x == root->data) + return true; + else if (x < root->data) + return search(root->left, x); + else + return search(root->right, x); +} +``` + +### C +```c +bool search(struct Node* root, int x) { + if (root == NULL) + return false; + if (x == root->data) + return true; + else if (x < root->data) + return search(root->left, x); + else + return search(root->right, x); +} +``` + +- **Time Complexity:** $O$(Height of the BST) +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0053.md b/solutions/gfg-solutions/Basic/0053.md new file mode 100644 index 0000000..19cc7c9 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0053.md @@ -0,0 +1,87 @@ +--- +id: product-of-array-elements +title: Product of Array Elements +sidebar_label: 0053 Product of Array Elements +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate the product of all elements in an array in various programming languages." +--- + +## Problem + +This is a functional problem. Your task is to return the product of array elements under a given modulo. + +The **modulo operation** finds the remainder after the division of one number by another. For example, K(mod(m))=K%m= remainder obtained when K is divided by m + +### Examples: +**Example 1:** +``` +Input: +1 +4 +1 2 3 4 + +Output: +24 +``` + +### Input: + +The first line of input contains T denoting the number of test cases. Then each of the T lines contains a single positive integer N denotes the number of elements in the array. The next line contains 'N' integer elements of the array. + +### Output: +Return the product of array elements under a given modulo. +That is, return (Array[0]*Array[1]*Array[2]...*Array[n])%modulo. + +### Constraints: + +- $1<=T<=200$ +- $1<=N<=10^5$ +- $1<=ar[i]<=10^5$ + +## Solution +### Python +```python +def product(arr,n,mod): + product_result = 1 + for n in arr: + product_result = (product_result * n) % mod + return product_result +``` + +### Java +```java +public static Long product(Long arr[], Long mod, int n) { + long productResult = 1; + for (int i = 0; i < n; i++) { + productResult = (productResult * arr[i]) % mod; + } + return productResult; +} +``` + +### C++ +```cpp +long long int product(int ar[], int n, long long int mod) { + long long int productResult = 1; + for (int i = 0; i < n; i++) { + productResult = (productResult * ar[i]) % mod; + } + return productResult; +} +``` + +### C +```c +long long int product(int ar[], int n, long long int mod) { + long long int productResult = 1; + for (int i = 0; i < n; i++) { + productResult = (productResult * ar[i]) % mod; + } + return productResult; +} +``` diff --git a/solutions/gfg-solutions/Basic/0054.md b/solutions/gfg-solutions/Basic/0054.md new file mode 100644 index 0000000..d61b758 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0054.md @@ -0,0 +1,125 @@ +--- +id: remove-consecutive-characters +title: Remove Consecutive Characters +sidebar_label: 0054 Remove Consecutive Characters +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to remove consecutive duplicate characters from a string in various programming languages." +--- + +## Problem + +Given a string S. For each index `i(1<=i<=N-1)`, erase it if s[i] is equal to s[i-1] in the string. + +### Examples: +**Example 1:** +``` +Input: +S = aabb +Output: ab +Explanation: 'a' at 2nd position is appearing 2nd time consecutively. Similiar explanation for b at 4th position. +``` + +**Example 2:** +``` +Input: +S = aabaa +Output: aba +Explanation: 'a' at 2nd position is appearing 2nd time consecutively. 'a' at fifth position is appearing 2nd time consecutively. +``` + +### Your task: + +You dont need to read input or print anything. Complete the function **removeConsecutiveCharacter()** which accepts a string as input parameter and returns modified string. + +- **Expected Time Complexity:** $O(|S|)$ +- **Expected Auxiliary Space:** $O(|S|)$ + +### Constraints: + +- $1<=|S|<=10^5$ + +All characters are lowercase alphabets. + +## Solution +### Python +```python +def removeConsecutiveCharacter(self, S): + if len(S) == 0: + return "" + result = [] + result.append(S[0]) + for i in range(1, len(S)): + if S[i] != S[i - 1]: + result.append(S[i]) + return ''.join(result) +``` + +### Java +```java +public String removeConsecutiveCharacter(String S){ + if (S == null || S.length() == 0) { + return ""; + } + StringBuilder result = new StringBuilder(); + result.append(S.charAt(0)); + for (int i = 1; i < S.length(); i++) { + char currentChar = S.charAt(i); + char previousChar = result.charAt(result.length() - 1); + if (currentChar != previousChar) { + result.append(currentChar); + } + } + return result.toString(); +} +``` + +### C++ +```cpp +string removeConsecutiveCharacter(string S) { + if (S.empty()) { + return ""; + } + string result; + result.push_back(S[0]); + for (int i = 1; i < S.length(); i++) { + if (S[i] != result.back()) { + result.push_back(S[i]); + } + } + return result; +} +``` + +### C +```c +char* removeConsecutiveCharacter(const char* S) { + if (S == NULL || strlen(S) == 0) { + char* result = (char*) malloc(sizeof(char)); + result[0] = '\0'; + return result; + } + int len = strlen(S); + char* result = (char*) malloc((len + 1) * sizeof(char)); + if (result == NULL) { + return NULL; + } + int resultIndex = 0; + result[resultIndex++] = S[0]; + for (int i = 1; i < len; i++) { + if (S[i] != result[resultIndex - 1]) { + result[resultIndex++] = S[i]; + } + } + result[resultIndex] = '\0'; + return result; +} + +``` + +- **Time Complexity:** $O(|S|)$ +- **Auxiliary Space:** $O(|S|)$ diff --git a/solutions/gfg-solutions/Basic/0055.md b/solutions/gfg-solutions/Basic/0055.md new file mode 100644 index 0000000..2a17815 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0055.md @@ -0,0 +1,167 @@ +--- +id: middle-of-three +title: Middle of Three +sidebar_label: 0055 Middle of Three +tags: +- Algorithm +- Python +- Java +- C++ +- C +description: "This document covers methods to find the middle of three given numbers in various programming languages." +--- + +## Problem + +Given three distinct numbers A, B and C. Find the number with value in middle (Try to do it with minimum comparisons). + +### Examples: +**Example 1:** +``` +Input: +A = 978, B = 518, C = 300 +Output: +518 +Explanation: +Since 518>300 and 518<978, so 518 is the middle element. +``` + +**Example 2:** +``` +Input: +A = 162, B = 934, C = 200 +Output: +200 +Exaplanation: +Since 200>162 && 200<934, So, 200 is the middle element. +``` + +### Your task: + +You don't need to read input or print anything.Your task is to complete the function ***middle()*** which takes three integers A,B and C as input parameters and returns the number which has middle value. + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=A,B,C<=10^9$ + +A,B,C are distinct. + +## Solution +### Python +```python +def middle(self,A,B,C): + if A > B: + if A > C: + if B > C: + return B + else: + return C + else: + return A + else: + if B > C: + if A > C: + return A + else: + return C + else: + return B +``` + +### Java +```java +int middle(int A, int B, int C){ + if (A > B) { + if (A > C) { + if (B > C) { + return B; + } else { + return C; + } + } else { + return A; + } + } + else { + if (B > C) { + if (A > C) {e + return A; + } + else { + return C; + } + } + else { + return B; + } + } +} +``` + +### C++ +```cpp +int middle(int A, int B, int C){ + if (A > B) { + if (A > C) { + if (B > C) { + return B; + } else { + return C; + } + } + else { + return A; + } + } + else { + if (B > C) { + if (A > C) { + return A; + } + else { + return C; + } + } + else { + return B; + } + } +} +``` + +### C +```c +int middle(int A, int B, int C){ + if (A > B) { + if (A > C) { + if (B > C) { + return B; + } else { + return C; + } + } + else { + return A; + } + } + else { + if (B > C) { + if (A > C) { + return A; + } + else { + return C; + } + } + else { + return B; + } + } +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0056.md b/solutions/gfg-solutions/Basic/0056.md new file mode 100644 index 0000000..585a868 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0056.md @@ -0,0 +1,118 @@ +--- +id: replace-zeros-with-fives +title: Replace All 0's with 5 +sidebar_label: 0056 Replace All 0's with 5 +tags: +- Python +- Java +- C++ +- C +description: "This document covers methods to replace all occurrences of 0 with 5 in a given number in various programming languages." +--- + +## Problem + +You are given an integer N. You need to convert all zeroes of N to 5. + +### Examples: +**Example 1:** +``` +Input: +N = 1004 +Output: 1554 +Explanation: There are two zeroes in 1004 on replacing all zeroes with "5", the new number will be "1554". +``` + +**Example 2:** +``` +Input: +N = 121 +Output: 121 +Explanation: Since there are no zeroes in "121", the number remains as "121". +``` + +### Your task: + +Your task is to complete the function **convertFive()** which takes an integer N as an argument and replaces all zeros in the number N with 5. Your function should return the converted number. + +- **Expected Time Complexity:** $O(K)$, where K is the number of digits in N +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= n <= 10000$ + +## Solution +### Python +```python +def convertFive(n): + n_str = str(n) + modified_digits = [] + for char in n_str: + if char == '0': + modified_digits.append('5') + else: + modified_digits.append(char) + modified_str = ''.join(modified_digits) + modified_n = int(modified_str) + return modified_n +``` + +### Java +```java +int convertfive(int num) { + String numStr = String.valueOf(num); + StringBuilder modifiedDigits = new StringBuilder(); + for (int i = 0; i < numStr.length(); i++) { + char ch = numStr.charAt(i); + if (ch == '0') { + modifiedDigits.append('5'); + } else { + modifiedDigits.append(ch); + } + } + int modifiednum = Integer.parseInt(modifiedDigits.toString()); + return modifiednum; +} +``` + +### C++ +```cpp +int convertFive(int n) { + string nStr = to_string(n); + string modifiedStr = ""; + for (char ch : nStr) { + if (ch == '0') { + modifiedStr += '5'; + } else { + modifiedStr += ch; + } + } + int modifiedN = stoi(modifiedStr); + return modifiedN; +} +``` + +### C +```c +int convertFive(int num) { + if (num == 0) { + return 5; + } + int result = 0; + int decimalPlace = 1; + while (num > 0) { + int digit = num % 10; + if (digit == 0) { + digit = 5; + } + result = digit * decimalPlace + result; + decimalPlace *= 10; + num /= 10; + } + return result; +} +``` + +- **Time Complexity:** $O(K)$, where K is the number of digits in N +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0057.md b/solutions/gfg-solutions/Basic/0057.md new file mode 100644 index 0000000..08f95ab --- /dev/null +++ b/solutions/gfg-solutions/Basic/0057.md @@ -0,0 +1,167 @@ +--- +id: doubly-linked-list-insertion +title: Doubly Linked List Insertion at Given Position +sidebar_label: 0057 Doubly Linked List Insertion at Given Position +tags: +- Linked List +- Python +- Java +- C++ +- C +description: "This document covers methods to insert a node at a given position in a doubly linked list in various programming languages." +--- + +## Problem + +Given a doubly-linked list, a position p, and an integer x. The task is to add a new node with value x at the position just after pth node in the doubly linked list. + +### Examples: +**Example 1:** +``` +Input: +LinkedList: 2<->4<->5 +p = 2, x = 6 +Output: 2 4 5 6 +Explanation: p = 2, and x = 6. So, 6 is inserted after p, i.e, at position 3 (0-based indexing). +``` + +**Example 2:** +``` +Input: +LinkedList: 1<->2<->3<->4 +p = 0, x = 44 +Output: 1 44 2 3 4 +Explanation: p = 0, and x = 44 . So, 44 is inserted after p, i.e, at position 1 (0-based indexing). +``` + +### Your task: + +The task is to complete the function **addNode()** which head reference, position and data to be inserted as the arguments, with no return type. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^4$ +- $0 <= p < N$ + +## Solution +### Python +```python +def addNode(head, p, data): + new_node = Node(data) + if head is None: + head = new_node + else: + temp = head + count = 0 + while temp.next is not None and count < p: + temp = temp.next + count += 1 + if temp.next is None: + temp.next = new_node + new_node.prev = temp + else: + new_node.next = temp.next + new_node.prev = temp + temp.next = new_node + if new_node.next is not None: + new_node.next.prev = new_node +``` + +### Java +```java +void addNode(Node head_ref, int pos, int data) { + Node new_node = new Node(data); + if (head_ref == null) { + head_ref = new_node; + } + else { + Node temp = head_ref; + int count = 0; + while (temp.next != null && count < pos) { + temp = temp.next; + count++; + } + if (temp.next == null) { + temp.next = new_node; + new_node.prev = temp; + } + else { + new_node.next = temp.next; + new_node.prev = temp; + temp.next = new_node; + if (new_node.next != null) { + new_node.next.prev = new_node; + } + } + } +} +``` + +### C++ +```cpp +void addNode(Node *head, int pos, int data) { + Node* new_node = new Node(data); + if (head == nullptr) { + head = new_node; + } + else { + Node* temp = head; + int count = 0; + while (temp->next != nullptr && count < pos) { + temp = temp->next; + count++; + } + if (temp->next == nullptr) { + temp->next = new_node; + new_node->prev = temp; + } + else { + new_node->next = temp->next; + new_node->prev = temp; + temp->next = new_node; + if (new_node->next != nullptr) { + new_node->next->prev = new_node; + } + } + } +} +``` + +### C +```c +void addNode(struct Node *head, int pos, int data) { + struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); + new_node->data = data; + new_node->prev = NULL; + new_node->next = NULL; + if (head == NULL) { + head = new_node; + } + else { + struct Node* temp = head; + int count = 0; + while (temp->next != NULL && count < pos) { + temp = temp->next; + count++; + } + if (temp->next == NULL) { + temp->next = new_node; + new_node->prev = temp; + } + else { + new_node->next = temp->next; + new_node->prev = temp; + temp->next = new_node; + if (new_node->next != NULL) { + new_node->next->prev = new_node; + } + } + } +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0058.md b/solutions/gfg-solutions/Basic/0058.md new file mode 100644 index 0000000..57829c2 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0058.md @@ -0,0 +1,119 @@ +--- +id: repeated-character +title: Repeated Character +sidebar_label: 0058 Repeated Character +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to find the first repeated character in a string in various programming languages." +--- + +## Problem + +Given a string consisting of lowercase english alphabets. Find the repeated character present first in the string. + +**NOTE:** If there are no repeating characters return '#'. + +### Examples: +**Example 1:** +``` +Input: +S = "geeksforgeeks" +Output: g +Explanation: g, e, k and s are the repeating characters. Out of these, g occurs first. +``` + +**Example 2:** +``` +Input: +S = "abcde" +Output: -1 +Explanation: No repeating character present. (You need to return '#') +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **firstRep()** which takes the string S as input and returns the the first repeating character in the string. In case there's no repeating character present, return '#'. + +- **Expected Time Complexity:** $O(|S|)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=|S|<=10^5$ + +## Solution +### Python +```python +def firstRep(self, s): + char_count = {} + for index, char in enumerate(s): + if char in char_count: + char_count[char]['count'] += 1 + else: + char_count[char] = {'count': 1, 'index': index} + first_repeated = '#' + min_index = float('inf') + for char in s: + if char_count[char]['count'] > 1 and char_count[char]['index'] < min_index: + first_repeated = char + min_index = char_count[char]['index'] + return first_repeated +``` + +### Java +```java +char firstRep(String S) { + char []str=S.toCharArray(); + for(int i=0;im; + for(char c:s) { + m[c]++; + } + for(char c:s) { + if(m[c]>1) { + return c; + } + } + return '#'; +} +``` + +### C +```c +char firstRep(const char *s) { + Entry hashmap[256] = {0}; + int len = strlen(s); + for (int i = 0; i < len; i++) { + hashmap[s[i]].key = s[i]; + hashmap[s[i]].count++; + } + for (int i = 0; i < len; i++) { + if (hashmap[s[i]].count > 1) { + return s[i]; + } + } + return '#'; / +} +``` + +- **Time Complexity:** $O(|S|)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0059.md b/solutions/gfg-solutions/Basic/0059.md new file mode 100644 index 0000000..79f4879 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0059.md @@ -0,0 +1,90 @@ +--- +id: exceptionally-odd +title: Exceptionally Odd +sidebar_label: 0059 Exceptionally Odd +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to find the element that occurs an odd number of times in an array in various programming languages." +--- + +## Problem + +Given an array of N positive integers where all numbers occur even number of times except one number which occurs odd number of times. Find the exceptional number. + +### Examples: +**Example 1:** +``` +Input: +N = 7 +Arr[] = {1, 2, 3, 2, 3, 1, 3} +Output: 3 +Explaination: 3 occurs three times. +``` + +**Example 2:** +``` +Input: +N = 7 +Arr[] = {5, 7, 2, 7, 5, 2, 5} +Output: 5 +Explaination: 5 occurs three times. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **getOddOccurrence()** which takes **arr[]** and **n** as input parameters and returns the exceptional number. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1<=arr[i]<=10^6$ + +## Solution +### Python +```python +def getOddOccurrence(self, arr, n): + result = 0 + for num in arr: + result ^= num + return result +``` + +### Java +```java +int getOddOccurrence(int[] arr, int n) { + int result = 0; + for(int i = 0; i4->3 +Output: +Odd +Explanation: +The length of linked list is 3 which is odd. +``` + +**Example 2:** +``` +Input: +n = 6 +linked list = 12->52->10->47->95->0 +Output: +Even +Explanation: +The length of linked list is 6 which is even. +``` + +### Your task: + +Since this is a functional problem you don't have to worry about input, you just have to complete the function **isLengthEvenOrOdd()** which takes the head of the linked list as the input parameter and returns 0 if the length of the linked list is even otherwise returns 1. + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= n <= 10^4$ +- $1 <=$ elements of the linked list $<= 10^3$ + +## Solution +### Python +```python +def isLengthEvenOrOdd(head): + count = 0 + temp = head + while temp is not None: + count+=1 + temp = temp.next + if count%2==0: + return 0 + else: + return 1 +``` + +### Java +```java +public int isLengthEvenOrOdd(Node head) { + int count = 0; + Node temp = head; + while(temp!=null) { + count+=1; + temp = temp.next; + } + if(count%2==0) + return 0; + else + return 1; +} +``` + +### C++ +```cpp +int isLengthEvenOrOdd(struct Node* head) { + int count = 0; + Node* temp = head; + while(temp!=nullptr) { + count+=1; + temp = temp->next; + } + if(count%2==0) + return 0; + else + return 1; +} +``` + +### C +```c +int isLengthEvenOrOdd(struct Node* head) { + int count = 0; + struct Node* temp = head; + while (temp != NULL) { + count += 1; + temp = temp->next; + } + if (count % 2 == 0) + return 0; + else + return 1; +} +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0063.md b/solutions/gfg-solutions/Basic/0063.md new file mode 100644 index 0000000..184727f --- /dev/null +++ b/solutions/gfg-solutions/Basic/0063.md @@ -0,0 +1,121 @@ +--- +id: find-position-of-set-bit +title: Find Position of Set Bit +sidebar_label: 0063 Find Position of Set Bit +tags: +- Bit Manipulation +- Python +- Java +- C++ +- C +description: "This document covers methods to find the position of the set bit in a number in various programming languages." +--- + +## Problem + +Given a number N having only one β€˜1’ and all other ’0’s in its binary representation, find position of the only set bit. If there are 0 or more than 1 set bit the answer should be -1. Position of set bit '1' should be counted starting with 1 from LSB side in binary representation of the number. + +### Examples: +**Example 1:** +``` +Input: +N = 2 +Output: +2 +Explanation: +2 is represented as "10" in Binary. As we see there's only one set bit and it's in Position 2 and thus the +Output 2. +``` + +**Example 2:** +``` +Input: +N = 5 +Output: +-1 +Explanation: +5 is represented as "101" in Binary. As we see there's two set bits and thus the Output -1. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **findPosition()** which takes an integer N as input and returns the answer. + +- **Expected Time Complexity:** $O(log(N))$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $0 <= N <= 10^8$ + +## Solution +### Python +```python +def findPosition(self, N): + if N == 0 or (N & (N - 1)) != 0: + return -1 + position = 1 + while N: + if N & 1: + return position + N >>= 1 + position += 1 + return -1 +``` + +### Java +```java +static int findPosition(int N) { + if (N == 0 || (N & (N - 1)) != 0) { + return -1; + } + int position = 1; + while (N != 0) { + if ((N & 1) != 0) { + return position; + } + N >>= 1; + position++; + } + return -1; +} +``` + +### C++ +```cpp +int findPosition(int N) { + if (N == 0 || (N & (N - 1)) != 0) { + return -1; + } + int position = 1; + while (N != 0) { + if ((N & 1) != 0) { + return position; + } + N >>= 1; + position++; + } + return -1; +} +``` + +### C +```c +int findPosition(int N) { + if (N == 0 || (N & (N - 1)) != 0) { + return -1; + } + int position = 1; + while (N != 0) { + if ((N & 1) != 0) { + return position; + } + N >>= 1; + position++; + } + return -1; +} +``` + +- **Time Complexity:** $O(log(N))$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0064.md b/solutions/gfg-solutions/Basic/0064.md new file mode 100644 index 0000000..0465524 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0064.md @@ -0,0 +1,174 @@ +--- +id: remove-common-characters-concatenate +title: Remove Common Characters and Concatenate +sidebar_label: 0064 Remove Common Characters and Concatenate +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to remove common characters from two strings and concatenate the remaining characters in various programming languages." +--- + +## Problem + +Given two strings s1 and s2. Modify both the strings such that all the common characters of s1 and s2 are to be removed and the uncommon characters of s1 and s2 are to be concatenated. + +**Note:** If all characters are removed print -1. + +### Examples: +**Example 1:** +``` +Input: +s1 = aacdb +s2 = gafd +Output: cbgf +Explanation: The common characters of s1 and s2 are: a, d. The uncommon characters of s1 and s2 are c, b, g and f. Thus the modified string with uncommon characters concatenated is cbgf. +``` + +**Example 2:** +``` +Input: +s1 = abcs +s2 = cxzca +Output: bsxz +Explanation: The common characters of s1 and s2 are: a,c. The uncommon characters of s1 and s2 are b,s,x and z. Thus the modified string with uncommon characters concatenated is bsxz. +``` + +### Your task: + +The task is to complete the function **concatenatedString()** which removes the common characters, concatenates, and returns the string. If all characters are removed then return -1. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O$(Number of distinct characters) + +**Note:** N = |Length of Strings| + +### Constraints: + +- $1<=$|Length of Strings|$<=10^4$ + +## Solution +### Python +```python +def concatenatedString(self,s1,s2): + freq_s1 = {} + freq_s2 = {} + for char in s1: + freq_s1[char] = freq_s1.get(char, 0) + 1 + for char in s2: + freq_s2[char] = freq_s2.get(char, 0) + 1 + result = [] + for char in s1: + if char not in freq_s2: + result.append(char) + for char in s2: + if char not in freq_s1: + result.append(char) + if len(result) == 0: + return "-1" + else: + return "".join(result) +``` + +### Java +```java +public static String concatenatedString(String s1,String s2) { + Map freq_s1 = new HashMap<>(); + Map freq_s2 = new HashMap<>(); + for (char ch : s1.toCharArray()) { + freq_s1.put(ch, freq_s1.getOrDefault(ch, 0) + 1); + } + for (char ch : s2.toCharArray()) { + freq_s2.put(ch, freq_s2.getOrDefault(ch, 0) + 1); + } + StringBuilder result = new StringBuilder(); + for (char ch : s1.toCharArray()) { + if (!freq_s2.containsKey(ch)) { + result.append(ch); + } + } + for (char ch : s2.toCharArray()) { + if (!freq_s1.containsKey(ch)) { + result.append(ch); + } + } + if (result.length() == 0) { + return "-1"; + } + else { + return result.toString(); + } +} +``` + +### C++ +```cpp +string concatenatedString(string s1, string s2) { + unordered_map freq_s1; + unordered_map freq_s2; + for (char ch : s1) { + freq_s1[ch]++; + } + for (char ch : s2) { + freq_s2[ch]++; + } + string result; + for (char ch : s1) { + if (freq_s2.find(ch) == freq_s2.end()) { + result += ch; + } + } + for (char ch : s2) { + if (freq_s1.find(ch) == freq_s1.end()) { + result += ch; + } + } + if (result.empty()) { + return "-1"; + } + else { + return result; + } +} +``` + +### C +```c +char* concatenatedString(const char* s1, const char* s2) { + Entry freq_s1[256] = {0}; + Entry freq_s2[256] = {0}; + int len1 = strlen(s1); + int len2 = strlen(s2); + for (int i = 0; i < len1; i++) { + freq_s1[s1[i]].key = s1[i]; + freq_s1[s1[i]].count++; + } + for (int i = 0; i < len2; i++) { + freq_s2[s2[i]].key = s2[i]; + freq_s2[s2[i]].count++; + } + + char* result = (char*)malloc((len1 + len2 + 1) * sizeof(char)); + int idx = 0; + for (int i = 0; i < len1; i++) { + if (freq_s2[s1[i]].count == 0) { + result[idx++] = s1[i]; + } + } + for (int i = 0; i < len2; i++) { + if (freq_s1[s2[i]].count == 0) { + result[idx++] = s2[i]; + } + } + result[idx] = '\0'; + if (idx == 0) { + strcpy(result, "-1"); + } + return result; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O$(Number of distinct characters) \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0065.md b/solutions/gfg-solutions/Basic/0065.md new file mode 100644 index 0000000..242fd3b --- /dev/null +++ b/solutions/gfg-solutions/Basic/0065.md @@ -0,0 +1,101 @@ +--- +id: pattern-1 +title: Pattern 1 +sidebar_label: 0065 Pattern 1 +tags: +- Patterns +- Python +- Java +- C++ +- C +description: "This document covers methods to print square pattern in various programming languages." +--- + +## Problem + +Geek is very fond of patterns. Once, his teacher gave him a square pattern to solve. He gave Geek an integer n and asked him to build a pattern. + +Help Geek to build a square pattern with the help of * such that each * is space-separated in each line. + +### Examples: +**Example 1:** +``` +Input: +n = 3 +Output: +* * * +* * * +* * * +``` + +**Example 2:** +``` +Input: +n = 5 +Output: +* * * * * +* * * * * +* * * * * +* * * * * +* * * * * +``` + +### Your task: + +You don't need to input anything. Complete the function **printSquare()** which takes an integer n as the input parameter and print the pattern. + +- **Expected Time Complexity:** $O(N^2)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<= n <= 1000$ + +## Solution +### Python +```python +def printSquare(self, N): + for i in range(N): + for j in range(N): + print("* ", end="") + print() +``` + +### Java +```java +void printSquare(int n) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + System.out.print("* "); + } + System.out.println(); + } +} +``` + +### C++ +```cpp +void printSquare(int n) { + for(int i = 0; i < n; i++) { + for(int j = 0; j < n; j++) { + cout << "* "; + } + cout << endl; + } +} +``` + +### C +```c +void printSquare(int n) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + printf("* "); + } + printf("\n"); + } +} +``` + +- **Time Complexity:** $O(N^2)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0066.md b/solutions/gfg-solutions/Basic/0066.md new file mode 100644 index 0000000..8b0e574 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0066.md @@ -0,0 +1,124 @@ +--- +id: anagram-of-string +title: Anagram of String +sidebar_label: 0066 Anagram of String +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to check if two strings are anagrams of each other in various programming languages." +--- + +## Problem + +Given two strings S1 and S2 in lowercase, the task is to make them anagram. The only allowed operation is to remove a character from any string. Find the minimum number of characters to be deleted to make both the strings anagram. Two strings are called anagram of each other if one of them can be converted into another by rearranging its letters. + +### Examples: +**Example 1:** +``` +Input: +S1 = bcadeh +S2 = hea +Output: 3 +Explanation: We need to remove b, c and d from S1. +``` + +**Example 2:** +``` +Input: +S1 = cddgk +S2 = gcd +Output: 2 +Explanation: We need to remove d and k from S1. +``` + +### Your task: + +Complete the function **remAnagram()** which takes two strings S1, S2 as input parameter, and returns minimum characters needs to be deleted. + +- **Expected Time Complexity:** $O(max(|S1|, |S2|))$, where |S| = length of string S +- **Expected Auxiliary Space:** $O(26)$ + +### Constraints: + +- $1 <= |S1|, |S2| <= 10^5$ + +## Solution +### Python +```python +def remAnagram(str1,str2): + CHARS = 26 + count1 = [0]*CHARS + count2 = [0]*CHARS + i = 0 + while i < len(str1): + count1[ord(str1[i])-ord('a')] += 1 + i += 1 + i =0 + while i < len(str2): + count2[ord(str2[i])-ord('a')] += 1 + i += 1 + result = 0 + for i in range(26): + result += abs(count1[i] - count2[i]) + return result +``` + +### Java +```java +public int remAnagrams(String s,String s1) { + int count1[] = new int[26]; + int count2[] = new int[26]; + for (int i = 0; i < s.length() ; i++) + count1[s.charAt(i) -'a']++; + for (int i = 0; i < s1.length() ; i++) + count2[s1.charAt(i) -'a']++; + int result = 0; + for (int i = 0; i < 26; i++) + result += Math.abs(count1[i] - count2[i]); + return result; +} +``` + +### C++ +```cpp +int remAnagram(string str1, string str2) { + int count1[26] = {0}; + int count2[26] = {0}; + for (char c : str1) { + count1[c - 'a']++; + } + for (char c : str2) { + count2[c - 'a']++; + } + int result = 0; + for (int i = 0; i < 26; i++) { + result += abs(count1[i] - count2[i]); + } + return result; +} +``` + +### C +```c +int remAnagram(const char* str1, const char* str2) { + int count1[26] = {0}; + int count2[26] = {0}; + for (int i = 0; str1[i] != '\0'; i++) { + count1[str1[i] - 'a']++; + } + for (int i = 0; str2[i] != '\0'; i++) { + count2[str2[i] - 'a']++; + } + int result = 0; + for (int i = 0; i < 26; i++) { + result += abs(count1[i] - count2[i]); + } + return result; +} +``` + +- **Time Complexity:** $O(max(|S1|, |S2|))$ +- **Auxiliary Space:** $O(26)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0067.md b/solutions/gfg-solutions/Basic/0067.md new file mode 100644 index 0000000..2e24264 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0067.md @@ -0,0 +1,116 @@ +--- +id: number-sparse-or-not +title: Number is Sparse or Not +sidebar_label: 0067 Number is Sparse or Not +tags: +- Bit Manipulation +- Python +- Java +- C++ +- C +description: "This document covers methods to determine if a number is sparse or not in various programming languages." +--- + +## Problem + +Given a number N. The task is to check whether it is sparse or not. A number is said to be a sparse number if no two or more consecutive bits are set in the binary representation. + +### Examples: +**Example 1:** +``` +Input: N = 2 +Output: 1 +Explanation: Binary Representation of 2 is 10, which is not having consecutive set bits. So, it is sparse number. +``` + +**Example 2:** +``` +Input: N = 3 +Output: 0 +Explanation: Binary Representation of 3 is 11, which is having consecutive set bits in it. So, it is not a sparse number. +``` + +### Your task: + +The task is to complete the function **checkSparse()** that takes n as a parameter and returns 1 if the number is sparse else returns 0. + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^6$ + +## Solution +### Python +```python +def isSparse(self,n): + if (n == 1): + return True + global prev + while(n > 0): + prev = n & 1 + n = n >> 1 + curr = n & 1 + if(prev == curr and prev == 1): + return False + prev = curr + return True +``` + +### Java +```java +public static boolean isSparse(int n) { + int prev; + if (n == 1) + return true; + while (n > 0) { + prev = n & 1; + n = n >> 1; + int curr = n & 1; + if (prev == curr && prev == 1) + return false; + prev = curr; + } + return true; +} +``` + +### C++ +```cpp +bool isSparse(int n) { + int prev; + if (n == 1) + return true; + while (n > 0) { + prev = n & 1; + n = n >> 1; + int curr = n & 1; + if (prev == curr && prev == 1) + return false; + prev = curr; + } + return true; +} +``` + +### C +```c +bool isSparse(int n) { + int prev; + if (n == 1) + return true; + while (n > 0) { + prev = n & 1; + n = n >> 1; + int curr = n & 1; + if (prev == curr && prev == 1) + return false; + prev = curr; + } + return true; +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0068.md b/solutions/gfg-solutions/Basic/0068.md new file mode 100644 index 0000000..29e6082 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0068.md @@ -0,0 +1,111 @@ +--- +id: delete-alternate-nodes +title: Delete Alternate Nodes +sidebar_label: 0068 Delete Alternate Nodes +tags: +- Linked List +- Python +- Java +- C++ +- C +description: "This document covers methods to delete alternate nodes from a linked list in various programming languages." +--- + +## Problem + +Given a Singly Linked List of size n, delete all alternate nodes of the list. + +### Examples: +**Example 1:** +``` +Input: +LinkedList: 1->2->3->4->5->6 +Output: 1->3->5 +Explanation: Deleting alternate nodes results in the linked list with elements 1->3->5. +``` + +**Example 2:** +``` +Input: +LinkedList: 99->59->42->20 +Output: 99->42 +``` + +### Your task: + +Your task is to complete the function **deleteAlt()** which takes the **head** of the linked list in the input parameter and modifies the given linked list accordingly. + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=n<=10^5$ +- $1<=node.data<=10^6$ + +## Solution +### Python +```python +def deleteAlt(self, head): + if (head == None): + return + prev = head + now = head.next + while (prev != None and now != None): + prev.next = now.next + now = None + prev = prev.next + if (prev != None): + now = prev.next +``` + +### Java +```java +public void deleteAlternate (Node head){ + if (head == null) + return; + Node node = head; + while (node != null && node.next != null) { + node.next = node.next.next; + node = node.next; + } +} +``` + +### C++ +```cpp +void deleteAlt(struct Node *head){ + if (head == NULL) + return + Node *prev = head; + Node *node = head->next; + while (prev != NULL && node != NULL) { + prev->next = node->next; + delete(node); + prev = prev->next; + if (prev != NULL) + node = prev->next; + } +} +``` + +### C +```c +void deleteAlt(struct Node *head) { + if (head == NULL) + return; + struct Node *prev = head; + struct Node *node = head->next; + while (prev != NULL && node != NULL) { + prev->next = node->next; + free(node); + prev = prev->next; + if (prev != NULL) + node = prev->next; + } +} + +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0069.md b/solutions/gfg-solutions/Basic/0069.md new file mode 100644 index 0000000..8d16a19 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0069.md @@ -0,0 +1,116 @@ +--- +id: ishaan-loves-chocolates +title: Ishaan Loves Chocolates +sidebar_label: 0069 Ishaan Loves Chocolates +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods for determining the tastiness level of the square which his sister gets in various programming languages." +--- + +## Problem + +As we know, Ishaan has a love for chocolates. He has bought a huge chocolate bar that contains N chocolate squares. Each of the squares has a tastiness level which is denoted by an array A[]. + +Ishaan can eat the first or the last square of the chocolate at once. Ishaan has a sister who loves chocolates too and she demands the last chocolate square. Now, Ishaan being greedy eats the more tasty square first. + +Determine the tastiness level of the square which his sister gets. + +### Examples: +**Example 1:** +``` +Input : arr[ ] = {5, 3, 1, 6, 9} +Output : 1 +Explanation: +Initially: 5 3 1 6 9 +In first step: 5 3 1 6 +In Second step: 5 3 1 +In Third step: 3 1 +In Fourth step: 1 +Return 1 +``` + +**Example 2:** +``` +Input : arr[ ] = {5, 9, 2, 6} +Output : 2 +``` + +### Your task: + +This is a function problem. The input is already taken care of by the driver code. You only need to complete the function **chocolates()** that takes an array (arr), sizeOfArray (n) and return the tastiness level of the square which his sister gets. The driver code takes care of the printing. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1 ≀ A[i] ≀ 10^9$ + +## Solution +### Python +```python +def chocolates(self, n : int, arr : List[int]) -> int: + low = 0 + high = n-1 + while lowarr[high]: + low+=1 + else: + high-=1 + return arr[low] +``` + +### Java +```java +public static int chocolates(int n, int[] arr) { + int low = 0, high = n-1; + while(lowarr[high]) { + low++; + } + else { + high--; + } + } + return arr[low]; +} +``` + +### C++ +```cpp +int chocolates(int n, vector &arr) { + int low = 0, high = n-1; + while(lowarr[high]) { + low++; + } + else { + high--; + } + } + return arr[low]; +} +``` + +### C +```c +int chocolates(int arr[], int l, int r) { + while(larr[r]) { + l++; + } + else { + r--; + } + } + return arr[l]; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0070.md b/solutions/gfg-solutions/Basic/0070.md new file mode 100644 index 0000000..7a0cb30 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0070.md @@ -0,0 +1,100 @@ +--- +id: binary-to-decimal +title: Binary Number to Decimal Number +sidebar_label: 0070 Binary Number to Decimal Number +tags: +- Binary +- Python +- Java +- C++ +- C +description: "This document covers methods to convert a binary number to a decimal number in various programming languages." +--- + +## Problem + +Given a Binary Number B, find its decimal equivalent. + +### Examples: +**Example 1:** +``` +Input: B = 10001000 +Output: 136 +``` + +**Example 2:** +``` +Input: B = 101100 +Output: 44 +``` + +### Your task: + +You don't need to read or print anything. Your task is to complete the function **binary_to_decimal()** which takes the binary number as string input parameter and returns its decimal equivalent. + +- **Expected Time Complexity:** $O(K * Log(K))$, where K is number of bits in binary number. +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <=$ number of bits in binary number $<= 16$ + +## Solution +### Python +```python +def binary_to_decimal(self, str): + num = int(str); + dec_value = 0; + base = 1; + temp = num; + while(temp): + last_digit = temp % 10; + temp = int(temp / 10); + dec_value += last_digit * base; + base = base * 2; + return dec_value; +``` + +### Java +```java +public int binary_to_decimal(String str) { + int decValue = 0; + int base = 1; + for (int i = str.length() - 1; i >= 0; i--) { + if (str.charAt(i) == '1') { + decValue += base; + } + base = base * 2; + } + return decValue; +} +``` + +### C++ +```cpp +int binary_to_decimal(string str) { + unsigned long long num = bitset<64>(str).to_ullong(); + int decValue = static_cast(num); + return decValue; +} +``` + +### C +```c +int binary_to_decimal(char str[]) { + int len = strlen(str); + int dec_value = 0; + int base = 1; + int i; + for (i = len - 1; i >= 0; i--) { + if (str[i] == '1') { + dec_value += base; + } + base *= 2; + } + return dec_value; +} +``` + +- **Time Complexity:** $O(K * Log(K))$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0071.md b/solutions/gfg-solutions/Basic/0071.md new file mode 100644 index 0000000..e571e57 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0071.md @@ -0,0 +1,124 @@ +--- +id: isogram-check +title: Check if a String is Isogram or Not +sidebar_label: 0071 Check if a String is Isogram or Not +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to check if a string is an isogram (a string with no repeating characters) in various programming languages." +--- + +## Problem + +Given a string S of lowercase alphabets, check if it is isogram or not. An Isogram is a string in which no letter occurs more than once. + +### Examples: +**Example 1:** +``` +Input: +S = machine +Output: 1 +Explanation: machine is an isogram as no letter has appeared twice. Hence we print 1. +``` + +**Example 2:** +``` +Input: +S = geeks +Output: 0 +Explanation: geeks is not an isogram as 'e' appears twice. Hence we print 0. +``` + +### Your task: + +This is a function problem. You only need to complete the function **isIsogram()** that takes a string as a parameter and returns either true or false. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O$(Number of distinct characters) + +Note: N = |S| + +### Constraints: + +- $1 <= |s| <= 10^3$ + +## Solution +### Python +```python +def isIsogram(self,s): + length = len(s) + mapHash = [0] * 26 + for i in range(length): + mapHash[ord(s[i]) - ord('a')] += 1 + if (mapHash[ord(s[i]) - ord('a')] > 1): + return False + return True +``` + +### Java +```java +static boolean isIsogram(String data){ + int length = data.length(); + int[] mapHash = new int[26]; + for (int i = 0; i < length; i++) { + char currentChar = data.charAt(i); + if (Character.isLetter(currentChar)) { + currentChar = Character.toLowerCase(currentChar); + mapHash[currentChar - 'a']++; + if (mapHash[currentChar - 'a'] > 1) { + return false; + } + } + } + return true; +} +``` + +### C++ +```cpp +bool isIsogram(string s) { + int length = s.length(); + vector mapHash(26, 0); + for (int i = 0; i < length; i++) { + char currentChar = s[i]; + if (isalpha(currentChar)) { + currentChar = tolower(currentChar); + mapHash[currentChar - 'a']++; + if (mapHash[currentChar - 'a'] > 1) { + return false; + } + } + } + return true; +} +``` + +### C +```c +int isIsogram(const char* s) { + int mapHash[26] = {0}; + int length = 0; + const char* ptr = s; + while (*ptr != '\0') { + length++; + ptr++; + } + for (int i = 0; i < length; i++) { + char currentChar = s[i]; + if (isalpha(currentChar)) { + currentChar = tolower(currentChar); + mapHash[currentChar - 'a']++; + if (mapHash[currentChar - 'a'] > 1) { + return 0; + } + } + } + return 1; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O$(Number of distinct characters) \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0072.md b/solutions/gfg-solutions/Basic/0072.md new file mode 100644 index 0000000..87bf920 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0072.md @@ -0,0 +1,110 @@ +--- +id: size-of-binary-tree +title: Size of Binary Tree +sidebar_label: 0072 Size of Binary Tree +tags: +- Binary Tree +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate the size (number of nodes) of a binary tree in various programming languages." +--- + +## Problem + +Given a binary tree of size n, you have to count the number of nodes in it. For example, the count of nodes in the tree below is 4. + +``` + 1 + / \ + 10 39 + / +5 +``` + +### Examples: +**Example 1:** +``` +Input: +1 2 3 +Output: +3 +Explanation: +Given Tree is : + 1 + / \ + 2 3 +There are 3 nodes in the tree. +``` + +**Example 2:** +``` +Input: +10 5 9 N 1 3 6 +Output: +6 +Explanation: +Given Tree is : + 10 + / \ + 5 9 + \ / \ + 1 3 6 +There are 6 nodes in the tree. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **getSize()** which takes the tree head node and returns an integer representing the number of nodes in the tree. + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(h)$, where h is the height of the binary tree + +### Constraints: + +- $1<=n<=10^5$ +- $1 <=$ values of nodes $<= 10^6$ + +## Solution +### Python +```python +def getSize(self, node : Optional['Node']) -> int: + if node is None: + return 0 + else: + return self.getSize(node.left) + 1 + self.getSize(node.right) +``` + +### Java +```java +public static int getSize(Node node) { + if(node==null) + return 0; + else + return getSize(node.left) + 1 + getSize(node.right); +} +``` + +### C++ +```cpp +int getSize(Node* node) { + if (node == nullptr) + return 0; + else + return getSize(node->left) + 1 + getSize(node->right); +} +``` + +### C +```c +int getSize(struct Node* node) { + if (node == NULL) + return 0; + else + return getSize(node->left) + 1 + getSize(node->right); +} +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(h)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0073.md b/solutions/gfg-solutions/Basic/0073.md new file mode 100644 index 0000000..843fc2b --- /dev/null +++ b/solutions/gfg-solutions/Basic/0073.md @@ -0,0 +1,163 @@ +--- +id: elements-in-the-range +title: Elements in the Range +sidebar_label: 0073 Elements in the Range +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to find elements within a specified range in an array in various programming languages." +--- + +## Problem + +Given an array arr[] containing positive elements. A and B are two numbers defining a range. The task is to check if the array contains all elements in the given range. + +### Examples: +**Example 1:** +``` +Input: N = 7, A = 2, B = 5 +arr[] = {1, 4, 5, 2, 7, 8, 3} +Output: Yes +Explanation: It has elements between range 2-5 i.e 2,3,4,5 +``` + +**Example 2:** +``` +Input: N = 7, A = 2, B = 6 +arr[] = {1, 4, 5, 2, 7, 8, 3} +Output: No +Explanation: Array does not contain 6. +``` + +### Your task: + +This is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function **check_elements()** that takes array arr, integer N, integer A, and integer B as parameters and returns the boolean True if array elements contain all elements in the given range else boolean False. + +**Note:** If the array contains all elements in the given range then driver code outputs Yes otherwise, it outputs No + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^7$ + +## Solution +### Python +```python +def check_elements(self, arr, n, A, B): + rangeV = B - A + for i in range(0, n): + if A <= abs(arr[i]) <= B: + z = abs(arr[i]) - A + if 0 <= z < n and arr[z] > 0: + arr[z] = arr[z] * -1 + count = 0 + for i in range(0, rangeV + 1): + if i >= n: + break + if arr[i] > 0: + return False + else: + count += 1 + if count != (rangeV + 1): + return False + return True +``` + +### Java +```java +boolean check_elements(int arr[], int n, int A, int B) { + int rangeV = B - A; + for (int i = 0; i < n; i++) { + if (Math.abs(arr[i]) >= A && Math.abs(arr[i]) <= B) { + int z = Math.abs(arr[i]) - A; + if (z >= 0 && z < n && arr[z] > 0) { + arr[z] = arr[z] * -1; + } + } + } + int count = 0; + for (int i = 0; i <= rangeV; i++) { + if (i >= n) { + break; + } + if (arr[i] > 0) { + return false; + } else { + count++; + } + } + + if (count != (rangeV + 1)) { + return false; + } + return true; +} +``` + +### C++ +```cpp +bool check_elements(int arr[], int n, int A, int B) { + int rangeV = B - A; + for (int i = 0; i < n; i++) { + if (abs(arr[i]) >= A && abs(arr[i]) <= B) { + int z = abs(arr[i]) - A; + if (z >= 0 && z < n && arr[z] > 0) { + arr[z] = arr[z] * -1; + } + } + } + int count = 0; + for (int i = 0; i <= rangeV; i++) { + if (i >= n) { + break; + } + if (arr[i] > 0) { + return false; + } else { + count++; + } + } + if (count != (rangeV + 1)) { + return false; + } + return true; +} +``` + +### C +```c +bool check_elements(int arr[], int n, int A, int B) { + int rangeV = B - A; + for (int i = 0; i < n; i++) { + if (abs(arr[i]) >= A && abs(arr[i]) <= B) { + int z = abs(arr[i]) - A; + if (z >= 0 && z < n && arr[z] > 0) { + arr[z] = arr[z] * -1; + } + } + } + int count = 0; + for (int i = 0; i <= rangeV; i++) { + if (i >= n) { + break; + } + if (arr[i] > 0) { + return false; + } else { + count++; + } + } + if (count != (rangeV + 1)) { + return false; + } + return true; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0074.md b/solutions/gfg-solutions/Basic/0074.md new file mode 100644 index 0000000..cc67ad6 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0074.md @@ -0,0 +1,99 @@ +--- +id: game-with-numbers +title: Game with Numbers +sidebar_label: 0074 Game with Numbers +tags: +- Number Games +- Python +- Java +- C++ +- C +description: "This document provides solutions for forming the array by xoring the consecutive elements in various programming languages." +--- + +## Problem + +You are given an array arr[], and you have to re-construct an array arr[]. + +The values in arr[] are obtained by doing Xor of consecutive elements in the array. + +### Examples: +**Example 1:** +``` +Input : n=5, arr[ ] = {10, 11, 1, 2, 3} +Output : 1 10 3 1 3 +Explanation: +At index 0, arr[0] xor arr[1] = 1 +At index 1, arr[1] xor arr[2] = 10 +At index 2, arr[2] xor arr[3] = 3 +... +At index 4, No element is left So, it will remain as +it is. +New Array will be {1, 10, 3, 1, 3}. +``` + +**Example 2:** +``` +Input : n=4, arr[ ] = {5, 9, 7, 6} +Output : 12 14 1 6 +Explanation: +At index 0, arr[0] xor arr[1] = 12 +At index 1, arr[1] xor arr[2] = 14 +At index 2, arr[2] xor arr[3] = 1 +At index 3, No element is left So, it will remain as it is. +New Array will be {12, 14, 1, 6}. +``` + +### Your task: + +This is a function problem. The input is already taken care of by the driver code. You only need to complete the function **game_with_number()** that takes an array (arr), sizeOfArray (n) and return the array re-constructed array arr. The driver code takes care of the printing. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1<=arr[i]<=10^7$ + +## Solution +### Python +```python +def game_with_number (arr, n) : + for i in range(0,n-1): + arr[i] = arr[i]^arr[i+1] + return arr +``` + +### Java +```java +public static int[] game_with_number (int arr[], int n) { + for(int i = 0; i None: + print("Hello World") +``` + +### Java +```java +public static void printHello() { + System.out.println("Hello World"); +} +``` + +### C++ +```cpp +void printHello() { + cout<<"Hello World"; +} +``` + +### C +```c +void printHello() { + printf("Hello World\n"); +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ diff --git a/solutions/gfg-solutions/Basic/0077.md b/solutions/gfg-solutions/Basic/0077.md new file mode 100644 index 0000000..3e0027d --- /dev/null +++ b/solutions/gfg-solutions/Basic/0077.md @@ -0,0 +1,152 @@ +--- +id: angle-between-hour-and-minute-hand +title: Angle between Hour and Minute Hand +sidebar_label: 0077 Angle between Hour and Minute Hand +tags: +- Mathematics +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate the angle between the hour and minute hands of a clock at a given time in various programming languages." +--- + +## Problem + +Calculate the angle between the hour hand and minute hand. + +Note: There can be two angles between hands; we need to print a minimum of two. Also, we need to print the floor of the final result angle. For example, if the final angle is 10.61, we need to print 10. + +### Examples: +**Example 1:** +``` +Input: +H = 9 , M = 0 +Output: +90 +Explanation: +The minimum angle between hour and minute hand when the time is 9 is 90 degress. +``` + +**Example 2:** +``` +Input: +H = 3 , M = 30 +Output: +75 +Explanation: +The minimum angle between hour and minute hand when the time is 3:30 is 75 degress. +``` + +### Your task: + +You don't need to read, input, or print anything. Your task is to complete the function **getAngle()**, which takes 2 Integers H and M as input and returns the answer. + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 ≀ H ≀ 12$ +- $0 ≀ M < 60$ + +H and M are Integers + +## Solution +### Python +```python +def getAngle(self, H , M): + if H < 0 or M < 0 or H > 12 or M > 60: + print('Wrong input') + return None + if H == 12: + H = 0 + if M == 60: + M = 0 + H += 1 + if H > 12: + H -= 12 + hour_angle = 0.5 * (H * 60 + M) + minute_angle = 6 * M + angle = abs(hour_angle - minute_angle) + angle = min(360 - angle, angle) + return int(angle) +``` + +### Java +```java +static int getAngle(int H , int M) { + if (H < 0 || M < 0 || H > 12 || M > 60) { + System.out.println("Wrong input"); + return -1; + } + if (H == 12) { + H = 0; + } + if (M == 60) { + M = 0; + H += 1; + if (H > 12) { + H -= 12; + } + } + double hourAngle = 0.5 * (H * 60 + M); + double minuteAngle = 6 * M; + double angle = Math.abs(hourAngle - minuteAngle); + angle = Math.min(360 - angle, angle); + return (int) angle; +} +``` + +### C++ +```cpp +int getAngle(int H , int M) { + if (H < 0 || M < 0 || H > 12 || M > 60) { + cout << "Wrong input" << endl; + return -1; + } + if (H == 12) { + H = 0; + } + if (M == 60) { + M = 0; + H += 1; + if (H > 12) { + H -= 12; + } + } + double hourAngle = 0.5 * (H * 60 + M); + double minuteAngle = 6 * M; + double angle = abs(hourAngle - minuteAngle); + angle = min(360 - angle, angle); + return static_cast(angle); +} +``` + +### C +```c +int getAngle(int H, int M) { + if (H < 0 || M < 0 || H > 12 || M > 60) { + printf("Wrong input\n"); + return -1; + } + if (H == 12) { + H = 0; + } + if (M == 60) { + M = 0; + H += 1; + if (H > 12) { + H -= 12; + } + } + double hourAngle = 0.5 * (H * 60 + M); + double minuteAngle = 6 * M; + double angle = fabs(hourAngle - minuteAngle); + angle = fmin(360 - angle, angle); + return (int)angle; +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0078.md b/solutions/gfg-solutions/Basic/0078.md new file mode 100644 index 0000000..0692050 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0078.md @@ -0,0 +1,152 @@ +--- +id: sorted-matrix +title: Sorted Matrix +sidebar_label: 0078 Sorted Matrix +tags: +- Matrix +- Sorting +- Python +- Java +- C++ +- C +description: "This document covers methods to sort elements of a matrix in non-decreasing order in various programming languages." +--- + +## Problem + +Given an NxN matrix Mat. Sort all elements of the matrix. + +### Examples: +**Example 1:** +``` +Input: +N=4 +Mat=[[10,20,30,40], +[15,25,35,45] +[27,29,37,48] +[32,33,39,50]] +Output: +10 15 20 25 +27 29 30 32 +33 35 37 39 +40 45 48 50 +Explanation: +Sorting the matrix gives this result. +``` + +**Example 2:** +``` +Input: +N=3 +Mat=[[1,5,3],[2,8,7],[4,6,9]] +Output: +1 2 3 +4 5 6 +7 8 9 +Explanation: +Sorting the matrix gives this result. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **sortedMatrix()** which takes the integer N and the matrix Mat as input parameters and returns the sorted matrix. + +- **Expected Time Complexity:** $O(N^2LogN)$ +- **Expected Auxiliary Space:** $O(N^2)$ + +### Constraints: + +- $1<=N<=1000$ +- $1<=Mat[i][j]<=10^5$ + +## Solution +### Python +```python +def sortedMatrix(self,N,Mat): + temp = [0] * (N * N) + k = 0 + for i in range(0, N) : + for j in range(0, N) : + temp[k] = Mat[i][j] + k += 1 + temp.sort() + k = 0 + for i in range(0, N) : + for j in range(0, N) : + Mat[i][j] = temp[k] + k += 1 + return Mat +``` + +### Java +```java +int[][] sortedMatrix(int N, int Mat[][]) { + int[] temp = new int[N * N]; + int k = 0; + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + temp[k] = Mat[i][j]; + k++; + } + } + Arrays.sort(temp); + k = 0; + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + Mat[i][j] = temp[k]; + k++; + } + } + return Mat; +} +``` + +### C++ +```cpp +vector> sortedMatrix(int N, vector> Mat) { + vector temp(N * N); + int k = 0; + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + temp[k++] = Mat[i][j]; + } + } + sort(temp.begin(), temp.end()); + k = 0; + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + Mat[i][j] = temp[k++]; + } + } + return Mat; +} +``` + +### C +```c +int compare(const void *a, const void *b) { + return (*(int *)a - *(int *)b); +} + +int** sortedMatrix(int N, int **Mat) { + int *temp = (int *)malloc(N * N * sizeof(int)); + int k = 0; + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + temp[k++] = Mat[i][j]; + } + } + qsort(temp, N * N, sizeof(int), compare); + k = 0; + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + Mat[i][j] = temp[k++]; + } + } + free(temp); + return Mat; +} +``` + +- **Time Complexity:** $O(N^2LogN)$ +- **Auxiliary Space:** $O(N^2)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0079.md b/solutions/gfg-solutions/Basic/0079.md new file mode 100644 index 0000000..8b5694a --- /dev/null +++ b/solutions/gfg-solutions/Basic/0079.md @@ -0,0 +1,116 @@ +--- +id: check-for-subsequence +title: Check for Subsequence +sidebar_label: 0079 Check for Subsequence +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to check if one string is a subsequence of another string in various programming languages." +--- + +## Problem + +Given two strings A and B, find if A is a subsequence of B. + +### Examples: +**Example 1:** +``` +Input: +A = AXY +B = YADXCP +Output: 0 +Explanation: A is not a subsequence of B as 'Y' appears before 'A'. +``` + +**Example 2:** +``` +Input: +A = gksrek +B = geeksforgeeks +Output: 1 +Explanation: A is a subsequence of B. +``` + +### Your task: + +You dont need to read input or print anything. Complete the function **isSubSequence()** which takes A and B as input parameters and returns a boolean value denoting if A is a subsequence of B or not. + +- **Expected Time Complexity:** $O(N)$, where N is length of string B +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<= |A|,|B| <=10^4$ + +## Solution +### Python +```python +def isSubSequence(self, A, B): + n, m = len(A), len(B) + i, j = 0, 0 + while (i < n and j < m): + if (A[i] == B[j]): + i += 1 + j += 1 + return i == n +``` + +### Java +```java +boolean isSubSequence(String A, String B){ + int n = A.length(); + int m = B.length(); + int i = 0, j = 0; + while (i < n && j < m) { + if (A.charAt(i) == B.charAt(j)) { + i++; + } + j++; + } + return i == n; +} +``` + +### C++ +```cpp +bool isSubSequence(string A, string B) { + int n = A.length(); + int m = B.length(); + int i = 0, j = 0; + while (i < n && j < m) { + if (A[i] == B[j]) { + i++; + } + j++; + } + return i == n; +} +``` + +### C +```c +int isSubSequence(const char *A, const char *B) { + int n = 0; + while (A[n] != '\0') { + n++; + } + int m = 0; + while (B[m] != '\0') { + m++; + } + int i = 0, j = 0; + while (i < n && j < m) { + if (A[i] == B[j]) { + i++; + } + j++; + } + return i == n; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0080.md b/solutions/gfg-solutions/Basic/0080.md new file mode 100644 index 0000000..4e35574 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0080.md @@ -0,0 +1,110 @@ +--- +id: multiply-left-right-array-sum +title: Multiply Left and Right Array Sum +sidebar_label: 0080 Multiply Left and Right Array Sum +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate the product of the left and right array sums for a given array in various programming languages." +--- + +## Problem + +Pitsy needs help with the given task by her teacher. The task is to divide an array into two sub-array (left and right) containing n/2 elements each and do the sum of the subarrays and then multiply both the subarrays. + +**Note:** If the length of the array is odd then the right half will contain one element more than the left half. + +### Examples: +**Example 1:** +``` +Input : arr[ ] = {1, 2, 3, 4} +Output : 21 +Explanation: +Sum up an array from index 0 to 1 = 3 +Sum up an array from index 2 to 3 = 7 +Their multiplication is 21. +``` + +**Example 2:** +``` +Input : arr[ ] = {1, 2} +Output : 2 +``` + +### Your task: + +This is a function problem. The input is already taken care of by the driver code. You only need to complete the function **multiply()** that takes an array (arr), sizeOfArray (n), and return the sum of the subarrays and then multiply both the subarrays. The driver code takes care of the printing. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 ≀ T ≀ 100$ +- $1 ≀ N ≀ 1000$ +- $1 ≀ A[i] ≀ 100$ + +## Solution +### Python +```python +def multiply (arr, n) : + sum_left, sum_right=0, 0 + for i in range(0, n//2): + sum_left = sum_left+arr[i] + for j in range(n//2, n): + sum_right = sum_right+arr[j] + result = sum_left*sum_right + return result +``` + +### Java +```java +public static int multiply (int arr[], int n) { + int sum_left=0, sum_right=0; + for(int i=0; i 0$ + +## Solution +### Python +```python +def fractionalNodes(head,k): + if (k <= 0 or head == None): + return None + fractionalNode = None + i = 0 + temp = head + while (temp != None): + if (i % k == 0): + if (fractionalNode == None): + fractionalNode = head + else: + fractionalNode = fractionalNode.next + i = i + 1 + temp = temp.next + return fractionalNode.data +``` + +### Java +```java +public static int nknode(Node head, int k) { + if (k <= 0 || head == null) + return -1; + Node fractionalNode = null; + int i = 0; + Node temp = head; + while (temp != null) { + if (i % k == 0) { + if (fractionalNode == null) { + fractionalNode = head; + } else { + fractionalNode = fractionalNode.next; + } + } + i++; + temp = temp.next; + } + if (fractionalNode != null) { + return fractionalNode.data; + } + else { + return -1; + } +} +``` + +### C++ +```cpp +int fractional_node(struct Node *head, int k) { + if (k <= 0 || head == nullptr) + return -1; + Node* fractionalNode = nullptr; + int i = 0; + Node* temp = head; + while (temp != nullptr) { + if (i % k == 0) { + if (fractionalNode == nullptr) { + fractionalNode = head; + } else { + fractionalNode = fractionalNode->next; + } + } + i++; + temp = temp->next; + } + if (fractionalNode != nullptr) { + return fractionalNode->data; + } + else { + return -1; + } +} +``` + +### C +```c +int fractional_node(struct Node *head, int k) { + if (k <= 0 || head == NULL) + return -1; + struct Node *fractionalNode = NULL; + int i = 0; + struct Node *temp = head; + while (temp != NULL) { + if (i % k == 0) { + if (fractionalNode == NULL) { + fractionalNode = head; + } else { + fractionalNode = fractionalNode->next; + } + } + i++; + temp = temp->next; + } + if (fractionalNode != NULL) { + return fractionalNode->data; + } + else { + return -1; + } +} +``` diff --git a/solutions/gfg-solutions/Basic/0083.md b/solutions/gfg-solutions/Basic/0083.md new file mode 100644 index 0000000..7a099cf --- /dev/null +++ b/solutions/gfg-solutions/Basic/0083.md @@ -0,0 +1,158 @@ +--- +id: first-last-occurrences-x +title: First and Last Occurrences of X +sidebar_label: 0083 First and Last Occurrences of X +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to find the first and last occurrences of a specified element X in an array in various programming languages." +--- + +## Problem + +Given a sorted array having N elements, find the indices of the first and last occurrences of an element X in the given array. + +**Note:** If the number X is not found in the array, return '-1' as an array. + +### Examples: +**Example 1:** +``` +Input: +N = 4 , X = 3 +arr[] = { 1, 3, 3, 4 } +Output: +1 2 +Explanation: +For the above array, first occurence of X = 3 is at index = 1 and last occurence is at index = 2. +``` + +**Example 2:** +``` +Input: +N = 4, X = 5 +arr[] = { 1, 2, 3, 4 } +Output: +-1 +Explanation: +As 5 is not present in the array, so the answer is -1. +``` + +### Your task: + +ou don't need to read input or print anything. Complete the function **firstAndLast()** that takes the array arr, its size N and the value X as input parameters and returns a list of integers containing the indices of first and last occurence of X. + +- **Expected Time Complexity:** $O(log(N))$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $0 <= arr[i], X <= 10^9$ + +## Solution +### Python +```python +def firstAndLast(self, arr, n, x): + first = -1 + last = -1 + for i in range(n): + if x != arr[i]: + continue + if first == -1: + first = i + last = i + if first != -1: + return [first, last] + else: + return [-1] +``` + +### Java +```java +public ArrayList firstAndLast(int arr[], int n, int x){ + ArrayList result = new ArrayList<>(); + int first = -1; + int last = -1; + for (int i = 0; i < n; i++) { + if (x != arr[i]) { + continue; + } + if (first == -1) { + first = i; + } + last = i; + } + if (first != -1) { + result.add(first); + result.add(last); + } + else { + result.add(-1); + } + return result; +} +``` + +### C++ +```cpp +vector firstAndLast(vector &arr, int n, int x) { + vector result; + int first = -1; + int last = -1; + for (int i = 0; i < n; i++) { + if (x != arr[i]) { + continue; + } + if (first == -1) { + first = i; + } + last = i; + } + if (first != -1) { + result.push_back(first); + result.push_back(last); + } + else { + result.push_back(-1); + } + return result; +} +``` + +### C +```c +int* firstAndLast(int *arr, int n, int x, int *resultSize) { + int *result = (int *)malloc(2 * sizeof(int)); + if (result == NULL) { + perror("Memory allocation failed"); + exit(EXIT_FAILURE); + } + int first = -1; + int last = -1; + for (int i = 0; i < n; i++) { + if (x != arr[i]) { + continue; + } + if (first == -1) { + first = i; + } + last = i; + } + if (first != -1) { + result[0] = first; + result[1] = last; + *resultSize = 2; + } + else { + result[0] = -1; + *resultSize = 1; + } + return result; +} +``` + +- **Time Complexity:** $O(log(N))$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0084.md b/solutions/gfg-solutions/Basic/0084.md new file mode 100644 index 0000000..093c0f3 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0084.md @@ -0,0 +1,79 @@ +--- +id: maximum-money +title: Maximum Money +sidebar_label: 0084 Maximum Money +tags: +- Problem Solving +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate the maximum amount of money that can be collected from a sequence of houses where every house has some amount of money in various programming languages." +--- + +## Problem + +Given a street of N houses (a row of houses), each house having K amount of money kept inside; now there is a thief who is going to steal this money but he has a constraint/rule that he cannot steal/rob two adjacent houses. Find the maximum money he can rob. + +### Examples: +**Example 1:** +``` +Input: +N = 5 , K = 10 +Output: +30 +Explanation: +The Robber can rob from the first, third and fifth houses which will result in 30. +``` + +**Example 2:** +``` +Input: +N = 2 , K = 12 +Output: +12 +Explanation: +The Robber can only rob from the first or second which will result in 12. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **maximizeMoney()** which takes 2 Integers N and K as input and returns the answer. + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= N,K <= 10^3$ + +## Solution +### Python +```python +def maximizeMoney(self, N , K): + return ((N+1)//2)*K; +``` + +### Java +```java +static int maximizeMoney(int N , int K) { + return ((N+1)/2)*K; +} +``` + +### C++ +```cpp +int maximizeMoney(int N , int K) { + return ((N+1)/2)*K; +} +``` + +### C +```c +int maximizeMoney(int N , int K) { + return ((N+1)/2)*K; +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0085.md b/solutions/gfg-solutions/Basic/0085.md new file mode 100644 index 0000000..b99f495 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0085.md @@ -0,0 +1,99 @@ +--- +id: pattern-5 +title: Pattern 5 +sidebar_label: 0085 Pattern 5 +tags: +- Patterns +- Python +- Java +- C++ +- C +description: "This document covers methods to printinverted pyramid in various programming languages." +--- + +## Problem + +Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern. + +Help Geek build a star pattern. + +### Examples: +**Example 1:** +``` +Input: 5 +Output: +* * * * * +* * * * +* * * +* * +* +``` + +**Example 2:** +``` +Input: 3 +Output: +* * * +* * +* +``` + +### Your task: + +You don't need to input anything. Complete the function **printTriangle()** which takes an integer n as the input parameter and prints the pattern. + +- **Expected Time Complexity:** $O(n^2)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<= n <= 100$ + +## Solution +### Python +```python +def printTriangle(self, N): + for i in range(1, N + 1): + for j in range(N, i - 1, -1): + print("* ", end="") + print() +``` + +### Java +```java +void printTriangle(int n) { + for(int i = 1; i<=n; i++) { + for(int j = n; j>=i; j--) { + System.out.print("* "); + } + System.out.println(); + } +} +``` + +### C++ +```cpp +void printTriangle(int n) { + for(int i = 1; i<=n; i++) { + for(int j = n; j>=i; j--) { + cout<<"* "; + } + cout<= i; j--) { + printf("* "); + } + printf("\n"); + } +} +``` + +- **Time Complexity:** $O(n^2)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0086.md b/solutions/gfg-solutions/Basic/0086.md new file mode 100644 index 0000000..674300a --- /dev/null +++ b/solutions/gfg-solutions/Basic/0086.md @@ -0,0 +1,114 @@ +--- +id: balanced-array +title: Balanced Array +sidebar_label: 0086 Balanced Array +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to check if an array is balanced in various programming languages." +--- + +## Problem + +Given an array of even size N, task is to find minimum value that can be added to an element so that array become balanced. An array is balanced if the sum of the left half of the array elements is equal to the sum of right half. + +### Examples: +**Example 1:** +``` +Input: +N = 4 +arr[] = {1, 5, 3, 2} +Output: 1 +Explanation: +Sum of first 2 elements is 1 + 5 = 6, +Sum of last 2 elements is 3 + 2 = 5, +To make the array balanced you can add 1. +``` + +**Example 2:** +``` +Input: +N = 6 +arr[] = { 1, 2, 1, 2, 1, 3 } +Output: 2 +Explanation: +Sum of first 3 elements is 1 + 2 + 1 = 4, +Sum of last three elements is 2 + 1 + 3 = 6, +To make the array balanced you can add 2. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **minValueToBalance()** which takes the array a[] and N as inputs and returns the desired result. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $2<=N<=10^7$ +- $N\%2==0$ + +## Solution +### Python +```python +def minValueToBalance(self,a,n): + sum1 = 0 + for i in range( int(n / 2)): + sum1 += a[i] + sum2 = 0; + i = int(n / 2) + while i < n: + sum2 += a[i] + i = i + 1 + return abs(sum1 - sum2) +``` + +### Java +```java +long minValueToBalance(long a[] ,int n) { + long sum1 = 0; + for (int i = 0; i < n / 2; i++) + sum1 += a[i]; + long sum2 = 0; + for (int i = n/2; i < n; i++) + sum2 += a[i]; + return Math.abs(sum1 - sum2); + +} +``` + +### C++ +```cpp +int minValueToBalance(int a[], int n) { + int sum1 = 0; + for (int i = 0; i < n/2; i++) + sum1 += a[i]; + int sum2 = 0; + for (int i = n/2; i < n; i++) + sum2 += a[i]; + return abs(sum1 - sum2); +} +``` + +### C +```c +int minValueToBalance(int a[], int n) { + int sum1 = 0; + int sum2 = 0; + for (int i = 0; i < n / 2; i++) { + sum1 += a[i]; + } + for (int i = n / 2; i < n; i++) { + sum2 += a[i]; + } + int balanceValue = abs(sum1 - sum2); + return balanceValue; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0087.md b/solutions/gfg-solutions/Basic/0087.md new file mode 100644 index 0000000..b34e078 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0087.md @@ -0,0 +1,125 @@ +--- +id: product-max-first-min-second +title: Product of Maximum in First Array and Minimum in Second +sidebar_label: 0087 Product of Maximum in First Array and Minimum in Second +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to find the product of the maximum element in the first array and the minimum element in the second array in various programming languages." +--- + +## Problem + +Given two arrays of A and B respectively of sizes N1 and N2, the task is to calculate the product of the maximum element of the first array and minimum element of the second array. + +### Examples: +**Example 1:** +``` +Input : A[] = {5, 7, 9, 3, 6, 2}, + B[] = {1, 2, 6, -1, 0, 9} +Output : -9 +Explanation: +The first array is 5 7 9 3 6 2. +The max element among these elements is 9. +The second array is 1 2 6 -1 0 9. +The min element among these elements is -1. +The product of 9 and -1 is 9*-1=-9. + +``` + +**Example 2:** +``` +Input : A[] = {0, 0, 0, 0}, + B[] = {1, -1, 2} +Output : 0 +``` + +### Your task: + +This is a function problem. The input is already taken care of by the driver code. You only need to complete the function **find_multiplication()** that takes an array of integer (A), another array of integer (B), size of array A(n), size of array B(m) and return the product of the max element of the first array and the minimum element of the second array. The driver code takes care of the printing. + +- **Expected Time Complexity:** $O(N+M)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 ≀ N, M ≀ 10^6$ +- $-10^8 ≀ Ai, Bi ≀ 10^8$ + +## Solution +### Python +```python +def find_multiplication (self, arr, brr, n, m) : + max_arr = arr[0] + min_brr = brr[0] + for i in range(1, n): + if arr[i] > max_arr: + max_arr = arr[i] + for i in range(1, m): + if brr[i] < min_brr: + min_brr = brr[i] + return max_arr * min_brr +``` + +### Java +```java +public static long find_multiplication (int arr[], int brr[], int n, int m) { + int maxArr = arr[0]; + int minBrr = brr[0]; + for (int i = 1; i < n; ++i) { + if (arr[i] > maxArr) { + maxArr = arr[i]; + } + } + for (int i = 1; i < m; ++i) { + if (brr[i] < minBrr) { + minBrr = brr[i]; + } + } + return (long) maxArr * minBrr; +} +``` + +### C++ +```cpp +long long find_multiplication(int a[], int b[], int n, int m) { + int max_a = INT_MIN; + int min_b = INT_MAX; + for (int i = 0; i < n; ++i) { + if (a[i] > max_a) { + max_a = a[i]; + } + } + for (int i = 0; i < m; ++i) { + if (b[i] < min_b) { + min_b = b[i]; + } + } + return (long long) max_a * min_b; +} +``` + +### C +```c +long long find_multiplication(int a[], int b[], int n, int m) { + int max_a = INT_MIN; + int min_b = INT_MAX; + for (int i = 0; i < n; ++i) { + if (a[i] > max_a) { + max_a = a[i]; + } + } + for (int i = 0; i < m; ++i) { + if (b[i] < min_b) { + min_b = b[i]; + } + } + return (long long) max_a * min_b; +} +``` + +- **Time Complexity:** $O(N+M)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0088.md b/solutions/gfg-solutions/Basic/0088.md new file mode 100644 index 0000000..db1b863 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0088.md @@ -0,0 +1,134 @@ +--- +id: find-the-fine +title: Find the Fine +sidebar_label: 0088 Find the Fine +tags: +- Problem Solving +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate total fines based from the cars in various programming languages." +--- + +## Problem + +Given an array of penalties fine[], an array of car numbers car[], and also the date. The task is to find the total fine which will be collected on the given date. Fine is collected from odd-numbered cars on even dates and vice versa. + +### Examples: +**Example 1:** +``` +Input: +N = 4, date = 12 +car[] = {2375, 7682, 2325, 2352} +fine[] = {250, 500, 350, 200} +Output: +600 +Explantion: +The date is 12 (even), so we collect the fine from odd numbered cars. The odd numbered cars and the fines associated with them are as follows: +2375 -> 250 +2325 -> 350 +The sum of the fines is 250+350 = 600 +``` + +**Example 2:** +``` +Input: +N = 3, date = 8 +car[] = {2222, 2223, 2224} +fine[] = {200, 300, 400} +Output: +300 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **totalFine()** which takes the array car[] and fine[] its size N and an integer date as inputs and returns the total fine. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1 <= Car_i <= 10^5$ +- $1 <= Date <= 10^5$ +- $1 <= Fine_i <= 10^5$ + +## Solution +### Python +```python +def totalFine(self, n, date, car, fine): + totalFine = 0 + for i in range(n): + if date % 2 == 0: + if car[i] % 2 != 0: + totalFine += fine[i] + else: + if car[i] % 2 == 0: + totalFine += fine[i] + return totalFine +``` + +### Java +```java +public long totalFine( long n, long date, long car[], long fine[]) { + long totalFine = 0; + for (int i = 0; i < n; i++) { + if (date % 2 == 0) { / + if (car[i] % 2 != 0) { + totalFine += fine[i]; + } + } + else { + if (car[i] % 2 == 0) { + totalFine += fine[i]; + } + } + } + return totalFine; +} +``` + +### C++ +```cpp +long long int totalFine(int n, int date, int car[], int fine[]) { + long long int totalFine = 0; + for (int i = 0; i < n; i++) { + if (date % 2 == 0) { + if (car[i] % 2 != 0) { + totalFine += fine[i]; + } + } + else { + if (car[i] % 2 == 0) { + totalFine += fine[i]; + } + } + } + return totalFine; +} +``` + +### C +```c +long long int totalFine(int n, int date, int car[], int fine[]) { + long long int totalFine = 0; + for (int i = 0; i < n; i++) { + if (date % 2 == 0) { + if (car[i] % 2 != 0) { + totalFine += fine[i]; + } + } + else { + if (car[i] % 2 == 0) { + totalFine += fine[i]; + } + } + } + return totalFine; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0089.md b/solutions/gfg-solutions/Basic/0089.md new file mode 100644 index 0000000..128bf5f --- /dev/null +++ b/solutions/gfg-solutions/Basic/0089.md @@ -0,0 +1,135 @@ +--- +id: ways-to-tile-a-floor +title: Ways To Tile A Floor +sidebar_label: 0089 Ways To Tile A Floor +tags: +- Dynamic Programming +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate the number of ways to tile a floor of given dimensions using tiles of given sizes in various programming languages." +--- + +## Problem + +Given a floor of dimensions 2 x n and tiles of dimensions 2 x 1, the task is to find the number of ways the floor can be tiled. A tile can either be placed horizontally i.e as a 1 x 2 tile or vertically i.e as 2 x 1 tile. return the answer with modulo $10^9+7$. + +### Examples: +**Example 1:** +``` +Input: +n = 3 +Output: 3 +Explanation: +We need 3 tiles to tile the boardof size 2 x 3. +We can tile in following ways: +1) Place all 3 tiles vertically. +2) Place first tile verticallyand remaining 2 tiles horizontally. +3) Place first 2 tiles horizontally and remaining tiles vertically. +``` + +**Example 2:** +``` +Input: +n = 4 +Output:5 +Explanation: +For a 2 x 4 board, there are 5 ways +1) All 4 vertical +2) All 4 horizontal +3) First 2 vertical, remaining 2 horizontal. +4) First 2 horizontal, remaining2 vertical. +5) Corner 2 vertical, middle 2 horizontal. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **numberOfWays()** which takes an Integer n as input and returns the answer. + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=n<=10^5$ + +## Solution +### Python +```python +def numberOfWays(self, N): + if N == 1: + return 1 + elif N == 2: + return 2 + MOD = 1000000007 + dp = [0] * (N + 1) + dp[1] = 1 + dp[2] = 2 + for i in range(3, N + 1): + dp[i] = (dp[i-1] + dp[i-2]) % MOD + return dp[N] +``` + +### Java +```java +static int numberOfWays(int n) { + if (n == 1) { + return 1; + } + else if (n == 2) { + return 2; + } + int MOD = 1000000007; + int[] dp = new int[n + 1]; + dp[1] = 1; + dp[2] = 2; + for (int i = 3; i <= n; i++) { + dp[i] = (dp[i - 1] + dp[i - 2]) % MOD; + } + return dp[n]; +} +``` + +### C++ +```cpp +int numberOfWays(int n) { + if (n == 1) { + return 1; + } + else if (n == 2) { + return 2; + } + const int MOD = 1000000007; + int dp[n + 1]; + dp[1] = 1; + dp[2] = 2; + for (int i = 3; i <= n; i++) { + dp[i] = (dp[i - 1] + dp[i - 2]) % MOD; + } + return dp[n]; +} +``` + +### C +```c +int numberOfWays(int n) { + if (n == 1) { + return 1; + } + else if (n == 2) { + return 2; + } + const int MOD = 1000000007; + int dp[n + 1]; + dp[1] = 1; + dp[2] = 2; + for (int i = 3; i <= n; i++) { + dp[i] = (dp[i - 1] + dp[i - 2]) % MOD; + } + return dp[n]; +} +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0090.md b/solutions/gfg-solutions/Basic/0090.md new file mode 100644 index 0000000..271c62d --- /dev/null +++ b/solutions/gfg-solutions/Basic/0090.md @@ -0,0 +1,131 @@ +--- +id: index-first-1-sorted-array +title: Index of First 1 in a Sorted Array of 0s and 1s +sidebar_label: 0090 Index of First 1 in a Sorted Array of 0s and 1s +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to find the index of the first occurrence of 1 in a sorted array of 0s and 1s in various programming languages." +--- + +## Problem + +Given a sorted array consisting 0s and 1s. The task is to find the index of first 1 in the given array. + +NOTE: If one is not present then, return -1. + +### Examples: +**Example 1:** +``` +Input : +arr[] = {0, 0, 0, 0, 0, 0, 1, 1, 1, 1} +Output : +6 +Explanation: +The index of first 1 in the array is 6. +``` + +**Example 2:** +``` +Input : +arr[] = {0, 0, 0, 0} +Output : +-1 +Explanation: +1's are not present in the array. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **firstIndex()** which takes the array A[] and its size N as inputs and returns the index of first 1. If 1 is not present in the array then return -1. + +- **Expected Time Complexity:** $O(Log (N))$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^6$ +- $0<=A_i<=1$ + +## Solution +### Python +```python +def firstIndex(self, arr, n): + low = 0 + high = n - 1 + first_one_index = -1 + while low <= high: + mid = (low + high) // 2 + if arr[mid] == 1: + first_one_index = mid + high = mid - 1 + else: + low = mid + 1 + return first_one_index +``` + +### Java +```java +public long firstIndex(long arr[], long n) { + long low = 0; + long high = n - 1; + long firstOneIndex = -1; + while (low <= high) { + long mid = (low + high) / 2; + if (arr[(int)mid] == 1) { + firstOneIndex = mid; + high = mid - 1; + } + else { + low = mid + 1; + } + } + return firstOneIndex; +} +``` + +### C++ +```cpp +int firstIndex(int a[], int n) { + int low = 0; + int high = n - 1; + int firstOneIndex = -1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (a[mid] == 1) { + firstOneIndex = mid; + high = mid - 1; + } + else { + low = mid + 1; + } + } + return firstOneIndex; +} +``` + +### C +```c +int firstIndex(int a[], int n) { + int low = 0; + int high = n - 1; + int firstOneIndex = -1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (a[mid] == 1) { + firstOneIndex = mid; + high = mid - 1; + } + else { + low = mid + 1; + } + } + return firstOneIndex; +} +``` + +- **Time Complexity:** $O(Log (N))$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0091.md b/solutions/gfg-solutions/Basic/0091.md new file mode 100644 index 0000000..ff31182 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0091.md @@ -0,0 +1,114 @@ +--- +id: remove-character +title: Remove Character +sidebar_label: 0091 Remove Character +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to remove a characters from the first string that are present in the second string in various programming languages." +--- + +## Problem + +Given two strings string1 and string2, remove those characters from first string(string1) which are present in second string(string2). Both the strings are different and contain only lowercase characters. + +**NOTE:** Size of first string is always greater than the size of second string( |string1| > |string2|). + +### Examples: +**Example 1:** +``` +Input: +string1 = "computer" +string2 = "cat" +Output: "ompuer" +Explanation: After removing characters(c, a, t) from string1 we get "ompuer". +``` + +**Example 2:** +``` +Input: +string1 = "occurrence" +string2 = "car" +Output: "ouene" +Explanation: After removing characters (c, a, r) from string1 we get "ouene". +``` + +### Your task: + +You dont need to read input or print anything. Complete the function **removeChars()** which takes string1 and string2 as input parameter and returns the result string after removing characters from string2 from string1. + +- **Expected Time Complexity:** $O(|String1| + |String2|)$ +- **Expected Auxiliary Space:** $O(|String1|)$ + +### Constraints: + +- $1 <= |String1| , |String2| <= 50$ + +## Solution +### Python +```python +def removeChars (ob, string1, string2): + set_string2 = set(string2) + result = [] + for char in string1: + if char not in set_string2: + result.append(char) + return ''.join(result) +``` + +### Java +```java +static String removeChars(String string1, String string2){ + Set setString2 = new HashSet<>(); + for (char c : string2.toCharArray()) { + setString2.add(c); + } + StringBuilder result = new StringBuilder(); + for (char c : string1.toCharArray()) { + if (!setString2.contains(c)) { + result.append(c); + } + } + return result.toString(); +} +``` + +### C++ +```cpp +string removeChars(string string1, string string2) { + unordered_set setString2; + for (char c : string2) { + setString2.insert(c); + } + string result; + for (char c : string1) { + if (setString2.find(c) == setString2.end()) { + result += c; + } + } + return result; +} +``` + +### C +```c +void removeChars(char *string1, char *string2) { + int map[256] = {0}; + for (int i = 0; i < strlen(string2); ++i) { + map[(int)string2[i]] = 1; + } + int index = 0; + for (int i = 0; i < strlen(string1); ++i) { + if (!map[(int)string1[i]]) { + string1[index++] = string1[i]; + } + } + string1[index] = '\0'; +} +``` + +- **Time Complexity:** $O(|String1| + |String2|)$ +- **Auxiliary Space:** $O(|String1|)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0092.md b/solutions/gfg-solutions/Basic/0092.md new file mode 100644 index 0000000..06898dc --- /dev/null +++ b/solutions/gfg-solutions/Basic/0092.md @@ -0,0 +1,108 @@ +--- +id: print-first-letter-every-word +title: Print First Letter of Every Word in the String +sidebar_label: 0092 Print First Letter of Every Word in the String +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to print the first letter of every word in a given string in various programming languages." +--- + +## Problem + +Given a string S, the task is to create a string with the first letter of every word in the string. + +### Examples: +**Example 1:** +``` +Input: +S = "geeks for geeks" +Output: gfg +``` + +**Example 2:** +``` +Input: +S = "bad is good" +Output: big +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **firstAlphabet()** which takes string S as input parameter and returns a string that contains the first letter of every word in S. + +- **Expected Time Complexity:** $O(|S|)$ +- **Expected Auxiliary Space:** $O(|S|)$ + +### Constraints: + +- $1<=N<=10^5$ +- $0<=a[i]<=10^5$ + +## Solution +### Python +```python +def firstAlphabet(self, S): + words = S.split() + result = "" + for word in words: + result += word[0] + return result +``` + +### Java +```java +String firstAlphabet(String S) { + String[] words = S.split("\\s+"); + StringBuilder result = new StringBuilder(); + for (String word : words) { + if (!word.isEmpty()) { + result.append(word.charAt(0)); + } + } + return result.toString(); +} +``` + +### C++ +```cpp +string firstAlphabet(string S) { + istringstream iss(S); + string word; + string result; + while (iss >> word) { + result += word[0]; + } + return result; +} +``` + +### C +```c +char* firstAlphabet(char S[]) { + char result[100000]; + int result_index = 0; + int i = 0; + while (S[i] != '\0') { + while (isspace(S[i])) { + i++; + } + if (!isspace(S[i])) { + result[result_index++] = S[i]; + } + while (S[i] != '\0' && !isspace(S[i])) { + i++; + } + } + result[result_index] = '\0'; + char* final_result = (char*) malloc(strlen(result) + 1); + strcpy(final_result, result); + return final_result; +} +``` + +- **Time Complexity:** $O(|S|)$ +- **Auxiliary Space:** $O(|S|)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0093.md b/solutions/gfg-solutions/Basic/0093.md new file mode 100644 index 0000000..009d0d1 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0093.md @@ -0,0 +1,124 @@ +--- +id: replace-zeros-with-five +title: Replace All 0's with 5 +sidebar_label: 0093 Replace All 0's with 5 +tags: + - Python + - Java + - C++ + - C +description: "This document covers methods to replace all occurrences of the digit 0 with the digit 5 in a given number in various programming languages." +--- + +## Problem + +Given a number N. The task is to complete the function **convertFive()** which replaces all zeros in the number with 5 and returns the number. + +### Examples: + +**Example 1:** + +``` +Input +2 +1004 +121 + +Output +1554 +121 + +Explanation: +Testcase 1: At index 1 and 2 there is 0 so we replace it with 5. +Testcase 2: There is no,0 so output will remain the same. +``` + +### Input: + +The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. +Each test case contains a single integer N denoting the number. + +### Output: + +The function will return an integer where all zero's are converted to 5. + +### Your task: + +Since this is a functional problem you don't have to worry about input, you just have to complete the function **convertFive()**. + +### Constraints: + +- $1 <= T <= 10^3$ +- $1 <= N <= 10^4$ + +## Solution + +### Python + +```python +def convertFive(self,n): + num_str = str(n) + result = "" + for char in num_str: + if char == '0': + result += '5' + else: + result += char + return int(result) +``` + +### Java + +```java +public static int convertFive(int n){ + String numStr = String.valueOf(n); + StringBuilder result = new StringBuilder(); + for (int i = 0; i < numStr.length(); i++) { + char currentChar = numStr.charAt(i); + if (currentChar == '0') { + result.append('5'); + } + else { + result.append(currentChar); + } + } + int convertedNumber = Integer.parseInt(result.toString()); + return convertedNumber; +} +``` + +### C++ + +```cpp +int convertFive(int n) { + string numStr = to_string(n); + for (char &c : numStr) { + if (c == '0') { + c = '5'; + } + } + int convertedNumber = stoi(numStr); + return convertedNumber; +} +``` + +### C + +```c +int convertFive(int n) { + int result = 0; + int position = 1; + while (n != 0) { + int digit = n % 10; + if (digit == 0) { + result += 5 * position; + } + else { + result += digit * position; + } + n /= 10; + position *= 10; + } + return result; +} +``` diff --git a/solutions/gfg-solutions/Basic/0094.md b/solutions/gfg-solutions/Basic/0094.md new file mode 100644 index 0000000..b0b7bd2 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0094.md @@ -0,0 +1,101 @@ +--- +id: pattern-6 +title: Pattern 6 +sidebar_label: 0094 Pattern 6 +tags: +- Patterns +- Python +- Java +- C++ +- C +description: "This document covers methods to print triangle number in various programming languages." +--- + +## Problem + +Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern. + +Help Geek to build a pattern. + +### Examples: +**Example 1:** +``` +Input: 5 + +Output: +1 2 3 4 5 +1 2 3 4 +1 2 3 +1 2 +1 +``` + +### Your task: + +You don't need to input anything. Complete the function **printTriangle()** which takes an integer n as the input parameter and print the pattern. + +### Constraints: + +- $1<= N <= 20$ + +## Solution +### Python +```python +def printTriangle(self, N): + for i in range(N, 0, -1): + for j in range(1, i + 1): + if j == 1: + print(j, end='') + else: + print(' ' + str(j), end='') + print() +``` + +### Java +```java +void printTriangle(int n) { + for (int i = n; i >= 1; i--) { + for (int j = 1; j <= i; j++) { + if (j == 1) { + System.out.print(j); + } else { + System.out.print(" " + j); + } + } + System.out.println(); + } +} +``` + +### C++ +```cpp +void printTriangle(int n) { + for (int i = n; i >= 1; i--) { + for (int j = 1; j <= i; j++) { + if (j == 1) { + cout << j; + } else { + cout << " " << j; + } + } + cout << endl; + } +} +``` + +### C +```c +void printTriangle(int n) { + int i, j; + for (i = n; i >= 1; i--) { + for (j = 1; j <= i; j++) { + if (j == 1) { + printf("%d", j); + } else { + printf(" %d", j); + } + } + printf("\n"); + } +} +``` \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0095.md b/solutions/gfg-solutions/Basic/0095.md new file mode 100644 index 0000000..b494cf2 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0095.md @@ -0,0 +1,90 @@ +--- +id: set-kth-bit +title: Set kth Bit +sidebar_label: 0095 Set kth Bit +tags: +- Bit Manipulation +- Python +- Java +- C++ +- C +description: "This document covers methods to set the kth bit of a number to 1 in various programming languages." +--- + +## Problem + +Given a number N and a value K. From the right, set the Kth bit in the binary representation of N. The position of Least Significant Bit(or last bit) is 0, the second last bit is 1 and so on. + +### Examples: +**Example 1:** +``` +Input: +N = 10 +K = 2 +Output: +14 +Explanation: +Binary representation of the given number 10 is: 1 0 1 0, number of bits in the binary reprsentation is 4. Thus 2nd bit from right is 0. The number after changing this bit to 1 is: 14(1 1 1 0). +``` + +**Example 2:** +``` +Input: +N = 15 +K = 3 +Output: +15 +Explanation: +The binary representation of the given number 15 is: 1 1 1 1, number of bits in the binary representation is 4. Thus 3rd bit from the right is 1. The number after changing this bit to 1 is 15(1 1 1 1). +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **setKthBit()** which takes two integer N and K as input parameter and returns an integer after setting the K'th bit in N. + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^9$ +- $0 <= K < X$, where X is the number of bits in the binary representation of N. + +## Solution +### Python +```python +def setKthBit(self, N, K): + mask = 1 << K + result = N | mask + return result +``` + +### Java +```java +static int setKthBit(int N,int K){ + int mask = 1 << K; + int result = N | mask; + return result; +} +``` + +### C++ +```cpp +int setKthBit(int N, int K) { + int mask = 1 << K; + int result = N | mask; + return result; +} +``` + +### C +```c +int setKthBit(int N, int K) { + int mask = 1 << K; + int result = N | mask; + return result; +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0096.md b/solutions/gfg-solutions/Basic/0096.md new file mode 100644 index 0000000..23fb763 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0096.md @@ -0,0 +1,142 @@ +--- +id: gcd-of-array +title: GCD of Array +sidebar_label: 0096 GCD of Array +tags: +- Array +- Mathematics +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate the Greatest Common Divisor (GCD) of an array of integers in various programming languages." +--- + +## Problem + +Given an array of N positive integers, find GCD of all the array elements. + +### Examples: +**Example 1:** +``` +Input: N = 3, arr[] = {2, 4, 6} +Output: 2 +Explanation: GCD of 2,4,6 is 2. +``` + +**Example 2:** +``` +Input: N = 1, arr[] = {1} +Output: 1 +Explanation: Greatest common divisor of all the numbers is 1. +``` + +### Your task: + +You don't need to read input or print anything. Complete the function **gcd()** which takes N and array as input parameters and returns the gcd. + +- **Expected Time Complexity:** $O(N logN)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 ≀ N, arr[i] ≀ 10^5$ + +## Solution +### Python +```python +def gcd(self, n, arr): + def compute_gcd(a, b): + while b != 0: + a, b = b, a % b + return a + if n == 1: + return arr[0] + current_gcd = arr[0] + for i in range(1, n): + current_gcd = compute_gcd(current_gcd, arr[i]) + if current_gcd == 1: + return 1 + return current_gcd +``` + +### Java +```java +public int gcd(int N , int arr[]) { + if (N == 1) { + return arr[0]; + } + int currentGCD = arr[0]; + for (int i = 1; i < N; i++) { + currentGCD = computeGCD(currentGCD, arr[i]); + if (currentGCD == 1) { + return 1; + } + } + return currentGCD; +} + +private int computeGCD(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; +} +``` + +### C++ +```cpp +int gcd(int N, int arr[]) { + if (N == 1) { + return arr[0]; + } + int currentGCD = arr[0]; + for (int i = 1; i < N; i++) { + currentGCD = computeGCD(currentGCD, arr[i]); + if (currentGCD == 1) { + return 1; + } + } + return currentGCD; +} + +int computeGCD(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; +} +``` + +### C +```c +int gcd(int N, int arr[]) { + if (N == 1) { + return arr[0]; + } + int currentGCD = arr[0]; + for (int i = 1; i < N; i++) { + currentGCD = computeGCD(currentGCD, arr[i]); + if (currentGCD == 1) { + return 1; + } + } + return currentGCD; +} + +int computeGCD(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; +} +``` + +- **Time Complexity:** $O(N logN)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0097.md b/solutions/gfg-solutions/Basic/0097.md new file mode 100644 index 0000000..4900237 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0097.md @@ -0,0 +1,120 @@ +--- +id: greater-on-right-side +title: Greater on Right Side +sidebar_label: 0097 Greater on Right Side +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to replace every element with the greatest element in various programming languages." +--- + +## Problem + +You are given an array Arr of size N. Replace every element with the next greatest element (greatest element on its right side) in the array. Also, since there is no element next to the last element, replace it with -1. + +### Examples: +**Example 1:** +``` +Input: +N = 6 +Arr[] = {16, 17, 4, 3, 5, 2} +Output: +17 5 5 5 2 -1 +Explanation: For 16 the greatest element +on its right is 17. For 17 it's 5. +For 4 it's 5. For 3 it's 5. For 5 it's 2. +For 2 it's -1(no element to its right). +So the answer is 17 5 5 5 2 -1 +``` + +**Example 2:** +``` +Input: +N = 4 +Arr[] = {2, 3, 1, 9} +Output: +9 9 9 -1 +Explanation: For each element except 9 the greatest element on its right is 9. +So the answer is 9 9 9 -1 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **nextGreatest()** which takes the array of integers arr and n as parameters and returns void. You need to change the array itself. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1 <= Arr_i <= 10^6$ + +## Solution +### Python +```python +def nextGreatest(self,arr, n): + if n == 0: + return + max_right = -1 + for i in range(n-1, -1, -1): + current = arr[i] + arr[i] = max_right + max_right = max(max_right, current) + arr[n-1] = -1 +``` + +### Java +```java +void nextGreatest(int arr[], int n) { + if (n == 0) { + return; + } + int maxRight = -1; + for (int i = n - 1; i >= 0; i--) { + int current = arr[i]; + arr[i] = maxRight; + maxRight = Math.max(maxRight, current); + } + arr[n - 1] = -1; +} +``` + +### C++ +```cpp +void nextGreatest(int arr[], int n) { + if (n == 0) { + return; + } + int maxRight = -1; + for (int i = n - 1; i >= 0; i--) { + int current = arr[i]; + arr[i] = maxRight; + maxRight = std::max(maxRight, current); + } + arr[n - 1] = -1; +} +``` + +### C +```c +void nextGreatest(int arr[], int n) { + if (n == 0) { + return; + } + + int maxRight = -1; + for (int i = n - 1; i >= 0; i--) { + int current = arr[i]; + arr[i] = maxRight; + maxRight = (maxRight > current) ? maxRight : current; + } + arr[n - 1] = -1; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0098.md b/solutions/gfg-solutions/Basic/0098.md new file mode 100644 index 0000000..5259686 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0098.md @@ -0,0 +1,106 @@ +--- +id: max-days-without-darkness +title: Maximum Days Without Darkness +sidebar_label: 0098 Maximum Days Without Darkness +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to find the maximum number of days the room remains illuminated using candles that reduce by 1 unit each day, given an array representing the sizes of the candles." +--- + +## Problem + +Given an array arr[] of size N representing the size of candles which reduce by 1 unit each day. The room is illuminated using the given N candles. Find the maximum number of days the room is without darkness. + +### Examples: +**Example 1:** +``` +Input: N = 3, arr[] = {1,1,2} +Output: 2 +Explanation: The candles' length reduce by 1 in 1 day. So, at the end of day 1: +Sizes would be 0 0 1, So, at end of day 2: Sizes would be 0 0 0. This means the room was illuminated for 2 days. +``` + +**Example 2:** +``` +Input: N = 5, arr[] = {2,3,4,2,1} +Output: 4 +``` + +### Your task: + +This is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function **maxDays()** that takes array A[] and integer N as parameters and returns the desired output. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^6$ + +## Solution +### Python +```python +def maxDays(self, arr, n): + if n == 0: + return 0 + max_initial_height = 0 + for height in arr: + if height > max_initial_height: + max_initial_height = height + return max_initial_height +``` + +### Java +```java +long maxDays(long arr[], int n){ + if (n == 0) { + return 0; + } + long maxInitialHeight = 0; + for (int i = 0; i < n; i++) { + if (arr[i] > maxInitialHeight) { + maxInitialHeight = arr[i]; + } + } + return maxInitialHeight; +} +``` + +### C++ +```cpp +int maxDays(int arr[],int n){ + if (n == 0) { + return 0; + } + long maxInitialHeight = 0; + for (int i = 0; i < n; i++) { + if (arr[i] > maxInitialHeight) { + maxInitialHeight = arr[i]; + } + } + return maxInitialHeight; +} +``` + +### C +```c +int maxDays(int arr[], int n) { + if (n == 0) { + return 0; + } + long maxInitialHeight = 0; + for (int i = 0; i < n; i++) { + if (arr[i] > maxInitialHeight) { + maxInitialHeight = arr[i]; + } + } + return maxInitialHeight; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0099.md b/solutions/gfg-solutions/Basic/0099.md new file mode 100644 index 0000000..6f3779f --- /dev/null +++ b/solutions/gfg-solutions/Basic/0099.md @@ -0,0 +1,123 @@ +--- +id: pattern-10 +title: Pattern 10 +sidebar_label: 0099 Pattern 10 +tags: +- Patterns +- Python +- Java +- C++ +- C +description: "This document covers methods to print a pattern in various programming languages." +--- + +## Problem + +Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern. + +Help Geek to build a star pattern. + +### Examples: +**Example 1:** +``` +Input: 5 +Output: +* +* * +* * * +* * * * +* * * * * +* * * * +* * * +* * +* +``` + +**Example 2:** +``` +Input: 3 +Output: +* +* * +* * * +* * +* +``` + +### Your task: + +You don't need to input anything. Complete the function **printTriangle()** which takes an integer n as the input parameter and prints the pattern. + +- **Expected Time Complexity:** $O(n^2)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= n <= 1000$ + +## Solution +### Python +```python +def printTriangle(self, n): + for i in range(1, n+1): + print('* ' * i) + for i in range(n-1, 0, -1): + print('* ' * i) +``` + +### Java +```java +void printTriangle(int n) { + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= i; j++) { + System.out.print("* "); + } + System.out.println(); + } + for (int i = n - 1; i >= 1; i--) { + for (int j = 1; j <= i; j++) { + System.out.print("* "); + } + System.out.println(); + } +} +``` + +### C++ +```cpp +void printTriangle(int n) { + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= i; j++) { + std::cout << "* "; + } + std::cout << std::endl; + } + for (int i = n - 1; i >= 1; i--) { + for (int j = 1; j <= i; j++) { + std::cout << "* "; + } + std::cout << std::endl; + } +} +``` + +### C +```c +void printTriangle(int n) { + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= i; j++) { + printf("* "); + } + printf("\n"); + } + for (int i = n - 1; i >= 1; i--) { + for (int j = 1; j <= i; j++) { + printf("* "); + } + printf("\n"); + } +} +``` + +- **Time Complexity:** $O(n^2)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0100.md b/solutions/gfg-solutions/Basic/0100.md new file mode 100644 index 0000000..d4b26ba --- /dev/null +++ b/solutions/gfg-solutions/Basic/0100.md @@ -0,0 +1,107 @@ +--- +id: factorial-numbers-less-than-n +title: Find All Factorial Numbers Less Than or Equal to n +sidebar_label: 0100 Find All Factorial Numbers Less Than or Equal to n +tags: +- Mathematics +- Python +- Java +- C++ +- C +description: "This document covers methods to find all factorial numbers less than or equal to a given number n in various programming languages." +--- + +## Problem + +A number n is called a factorial number if it is the factorial of a positive integer. For example, the first few factorial numbers are 1, 2, 6, 24, 120, + +Given a number n, the task is to return the list/vector of the factorial numbers smaller than or equal to n. + +### Examples: +**Example 1:** +``` +Input: n = 3 +Output: 1 2 +Explanation: The first factorial number is 1 which is less than equal to n. The second number is 2 which is less than equal to n,but the third factorial number is 6 which is greater than n. So we print only 1 and 2. +``` + +**Example 2:** +``` +Input: n = 6 +Output: 1 2 6 +Explanation: The first three factorial numbers are less than equal to n but the fourth factorial number 24 is greater than n. So we print only first three factorial numbers. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **rotate()** which takes the array **A[]** and its size **N** as inputs and modify the array in place. + +- **Expected Time Complexity:** $O(K)$, Where K is the number of factorial numbers. +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=n<=10^{18}$ + +## Solution +### Python +```python +def factorialNumbers(self, n): + factorial = 1 + factorials = [] + i = 1 + while factorial <= n: + factorials.append(factorial) + i += 1 + factorial *= i + + return factorials +``` + +### Java +```java +static ArrayList factorialNumbers(long n) { + ArrayList factorials = new ArrayList<>(); + long factorial = 1; + int i = 1; + while (factorial <= n) { + factorials.add(factorial); + i++; + factorial *= i; + } + return factorials; +} +``` + +### C++ +```cpp +vector factorialNumbers(long long n) { + vector factorials; + long long factorial = 1; + int i = 1; + while (factorial <= n) { + factorials.push_back(factorial); + i++; + factorial *= i; + } + return factorials; +} +``` + +### C +```c +long long factorialNumbers(long long n, long long *out, int *out_size) { + long long factorial = 1; + int i = 1; + *out_size = 0; + while (factorial <= n) { + out[(*out_size)++] = factorial; + i++; + factorial *= i; + } + return factorial; +} +``` + +- **Time Complexity:** $O(K)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0101.md b/solutions/gfg-solutions/Basic/0101.md new file mode 100644 index 0000000..b480413 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0101.md @@ -0,0 +1,239 @@ +--- +id: cpp-classes-introduction +title: C++ Classes Introduction +sidebar_label: 0101 C++ Classes Introduction + +tags: +- CPP +- OOP +- Classes + +description: "This is a solution to the C++ Classes Introduction problem on GeeksForGeeks." +--- + +## Problem Description +Create class named `CollegeCourse` with fields courseID, grade, credits, gradePoints and honorPoints. Calculate honorpoints as the product of gradepoints and credits. GradePoints are calculated as (A-10),(B-9),(C-8),(D-7),(E-6) & (F-5). +Class CollegeCourse contains following functions: +1. set_CourseId( string CID): sets courseId +2. set_Grade(char g): sets grade equal to g +3. set_Credit(int cr): sets credits equal to cr +4.calculateGradePoints(char g): returns gradePoint(int) +5. calculateHonorPoints(int gp,int cr): return honorPoint (float) +6. display(): prints gradePoint and honorPoint + +### Examples + +**Example 1:** +``` +Input: +The first line contains an integer T, the number of test cases. For each test case, there is a string CID, denoting Course ID, a character g, denoting the grade and an integer cr, denoting the credits of the course. + +Output: +For each test case, the output is the gradePoints & the honorPoints of that course. +``` + + +### Constraints +- `1 ≀ T ≀ 100` +- `0 ≀ CID.length() ≀ 100` +- `'A' <= g <= 'F'` +- `1 <= cr <= 4` + +Note: Grades are not case sensitive. + +### Example + +**Example 1:** +``` +Input: +2 +CSN-206 A 4 +ECE-500 d 3 + +Output: +10 40 +7 21 +``` + + +## Solution for C++ Classes Introduction + +### Code in Different Languages + + + + + + + ```python + class CollegeCourse: + def __init__(self): + self.courseID = "" + self.gp = 0 + self.grade = '' + self.credits = 0 + + def set_CourseId(self, courseID): + self.courseID = courseID + + def set_Grade(self, grade): + self.grade = grade + + def set_Credit(self, credits): + self.credits = credits + + def calculateGradePoints(self, grade): + grade = grade.upper() + if grade == 'A': + self.gp = 10 + elif grade == 'B': + self.gp = 9 + elif grade == 'C': + self.gp = 8 + elif grade == 'D': + self.gp = 7 + elif grade == 'E': + self.gp = 6 + elif grade == 'F': + self.gp = 5 + return self.gp + + def calculateHonorPoints(self, gp, credits): + return gp * credits + + def display(self): + print(self.calculateGradePoints(self.grade), self.calculateHonorPoints(self.gp, self.credits)) + +# Example usage: +course = CollegeCourse() +course.set_CourseId("CS101") +course.set_Grade("A") +course.set_Credit(4) +course.display() # + ``` + + + + + + + ``` + public class CollegeCourse { + private String courseID; + private int gp; + private char grade; + private int credits; + + public void setCourseId(String courseID) { + this.courseID = courseID; + } + + public void setGrade(char grade) { + this.grade = grade; + } + + public void setCredit(int credits) { + this.credits = credits; + } + + public int calculateGradePoints(char grade) { + grade = Character.toUpperCase(grade); + switch (grade) { + case 'A': + gp = 10; + break; + case 'B': + gp = 9; + break; + case 'C': + gp = 8; + break; + case 'D': + gp = 7; + break; + case 'E': + gp = 6; + break; + case 'F': + gp = 5; + break; + } + return gp; + } + + public int calculateHonorPoints(int gp, int credits) { + return gp * credits; + } + + public void display() { + System.out.println(calculateGradePoints(grade) + " " + calculateHonorPoints(gp, credits)); + } + + public static void main(String[] args) { + CollegeCourse course = new CollegeCourse(); + course.setCourseId("CS101"); + course.setGrade('A'); + course.setCredit(4); + course.display(); // Output: 10 40 + } + } + ``` + + + + + + + ```cpp + class CollegeCourse + { + //your code here + private: + string courseID; + int gp; + char grade; + int credits; + + public: + void set_CourseId(string courseID){ + this->courseID = courseID; + } + + void set_Grade(char grade){ + this->grade = grade; + } + + void set_Credit(int credits){ + this->credits = credits; + } + + int calculateGradePoints(char grade){ + grade = toupper(grade); + switch(grade){ + case 'A': gp = 10; break; + case 'B': gp = 9; break; + case 'C': gp = 8; break; + case 'D': gp = 7; break; + case 'E': gp = 6; break; + case 'F': gp = 5; break; + } + return gp; + } + + int calculateHonorPoints(int gp, int credits){ + return gp * credits; + } + + void display(){ + cout< + + +## References + +- **GeekForGeeks Problem**: [C++ Classes Introduction](https://www.geeksforgeeks.org/problems/c-classes-introduction/0) \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0102.md b/solutions/gfg-solutions/Basic/0102.md new file mode 100644 index 0000000..34a2fc7 --- /dev/null +++ b/solutions/gfg-solutions/Basic/0102.md @@ -0,0 +1,149 @@ +--- +id: maximum-in-struct-array +title: Maximum in Struct Array +sidebar_label: 0102 Maximum in Struct Array + +tags: +- CPP +- Arrays +- Mathematical + +description: "This is a solution to the Maximum in Struct Array problem on GeeksForGeeks." +--- + +## Problem Description +Given a struct array of type **height**, having two elements **feet** and **inches**. Find the `maximum height` among n heights, where height is calculated `sum of feet and inches` after converting `feet` into `inches`. + +### Examples + +**Example 1:** +``` +Input: +n = 2 h1 -> {1 2} h2 -> {2 1} + +Output: +25 + +Explanation: +(1, 2) and (2, 1) are respective given heights.After converting both heigths in to inches,we get 14 and 25 as respective heights.So, 25 is the maximum height. +``` + +**Example 2:** +``` +Input: +n = n = 3 h1 -> {3 2} h2 -> {2 3} h3 ->{1 2} + +Output: +38 + +Explanation: +(3, 2), (2,3) and (1, 2) are respective given heights.After converting both heigths in to inches,we get 38,27 and 14 as respective heights.So, 38 is the maximum height. +``` + + +### Constraints +- `1 ≀ n ≀ 10^5` + + +## Solution for Maximum in Struct Array + +### Code in Different Languages + + + + + + + ```python + class Height: + def __init__(self, feet, inches): + self.feet = feet + self.inches = inches + + def findMax(arr, n): + ans = [0] * n + max_height = 0 + + for i in range(n): + ans[i] = arr[i].feet * 12 + arr[i].inches + + for height in ans: + if height > max_height: + max_height = height + + return max_height + + # Example usage + arr = [Height(5, 9), Height(6, 2), Height(5, 11)] + n = len(arr) + print(findMax(arr, n)) # Output: 74 (6 feet 2 inches) + ``` + + + + + + + ``` + class Height { + int feet; + int inches; + + public Height(int feet, int inches) { + this.feet = feet; + this.inches = inches; + } + } + + public class Main { + public static int findMax(Height[] arr, int n) { + int[] ans = new int[n]; + int max = 0; + + for (int i = 0; i < n; i++) { + ans[i] = arr[i].feet * 12 + arr[i].inches; + } + + for (int i = 0; i < n; i++) { + if (ans[i] > max) { + max = ans[i]; + } + } + + return max; + } + + public static void main(String[] args) { + Height[] arr = {new Height(5, 9), new Height(6, 2), new Height(5, 11)}; + int n = arr.length; + System.out.println(findMax(arr, n)); // Output: 74 (6 feet 2 inches) + } + } + ``` + + + + + + + ```cpp + int findMax(Height arr[], int n) { + // Code here + int ans[n]; + int max = 0; + for(int i=0;imax) max=ans[i]; + } + return max; + } + ``` + + + + +## References + +- **GeekForGeeks Problem**: [Maximum in Struct Array](https://www.geeksforgeeks.org/problems/maximum-in-struct-array/0) \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0103.md b/solutions/gfg-solutions/Basic/0103.md new file mode 100644 index 0000000..8ae90dc --- /dev/null +++ b/solutions/gfg-solutions/Basic/0103.md @@ -0,0 +1,144 @@ +--- +id: stack-designer +title: Stack Designer +sidebar_label: 0103 Stack Designer + +tags: +- CPP +- Stack +- STL +- Data structures + +description: "This is a solution to the Stack Designer problem on GeeksForGeeks." +--- + +## Problem Description +You are given an array **arr** of size **N**. You need to push the elements of the array into a stack and then print them while popping. + +### Examples + +**Example 1:** +``` +Input: +n = 5 +arr = {1 2 3 4 5} + +Output: +5 4 3 2 1 +``` + +**Example 2:** +``` +Input: +n = 7 +arr = {1 6 43 1 2 0 5} + +Output: +5 0 2 1 43 6 1 +``` + + +### Constraints +- `1 ≀ Ai ≀ 10^7` + + +## Solution for Stack Designer + +### Code in Different Languages + + + + + + + ```python + class Stack: + def __init__(self): + self.stack = [] + + def push(self, arr): + for item in arr: + self.stack.append(item) + return self.stack + + def pop_all(self): + while self.stack: + print(self.stack.pop(), end=" ") + + # Example usage + arr = [1, 2, 3, 4, 5] + n = len(arr) + s = Stack() + s.push(arr) + s.pop_all() + # Output: 5 4 3 2 1 + ``` + + + + + + + ``` + import java.util.Stack; + + public class Main { + public static Stack _push(int arr[], int n) { + Stack s = new Stack<>(); + for (int i = 0; i < n; ++i) { + s.push(arr[i]); + } + return s; + } + + public static void _pop(Stack s) { + while (!s.empty()) { + System.out.print(s.pop() + " "); + } + } + + public static void main(String[] args) { + int[] arr = {1, 2, 3, 4, 5}; + int n = arr.length; + Stack s = _push(arr, n); + _pop(s); + // Output: 5 4 3 2 1 + } + } + ``` + + + + + + + ```cpp + stack_push(int arr[],int n) + { + //return a stack with all elements of arr inserted in it + stack s; + for (int i = 0; i < n; ++i) { + s.push(arr[i]); + } + return s; + } + + /* _pop function to print elements of the stack + remove as well + */ + void _pop(stack s) + { + //print top and pop for each element until it becomes empty + while (!s.empty()) { + cout << s.top() << " "; + s.pop(); + } + } + ``` + + + + +## References + +- **GeekForGeeks Problem**: [Stack Designer](https://www.geeksforgeeks.org/problems/stack-designer/0) \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0104.md b/solutions/gfg-solutions/Basic/0104.md new file mode 100644 index 0000000..3436f9f --- /dev/null +++ b/solutions/gfg-solutions/Basic/0104.md @@ -0,0 +1,158 @@ +--- +id: parties-and-seats +title: Parties and Seats +sidebar_label: 0104 Parties and Seats + +tags: +- CPP +- Map +- STL +- Data structures + +description: "This is a solution to the Parties and Seats problem on GeeksForGeeks." +--- + +## Problem Description +Given two arrays, one is array of political parties namely - **party**, and their corresponding array of **seats** received - seats. You have to print the **political parties in lexicographical sorted order** along with their seats, and **highest seats received by the party.** + +**Input Format:** +The first line of input contains **T** denoting the number of testcases. T testcases follow. Each testcase contains three lines of input. The first line contains number of parties **N**. The second line contains the **names** of the parties. The third line contains the **votes** corresponding to each party. + +**Output Format:** +For each testcase, in a new line, print the required answer. + +**User Task:** +Your task is to complete the function **Election2019(party, seats, n)** which accepts three arguments and prints the required result. + +### Examples + +**Example 1:** +``` +Input: +1 +7 +A B C D E F G +90 150 33 23 17 500 2 + +Output: +A 90 +B 150 +C 33 +D 23 +E 17 +F 500 +G 2 +500 +``` + +### Constraints +- `1 ≀ T ≀ 100` +- `1 ≀ N ≀ 26` +- `1 ≀ seats ≀ 543` + + +## Solution for Parties and Seats + +### Code in Different Languages + + + + + + + ```python + def Election2019(party, seats, n): + # Combine party and seats into a list of tuples + v = [(party[i], seats[i]) for i in range(n)] + + # Sort the list by party name + v.sort(key=lambda x: x[0]) + + # Find the maximum seats + max_seats = max(v, key=lambda x: x[1])[1] + + # Print the sorted party and seats + for p, s in v: + print(f"{p} {s}") + + # Print the maximum seats + print(max_seats) + + # Example usage + party = ['A', 'B', 'C', 'A', 'B'] + seats = [10, 20, 30, 15, 25] + n = len(party) + Election2019(party, seats, n) + ``` + + + + + + + ``` + import java.util.*; + + public class Main { + public static void Election2019(char[] party, int[] seats, int n) { + // Create a list of pairs + List> v = new ArrayList<>(); + for (int i = 0; i < n; i++) { + v.add(new AbstractMap.SimpleEntry<>(String.valueOf(party[i]), seats[i])); + } + + // Sort the list by party name + v.sort(Comparator.comparing(AbstractMap.SimpleEntry::getKey)); + + // Find the maximum seats + int max_seats = Collections.max(v, Comparator.comparing(AbstractMap.SimpleEntry::getValue)).getValue(); + + // Print the sorted party and seats + for (AbstractMap.SimpleEntry entry : v) { + System.out.println(entry.getKey() + " " + entry.getValue()); + } + + // Print the maximum seats + System.out.println(max_seats); + } + + public static void main(String[] args) { + char[] party = {'A', 'B', 'C', 'A', 'B'}; + int[] seats = {10, 20, 30, 15, 25}; + int n = party.length; + Election2019(party, seats, n); + } + } + ``` + + + + + + + ```cpp + void Election2019(char party[], int seats[], int n) + { + //Your code here + vector> v; + for (int i = 0; i < n; i++) { + string s(1, party[i]); + v.push_back({s, seats[i]}); + } + sort(v.begin(), v.end()); + int max_seats = max_element(v.begin(), v.end(), [](pair a, pair b) { + return a.second < b.second; + })->second; + for (auto x : v) { + cout << x.first << " " << x.second << endl; + } + cout << max_seats << endl; + } + ``` + + + + +## References + +- **GeekForGeeks Problem**: [Parties and Seats](https://www.geeksforgeeks.org/problems/parties-and-seats/0) \ No newline at end of file diff --git a/solutions/gfg-solutions/Basic/0105.md b/solutions/gfg-solutions/Basic/0105.md new file mode 100644 index 0000000..3e42ded --- /dev/null +++ b/solutions/gfg-solutions/Basic/0105.md @@ -0,0 +1,110 @@ +--- +id: celsius-to-fahrenheit-conversion +title: Celsius to Fahrenheit Conversion +sidebar_label: 0105 Celsius to Fahrenheit Conversion + +tags: +- CPP +- Mathematical +- Algorithms + +description: "This is a solution to the Celsius to Fahrenheit Conversion problem on GeeksForGeeks." +--- + +## Problem Description +Given a temperature in celsius **C**. You have to convert it in **Fahrenheit**. + +### Examples + +**Example 1:** +``` +Input: +C = 32 + +Output: +89.60 + +Explanation: +For 32 degree C temperature +in farenheit = 89.60 +``` + +**Example 2:** +``` +Input: +C = 25 + +Output: +77.00 + +Explanation: +For 25 degree C temperature +in farenheit = 77. +``` + +### Constraints +- `1 ≀ C ≀ 100000` + + +## Solution for Celsius to Fahrenheit Conversion + +### Code in Different Languages + + + + + + + ```python + class Solution: + def celciusToFahrenheit(self, C: int) -> float: + # code here + return C * 9 / 5 + 32 + + # Example usage + solution = Solution() + print(solution.celciusToFahrenheit(0)) # 32.0 + print(solution.celciusToFahrenheit(100)) # 212.0 + ``` + + + + + + + ``` + class Solution { + public double celciusToFahrenheit(int C) { + // code here + return (double) C * 9 / 5 + 32; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.celciusToFahrenheit(0)); // 32.0 + System.out.println(solution.celciusToFahrenheit(100)); // 212.0 + } + } + ``` + + + + + + + ```cpp + class Solution{ + public: + double celciusToFahrenheit(int C){ + //code here + return (double) C * 9 / 5 + 32; + } + }; + ``` + + + + +## References + +- **GeekForGeeks Problem**: [Celsius to Fahrenheit Conversion](https://www.geeksforgeeks.org/problems/celsius-to-fahrenheit-conversion5212/1) diff --git a/solutions/gfg-solutions/Easy problems/Arithmetic-Number.md b/solutions/gfg-solutions/Easy problems/Arithmetic-Number.md new file mode 100644 index 0000000..72974b7 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Arithmetic-Number.md @@ -0,0 +1,146 @@ +--- +id: arithmetic-number +title: Arithmetic Number +sidebar_label: Arithmetic-Number +tags: + - Intermediate + - Array + - Mathematical + - GeeksforGeeks + - CPP + - Python + - DSA +description: "This tutorial covers the solution to the Find the Arithmetic Number problem from the GeeksforGeeks." +--- +## Problem Description + +Given three integers `'A'` denoting the first term of an arithmetic sequence , `'C'` denoting the common difference of an arithmetic sequence and an integer `'B'`. you need to tell whether `'B'` exists in the arithmetic sequence or not. Return `1` if `B` is present in the sequence. Otherwise, returns `0`. + +## Examples + +**Example 1:** + +``` +Input: A = 1, B = 3, C = 2 +Output: 1 +Explaination: 3 is the second term of the +sequence starting with 1 and having a common +difference 2. +``` + +**Example 2:** + +``` +Input: A = 1, B = 2, C = 3 +Output: 0 +Explaination: 2 is not present in the sequence. +``` + +## Your Task + +You do not need to read input or print anything. Your task is to complete the function inSequence() which takes A, B and C and returns 1 if B is present in the sequence. Otherwise, returns 0. + +Expected Time Complexity: $O(1)$ + +Expected Auxiliary Space: $O(1)$ + +## Constraints + +* `-10^9 ≀ A, B, C ≀ 10^9` + +## Problem Explanation +Given three integers 'A' denoting the first term of an arithmetic sequence , 'C' denoting the common difference of an arithmetic sequence and an integer 'B'. you need to tell whether 'B' exists in the arithmetic sequence or not. Return 1 if B is present in the sequence. Otherwise, returns 0. + + +## Code Implementation + + + + + + ```py + def is_present(A, C, B): + if (B - A) % C == 0 and (B - A) / C >= 0: + return 1 + return 0 + + + ``` + + + + + + ```cpp + int isPresent(int A, int C, int B) { + if ((B - A) % C == 0 && (B - A) / C >= 0) { + return 1; + } + return 0; +} + + ``` + + + + + + + ```javascript + function isPresent(A, C, B) { + if ((B - A) % C === 0 && (B - A) / C >= 0) { + return 1; + } + return 0; +} + + + ``` + + + + + + + ```typescript +function isPresent(A, C, B) { + if ((B - A) % C === 0 && (B - A) / C >= 0) { + return 1; + } + return 0; +} + + ``` + + + + + + + ```java + public int isPresent(int A, int C, int B) { + if ((B - A) % C == 0 && (B - A) / C >= 0) { + return 1; + } + return 0; +} + + + ``` + + + + + +## Solution Logic: +The solution checks if the difference between B and A is a multiple of C (the common difference) and if the result is non-negative. If both conditions are true, it means that B is present in the arithmetic sequence. + + +## Time Complexity + +* The time complexity is $O(1)$, because it only involves simple arithmetic operations. + + +## Space Complexity + +* The auxiliary space complexity is $O(1)$ because we are not using any extra space proportional to the size of the input array. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/Array-Leaders.md b/solutions/gfg-solutions/Easy problems/Array-Leaders.md new file mode 100644 index 0000000..7ccdfa2 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Array-Leaders.md @@ -0,0 +1,228 @@ +--- +id: array-leaders +title: Array Leaders +sidebar_label: Array-Leaders +tags: + - Array + - Data Structure +description: "This tutorial covers the solution to the Array Leaders problem from the GeeksforGeeks website." +--- +## Problem Description + +Given an array `arr` of `n` positive integers, your task is to find all the leaders in the array. An element of the array is considered a leader if it is greater than all the elements on its right side or if it is equal to the maximum element on its right side. The rightmost element is always a leader. + +## Examples + +**Example 1:** + +``` +Input: +arr = [16, 17, 4, 3, 5, 2] +Output: 17, 5, 2 +Explanation: The leaders are 17, 5, and 2. +``` + +**Example 2:** + +``` +Input: +arr = [1, 2, 3, 4, 0] +Output: 4, 0 +Explanation: The leaders are 4 and 0. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `leaders()` which takes the array `arr[]` and its size `n` as input parameters and returns a list of integers containing the leaders in the array. + +Expected Time Complexity: $O(n)$ + +Expected Auxiliary Space: $O(n)$ + +## Constraints + +* `1 ≀ n ≀ 10^7` +* `0 ≀ arr[i] ≀ 10^7` + +## Problem Explanation + +The task is to find all the leaders in the array, where a leader is an element that is greater than or equal to all the elements to its right. The rightmost element is always a leader. + +## Code Implementation + + + + + + ```python + class Solution: + def leaders(self, arr, n): + leaders = [] + max_from_right = arr[-1] + leaders.append(max_from_right) + + for i in range(n-2, -1, -1): + if arr[i] >= max_from_right: + leaders.append(arr[i]) + max_from_right = arr[i] + + return leaders[::-1] + + # Example usage + if __name__ == "__main__": + solution = Solution() + arr = [16, 17, 4, 3, 5, 2] + print(solution.leaders(arr, len(arr))) # Expected output: [17, 5, 2] + ``` + + + + + + ```cpp + //{ Driver Code Starts + #include + using namespace std; + + // } Driver Code Ends + class Solution { + public: + vector leaders(int n, int arr[]) { + vector leaders; + int max_from_right = arr[n-1]; + leaders.push_back(max_from_right); + + for (int i = n-2; i >= 0; i--) { + if (arr[i] >= max_from_right) { + leaders.push_back(arr[i]); + max_from_right = arr[i]; + } + } + + reverse(leaders.begin(), leaders.end()); + return leaders; + } + }; + + //{ Driver Code Starts. + int main() { + long long t; + cin >> t; // testcases + while (t--) { + long long n; + cin >> n; // total size of array + + int arr[n]; + + // inserting elements in the array + for (long long i = 0; i < n; i++) { + cin >> arr[i]; + } + Solution obj; + // calling leaders() function + vector v = obj.leaders(n, arr); + + // printing elements of the vector + for (auto it = v.begin(); it != v.end(); it++) { + cout << *it << " "; + } + + cout << endl; + } + } + // } Driver Code Ends + ``` + + + + + + + ```javascript + class Solution { + leaders(arr, n) { + let leaders = []; + let maxFromRight = arr[n - 1]; + leaders.push(maxFromRight); + for (let i = n - 2; i >= 0; i--) { + if (arr[i] >= maxFromRight) { + leaders.push(arr[i]); + maxFromRight = arr[i]; + } + } + return leaders.reverse(); + } +} + + ``` + + + + + + + ```typescript +class Solution { + leaders(arr: number[], n: number): number[] { + let leaders: number[] = []; + let maxFromRight: number = arr[n - 1]; + leaders.push(maxFromRight); + for (let i: number = n - 2; i >= 0; i--) { + if (arr[i] >= maxFromRight) { + leaders.push(arr[i]); + maxFromRight = arr[i]; + } + } + return leaders.reverse(); + } +} + + + ``` + + + + + + + ```java +import java.util.ArrayList; +import java.util.Collections; + +public class Solution { + public ArrayList leaders(ArrayList arr, int n) { + ArrayList leaders = new ArrayList(); + int maxFromRight = arr.get(n - 1); + leaders.add(maxFromRight); + for (int i = n - 2; i >= 0; i--) { + if (arr.get(i) >= maxFromRight) { + leaders.add(arr.get(i)); + maxFromRight = arr.get(i); + } + } + Collections.reverse(leaders); + return leaders; + } +} + + ``` + + + + + +## Solution Logic: + +1. Traverse the array from right to left. +2. Keep track of the maximum element encountered so far. +3. If the current element is greater than or equal to the maximum element, it is a leader. +4. Add the leader to the result list and update the maximum element. +5. Return the result list in reverse order. + +## Time Complexity + +* The function iterates through the array once, so the time complexity is $O(n)$. + +## Space Complexity + +* The function uses additional space for the result list, so the auxiliary space complexity is $O(n)$. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/Balanced_Tree_check.md b/solutions/gfg-solutions/Easy problems/Balanced_Tree_check.md new file mode 100644 index 0000000..3c49ac1 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Balanced_Tree_check.md @@ -0,0 +1,187 @@ +--- +id: balanced-tree-check +title: Balanced Tree Check +sidebar_label: Balanced Tree Check +tags: + - Easy + - Binary Tree + - Tree + - Recursion + - C++ +description: "This is a solution to the Balanced Tree Check problem." +--- + +This tutorial contains a complete walk-through of the Balanced Tree Check problem. It features the implementation of the solution code in C++. + +## Problem Description + +Given a binary tree, find if it is height balanced or not. A tree is height balanced if the difference between the heights of left and right subtrees is not more than one for all nodes of the tree. + +## Examples + +**Example 1:** + +``` +Input: + 1 + / \ + 2 3 + / + 4 +Output: 1 (true) +Explanation: The given tree is balanced as the height difference between the left and right subtrees is not more than one. +``` + +**Example 2:** + +``` +Input: + 10 + / \ + 20 30 + / \ + 40 60 + \ + 70 +Output: 0 (false) +Explanation: The given tree is not balanced as the height difference between the left and right subtrees is more than one. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `isBalanced()` which takes the root node of the tree as input and returns `true` if the tree is balanced, otherwise `false`. + +Expected Time Complexity: O(N) + +Expected Auxiliary Space: O(h) where h is the height of the tree. + +## Constraints + +* 1 ≀ Number of nodes ≀ 10^5 +* 1 ≀ Data of a node ≀ 10^5 + +## Problem Explanation + +The problem is to check if a given binary tree is height balanced. A tree is height balanced if, for every node, the difference between the heights of the left and right subtrees is not more than one. + +## Code Implementation + +```cpp +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends + +struct Node { + int data; + Node* left; + Node* right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; + +class Solution { + public: + // Helper function to check if tree is balanced and to return its height + pair isBalancedHelper(Node* root) { + // Base case: An empty tree is balanced and its height is 0 + if (root == NULL) { + return {true, 0}; + } + + // Recursively check the left and right subtrees + auto left = isBalancedHelper(root->left); + auto right = isBalancedHelper(root->right); + + // The tree is balanced if the left and right subtrees are balanced and + // the height difference between the left and right subtrees is not more than 1 + bool balanced = left.first && right.first && abs(left.second - right.second <= 1); + + // Height of the current tree is 1 plus the maximum of the heights of the left and right subtrees + int height = max(left.second, right.second) + 1; + + return {balanced, height}; + } + + // Function to check whether a binary tree is balanced or not. + bool isBalanced(Node* root) { + return isBalancedHelper(root).first; + } +}; + +//{ Driver Code Starts. + +int main() { + int t; + cin >> t; + while (t--) { + int n; + cin >> n; + + unordered_map m; + Node* root = NULL; + + while (n--) { + int n1, n2; + char lr; + cin >> n1 >> n2 >> lr; + + Node* parent; + if (m.find(n1) == m.end()) { + parent = new Node(n1); + m[n1] = parent; + if (root == NULL) root = parent; + } else { + parent = m[n1]; + } + + Node* child = new Node(n2); + if (lr == 'L') parent->left = child; + else parent->right = child; + + m[n2] = child; + } + + Solution obj; + cout << obj.isBalanced(root) << endl; + } + return 0; +} +// } Driver Code Ends +``` + +## Example Walkthrough + +For the given example: + +Input: +``` + 1 + / \ + 2 3 + / + 4 +``` +The function should return `true` because the given tree is balanced as the height difference between the left and right subtrees is not more than one. + +## Solution Logic + +1. Define a helper function `isBalancedHelper` that returns a pair consisting of a boolean (whether the tree is balanced) and an integer (the height of the tree). +2. In the helper function, recursively check the left and right subtrees. +3. Determine if the current tree is balanced by checking if the left and right subtrees are balanced and if their height difference is not more than 1. +4. Return the balanced status and height of the current tree. +5. The main function `isBalanced` calls the helper function and returns the balanced status. + +## Time Complexity + +* The time complexity is O(N) where N is the number of nodes in the tree. + +## Space Complexity + +* The auxiliary space complexity is O(h) where h is the height of the tree, due to the recursive call stack. + **gfg Problem:** [gfg Problem](https://www.geeksforgeeks.org/problems/check-for-balanced-tree/1?page=1&difficulty=Easy&sortBy=submissions) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/Binary-Search.md b/solutions/gfg-solutions/Easy problems/Binary-Search.md new file mode 100644 index 0000000..a683235 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Binary-Search.md @@ -0,0 +1,178 @@ +--- +id: binary-search +title: Binary Search +sidebar_label: Binary-Search +tags: + - Modular Arithmetic + - Algorithms +description: "This tutorial covers the solution to the Count Digits problem from the GeeksforGeeks." +--- +## Problem Description +Given a sorted array `arr` and an integer `k`, find the position(0-based indexing) at which `k` is present in the array using binary search. when divided. + +## Examples + +**Example 1:** + +``` +Input: k = 4, arr= [1, 2, 3, 4, 5] +Output: 3 +Explanation: 4 appears at index 3. +``` + +**Example 2:** + +``` +Input: k = 445, arr= [11, 22, 33, 44, 55] +Output: -1 +Explanation: 445 is not present. +``` + + +Expected Time Complexity: O(logn) + +Expected Auxiliary Space: O(logn) + +## Constraints + +* `1 ≀ N ≀ 10^5` + +## Problem Explanation + +The task is to traverse the array and search the number. + +## Code Implementation + +### C++ Solution + +```cpp + +#include +#include + +int binarySearch(const std::vector& arr, int k) { + int low = 0; + int high = arr.size() - 1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (arr[mid] == k) { + return mid; + } else if (arr[mid] < k) { + low = mid + 1; + } else { + high = mid - 1; + } + } + return -1; // return -1 if k is not found in the array +} +int main() { + std::vector arr = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + int k = 5; + int position = binarySearch(arr, k); + if (position != -1) { + std::cout << "Element " << k << " is present at position " << position << std::endl; + } else { + std::cout << "Element " << k << " is not present in the array" << std::endl; + } + return 0; +} + + + + +``` + +```java +import java.util.*; + +public class Main { + public static int binarySearch(int[] arr, int k) { + int low = 0; + int high = arr.length - 1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (arr[mid] == k) { + return mid; + } else if (arr[mid] < k) { + low = mid + 1; + } else { + high = mid - 1; + } + } + return -1; // return -1 if k is not found in the array + } + public static void main(String[] args) { + int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + int k = 5; + int position = binarySearch(arr, k); + if (position != -1) { + System.out.println("Element " + k + " is present at position " + position); + } else { + System.out.println("Element " + k + " is not present in the array"); + } + } +} + + +``` + +```python + +def binary_search(arr, k): + low = 0 + high = len(arr) - 1 + while low <= high: + mid = low + (high - low) // 2 + if arr[mid] == k: + return mid + elif arr[mid] < k: + low = mid + 1 + else: + high = mid - 1 + return -1 # return -1 if k is not found in the array + +arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] +k = 5 +position = binary_search(arr, k) +if position != -1: + print("Element {} is present at position {}".format(k, position)) +else: + print("Element {} is not present in the array".format(k)) + + +``` + +```javascript +function binarySearch(arr, k) { + let low = 0; + let high = arr.length - 1; + while (low <= high) { + let mid = Math.floor(low + (high - low) / 2); + if (arr[mid] === k) { + return mid; + } else if (arr[mid] < k) { + low = mid + 1; + } else { + high = mid - 1; + } + } + return -1; // return -1 if k is not found in the array +} + + +``` + +## Solution Logic: +This solution uses binary search to find the position of k in the sorted array. It starts by considering the middle element of the array. If the middle element is equal to k, it returns the position of the middle element. If the middle element is less than k, it repeats the process for the right half of the array. If the middle element is greater than k, it repeats the process for the left half of the array. + + + + +## Time Complexity + +* The time complexity is $O(log(n))$ where n is the input number. + + +## Space Complexity + +* The auxiliary space complexity is $O(1)$ due to the only extra memory used is for temporary variables while swapping two values in Array. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/Bubble-Sort.md b/solutions/gfg-solutions/Easy problems/Bubble-Sort.md new file mode 100644 index 0000000..aca6862 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Bubble-Sort.md @@ -0,0 +1,263 @@ +--- +id: bubble-sort +title: Bubble Sort +sidebar_label: Bubble-Sort +tags: + - Sorting + - Algorithms +description: "This tutorial covers the solution to the Bubble Sort problem from the GeeksforGeeks." +--- +## Problem Description + +Given an unsorted array of size `N`, use bubblesort to sort `arr[]` in increasing order. + +## Examples + +**Example 1:** + +``` +Input: +N = 5 +arr[] = {4, 1, 3, 9, 7} +Output: +1 3 4 7 9 +``` + +**Example 2:** + +``` +Input: +N = 10 +arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1} +Output: +1 2 3 4 5 6 7 8 9 10 +``` + +## Your Task +You don't have to read input or print anything. Your task is to complete the function bubblesort() which takes the array and it's size as input and sorts the array using bubble sort algorithm. + +Expected Time Complexity: O(N^2) + +Expected Auxiliary Space: O(1) + +## Constraints + +* `1 ≀ N ≀ 10^3` + +## Problem Explanation + +The task is to traverse the array and sort the array using bubble sort. + +## Code Implementation + +### C++ Solution + +```cpp +// Optimized implementation of Bubble sort +#include +using namespace std; + +// An optimized version of Bubble Sort +void bubbleSort(int arr[], int n) +{ + int i, j; + bool swapped; + for (i = 0; i < n - 1; i++) { + swapped = false; + for (j = 0; j < n - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + swap(arr[j], arr[j + 1]); + swapped = true; + } + } + + // If no two elements were swapped + // by inner loop, then break + if (swapped == false) + break; + } +} + +// Function to print an array +void printArray(int arr[], int size) +{ + int i; + for (i = 0; i < size; i++) + cout << " " << arr[i]; +} + +// Driver program to test above functions +int main() +{ + int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; + int N = sizeof(arr) / sizeof(arr[0]); + bubbleSort(arr, N); + cout << "Sorted array: \n"; + printArray(arr, N); + return 0; +} + + +``` + +```java +// Optimized java implementation of Bubble sort + +import java.io.*; + +class GFG { + + // An optimized version of Bubble Sort + static void bubbleSort(int arr[], int n) + { + int i, j, temp; + boolean swapped; + for (i = 0; i < n - 1; i++) { + swapped = false; + for (j = 0; j < n - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + + // Swap arr[j] and arr[j+1] + temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + swapped = true; + } + } + + // If no two elements were + // swapped by inner loop, then break + if (swapped == false) + break; + } + } + + // Function to print an array + static void printArray(int arr[], int size) + { + int i; + for (i = 0; i < size; i++) + System.out.print(arr[i] + " "); + System.out.println(); + } + + // Driver program + public static void main(String args[]) + { + int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; + int n = arr.length; + bubbleSort(arr, n); + System.out.println("Sorted array: "); + printArray(arr, n); + } +} + + + +``` + +```python +# Optimized Python program for implementation of Bubble Sort + + +def bubbleSort(arr): + n = len(arr) + + # Traverse through all array elements + for i in range(n): + swapped = False + + # Last i elements are already in place + for j in range(0, n-i-1): + + # Traverse the array from 0 to n-i-1 + # Swap if the element found is greater + # than the next element + if arr[j] > arr[j+1]: + arr[j], arr[j+1] = arr[j+1], arr[j] + swapped = True + if (swapped == False): + break + + +# Driver code to test above +if __name__ == "__main__": + arr = [64, 34, 25, 12, 22, 11, 90] + + bubbleSort(arr) + + print("Sorted array:") + for i in range(len(arr)): + print("%d" % arr[i], end=" ") + + + +``` + +```javascript +// Optimized javaScript implementation +// of Bubble sort +// An optimized version of Bubble Sort +function bubbleSort(arr, n) +{ + var i, j, temp; + var swapped; + for (i = 0; i < n - 1; i++) + { + swapped = false; + for (j = 0; j < n - i - 1; j++) + { + if (arr[j] > arr[j + 1]) + { + // Swap arr[j] and arr[j+1] + temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + swapped = true; + } + } + + // IF no two elements were + // swapped by inner loop, then break + if (swapped == false) + break; + } +} + +// Function to print an array +function printArray(arr, size) +{ + var i; + for (i = 0; i < size; i++) + console.log(arr[i] + " "); +} + +// Driver program +var arr = [ 64, 34, 25, 12, 22, 11, 90 ]; +var n = arr.length; +bubbleSort(arr, n); +console.log("Sorted array: "); +printArray(arr, n); + + + +``` + +## Solution Logic: + +1. The largest element is placed in its correct position, i.e., the end of the array. + +2. Place the second largest element at correct position + +3. Place the remaining two elements at their correct positions. + +4. Total no. of passes: n-1. Total no. of comparisons: n*(n-1)/2 + + +## Time Complexity + +* The time complexity is $O(N^2)$ as there are two nested loops + +## Space Complexity + +* The auxiliary space complexity is $O(1)$ due to the only extra memory used is for temporary variables while swapping two values in Array. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/Check-Equal-Arrays.md b/solutions/gfg-solutions/Easy problems/Check-Equal-Arrays.md new file mode 100644 index 0000000..ab394bc --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Check-Equal-Arrays.md @@ -0,0 +1,106 @@ +--- +id: check-equal-arrays +title: Check Equal Arrays +sidebar_label: Check-Equal-Arrays +tags: + - Modular Arithmetic + - Algorithms +description: "This tutorial covers the solution to the Check Equal Arrays problem from the GeeksforGeeks." +--- +## Problem Description +Given two arrays `arr1` and `arr2` of equal size, the task is to find whether the given arrays are equal. Two arrays are said to be equal if both contain the same set of elements, arrangements (or permutations) of elements may be different though. +Note: If there are repetitions, then counts of repeated elements must also be the same for two arrays to be equal. + +## Examples + +**Example 1:** + +``` +Input: arr1[] = [1, 2, 5, 4, 0], arr2[] = [2, 4, 5, 0, 1] +Output: true +Explanation: Both the array can be rearranged to [0,1,2,4,5] +``` + +**Example 2:** + +``` +Input: arr1[] = [1, 2, 5], arr2[] = [2, 4, 15] +Output: false +Explanation: arr1[] and arr2[] have only one common value. +``` + + +Expected Time Complexity: O(n) + +Expected Auxiliary Space: O(n) + +## Constraints + +* `1<= arr1.size, arr2.size<=10^7` + +## Problem Explanation + +The task is to traverse the array and search the number. + +## Code Implementation + +### C++ Solution + +```cpp + +#include +#include + +bool areEqual(std::vector arr1, std::vector arr2) { + std::sort(arr1.begin(), arr1.end()); + std::sort(arr2.begin(), arr2.end()); + return arr1 == arr2; +} + + +``` + +```java +import java.util.Arrays; + +public class Main { + public static boolean areEqual(int[] arr1, int[] arr2) { + Arrays.sort(arr1); + Arrays.sort(arr2); + return Arrays.equals(arr1, arr2); + } +} + + + +``` + +```python + +def are_equal(arr1, arr2): + return sorted(arr1) == sorted(arr2) +``` + +```javascript + +function areEqual(arr1, arr2) { + return arr1.sort((a, b) => a - b).every((value, index) => value === arr2.sort((a, b) => a - b)[index]); +} + + +``` + +## Solution Logic: +In the solution, the arrays are sorted and then compared. If the sorted arrays are equal, then the original arrays contain the same set of elements, regardless of order. Note that this approach assumes that the arrays contain only elements that can be compared using the default comparison operators (e.g., numbers, strings). If the arrays contain custom objects, a custom comparison functionΒ mayΒ beΒ needed. + + + + +## Time Complexity + +* The time complexity is $O(log(n))$ where n is the input number. + + +## Space Complexity + +* The auxiliary space complexity is $O(1)$ due to the only extra memory used is for temporary variables while swapping two values in Array. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/Common-in-3-Sorted-Array.md b/solutions/gfg-solutions/Easy problems/Common-in-3-Sorted-Array.md new file mode 100644 index 0000000..470968c --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Common-in-3-Sorted-Array.md @@ -0,0 +1,186 @@ +--- +id: common-in-3-sorted-arrays +title: Common In 3 Sorted Arrays +sidebar_label: Common-In-3-Sorted-Arrays +tags: + - Searching + - Algorithms +description: "This tutorial covers the solution to the Common in 3 sorted arrays problem from the GeeksforGeeks." +--- +## Problem Description + +You are given three arrays sorted in increasing order. Find the elements that are common in all three arrays. +If there are no such elements return an empty array. In this case, the output will be -1. + +## Examples + +**Example 1:** + +``` +Input: arr1 = [1, 5, 10, 20, 40, 80] , arr2 = [6, 7, 20, 80, 100] , arr3 = [3, 4, 15, 20, 30, 70, 80, 120] +Output: [20, 80] +Explanation: 20 and 80 are the only common elements in arr, brr and crr. +``` + +**Example 2:** + +``` +Input: arr1 = [1, 2, 3, 4, 5] , arr2 = [6, 7] , arr3 = [8,9,10] +Output: [-1] +Explanation: There are no common elements in arr, brr and crr. +``` + + +Expected Time Complexity: O(n) + +Expected Auxiliary Space: O(n) + +## Constraints + +* `-10^5 <= arr1i , arr2i , 1arr3i <= 10^5` + +## Problem Explanation + +The task is to traverse the arrays and find the common element. + +## Code Implementation + +### C++ Solution + +```cpp + +#include +#include + +std::vector commonElements(std::vector arr1, std::vector arr2, std::vector arr3) { + std::vector result; + int i = 0, j = 0, k = 0; + while (i < arr1.size() && j < arr2.size() && k < arr3.size()) { + if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) { + result.push_back(arr1[i]); + i++; + j++; + k++; + } else { + if (arr1[i] <= arr2[j] && arr1[i] <= arr3[k]) { + i++; + } else if (arr2[j] <= arr1[i] && arr2[j] <= arr3[k]) { + j++; + } else { + k++; + } + } + } + + return result; +} + + +``` + +```java +import java.util.ArrayList; +import java.util.List; + +public class Main { + public static List commonElements(List arr1, List arr2, List arr3) { + List result = new ArrayList<>(); + int i = 0, j = 0, k = 0; + while (i < arr1.size() && j < arr2.size() && k < arr3.size()) { + if (arr1.get(i) == arr2.get(j) && arr2.get(j) == arr3.get(k)) { + result.add(arr1.get(i)); + i++; + j++; + k++; + } else { + if (arr1.get(i) <= arr2.get(j) && arr1.get(i) <= arr3.get(k)) { + i++; + } else if (arr2.get(j) <= arr1.get(i) && arr2.get(j) <= arr3.get(k)) { + j++; + } else { + k++; + } + } + } + + return result; + } +} + + + + +``` + +```python + +def commonElements(arr1, arr2, arr3): + result = [] + i = j = k = 0 + + while i < len(arr1) and j < len(arr2) and k < len(arr3): + if arr1[i] == arr2[j] == arr3[k]: + result.append(arr1[i]) + i += 1 + j += 1 + k += 1 + else: + if arr1[i] <= arr2[j] and arr1[i] <= arr3[k]: + i += 1 + elif arr2[j] <= arr1[i] and arr2[j] <= arr3[k]: + j += 1 + else: + k += 1 + + return result + + +``` + +```javascript +function commonElements(arr1, arr2, arr3) { + const result = []; + const i = j = k = 0; + + while (i < arr1.length && j < arr2.length && k < arr3.length) { + if (arr1[i] === arr2[j] && arr2[j] === arr3[k]) { + result.push(arr1[i]); + i++; + j++; + k++; + } else { + if (arr1[i] <= arr2[j] && arr1[i] <= arr3[k]) { + i++; + } else if (arr2[j] <= arr1[i] && arr2[j] <= arr3[k]) { + j++; + } else { + k++; + } + } + } + + return result.length ? result : [-1]; +} + + +``` + +## Solution Logic: + +1. Initialize three pointers, one for each array, at the beginning of the arrays. +2. Compare the elements at the current pointers. If they are equal, add the element to the result array and increment all three pointers. +3. If the elements are not equal, increment the pointer of the array with the smallest current element. +4. Repeat steps 2-3 until one of the arrays is exhausted. +5. Return the result array. + + + +## Time Complexity + +* The time complexity is $O(N^2)$ where n is the length of the shortest array. This is because in the worst case, we need to iterate through all elements of the shortest array. + + +## Space Complexity + +* The auxiliary space complexity is $O(m)$ where m is the number of common elements found. This is because we store the common elements in the result array. + diff --git a/solutions/gfg-solutions/Easy problems/Faithful-Numbers.md b/solutions/gfg-solutions/Easy problems/Faithful-Numbers.md new file mode 100644 index 0000000..7a2f729 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Faithful-Numbers.md @@ -0,0 +1,213 @@ +--- +id: faithful-numbers +title: Faithful Numbers +sidebar_label: Faithful-Numbers +tags: + - Array + - Data Structure +description: "This tutorial covers the solution to the Faithful Numbers problem from the GeeksforGeeks website." +--- +## Problem Description + +A number is called faithful if you can write it as the sum of distinct powers of 7. +e.g., `2457 = 7 + 72 + 74` . If we order all the faithful numbers, we get the sequence `1 = 70`, `7 = 71`, `8 = 70 + 71`, `49 = 72`, `50 = 70 + 72` . . . and so on. +Given some value of `N`, you have to find the N'th faithful number. + +## Examples + +**Example 1:** + +``` +Input: +N = 3 +Output: +8 +Explanation: +8 is the 3rd Faithful number. +``` + +**Example 2:** + +``` +Input: +N = 7 +Output: +57 +Explanation: +57 is the 7th Faithful number. +``` + +## Your Task +You don't need to read input or print anything. Your task is to complete the function `nthFaithfulNum()` which takes an Integer N as input and returns the answer. + + +Expected Time Complexity: $O(log(n))$ + +Expected Auxiliary Space: $O(log(n))$ + +## Constraints + +* `1 ≀ n ≀ 10^5` + +## Problem Explanation +A number is called faithful if you can write it as the sum of distinct powers of 7. +e.g., `2457 = 7 + 72 + 74` . If we order all the faithful numbers, we get the sequence `1 = 70`, `7 = 71`, `8 = 70 + 71`, `49 = 72`, `50 = 70 + 72` . . . and so on. +Given some value of `N`, you have to find the N'th faithful number. + + +## Code Implementation + + + + + + ```python + +def get_nth_faithful_number(n): + faithful_numbers = [] + power = 0 + while len(faithful_numbers) < n: + num = 7 ** power + faithful_numbers.append(num) + for i in range(len(faithful_numbers) - 1): + faithful_numbers.append(num + faithful_numbers[i]) + power += 1 + return faithful_numbers[n - 1] + +n = int(input("Enter the value of N: ")) +print("The {}th faithful number is: {}".format(n, get_nth_faithful_number(n))) + + ``` + + + + + + ```cpp +#include +#include +#include + +int getNthFaithfulNumber(int n) { + std::vector faithfulNumbers; + int power = 0; + while (faithfulNumbers.size() < n) { + int num = pow(7, power); + faithfulNumbers.push_back(num); + for (int i = 0; i < faithfulNumbers.size() - 1; i++) { + faithfulNumbers.push_back(num + faithfulNumbers[i]); + } + power++; + } + return faithfulNumbers[n - 1]; +} +int main() { + int n; + std::cout << "Enter the value of N: "; + std::cin >> n; + std::cout << "The " << n << "th faithful number is: " << getNthFaithfulNumber(n) << std::endl; + return 0; +} + + ``` + + + + + + + ```javascript + function getNthFaithfulNumber(n) { + let faithfulNumbers = []; + let power = 0; + while (faithfulNumbers.length < n) { + let num = Math.pow(7, power); + faithfulNumbers.push(num); + for (let i = 0; i < faithfulNumbers.length - 1; i++) { + faithfulNumbers.push(num + faithfulNumbers[i]); + } + power++; + } + return faithfulNumbers[n - 1]; +} +let n = parseInt(prompt("Enter the value of N:")); +alert("The " + n + "th faithful number is: " + getNthFaithfulNumber(n)); + + + ``` + + + + + + + ```typescript + +function getNthFaithfulNumber(n: number): number { + let faithfulNumbers: number[] = []; + let power: number = 0; + while (faithfulNumbers.length < n) { + let num: number = Math.pow(7, power); + faithfulNumbers.push(num); + for (let i: number = 0; i < faithfulNumbers.length - 1; i++) { + faithfulNumbers.push(num + faithfulNumbers[i]); + } + power++; + } + return faithfulNumbers[n - 1]; +} + +let n: number = parseInt(prompt("Enter the value of N:")); +alert("The " + n + "th faithful number is: " + getNthFaithfulNumber(n)); + + + ``` + + + + + + + ```java +import java.util.*; + +public class Main { + public static int getNthFaithfulNumber(int n) { + List faithfulNumbers = new ArrayList<>(); + int power = 0; + while (faithfulNumbers.size() < n) { + int num = (int) Math.pow(7, power); + faithfulNumbers.add(num); + for (int i = 0; i < faithfulNumbers.size() - 1; i++) { + faithfulNumbers.add(num + faithfulNumbers.get(i)); + } + power++; + } + return faithfulNumbers.get(n - 1); + } + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.print("Enter the value of N: "); + int n = scanner.nextInt(); + System.out.println("The " + n + "th faithful number is: " + getNthFaithfulNumber(n)); + } +} + + + ``` + + + + + +## Solution Logic: +This solution works by generating faithful numbers on the fly and storing them in a vector. It starts with the smallest faithful number, 1 (which is 7^0), and then generates larger faithful numbers by adding powers of 7 to the previously generated numbers. + + +## Time Complexity + +* The function iterates through the array once, so the time complexity is $O(n log n)$. + +## Space Complexity + +* The function uses additional space for the result list, so the auxiliary space complexity is $O(n)$. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/Insertion-Sort.md b/solutions/gfg-solutions/Easy problems/Insertion-Sort.md new file mode 100644 index 0000000..1097229 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Insertion-Sort.md @@ -0,0 +1,243 @@ +--- +id: insertion-sort +title: Insertion Sort +sidebar_label: Insertion-Sort +tags: + - Sorting + - Algorithms +description: "This tutorial covers the solution to the Insertion Sort problem from the GeeksforGeeks." +--- +## Problem Description + +The task is to complete the `insert()` function which is used to implement Insertion Sort. + +## Examples + +**Example 1:** + +``` +Input: +N = 5 +arr[] = { 4, 1, 3, 9, 7} +Output: +1 3 4 7 9 +``` + +**Example 2:** + +``` +Input: +N = 10 +arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1} +Output: +1 2 3 4 5 6 7 8 9 10 +``` + +## Your Task +You don't have to read input or print anything. Your task is to complete the function insert() and insertionSort() where insert() takes the array, it's size and an index i and insertionSort() uses insert function to sort the array in ascending order using insertion sort algorithm. + +Expected Time Complexity: O(N^2) + +Expected Auxiliary Space: O(1) + +## Constraints + +* `1 ≀ N ≀ 10^3` + +## Problem Explanation + +The task is to traverse the array and sort the array using insertion sort. + +## Code Implementation + +### C++ Solution + +```cpp +// C++ program for insertion sort + +#include +using namespace std; + +// Function to sort an array using +// insertion sort +void insertionSort(int arr[], int n) +{ + int i, key, j; + for (i = 1; i < n; i++) { + key = arr[i]; + j = i - 1; + + // Move elements of arr[0..i-1], + // that are greater than key, + // to one position ahead of their + // current position + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } +} + +// A utility function to print an array +// of size n +void printArray(int arr[], int n) +{ + int i; + for (i = 0; i < n; i++) + cout << arr[i] << " "; + cout << endl; +} + +// Driver code +int main() +{ + int arr[] = { 12, 11, 13, 5, 6 }; + int N = sizeof(arr) / sizeof(arr[0]); + + insertionSort(arr, N); + printArray(arr, N); + + return 0; +} +``` + +```java +// Java program for implementation of Insertion Sort +public class InsertionSort { + /*Function to sort array using insertion sort*/ + void sort(int arr[]) + { + int n = arr.length; + for (int i = 1; i < n; ++i) { + int key = arr[i]; + int j = i - 1; + + /* Move elements of arr[0..i-1], that are + greater than key, to one position ahead + of their current position */ + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } + } + + /* A utility function to print array of size n*/ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + + System.out.println(); + } + + // Driver method + public static void main(String args[]) + { + int arr[] = { 12, 11, 13, 5, 6 }; + + InsertionSort ob = new InsertionSort(); + ob.sort(arr); + + printArray(arr); + } +}; +``` + +```python +# Python program for implementation of Insertion Sort + +# Function to do insertion sort +def insertionSort(arr): + + # Traverse through 1 to len(arr) + for i in range(1, len(arr)): + + key = arr[i] + + # Move elements of arr[0..i-1], that are + # greater than key, to one position ahead + # of their current position + j = i-1 + while j >= 0 and key < arr[j] : + arr[j + 1] = arr[j] + j -= 1 + arr[j + 1] = key + + +# Driver code to test above +arr = [12, 11, 13, 5, 6] +insertionSort(arr) +for i in range(len(arr)): + print ("% d" % arr[i]) + +``` + +```javascript + + +``` + +## Solution Logic: + +1. We have to start with second element of the array as first element in the array is assumed to be sorted. + +2. Compare second element with the first element and check if the second element is smaller then swap them. + +3. Move to the third element and compare it with the second element, then the first element and swap as necessary to put it in the correct position among the first three elements. + +4. Continue this process, comparing each element with the ones before it and swapping as needed to place it in the correct position among the sorted elements. + +5. Repeat until the entire array is sorted. + +## Time Complexity + +* The time complexity is $O(N^2)$ as there are two nested loops + +## Space Complexity + +* The auxiliary space complexity is $O(1)$ due to the only extra memory used is for temporary variables while swapping two values in Array. The selection sort never makes more than $O(N)$ swaps and can be useful when memory writing is costly. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/Kth-Smallest.md b/solutions/gfg-solutions/Easy problems/Kth-Smallest.md new file mode 100644 index 0000000..ec5894c --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Kth-Smallest.md @@ -0,0 +1,128 @@ +--- +id: kth-smallest +title: Kth Smallest +sidebar_label: Kth-Smallest +tags: + - Sorting + - Algorithms + - Arrays + - Searching +description: "This tutorial covers the solution to the Kth Smallest problem from the GeeksforGeeks." +--- +## Problem Description + +Given an array `arr[]` and an integer `k` where `k` is smaller than the size of the array, the task is to find the `kth` smallest element in the given array. It is given that all array elements are distinct. + +Note:- `l` and `r` denotes the starting and ending index of the array. + +## Examples + +**Example 1:** + +``` +Input: +n = 6 +arr[] = 7 10 4 3 20 15 +k = 3 +l=0 r=5 + +Output : +7 + +Explanation : +3rd smallest element in the given +array is 7. +``` + +**Example 2:** +``` +Input: +n = 5 +arr[] = 7 10 4 20 15 +k = 4 +l=0 r=4 + +Output : +15 + +Explanation : +4th smallest element in the given +array is 15. +``` + +### Your Task +You don't have to read input or print anything. Your task is to complete the function kthSmallest() which takes the array arr[], integers l and r denoting the starting and ending index of the array and an integer k as input and returns the kth smallest element. + +Expected Time Complexity: O(n*log(n)) + +Expected Auxiliary Space: O(1) + +## Constraints + +* `1 ≀ N ≀ 10^5` + +## Problem Explanation + +Given an array `arr[]` and an integer `k` where `k` is smaller than the size of the array, the task is to find the `kth` smallest element in the given array. It is given that all array elements are distinct. + +Note:- `l` and `r` denotes the starting and ending index of the array. + +## Code Implementation + +### C++ Solution + +```cpp +int kthSmallest(int arr[], int l, int r, int k) { + sort(arr + l, arr + r + 1); + return arr[l + k - 1]; +} + + +``` + +```java + +int kthSmallest(int arr[], int l, int r, int k) { + Arrays.sort(arr, l, r + 1); + return arr[l + k - 1]; +} + + +``` + +```python +def kthSmallest(arr, l, r, k): + arr.sort() + return arr[l + k - 1] + + +``` + +```javascript +function kthSmallest(arr, l, r, k) { + arr.sort((a, b) => a - b); + return arr[l + k - 1]; +} + + +``` + +## Solution Logic: + +1. sort(arr + l, arr + r + 1) (C++), arr.sort() (Python, JavaScript, TypeScript): + - Sort the array in ascending order. + - This step is necessary to ensure that the array is in a sorted state, allowing us to easily access the kth smallest element. +2. return arr[l + k - 1]: + - Return the element at the index l + k - 1. + - l is the starting index of the array, k is the position of the element to be found, and -1 is to adjust for zero-based indexing. + - Since the array is sorted in ascending order, the element at this index will be the kth smallest element. + + + +## Time Complexity + +* The time complexity is $O(n*log(n))$ due to the sorting step, where n is the length of the array. + +## Space Complexity + +* The auxiliary space complexity is $O(1)$ due to the only extra memory used is for temporary variables while swapping two values in Array. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/Kth_from_End_of_Linked_List.md b/solutions/gfg-solutions/Easy problems/Kth_from_End_of_Linked_List.md new file mode 100644 index 0000000..7af6eaa --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Kth_from_End_of_Linked_List.md @@ -0,0 +1,199 @@ +--- +id: kth-from-end-of-linked-list +title: Kth from End of Linked List +sidebar_label: 0016 - Kth from End of Linked List +tags: + - Easy + - Linked List + - GeeksforGeeks + - CPP + - Python + - DSA +description: "This tutorial covers the solution to the Kth from End of Linked List problem from the GeeksforGeeks website, featuring implementations in Python and C++." +--- +## Problem Description + +Given the head of a linked list and a number `k`, your task is to find the kth node from the end. If `k` is more than the number of nodes, then the output should be -1. + +## Examples + +**Example 1:** + +``` +Input: +n = 5, k = 2 +value[] = [1, 2, 3, 4, 5] +Output: 4 +Explanation: The 2nd node from the end is 4. +``` + +**Example 2:** + +``` +Input: +n = 3, k = 4 +value[] = [10, 20, 30] +Output: -1 +Explanation: There are only 3 nodes in the linked list, so the 4th node from the end does not exist. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `getKthFromLast()` which takes the head of the linked list and `k` as input parameters and returns the data of the kth node from the end of the linked list. + +Expected Time Complexity: $O(N)$ + +Expected Auxiliary Space: $O(1)$ + +## Constraints + +* `1 ≀ n ≀ 10^5` +* `1 ≀ value[i] ≀ 10^7` +* `1 ≀ k ≀ 10^5` + +## Problem Explanation + +The task is to find the kth node from the end of a linked list. If `k` is greater than the number of nodes in the list, return -1. + +## Code Implementation + + + + + + ```py + class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + class Solution: + def getKthFromLast(self, head: ListNode, k: int) -> int: + fast = slow = head + for _ in range(k): + if not fast: + return -1 + fast = fast.next + + while fast: + slow = slow.next + fast = fast.next + + return slow.val if slow else -1 + + # Example usage + if __name__ == "__main__": + head = ListNode(1) + head.next = ListNode(2) + head.next.next = ListNode(3) + head.next.next.next = ListNode(4) + head.next.next.next.next = ListNode(5) + solution = Solution() + print(solution.getKthFromLast(head, 2)) # Expected output: 4 + ``` + + + + + + ```cpp + //{ Driver Code Starts + #include + using namespace std; + + struct Node { + int data; + struct Node *next; + + Node(int x) { + data = x; + next = NULL; + } + }; + + // } Driver Code Ends + class Solution { + public: + int getKthFromLast(Node *head, int k) { + Node *fast = head, *slow = head; + for (int i = 0; i < k; ++i) { + if (!fast) return -1; + fast = fast->next; + } + while (fast) { + slow = slow->next; + fast = fast->next; + } + return slow ? slow->data : -1; + } + }; + + //{ Driver Code Starts. + + int main() { + int T, i, n, l, k; + + cin >> T; + + while (T--) { + struct Node *head = NULL, *tail = NULL; + + cin >> n >> k; + int firstdata; + cin >> firstdata; + head = new Node(firstdata); + tail = head; + for (i = 1; i < n; i++) { + cin >> l; + tail->next = new Node(l); + tail = tail->next; + } + Solution obj; + cout << obj.getKthFromLast(head, k) << endl; + } + return 0; + } + // } Driver Code Ends + ``` + + + + +## Example Walkthrough + +**Example 1:** + +For the linked list: +``` +1 -> 2 -> 3 -> 4 -> 5 +``` +1. The 2nd node from the end is 4. + +**Example 2:** + +For the linked list: +``` +10 -> 20 -> 30 +``` +1. There are only 3 nodes in the linked list, so the 4th node from the end does not exist, thus the output is -1. + +## Solution Logic: + +1. Use two pointers `fast` and `slow`. +2. Move `fast` pointer `k` steps ahead. +3. Move both pointers until `fast` reaches the end. +4. The `slow` pointer will be at the kth node from the end. +5. Return the value of the `slow` pointer or -1 if `k` is greater than the number of nodes. + +## Time Complexity + +* The function traverses the linked list once, so the time complexity is $O(N)$. + +## Space Complexity + +* The function uses constant space, so the auxiliary space complexity is $O(1)$. + +## References + +- **GeeksforGeeks Problem:** [Kth from End of Linked List](https://www.geeksforgeeks.org/problems/nth-node-from-end-of-linked-list/1) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/Largest-Element-In-Array.md b/solutions/gfg-solutions/Easy problems/Largest-Element-In-Array.md new file mode 100644 index 0000000..05669a8 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Largest-Element-In-Array.md @@ -0,0 +1,122 @@ +--- +id: largest-element-in-array +title: Largest Element In Array +sidebar_label: Largest-Element-In-Array +tags: + - Arrays + - Data Structure +description: "This tutorial covers the solution to the Largest Element In Array problem from the GeeksforGeeks website, featuring implementations in C++." +--- +## Problem Description +Given an array `arr`, the task is to find the largest element in it. + +## Examples + +**Example 1:** + +``` +Input: arr= [1, 8, 7, 56, 90] +Output: 90 +Explanation: The largest element of given array is 90. +``` + +**Example 2:** + +``` +Input: arr = [5, 5, 5, 5] +Output: 5 +Explanation: The largest element of given array is 5. +``` + +## Your Task + +You don't need to read input anything. Your task is to complete the function `largest()` which takes the array `arr` and an size of array as `n` as input parameters and returns the largest number. + +Expected Time Complexity: O(n) + +Expected Auxiliary Space: O(1) + +## Constraints + +* `1 <= arr.size()<= 10^5` + +## Problem Explanation + +The task is to traverse the whole array and find the largest element of that array. + +## Code Implementation + +### C++ Solution + + +```cpp +class Solution +{ +public: + int largest(vector &arr, int n) + { + int maxi = INT_MIN; + for(int i=0; i + + + +```py +def is_lucky(N): + lucky_numbers = list(range(1, N + 1)) + delete_step = 2 + while delete_step <= len(lucky_numbers): + lucky_numbers = [num for i, num in enumerate(lucky_numbers) if (i + 1) % delete_step != 0] + delete_step += 1 + return 1 if N in lucky_numbers else 0 + +``` + + + + + +```cpp +int isLucky(int N) { + vector luckyNumbers; + for (int i = 1; i <= N; i++) { + luckyNumbers.push_back(i); + } + int deleteStep = 2; + while (deleteStep <= luckyNumbers.size()) { + for (int i = deleteStep - 1; i < luckyNumbers.size(); i += deleteStep) { + luckyNumbers.erase(luckyNumbers.begin() + i); + } + deleteStep++; + } + for (int num : luckyNumbers) { + if (num == N) { + return 1; + } + } + return 0; +} + +``` + + + + + + +```javascript +function isLucky(N) { + let luckyNumbers = Array.from({ length: N }, (_, i) => i + 1); + let deleteStep = 2; + while (deleteStep <= luckyNumbers.length) { + luckyNumbers = luckyNumbers.filter((_, i) => (i + 1) % deleteStep !== 0); + deleteStep++; + } + return luckyNumbers.includes(N) ? 1 : 0; +} +``` + + + + + + +```typescript +function isLucky(N) { + let luckyNumbers = Array.from({ length: N }, (_, i) => i + 1); + let deleteStep = 2; + while (deleteStep <= luckyNumbers.length) { + luckyNumbers = luckyNumbers.filter((_, i) => (i + 1) % deleteStep !== 0); + deleteStep++; + } + return luckyNumbers.includes(N) ? 1 : 0; +} +``` + + + + + + +```java +public int isLucky(int N) { + List luckyNumbers = new ArrayList<>(); + for (int i = 1; i <= N; i++) { + luckyNumbers.add(i); + } + int deleteStep = 2; + while (deleteStep <= luckyNumbers.size()) { + for (int i = deleteStep - 1; i < luckyNumbers.size(); i += deleteStep) { + luckyNumbers.remove(i); + } + deleteStep++; + } + for (int num : luckyNumbers) { + if (num == N) { + return 1; + } + } + return 0; +} + + +``` + + + + +## Time Complexity + +- The iterative approach has a time complexity of $O(n^2)$. + +## Space Complexity + +- The space complexity is $O(n)$ since we are using only a fixed amount of extra space. diff --git a/solutions/gfg-solutions/Easy problems/Magic-Numbers.md b/solutions/gfg-solutions/Easy problems/Magic-Numbers.md new file mode 100644 index 0000000..cb46abc --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Magic-Numbers.md @@ -0,0 +1,202 @@ +--- +id: magic-number +title: Magic Number +sidebar_label: Magic-Number +tags: + - Easy + - Dynamic Programming + - Math +description: "This tutorial covers the solution to the Magic Number problem from the GeeksforGeeks." +--- +## Problem Description +A magic number is defined as a number that can be expressed as a power of 5 or sum of unique powers of `5`. First few magic numbers are `5`, `25`, `30(5 + 25)`, `125`, `130(125 + 5)`, … +Given the value of `n`, find the `n`'th Magic number modulo `109+7`. + +## Examples + +**Example 1:** + +``` +Input: n = 1 +Output: 5 +Explanation: 1'st Magic number is 5. +``` + +**Example 2:** + +``` +Input: n = 2 +Output: 25 +Explanation: 2'nd Magic number is 25. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `nthMagicNo()` which takes n input and returns the answer with modulo `10^9+7`. + +Expected Time Complexity: $O(log(n))$ + +Expected Auxiliary Space: $O(1)$ for iterative approach. + +## Constraints + +* `1 ≀ n ≀ 10^5` + +## Problem Explanation +A magic number is defined as a number that can be expressed as a power of 5 or sum of unique powers of `5`. First few magic numbers are `5`, `25`, `30(5 + 25)`, `125`, `130(125 + 5)`, … +Given the value of `n`, find the `n`'th Magic number modulo `109+7`. + +## Code Implementation + + + + + + ```py + def get_nth_magic_number(n): + magic_numbers = [] + power = 0 + while len(magic_numbers) < n: + num = 5 ** power + magic_numbers.append(num) + for i in range(len(magic_numbers) - 1): + magic_numbers.append(num + magic_numbers[i]) + power += 1 + return magic_numbers[n - 1] % (10**9 + 7) + +n = int(input("Enter the value of N: ")) +print("The {}th magic number is: {}".format(n, get_nth_magic_number(n))) + + + ``` + + + + + + ```cpp + #include +#include + +const int MOD = 1e9 + 7; + +int getNthMagicNumber(int n) { + std::vector magicNumbers; + int power = 0; + while (magicNumbers.size() < n) { + int num = pow(5, power); + magicNumbers.push_back(num); + for (int i = 0; i < magicNumbers.size() - 1; i++) { + magicNumbers.push_back(num + magicNumbers[i]); + } + power++; + } + return magicNumbers[n - 1] % MOD; +} +int main() { + int n; + std::cout << "Enter the value of N: "; + std::cin >> n; + std::cout << "The " << n << "th magic number is: " << getNthMagicNumber(n) << std::endl; + return 0; +} + + + ``` + + + + + + + ```javascript +function getNthMagicNumber(n) { + let magicNumbers = []; + let power = 0; + while (magicNumbers.length < n) { + let num = Math.pow(5, power); + magicNumbers.push(num); + for (let i = 0; i < magicNumbers.length - 1; i++) { + magicNumbers.push(num + magicNumbers[i]); + } + power++; + } + return magicNumbers[n - 1] % (10**9 + 7); +} + +let n = parseInt(prompt("Enter the value of N:")); +alert("The " + n + "th magic number is: " + getNthMagicNumber(n)); + + + ``` + + + + + + + ```typescript +function getNthMagicNumber(n: number): number { + let magicNumbers: number[] = []; + let power: number = 0; + while (magicNumbers.length < n) { + let num: number = Math.pow(5, power); + magicNumbers.push(num); + for (let i: number = 0; i < magicNumbers.length - 1; i++) { + magicNumbers.push(num + magicNumbers[i]); + } + power++; + } + return magicNumbers[n - 1] % (10**9 + 7); +} + +let n: number = parseInt(prompt("Enter the value of N:")); +alert("The " + n + "th magic number is: " + getNthMagicNumber(n)); + + ``` + + + + + + + ```java + +import java.util.*; + +public class Main { + public static int getNthMagicNumber(int n) { + List magicNumbers = new ArrayList<>(); + int power = 0; + while (magicNumbers.size() < n) { + int num = (int) Math.pow(5, power); + magicNumbers.add(num); + for (int i = 0; i < magicNumbers.size() - 1; i++) { + magicNumbers.add(num + magicNumbers.get(i)); + } + power++; + } + return magicNumbers.get(n - 1) % (int) (1e9 + 7); + } + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.print("Enter the value of N: "); + int n = scanner.nextInt(); + System.out.println("The " + n + "th magic number is: " + getNthMagicNumber(n)); + } +} + + + ``` + + + + + +## Time Complexity + +* The iterative approach has a time complexity of $O(n log n)$. + +## Space Complexity + +* The space complexity is $O(n)$ since we are using only a fixed amount of extra space. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/Majority-Element.md b/solutions/gfg-solutions/Easy problems/Majority-Element.md new file mode 100644 index 0000000..f46b6c6 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Majority-Element.md @@ -0,0 +1,168 @@ +--- +id: majority-element +title: Majority Element +sidebar_label: Majority-Element +tags: + - Beginner + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Majority Element Problem on Geeks for Geeks." +--- + +This tutorial contains a complete walk-through of the Majority Element problem from the Geeks for Geeks website. It features the implementation of the solution code in two programming languages: Python and C++. + +## Problem Description +Given an array `A` of `N` elements. Find the majority element in the array. A majority element in an array `A` of size `N` is an element that appears strictly more than `N/2` times in the array. + +## Examples + +**Example 1:** + +``` +Input: +N = 3 +A[] = {1,2,3} +Output: +-1 +Explanation: +Since, each element in +{1,2,3} appears only once so there +is no majority element. +``` + +**Example 2:** + +``` +Input: +N = 5 +A[] = {3,1,3,3,2} +Output: +3 +Explanation: +Since, 3 is present more +than N/2 times, so it is +the majority element. +``` + +## Your Task +The task is to complete the function majorityElement() which returns the majority element in the array. If no majority exists, return -1. + +Expected Time Complexity: $O(n)$ +Expected Auxiliary Space: $O(1)$ + +## Constraints + +`100 <= N <= 2*10^9` + + +## Code Implementation + + + + + ```py + class Solution: + + +def majority_element(A): + count = 0 + candidate = None + for num in A: + if count == 0: + candidate = num + count = 1 + elif candidate == num: + count += 1 + else: + count -= 1 + return candidate + + ``` + + + + + + ```cpp + int majorityElement(vector& A) { + int count = 0; + int candidate; + for (int num : A) { + if (count == 0) { + candidate = num; + count = 1; + } else if (candidate == num) { + count++; + } else { + count--; + } + } + return candidate; +} + +``` + + + + + + ```java + public int majorityElement(int[] A) { + int count = 0; + int candidate = 0; + for (int num : A) { + if (count == 0) { + candidate = num; + count = 1; + } else if (candidate == num) { + count++; + } else { + count--; + } + } + return candidate; +} + + + ``` + + + + + + ```js + +function majorityElement(A) { + let count = 0; + let candidate; + for (let num of A) { + if (count === 0) { + candidate = num; + count = 1; + } else if (candidate === num) { + count++; + } else { + count--; + } + } + return candidate; +} + + + ``` + + + + + + + +## Time Complexity + +The time complexity is $O(n)$ because the operations involve a fixed number of steps regardless of the size of N: + +## Space Complexity + +The space complexity is $O(1)$ as well since the operations use a constant amount of extra space for storing the products and concatenated strings. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/Merge-K-Sorted-Arrays.md b/solutions/gfg-solutions/Easy problems/Merge-K-Sorted-Arrays.md new file mode 100644 index 0000000..bd3662b --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Merge-K-Sorted-Arrays.md @@ -0,0 +1,130 @@ +--- +id: merge-k-sorted-arrays +title: Merge K Sorted Arrays +sidebar_label: Merge-K-Sorted-Arrays +tags: + - Sorting + - Algorithms +description: "This tutorial covers the solution to the Merge K Sorted Arrays problem from the GeeksforGeeks." +--- +## Problem Description +Given `k` sorted arrays arranged in the form of a matrix of size `k * k`. The task is to merge them into one sorted array. Return the merged sorted array + +## Examples + +**Example 1:** + +``` +Input: k = 3, arr[][] = {{1,2,3},{4,5,6},{7,8,9}} +Output: 1 2 3 4 5 6 7 8 9 +Explanation: Above test case has 3 sorted arrays of size 3, 3, 3 arr[][] = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]. The merged list will be [1, 2, 3, 4, 5, 6, 7, 8, 9]. +``` + +**Example 2:** + +``` +Input: k = 4, arr[][]={{1,2,3,4},{2,2,3,4},{5,5,6,6},{7,8,9,9}} +Output: 1 2 2 2 3 3 4 4 5 5 6 6 7 8 9 9 +Explanation: Above test case has 4 sorted arrays of size 4, 4, 4, 4 arr[][] = [[1, 2, 2, 2], [3, 3, 4, 4], [5, 5, 6, 6], [7, 8, 9, 9 ]]. The merged list will be [1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 9, 9]. +``` + +## Constraints + +* `1 <= k <= 100` + +## Problem Explanation +Given k sorted arrays arranged in the form of a matrix of size k * k. The task is to merge them into one sorted array. Return the merged sorted array + +## Code Implementation + +### C++ Solution + +```cpp +#include +#include +#include + +std::vector mergeSortedArrays(std::vector> arrays) { + std::vector result; + for (const auto& array : arrays) { + result.insert(result.end(), array.begin(), array.end()); + } + std::sort(result.begin(), result.end()); + return result; +} + +int main() { + std::vector> arrays = { { 1, 3, 5 }, { 2, 4, 6 }, { 0, 7, 8 } }; + std::vector result = mergeSortedArrays(arrays); + for (int num : result) { + std::cout << num << " "; + } + return 0; +} + + +``` + +```java + + +import java.util.Arrays; + +public class Main { + public static void main(String[] args) { + int[][] arrays = { { 1, 3, 5 }, { 2, 4, 6 }, { 0, 7, 8 } }; + int[] result = mergeSortedArrays(arrays); + System.out.println(Arrays.toString(result)); + } + + public static int[] mergeSortedArrays(int[][] arrays) { + int[] result = new int[arrays.length * arrays[0].length]; + int index = 0; + for (int[] array : arrays) { + for (int num : array) { + result[index++] = num; + } + } + Arrays.sort(result); + return result; + } +} + + +``` + +```python +import itertools + +def merge_sorted_arrays(arrays): + return sorted(itertools.chain(*arrays)) + +``` + +```javascript + +function mergeSortedArrays(arrays) { + return arrays.flat().sort((a, b) => a - b); +} + + +``` + +## Solution Logic: + + +1. Flatten the 2D array: + - Iterate through each subarray in the 2D array. + - Concatenate each subarray to a single array. +2. Sort the 1D array: + - Use a sorting algorithm (e.g. quicksort, mergesort) to sort the array in ascending order. +3. Return the sorted 1D array: + - Return the sorted array as the final result. + +## Time Complexity + +* The time complexity is $O(n*log(n))$ where n is the total number of elements in the arrays. + +## Space Complexity + +* $O(n)$ where n is the total number of elements in the arrays. diff --git a/solutions/gfg-solutions/Easy problems/Parenthesis-checker.md b/solutions/gfg-solutions/Easy problems/Parenthesis-checker.md new file mode 100644 index 0000000..61aebbe --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Parenthesis-checker.md @@ -0,0 +1,173 @@ +--- +id: parenthesis-checker +title: Parenthesis Checker +sidebar_label: 0017 - Parenthesis Checker +tags: + - Easy + - Stack + - GeeksforGeeks + - CPP + - DSA +description: "This tutorial covers the solution to the Parenthesis Checker problem from the GeeksforGeeks website, featuring implementations in Python and C++." +--- +## Problem Description + +Given an expression string `x`, examine whether the pairs and the orders of `{}`, `()`, `[]` are correct in the expression. + +## Examples + +**Example 1:** + +``` +Input: +x = "[()]{}{[()()]()}" +Output: true +Explanation: All the brackets are well-formed and properly nested. +``` + +**Example 2:** + +``` +Input: +x = "[(])" +Output: false +Explanation: The brackets are not properly nested. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `ispar()` which takes the string `x` as input and returns a boolean indicating whether the string has balanced parentheses. + +Expected Time Complexity: $O(N)$ + +Expected Auxiliary Space: $O(N)$ + +## Constraints + +* `1 ≀ |x| ≀ 10^5` + +## Problem Explanation + +The task is to check whether the input string `x` has balanced parentheses. Balanced parentheses mean that each opening bracket has a corresponding closing bracket and the brackets are properly nested. + +## Code Implementation + + + + + + ```py + class Solution: + def ispar(self, x: str) -> bool: + stack = [] + pair = {')': '(', '}': '{', ']': '['} + + for char in x: + if char in '({[': + stack.append(char) + elif char in ')}]': + if not stack or stack.pop() != pair[char]: + return False + + return not stack + + # Example usage + if __name__ == "__main__": + solution = Solution() + print(solution.ispar("[()]{}{[()()]()}")) # Expected output: True + print(solution.ispar("[(])")) # Expected output: False + ``` + + + + + + ```cpp + //{ Driver Code Starts + #include + using namespace std; + + // } Driver Code Ends + class Solution { + public: + // Function to check if brackets are balanced or not. + bool ispar(string x) { + stack s; + for (char ch : x) { + if (ch == '(' || ch == '{' || ch == '[') { + s.push(ch); + } else { + if (s.empty()) return false; + char top = s.top(); + if ((ch == ')' && top == '(') || + (ch == '}' && top == '{') || + (ch == ']' && top == '[')) { + s.pop(); + } else { + return false; + } + } + } + return s.empty(); + } + }; + + //{ Driver Code Starts. + int main() { + int t; + string a; + cin >> t; + while (t--) { + cin >> a; + Solution obj; + if (obj.ispar(a)) { + cout << "balanced" << endl; + } else { + cout << "not balanced" << endl; + } + } + } + // } Driver Code Ends + ``` + + + + +## Example Walkthrough + +**Example 1:** + +For the input string: +``` +x = "[()]{}{[()()]()}" +``` +1. The string contains properly nested and balanced parentheses, so the output is true. + +**Example 2:** + +For the input string: +``` +x = "[(])" +``` +1. The brackets are not properly nested, so the output is false. + +## Solution Logic: + +1. Use a stack to keep track of opening brackets. +2. Traverse the string character by character: + - If the character is an opening bracket, push it onto the stack. + - If the character is a closing bracket, check if it matches the top of the stack. +3. If the stack is empty at the end, the parentheses are balanced; otherwise, they are not. + +## Time Complexity + +* The function traverses the string once, so the time complexity is $O(N)$. + +## Space Complexity + +* The function uses a stack to store opening brackets, so the auxiliary space complexity is $O(N)$. + +## References + +- **GeeksforGeeks Problem:** [Parenthesis Checker](https://www.geeksforgeeks.org/problems/parenthesis-checker2744/1) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/Peak-Element.md b/solutions/gfg-solutions/Easy problems/Peak-Element.md new file mode 100644 index 0000000..2ba409a --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Peak-Element.md @@ -0,0 +1,190 @@ +--- +id: peak-element +title: Peak Element +sidebar_label: Peak-Element +tags: + - Modular Arithmetic + - Algorithms +description: "This tutorial covers the solution to the Peak Element problem from the GeeksforGeeks." +--- +## Problem Description +Given an `0`-indexed array of integers `arr[]` of size n, find its peak element and return it's index. An element is considered to be peak if it's value is greater than or equal to the values of its adjacent elements (if they exist). + +Note: The output will be `1` if the index returned by your function is correct; otherwise, it will be `0`. + +## Examples + +**Example 1:** + +``` +Input: n = 3, arr[] = {1, 2, 3} +Output: 1 +Explanation: If the index returned is 2, then the output printed will be 1. Since arr[2] = 3 is greater than its adjacent elements, and there is no element after it, we can consider it as a peak element. No other index satisfies the same property, so answer will be printed as 0. +``` + +**Example 2:** + +``` +Input: n = 7, arr[] = {1, 1, 1, 2, 1, 1, 1} +Output: 1 +Explanation: In this case there are 5 peak elements with indices as {0,1,3,5,6}. Returning any of them will give you correct answer. +``` + + +Expected Time Complexity: O(logn) + +Expected Auxiliary Space: O(1) + +## Constraints + +* `1 ≀ N ≀ 10^5` + +## Problem Explanation + +The task is to traverse the array and find the peak element. + +## Code Implementation + +### C++ Solution + +```cpp +#include +#include + +int findPeakElement(const std::vector& arr) { + int n = arr.size(); + if (n == 1) { + return 0; + } + if (arr[0] >= arr[1]) { + return 0; + } + if (arr[n - 1] >= arr[n - 2]) { + return n - 1; + } + for (int i = 1; i < n - 1; i++) { + if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) { + return i; + } + } + return -1; // return -1 if no peak element is found +} +int main() { + std::vector arr = {1, 3, 20, 4, 1, 0}; + int peakIndex = findPeakElement(arr); + if (peakIndex != -1) { + std::cout << "Peak element is at index " << peakIndex << std::endl; + } else { + std::cout << "No peak element found" << std::endl; + } + return 0; +} + + +``` + +```java +import java.util.*; + +public class Main { + public static int findPeakElement(int[] arr) { + int n = arr.length; + if (n == 1) { + return 0; + } + if (arr[0] >= arr[1]) { + return 0; + } + if (arr[n - 1] >= arr[n - 2]) { + return n - 1; + } + for (int i = 1; i < n - 1; i++) { + if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) { + return i; + } + } + return -1; // return -1 if no peak element is found + } + public static void main(String[] args) { + int[] arr = {1, 3, 20, 4, 1, 0}; + int peakIndex = findPeakElement(arr); + if (peakIndex != -1) { + System.out.println("Peak element is at index " + peakIndex); + } else { + System.out.println("No peak element found"); + } + } +} + + +``` + +```python + +def find_peak_element(arr): + n = len(arr) + if n == 1: + return 0 + if arr[0] >= arr[1]: + return 0 + if arr[n - 1] >= arr[n - 2]: + return n - 1 + for i in range(1, n - 1): + if arr[i] >= arr[i - 1] and arr[i] >= arr[i + 1]: + return i + return -1 # return -1 if no peak element is found + +arr = [1, 3, 20, 4, 1, 0] +peak_index = find_peak_element(arr) +if peak_index != -1: + print("Peak element is at index", peak_index) +else: + print("No peak element found") + + +``` + +```javascript +function findPeakElement(arr) { + let n = arr.length; + if (n === 1) { + return 0; + } + if (arr[0] >= arr[1]) { + return 0; + } + if (arr[n - 1] >= arr[n - 2]) { + return n - 1; + } + for (let i = 1; i < n - 1; i++) { + if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) { + return i; + } + } + return -1; // return -1 if no peak element is found +} + +let arr = [1, 3, 20, 4, 1, 0]; +let peakIndex = findPeakElement(arr); +if (peakIndex !== -1) { + console.log(`Peak element is at index ${peakIndex}`); +} else { + console.log("No peak elementΒ found"); +} + +``` + +## Solution Logic: +This solution iterates through the array and checks each element to see if it's greater than or equal to its adjacent elements. If it finds such an element, it returns its index. If no such element is found, it returns -1. + + + + +## Time Complexity + +* The time complexity is $O(n)$ where n is the input number. + + +## Space Complexity + +* The auxiliary space complexity is $O(1)$ due to the only extra memory used is for temporary variables while swapping two values in Array. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/Perfect-Numbers.md b/solutions/gfg-solutions/Easy problems/Perfect-Numbers.md new file mode 100644 index 0000000..014b4dd --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Perfect-Numbers.md @@ -0,0 +1,164 @@ +--- +id: perfect-numbers +title: Perfect Numbers +tags: + - Easy + - GeeksforGeeks + - CPP + - Python + - DSA +description: "This tutorial covers the solution to the Perfect Numbers problem from the GeeksforGeeks." +--- + +## Problem Description + +Given a number `N`, check if a number is perfect or not. A number is said to be perfect if sum of all its factors excluding the number itself is equal to the number. Return `1` if the number is Perfect otherwise return `0`. + +## Examples + +**Example 1:** + +``` +Input: +N = 6 +Output: +1 +Explanation: +Factors of 6 are 1, 2, 3 and 6. +Excluding 6 their sum is 6 which +is equal to N itself. So, it's a +Perfect Number. +``` + +**Example 2:** + +``` +Input: +N = 10 +Output: +0 +Explanation: +Factors of 10 are 1, 2, 5 and 10. +Excluding 10 their sum is 8 which +is not equal to N itself. So, it's +not a Perfect Number. +``` + + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `isPerfectNumber()` which takes an Integer `N` as input and returns `1` if `N` is a Perfect number else returns `0`. + +Expected Time Complexity: $O(sqrt(N))$ + +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- `1 ≀ n ≀ 10^12` + +## Problem Explanation +Given a number `N`, check if a number is perfect or not. A number is said to be perfect if sum of all its factors excluding the number itself is equal to the number. Return `1` if the number is Perfect otherwise return `0`. + + +## Code Implementation + + + + + + ```python + def is_perfect(N): + sum = 0 + for i in range(1, N): + if N % i == 0: + sum += i + return (sum == N) and 1 or 0 + + ``` + + + + + + ```cpp + int isPerfect(int N) { + int sum = 0; + for (int i = 1; i < N; i++) { + if (N % i == 0) { + sum += i; + } + } + return (sum == N) ? 1 : 0; +} + + ``` + + + + + + + ```javascript +function isPerfect(N) { + let sum = 0; + for (let i = 1; i < N; i++) { + if (N % i === 0) { + sum += i; + } + } + return (sum === N) ? 1 : 0; +} + + ``` + + + + + + ```typescript +function isPerfect(N) { + let sum = 0; + for (let i = 1; i < N; i++) { + if (N % i === 0) { + sum += i; + } + } + return (sum === N) ? 1 : 0; +} + + ``` + + + + + + + + ```java +public int isPerfect(int N) { + int sum = 0; + for (int i = 1; i < N; i++) { + if (N % i == 0) { + sum += i; + } + } + return (sum == N) ? 1 : 0; +} + + ``` + + + + +## Solution Logic: +The solution iterates through all numbers from 1 to N-1 and checks if the current number is a factor of N. If it is, it adds the number to the sum. Finally, it checks if the sum is equal to N. If it is, the number is perfect, and the function returns 1. Otherwise, it returns 0. + + +## Time Complexity + +- The function operates in constant time, $O(N)$ where N is the input number. This is because the solution iterates through all numbers from 1 to N-1. + +## Space Complexity + +- The function uses constant space, $O(1)$, because it only uses a few extra variables to store the sum and the current number. diff --git a/solutions/gfg-solutions/Easy problems/Plus-One.md b/solutions/gfg-solutions/Easy problems/Plus-One.md new file mode 100644 index 0000000..2ac0769 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Plus-One.md @@ -0,0 +1,175 @@ +--- +id: plus-one +title: Plus One +sidebar_label: Plus-One +tags: + - Arrays + - STL +description: "This tutorial covers the solution to the Plus One problem from the GeeksforGeeks." +--- +## Problem Description +Given a non-negative number represented as a list of digits, add `1` to the number (increment the number represented by the digits). The digits are stored such that the most significant digit is first element of array. + + + +## Examples + +**Example 1:** + +``` +Input: +N = 3 +arr[] = {1, 2, 4} +Output: +1 2 5 +Explanation: +124+1 = 125, and so the Output +``` + +**Example 2:** + +``` +Input: +N = 3 +arr[] = {9,9,9} +Output: +1 0 0 0 +Explanation: +999+1 = 1000, and so the output +``` + +## Your Task + +You don't need to read input or print anything. You only need to complete the function `increment()` that takes an integer N, and an array arr of size N as input and returns a list of integers denoting the new number which we get after adding one to the number denoted by the array arr. + +Expected Time Complexity: $O(n)$ + +Expected Auxiliary Space: $O(1)$ for iterative approach. + +## Constraints + +* `1 ≀ n ≀ 10^5` + +## Problem Explanation + +Given a non-negative number represented as a list of digits, add `1` to the number (increment the number represented by the digits). The digits are stored such that the most significant digit is first element of array. + +## Code Implementation + + + + + + ```py + def increment(digits): + for i in range(len(digits) - 1, -1, -1): + if digits[i] == 9: + digits[i] = 0 + else: + digits[i] += 1 + return digits + digits.insert(0, 1) + return digits + + ``` + + + + + + ```cpp +vector increment(vector& digits) { + for (int i = digits.size() - 1; i >= 0; --i) { + if (digits[i] == 9) { + digits[i] = 0; + } else { + digits[i]++; + return digits; + } + } + digits.insert(digits.begin(), 1); + return digits; +} + + ``` + + + + + + + ```javascript +function increment(digits) { + for (let i = digits.length - 1; i >= 0; --i) { + if (digits[i] === 9) { + digits[i] = 0; + } else { + digits[i]++; + return digits; + } + } + digits.unshift(1); + return digits; +} + + + + ``` + + + + + + + ```typescript +function increment(digits) { + for (let i = digits.length - 1; i >= 0; --i) { + if (digits[i] === 9) { + digits[i] = 0; + } else { + digits[i]++; + return digits; + } + } + digits.unshift(1); + return digits; +} + + + + ``` + + + + + + + ```java +public List increment(List digits) { + for (int i = digits.size() - 1; i >= 0; --i) { + if (digits.get(i) == 9) { + digits.set(i, 0); + } else { + digits.set(i, digits.get(i) + 1); + return digits; + } + } + digits.add(0, 1); + return digits; +} + + + + ``` + + + + + +## Time Complexity + +* The iterative approach has a time complexity of $O(n)$. + +## Space Complexity + +* The space complexity is $O(1)$ since we are using only a fixed amount of extra space. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/Print-Pattern.md b/solutions/gfg-solutions/Easy problems/Print-Pattern.md new file mode 100644 index 0000000..b8ff74c --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Print-Pattern.md @@ -0,0 +1,119 @@ +--- +id: print-pattern +title: Print Pattern +sidebar_label: Print-Pattern +tags: + - Recursion + - Algorithms +description: "This tutorial covers the solution to the Print Pattern problem from the GeeksforGeeks." +--- +## Problem Description +Print a sequence of numbers starting with nn, without using a loop. Replace `nn` with `nβˆ’5n - 5nβˆ’5` until `n≀0n` `\leq 0n≀0`. Then, replace n with `n+5n + 5n+5` until `nn` regains its initial value. Complete the function pattern(n) which takes n as input and returns a list containing the pattern. + +## Examples + +**Example 1:** + +``` +Input: n = 16 +Output: 16 11 6 1 -4 1 6 11 16 +Explanation: The value decreases until it is greater than 0. After that it increases and stops when it becomes 16 again. +``` + +**Example 2:** + +``` +Input: n = 10 +Output: 10 5 0 5 10 +Explanation: It follows the same logic as per the above example. +``` + + + +Expected Time Complexity: $O(n)$ + +Expected Auxiliary Space: $O(n)$ for dynamic programming + +## Constraints + +* `-10^5 ≀ n ≀ 10^5` + +## Problem Explanation +Print a sequence of numbers starting with nn, without using a loop. Replace `nn` with `nβˆ’5n - 5nβˆ’5` until `n≀0n` `\leq 0n≀0`. Then, replace n with `n+5n + 5n+5` until nn regains its initial value. Complete the function pattern(n) which takes n as input and returns a list containing the pattern. + +## Code Implementation + + + + + + ```py + def pattern(n, initial=None, result=None): + if result is None: + result = [] + if initial is None: + initial = n + if n > 0: + result.append(n) + return pattern(n - 5, initial, result) + elif n < initial: + result.append(n) + return pattern(n + 5, initial, result) + returnΒ result + + ``` + + + + + + ```cpp + vector pattern(int n) { + vector result; + while (n > 0) { + result.push_back(n); + n -= 5; + } + while (n < result[0]) { + result.push_back(n); + n += 5; + } + return result; +} + + + ``` + + + + + + + + ```java +public List pattern(int n) { + List result = new ArrayList<>(); + while (n > 0) { + result.add(n); + n -= 5; + } + while (n < result.get(0)) { + result.add(n); + n += 5; + } + return result; +} + + ``` + + + + + +## Time Complexity + +* The iterative approach has a time complexity of $O(n)$ because we are iterating through the sequence of numbers twice: once from n to 0, and once from 0 to n. + +## Space Complexity + +* The space complexity is O(n) because we are storing the sequence of numbers in the result list. diff --git a/solutions/gfg-solutions/Easy problems/Selection-Sort.md b/solutions/gfg-solutions/Easy problems/Selection-Sort.md new file mode 100644 index 0000000..9651355 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Selection-Sort.md @@ -0,0 +1,267 @@ +--- +id: selection-sort +title: Selection Sort +sidebar_label: Selection-Sort +tags: + - Sorting + - Algorithms +description: "This tutorial covers the solution to the SelectionSort problem from the GeeksforGeeks." +--- +## Problem Description + +Given an unsorted array of size `N`, use selection sort to sort `arr[]` in increasing order. + +## Examples + +**Example 1:** + +``` +Input: +N = 5 +arr[] = {4, 1, 3, 9, 7} +Output: +1 3 4 7 9 +Explanation: +Maintain sorted (in bold) and unsorted subarrays. +Select 1. Array becomes 1 4 3 9 7. +Select 3. Array becomes 1 3 4 9 7. +Select 4. Array becomes 1 3 4 9 7. +Select 7. Array becomes 1 3 4 7 9. +Select 9. Array becomes 1 3 4 7 9. +``` + +**Example 2:** + +``` +Input: +N = 10 +arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1} +Output: +1 2 3 4 5 6 7 8 9 10 +``` + +## Your Task +You dont need to read input or print anything. Complete the functions select() and selectionSort() ,where select() takes arr[] and starting point of unsorted array i as input parameters and returns the selected element for each iteration in selection sort, and selectionSort() takes the array and it's size and sorts the array. + +Expected Time Complexity: O(N^2) + +Expected Auxiliary Space: O(1) + +## Constraints + +* `1 ≀ N ≀ 10^3` + +## Problem Explanation + +The task is to traverse the array and sort the array using selection sort. + +## Code Implementation + +### C++ Solution + +```cpp + +// C++ program for implementation of +// selection sort +#include +using namespace std; + +// Function for Selection sort +void selectionSort(int arr[], int n) +{ + int i, j, min_idx; + + // One by one move boundary of + // unsorted subarray + for (i = 0; i < n - 1; i++) { + + // Find the minimum element in + // unsorted array + min_idx = i; + for (j = i + 1; j < n; j++) { + if (arr[j] < arr[min_idx]) + min_idx = j; + } + + // Swap the found minimum element + // with the first element + if (min_idx != i) + swap(arr[min_idx], arr[i]); + } +} + +// Function to print an array +void printArray(int arr[], int size) +{ + int i; + for (i = 0; i < size; i++) { + cout << arr[i] << " "; + cout << endl; + } +} + +// Driver program +int main() +{ + int arr[] = { 64, 25, 12, 22, 11 }; + int n = sizeof(arr) / sizeof(arr[0]); + + // Function Call + selectionSort(arr, n); + cout << "Sorted array: \n"; + printArray(arr, n); + return 0; +} + +``` + +```java +// Java program for implementation of Selection Sort +import java.io.*; +public class SelectionSort +{ + void sort(int arr[]) + { + int n = arr.length; + + // One by one move boundary of unsorted subarray + for (int i = 0; i < n-1; i++) + { + // Find the minimum element in unsorted array + int min_idx = i; + for (int j = i+1; j < n; j++) + if (arr[j] < arr[min_idx]) + min_idx = j; + + // Swap the found minimum element with the first + // element + int temp = arr[min_idx]; + arr[min_idx] = arr[i]; + arr[i] = temp; + } + } + + // Prints the array + void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i A[j]: + min_idx = j + + # Swap the found minimum element with + # the first element + A[i], A[min_idx] = A[min_idx], A[i] + +# Driver code to test above +print ("Sorted array") +for i in range(len(A)): + print(A[i],end=" ") + +``` + +```javascript + + +``` + +## Solution Logic: + +1. For the first position in the sorted array, the whole array is traversed from index 0 to 4 sequentially. The first position where 64 is stored presently, after traversing whole array it is clear that 11 is the lowest value. + +2. Thus, replace 64 with 11. After one iteration 11, which happens to be the least value in the array, tends to appear in the first position of the sorted list. + +3. For the second position, where 25 is present, again traverse the rest of the array in a sequential manner. + +4. After traversing, we found that 12 is the second lowest value in the array and it should appear at the second place in the array, thus swap these values. + +5. Now, for third place, where 25 is present again traverse the rest of the array and find the third least value present in the array. + +6. While traversing, 22 came out to be the third least value and it should appear at the third place in the array, thus swap 22 with element present at third position. + +7. Similarly, for fourth position traverse the rest of the array and find the fourth least element in the array + +8. As 25 is the 4th lowest value hence, it will place at the fourth position. + +9. At last the largest value present in the array automatically get placed at the last position in the array + +10. The resulted array is the sorted array. + +## Time Complexity + +* The time complexity is $O(N^2)$ as there are two nested loops + +## Space Complexity + +* The auxiliary space complexity is $O(1)$ due to the only extra memory used is for temporary variables while swapping two values in Array. The selection sort never makes more than $O(N)$ swaps and can be useful when memory writing is costly. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/Sort-0s-1s-2s.md b/solutions/gfg-solutions/Easy problems/Sort-0s-1s-2s.md new file mode 100644 index 0000000..702cffb --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Sort-0s-1s-2s.md @@ -0,0 +1,176 @@ +--- +id: sort-0s-1s-2s +title: Sort 0s, 1s And 2s +sidebar_label: Sort-0s-1s-and-2s +tags: + - Arrays + - Sorting +description: "This tutorial covers the solution to the SSort 0s, 1s and 2s problem from the GeeksforGeeks website." +--- +## Problem Description +Given an array of size `N` containing only `0s`, `1s`, and `2s`; sort the array in ascending order. + +## Examples + +**Example 1:** + +``` +Input: +N = 5 +arr[]= {0 2 1 2 0} +Output: +0 0 1 2 2 +Explanation: +0s 1s and 2s are segregated +into ascending order. +``` + +**Example 2:** + +``` +Input: +N = 3 +arr[] = {0 1 0} +Output: +0 0 1 +Explanation: +0s 1s and 2s are segregated +into ascending order. +``` + +## Your Task +You don't need to read input or print anything. Your task is to complete the function sort012() that takes an array arr and N as input parameters and sorts the array in-place. + + + +Expected Time Complexity: O(N) + +Expected Auxiliary Space: O(1) + +## Constraints + +* `1 <= N <= 10^6` + +## Problem Explanation + +The task is to traverse the array and sort 0s, 1s, 2s. + +## Code Implementation + +### C++ Solution + +```cpp +void sortArray(vector& arr) { + int low = 0, mid = 0, high = arr.size() - 1; + while (mid <= high) { + if (arr[mid] == 0) { + swap(arr[low], arr[mid]); + low++; + mid++; + } else if (arr[mid] == 1) { + mid++; + } else { + swap(arr[mid], arr[high]); + high--; + } + } +} +``` + +```java +public void sortArray(int[] arr) { + int low = 0, mid = 0, high = arr.length - 1; + while (mid <= high) { + if (arr[mid] == 0) { + swap(arr, low, mid); + low++; + mid++; + } else if (arr[mid] == 1) { + mid++; + } else { + swap(arr, mid, high); + high--; + } + } +} +public void swap(int[] arr, int i, int j) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; +} + + +``` + +```python +def sortArray(arr): + low, mid, high = 0, 0, len(arr) - 1 + while mid <= high: + if arr[mid] == 0: + arr[low], arr[mid] = arr[mid], arr[low] + low += 1 + mid += 1 + elif arr[mid] == 1: + mid += 1 + else: + arr[mid], arr[high] = arr[high], arr[mid] + high -= 1 + + + +``` + +```javascript +function sortArray(arr) { + let low = 0, mid = 0, high = arr.length - 1; + while (mid <= high) { + if (arr[mid] === 0) { + [arr[low], arr[mid]] = [arr[mid], arr[low]]; + low++; + mid++; + } else if (arr[mid] === 1) { + mid++; + } else { + [arr[mid], arr[high]] = [arr[high], arr[mid]]; + high--; + } + } +} + + +``` + +```typescript +function sortArray(arr) { + let low = 0, mid = 0, high = arr.length - 1; + while (mid <= high) { + if (arr[mid] === 0) { + [arr[low], arr[mid]] = [arr[mid], arr[low]]; + low++; + mid++; + } else if (arr[mid] === 1) { + mid++; + } else { + [arr[mid], arr[high]] = [arr[high], arr[mid]]; + high--; + } + } +} + +``` + +## Solution Logic: +The solution uses a variation of the Dutch National Flag algorithm, which is used to sort an array of 0s, 1s, and 2s. The algorithm uses three pointers: low, mid, and high. The low pointer is used to track the position of the next 0, the mid pointer is used to track the position of the next 1, and the high pointer is used to track the position of the next 2. + + + + +## Time Complexity + +* The time complexity is $O(N)$,where N is the length of the array. This is because we only need to iterate through the array once to sort it. + + + +## Space Complexity + +* The auxiliary space complexity is $O(1)$ due to the algorithm only uses a fixed amount of space to store the indices and the target element. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/Special-Number.md b/solutions/gfg-solutions/Easy problems/Special-Number.md new file mode 100644 index 0000000..b29abbe --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Special-Number.md @@ -0,0 +1,183 @@ +--- +id: special-numbers +title: Special Numbers +sidebar_label: Special-Numbers +tags: + - Mathematical + - Algorithms +description: "This tutorial covers the solution to the Special Numbers problem from the GeeksforGeeks." +--- +## Problem Description + +A number is a special number if it’s digits only consist `0`, `1`, `2`, `3`, `4` or `5`. Given a number N and we have to find N-th Special Number. + +## Examples + +**Example 1:** + +``` +Input: +N = 6 +Output: 5 +Explanation: First 6 numbers are +( 0, 1, 2, 3, 4, 5 ) +``` + +**Example 2:** + +``` +Input: +N = 7 +Output: 10 +Explanation: First 7 numbers are +( 0, 1, 2, 3, 4, 5, 10 ) +``` + + +Expected Time Complexity: O(logN) + +Expected Auxiliary Space: O(1) + +## Constraints + +* `1 ≀ N ≀ 10^5` + +## Problem Explanation + +The task is to traverse the number and count the digits. + +## Code Implementation + +### C++ Solution + +```cpp +int findNthSpecial(int N) { + int count = 0; + int num = 0; + while (true) { + num++; + if (isSpecial(num)) { + count++; + if (count == N) { + return num; + } + } + } +} + +bool isSpecial(int num) { + while (num > 0) { + int digit = num % 10; + if (digit > 5) { + return false; + } + num /= 10; + } + return true; +} + + + +``` + +```java +public int findNthSpecial(int N) { + int count = 0; + int num = 0; + while (true) { + num++; + if (isSpecial(num)) { + count++; + if (count == N) { + return num; + } + } + } +} + +public boolean isSpecial(int num) { + while (num > 0) { + int digit = num % 10; + if (digit > 5) { + return false; + } + num /= 10; + } + return true; +} + + +``` + +```python + +def find_nth_special(N): + count = 0 + num = 0 + while True: + num += 1 + if is_special(num): + count += 1 + if count == N: + return num + +def is_special(num): + while num > 0: + digit = num % 10 + if digit > 5: + return False + num //= 10 + return True + + +``` + +```javascript +function findNthSpecial(N) { + let count = 0; + let num = 0; + while (true) { + num++; + if (isSpecial(num)) { + count++; + if (count === N) { + return num; + } + } + } +} + +function isSpecial(num) { + while (num > 0) { + const digit = num % 10; + if (digit > 5) { + return false; + } + num = Math.floor(num / 10); + } + return true; +} + + + +``` + +## Solution Logic: +1. Initialize a counter count to 0 and a number num to 0. +2. Iterate through numbers starting from 1. +3. For each number, check if it's special (i.e., its digits only consist of 0, 1, 2, 3, 4, or 5) using the isSpecial function. +4. If the number is special, increment the count. +5. If the count reaches N, return the current number. +6. Repeat steps 2-5 until the N-th special number is found. + +## Time Complexity + +- The `isSpecial` function has a time complexity of O(log num), where num is the input number, because it iterates through the digits of the number. + +- The main function findNthSpecial has a time complexity of O(N log M), where N is the input number and M is the N-th special number, because it iterates through numbers and calls the isSpecial function for each number. + + + +## Space Complexity + +- The solution uses a constant amount of space to store the count and num variables, so the space complexity is O(1). diff --git a/solutions/gfg-solutions/Easy problems/Star- Element.md b/solutions/gfg-solutions/Easy problems/Star- Element.md new file mode 100644 index 0000000..f155e21 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/Star- Element.md @@ -0,0 +1,192 @@ +--- +id: star-elements +title: Star Elements +sidebar_label: Star-Elements +tags: + - Modular Arithmetic + - Algorithms +description: "This tutorial covers the solution to the Star elements problem from the GeeksforGeeks." +--- +## Problem Description +Given an unsorted array `arr` of size `n`. The task is to find all the star and super star elements in the array. Star are those elements which are strictly greater than all the elements on its right side. Super star are those elements which are strictly greater than all the elements on its left and right side. + +Note: Assume first element (`arr[0]`) is greater than all the elements on its left side, And last element `(arr[n-1])` is greater than all the elements on its right side. + +## Examples + +**Example 1:** + +``` +Input: +n = 10 +arr[] = {1, 6, 5, 4, 7, 8, 4, 3, 2, 1} +Output: +8 4 3 2 1 +8 +Explanation: Star elements are 8, 4, 3, 2 and 1. +Super star element is 8. +``` + +**Example 2:** + +``` +Input: +a = 9 +arr[] = {1, 2, 10, 3, 4, 5, 8, 10, 4} +Output: +10 4 +-1 +Explanation: Star elements are 10 and 4. +No super star element present here. +``` + + +Expected Time Complexity: O(n) + +Expected Auxiliary Space: O(1) + +## Constraints + +* `1 ≀ N ≀ 10^6` + +## Problem Explanation + +The task is to traverse the array and search the number. + +## Code Implementation + +### C++ Solution + +```cpp +#include +using namespace std; + +void findStars(int arr[], int n) { + int maxRight = arr[n-1]; + cout << "Super Stars: "; + for (int i = n-1; i >= 0; i--) { + if (arr[i] > maxRight) { + cout << arr[i] << " "; + maxRight = arr[i]; + } + } + cout << endl; + cout << "Stars: "; + maxRight = arr[n-1]; + for (int i = n-2; i >= 0; i--) { + if (arr[i] > maxRight) { + cout << arr[i] << " "; + maxRight = arr[i]; + } + } + cout << endl; +} + +int main() { + int arr[] = {4, 6, 3, 7, 2, 8}; + int n = sizeof(arr)/sizeof(arr[0]); + findStars(arr, n); + return 0; +} + + + +``` + +```java + +public class Main { + public static void findStars(int[] arr) { + int maxRight = arr[arr.length-1]; + System.out.print("Super Stars: "); + for (int i = arr.length-1; i >= 0; i--) { + if (arr[i] > maxRight) { + System.out.print(arr[i] + " "); + maxRight = arr[i]; + } + } + System.out.println(); + System.out.print("Stars: "); + maxRight = arr[arr.length-1]; + for (int i = arr.length-2; i >= 0; i--) { + if (arr[i] > maxRight) { + System.out.print(arr[i] + " "); + maxRight = arr[i]; + } + } + System.out.println(); + } + + public static void main(String[] args) { + int[] arr = {4, 6, 3, 7, 2, 8}; + findStars(arr); + } +} + + + +``` + +```python +def find_stars(arr): + max_right = arr[-1] + super_stars = [] + for i in range(len(arr)-1, -1, -1): + if arr[i] > max_right: + super_stars.append(arr[i]) + max_right = arr[i] + print("Super Stars:", super_stars) + max_right = arr[-1] + stars = [] + for i in range(len(arr)-2, -1, -1): + if arr[i] > max_right: + stars.append(arr[i]) + max_right = arr[i] + print("Stars:", stars) + +arr = [4, 6, 3, 7, 2, 8] +find_stars(arr) + +``` + +```javascript +function findStars(arr) { + let maxRight = arr[arr.length-1]; + let superStars = []; + for (let i = arr.length-1; i >= 0; i--) { + if (arr[i] > maxRight) { + superStars.push(arr[i]); + maxRight = arr[i]; + } + } + console.log("Super Stars:", superStars); + maxRight = arr[arr.length-1]; + let stars = []; + for (let i = arr.length-2; i >= 0; i--) { + if (arr[i] > maxRight) { + stars.push(arr[i]); + maxRight = arr[i]; + } + } + console.log("Stars:", stars); +} + + +``` + +## Solution Logic: +1. Initialize maxRight to the last element of the array. +2. Iterate through the array from right to left (starting from the second last element). +3. For each element, check if it is greater than maxRight. If it is, add it to the stars array and update maxRight. +4. Repeat steps 2-3 until the beginning of the array is reached. +5. To find super stars, repeat steps 2-4, but add elements to the superStars array only if they are greater than maxRight and also greater than all elements on their left side. + + +## Time Complexity + +* The time complexity is $O(log(n))$ where n is the input number. + + +## Space Complexity + +* The auxiliary space complexity is $O(1)$ due to the only extra memory used is for temporary variables while swapping two values in Array. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/anagram-1587115620.md b/solutions/gfg-solutions/Easy problems/anagram-1587115620.md new file mode 100644 index 0000000..2e6a500 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/anagram-1587115620.md @@ -0,0 +1,149 @@ +--- +id: check-if-strings-are-anagram +title: Check if Two Strings are Anagram (gfg) +sidebar_label: 0008 - Check if Two Strings are Anagram +tags: + - Easy + - String + - GeeksforGeeks + - CPP + - Python + - DSA +description: "This tutorial covers the solution to the Check if Two Strings are Anagram problem from the GeeksforGeeks website, featuring implementations in Python and C++." +--- +## Problem Description + +Given two strings `a` and `b` consisting of lowercase characters, the task is to check whether the two given strings are an anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, `act` and `tac` are an anagram of each other. Strings `a` and `b` can only contain lowercase alphabets. + +## Examples + +**Example 1:** + +``` +Input: a = "listen", b = "silent" +Output: YES +Explanation: The characters in both strings are the same. +``` + +**Example 2:** + +``` +Input: a = "hello", b = "billion" +Output: NO +Explanation: The characters in the strings are different. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `isAnagram()` which takes the strings `a` and `b` as inputs and returns a boolean indicating whether the two strings are an anagram of each other. + +Expected Time Complexity: $O(n \log n)$ for sorting-based approach or $O(n)$ for counting-based approach. + +Expected Auxiliary Space: $O(1)$ for constant extra space. + +## Constraints + +* `1 ≀ |a|, |b| ≀ 10^5` + +## Problem Explanation + +The problem is to check if two strings are anagram of each other, meaning both strings should have the same characters in any order. + +## Code Implementation + + + + + + ```py + class Solution: + def isAnagram(self, a: str, b: str) -> bool: + # If lengths are different, they cannot be anagrams + if len(a) != len(b): + return False + + # Sort and compare + return sorted(a) == sorted(b) + + # Example usage + if __name__ == "__main__": + solution = Solution() + print(solution.isAnagram("listen", "silent")) # Expected output: True + print(solution.isAnagram("hello", "billion")) # Expected output: False + ``` + + + + + + ```cpp + //{ Driver Code Starts + #include + using namespace std; + + // } Driver Code Ends + class Solution { + public: + // Function to check whether two strings are anagram of each other or not. + bool isAnagram(string a, string b) { + // If lengths are different, they cannot be anagrams + if (a.size() != b.size()) return false; + + // Sort both strings + sort(a.begin(), a.end()); + sort(b.begin(), b.end()); + + // Compare sorted strings + return a == b; + } + }; + + //{ Driver Code Starts. + int main() { + int t; + cin >> t; + while(t--) { + string c, d; + cin >> c >> d; + Solution obj; + if (obj.isAnagram(c, d)) cout << "YES" << endl; + else cout << "NO" << endl; + } + return 0; + } + // } Driver Code Ends + ``` + + + + +## Example Walkthrough + +For the strings `a = "listen"` and `b = "silent"`: + +1. Check the lengths of `a` and `b`. They are both 6. +2. Sort both strings: `a` becomes `eilnst` and `b` becomes `eilnst`. +3. Compare the sorted strings. They are equal, so the result is `YES`. + +For the strings `a = "hello"` and `b = "billion"`: + +1. Check the lengths of `a` and `b`. `a` is 5 and `b` is 7. +2. Since the lengths are different, the result is `NO`. + +## Solution Logic: + +1. Check if the lengths of the two strings are the same. If not, they cannot be anagrams. +2. Sort both strings and compare them. If they are equal, the strings are anagrams. + +## Time Complexity + +* The sorting-based approach has a time complexity of $O(n \log n)$, where n is the length of the strings. + +## Space Complexity + +* The auxiliary space complexity is $O(1)$ for constant extra space. + +## References + +- **gfg Problem:** [gfg Problem](https://www.geeksforgeeks.org/problems/anagram-1587115620/1?page=1&difficulty=Easy&sortBy=submissions) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/bfs-of-graph.md b/solutions/gfg-solutions/Easy problems/bfs-of-graph.md new file mode 100644 index 0000000..1acd8e4 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/bfs-of-graph.md @@ -0,0 +1,222 @@ +--- +id: bfs-of-graph +title: BFS of Graph +sidebar_label: 8 BFS of Graph +tags: +- Graph +- BFS +- Python +- Java +- C++ +- JavaScript +- TypeScript +description: "This document provides solutions to the problem of performing a Breadth First Search (BFS) traversal of a directed graph in various programming languages." +--- + +## Problem + +Given a directed graph, perform a Breadth First Traversal starting from the 0th vertex. One can move from node `u` to node `v` only if there's an edge from `u` to `v`. Find the BFS traversal of the graph starting from the 0th vertex, from left to right according to the input graph. Only consider nodes that are directly or indirectly connected to node `0`. + +### Examples + +**Example 1:** + +``` +Input: V = 5, E = 4, adj = {{1,2,3},{},{4},{},{}} +Output: 0 1 2 3 4 +Explanation: +0 is connected to 1, 2, 3. +2 is connected to 4. +Starting from 0, it will go to 1 then 2 then 3. After this, 2 to 4, thus BFS will be 0 1 2 3 4. +``` + +**Example 2:** + +``` +Input: V = 3, E = 2, adj = {{1,2},{},{}} +Output: 0 1 2 +Explanation: +0 is connected to 1, 2. +Starting from 0, it will go to 1 then 2, thus BFS will be 0 1 2. +``` + +### Your Task + +You don't need to read input or print anything. Your task is to complete the function `bfsOfGraph()` which takes the integer `V` denoting the number of vertices and adjacency list as input parameters and returns a list containing the BFS traversal of the graph starting from the 0th vertex from left to right. + +**Expected Time Complexity:** $O(V + E)$ +**Expected Auxiliary Space:** $O(V)$ + +**Constraints** +- $1 ≀ V, E ≀ 10^4$ + +## Solution + +### Intuition & Approach + +Breadth First Search (BFS) is a method to traverse a graph level by level, starting from a given node. We use a queue data structure to facilitate this traversal. The main steps are: + +1. Create a boolean list `visited` to mark all vertices as not visited. +2. Initialize the traversal from the starting vertex (0th vertex). +3. Use a queue to explore nodes level by level, marking each node as visited once it is processed. +4. For each node, explore its adjacent vertices that have not been visited yet, marking them as visited and adding them to the queue. +5. Continue this process until the queue is empty. + +### Implementation + + + + +```python +from collections import deque + +class Solution: + + def bfsOfGraph(self, V, adj): + visited = [False] * V + queue = deque([0]) + visited[0] = True + result = [] + + while queue: + node = queue.popleft() + result.append(node) + for neighbor in adj[node]: + if not visited[neighbor]: + queue.append(neighbor) + visited[neighbor] = True + return result +``` + + + + +```java +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +class Solution { + public ArrayList bfsOfGraph(int V, ArrayList> adj) { + ArrayList traversal = new ArrayList<>(); + Queue queue = new LinkedList<>(); + boolean[] visited = new boolean[V]; + queue.add(0); + visited[0] = true; + + while (!queue.isEmpty()) { + int node = queue.poll(); + traversal.add(node); + for (int neighbor : adj.get(node)) { + if (!visited[neighbor]) { + queue.add(neighbor); + visited[neighbor] = true; + } + } + } + return traversal; + } +} +``` + + + + +```cpp +#include +#include + +class Solution { +public: + std::vector bfsOfGraph(int V, std::vector adj[]) { + std::vector result; + std::vector visited(V, false); + std::queue q; + + q.push(0); + visited[0] = true; + + while (!q.empty()) { + int node = q.front(); + q.pop(); + result.push_back(node); + for (int neighbor : adj[node]) { + if (!visited[neighbor]) { + q.push(neighbor); + visited[neighbor] = true; + } + } + } + return result; + } +}; +``` + + + + +```javascript +class Solution { + bfsOfGraph(V, adj) { + let visited = new Array(V).fill(false); + let queue = [0]; + visited[0] = true; + let result = []; + + while (queue.length > 0) { + let node = queue.shift(); + result.push(node); + for (let neighbor of adj[node]) { + if (!visited[neighbor]) { + queue.push(neighbor); + visited[neighbor] = true; + } + } + } + return result; + } +} +``` + + + + +```typescript +class Solution { + bfsOfGraph(V: number, adj: number[][]): number[] { + let visited = new Array(V).fill(false); + let queue: number[] = [0]; + visited[0] = true; + let result: number[] = []; + + while (queue.length > 0) { + let node = queue.shift() as number; + result.push(node); + for (let neighbor of adj[node]) { + if (!visited[neighbor]) { + queue.push(neighbor); + visited[neighbor] = true; + } + } + } + return result; + } +} +``` + + + + +--- + +## Complexity analysis + +The provided solutions efficiently perform a Breadth First Search (BFS) traversal of a directed graph. By starting from the 0th vertex and using a queue to manage the traversal, the algorithms ensure that all reachable vertices are visited in the correct order. The solutions operate in $O(V + E)$ time and use $O(V)$ space complexity, where V and E are the numbers of vertices and edges in the graph, respectively. + +**Time Complexity:** $O(V + E)$ +**Auxiliary Space:** $O(V)$ + +## References + +- **GeeksforGeeks Problem:** [BFS of graph](https://www.geeksforgeeks.org/problems/bfs-traversal-of-graph/0) +- **Author GeeksforGeeks Profile:** [GeeksforGeeks](https://www.geeksforgeeks.org/user/GeeksforGeeks/) \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/check-for-balanced-tree.md b/solutions/gfg-solutions/Easy problems/check-for-balanced-tree.md new file mode 100644 index 0000000..6b49186 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/check-for-balanced-tree.md @@ -0,0 +1,255 @@ +--- +id: check-for-balanced-tree +title: Check for balanced Tree +sidebar_label: 4 Check for balanced tree +tags: + - Binary Tree + - Depth-First Search + - Recursion + - LeetCode + - C++ + - Java + - Python +description: "This is a solution to the Balanced Binary Tree problem on LeetCode." +--- + +## Problem Description + +Given a binary tree, determine if it is height-balanced. + +A height-balanced binary tree is defined as: + +- A binary tree in which the left and right subtrees of every node differ in height by no more than 1. + +### Examples + +**Example 1:** + +![input Tree](https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg) + +``` +Input: root = [3,9,20,null,null,15,7] +Output: true +``` + +**Example 2:** + +![input Tree](https://assets.leetcode.com/uploads/2020/10/06/balance_2.jpg) +``` +Input: root = [1,2,2,3,3,null,null,4,4] +Output: false +``` + +**Example 3:** + +``` +Input: root = [] +Output: true +``` + +### Constraints + +- The number of nodes in the tree is in the range `[0, 5000]`. +- $-10^4 <=$ Node.val $<= 10^4$ + +--- + +## Solution for Balanced Binary Tree Problem + + + + +### Approach 1: Top-Down + +#### Intuition + +This method checks whether the tree is balanced strictly according to the definition of a balanced binary tree: the difference between the heights of the two subtrees is not greater than 1, and both the left and right subtrees are also balanced. With the helper function depth(), we can easily write the code. + +#### Implementation + +Implement a helper function `depth(root)` that returns the depth of the tree rooted at root. +Check if the absolute difference between the depths of the left and right subtrees is not greater than 1. +Recursively check if both the left and right subtrees are balanced. +Return true if the tree is balanced, otherwise return false. + +#### Code in Different Languages + + + + + ```java + class Solution { + public int depth(TreeNode root) { + if (root == null) return 0; + return Math.max(depth(root.left), depth(root.right)) + 1; + } + + public boolean isBalanced(TreeNode root) { + if (root == null) return true; + + int left = depth(root.left); + int right = depth(root.right); + + return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right); + } + } + ``` + + + + + ```python + class Solution: + def depth(self, root: TreeNode) -> int: + if root is None: + return 0 + return max(self.depth(root.left), self.depth(root.right)) + 1 + + def isBalanced(self, root: TreeNode) -> bool: + if root is None: + return True + + left = self.depth(root.left) + right = self.depth(root.right) + + return abs(left - right) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right) + ``` + + + + + ```cpp + class Solution { + public: + int depth(TreeNode* root) { + if (root == nullptr) return 0; + return max(depth(root->left), depth(root->right)) + 1; + } + + bool isBalanced(TreeNode* root) { + if (root == nullptr) return true; + + int left = depth(root->left); + int right = depth(root->right); + + return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right); + } + }; + ``` + + + + +#### Complexity Analysis + +- **Time Complexity**: O(n log n) in the worst case where n is the number of nodes in the tree. We visit each node once, and for each node, we calculate its depth. Since the depth calculation involves traversing the subtree, the overall time complexity is O(n log n). +- **Space Complexity**: O(n) for the recursive call stack. + + + + +### Approach 2: Bottom-Up + +#### Intuition + +The second method is based on DFS. Instead of calling depth() explicitly for each child node, we return the height of the current node in DFS recursion. When the subtree of the current node (inclusive) is balanced, the function dfsHeight() returns a non-negative value as the height. Otherwise, -1 is returned. According to the left height and right height of the two children, the parent node could check if the subtree is balanced and decide its return value. + +#### Implementation + +Implement a helper function dfsHeight(root) that returns the height of the tree rooted at root. +If the subtree rooted at root is balanced, return its height. Otherwise, return -1. +Check if the returned height is -1 to determine if the tree is balanced. + +#### Code in Different Languages + + + + + ```java + class Solution { + public int dfsHeight(TreeNode root) { + if (root == null) return 0; + + int leftHeight = dfsHeight(root.left); + if (leftHeight == -1) return -1; + int rightHeight = dfsHeight(root.right); + if (rightHeight == -1) return -1; + + if (Math.abs(leftHeight - rightHeight) > 1) return -1; + return Math.max(leftHeight, rightHeight) + 1; + } + + public boolean isBalanced(TreeNode root) { + return dfsHeight(root) != -1; + } + } + ``` + + + + + ```python + class Solution: + def dfsHeight(self, root: TreeNode) -> int: + if root is None: + return 0 + + leftHeight = self.dfsHeight(root.left) + if leftHeight == -1: + return -1 + right + + Height = self.dfsHeight(root.right) + if rightHeight == -1: + return -1 + + if abs(leftHeight - rightHeight) > 1: + return -1 + return max(leftHeight, rightHeight) + 1 + + def isBalanced(self, root: TreeNode) -> bool: + return self.dfsHeight(root) != -1 + ``` + + + + + ```cpp + class Solution { + public: + int dfsHeight(TreeNode* root) { + if (root == nullptr) return 0; + + int leftHeight = dfsHeight(root->left); + if (leftHeight == -1) return -1; + int rightHeight = dfsHeight(root->right); + if (rightHeight == -1) return -1; + + if (abs(leftHeight - rightHeight) > 1) return -1; + return max(leftHeight, rightHeight) + 1; + } + + bool isBalanced(TreeNode* root) { + return dfsHeight(root) != -1; + } + }; + ``` + + + + +#### Complexity Analysis + +- **Time Complexity**: O(n) in the worst case where n is the number of nodes in the tree. Each node is visited once. +- **Space Complexity**: O(n) for the recursive call stack. + + + + +--- + +## References + +- **GFG Problem**: [Check for Balanced Tree](https://www.geeksforgeeks.org/problems/check-for-balanced-tree/0) +- **Author GeeksforGeeks Profile:** [GeeksforGeeks](https://www.geeksforgeeks.org/user/GeeksforGeeks/) + diff --git a/solutions/gfg-solutions/Easy problems/common-elements1132.md b/solutions/gfg-solutions/Easy problems/common-elements1132.md new file mode 100644 index 0000000..5b2d67b --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/common-elements1132.md @@ -0,0 +1,221 @@ +--- +id: common-elements-sorted-arrays +title: Common in 3 Sorted Arrays +sidebar_label: 0014 - Common in 3 Sorted Arrays +tags: + - Easy + - Array + - GeeksforGeeks + - CPP + - Python + - DSA +description: "This tutorial covers the solution to the Common in 3 Sorted Arrays problem from the GeeksforGeeks website, featuring implementations in Python and C++." +--- + +## Problem Description + +Given three arrays sorted in increasing order. Find the elements that are common in all three arrays. Note: Handle duplicates without using any additional data structure. + +## Examples + +**Example 1:** + +``` +Input: +A = [1, 5, 10, 20, 40, 80] +B = [6, 7, 20, 80, 100] +C = [3, 4, 15, 20, 30, 70, 80, 120] + +Output: 20, 80 +Explanation: 20 and 80 are the common elements. +``` + +**Example 2:** + +``` +Input: +A = [1, 2, 3, 4, 5] +B = [1, 2, 5, 7, 9] +C = [1, 3, 4, 5, 8] + +Output: 1, 5 +Explanation: 1 and 5 are the common elements. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `commonElements()` which takes the arrays `A[], B[], C[]` and their sizes `n1, n2, n3` as input parameters and returns a list of integers containing the common elements in sorted order. + +Expected Time Complexity: $O(n1 + n2 + n3)$ + +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- `1 ≀ n1, n2, n3 ≀ 10^5` +- `The arrays can have up to 10^5 elements each.` +- `1 ≀ A[i], B[i], C[i] ≀ 10^9` + +## Problem Explanation + +The task is to find the common elements in three sorted arrays and handle duplicates without using any additional data structure. + +## Code Implementation + + + + + +```py +class Solution: + def commonElements(self, A, B, C, n1, n2, n3): + i, j, k = 0, 0, 0 + common = [] + + while i < n1 and j < n2 and k < n3: + if A[i] == B[j] == C[k]: + common.append(A[i]) + i += 1 + j += 1 + k += 1 + elif A[i] < B[j]: + i += 1 + elif B[j] < C[k]: + j += 1 + else: + k += 1 + + # Skip duplicates in A + while i > 0 and i < n1 and A[i] == A[i-1]: + i += 1 + # Skip duplicates in B + while j > 0 and j < n2 and B[j] == B[j-1]: + j += 1 + # Skip duplicates in C + while k > 0 and k < n3 and C[k] == C[k-1]: + k += 1 + + return common + +# Example usage +if __name__ == "__main__": + solution = Solution() + A = [1, 5, 10, 20, 40, 80] + B = [6, 7, 20, 80, 100] + C = [3, 4, 15, 20, 30, 70, 80, 120] + print(solution.commonElements(A, B, C, len(A), len(B), len(C))) # Expected output: [20, 80] +``` + + + + + +```cpp +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution { +public: + vector commonElements(int A[], int B[], int C[], int n1, int n2, int n3) { + vector common; + int i = 0, j = 0, k = 0; + + while (i < n1 && j < n2 && k < n3) { + if (A[i] == B[j] && B[j] == C[k]) { + common.push_back(A[i]); + i++; + j++; + k++; + } + else if (A[i] < B[j]) i++; + else if (B[j] < C[k]) j++; + else k++; + + // Skip duplicates in A + while (i > 0 && i < n1 && A[i] == A[i-1]) i++; + // Skip duplicates in B + while (j > 0 && j < n2 && B[j] == B[j-1]) j++; + // Skip duplicates in C + while (k > 0 && k < n3 && C[k] == C[k-1]) k++; + } + + return common; + } +}; + +//{ Driver Code Starts. +int main() { + int t; cin >> t; + while (t--) { + int n1, n2, n3; + cin >> n1 >> n2 >> n3; + int A[n1], B[n2], C[n3]; + + for (int i = 0; i < n1; i++) cin >> A[i]; + for (int i = 0; i < n2; i++) cin >> B[i]; + for (int i = 0; i < n3; i++) cin >> C[i]; + + Solution ob; + vector res = ob.commonElements(A, B, C, n1, n2, n3); + if (res.size() == 0) + cout << -1; + else + for (int i = 0; i < res.size(); i++) + cout << res[i] << " "; + cout << endl; + } +} +// } Driver Code Ends +``` + + + + +## Example Walkthrough + +**Example 1:** + +For the arrays: + +``` +A = [1, 5, 10, 20, 40, 80] +B = [6, 7, 20, 80, 100] +C = [3, 4, 15, 20, 30, 70, 80, 120] +``` + +1. The common elements in A, B, and C are 20 and 80. + +**Example 2:** + +For the arrays: + +``` +A = [1, 2, 3, 4, 5] +B = [1, 2, 5, 7, 9] +C = [1, 3, 4, 5, 8] +``` + +1. The common elements in A, B, and C are 1 and 5. + +## Solution Logic: + +1. Use three pointers to iterate through the three arrays simultaneously. +2. Compare the current elements pointed by the three pointers. +3. If they are equal, add the element to the result and move all three pointers forward. +4. If they are not equal, move the pointer(s) with the smallest value forward. +5. Skip any duplicate elements to avoid repetition in the result. + +## Time Complexity + +- The function iterates through each array once, so the time complexity is $O(n1 + n2 + n3)$. + +## Space Complexity + +- The function uses constant space, $O(1)$, apart from the space used for the result vector. + +## References + +- -**gfg Problem:** [gfg Problem](https://www.geeksforgeeks.org/problems/common-elements1132/1) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/count-digits.md b/solutions/gfg-solutions/Easy problems/count-digits.md new file mode 100644 index 0000000..8e786d5 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/count-digits.md @@ -0,0 +1,134 @@ +--- +id: count-digits +title: Count Digits +sidebar_label: Count-Digits +tags: + - Modular Arithmetic + - Algorithms +description: "This tutorial covers the solution to the Count Digits problem from the GeeksforGeeks." +--- +## Problem Description + +Given a number `n`. Count the number of digits in `n` which evenly divide n. Return an integer, total number of digits of n which divides n evenly. + +Note :- Evenly divides means whether `n` is divisible by a digit i.e. leaves a remainder `0` when divided. + +## Examples + +**Example 1:** + +``` +Input: n = 12 +Output: 2 +Explanation: 1, 2 when both divide 12 leaves remainder 0. +``` + +**Example 2:** + +``` +Input: n = 2446 +Output: 1 +Explanation: Here among 2, 4, 6 only 2 divides 2446 evenly while 4 and 6 do not. +``` + + +Expected Time Complexity: O(N) + +Expected Auxiliary Space: O(1) + +## Constraints + +* `1 ≀ N ≀ 10^5` + +## Problem Explanation + +The task is to traverse the number and count the digits. + +## Code Implementation + +### C++ Solution + +```cpp +int countDigits(int n) { + int count = 0; + int temp = n; + while (temp != 0) { + int digit = temp % 10; + if (n % digit == 0) { + count++; + } + temp /= 10; + } + return count; +} + + +``` + +```java + +public int countDigits(int n) { + int count = 0; + int temp = n; + while (temp != 0) { + int digit = temp % 10; + if (n % digit == 0) { + count++; + } + temp /= 10; + } + return count; +} + + +``` + +```python +def count_digits(n): + count = 0 + temp = n + while temp != 0: + digit = temp % 10 + if n % digit == 0: + count += 1 + temp //= 10 + return count + +``` + +```javascript +function countDigits(n) { + let count = 0; + let temp = n; + while (temp !== 0) { + const digit = temp % 10; + if (n % digit === 0) { + count++; + } + temp = Math.floor(temp / 10); + } + return count; +} + + +``` + +## Solution Logic: +1. Initialize a variable count to 0, which will store the number of digits that evenly divide n. +2. Initialize a variable temp to n, which will be used to iterate through each digit of n. +3. Use a while loop to iterate through each digit of n. In each iteration, do the following: + - Calculate the current digit by taking the remainder of temp divided by 10 (temp % 10). + - Check if n is divisible by the current digit by checking if n % digit == 0. If it is, increment count. + - Update temp by dividing it by 10 (temp /= 10). +4. Return count at the end of the function. + + + +## Time Complexity + +* The time complexity is $O(log(n))$ where n is the input number. This is because we are iterating through each digit of n using a while loop, and the number of digits in n is proportional to the logarithm of n. + + +## Space Complexity + +* The auxiliary space complexity is $O(1)$ due to the only extra memory used is for temporary variables while swapping two values in Array. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/delete-middle-of-linked-list.md b/solutions/gfg-solutions/Easy problems/delete-middle-of-linked-list.md new file mode 100644 index 0000000..27f5431 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/delete-middle-of-linked-list.md @@ -0,0 +1,175 @@ +--- +id: delete-middle-of-linked-list +title: Delete Middle of Linked List +sidebar_label: 5 Delete Middle of Linked List +tags: +- Linked List +- Python +- Java +- C++ +- JavaScript +- TypeScript +description: "This document provides solutions to the problem of deleting the middle node from a singly linked list in various programming languages." +--- + +## Problem + +Given a singly linked list, delete the middle of the linked list. For example, if given linked list is 1->2->3->4->5 then linked list should be modified to 1->2->4->5. +If there are even nodes, then there would be two middle nodes, we need to delete the second middle element. For example, if given linked list is 1->2->3->4->5->6 then it should be modified to 1->2->3->5->6. +If the input linked list has a single node, then it should return NULL. + +### Examples + +**Example 1:** + +``` +Input: +LinkedList: 1->2->3->4->5 +Output: +1 2 4 5 +``` + +**Example 2:** + +``` +Input: +LinkedList: 2->4->6->7->5->1 +Output: +2 4 6 5 1 +``` + +### Your Task +The task is to complete the function `deleteMid()` which takes head of the linked list and returns head of the linked list with the middle element deleted. If the linked list is empty or contains a single element, then it should return NULL. + +**Expected Time Complexity:** $O(n)$ +**Expected Auxiliary Space:** $O(1)$ + +### Constraints +- $1 ≀ n ≀ 10^5$ +- $1 ≀ value[i] ≀ 10^9$ + +## Solution + +### Intuition & Approach + +The simplest idea is to make two pointers, `fast` and `slow`. Increment the `fast` pointer by two steps and the `slow` pointer by one step until the `fast` pointer reaches the end of the linked list. By then, the `slow` pointer will have reached the exact middle of the list. + +To delete the middle node, ensure that the `slow` pointer is at the node just before the middle. This can be done by starting the `fast` pointer from the second node instead of the first. Then, skip the middle node by changing the `next` pointer of the `slow` node to `slow->next->next` or `slow.next.next`. + +**Edge Case:** If there is only one node in the linked list, return NULL or None. + +### Complexity +- **Time Complexity:** $O(n)$- **Space Complexity:** O(1) + +### Implementation + + + + +```python +class Solution: + def deleteMid(self, head): + if not head.next: + return None + slow, fast = head, head.next + while fast and fast.next and fast.next.next: + fast = fast.next.next + slow = slow.next + slow.next = slow.next.next + return head +``` + + + + +```java +class Solution { + public ListNode deleteMid(ListNode head) { + if (head == null || head.next == null) { + return null; + } + ListNode slow = head, fast = head.next; + while (fast != null && fast.next != null && fast.next.next != null) { + fast = fast.next.next; + slow = slow.next; + } + slow.next = slow.next.next; + return head; + } +} +``` + + + + +```cpp +class Solution { +public: + ListNode* deleteMid(ListNode* head) { + if (head->next == nullptr) { + return nullptr; + } + ListNode* slow = head; + ListNode* fast = head->next; + while (fast != nullptr && fast->next != nullptr && fast->next->next != nullptr) { + fast = fast->next->next; + slow = slow->next; + } + slow->next = slow->next->next; + return head; + } +}; +``` + + + + +```javascript +function deleteMid(head) { + if (!head.next) { + return null; + } + let slow = head, fast = head.next; + while (fast !== null && fast.next !== null && fast.next.next !== null) { + fast = fast.next.next; + slow = slow.next; + } + slow.next = slow.next.next; + return head; +} +``` + + + + +```typescript +function deleteMid(head: ListNode | null): ListNode | null { + if (!head || !head.next) { + return null; + } + let slow: ListNode | null = head, fast: ListNode | null = head.next; + while (fast !== null && fast.next !== null && fast.next.next !== null) { + fast = fast.next.next; + slow = slow.next; + } + if (slow && slow.next) { + slow.next = slow.next.next; + } + return head; +} +``` + + + + +### Complexity +- **Time Complexity:** $O(n)$ +- **Space Complexity:** $O(1)$ + +--- + +## References + +- **GeeksforGeeks Problem:** [Delete Middle of Linked List](https://www.geeksforgeeks.org/problems/delete-middle-of-linked-list/0) +- **Author GeeksforGeeks Profile:** [GeeksforGeeks](https://www.geeksforgeeks.org/user/GeeksforGeeks/) + diff --git a/solutions/gfg-solutions/Easy problems/delete-without-head-pointer.md b/solutions/gfg-solutions/Easy problems/delete-without-head-pointer.md new file mode 100644 index 0000000..777486a --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/delete-without-head-pointer.md @@ -0,0 +1,224 @@ +--- +id: delete-without-head-pointer +title: Delete without Head Pointer +sidebar_label: 3 Delete without Head Pointer +tags: +- Linked List +- Python +- Java +- C++ +- JavaScript +- TypeScript +description: "This document provides solutions to the problem of deleting a node from a singly linked list without having a reference to the head pointer in various programming languages." +--- + +## Problem + +You are given a node `del_node` of a Singly Linked List where you have to delete a value of the given node from the linked list, but you are not given the head of the list. + +By deleting the node value, we mean that: +- The value of the given node should not exist in the linked list. +- The number of nodes in the linked list should decrease by one. +- All the values before and after the `del_node` node should be in the same order. + +Note: +- Multiple nodes can have the same values as the `del_node`, but you must only remove the node whose pointer `del_node` is given to you. +- It is guaranteed that there exists a node with a value equal to the `del_node` value, and it will not be the last node of the linked list. + +### Examples + +**Example 1:** + +``` +Input: +Linked List = 1 -> 2 +del_node = 1 +Output: +2 + +Explanation: +After deleting 1 from the linked list, +we have remaining nodes as 2. +``` + +**Example 2:** + +``` +Input: +Linked List = 10 -> 20 -> 4 -> 30 +del_node = 20 +Output: +10 4 30 + +Explanation: +After deleting 20 from the linked list, +we have remaining nodes as 10, 4, 30. +``` + +### Your Task +You don't need to read or print anything. You only need to complete the function `deleteNode()` which takes a reference of the deleting node value and your task is to delete the given node value. + +**Expected Time Complexity:** $O(1)$ +**Expected Auxiliary Space:** $O(1)$ + +### Constraints +- $2 ≀ n ≀ 10^3$ +- $1 ≀ elements of the linked list ≀ 10^9$ + +## Solution + +### Approach + +To delete a node without a reference to the head pointer, we can mimic the effect of deleting the node by copying the value of the next node to the given node (`del_node`) and then deleting the next node. + +### Implementation + + + + +```python +class Solution: + + def reverseDLL(self, head): + while head: + head.next, head.prev = head.prev, head.next + if not head.prev:return head + head=head.prev +``` + + + + +```java +class Node { + int data; + Node next; + Node prev; + + Node(int data) { + this.data = data; + this.next = null; + this.prev = null; + } +} + +class Solution { + public Node reverseDLL(Node head) { + while (head != null) { + Node temp = head.next; + head.next = head.prev; + head.prev = temp; + if (head.prev == null) { + return head; + } + head = head.prev; + } + return head; + } +} +``` + + + + +```cpp +#include +using namespace std; + +class Node { +public: + int data; + Node* next; + Node* prev; + Node(int data) { + this->data = data; + this->next = nullptr; + this->prev = nullptr; + } +}; + +class Solution { +public: + Node* reverseDLL(Node* head) { + while (head != nullptr) { + swap(head->next, head->prev); + if (head->prev == nullptr) { + return head; + } + head = head->prev; + } + return head; + } +}; +``` + + + + +```javascript +class Node { + constructor(data) { + this.data = data; + this.next = null; + this.prev = null; + } +} + +class Solution { + reverseDLL(head) { + while (head !== null) { + [head.next, head.prev] = [head.prev, head.next]; + if (head.prev === null) { + return head; + } + head = head.prev; + } + return head; + } +} +``` + + + + +```typescript +class Node { + data: number; + next: Node | null; + prev: Node | null; + + constructor(data: number) { + this.data = data; + this.next = null; + this.prev = null; + } +} + +class Solution { + reverseDLL(head: Node | null): Node | null { + while (head !== null) { + [head.next, head.prev] = [head.prev, head.next]; + if (head.prev === null) { + return head; + } + head = head.prev; + } + return head; + } +} +``` + + + + +### Complexity Analysis + +- **Time Complexity:** $O(1)$, as the deletion operation requires constant time regardless of the size of the linked list. +- **Space Complexity:** $O(1)$, as the algorithm uses only a constant amount of extra space regardless of the input size. + +--- + +## References + +- **GeeksforGeeks Problem:** [Delete without head pointer](https://www.geeksforgeeks.org/problems/delete-without-head-pointer/0) +- **Author GeeksforGeeks Profile:** [GeeksforGeeks](https://www.geeksforgeeks.org/user/GeeksforGeeks/) diff --git a/solutions/gfg-solutions/Easy problems/determine-if-two-trees-are-identical.md b/solutions/gfg-solutions/Easy problems/determine-if-two-trees-are-identical.md new file mode 100644 index 0000000..c425ea8 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/determine-if-two-trees-are-identical.md @@ -0,0 +1,258 @@ +--- +id: determine-if-two-trees-are-identical +title: Determine if Two Trees are Identical (gfg) +sidebar_label: 0012 - Determine if Two Trees are Identical +tags: + - Easy + - Tree + - Binary Tree + - GeeksforGeeks + - CPP + - Python + - DSA +description: "This tutorial covers the solution to the Determine if Two Trees are Identical problem from the GeeksforGeeks website, featuring implementations in Python and C++." +--- + +## Problem Description + +Given two binary trees, the task is to find if both of them are identical or not. Note: You need to return true or false, the printing is done by the driver code. + +## Examples + +**Example 1:** + +``` +Input: + Tree 1: + 1 + / \ + 2 3 + + Tree 2: + 1 + / \ + 2 3 +Output: Yes +``` + +**Example 2:** + +``` +Input: + Tree 1: + 1 + / \ + 2 3 + + Tree 2: + 1 + / \ + 3 2 +Output: No +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `isIdentical()` which takes the roots of both trees as input and returns true if the trees are identical, otherwise false. + +Expected Time Complexity: $O(N)$, where N is the number of nodes in the trees. + +Expected Auxiliary Space: $O(H)$, where H is the height of the trees. + +## Constraints + +- `1 ≀ Number of nodes ≀ 10^5` +- `1 ≀ Data of a node ≀ 10^5` + +## Problem Explanation + +Two trees are considered identical if they have the same structure and their corresponding nodes have the same value. + +## Code Implementation + + + + + +```py +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def isIdentical(self, r1: TreeNode, r2: TreeNode) -> bool: + if not r1 and not r2: + return True + if not r1 or not r2: + return False + return (r1.val == r2.val) and self.isIdentical(r1.left, r2.left) and self.isIdentical(r1.right, r2.right) + +# Example usage +if __name__ == "__main__": + root1 = TreeNode(1) + root1.left = TreeNode(2) + root1.right = TreeNode(3) + + root2 = TreeNode(1) + root2.left = TreeNode(2) + root2.right = TreeNode(3) + + solution = Solution() + print(solution.isIdentical(root1, root2)) # Expected output: True +``` + + + + + +```cpp +//{ Driver Code Starts +#include +using namespace std; + +struct Node { + int data; + Node* left; + Node* right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; + +// } Driver Code Ends +class Solution { +public: + // Function to check if two trees are identical. + bool isIdentical(Node* r1, Node* r2) { + if (!r1 && !r2) return true; + if (!r1 || !r2) return false; + return (r1->data == r2->data) && isIdentical(r1->left, r2->left) && isIdentical(r1->right, r2->right); + } +}; + +//{ Driver Code Starts. +// Function to Build Tree +Node* buildTree(string str) { + if (str.length() == 0 || str[0] == 'N') return NULL; + + vector ip; + istringstream iss(str); + for (string str; iss >> str;) ip.push_back(str); + + Node* root = new Node(stoi(ip[0])); + queue queue; + queue.push(root); + + int i = 1; + while (!queue.empty() && i < ip.size()) { + Node* currNode = queue.front(); + queue.pop(); + + string currVal = ip[i]; + if (currVal != "N") { + currNode->left = new Node(stoi(currVal)); + queue.push(currNode->left); + } + + i++; + if (i >= ip.size()) break; + currVal = ip[i]; + + if (currVal != "N") { + currNode->right = new Node(stoi(currVal)); + queue.push(currNode->right); + } + i++; + } + + return root; +} + +int main() { + int tc; + scanf("%d ", &tc); + while (tc--) { + string str, str1; + getline(cin, str); + Node* rootA = buildTree(str); + getline(cin, str1); + Node* rootB = buildTree(str1); + Solution ob; + if (ob.isIdentical(rootA, rootB)) { + cout << "Yes\n"; + } else { + cout << "No\n"; + } + } + return 0; +} +// } Driver Code Ends +``` + + + + +## Example Walkthrough + +For the trees: + +``` + Tree 1: + 1 + / \ + 2 3 + + Tree 2: + 1 + / \ + 2 3 +``` + +1. The root nodes are both 1. +2. The left children are both 2. +3. The right children are both 3. +4. Since all corresponding nodes match, the trees are identical. + +For the trees: + +``` + Tree 1: + 1 + / \ + 2 3 + + Tree 2: + 1 + / \ + 3 2 +``` + +1. The root nodes are both 1. +2. The left child of Tree 1 is 2 and of Tree 2 is 3. +3. The right child of Tree 1 is 3 and of Tree 2 is 2. +4. Since corresponding nodes do not match, the trees are not identical. + +## Solution Logic: + +1. Recursively compare the current nodes of both trees. +2. Check if the values of the nodes are the same. +3. Check if the left children of both nodes are identical. +4. Check if the right children of both nodes are identical. + +## Time Complexity + +- The function visits each node once, so the time complexity is $O(N)$. + +## Space Complexity + +- The auxiliary space complexity is $O(H)$ due to the recursion stack, where H is the height of the tree. + +## References + +- **gfg Problem:** [gfg Problem](https://www.geeksforgeeks.org/problems/determine-if-two-trees-are-identical/1?page=2&difficulty=Easy&sortBy=submissions) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/dfs-of-graph.md b/solutions/gfg-solutions/Easy problems/dfs-of-graph.md new file mode 100644 index 0000000..b6fffd8 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/dfs-of-graph.md @@ -0,0 +1,163 @@ +--- +id: dfs-of-graph +title: DFS of Graph +sidebar_label: 0022 - DFS of Graph +tags: + - Easy + - Graph + - DFS + - GeeksforGeeks + - CPP + - DSA +description: "This tutorial covers the solution to the DFS of Graph problem from the GeeksforGeeks website, featuring implementations in C++." +--- +## Problem Description + +You are given a connected undirected graph. Perform a Depth First Traversal of the graph. +Note: Use the recursive approach to find the DFS traversal of the graph starting from the 0th vertex from left to right according to the graph. + +## Examples + +**Example 1:** + +``` +Input: +Graph: +0->1, 0->2, 1->2, 2->0, 2->3, 3->3 +Output: 0 1 2 3 +Explanation: +0 is connected to 1, 2. +1 is connected to 2. +2 is connected to 0, 3. +3 is connected to 3. +``` + +**Example 2:** + +``` +Input: +Graph: +0->1, 0->2, 1->2, 2->0, 2->3, 3->3 +Output: 0 1 2 3 +Explanation: +0 is connected to 1, 2. +1 is connected to 2. +2 is connected to 0, 3. +3 is connected to 3. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `dfsOfGraph()` which takes the number of vertices `V` and an adjacency list `adj` as input parameters and returns a list containing the DFS traversal of the graph starting from the 0th vertex. + +Expected Time Complexity: O(V + E) + +Expected Auxiliary Space: O(V) + +## Constraints + +* `1 ≀ V, E ≀ 10^4` + +## Problem Explanation + +The task is to traverse a given connected undirected graph using Depth First Search (DFS). DFS is a traversal algorithm that starts at a source node and explores as far as possible along each branch before backtracking. This recursive approach uses a stack data structure for its implementation. + +## Code Implementation + +### C++ Solution + +```cpp +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution { + public: + // Function to return a list containing the DFS traversal of the graph. + void dfsUtil(int node, vector adj[], vector& visited, vector& result) { + visited[node] = true; + result.push_back(node); + + for (int neighbor : adj[node]) { + if (!visited[neighbor]) { + dfsUtil(neighbor, adj, visited, result); + } + } + } + + vector dfsOfGraph(int V, vector adj[]) { + vector result; + vector visited(V, false); + + dfsUtil(0, adj, visited, result); + + return result; + } +}; + +//{ Driver Code Starts. +int main() { + int tc; + cin >> tc; + while (tc--) { + int V, E; + cin >> V >> E; + + vector adj[V]; + + for (int i = 0; i < E; i++) { + int u, v; + cin >> u >> v; + adj[u].push_back(v); + adj[v].push_back(u); + } + Solution obj; + vector ans = obj.dfsOfGraph(V, adj); + for (int i = 0; i < ans.size(); i++) { + cout << ans[i] << " "; + } + cout << endl; + } + return 0; +} +// } Driver Code Ends +``` + +## Example Walkthrough + +**Example 1:** + +For the input: +``` +Graph: +0->1, 0->2, 1->2, 2->0, 2->3, 3->3 +Output: 0 1 2 3 +``` +1. Start DFS from node 0. +2. Visit node 1 from node 0. +3. Visit node 2 from node 1. +4. Visit node 3 from node 2. +5. Backtrack to node 2, then to node 1, and finally to node 0. + +The result of the traversal is [0, 1, 2, 3]. + +## Solution Logic: + +1. Use a recursive helper function `dfsUtil` to perform DFS starting from a given node. +2. Mark the node as visited and add it to the result list. +3. Recursively visit all unvisited neighbors of the current node. +4. The main function initializes the visited list and starts the DFS from node 0. + +## Time Complexity + +* The time complexity is $O(V + E)$ where $V$ is the number of vertices and $E$ is the number of edges, as each vertex and edge is visited once. + +## Space Complexity + +* The auxiliary space complexity is $O(V)$ due to the visited list and the recursive stack. + +## References + +- **GeeksforGeeks Problem:** [DFS of Graph](https://www.geeksforgeeks.org/problems/depth-first-traversal-for-a-graph/1?page=2&difficulty=Easy&sortBy=submissions) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/equilibrium-point.md b/solutions/gfg-solutions/Easy problems/equilibrium-point.md new file mode 100644 index 0000000..d143e7e --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/equilibrium-point.md @@ -0,0 +1,178 @@ +--- +id: equilibrium-point +title: Equilibrium Point +sidebar_label: 0018 - Equilibrium Point +tags: + - Easy + - Array + - GeeksforGeeks + - CPP + - DSA +description: "This tutorial covers the solution to the Equilibrium Point problem from the GeeksforGeeks website, featuring implementations in Python and C++." +--- +## Problem Description + +Given an array `arr` of non-negative numbers, the task is to find the first equilibrium point in the array. The equilibrium point in an array is an index (or position) such that the sum of all elements before that index is equal to the sum of elements after it. + +**Note:** Return equilibrium point in 1-based indexing. Return -1 if no such point exists. + +## Examples + +**Example 1:** + +``` +Input: +arr = [1, 3, 5, 2, 2] +Output: 3 +Explanation: The equilibrium point is at position 3 as the sum of elements before it (1+3) is equal to the sum of elements after it (2+2). +``` + +**Example 2:** + +``` +Input: +arr = [1] +Output: 1 +Explanation: Since there's only one element, it is the equilibrium point. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `equilibriumPoint()` which takes the array `arr` as input and returns the 1-based index of the equilibrium point. If no such point exists, return -1. + +Expected Time Complexity: $O(N)$ + +Expected Auxiliary Space: $O(1)$ + +## Constraints + +* `1 ≀ N ≀ 10^6` +* `0 ≀ arr[i] ≀ 10^8` + +## Problem Explanation + +The task is to find the first index in the array where the sum of elements before it is equal to the sum of elements after it. The solution should be efficient in terms of both time and space complexity. + +## Code Implementation + + + + + + ```py + class Solution: + def equilibriumPoint(self, arr): + total_sum = sum(arr) + left_sum = 0 + + for i, num in enumerate(arr): + total_sum -= num + if left_sum == total_sum: + return i + 1 + left_sum += num + + return -1 + + # Example usage + if __name__ == "__main__": + solution = Solution() + print(solution.equilibriumPoint([1, 3, 5, 2, 2])) # Expected output: 3 + print(solution.equilibriumPoint([1])) # Expected output: 1 + ``` + + + + + + ```cpp + //{ Driver Code Starts + // Initial Template for C++ + #include + using namespace std; + + // } Driver Code Ends + class Solution { + public: + // Function to find equilibrium point in the array. + // arr: input array + int equilibriumPoint(vector &arr) { + long long total_sum = accumulate(arr.begin(), arr.end(), 0LL); + long long left_sum = 0; + + for (int i = 0; i < arr.size(); i++) { + total_sum -= arr[i]; + if (left_sum == total_sum) { + return i + 1; // 1-based index + } + left_sum += arr[i]; + } + + return -1; + } + }; + + //{ Driver Code Starts. + int main() { + int t; + cin >> t; + cin.ignore(); // To discard any leftover newline characters + while (t--) { + vector arr; + string input; + getline(cin, input); // Read the entire line for the array elements + stringstream ss(input); + long long number; + while (ss >> number) { + arr.push_back(number); + } + + Solution ob; + cout << ob.equilibriumPoint(arr) << endl; + } + } + // } Driver Code Ends + ``` + + + + +## Example Walkthrough + +**Example 1:** + +For the input array: +``` +arr = [1, 3, 5, 2, 2] +``` +1. The equilibrium point is at position 3 because the sum of elements before it (1+3) is equal to the sum of elements after it (2+2). + +**Example 2:** + +For the input array: +``` +arr = [1] +``` +1. Since there's only one element, it is the equilibrium point. + +## Solution Logic: + +1. Calculate the total sum of the array. +2. Initialize the left sum to zero. +3. Traverse the array: + - Subtract the current element from the total sum to get the right sum. + - If the left sum equals the right sum, return the current index (1-based). + - Add the current element to the left sum. +4. If no equilibrium point is found, return -1. + +## Time Complexity + +* The function traverses the array once, so the time complexity is $O(N)$. + +## Space Complexity + +* The function uses a few extra variables, so the auxiliary space complexity is $O(1)$. + +## References + +- **GeeksforGeeks Problem:** [Equilibrium Point](https://www.geeksforgeeks.org/problems/equilibrium-point-1587115620/1) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/find-duplicates-in-an-array.md b/solutions/gfg-solutions/Easy problems/find-duplicates-in-an-array.md new file mode 100644 index 0000000..989f521 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/find-duplicates-in-an-array.md @@ -0,0 +1,183 @@ +--- +id: find-duplicates-in-an-array +title: Find Duplicates in an Array (gfg) +sidebar_label: 0006 - Find Duplicates in an Array +tags: + - Easy + - Array + - GeeksforGeeks + - CPP + - Python + - DSA +description: "This tutorial covers the solution to the Find Duplicates in an Array problem from the GeeksforGeeks website, featuring implementations in Python and C++." +--- + +## Problem Description + +Given an array `arr` of size `n` which contains elements in the range from 0 to `n-1`, you need to find all the elements occurring more than once in the given array. Return the answer in ascending order. If no such element is found, return a list containing [-1]. + +:::note +Try and perform all operations within the provided array. The extra (non-constant) space needs to be used only for the array to be returned. +::: + +## Examples + +**Example 1:** + +``` +Input: arr = [2, 3, 1, 2, 3] +Output: [2, 3] +Explanation: 2 and 3 occur more than once in the array. +``` + +**Example 2:** + +``` +Input: arr = [0, 1, 2, 3] +Output: [-1] +Explanation: No element occurs more than once. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `duplicates()` which takes the array `arr` as input and returns a list of the duplicate elements in ascending order. + +Expected Time Complexity: $O(n)$ + +Expected Auxiliary Space: $O(1)$ (excluding the space for the output list) + +## Constraints + +- `1 ≀ n ≀ 10^5` +- `0 ≀ arr[i] ≀ n-1` + +## Problem Explanation + +The problem is to find the duplicate elements in an array of size `n`, where the elements range from 0 to `n-1`. The duplicates should be returned in ascending order. If no duplicates are found, return [-1]. + +## Code Implementation + + + + + +```py +class Solution: + def duplicates(self, arr): + n = len(arr) + # Use the array elements as index + for i in range(n): + arr[arr[i] % n] += n + + # Collect elements that occur more than once + result = [i for i in range(n) if arr[i] // n > 1] + + return result if result else [-1] + +# Example usage +if __name__ == "__main__": + solution = Solution() + print(solution.duplicates([2, 3, 1, 2, 3])) # Expected output: [2, 3] + print(solution.duplicates([0, 1, 2, 3])) # Expected output: [-1] +``` + + + + + +```cpp +#include +#include +#include +using namespace std; + +class Solution { +public: + vector duplicates(vector& arr) { + int n = arr.size(); + vector result; + + // Use the array elements as index + for (int i = 0; i < n; i++) { + arr[arr[i] % n] += n; + } + + // Collect elements that occur more than once + for (int i = 0; i < n; i++) { + if (arr[i] / n > 1) { + result.push_back(i); + } + } + + if (result.empty()) { + return {-1}; + } + + return result; + } +}; + +// Example usage +void solve() { + int n; + cin >> n; + vector arr(n); + for (int i = 0; i < n; i++) { + cin >> arr[i]; + } + + Solution obj; + vector ans = obj.duplicates(arr); + for (int i : ans) { + cout << i << ' '; + } + cout << endl; +} + +int main() { + int t; + cin >> t; + + while (t--) { + solve(); + } + return 0; +} +``` + + + + +## Example Walkthrough + +For the array `arr = [2, 3, 1, 2, 3]`: + +1. Iterate through the array and use each element as an index. Increase the value at that index by `n` to mark the occurrence. +2. After the iteration, elements with values greater than `2 * n` indicate duplicates. +3. Collect such elements and return them in ascending order. + +For the array `arr = [0, 1, 2, 3]`: + +1. Iterate through the array and use each element as an index. Increase the value at that index by `n` to mark the occurrence. +2. After the iteration, no elements have values greater than `2 * n`. +3. Return [-1] since no duplicates are found. + +## Solution Logic: + +1. Iterate through the array, using each element as an index. +2. Increase the value at the calculated index by `n`. +3. After the iteration, check which elements have values greater than `2 * n` to find duplicates. +4. Collect such elements and return them in ascending order. + +## Time Complexity + +- The time complexity is $O(n)$, where n is the size of the input array. + +## Space Complexity + +- The auxiliary space complexity is $O(1)$ because we are not using any extra space proportional to the size of the input array. + +## References + +- **gfg Problem:** [gfg Problem](https://www.geeksforgeeks.org/problems/find-duplicates-in-an-array/1?page=1&difficulty=Easy&sortBy=submissions) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/find-pair-given-difference.md b/solutions/gfg-solutions/Easy problems/find-pair-given-difference.md new file mode 100644 index 0000000..cfafd9b --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/find-pair-given-difference.md @@ -0,0 +1,184 @@ +--- +id: find-pair-given-difference +title: Find Pair Given Difference +sidebar_label: 0029 - Find Pair Given Difference +tags: + - Easy + - Array + - GeeksforGeeks + - CPP + - DSA +description: "This tutorial covers the solution to the Find Pair Given Difference problem from the GeeksforGeeks website, featuring implementations in C++." +--- +## Problem Description + +Given an array `arr[]` of size `n` and an integer `x`, return `1` if there exists a pair of elements in the array whose absolute difference is `x`, otherwise, return `-1`. + +## Examples + +**Example 1:** + +``` +Input: +n = 5 +arr[] = {1, 8, 30, 40, 100} +x = 60 + +Output: +1 + +Explanation: +The pair (100, 40) has an absolute difference of 60. +``` + +**Example 2:** + +``` +Input: +n = 3 +arr[] = {5, 10, 3} +x = 8 + +Output: +-1 + +Explanation: +There is no pair with an absolute difference of 8. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `findPair()` which takes the array and its size and an integer `x` as parameters and returns `1` if there exists a pair with an absolute difference of `x`, otherwise, return `-1`. + +Expected Time Complexity: O(N) + +Expected Auxiliary Space: O(N) + +## Constraints + +* `1 ≀ n ≀ 10^5` +* `1 ≀ arr[i] ≀ 10^5` +* `0 ≀ x ≀ 10^5` + +## Problem Explanation + +To find if there exists a pair with the given difference `x`, we can use a set to store the elements as we iterate through the array. For each element `arr[i]`, we check if `(arr[i] + x)` or `(arr[i] - x)` exists in the set. If either condition is true, we return `1`. If we complete the iteration without finding any such pair, we return `-1`. + +## Code Implementation + +### C++ Solution + +```cpp +// Initial template for C++ +#include +using namespace std; + +class Array { + public: + template + static void input(vector &A, int n) { + for (int i = 0; i < n; i++) { + scanf("%d ", &A[i]); + } + } + + template + static void print(vector &A) { + for (int i = 0; i < A.size(); i++) { + cout << A[i] << " "; + } + cout << endl; + } +}; + +class Solution { + public: + int findPair(int n, int x, vector &arr) { + unordered_set s; + for (int i = 0; i < n; i++) { + if (s.find(arr[i] + x) != s.end() || s.find(arr[i] - x) != s.end()) { + return 1; + } + s.insert(arr[i]); + } + return -1; + } +}; + +// Driver code +int main() { + int t; + scanf("%d ", &t); + while (t--) { + int n; + scanf("%d", &n); + + int x; + scanf("%d", &x); + + vector arr(n); + Array::input(arr, n); + + Solution obj; + int res = obj.findPair(n, x, arr); + + cout << res << endl; + } + return 0; +} +``` + +## Example Walkthrough + +**Example 1:** + +For the input: +``` +n = 5 +arr[] = {1, 8, 30, 40, 100} +x = 60 +``` + +1. Initialize an empty set `s`. +2. Iterate through the array: + - For `arr[0] = 1`: add 1 to the set. + - For `arr[1] = 8`: add 8 to the set. + - For `arr[2] = 30`: add 30 to the set. + - For `arr[3] = 40`: add 40 to the set. + - For `arr[4] = 100`: check if `100 - 60 = 40` is in the set (it is). +3. Return `1` as the pair `(100, 40)` has an absolute difference of 60. + +**Example 2:** + +For the input: +``` +n = 3 +arr[] = {5, 10, 3} +x = 8 +``` + +1. Initialize an empty set `s`. +2. Iterate through the array: + - For `arr[0] = 5`: add 5 to the set. + - For `arr[1] = 10`: add 10 to the set. + - For `arr[2] = 3`: add 3 to the set. +3. Return `-1` as no pair with an absolute difference of 8 is found. + +## Solution Logic: + +1. Use a set to store the elements. +2. For each element, check if `(arr[i] + x)` or `(arr[i] - x)` exists in the set. +3. Return `1` if a pair is found, otherwise return `-1`. + +## Time Complexity + +* The time complexity is $O(n)$ where $(n)$ is the number of elements in the array. + +## Space Complexity + +* The auxiliary space complexity is $O(n)$ as we use a set to store the elements. + +## References + +- **GeeksforGeeks Problem:** [Find pair given difference](https://www.geeksforgeeks.org/problems/find-pair-given-difference1559/1?page=2&difficulty=Easy&sortBy=submissions) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/first-repeating-element.md b/solutions/gfg-solutions/Easy problems/first-repeating-element.md new file mode 100644 index 0000000..36dc4cd --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/first-repeating-element.md @@ -0,0 +1,166 @@ +--- +id: first-repeating-element +title: First Repeating Element +sidebar_label: 0026 - First Repeating Element +tags: + - Easy + - Array + - GeeksforGeeks + - CPP + - DSA +description: "This tutorial covers the solution to the First Repeating Element problem from the GeeksforGeeks website, featuring implementations in C++." +--- +## Problem Description + +Given an array `arr[]` of size `n`, find the first repeating element. The element should occur more than once and the index of its first occurrence should be the smallest. + +**Note:** The position you return should be according to 1-based indexing. + +## Examples + +**Example 1:** + +``` +Input: +arr[] = {1, 5, 3, 4, 3, 5, 6} + +Output: +2 + +Explanation: +5 is the first element that repeats, and its first occurrence is at index 2. +``` + +**Example 2:** + +``` +Input: +arr[] = {1, 2, 3, 4} + +Output: +-1 + +Explanation: +There are no repeating elements, so the output is -1. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `firstRepeated()` which takes the array and its size as parameters and returns the position of the first repeating element. + +Expected Time Complexity: O(n) + +Expected Auxiliary Space: O(n) + +## Constraints + +* `1 ≀ n ≀ 10^6` +* `0 ≀ arr[i] ≀ 10^6` + +## Problem Explanation + +To find the first repeating element, we can use a hashmap to store the count of each element and another hashmap to store the first occurrence of each element. This way, we can efficiently determine the first repeating element and its position. + +## Code Implementation + +### C++ Solution + +```cpp +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution { + public: + // Function to return the position of the first repeating element. + int firstRepeated(vector &arr) { + unordered_map elementCount; + unordered_map firstOccurrence; + + for (int i = 0; i < arr.size(); i++) { + if (elementCount.find(arr[i]) == elementCount.end()) { + elementCount[arr[i]] = 1; + firstOccurrence[arr[i]] = i + 1; + } else { + elementCount[arr[i]]++; + } + } + + int minIndex = INT_MAX; + + for (int i = 0; i < arr.size(); i++) { + if (elementCount[arr[i]] > 1) { + if (firstOccurrence[arr[i]] < minIndex) { + minIndex = firstOccurrence[arr[i]]; + } + } + } + + if (minIndex == INT_MAX) { + return -1; + } + + return minIndex; + } +}; + +//{ Driver Code Starts. +int main() { + + int t; + cin >> t; + cin.ignore(); + while (t--) { + vector arr; + string input; + getline(cin, input); // Read the entire line for the array elements + stringstream ss(input); + int number; + while (ss >> number) { + arr.push_back(number); + } + + Solution ob; + cout << ob.firstRepeated(arr) << endl; + } + + return 0; +} +// } Driver Code Ends +``` + +## Example Walkthrough + +**Example 1:** + +For the input: +``` +arr[] = {1, 5, 3, 4, 3, 5, 6} +``` + +1. Create a hashmap `elementCount` to store the count of each element and another hashmap `firstOccurrence` to store the first occurrence index of each element. +2. Traverse the array and populate the `elementCount` and `firstOccurrence` hashmaps. +3. Find the first repeating element by checking the minimum index in `firstOccurrence` where the count of the element in `elementCount` is greater than 1. + +The result is 2, as 5 is the first repeating element with the smallest index. + +## Solution Logic: + +1. Use a hashmap to store the count of each element. +2. Use another hashmap to store the first occurrence index of each element. +3. Traverse the array to populate the hashmaps. +4. Find the first repeating element by checking the minimum index in `firstOccurrence` where the count of the element in `elementCount` is greater than 1. + +## Time Complexity + +* The time complexity is \(O(n)\) where \(n\) is the number of elements in the array, as we only iterate through the array once. + +## Space Complexity + +* The auxiliary space complexity is \(O(n)\) as we use two hashmaps to store the counts and first occurrences. + +## References + +- **GeeksforGeeks Problem:** [First Repeating Element](https://www.geeksforgeeks.org/problems/first-repeating-element4018/1?page=2&difficulty=Easy&sortBy=submissions) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/floor-in-a-sorted-array.md b/solutions/gfg-solutions/Easy problems/floor-in-a-sorted-array.md new file mode 100644 index 0000000..301fa1c --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/floor-in-a-sorted-array.md @@ -0,0 +1,202 @@ +--- +id: floor-in-sorted-array +title: Floor in a Sorted Array Problem (gfg) +sidebar_label: 0013 - Floor in a Sorted Array +tags: + - Easy + - Array + - Binary Search + - GeeksforGeeks + - CPP + - Python + - DSA +description: "This tutorial covers the solution to the Floor in a Sorted Array problem from the GeeksforGeeks website, featuring implementations in Python and C++." +--- + +## Problem Description + +Given a sorted array `arr[]` of size `n` without duplicates, and given a value `x`. Floor of `x` is defined as the largest element `k` in `arr[]` such that `k` is smaller than or equal to `x`. Find the index of `k` (0-based indexing). + +## Examples + +**Example 1:** + +``` +Input: +arr = [1, 2, 8, 10, 11, 12, 19] +x = 5 +Output: 1 +Explanation: The largest element less than or equal to 5 is 2, which is at index 1. +``` + +**Example 2:** + +``` +Input: +arr = [1, 2, 8, 10, 11, 12, 19] +x = 20 +Output: 6 +Explanation: The largest element less than or equal to 20 is 19, which is at index 6. +``` + +**Example 3:** + +``` +Input: +arr = [1, 2, 8, 10, 11, 12, 19] +x = 0 +Output: -1 +Explanation: No element is less than or equal to 0. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `findFloor()` which takes the sorted array `arr[]`, its size `n`, and the value `x` as inputs and returns the index of the floor of `x`. If there is no floor, return `-1`. + +Expected Time Complexity: $O(\log N)$ + +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- `1 ≀ n ≀ 10^7` +- `1 ≀ arr[i] ≀ 10^18` +- `0 ≀ x ≀ 10^18` + +## Problem Explanation + +The floor of a number `x` in a sorted array is the largest element in the array that is less than or equal to `x`. This problem can be efficiently solved using binary search due to the sorted nature of the array. + +## Code Implementation + + + + + +```py +from typing import List + +class Solution: + def findFloor(self, arr: List[int], n: int, x: int) -> int: + low, high = 0, n - 1 + floor_index = -1 + + while low <= high: + mid = (low + high) // 2 + + if arr[mid] == x: + return mid + elif arr[mid] < x: + floor_index = mid + low = mid + 1 + else: + high = mid - 1 + + return floor_index + +# Example usage +if __name__ == "__main__": + solution = Solution() + arr = [1, 2, 8, 10, 11, 12, 19] + x = 5 + print(solution.findFloor(arr, len(arr), x)) # Expected output: 1 +``` + + + + + +```cpp +//{ Driver Code Starts +#include +using namespace std; + +class Solution{ +public: + int findFloor(vector v, long long n, long long x){ + int low = 0, high = n - 1; + int floor_index = -1; + + while (low <= high) { + int mid = low + (high - low) / 2; + + if (v[mid] == x) { + return mid; + } else if (v[mid] < x) { + floor_index = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + + return floor_index; + } +}; + +int main() { + long long t; + cin >> t; + + while(t--){ + long long n; + cin >> n; + long long x; + cin >> x; + + vector v(n); + + for(long long i = 0; i < n; i++){ + cin >> v[i]; + } + + Solution obj; + cout << obj.findFloor(v, n, x) << endl; + } + + return 0; +} +// } Driver Code Ends +``` + + + + +## Example Walkthrough + +For the array `[1, 2, 8, 10, 11, 12, 19]` and `x = 5`: + +1. Start with the full array range. +2. Compare the middle element to `x`. +3. Adjust the search range based on whether the middle element is less than or greater than `x`. +4. Continue until the search range is exhausted. +5. The index of the largest element less than or equal to `x` is returned. + +For `x = 20`: + +1. The entire array is scanned. +2. The largest element less than or equal to 20 is 19 at index 6. + +For `x = 0`: + +1. No element is less than or equal to 0. +2. Return -1. + +## Solution Logic: + +1. Perform a binary search to find the largest element less than or equal to `x`. +2. Maintain a variable to keep track of the floor index during the search. +3. Return the floor index at the end of the search. + +## Time Complexity + +- The time complexity of the binary search is $O(\log N)$. + +## Space Complexity + +- The auxiliary space complexity is $O(1)$. + +## References + +- **gfg Problem:** [gfg Problem](https://www.geeksforgeeks.org/problems/floor-in-a-sorted-array-1587115620/1) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/height-of-binary-tree.md b/solutions/gfg-solutions/Easy problems/height-of-binary-tree.md new file mode 100644 index 0000000..ce9c87c --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/height-of-binary-tree.md @@ -0,0 +1,213 @@ +--- +id: height-of-binary-tree +title: Height of Binary Tree Problem (gfg) +sidebar_label: 0011 - Height of Binary Tree +tags: + - Easy + - Tree + - Binary Tree + - GeeksforGeeks + - CPP + - Python + - DSA +description: "This tutorial covers the solution to the Height of Binary Tree problem from the GeeksforGeeks website, featuring implementations in Python and C++." +--- +## Problem Description + +Given a binary tree, find its height. The height of a binary tree is the number of edges in the longest path from the root to a leaf node. + +## Examples + +**Example 1:** + +``` +Input: + 1 + / \ + 2 3 +Output: 2 +``` + +**Example 2:** + +``` +Input: + 1 + / + 2 + / + 3 +Output: 3 +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `height()` which takes the root of the tree as input and returns the height of the tree. + +Expected Time Complexity: $O(N)$, where N is the number of nodes in the tree. + +Expected Auxiliary Space: $O(N)$ + +## Constraints + +* `1 ≀ Number of nodes ≀ 10^5` +* `1 ≀ Data of a node ≀ 10^5` + +## Problem Explanation + +The height of a binary tree is defined as the number of edges in the longest path from the root node to a leaf node. For a tree with a single node, the height is 0. + +## Code Implementation + + + + + + ```py + # Definition for a binary tree node. + class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + class Solution: + def height(self, root: TreeNode) -> int: + if root is None: + return 0 + else: + # Compute the height of each subtree + left_height = self.height(root.left) + right_height = self.height(root.right) + # Return the larger one plus one for the root + return max(left_height, right_height) + 1 + + # Example usage + if __name__ == "__main__": + root = TreeNode(1) + root.left = TreeNode(2) + root.right = TreeNode(3) + solution = Solution() + print(solution.height(root)) # Expected output: 2 + ``` + + + + + + ```cpp + //{ Driver Code Starts + #include + using namespace std; + + struct Node { + int data; + Node* left; + Node* right; + + Node(int val) { + data = val; + left = right = NULL; + } + }; + + // } Driver Code Ends + class Solution { + public: + // Function to find the height of a binary tree. + int height(Node* node) { + if (node == NULL) return 0; + + // Compute the height of each subtree + int left_height = height(node->left); + int right_height = height(node->right); + + // Return the larger one plus one for the root + return max(left_height, right_height) + 1; + } + }; + + //{ Driver Code Starts. + int main() { + int t; + cin >> t; + while (t--) { + int n; + cin >> n; + + Node* root = new Node(1); // Example root node + + // Constructing the tree + queue q; + q.push(root); + for (int i = 0; i < n; i++) { + int a, b; + char lr; + cin >> a >> b >> lr; + Node* temp = q.front(); + q.pop(); + + if (lr == 'L') { + temp->left = new Node(b); + q.push(temp->left); + } else { + temp->right = new Node(b); + q.push(temp->right); + } + } + Solution obj; + cout << obj.height(root) << endl; + } + return 0; + } + // } Driver Code Ends + ``` + + + + +## Example Walkthrough + +For the tree: + +``` + 1 + / \ + 2 3 +``` + +1. The height of the left subtree (node 2) is 1. +2. The height of the right subtree (node 3) is 1. +3. The height of the tree is the maximum of the two heights plus 1, which is 2. + +For the tree: + +``` + 1 + / + 2 + / + 3 +``` + +1. The height of the left subtree (node 2) is 2. +2. The right subtree is empty, so its height is 0. +3. The height of the tree is the maximum of the two heights plus 1, which is 3. + +## Solution Logic: + +1. Recursively compute the height of the left and right subtrees. +2. Return the maximum height of the two subtrees plus 1 for the root. + +## Time Complexity + +* The function visits each node once, so the time complexity is $O(N)$. + +## Space Complexity + +* The auxiliary space complexity is $O(N)$ due to the recursion stack. + +## References + +- **gfg Problem:** [gfg Problem](https://www.geeksforgeeks.org/problems/height-of-binary-tree/1?page=2&difficulty=Easy&sortBy=submissions) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/implement-two-stacks-in-an-array.md b/solutions/gfg-solutions/Easy problems/implement-two-stacks-in-an-array.md new file mode 100644 index 0000000..d910c58 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/implement-two-stacks-in-an-array.md @@ -0,0 +1,349 @@ +--- +id: implement-two-stacks-in-an-array +title: Implement Two Stacks in an Array +sidebar_label: 10 Implement Two Stacks in an Array +tags: +- Data Structures +- Stacks +- Python +- Java +- C++ +- JavaScript +- TypeScript +description: "This document provides solutions to the problem of implementing two stacks in a single array using various programming languages." +--- + +## Problem + +Your task is to implement two stacks in one array efficiently. You need to implement four methods. + +- `twoStacks(n)`: Initialize the data structures and variables to be used to implement two stacks in one array. +- `push1(x)`: Pushes element into the first stack. +- `push2(x)`: Pushes element into the second stack. +- `pop1()`: Pops element from the first stack and returns the popped element. If the first stack is empty, it should return -1. +- `pop2()`: Pops element from the second stack and returns the popped element. If the second stack is empty, it should return -1. + +### Examples + +**Example 1:** + +``` +Input: +push1(2) +push1(3) +push2(4) +pop1() +pop2() +pop2() + +Output: +3 4 -1 + +Explanation: +push1(2) -> stack1 = {2} +push1(3) -> stack1 = {2, 3} +push2(4) -> stack2 = {4} +pop1() -> returns 3, stack1 = {2} +pop2() -> returns 4, stack2 = {} +pop2() -> stack2 is empty, returns -1 +``` + +**Example 2:** + +``` +Input: +push1(1) +push2(2) +pop1() +push1(3) +pop1() +pop1() + +Output: +1 3 -1 + +Explanation: +push1(1) -> stack1 = {1} +push2(2) -> stack2 = {2} +pop1() -> returns 1, stack1 = {} +push1(3) -> stack1 = {3} +pop1() -> returns 3, stack1 = {} +pop1() -> stack1 is empty, returns -1 +``` + +### Your Task + +You don't need to read input or print anything. You are required to complete the four methods `push1`, `push2`, `pop1`, and `pop2`. + +**Expected Time Complexity:** $O(1)$ for all the four methods. +**Expected Auxiliary Space:** $O(1)$ for all the four methods. + +**Constraints** +- 1 ≀ Number of queries ≀ 10^4 +- 1 ≀ Number of elements in the stack ≀ 100 +- The sum of the count of elements in both stacks < size of the given array + +## Solution + +### Intuition & Approach + +To efficiently implement two stacks in one array, we can start one stack from the beginning of the array and the other stack from the end of the array. This way, both stacks grow towards each other and we can manage them independently. + +### Implementation + + + + +```python +class TwoStacks: + def __init__(self, n=100): + self.size = n + self.arr = [0] * n + self.top1 = -1 + self.top2 = n + + # Function to push an integer into stack 1 + def push1(self, x): + if self.top1 < self.top2 - 1: + self.top1 += 1 + self.arr[self.top1] = x + + # Function to push an integer into stack 2 + def push2(self, x): + if self.top1 < self.top2 - 1: + self.top2 -= 1 + self.arr[self.top2] = x + + # Function to remove an element from top of stack 1 + def pop1(self): + if self.top1 >= 0: + x = self.arr[self.top1] + self.top1 -= 1 + return x + else: + return -1 + + # Function to remove an element from top of stack 2 + def pop2(self): + if self.top2 < self.size: + x = self.arr[self.top2] + self.top2 += 1 + return x + else: + return -1 +``` + + + + +```java +class TwoStacks { + int size; + int top1, top2; + int arr[]; + + TwoStacks(int n) { + size = n; + arr = new int[n]; + top1 = -1; + top2 = n; + } + + void push1(int x) { + if (top1 < top2 - 1) { + top1++; + arr[top1] = x; + } + } + + void push2(int x) { + if (top1 < top2 - 1) { + top2--; + arr[top2] = x; + } + } + + int pop1() { + if (top1 >= 0) { + int x = arr[top1]; + top1--; + return x; + } else { + return -1; + } + } + + int pop2() { + if (top2 < size) { + int x = arr[top2]; + top2++; + return x; + } else { + return -1; + } + } +} +``` + + + + +```cpp +class TwoStacks { + int* arr; + int size; + int top1, top2; +public: + TwoStacks(int n) { + size = n; + arr = new int[n]; + top1 = -1; + top2 = n; + } + + void push1(int x) { + if (top1 < top2 - 1) { + arr[++top1] = x; + } + } + + void push2(int x) { + if (top1 < top2 - 1) { + arr[--top2] = x; + } + } + + int pop1() { + if (top1 >= 0) { + return arr[top1--]; + } else { + return -1; + } + } + + int pop2() { + if (top2 < size) { + return arr[top2++]; + } else { + return -1; + } + } +}; +``` + + + + +```javascript +class TwoStacks { + constructor(n = 100) { + this.size = n; + this.arr = new Array(n).fill(0); + this.top1 = -1; + this.top2 = n; + } + + push1(x) { + if (this.top1 < this.top2 - 1) { + this.top1++; + this.arr[this.top1] = x; + } + } + + push2(x) { + if (this.top1 < this.top2 - 1) { + this.top2--; + this.arr[this.top2] = x; + } + } + + pop1() { + if (this.top1 >= 0) { + const x = this.arr[this.top1]; + this.top1--; + return x; + } else { + return -1; + } + } + + pop2() { + if (this.top2 < this.size) { + const x = this.arr[this.top2]; + this.top2++; + return x; + } else { + return -1; + } + } +} +``` + + + + +```typescript +class TwoStacks { + size: number; + top1: number; + top2: number; + arr: number[]; + + constructor(n: number = 100) { + this.size = n; + this.arr = new Array(n).fill(0); + this.top1 = -1; + this.top2 = n; + } + + push1(x: number): void { + if (this.top1 < this.top2 - 1) { + this.top1++; + this.arr[this.top1] = x; + } + } + + push2(x: number): void { + if (this.top1 < this.top2 - 1) { + this.top2--; + this.arr[this.top2] = x; + } + } + + pop1(): number { + if (this.top1 >= 0) { + const x = this.arr[this.top1]; + this.top1--; + return x; + } else { + return -1; + } + } + + pop2(): number { + if (this.top2 < this.size) { + const x = this.arr[this.top2]; + this.top2++; + return x; + } else { + return -1; + } + } +} +``` + + + + +## Complexity Analysis + +The provided solutions efficiently implement two stacks in a single array using pointers. This approach ensures a time complexity of $O(1)$ for all stack operations and an auxiliary space complexity of $O(1)$. The algorithms are designed to handle up to $10^4$ queries efficiently without relying on dynamic data structures. + +**Time Complexity:** $O(1)$ for all the four methods. +**Auxiliary Space:** $O(1)$ for all the four methods. + +--- + +- **GeeksforGeeks Problem:** [Implement two stack in an array](https://www.geeksforgeeks.org/problems/implement-two-stacks-in-an-array/0) +- **Author GeeksforGeeks Profile:** [GeeksforGeeks](https://www.geeksforgeeks.org/user/GeeksforGeeks/) + diff --git a/solutions/gfg-solutions/Easy problems/intersection-of-two-sorted-linked-lists.md b/solutions/gfg-solutions/Easy problems/intersection-of-two-sorted-linked-lists.md new file mode 100644 index 0000000..e51deb4 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/intersection-of-two-sorted-linked-lists.md @@ -0,0 +1,240 @@ +--- +id: intersection-of-two-sorted-linked-lists +title: Intersection of Two Sorted Linked Lists +sidebar_label: 6 Intersection of Two Sorted Linked Lists +tags: +- Linked List +- Python +- Java +- C++ +- JavaScript +- TypeScript +description: "This document provides solutions to the problem of finding the intersection of two sorted linked lists in various programming languages." +--- + +## Problem + +Given two linked lists sorted in increasing order, create a new linked list representing the intersection of the two linked lists. The new linked list should be made without changing the original lists. + +**Note:** The elements of the linked list are not necessarily distinct. + +### Examples + +**Example 1:** + +``` +Input: +LinkedList1 = 1->2->3->4->6 +LinkedList2 = 2->4->6->8 +Output: +2 4 6 +Explanation: For the given two linked list, 2, 4 and 6 are the elements in the intersection. +``` + +**Example 2:** + +``` +Input: +LinkedList1 = 10->20->40->50 +LinkedList2 = 15->40 +Output: +40 +``` + +### Your Task + +You don't have to take any input or print anything. Your task is to complete the function `findIntersection()`, which will take the head of both of the linked lists as input and should find the intersection of the two linked lists and add all the elements in the intersection to the third linked list and return the head of the third linked list. + +**Expected Time Complexity:** $O(n + m)$ +**Expected Auxiliary Space:** $O(n + m)$ + +**Note:** n, m are the sizes of the respective linked lists. + +### Constraints +- $1 ≀ size of linked lists ≀ 5000$ +- $1 ≀ Data in linked list nodes ≀ 10^4$ + +## Solution + +### Intuition & Approach + +To find the intersection of two sorted linked lists, we can iterate through both lists simultaneously. By comparing the elements at each step, we can identify common elements and construct a new linked list to represent the intersection. This process allows us to efficiently determine which elements are present in both lists without altering the original structures. + +### Implementation + + + + +```python +class ListNode: + def __init__(self, x): + self.data = x + self.next = None + +class Solution: + def findIntersection(self, head1, head2): + intersection = ListNode(0) # dummy node + tail = intersection + + while head1 and head2: + if head1.data == head2.data: + tail.next = ListNode(head1.data) + tail = tail.next + head1 = head1.next + head2 = head2.next + elif head1.data < head2.data: + head1 = head1.next + else: + head2 = head2.next + + return intersection.next +``` + + + + +```java +class ListNode { + int data; + ListNode next; + ListNode(int x) { data = x; next = null; } +} + +class Solution { + public ListNode findIntersection(ListNode head1, ListNode head2) { + ListNode intersection = new ListNode(0); // dummy node + ListNode tail = intersection; + + while (head1 != null && head2 != null) { + if (head1.data == head2.data) { + tail.next = new ListNode(head1.data); + tail = tail.next; + head1 = head1.next; + head2 = head2.next; + } else if (head1.data < head2.data) { + head1 = head1.next; + } else { + head2 = head2.next; + } + } + + return intersection.next; + } +} +``` + + + + +```cpp +struct ListNode { + int data; + ListNode* next; + ListNode(int x) : data(x), next(nullptr) {} +}; + +class Solution { +public: + ListNode* findIntersection(ListNode* head1, ListNode* head2) { + ListNode* intersection = new ListNode(0); // dummy node + ListNode* tail = intersection; + + while (head1 != nullptr && head2 != nullptr) { + if (head1->data == head2->data) { + tail->next = new ListNode(head1->data); + tail = tail->next; + head1 = head1->next; + head2 = head2->next; + } else if (head1->data < head2->data) { + head1 = head1->next; + } else { + head2 = head2->next; + } + } + + return intersection->next; + } +}; +``` + + + + +```javascript +class ListNode { + constructor(data) { + this.data = data; + this.next = null; + } +} + +class Solution { + findIntersection(head1, head2) { + let intersection = new ListNode(0); // dummy node + let tail = intersection; + + while (head1 !== null && head2 !== null) { + if (head1.data === head2.data) { + tail.next = new ListNode(head1.data); + tail = tail.next; + head1 = head1.next; + head2 = head2.next; + } else if (head1.data < head2.data) { + head1 = head1.next; + } else { + head2 = head2.next; + } + } + + return intersection.next; + } +} +``` + + + + +```typescript +class ListNode { + data: number; + next: ListNode | null; + + constructor(data: number) { + this.data = data; + this.next = null; + } +} + +class Solution { + findIntersection(head1: ListNode | null, head2: ListNode | null): ListNode | null { + let intersection = new ListNode(0); // dummy node + let tail = intersection; + + while (head1 !== null && head2 !== null) { + if (head1.data === head2.data) { + tail.next = new ListNode(head1.data); + tail = tail.next; + head1 = head1.next; + head2 = head2.next; + } else if (head1.data < head2.data) { + head1 = head1.next; + } else { + head2 = head2.next; + } + } + + return intersection.next; + } +} +``` + + + + +**Time Complexity:** $O(n + m)$ +**Auxiliary Space:** $O(n + m)$ + +## References + +- **GeeksforGeeks Problem:** [Intersection of Two Sorted Linked Lists](https://www.geeksforgeeks.org/problems/intersection-of-two-sorted-linked-lists/0) +- **Author GeeksforGeeks Profile:** [GeeksforGeeks](https://www.geeksforgeeks.org/user/GeeksforGeeks/) diff --git a/solutions/gfg-solutions/Easy problems/leaders-in-an-array-1587115620 b/solutions/gfg-solutions/Easy problems/leaders-in-an-array-1587115620 new file mode 100644 index 0000000..d0bc7a8 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/leaders-in-an-array-1587115620 @@ -0,0 +1,187 @@ +--- +id: array-leaders +title: Array Leaders +sidebar_label: 0015 - Array Leaders +tags: + - Easy + - Array + - GeeksforGeeks + - CPP + - Python + - DSA +description: "This tutorial covers the solution to the Array Leaders problem from the GeeksforGeeks website, featuring implementations in Python and C++." +--- +## Problem Description + +Given an array `arr` of `n` positive integers, your task is to find all the leaders in the array. An element of the array is considered a leader if it is greater than all the elements on its right side or if it is equal to the maximum element on its right side. The rightmost element is always a leader. + +## Examples + +**Example 1:** + +``` +Input: +arr = [16, 17, 4, 3, 5, 2] +Output: 17, 5, 2 +Explanation: The leaders are 17, 5, and 2. +``` + +**Example 2:** + +``` +Input: +arr = [1, 2, 3, 4, 0] +Output: 4, 0 +Explanation: The leaders are 4 and 0. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `leaders()` which takes the array `arr[]` and its size `n` as input parameters and returns a list of integers containing the leaders in the array. + +Expected Time Complexity: $O(n)$ + +Expected Auxiliary Space: $O(n)$ + +## Constraints + +* `1 ≀ n ≀ 10^7` +* `0 ≀ arr[i] ≀ 10^7` + +## Problem Explanation + +The task is to find all the leaders in the array, where a leader is an element that is greater than or equal to all the elements to its right. The rightmost element is always a leader. + +## Code Implementation + + + + + + ```py + class Solution: + def leaders(self, arr, n): + leaders = [] + max_from_right = arr[-1] + leaders.append(max_from_right) + + for i in range(n-2, -1, -1): + if arr[i] >= max_from_right: + leaders.append(arr[i]) + max_from_right = arr[i] + + return leaders[::-1] + + # Example usage + if __name__ == "__main__": + solution = Solution() + arr = [16, 17, 4, 3, 5, 2] + print(solution.leaders(arr, len(arr))) # Expected output: [17, 5, 2] + ``` + + + + + + ```cpp + //{ Driver Code Starts + #include + using namespace std; + + // } Driver Code Ends + class Solution { + public: + vector leaders(int n, int arr[]) { + vector leaders; + int max_from_right = arr[n-1]; + leaders.push_back(max_from_right); + + for (int i = n-2; i >= 0; i--) { + if (arr[i] >= max_from_right) { + leaders.push_back(arr[i]); + max_from_right = arr[i]; + } + } + + reverse(leaders.begin(), leaders.end()); + return leaders; + } + }; + + //{ Driver Code Starts. + int main() { + long long t; + cin >> t; // testcases + while (t--) { + long long n; + cin >> n; // total size of array + + int arr[n]; + + // inserting elements in the array + for (long long i = 0; i < n; i++) { + cin >> arr[i]; + } + Solution obj; + // calling leaders() function + vector v = obj.leaders(n, arr); + + // printing elements of the vector + for (auto it = v.begin(); it != v.end(); it++) { + cout << *it << " "; + } + + cout << endl; + } + } + // } Driver Code Ends + ``` + + + + +## Example Walkthrough + +**Example 1:** + +For the array: +``` +arr = [16, 17, 4, 3, 5, 2] +``` +1. The rightmost element, 2, is a leader. +2. 5 is greater than all elements to its right. +3. 17 is greater than all elements to its right. + +So the leaders are 17, 5, and 2. + +**Example 2:** + +For the array: +``` +arr = [1, 2, 3, 4, 0] +``` +1. The rightmost element, 0, is a leader. +2. 4 is greater than all elements to its right. + +So the leaders are 4 and 0. + +## Solution Logic: + +1. Traverse the array from right to left. +2. Keep track of the maximum element encountered so far. +3. If the current element is greater than or equal to the maximum element, it is a leader. +4. Add the leader to the result list and update the maximum element. +5. Return the result list in reverse order. + +## Time Complexity + +* The function iterates through the array once, so the time complexity is $O(n)$. + +## Space Complexity + +* The function uses additional space for the result list, so the auxiliary space complexity is $O(n)$. + +## References + +- **gfg Problem:** [gfg Problem](https://www.geeksforgeeks.org/problems/leaders-in-an-array-1587115620/1) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6) diff --git a/solutions/gfg-solutions/Easy problems/longest-common-prefix.md b/solutions/gfg-solutions/Easy problems/longest-common-prefix.md new file mode 100644 index 0000000..dea0054 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/longest-common-prefix.md @@ -0,0 +1,157 @@ +--- +id: longest-common-prefix +title: Longest Common Prefix of Strings +sidebar_label: 0028 - Longest Common Prefix of Strings +tags: + - Easy + - Strings + - GeeksforGeeks + - CPP + - DSA +description: "This tutorial covers the solution to the Longest Common Prefix problem from the GeeksforGeeks website, featuring implementations in C++." +--- +## Problem Description + +Given an array of strings, return the longest common prefix among all strings present in the array. If there's no prefix common in all the strings, return "-1". + +## Examples + +**Example 1:** + +``` +Input: +n = 4 +arr[] = {"geeksforgeeks", "geeks", "geek", "geezer"} + +Output: +gee + +Explanation: +"gee" is the longest common prefix among the input strings. +``` + +**Example 2:** + +``` +Input: +n = 2 +arr[] = {"hello", "world"} + +Output: +-1 + +Explanation: +There is no common prefix among the input strings. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `longestCommonPrefix()` which takes the array and its size as parameters and returns the longest common prefix among all strings present in the array. + +Expected Time Complexity: O(N * minLength), where N is the number of strings and minLength is the length of the shortest string. + +Expected Auxiliary Space: O(1) + +## Constraints + +* `1 ≀ n ≀ 1000` +* `1 ≀ |arr[i]| ≀ 1000` + +## Problem Explanation + +To find the longest common prefix, we can compare characters of each string one by one until a mismatch is found. This approach ensures that we only consider characters common in all strings. + +## Code Implementation + +### C++ Solution + +```cpp +// Initial template for C++ +#include +using namespace std; + +// User function template for C++ +class Solution { + public: + string longestCommonPrefix(int n, string arr[]) { + if (n == 0) return "-1"; + + string prefix = arr[0]; + + for (int i = 1; i < n; i++) { + while (arr[i].find(prefix) != 0) { + prefix = prefix.substr(0, prefix.size() - 1); + if (prefix.empty()) return "-1"; + } + } + + return prefix; + } +}; + +// Driver code +int main() { + int t; + cin >> t; + while (t--) { + int n; + cin >> n; + string arr[n]; + for (int i = 0; i < n; ++i) + cin >> arr[i]; + + Solution ob; + cout << ob.longestCommonPrefix(n, arr) << endl; + } + return 0; +} +``` + +## Example Walkthrough + +**Example 1:** + +For the input: +``` +n = 4 +arr[] = {"geeksforgeeks", "geeks", "geek", "geezer"} +``` + +1. Initialize `prefix` as the first string "geeksforgeeks". +2. Compare `prefix` with each string in the array: + - "geeksforgeeks" and "geeks": common prefix is "geeks". + - "geeks" and "geek": common prefix is "geek". + - "geek" and "geezer": common prefix is "gee". +3. The result is "gee", which is the longest common prefix. + +**Example 2:** + +For the input: +``` +n = 2 +arr[] = {"hello", "world"} +``` + +1. Initialize `prefix` as the first string "hello". +2. Compare `prefix` with the second string "world": + - No common prefix is found, so return "-1". + +## Solution Logic: + +1. Initialize `prefix` as the first string. +2. Iterate through the remaining strings and update `prefix` by checking for common prefixes. +3. If `prefix` becomes empty, return "-1". +4. Return the final `prefix` as the result. + +## Time Complexity + +* The time complexity is \(O(N * minLength)\) where \(N\) is the number of strings and \(minLength\) is the length of the shortest string. + +## Space Complexity + +* The auxiliary space complexity is \(O(1)\) as we use a constant amount of extra space. + +## References + +- **GeeksforGeeks Problem:** [Longest Common Prefix in an array](https://www.geeksforgeeks.org/problems/longest-common-prefix-in-an-array5129/1?page=2&difficulty=Easy&sortBy=submissions) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/missing-number-in-array1416 b/solutions/gfg-solutions/Easy problems/missing-number-in-array1416 new file mode 100644 index 0000000..9439cb9 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/missing-number-in-array1416 @@ -0,0 +1,158 @@ +--- +id: find-the-missing-number +title: Find the Missing Number Problem (gfg) +sidebar_label: 0005 - Find the Missing Number +tags: + - Intermediate + - Array + - Mathematical + - GeeksforGeeks + - CPP + - Python + - DSA +description: "This tutorial covers the solution to the Find the Missing Number problem from the GeeksforGeeks website, featuring implementations in Python and C++." +--- +## Problem Description + +Given an array containing `n-1` distinct numbers taken from 1 to `n`, find the one number that is missing from the array. + +## Examples + +**Example 1:** + +``` +Input: array = [3, 1, 4] +Output: 2 +Explanation: The missing number is 2. +``` + +**Example 2:** + +``` +Input: array = [5, 3, 1, 2] +Output: 4 +Explanation: The missing number is 4. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `missingNumber()` which takes the size `n` of the range and the array `arr` as inputs and returns the missing number. + +Expected Time Complexity: $O(n)$ + +Expected Auxiliary Space: $O(1)$ + +## Constraints + +* `2 ≀ n ≀ 10^6` +* `1 ≀ array[i] ≀ n` +* All elements of the array are distinct. + +## Problem Explanation + +The problem is to find the missing number from an array of `n-1` elements which contains distinct numbers from 1 to `n`. The missing number is the one number that is not present in the array. + +## Code Implementation + + + + + + ```py + class Solution: + def missingNumber(self, n, arr): + # Calculate the expected sum of the first n natural numbers + total_sum = n * (n + 1) // 2 + + # Calculate the sum of the elements in the array + arr_sum = sum(arr) + + # The missing number is the difference between the expected sum and the array sum + return total_sum - arr_sum + + # Example usage + if __name__ == "__main__": + solution = Solution() + print(solution.missingNumber(4, [3, 1, 4])) # Expected output: 2 + print(solution.missingNumber(5, [5, 3, 1, 2])) # Expected output: 4 + ``` + + + + + + ```cpp + #include + #include + using namespace std; + + class Solution { + public: + int missingNumber(int n, vector& arr) { + // Calculate the expected sum of the first n natural numbers + int total_sum = n * (n + 1) / 2; + + // Calculate the sum of the elements in the array + int arr_sum = 0; + for (int num : arr) { + arr_sum += num; + } + + // The missing number is the difference between the expected sum and the array sum + return total_sum - arr_sum; + } + }; + + // Example usage + int main() { + int t; + cin >> t; + while (t--) { + int n; + cin >> n; + + vector arr(n - 1); + for (int i = 0; i < n - 1; ++i) + cin >> arr[i]; + Solution obj; + cout << obj.missingNumber(n, arr) << "\n"; + } + return 0; + } + ``` + + + + +## Example Walkthrough + +For the array `array = [3, 1, 4]` with `n = 4`: + +1. The expected sum of the first 4 natural numbers is `4 * (4 + 1) / 2 = 10`. +2. The sum of the array elements is `3 + 1 + 4 = 8`. +3. The missing number is `10 - 8 = 2`. + +For the array `array = [5, 3, 1, 2]` with `n = 5`: + +1. The expected sum of the first 5 natural numbers is `5 * (5 + 1) / 2 = 15`. +2. The sum of the array elements is `5 + 3 + 1 + 2 = 11`. +3. The missing number is `15 - 11 = 4`. + +## Solution Logic: + +1. Calculate the expected sum of the first `n` natural numbers using the formula `n * (n + 1) / 2`. +2. Calculate the sum of the elements in the given array. +3. The missing number is the difference between the expected sum and the sum of the array elements. + +## Time Complexity + +* The time complexity is $O(n)$, where n is the size of the input array. + +## Space Complexity + +* The auxiliary space complexity is $O(1)$ because we are not using any extra space proportional to the size of the input array. + +## References + +- **gfg Problem:** [gfg Problem](https://www.geeksforgeeks.org/problems/missing-number-in-array1416/1?page=1&difficulty=Easy&sortBy=submissions) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/nth-fibonacci-number1335.md b/solutions/gfg-solutions/Easy problems/nth-fibonacci-number1335.md new file mode 100644 index 0000000..cd97f02 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/nth-fibonacci-number1335.md @@ -0,0 +1,154 @@ +--- +id: nth-fibonacci-number +title: Nth Fibonacci Number Problem (gfg) +sidebar_label: 0010 - Nth Fibonacci Number +tags: + - Easy + - Dynamic Programming + - Math + - GeeksforGeeks + - CPP + - Python + - DSA +description: "This tutorial covers the solution to the Nth Fibonacci Number problem from the GeeksforGeeks website, featuring implementations in Python and C++." +--- + +## Problem Description + +Given a positive integer `n`, find the nth Fibonacci number. Since the answer can be very large, return the answer modulo `1000000007`. + +Note: For this question, take the first Fibonacci number to be 1. + +## Examples + +**Example 1:** + +``` +Input: n = 1 +Output: 1 +``` + +**Example 2:** + +``` +Input: n = 5 +Output: 5 +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `nthFibonacci()` which takes the integer `n` as input and returns the nth Fibonacci number modulo `1000000007`. + +Expected Time Complexity: $O(n)$ + +Expected Auxiliary Space: $O(n)$ for dynamic programming or $O(1)$ for iterative approach. + +## Constraints + +- `1 ≀ n ≀ 10^7` + +## Problem Explanation + +The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 1 and 1. The nth Fibonacci number can be computed using the formula: `F(n) = F(n-1) + F(n-2)`. For large values of `n`, the result should be returned modulo `1000000007`. + +## Code Implementation + + + + + +```py +MOD = 1000000007 + +class Solution: + def nthFibonacci(self, n: int) -> int: + if n == 1 or n == 2: + return 1 + + a, b = 1, 1 + for i in range(3, n + 1): + a, b = b, (a + b) % MOD + + return b + +# Example usage +if __name__ == "__main__": + solution = Solution() + print(solution.nthFibonacci(1)) # Expected output: 1 + print(solution.nthFibonacci(5)) # Expected output: 5 +``` + + + + + +```cpp +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution { +public: + // Function to find nth Fibonacci number + int nthFibonacci(int n) { + const int MOD = 1000000007; + if (n == 1 || n == 2) return 1; + + int a = 1, b = 1, c; + for (int i = 3; i <= n; ++i) { + c = (a + b) % MOD; + a = b; + b = c; + } + return b; + } +}; + +//{ Driver Code Starts. +int main() { + int t; + cin >> t; + while (t--) { + int n; + cin >> n; + Solution obj; + cout << obj.nthFibonacci(n) << endl; + } + return 0; +} +// } Driver Code Ends +``` + + + + +## Example Walkthrough + +For `n = 1`: + +1. The first Fibonacci number is 1. + +For `n = 5`: + +1. The Fibonacci sequence starts as: `1, 1, 2, 3, 5`. +2. The 5th Fibonacci number is 5. + +## Solution Logic: + +1. Initialize the first two Fibonacci numbers as 1. +2. Use a loop to iterate from 3 to `n`, updating the Fibonacci numbers. +3. Return the nth Fibonacci number modulo `1000000007`. + +## Time Complexity + +- The iterative approach has a time complexity of $O(n)$. + +## Space Complexity + +- The space complexity is $O(1)$ since we are using only a fixed amount of extra space. + +## References + +- **gfg Problem:** [gfg Problem](https://www.geeksforgeeks.org/problems/nth-fibonacci-number1335/1?page=1&difficulty=Easy&sortBy=submissions) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/ount-pairs-with-given-sum.md b/solutions/gfg-solutions/Easy problems/ount-pairs-with-given-sum.md new file mode 100644 index 0000000..178566c --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/ount-pairs-with-given-sum.md @@ -0,0 +1,194 @@ +--- +id: count-pairs-with-given-sum +title: Count Pairs with Given Sum +sidebar_label: 0019 - Count Pairs with Given Sum +tags: + - Easy + - Array + - Hashing + - GeeksforGeeks + - CPP + - DSA +description: "This tutorial covers the solution to the Count Pairs with Given Sum problem from the GeeksforGeeks website, featuring implementations in Python and C++." +--- +## Problem Description + +Given an array `arr` and an integer `k`, find the number of pairs of elements in the array whose sum is `k`. + +## Examples + +**Example 1:** + +``` +Input: +arr = [1, 5, 7, 1] +k = 6 +Output: 2 +Explanation: The pairs are (1, 5) and (5, 1). +``` + +**Example 2:** + +``` +Input: +arr = [1, 1, 1, 1] +k = 2 +Output: 6 +Explanation: The pairs are (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), and (1, 1). +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `getPairsCount()` which takes the array `arr` and the integer `k` as input and returns the number of pairs in the array whose sum is equal to `k`. + +Expected Time Complexity: $O(N)$ + +Expected Auxiliary Space: $O(N)$ + +## Constraints + +* `1 ≀ N ≀ 10^6` +* `1 ≀ arr[i] ≀ 10^8` +* `1 ≀ k ≀ 10^8` + +## Problem Explanation + +The task is to find the number of pairs in the array whose sum equals `k`. The solution should be efficient in terms of both time and space complexity. + +## Code Implementation + + + + + + ```py + class Solution: + def getPairsCount(self, arr, k): + count = 0 + freq = {} + + for num in arr: + if k - num in freq: + count += freq[k - num] + + if num in freq: + freq[num] += 1 + else: + freq[num] = 1 + + return count + + # Example usage + if __name__ == "__main__": + solution = Solution() + print(solution.getPairsCount([1, 5, 7, 1], 6)) # Expected output: 2 + print(solution.getPairsCount([1, 1, 1, 1], 2)) # Expected output: 6 + ``` + + + + + + ```cpp + //{ Driver Code Starts + // Initial template for C++ + + #include + using namespace std; + + // } Driver Code Ends + // User function template for C++ + + class Solution { + public: + int getPairsCount(const vector& arr, int k) { + unordered_map freq; + int count = 0; + + for (int num : arr) { + if (freq.find(k - num) != freq.end()) { + count += freq[k - num]; + } + freq[num]++; + } + + return count; + } + }; + + //{ Driver Code Starts. + + int main() { + int t; + cin >> t; + cin.ignore(); // Ignore the newline character after t + while (t--) { + vector arr; + int k; + + cin >> k; + cin.ignore(); // Ignore the newline character after k + + string input; + + getline(cin, input); // Read the entire line for the array elements + stringstream ss(input); + int number; + while (ss >> number) { + arr.push_back(number); + } + + Solution ob; + auto ans = ob.getPairsCount(arr, k); + cout << ans << "\n"; + } + + return 0; + } + // } Driver Code Ends + ``` + + + + +## Example Walkthrough + +**Example 1:** + +For the input array: +``` +arr = [1, 5, 7, 1] +k = 6 +``` +1. The pairs are (1, 5) and (5, 1). Hence, the output is 2. + +**Example 2:** + +For the input array: +``` +arr = [1, 1, 1, 1] +k = 2 +``` +1. The pairs are (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), and (1, 1). Hence, the output is 6. + +## Solution Logic: + +1. Use a hash map to keep track of the frequency of each element. +2. Traverse the array: + - For each element, check if `k - num` exists in the hash map. + - If it does, add the frequency of `k - num` to the count. + - Update the frequency of the current element in the hash map. +3. Return the count of pairs. + +## Time Complexity + +* The function traverses the array once and uses a hash map for constant time lookups, so the time complexity is $O(N)$. + +## Space Complexity + +* The function uses a hash map to store the frequency of elements, so the auxiliary space complexity is $O(N)$. + +## References + +- **GeeksforGeeks Problem:** [Count Pairs with Given Sum](https://www.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/1?page=1&difficulty=Easy&sortBy=submissions) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/power-of-two.md b/solutions/gfg-solutions/Easy problems/power-of-two.md new file mode 100644 index 0000000..0cd0d00 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/power-of-two.md @@ -0,0 +1,204 @@ +--- +id: power-of-2 +title: Power of 2 +tags: + - Easy + - Bit Manipulation + - GeeksforGeeks + - CPP + - Python + - DSA +description: "This tutorial covers the solution to the Power of 2 problem from the GeeksforGeeks." +--- + +## Problem Description + +Given a non-negative integer `n`, the task is to check if it is a power of 2. + +## Examples + +**Example 1:** + +``` +Input: n = 1 +Output: true +Explanation: 2^0 = 1 +``` + +**Example 2:** + +``` +Input: n = 16 +Output: true +Explanation: 2^4 = 16 +``` + +**Example 3:** + +``` +Input: n = 3 +Output: false +Explanation: 3 is not a power of 2 +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `isPowerofTwo()` which takes an integer `n` as input and returns `true` if `n` is a power of 2, otherwise `false`. + +Expected Time Complexity: $O(1)$ + +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- `0 ≀ n ≀ 10^18` + +## Problem Explanation + +A number is a power of 2 if there exists an integer `x` such that `n = 2^x`. + +## Code Implementation + + + + + + ```python + class Solution: + def isPowerofTwo(self, n: int) -> bool: + if n <= 0: + return False + # A power of two has exactly one bit set in binary representation + return (n & (n - 1)) == 0 + + # Example usage + if __name__ == "__main__": + solution = Solution() + print(solution.isPowerofTwo(16)) # Expected output: True + print(solution.isPowerofTwo(3)) # Expected output: False + ``` + + + + + + ```cpp + #include + using namespace std; + + class Solution { + public: + // Function to check if given number n is a power of two. + bool isPowerofTwo(long long n) { + if (n <= 0) return false; + // A power of two has exactly one bit set in binary representation + return (n & (n - 1)) == 0; + } + }; + + int main() { + int t; + cin >> t; // testcases + + for (int i = 0; i < t; i++) { + long long n; // input a number n + cin >> n; + Solution ob; + if (ob.isPowerofTwo(n)) + cout << "true" << endl; + else + cout << "false" << endl; + } + return 0; + } + ``` + + + + + + + ```javascript +class Solution { + isPowerofTwo(n) { + if (n <= 0) return false; + return (n & (n - 1)) == 0; + } +} + +let t = parseInt(prompt("Enter number of testcases")); +for (let i = 0; i < t; i++) { + let n = parseInt(prompt("Enter a number")); + let sol = new Solution(); + console.log(sol.isPowerofTwo(n)); +} + + ``` + + + + + + ```typescript +class Solution { + isPowerofTwo(n: number): boolean { + if (n <= 0) return false; + return (n & (n - 1)) == 0; + } +} + +let t: number = parseInt(prompt("Enter number of testcases")); +for (let i: number = 0; i < t; i++) { + let n: number = parseInt(prompt("Enter a number")); + let sol: Solution = new Solution(); + console.log(sol.isPowerofTwo(n)); +} + + ``` + + + + + + + + ```java +import java.util.Scanner; + +class Solution { + boolean isPowerofTwo(long n) { + if (n <= 0) return false; + return (n & (n - 1)) == 0; + } +} + +public class Main { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int t = sc.nextInt(); + for (int i = 0; i < t; i++) { + long n = sc.nextLong(); + Solution sol = new Solution(); + System.out.println(sol.isPowerofTwo(n)); + } + } +} + + ``` + + + + +## Solution Logic: + +1. A number `n` is a power of 2 if it has exactly one bit set in its binary representation. +2. To check this, you can use the property: `n & (n - 1) == 0`. +3. This expression is true only for powers of 2. + +## Time Complexity + +- The function operates in constant time, $O(1)$. + +## Space Complexity + +- The function uses constant space, $O(1)$. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/reverse-a-doubly-linked-list.md b/solutions/gfg-solutions/Easy problems/reverse-a-doubly-linked-list.md new file mode 100644 index 0000000..6ed0559 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/reverse-a-doubly-linked-list.md @@ -0,0 +1,166 @@ +--- +id: reverse-doubly-linked-list +title: Reverse a Doubly Linked List +sidebar_label: 2 Reverse a Doubly Linked List +tags: +- Doubly Linked List +- Python +- Java +- C++ +- JavaScript +- TypeScript +description: "This document explores different approaches to reversing a doubly linked list in-place, including solutions in Python, Java, C++, JavaScript, and TypeScript." +--- + +## Problem + +Given a doubly linked list of n elements, the task is to reverse this list in-place. + +### Examples + +**Example 1:** + +``` +Input: +LinkedList: 3 <--> 4 <--> 5 +Output: +5 4 3 + +Explanation: +After reversing the list, elements are 5 <--> 4 <--> 3. +``` + +**Example 2:** + +``` +Input: +LinkedList: 75 <--> 122 <--> 59 <--> 196 +Output: +196 59 122 75 + +Explanation: +After reversing the list, elements are 196 <--> 59 <--> 122 <--> 75. +``` + +### Your Task +Your task is to complete the given function `reverseDLL()`, which takes head reference as an argument and reverses the elements in-place such that the tail becomes the new head and all pointers are pointing in the right order. You need to return the new head of the reversed list. + +**Expected Time Complexity:** $O(N)$ +**Expected Auxiliary Space:** $O(1)$ + +### Constraints +- $1 ≀ number of nodes ≀ 10^4$ +- $0 ≀ value of nodes ≀ 10^4$ + +## Solution + +### Approach + +To reverse a doubly linked list in-place, we can use three pointers: `previous_node`, `current_node`, and `next_node`. The algorithm traverses the list, updating the pointers at each step until the entire list is reversed. + +### Python Code + + + + +```python +class Solution: + def reverseDLL(self, head): + while head: + head.next, head.prev = head.prev, head.next + if not head.prev: + return head + head = head.prev +``` + + + + +```java +class Solution { + public Node reverseDLL(Node head) { + while (head != null) { + Node temp = head.prev; + head.prev = head.next; + head.next = temp; + if (head.prev == null) { + return head; + } + head = head.prev; + } + return null; + } +} +``` + + + + +```cpp +class Solution { +public: + Node* reverseDLL(Node* head) { + while (head != nullptr) { + Node* temp = head->prev; + head->prev = head->next; + head->next = temp; + if (head->prev == nullptr) { + return head; + } + head = head->prev; + } + return nullptr; + } +}; +``` + + + + +```javascript +class Solution { + reverseDLL(head) { + while (head) { + [head.next, head.prev] = [head.prev, head.next]; + if (!head.prev) { + return head; + } + head = head.prev; + } + return null; + } +} +``` + + + + +```typescript +class Solution { + reverseDLL(head: Node): Node | null { + while (head) { + [head.next, head.prev] = [head.prev, head.next]; + if (!head.prev) { + return head; + } + head = head.prev; + } + return null; + } +} +``` + + + + +### Complexity Analysis + +- **Time Complexity:** $O(N),$ where N is the number of elements in the doubly linked list. We traverse the entire list once. +- **Space Complexity:** $O(1)$, as we only use a constant amount of extra space for pointers. + +--- + +## References + +- **GeeksforGeeks Problem:** [Reverse a Doubly Linked List](https://www.geeksforgeeks.org/reverse-a-doubly-linked-list/) +- **Author GeeksforGeeks Profile:** [GeeksforGeeks](https://www.geeksforgeeks.org/user/GeeksforGeeks/) diff --git a/solutions/gfg-solutions/Easy problems/reverse-a-linked-list.md b/solutions/gfg-solutions/Easy problems/reverse-a-linked-list.md new file mode 100644 index 0000000..126a9db --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/reverse-a-linked-list.md @@ -0,0 +1,189 @@ +--- +id: reverse-linked-list +title: Reverse a Linked List +sidebar_label: 1 Reverse a Linked List +tags: +- Linked List +- Python +- Java +- C++ +- JavaScript +- TypeScript +description: "This document explores different approaches to reversing a linked list, including solutions in Python, Java, C++, JavaScript, and TypeScript." +--- + +## Problem + +Given a linked list of N nodes, the task is to reverse this list. + +### Examples + +**Example 1:** + +``` +Input: +LinkedList: 1->2->3->4->5->6 +Output: +6 5 4 3 2 1 + +Explanation: +After reversing the list, elements are 6->5->4->3->2->1. +``` + +**Example 2:** + +``` +Input: +LinkedList: 2->7->8->9->10 +Output: +10 9 8 7 2 + +Explanation: +After reversing the list, elements are 10->9->8->7->2. +``` + +### Your Task +The task is to complete the function `reverseList()` with head reference as the only argument and should return the new head after reversing the list. + +**Expected Time Complexity:** $ O(N) $ +**Expected Auxiliary Space:** $ O(1) $ + +### Constraints +- $ 1 ≀ N ≀ 10^4 $ + +## Solution + +### Approach + +To reverse a linked list, we can follow these steps: + +1. Initialize three pointers: `prev` (previous node), `curr` (current node), and `nextNode` (next node). +2. Start with `prev = None` and `curr = head`, where `head` is the head of the original linked list. +3. Traverse the linked list: + - Store `nextNode` as `curr.next`. + - Reverse the link by pointing `curr.next` to `prev`. + - Move `prev` to `curr` and `curr` to `nextNode`. +4. After traversing, update the new head to `prev`. +5. Return the new head. + +### Implementation + + + + +```python +class Solution: + # Function to reverse a linked list. + def reverseList(self, head): + prev = None + curr = head + + while curr: + nextNode = curr.next + curr.next = prev + prev = curr + curr = nextNode + + head = prev + return head +``` + + + + +```java +class Solution { + public ListNode reverseList(ListNode head) { + ListNode prev = null; + ListNode curr = head; + + while (curr != null) { + ListNode nextNode = curr.next; + curr.next = prev; + prev = curr; + curr = nextNode; + } + + head = prev; + return head; + } +} +``` + + + + +```cpp +class Solution { +public: + ListNode* reverseList(ListNode* head) { + ListNode* prev = nullptr; + ListNode* curr = head; + + while (curr != nullptr) { + ListNode* nextNode = curr->next; + curr->next = prev; + prev = curr; + curr = nextNode; + } + + head = prev; + return head; + } +}; +``` + + + + +```javascript +function reverseList(head) { + let prev = null; + let curr = head; + + while (curr) { + let nextNode = curr.next; + curr.next = prev; + prev = curr; + curr = nextNode; + } + + head = prev; + return head; +} +``` + + + + +```typescript +function reverseList(head: ListNode | null): ListNode | null { + let prev: ListNode | null = null; + let curr: ListNode | null = head; + + while (curr !== null) { + let nextNode: ListNode | null = curr.next; + curr.next = prev; + prev = curr; + curr = nextNode; + } + + head = prev; + return head; +} +``` + + + + +### Complexity Analysis + +- **Time Complexity:** $O(N)$, where N is the number of nodes in the linked list. We traverse the entire list once. +- **Space Complexity:** $O(1)$, as we only use a constant amount of extra space for pointers. + +--- + +## References + +- **GeeksforGeeks Problem:** [Reverse a Linked List](https://www.geeksforgeeks.org/reverse-a-linked-list/) +- **Author GeeksforGeeks Profile:** [GeeksforGeeks](https://www.geeksforgeeks.org/user/GeeksforGeeks/) diff --git a/solutions/gfg-solutions/Easy problems/reverse-words-in-a-given-string5459.md b/solutions/gfg-solutions/Easy problems/reverse-words-in-a-given-string5459.md new file mode 100644 index 0000000..6815348 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/reverse-words-in-a-given-string5459.md @@ -0,0 +1,168 @@ +--- +id: reverse-words-in-a-given-string +title: Reverse Words in a Given String (gfg) +sidebar_label: 0007 - Reverse Words in a Given String +tags: + - Easy + - String + - GeeksforGeeks + - CPP + - Python + - DSA +description: "This tutorial covers the solution to the Reverse Words in a Given String problem from the GeeksforGeeks website, featuring implementations in Python and C++." +--- +## Problem Description + +Given a string `S`, you need to reverse the order of words in the string. Words are separated by dots. + +## Examples + +**Example 1:** + +``` +Input: S = "i.like.this.program.very.much" +Output: "much.very.program.this.like.i" +Explanation: After reversing the words, the new string is "much.very.program.this.like.i". +``` + +**Example 2:** + +``` +Input: S = "pqr.mno" +Output: "mno.pqr" +Explanation: After reversing the words, the new string is "mno.pqr". +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `reverseWords()` which takes the string `S` as input and returns the string with the words reversed. + +Expected Time Complexity: $O(|S|)$ + +Expected Auxiliary Space: $O(|S|)$ + +## Constraints + +* `1 ≀ |S| ≀ 2000` + +## Problem Explanation + +The problem is to reverse the order of words in a string where words are separated by dots. + +## Code Implementation + + + + + + ```py + class Solution: + def reverseWords(self, S): + # Split the string by dots + words = S.split('.') + # Reverse the list of words + words.reverse() + # Join the reversed list back into a string with dots + return '.'.join(words) + + # Example usage + if __name__ == "__main__": + solution = Solution() + print(solution.reverseWords("i.like.this.program.very.much")) # Expected output: "much.very.program.this.like.i" + print(solution.reverseWords("pqr.mno")) # Expected output: "mno.pqr" + ``` + + + + + + ```cpp + //{ Driver Code Starts + #include + using namespace std; + + // } Driver Code Ends + + class Solution { + public: + // Function to reverse words in a given string. + string reverseWords(string S) { + // Split the string by dots + vector words; + string word; + for (char c : S) { + if (c == '.') { + words.push_back(word); + word.clear(); + } else { + word += c; + } + } + words.push_back(word); // Add the last word + + // Reverse the list of words + reverse(words.begin(), words.end()); + + // Join the reversed list back into a string with dots + string result; + for (size_t i = 0; i < words.size(); ++i) { + if (i != 0) { + result += '.'; + } + result += words[i]; + } + + return result; + } + }; + + //{ Driver Code Starts. + int main() { + int t; + cin >> t; + while (t--) { + string s; + cin >> s; + Solution obj; + cout << obj.reverseWords(s) << endl; + } + return 0; + } + // } Driver Code Ends + ``` + + + + +## Example Walkthrough + +For the string `S = "i.like.this.program.very.much"`: + +1. Split the string by dots into `["i", "like", "this", "program", "very", "much"]`. +2. Reverse the list to `["much", "very", "program", "this", "like", "i"]`. +3. Join the reversed list with dots to get `"much.very.program.this.like.i"`. + +For the string `S = "pqr.mno"`: + +1. Split the string by dots into `["pqr", "mno"]`. +2. Reverse the list to `["mno", "pqr"]`. +3. Join the reversed list with dots to get `"mno.pqr"`. + +## Solution Logic: + +1. Split the string into words using the dot as a delimiter. +2. Reverse the list of words. +3. Join the reversed list back into a string with dots. + +## Time Complexity + +* The time complexity is $O(|S|)$, where |S| is the length of the input string. + +## Space Complexity + +* The auxiliary space complexity is $O(|S|)$ due to the storage required for the list of words. + +## References + +- **gfg Problem:** [gfg Problem](https://www.geeksforgeeks.org/problems/reverse-words-in-a-given-string5459/1?page=1&difficulty=Easy&sortBy=submissions) +- **Solution Author:** [arunimad6yuq/](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/rotate-array.md b/solutions/gfg-solutions/Easy problems/rotate-array.md new file mode 100644 index 0000000..89e256d --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/rotate-array.md @@ -0,0 +1,167 @@ +--- +id: rotate-array +title: Rotate Array +sidebar_label: 0021 - Rotate Array +tags: + - Easy + - Arrays + - Rotation + - GeeksforGeeks + - CPP + - DSA +description: "This tutorial covers the solution to the Rotate Array problem from the GeeksforGeeks website, featuring implementations in C++." +--- +## Problem Description + +Given an unsorted array `arr[]` of size `n`. Rotate the array to the left (counter-clockwise direction) by `d` steps, where `d` is a positive integer. + +## Examples + +**Example 1:** + +``` +Input: +n = 5, d = 2 +arr = [1, 2, 3, 4, 5] +Output: [3, 4, 5, 1, 2] +Explanation: After rotating the array by 2 positions to the left, the array becomes [3, 4, 5, 1, 2]. +``` + +**Example 2:** + +``` +Input: +n = 7, d = 3 +arr = [2, 4, 6, 8, 10, 12, 14] +Output: [8, 10, 12, 14, 2, 4, 6] +Explanation: After rotating the array by 3 positions to the left, the array becomes [8, 10, 12, 14, 2, 4, 6]. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `rotateArr()` which takes the array `arr`, integer `d` and integer `n`, and rotates the array by `d` elements to the left. + +Expected Time Complexity: $O(n)$ + +Expected Auxiliary Space: $O(1)$ + +## Constraints + +* `1 ≀ n ≀ 10^7` +* `1 ≀ d ≀ n` +* `0 ≀ arr[i] ≀ 10^5` + +## Problem Explanation + +The task is to rotate an array to the left by `d` elements. Rotating an array means shifting all elements to the left by a given number of positions, and the elements that fall off the start of the array reappear at the end. + +## Code Implementation + +### C++ Solution + +```cpp +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution{ + public: + //Function to rotate an array by d elements in counter-clockwise direction. + void rotateArr(int arr[], int d, int n){ + // Edge case: if d is 0 or d equals n, array remains unchanged + if(d == 0 || d == n) + return; + + // Normalize d if it's greater than n + d = d % n; + + // Reverse the first d elements + reverse(arr, arr + d); + + // Reverse the remaining n-d elements + reverse(arr + d, arr + n); + + // Reverse the entire array + reverse(arr, arr + n); + } +}; + +//{ Driver Code Starts. + +int main() { + int t; + //taking testcases + cin >> t; + + while(t--){ + int n, d; + + //input n and d + cin >> n >> d; + + int arr[n]; + + //inserting elements in the array + for(int i = 0; i < n; i++){ + cin >> arr[i]; + } + Solution ob; + //calling rotateArr() function + ob.rotateArr(arr, d, n); + + //printing the elements of the array + for(int i =0; i < n; i++){ + cout << arr[i] << " "; + } + cout << endl; + } + return 0; +} +// } Driver Code Ends +``` + +## Example Walkthrough + +**Example 1:** + +For the input: +``` +n = 5, d = 2 +arr = [1, 2, 3, 4, 5] +``` +1. Rotate the first `d` elements: [2, 1, 3, 4, 5] +2. Rotate the remaining `n-d` elements: [2, 1, 5, 4, 3] +3. Rotate the entire array: [3, 4, 5, 1, 2] + +**Example 2:** + +For the input: +``` +n = 7, d = 3 +arr = [2, 4, 6, 8, 10, 12, 14] +``` +1. Rotate the first `d` elements: [6, 4, 2, 8, 10, 12, 14] +2. Rotate the remaining `n-d` elements: [6, 4, 2, 14, 12, 10, 8] +3. Rotate the entire array: [8, 10, 12, 14, 2, 4, 6] + +## Solution Logic: + +1. Use three reverse operations: + - Reverse the first `d` elements. + - Reverse the remaining `n-d` elements. + - Reverse the entire array. +2. This approach ensures that the elements are shifted in place with an $O(n)$ time complexity and $O(1)$ auxiliary space. + +## Time Complexity + +* The time complexity is $O(n)$ as the array is processed three times. + +## Space Complexity + +* The auxiliary space complexity is $O(1)$ as no additional storage is used. + +## References + +- **GeeksforGeeks Problem:** [Rotate Array](https://www.geeksforgeeks.org/problems/rotate-array-by-n-elements-1587115621/1?page=1&difficulty=Easy&sortBy=submissions) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Easy problems/second-largest.md b/solutions/gfg-solutions/Easy problems/second-largest.md new file mode 100644 index 0000000..e93f3b5 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/second-largest.md @@ -0,0 +1,218 @@ +--- +id: second-largest-element +title: Second Largest Element +sidebar_label: 0012 - Second Largest Distinct Element +tags: + - Easy + - Array + - DSA +description: "This tutorial covers the solution to the Second Largest Distinct Element problem from the GeeksforGeeks." +--- + +## Problem Description + +Given an array `arr` of size `n`, print the second largest distinct element from the array. If the second largest element doesn't exist, return `-1`. + +## Examples + +**Example 1:** + +``` +Input: arr = [10, 5, 10] +Output: 5 +``` + +**Example 2:** + +``` +Input: arr = [10, 10, 10] +Output: -1 +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `print2largest()` which takes the array `arr` and its size `n` as input parameters and returns the second largest distinct element from the array. If no such element exists, return `-1`. + +Expected Time Complexity: $O(N)$, where N is the number of elements in the array. + +Expected Auxiliary Space: $O(1)$ + +## Constraints + +- `1 ≀ n ≀ 10^5` +- `1 ≀ arr[i] ≀ 10^5` + +## Problem Explanation + +To solve this problem, you need to find the second largest distinct element in the array. This can be achieved by keeping track of the largest and the second largest distinct elements while iterating through the array. + +## Code Implementation + + + + + +```python +class Solution: + def print2largest(self, arr, n): + if n < 2: + return -1 + + first = second = -1 + for num in arr: + if num > first: + second = first + first = num + elif num > second and num != first: + second = num + + return second + +# Example usage +if __name__ == "__main__": + solution = Solution() + arr = [10, 5, 10] + print(solution.print2largest(arr, len(arr))) # Expected output: 5 +``` + + + + + +```cpp +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution { +public: + // Function returns the second largest element + int print2largest(int arr[], int n) { + int first = -1, second = -1; + for (int i = 0; i < n; i++) { + if (arr[i] > first) { + second = first; + first = arr[i]; + } else if (arr[i] > second && arr[i] != first) { + second = arr[i]; + } + } + return second; + } +}; + +//{ Driver Code Starts. + +int main() { + int t; + cin >> t; + while (t--) { + int n; + cin >> n; + int arr[n]; + for (int i = 0; i < n; i++) { + cin >> arr[i]; + } + Solution ob; + auto ans = ob.print2largest(arr, n); + cout << ans << "\n"; + } + return 0; +} + +// } Driver Code Ends +``` + + + + + + +```javascript +class Solution { + print2largest(arr, n) { + if (n < 2) return -1; + let first = (second = -1); + for (let num of arr) { + if (num > first) { + second = first; + first = num; + } else if (num > second && num != first) { + second = num; + } + } + return second; + } +} +``` + + + + + + +```typescript +class Solution { +print2largest(arr: number[], n: number): number { + if (n < 2) return -1; + let first: number = second: number = -1; + for (let num of arr) { + if (num > first) { + second = first; + first = num; + } else if (num > second && num != first) { + second = num; + } + } + return second; +} +} + +``` + + + + + + +```java +public class Solution { +public int print2largest(int[] arr, int n) { + if (n < 2) return -1; + int first = Integer.MIN_VALUE; + int second = Integer.MIN_VALUE; + for (int num : arr) { + if (num > first) { + second = first; + first = num; + } else if (num > second && num != first) { + second = num; + } + } + return second; +} +} +public class Main { +public static void main(String[] args) { + Solution solution = new Solution(); + int[] arr = {10, 5, 10}; + System.out.println(solution.print2largest(arr, arr.length)); // Expected output: 5 +} +} + +``` + + + + +## Solution Logic: + +1. Iterate through the array and keep track of the largest and the second largest distinct elements. +2. Return the second largest distinct element or `-1` if it doesn't exist. + +## Time Complexity + +- The function visits each element once, so the time complexity is $O(n)$, where n is the length of the array. This is because we are iterating through the array once. + +- The space complexity of the solution is $O(1)$, which means the space required does not change with the size of the input array. This is because we are using a fixed amount of space to store the variables first, second,Β andΒ num. diff --git a/solutions/gfg-solutions/Easy problems/sorted-array-search.md b/solutions/gfg-solutions/Easy problems/sorted-array-search.md new file mode 100644 index 0000000..ed5b483 --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/sorted-array-search.md @@ -0,0 +1,152 @@ +--- +id: sorted-arrray-search +title: Sorted Array Search +sidebar_label: Sorted-Array-Search +tags: + - Searching + - Binary Search + - Algorithms +description: "This tutorial covers the solution to the Sorted Array Search problem from the GeeksforGeeks website." +--- +## Problem Description +Given an array `arr[]` sorted in ascending order of size `N` and an integer `K`. Check if `K` is present in the array or not. + +## Examples + +**Example 1:** + +``` +Input: +N = 5, K = 6 +arr[] = {1,2,3,4,6} +Output: 1 +Exlpanation: Since, 6 is present in +the array at index 4 (0-based indexing), +output is 1. +``` + +**Example 2:** + +``` +Input: +N = 5, K = 2 +arr[] = {1,3,4,5,6} +Output: -1 +Exlpanation: Since, 2 is not present +in the array, output is -1. +``` + +## Your Task + +You don't need to read input or print anything. Complete the function searchInSorted() which takes the sorted array arr[], its size N and the element K as input parameters and returns 1 if K is present in the array, else it returns -1. + + + +Expected Time Complexity: O(Log N) + +Expected Auxiliary Space: O(1) + +## Constraints + +* `1 <= arr[i] <= 10^6` + +## Problem Explanation + +The task is to traverse the array and find the reuired element. + +## Code Implementation + +### C++ Solution + +```cpp +class Solution{ + public: + // Function to find element in sorted array + // arr: input array + // N: size of array + // K: element to be searche + int searchInSorted(int arr[], int N, int K) + { + int cnt = 0; + for(int i=0; i + + +```python +class Solution: + def floorSqrt(self, x: int) -> int: + if x == 0 or x == 1: + return x + start, end = 1, x + ans = 0 + while start <= end: + mid = (start + end) // 2 + if mid * mid == x: + return mid + if mid * mid < x: + start = mid + 1 + ans = mid + else: + end = mid - 1 + return ans +``` + + + + +```java +class Solution { + long floorSqrt(long x) { + if (x == 0 || x == 1) { + return x; + } + long start = 1, end = x, ans = 0; + while (start <= end) { + long mid = (start + end) / 2; + if (mid * mid == x) { + return mid; + } + if (mid * mid < x) { + start = mid + 1; + ans = mid; + } else { + end = mid - 1; + } + } + return ans; + } +} +``` + + + + +```cpp +class Solution { +public: + long long int floorSqrt(long long int x) { + if (x == 0 || x == 1) + return x; + long long int start = 1, end = x, ans = 0; + while (start <= end) { + long long int mid = (start + end) / 2; + if (mid * mid == x) + return mid; + if (mid * mid < x) { + start = mid + 1; + ans = mid; + } else { + end = mid - 1; + } + } + return ans; + } +}; +``` + + + + +```javascript +class Solution { + floorSqrt(x) { + if (x === 0 || x === 1) { + return x; + } + let start = 1, + end = x, + ans = 0; + while (start <= end) { + let mid = Math.floor((start + end) / 2); + if (mid * mid === x) { + return mid; + } + if (mid * mid < x) { + start = mid + 1; + ans = mid; + } else { + end = mid - 1; + } + } + return ans; + } +} +``` + + + + +```typescript +class Solution { + floorSqrt(x: number): number { + if (x === 0 || x === 1) { + return x; + } + let start = 1, + end = x, + ans = 0; + while (start <= end) { + let mid = Math.floor((start + end) / 2); + if (mid * mid === x) { + return mid; + } + if (mid * mid < x) { + start = mid + 1; + ans = mid; + } else { + end = mid - 1; + } + } + return ans; + } +} +``` + + + + +## Complexity Analysis + +The provided solutions efficiently find the floor value of the square root of a given integer `x` using binary search. This approach ensures a time complexity of $ O(log N) and an auxiliary space complexity of $O(1)$. The algorithms are designed to handle large values of `x` up to 10^7 efficiently without relying on built-in square root functions. + +**Time Complexity:** $O(log N)$ +**Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/transpost-of-matrix.md b/solutions/gfg-solutions/Easy problems/transpost-of-matrix.md new file mode 100644 index 0000000..406b44a --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/transpost-of-matrix.md @@ -0,0 +1,124 @@ +--- +id: transpose-of-matrix +title: Transpose Of Matrix +sidebar_label: Transpose-Of-Matrix +tags: + - Matrix + - Data Structure +description: "This tutorial covers the solution to the Transpose of Matrix problem from the GeeksforGeeks." +--- +## Problem Description + +Write a program to find the transpose of a square matrix of size `N*N`. Transpose of a matrix is obtained by changing rows to columns and columns to rows. + +## Examples + +**Example 1:** + +``` +Input: +N = 4 +mat[][] = {{1, 1, 1, 1}, + {2, 2, 2, 2} + {3, 3, 3, 3} + {4, 4, 4, 4}} +Output: +{{1, 2, 3, 4}, + {1, 2, 3, 4} + {1, 2, 3, 4} + {1, 2, 3, 4}} +``` + +**Example 2:** + +``` +Input: +N = 2 +mat[][] = {{1, 2}, + {-9, -2}} +Output: +{{1, -9}, + {2, -2}} +``` + +## Your Task +You dont need to read input or print anything. Complete the function transpose() which takes matrix[][] and N as input parameter and finds the transpose of the input matrix. You need to do this in-place. That is you need to update the original matrix with the transpose. + + +## Constraints + +* `-10^9 <= mat[i][j] <= 10^9` + +## Problem Explanation + +The task is to traverse the matrix and transpose it. + +## Code Implementation + +### C++ Solution + +```cpp + +#include +#include + +std::vector> transposeMatrix(const std::vector>& matrix) { + int rows = matrix.size(); + int cols = matrix[0].size(); + std::vector> transpose(cols, std::vector(rows)); + for (int i = 0; i < rows; ++i) { + for (int j = 0; j < cols; ++j) { + transpose[j][i] = matrix[i][j]; + } + } + return transpose; +} +``` + +```java +public static int[][] transposeMatrix(int[][] matrix) { + int rows = matrix.length; + int cols = matrix[0].length; + int[][] transpose = new int[cols][rows]; + for (int i = 0; i < rows; ++i) { + for (int j = 0; j < cols; ++j) { + transpose[j][i] = matrix[i][j]; + } + } + return transpose; +} + + +``` + +```python + +def transpose_matrix(matrix): + return list(zip(*matrix)) + +``` + +```javascript +function transposeMatrix(matrix) { + return matrix[0].map((_, colIndex) => matrix.map(row => row[colIndex])); +} + +``` + +## Solution Logic: + +1. Create an empty matrix (2D array) to store the transposed matrix. +2. Iterate through the original matrix: + - For each element in the original matrix, swap its row and column indices to get the corresponding element in the transposed matrix. + - Assign the value of the original element to the transposed element. +3. Return the transposed matrix. + + +## Time Complexity + +* The time complexity is $O(n*m)$ as where n is the number of rows in the matrix and m is the number of columns. This is because the solution iterates through each element in the matrix once. + + +## Space Complexity + +* The space complexity of the solution is O(n*m), where n is the number of rows in the matrix and m is the number of columns. This is because the solution creates a new matrix to store the transposed matrix, which has the same size as the original matrix. \ No newline at end of file diff --git a/solutions/gfg-solutions/Easy problems/wave-array.md b/solutions/gfg-solutions/Easy problems/wave-array.md new file mode 100644 index 0000000..5e4d44a --- /dev/null +++ b/solutions/gfg-solutions/Easy problems/wave-array.md @@ -0,0 +1,138 @@ +--- +id: wave-array +title: Wave Array +sidebar_label: 0023 - Wave Array +tags: + - Easy + - Array + - GeeksforGeeks + - CPP + - DSA +description: "This tutorial covers the solution to the Wave Array problem from the GeeksforGeeks website, featuring implementations in C++." +--- +## Problem Description + +Given a sorted array arr[] of distinct integers, sort the array into a wave-like array in place. In other words, arrange the elements into a sequence such that `arr[1] >= arr[2] <= arr[3] >= arr[4] <= arr[5].....` +If there are multiple solutions, find the lexicographically smallest one. + +Note: The given array is sorted in ascending order, and you don't need to return anything to change the original array. + +## Examples + +**Example 1:** + +``` +Input: +arr[] = {1, 2, 3, 4, 5} + +Output: +2 1 4 3 5 +``` + +**Example 2:** + +``` +Input: +arr[] = {2, 4, 7, 8, 9, 10} + +Output: +4 2 8 7 10 9 +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `convertToWave()` which takes the array and its size as parameters and modifies the array into a wave-like array. + +Expected Time Complexity: O(n) + +Expected Auxiliary Space: O(1) + +## Constraints + +* `1 ≀ n ≀ 10^6` +* `0 ≀ arr[i] ≀ 10^6` + +## Problem Explanation + +To convert the array into a wave-like array, we can follow these steps: + +1. Iterate over the array with a step of 2. +2. Swap every adjacent pair of elements. + +## Code Implementation + +### C++ Solution + +```cpp +//{ Driver Code Starts +#include +using namespace std; + +// } Driver Code Ends +class Solution{ + public: + // arr: input array + // n: size of array + // Function to sort the array into a wave-like array. + void convertToWave(int n, vector& arr){ + for (int i = 0; i < n - 1; i += 2) { + swap(arr[i], arr[i + 1]); + } + } +}; + +//{ Driver Code Starts. + +int main() { + int t, n; + cin >> t; // Input testcases + while (t--) // While testcases exist + { + cin >> n; // Input size of array + vector a(n); // Declare vector of size n + for (int i = 0; i < n; i++) + cin >> a[i]; // Input elements of array + + Solution ob; + ob.convertToWave(n, a); + + for (int i = 0; i < n; i++) + cout << a[i] << " "; // Print array + + cout << endl; + } +} +// } Driver Code Ends +``` + +## Example Walkthrough + +**Example 1:** + +For the input: +``` +arr[] = {1, 2, 3, 4, 5} +``` +1. Start with the first pair (1, 2) and swap them to get {2, 1, 3, 4, 5}. +2. Move to the next pair (3, 4) and swap them to get {2, 1, 4, 3, 5}. +3. There are no more pairs to process. + +The result is [2, 1, 4, 3, 5]. + +## Solution Logic: + +1. Iterate through the array with a step of 2. +2. For each pair of adjacent elements, swap them. + +## Time Complexity + +* The time complexity is $O(n)$ where $n$ is the number of elements in the array, as we only iterate through the array once. + +## Space Complexity + +* The auxiliary space complexity is $O(1)$ as we are modifying the array in place. + +## References + +- **GeeksforGeeks Problem:** [Wave Array](https://www.geeksforgeeks.org/problems/wave-array-1587115621/1?page=2&difficulty=Easy&sortBy=submissions) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) diff --git a/solutions/gfg-solutions/Hard/0101-0200/0102-Minimum-BST-Sum-Subtree.md b/solutions/gfg-solutions/Hard/0101-0200/0102-Minimum-BST-Sum-Subtree.md new file mode 100644 index 0000000..703674b --- /dev/null +++ b/solutions/gfg-solutions/Hard/0101-0200/0102-Minimum-BST-Sum-Subtree.md @@ -0,0 +1,211 @@ +--- +id: minimum-bst-sum-subtree +title: Minimum-BST-Sum-Subtree (Geeks for Geeks) +sidebar_label: Minimum BST Sum Subtree +tags: + - Intermediate + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Minimum BST Sum Subtree problem on Geeks for Geeks." +--- +## Problem Description +Every house in the colony has at most one pipe going into it and at most one pipe going out of it. Tanks and taps are to be installed in a manner such that every house with one outgoing pipe but no incoming pipe gets a tank installed on its roof and every house with only an incoming pipe and no outgoing pipe gets a tap. +Given two integers n and p denoting the number of houses and the number of pipes. The connections of pipe among the houses contain three input values: a_i, b_i, d_i denoting the pipe of diameter d_i from house a_i to house b_i, find out the efficient solution for the network. +The output will contain the number of pairs of tanks and taps t installed in first line and the next t lines contain three integers: house number of tank, house number of tap and the minimum diameter of pipe between them. + +## Examples +**Example 1:** +**Input:** +``` + 5 + / \ + 4 6 + / \ + 3 7 + / + 1 +``` +**Output:** 1 +**Example 2:** +**Input:** +``` + 9 + \ + 10 + \ + 11 +``` +**Output:** 9 +## Your Task +The task is to complete the function minValue() which takes root as the argument and returns the minimum element of BST. If the tree is empty, there is no minimum element, so return -1 in that case. +Expected Time Complexity: $O(Height of the BST)$ +Expected Auxiliary Space: $O(1)$. +## Constraints +- `0 <= n <= 10^4` + + +## Your Task +The task is to complete the function minValue() which takes root as the argument and returns the minimum element of BST. If the tree is empty, there is no minimum element, so return -1 in that case. + +Expected Time Complexity: $O(Height of the BST)$ +Expected Auxiliary Space: $O(1)$. + +## Constraints + +- `0 <= n <= 10^4` + +## Problem Explanation + +The "Smallest Subtree with all the Deepest Nodes" is a problem where given a binary tree, you need to find the smallest subtree that contains all the deepest nodes. Let's break down the problem step-by-step: + +**Problem Statement** +You are given a binary tree. +Your task is to find the smallest subtree that contains all the deepest nodes in the original tree. +**Key Points** +Deepest Nodes: Nodes that are at the maximum depth from the root of the tree. +Smallest Subtree: Among all subtrees containing these deepest nodes, the one with the smallest number of nodes. + +### Code Implementation + + + + ```python +class Solution: + def lca(self, root, p, q): + if root in (None, p, q): return root + l = self.lca(root.left, p, q) + r = self.lca(root.right, p, q) + return root if l and r else l or r + def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode: + a = [] + def dfs(node, h): + if not node: + return + if len(a) == h: + a.append([]) + a[h].append(node) + dfs(node.left, h+1) + dfs(node.right, h+1) + dfs(root, 0) + p, q = a[-1][0], a[-1][-1] + return self.lca(root, p, q) + ``` + + + + ```cpp +class Solution { +public: + TreeNode* subtreeWithAllDeepest(TreeNode* root) { + vector temp; + vector> level; + unordered_map hash; + queue> q; + q.push({root,NULL}); + q.push({NULL,NULL}); + hash[root] = NULL; + while (!q.empty()) + { + auto [node,parent] = q.front();q.pop(); + if (node == NULL) + { + level.push_back(temp); + temp.clear(); + if (q.size()>0) + { + q.push({NULL,NULL}); + } + } + else + { + temp.push_back(node); + hash[node] = parent; + if (node->left) + { + q.push({node->left,node}); + } + if (node->right) + { + q.push({node->right,node}); + } + } + } + temp = level.back(); + queue qe; + unordered_map vis; + for (auto leaves : temp) + { + vis[leaves] = 1; + qe.push(leaves); + } + while (!qe.empty()) + { + int sz = qe.size(); + if (sz == 1) + { + return qe.front(); + } + while (sz--) + { + auto node = qe.front();qe.pop(); + + while (sz--) + { + auto node = qe.front();qe.pop(); + auto parent = hash[node]; + if (vis.find(parent) == vis.end()) + { + vis[parent] = 1; + qe.push(parent); + } + } + } + return NULL; + } +}; + ``` + + + + +## Solution Logic +**DFS to Collect Nodes by Depth:** +- You initialize an empty list a to store nodes at each depth. +- The dfs function is called with the root node and depth 0. +- For each node, if the current depth h matches the length of a, it means you have reached a new depth level, so you append an empty list to a. +- The node is then added to the appropriate sublist corresponding to its depth. +- The function is recursively called for left and right children, incrementing the depth by 1 for each recursive call. +**Finding the LCA:** +- After collecting all nodes, p and q are set to the first and last nodes in the deepest level sublist (a[-1]). +- The lca function is a recursive function that finds the lowest common ancestor of p and q. +- If the current node root is None, p, or q, it returns root. +- Otherwise, it recursively calls lca on the left and right children. +- If both recursive calls return non-None values, it means p and q are found in different subtrees, and thus the current node root is their LCA. +- If only one side returns a non-None value, it means both p and q are in the same subtree, so the LCA is in that subtree. +## Time Complexity +$O(Height of the BST)$ +## Space Complexity +Expected Auxiliary Space: $O(1)$. +## Resources +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/find-the-minimum-element-in-a-binary-search-tree/) +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/) +- **Author's Geeks for Geeks Profile:** | [DaminiChachane](https://leetcode.com/u/divcxl15/) | +This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow. + +## Time Complexity +$O(Height of the BST)$ + +## Space Complexity + +Expected Auxiliary Space: $O(1)$. + +## Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/find-the-minimum-element-in-a-binary-search-tree/) +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/) +- **Author's Geeks for Geeks Profile:** | [DaminiChachane](https://leetcode.com/u/divcxl15/) | + +This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow. + diff --git a/solutions/gfg-solutions/Hard/0101-0200/0105-Scrambled-String.md b/solutions/gfg-solutions/Hard/0101-0200/0105-Scrambled-String.md new file mode 100644 index 0000000..95d7402 --- /dev/null +++ b/solutions/gfg-solutions/Hard/0101-0200/0105-Scrambled-String.md @@ -0,0 +1,275 @@ +--- +id: Scrambled-String +title: Scrambled-String (Geeks for Geeks) +sidebar_label: Scrambled-String +tags: + - Intermediate + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Scrambled-String problem on Geeks for Geeks." +--- + +## Problem Description + +Given two strings S1 and S2 of equal length, the task is to determine if S2 is a scrambled form of S1. + +Scrambled string: Given string str, we can represent it as a binary tree by partitioning it into two non-empty substrings recursively. +Below is one possible representation of str = coder: +![alt text](image.png) +To scramble the string, we may choose any non-leaf node and swap its two children. +Suppose, we choose the node co and swap its two children, it produces a scrambled string ocder. +Similarly, if we continue to swap the children of nodes der and er, it produces a scrambled string ocred. + +Note: Scrambled string is not the same as an Anagram. +Print "Yes" if S2 is a scrambled form of S1 otherwise print "No". + + +## Examples + +**Example:** + +Consider the following graph: + +``` + ocder + / \ + oc der + / \ + o c +``` +**Input:** S1="coder", S2="ocder" +**Explanation:** ocder is a scrambled +form of coder. +**Output:** Yes + +## Your Task + +You don't need to read input or print anything. You only need to complete the function isScramble() which takes two strings S1 and S2 as input and returns a boolean value. + +Expected Time Complexity: $O(N2)$. +Expected Auxiliary Space: $O(N2)$. + +## Constraints + +- S1.length = S2.length +- `S1.length<=31` +- S1 and S2 consist of lower-case English letters. + +## Problem Explanation + +Here's the step-by-step breakdown of the Scrambled String process: + +**Step 1 :** A scrambled string is defined based on recursive partitioning and swapping of substrings. Here’s a more detailed explanation: + +**Step 2 :** Binary Tree Representation:Given a string str, you can represent it as a binary tree by recursively partitioning it into two non-empty substrings. +**Step 3 :** For example, for the string "coder": You can split it into "co" and "der". +Each of these can be further split recursively, forming a binary tree structure. +**Step 4 :**Scrambling: A string S2 is a scrambled form of string S1 if S2 can be obtained by swapping the left and right children of some non-leaf nodes in the binary tree representation of S1. +For instance, "coder" can be scrambled to "ocder" by swapping "co" and "der", then further scrambling "co" to "oc". + +### Code Implementation + + + + + ```python +class Solution(object): + def isScramble(self, s1, s2): + """ + :type s1: str + :type s2: str + :rtype: bool + """ + # Base cases + + n = len(s1) + + # If both strings are not equal in size + if len(s2) != n: + return False + + # If both strings are equal + if s1 == s2: + return True + + # If code is reached to this condition then following this are sure: + # 1. size of both string is equal + # 2. string are not equal + # so size is equal (where size==1) and they are not equal then obviously false + # example 'a' and 'b' size is equal, string are not equal + if n == 1: + return False + + key = s1 + " " + s2 + + # Check if this problem has already been solved + if key in self.mp: + return self.mp[key] + + # For every iteration it can two condition + # 1. We should proceed without swapping + # 2. We should swap before looking next + for i in range(1, n): + # ex of without swap: gr|eat and rg|eat + without_swap = ( + # Left part of first and second string + self.isScramble(s1[:i], s2[:i]) + and + # Right part of first and second string; + self.isScramble(s1[i:], s2[i:]) + ) + + # If without swap gives us the right answer then we do not need + # to call the recursion with swap + if without_swap: + return True + + # ex of with swap: gr|eat rge|at + # here we compare "gr" with "at" and "eat" with "rge" + with_swap = ( + # Left part of first and right part of second + self.isScramble(s1[:i], s2[n-i:]) + and + # Right part of first and left part of second + self.isScramble(s1[i:], s2[:n-i]) + ) + + # If with swap gives us the right answer then we return True + # otherwise, the for loop does its work + if with_swap: + return True + + self.mp[key] = False + return False + + # for storing already solved problems + mp = {} + ``` + + + + + ```cpp +class Solution { +public: +//for storing already solved problems + unordered_map mp; + + + bool isScramble(string s1, string s2) { + //base cases + + int n = s1.size(); + + //if both string are not equal in size + if(s2.size()!=n) + return false; + + //if both string are equal + if(s1==s2) + return true; + + + + //if code is reached to this condition then following this are sure: + //1. size of both string is equal + //2. string are not equal + //so size is equal (where size==1) and they are not equal then obviously false + //example 'a' and 'b' size is equal ,string are not equal + if(n==1) + return false; + + string key = s1+" "+s2; + + //check if this problem has already been solved + if(mp.find(key)!=mp.end()) + return mp[key]; + + //for every iteration it can two condition + //1.we should proceed without swapping + //2.we should swap before looking next + for(int i=1;i + + +## Solution Logic + +**1.Base Cases:**If the lengths of the two strings are not equal, they cannot be scrambled forms of each other, so return false. +If the two strings are identical, they are trivially scrambled forms of each other, so return true. +If the length of the string is 1 and the strings are not equal, return false. +**2.Memoization:** Use a map mp to store already solved subproblems to avoid redundant computations. +The key for the map is a combination of the two strings, represented as s1 + " " + s2. +**3.Recursive Check:** Iterate over possible split points of the strings. +For each split point, there are two cases to consider: +1.Without swapping: +Compare the left part of s1 with the left part of s2 and the right part of s1 with the right part of s2. +2.With swapping: +Compare the left part of s1 with the right part of s2 and the right part of s1 with the left part of s2. +**4.Return Result:** If either of the conditions (with or without swapping) is satisfied, return true. +If none of the conditions are satisfied after checking all possible split points, store the result as false in the memoization map and return false.1. + +## Time Complexity + + $O(N2)$. + +## Space Complexity + + $O(N2)$. + +## Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/problems/scrambled-string/1) +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/scramble-string/description/) +- **Author's Geeks for Geeks Profile:** | [DaminiChachane](https://leetcode.com/u/divcxl15/) | + +This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow. diff --git a/solutions/gfg-solutions/Hard/0101-0200/0106-Travelling-Salesperson-Problem.md b/solutions/gfg-solutions/Hard/0101-0200/0106-Travelling-Salesperson-Problem.md new file mode 100644 index 0000000..3eba2d8 --- /dev/null +++ b/solutions/gfg-solutions/Hard/0101-0200/0106-Travelling-Salesperson-Problem.md @@ -0,0 +1,190 @@ +--- +id: travelling-salesperson-problem +title: Travelling-Salesperson-Problem (Geeks for Geeks) +sidebar_label: Travelling Salesperson Problem +tags: + - Intermediate + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Travelling-Salesperson-Problem on Geeks for Geeks." +--- + +## Problem Description + +Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them. +You may assume that no string in words is a substring of another string in words. +Given a matrix cost of size n where cost[i][j] denotes the cost of moving from city i to city j. Your task is to complete a tour from city 0 (0-based index) to all other cities such that you visit each city exactly once and then at the end come back to city 0 at minimum cost. + +## Examples + +**Example:** + +Consider the following graph: + +**Input:** `cost = {{0,111},{112,0}}` +**Output:** 223 +**Explanation:** We can visit `0->1->0` and + +``` +Input: `cost = {{0,111},{112,0}}` +Output: 223 +Explanation: We can visit 0->1->0 and +cost = 111 + 112. +``` + +## Your Task + +You don't need to read or print anything. Your task is to complete the function total_cost() which takes cost as the input parameter and returns the total cost to visit each city exactly once starting from city 0 and again coming back to city 0. +Expected Time Complexity: $O(2n * n2)$. +Expected Auxiliary Space: $O(2n * n)$. + +## Constraints +- $1 \leq n \leq 20$ +- $1 \leq \text{cost[i][j]} \leq (103)$ + +## Problem Explanation + +Here's the step-by-step breakdown of the Travelling Salesperson process: + +**Step 1 :** Given a list of cities and the distances between each pair of cities, the task is to find the shortest possible route that visits each city exactly once and returns to the origin city. + +**Step 2 :** Key Characteristics: +Input: A set of n cities. A distance matrix D where D[i][j] represents the distance between city i and city j. +Output: The shortest possible route (a permutation of the cities) that starts and ends at the same city and visits each city exactly once. + +### Code Implementation + + + + + ```python + class Solution: + def shortestSuperstring(self, words: List[str]) -> str: + def getMinSuffix(w1, w2): + n = min(len(w1), len(w2)) + for i in range(n, 0, -1): + if w1[-i:] == w2[:i]: + return w2[i:] + return w2 + n = len(words) + suffix = defaultdict(dict) + for i in range(n): + for j in range(n): + suffix[i][j] = getMinSuffix(words[i], words[j]) + dp = [['']*n for _ in range(1< + + + ```cpp + class Solution { + public: + string shortestSuperstring(vector& A) { + int dp[4096][12] = {0}; + int failure[12][20] = {0}; + int cost[12][12] = {0}; + int trace_table[4096][12] = {0}; + const int sz = A.size(); + const int dp_sz = 1 << sz; + + for (int i = 0; i < sz; i++) { + const int str_sz = A[i].size(); + + failure[i][0] = -1; + + for (int j = 1, k = -1; j < str_sz; j++) { + while (k >= 0 && A[i][k + 1] != A[i][j]) + k = failure[i][k]; + + if (A[i][k + 1] == A[i][j]) k++; + + failure[i][j] = k; + } + } + for (int i = 0; i < sz; i++) { + const int i_sz = A[i].size(); + + for (int j = 0; j < sz; j++) { + if (i != j) { + const int j_sz = A[j].size(); + int h = -1; + + for (int k = 0; k < j_sz; k++) { + while (h >= 0 && A[i][h + 1] != A[j][k]) + h = failure[i][h]; + + if (A[i][h + 1] == A[j][k]) + h++; + } + cost[j][i] = i_sz - h - 1; + } + } + } + for (int i = 0; i < sz; i++) + dp[1 << i][i] = A[i].size(); + + for (int state = 1; state < dp_sz; state++) { + for (int t1 = state, b1 = t1 & (-t1); t1 ; t1 ^= b1 , b1 = t1 & (-t1)) { + const int state1 = state ^ b1; + const int i = __builtin_ctz(b1); + const int i_sz = A[i].size(); + + for (int t2 = state1, b2 = t2 & (-t2); t2; t2 ^= b2, b2 = t2 & (-t2)) { + const int j = __builtin_ctz(b2); + const int tmp = dp[state1][j] + cost[j][i]; + + if (!dp[state][i] || tmp < dp[state][i]) { + dp[state][i] = tmp; + trace_table[state][i] = j; + } + } + } + } + const auto& last = dp[dp_sz - 1]; + string res; + int i = std::distance(last, std::min_element(last, last + sz)); + + for (int state = dp_sz - 1, j = trace_table[state][i]; state & (state - 1); state ^= (1 << i), i = j, j = trace_table[state][i]) + res = A[i].substr(A[i].size() - cost[j][i]) + res; + + return A[i] + res; + } + }; + ``` + + + + +## Solution Logic + +**1.Helper Function:** getMinSuffix(w1, w2): This function calculates the minimum suffix of w2 that can be appended to w1 to create the shortest possible concatenation of w1 and w2 while overlapping the end of w1 with the start of w2. It checks from the longest possible overlap down to the shortest and returns the suffix of w2 that doesn't overlap. +**2.Suffix Dictionary:** suffix is a nested dictionary where suffix[i][j] stores the minimum suffix of words[j] that can be appended to words[i]. This pre-computation helps in efficiently constructing the superstring later. +**3.Dynamic Programming (DP) Array:** dp is a 2D list where dp[mask][i] represents the shortest superstring that can be formed using the set of words represented by mask, ending with the i-th word. mask is a bitmask representing the set of words included in the current superstring. For example, if n = 3 and mask = 5 (binary 101), it indicates that the 0th and 2nd words are included in the current set. +**4.DP Initialization and Iteration:** The outer loop iterates over all possible bitmasks from 1 to $2^n - 1$. For each bitmask, the inner loop iterates over all possible ending words j.For each ending word j, the algorithm finds the best possible previous word j2 in the current set (excluding j) and constructs the superstring by appending the precomputed suffix. +**5.Result Extraction:** After filling the DP table, the algorithm finds the shortest superstring from `dp[(1 << n) - 1][i]` for all i from 0 to n-1. The bitmask `(1 << n) - 1` represents the set containing all words. +**5.Result Extraction:** After filling the DP table, the algorithm finds the shortest superstring from `dp[(1 << n) - 1][i]` for all i from 0 to n-1. The bitmask `(1 << n) - 1` represents the set containing all words. + +## Time Complexity + +$O(2n * n2)$. + +## Space Complexity + +$O(2n * n)$. + +## Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/traveling-salesman-problem-tsp-implementation/) +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/shortest-path-visiting-all-nodes/) +- **Author's Geeks for Geeks Profile:** | [DaminiChachane](https://leetcode.com/u/divcxl15/) | +This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow. +Footer diff --git a/solutions/gfg-solutions/Hard/0101-0200/0110-Median-of-the-Subarrays.md b/solutions/gfg-solutions/Hard/0101-0200/0110-Median-of-the-Subarrays.md new file mode 100644 index 0000000..a215691 --- /dev/null +++ b/solutions/gfg-solutions/Hard/0101-0200/0110-Median-of-the-Subarrays.md @@ -0,0 +1,209 @@ +--- +id: median-of-the-subarrays +title: Median of the Subarrays +difficulty: Hard +sidebar_label: 0110-Median of the Subarrays +tags: + - Array + - Backtracking + - DSA + - Python + - C++ +--- + +## Problem Description + +Steps to solve a problem Median of the Subarrays . + +You are given an array nums of size n consisting of distinct integers from 1 to n and a positive integer k. + +Return the number of non-empty subarrays in nums that have a median equal to k. + +Note: + +The median of an array is the middle element after sorting the array in ascending order. If the array is of even length, the median is the left middle element. +For example, the median of [2,3,1,4] is 2, and the median of [8,4,3,5,1] is 4. +A subarray is a contiguous part of an array. + + + +### Examples + +#### Example 1: + +**Input:** `N = 5, M = 2 ,A[] = {2, 1, 3, 5, 4}` +**Output: ** 3 +**Explanation: ** The subarrays which has median equal to M +are [2], [2,1,3] and [2,1,3,5] +#### Example 2: +Input: +N = 1, M = 1 +A[] = {1} +Output: +1 +Explanation: +The subarrays which has median equal to M +is [1]. + + + +### Constraints + +- `1 ≀ N ≀ 105` +- `1 ≀ A[] ≀ 105` +- `1 ≀ M ≀ N` +### Approach + +**Step 1 :Convert Array Values:** + +The first step is to find the index of the value k in the array nums. +- Convert each element in nums such that: + - If `nums[i] < k`, set `nums[i] = -1`. + - If `nums[i] > k`, set `nums[i] = 1`. + - If `nums[i] == k`, set `nums[i] = 0` and store this index in idxK. +**Step 2 : Compute Prefix Sum:** +- Create a prefixSum array where each element at index i is the sum of the first i elements of the modified nums array. +- This helps in quickly calculating the sum of any subarray. +**Step 3 : Helper Function:** +- A helper function is used to calculate the number of subarrays in a given range [l, r] where the subarray sum is either 0 or 1. +- This is done using a hashmap to count the frequency of each prefix sum encountered so far. +**Step 4 : Calculate Result:** +- Use the helper function to calculate: + -left: Subarrays in the range [0, idxK-1]. + -right: Subarrays in the range [idxK+1, nums.length-1]. + -total: Subarrays in the range [0, nums.length-1]. +- The result is obtained by subtracting left and right from total to get the count of subarrays that include the element k and have the median equal to k. + +### Solution Code + +#### Java + +``` +class Solution { + public int countSubarrays(int[] nums, int k) { + // 1. find index of k, and convert array into -1, 0, 1 + int idxK = -1; + for (int i = 0; i < nums.length; i++) { + if (nums[i] < k) nums[i] = -1; + else if (nums[i] > k) nums[i] = 1; + else { + idxK = i; + nums[i] = 0; + } + } + // 2. calculate the prefix Sum + int[] prefixSum = new int[nums.length + 1]; + + for (int i = 1; i < prefixSum.length; i++) prefixSum[i] = prefixSum[i - 1] + nums[i - 1]; + + // 3. calculate three range: total [0, n - 1] - left[0, idxK - 1] - right[idxK + 1]; + int left = helper(0, idxK, prefixSum); + int right = helper(idxK + 1, nums.length, prefixSum); + int total = helper( 0, nums.length, prefixSum); + + return total - left - right; + } + + // calculate current interval, subarray sum = 0 and 1; + private int helper(int l, int r, int[] prefixSum) { + Map counter = new HashMap<>(); + + int ans = 0; + for (int i = l; i <= r; i++) { + int currSum = prefixSum[i]; + + if (counter.containsKey(currSum)) { + ans += counter.get(currSum); + } + + if (counter.containsKey(currSum - 1)) { + ans += counter.get(currSum - 1); + } + + counter.put(currSum, counter.getOrDefault(currSum, 0) + 1); + } + + return ans; + } +} + +``` + +#### C++ + +``` + class Solution { +public: + int countSubarrays(vector& nums, int k) { + //valid subarrays will be starting from 0 to i where i being the index of k and ending at i to n + //suppose i foudn a valid subarray between s and e + //numbers greater than k between s to i be g1 + //number smaller than k be s1 + //from i to end + //number greater than k be g2 and less than be s2 + // from given we know (g1+g2)-(s1+s2)=0 0r 1 + //----> (g1-s1)+(g2-s2)==0 o1 1 + //in first for loop we are calucalting g2-s2 at every index + + int n=nums.size(); + int ind=-1; + for(int i=0;imap; + int diff=0; + map[0]++; + for(int i=ind+1;ik) + { + diff++; + } + + else if(nums[i]=0;i--) + { + if(nums[i]>k) + { + diff++; + } + else if(nums[i]left); + if( prev!=NULL && root->val < prev->val){ + if(first==NULL){ + first = prev; + middle = root; + } + else last = root; + } + prev = root; + inorder(root-> right); + } +public: + + void recoverTree(TreeNode* root) { + first = middle = last = NULL; + prev = new TreeNode(INT_MIN); + inorder(root); + if( first && last){ + swap(first -> val, last->val); + } + + else if( first && middle ){ + swap(first->val, middle-> val); + } + + } +}; + +``` +## Your Task + +You don't need to take any input. Just complete the function correctBst() that takes root node as parameter. The function should return the root of corrected BST. BST will then be checked by driver code and 0 or 1 will be printed. +N = number of nodes +Expected Time Complexity: $O(N)$ +Expected Auxiliary Space: $O(logN)$ + + + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Fixing Two swapped nodes of a BST](https://www.geeksforgeeks.org/problems/fixing-two-swapped-nodes-of-a-bst--170646/1) | [Fixing Two swapped nodes of a BST](https://leetcode.com/problems/recover-binary-search-tree/solutions/3647453/easy-c-solution-inorder-efficient/) | [DaminiChachane](https://leetcode.com/u/divcxl15/) | + diff --git a/solutions/gfg-solutions/Hard/0101-0200/0114-Water-Connection-Problem.md b/solutions/gfg-solutions/Hard/0101-0200/0114-Water-Connection-Problem.md new file mode 100644 index 0000000..50376e8 --- /dev/null +++ b/solutions/gfg-solutions/Hard/0101-0200/0114-Water-Connection-Problem.md @@ -0,0 +1,129 @@ +--- +id: water-connection-problem +title: Water-Connection-Problem (Geeks for Geeks) +sidebar_label: Water Connection Problem +tags: + - Intermediate + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Water Connection Problem problem on Geeks for Geeks." +--- + +## Problem Description + +Every house in the colony has at most one pipe going into it and at most one pipe going out of it. Tanks and taps are to be installed in a manner such that every house with one outgoing pipe but no incoming pipe gets a tank installed on its roof and every house with only an incoming pipe and no outgoing pipe gets a tap. + +Given two integers n and p denoting the number of houses and the number of pipes. The connections of pipe among the houses contain three input values: a_i, b_i, d_i denoting the pipe of diameter d_i from house a_i to house b_i, find out the efficient solution for the network. + +The output will contain the number of pairs of tanks and taps t installed in first line and the next t lines contain three integers: house number of tank, house number of tap and the minimum diameter of pipe between them. + + +## Examples + +**Example:** +**Input:** +``` + 4 2 + 1 2 60 + 3 4 50 +``` +**Output:** +``` + 2 + 1 2 60 + 3 4 50 +``` +**Explanation:** +Connected components are: `1->2` and `3->4` +Therefore, our answer is 2 followed by `1 2 60` and `3 4 50`. +## Your Task +You don't need to read input or print anything. Your task is to complete the function solve() which takes an integer n(the number of houses), p(the number of pipes),the array a[] , b[] and d[] (where d[i] denoting the diameter of the ith pipe from the house a[i] to house b[i]) as input parameter and returns the array of pairs of tanks and taps installed i.e ith element of the array contains three integers: house number of tank, house number of tap and the minimum diameter of pipe between them. Note that, returned array must be sorted based on the house number containing a tank (i.e. smaller house number should come before a large house number). + +Expected Time Complexity: $O(n+p)$. +Expected Auxiliary Space: $O(n+p)$. + +## Constraints + +- `1<=n<=20` +- `1<=p<=50` +- `1<=a[i]`,`b[i]<=20` +- `1<=d[i]<=100` + +## Problem Explanation + +There are n houses and p water pipes in Geek Colony. Every house has at most one pipe going into it and at most one pipe going out of it. Geek needs to install pairs of tanks and taps in the colony according to the following guidelines. +**Step 1 :** Every house with one outgoing pipe but no incoming pipe gets a tank on its roof. +**Step 2 :** Every house with only one incoming and no outgoing pipe gets a tap. +The Geek council has proposed a network of pipes where connections are denoted by three input values: ai, bi, di denoting the pipe of diameter di from house ai to house bi. +**Step 3 :** Find a more efficient way for the construction of this network of pipes. Minimize the diameter of pipes wherever possible. +Note: The generated output will have the following format. The first line will contain t, denoting the total number of pairs of tanks and taps installed. The next t lines contain three integers each: house number of tank, house number of tap, and the minimum diameter of pipe between them. + + + +### Code Implementation + + + + + ```python +class Solution: + def canMeasureWater(self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int) -> bool: + + seen = set() + + def dfs(tot): + if tot == targetCapacity: + return True + if tot in seen or tot < 0 or tot > jug1Capacity + jug2Capacity: + return False + + seen.add(tot) + + return dfs(tot+jug1Capacity) or dfs(tot-jug1Capacity) or dfs(tot+jug2Capacity) or dfs(tot-jug2Capacity) + + return dfs(0) + ``` + + + + + ```cpp +class Solution { +public: + bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) { + int x = gcd(jug1Capacity,jug2Capacity) ; + if(jug1Capacity+ jug2Capacity < targetCapacity) return false; + if(targetCapacity % x == 0 ) return true ; + return false ; + } +}; + ``` + + + +## Solution Logic +To solve the problem of determining if it is possible to measure exactly targetCapacity liters using two jugs with capacities jug1Capacity and jug2Capacity, we can use mathematical reasoning involving the greatest common divisor (GCD). Here are the steps involved in the solution logic: + +**1.Calculate the Greatest Common Divisor (GCD):** Compute the GCD of the two jug capacities, jug1Capacity and jug2Capacity. The GCD is the largest integer that divides both numbers without leaving a remainder. +**2.Check if Total Capacity is Less Than Target:** If the sum of the two jug capacities (jug1Capacity + jug2Capacity) is less than the targetCapacity, return false. This is because even if we fill both jugs to their maximum, we still cannot reach the targetCapacity. +**3.Check Divisibility by GCD:** Check if the targetCapacity is divisible by the GCD. If targetCapacity % GCD == 0, return true. This is because if targetCapacity is a multiple of the GCD of the two jug capacities, it is possible to measure exactly targetCapacity liters using the two jugs. This stems from a property of the GCD which states that any linear combination of the two numbers (with integer coefficients) can be written as a multiple of their GCD. +**Default Case:** If none of the above conditions are met, return false. +The algorithm is based on the mathematical fact derived from Bezout's identity which states that the equation `π‘Žπ‘₯ + 𝑏𝑦 = 𝑑` has a solution if and only if `d` (the GCD of `a` and `b`) divides `c`. +This logic ensures that the solution is efficient and correct, leveraging properties of number theory to make the determination. +## Time Complexity + +$O(n+p)$ + +## Space Complexity + +$O(n+p)$ + +## Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/problems/water-connection-problem5822/) +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/water-and-jug-problem/) +- **Author's Geeks for Geeks Profile:** | [DaminiChachane](https://leetcode.com/u/divcxl15/) | + +This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow. diff --git a/solutions/gfg-solutions/Hard/0101-0200/0115-Binary-Tree-To-DLL.md b/solutions/gfg-solutions/Hard/0101-0200/0115-Binary-Tree-To-DLL.md new file mode 100644 index 0000000..addf24b --- /dev/null +++ b/solutions/gfg-solutions/Hard/0101-0200/0115-Binary-Tree-To-DLL.md @@ -0,0 +1,271 @@ +--- +id: binary-tree-to-dll +title: Binary Tree to DLL +sidebar_label: Binary Tree to DLL + +tags: +- Binary tree +- DLL + +description: "This is a solution to the Binary Tree to DLL problem on GeeksForGeeks." +--- + +## Problem Description +Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be same as Inorder of the given Binary Tree. The first node of Inorder traversal (leftmost node in BT) must be the head node of the DLL. +Note: H is the height of the tree and this space is used implicitly for the recursion stack. + +### Examples + +**Example 1:** +``` +Input: + 1 + / \ + 3 2 + +Output: +3 1 2 +2 1 3 + +Explanation: Explanation: DLL would be 3<=>1<=>2 +``` + +**Example 2:** +``` +Input: + 10 + / \ + 20 30 + / \ + 40 60 + +Output: +40 20 60 10 30 +30 10 60 20 40 + +Explanation: +DLL would be +40<=>20<=>60<=>10<=>30. +``` + + +### Constraints +- `1 ≀ Number of nodes ≀ 10^5` +- `0 ≀ Data of a node ≀ 10^5` + + +## Solution for Binary Tree to DLL +### Approach +#### Brute Force +- **Inorder Traversal**: Perform an inorder traversal of the binary tree to collect nodes in the order they would appear in the DLL. +- **Construct DLL**: As you traverse the tree in inorder + - Keep track of the previously visited node. + - Adjust pointers (`left` and `right`) of each node to convert it into a DLL node. + - Update the head of the DLL once you reach the leftmost node (first node in inorder traversal). + +**Implementation:** +```cpp +// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + TreeNode* treeToDoublyList(TreeNode* root) { + if (root == nullptr) + return nullptr; + + TreeNode* head = nullptr; // Head of the DLL + TreeNode* prev = nullptr; // Previous node in inorder traversal + + inorder(root, prev, head); + + // Connect head and tail for circular DLL + head->left = prev; + prev->right = head; + + return head; + } + + void inorder(TreeNode* node, TreeNode*& prev, TreeNode*& head) { + if (node == nullptr) + return; + + // Recursively traverse left subtree + inorder(node->left, prev, head); + + // Process current node + if (prev == nullptr) { + // This is the leftmost node (head of DLL) + head = node; + } else { + // Connect previous node with current node + prev->right = node; + node->left = prev; + } + prev = node; // Update prev to current node + + // Recursively traverse right subtree + inorder(node->right, prev, head); + } +}; +``` + + +#### Optimized Approach +- **Algorithm**: + - Use a recursive approach to perform an inorder traversal while adjusting the pointers to form a doubly linked list on the fly. + - Maintain a reference to the previously processed node to set the `left` and `right` pointers correctly. +- **Steps**: + - Initialize `prev` as `None` and `head` as `None` to keep track of the previous node and the head of the DLL, respectively. + - Define a recursive function `convert_to_dll` that: + - Recursively converts the left subtree. + - Adjusts the pointers of the current node based on the `prev` node. + - Updates `prev` to the current node. + - Recursively converts the right subtree. + - Call the recursive function with the root node. + - Return the `head` of the DLL. + +**Complexity:** +- Time Complexity: O(N), where N is the number of nodes in the binary tree. Each node is visited exactly once. +- Space Complexity: O(H), where H is the height of the binary tree. This is the space required for the recursion stack. + +**Corner Cases:** +- The binary tree is empty (i.e., the root is `None`). +- The binary tree has only one node. + + +## Code in Different Languages + + + + + + + ```python + class Solution: + def __init__(self): + self.prev = None + self.head = None + + + def bToDLL(self, root): + if not root: + return None + + def inorder(node): + if not node: + return + + inorder(node.left) + + if self.prev: + self.prev.right = node + node.left = self.prev + else: + self.head = node + + self.prev = node + + inorder(node.right) + + inorder(root) + return self.head + ``` + + + + + + + ``` + class Solution + { + //Function to convert binary tree to doubly linked list and return it. + Node prev = null; + Node head = null; + + // Function to convert binary tree to doubly linked list and return it. + public Node bToDLL(Node root) { + if (root == null) { + return null; + } + + inorder(root); + return head; + } + + private void inorder(Node node) { + if (node == null) { + return; + } + + inorder(node.left); + + if (prev != null) { + prev.right = node; + node.left = prev; + } else { + head = node; + } + + prev = node; + + inorder(node.right); + } + } + ``` + + + + + + + ```cpp + class Solution { + public: + Node* prev = nullptr; + Node* head = nullptr; + + // Function to convert binary tree to doubly linked list and return it. + Node* bToDLL(Node* root) { + if (root == nullptr) { + return nullptr; + } + + inorder(root); + return head; + } + + private: + void inorder(Node* node) { + if (node == nullptr) { + return; + } + + inorder(node->left); + + if (prev != nullptr) { + prev->right = node; + node->left = prev; + } else { + head = node; + } + + prev = node; + + inorder(node->right); + } + }; + ``` + + + + +## References + +- **LeetCode Problem**: [Binary Tree to DLL](https://www.geeksforgeeks.org/problems/binary-tree-to-dll/1) \ No newline at end of file diff --git a/solutions/gfg-solutions/Hard/0101-0200/0116-LRU-Cache.md b/solutions/gfg-solutions/Hard/0101-0200/0116-LRU-Cache.md new file mode 100644 index 0000000..9bd92ee --- /dev/null +++ b/solutions/gfg-solutions/Hard/0101-0200/0116-LRU-Cache.md @@ -0,0 +1,296 @@ +--- +id: lru-cache +title: LRU Cache +sidebar_label: LRU Cache + +tags: +- Linked List +- DLL +- Hash +- Queue +- Design Pattern +- Data Structures + +description: "This is a solution to the LRU Cache problem on GeeksForGeeks." +--- + +## Problem Description +Design a data structure that works like a LRU Cache. Here **cap** denotes the capacity of the cache and Q denotes the number of queries. Query can be of two types: +- **SET x y**: sets the value of the key x with value y +- **GET x**: gets the key of x if present else returns -1. + +The LRUCache class has two methods get() and set() which are defined as follows. +- **get(key)**: returns the value of the key if it already exists in the cache otherwise returns -1. +- **set(key, value)**: if the key is already present, update its value. If not present, add the key-value pair to the cache. If the cache reaches its capacity it should invalidate the least recently used item before inserting the new item. +- In the constructor of the class the capacity of the cache should be initialized. + +### Examples + +**Example 1:** +``` +Input: +cap = 2 +Q = 2 +Queries = SET 1 2 GET 1 + +Output: +2 + +Explanation: +Cache Size = 2 + +SET 1 2 GET 1 +SET 1 2 : 1 -> 2 + +GET 1 : Print the value corresponding +to Key 1, ie 2. +``` + +**Example 2:** +``` +Input: +cap = 2 +Q = 8 +Queries = SET 1 2 SET 2 3 SET 1 5 +SET 4 5 SET 6 7 GET 4 SET 1 2 GET 3 + +Output: +5 -1 + +Explanation: +Cache Size = 2 +SET 1 2 : 1 -> 2 + +SET 2 3 : 1 -> 2, 2 -> 3 (the most recently +used one is kept at the rightmost position) + +SET 1 5 : 2 -> 3, 1 -> 5 + +SET 4 5 : 1 -> 5, 4 -> 5 (Cache size is 2, hence +we delete the least recently used key-value pair) + +SET 6 7 : 4 -> 5, 6 -> 7 + +GET 4 : Prints 5 (The cache now looks like +6 -> 7, 4->5) + +SET 1 2 : 4 -> 5, 1 -> 2 +(Cache size is 2, hence we delete the least +recently used key-value pair) + +GET 3 : No key value pair having +key = 3. Hence, -1 is printed. +``` + + +### Constraints +- `1 ≀ Cap ≀ 10^3` +- `1 ≀ Q ≀ 10^5` +- `1 ≀ x,y ≀ 10^4` + + +## Solution for LRU Cache +### Approach +#### Brute Force +In the brute force approach, we'll use a list to maintain the order of elements and a dictionary to store key-value pairs. This solution will not meet the requirement of O(1) time complexity for both `get()` and `set()` operations but will help in understanding the mechanism. +- **Initialization**: Use a dictionary `cache` to store the key-value pairs and a list order to store the keys in the `order` of their usage. +- **GET Operation:** + - If the key exists in the cache, move the key to the end of the order list (to mark it as recently used) and return the value. + - If the key does not exist, return -1. +- **SET Operation:** + - If the key already exists, update the value and move the key to the end of the `order` list. + - If the key does not exist and the cache is not full, add the key-value pair and append the key to the end of the `order` list. + - If the cache is full, remove the least recently used item (the first item in the `order` list), then add the new key-value pair and append the key to the end of the `order` list. + + +**Implementation:** +```python +class LRUCache: + def __init__(self, capacity: int): + self.capacity = capacity + self.cache = {} + self.order = [] + + def get(self, key: int) -> int: + if key in self.cache: + self.order.remove(key) + self.order.append(key) + return self.cache[key] + return -1 + + def set(self, key: int, value: int) -> None: + if key in self.cache: + self.cache[key] = value + self.order.remove(key) + else: + if len(self.cache) >= self.capacity: + lru = self.order.pop(0) + del self.cache[lru] + self.cache[key] = value + self.order.append(key) + +# Example usage +lru_cache = LRUCache(2) +lru_cache.set(1, 2) +print(lru_cache.get(1)) # Output: 2 +``` + +#### Complexity Analysis: +- Time Complexity: + - `get()`: O(n) due to list removal and append operations. + - `set()`: O(n) due to list removal and append operations. +- Space Complexity: + - O(n) where n is the capacity of the cache. + + +#### Optimized Approach + For an optimized solution, we can use an OrderedDict from the collections module in Python, which maintains the order of insertion and provides O(1) time complexity for both get() and set() operations. +- **Steps**: + - Initialization: Use an OrderedDict to store the key-value pairs and maintain the order of insertion. + - GET Operation: + - If the key exists in the cache, move the key to the end (to mark it as recently used) and return the value. + - If the key does not exist, return -1. + - SET Operation: + - If the key already exists, update the value and move the key to the end. + - If the key does not exist and the cache is not full, add the key-value pair. + - If the cache is full, remove the first item (the least recently used item), then add the new key-value pair. + +**Implementation:** +```python +from collections import OrderedDict + +class LRUCache: + def __init__(self, capacity: int): + self.cache = OrderedDict() + self.capacity = capacity + + def get(self, key: int) -> int: + if key in self.cache: + self.cache.move_to_end(key) + return self.cache[key] + return -1 + + def set(self, key: int, value: int) -> None: + if key in self.cache: + self.cache.move_to_end(key) + self.cache[key] = value + if len(self.cache) > self.capacity: + self.cache.popitem(last=False) + +# Example usage +lru_cache = LRUCache(2) +lru_cache.set(1, 2) +print(lru_cache.get(1)) # Output: 2 +``` + +**Complexity:** +- Time Complexity: O(1) for both `get()` and `set()`. +- Space Complexity: O(n) where n is the capacity of the cache. + +**Corner Cases:** +- When the cache is empty, `get()` should return -1 for any key. +- When inserting into a full cache, ensure the least recently used item is removed. +- Ensure `set()` updates the value and position if the key already exists. +- Handling of negative and zero capacity should be considered (though usually, capacity will be a positive integer). + + +## Code in Different Languages + + + + + + + ```java + import java.util.LinkedHashMap; + import java.util.Map; + + class LRUCache { + private final int capacity; + private final Map cache; + + public LRUCache(int capacity) { + this.capacity = capacity; + this.cache = new LinkedHashMap(capacity, 0.75f, true) { + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > capacity; + } + }; + } + + public int get(int key) { + return cache.getOrDefault(key, -1); + } + + public void set(int key, int value) { + cache.put(key, value); + } + + public static void main(String[] args) { + LRUCache lruCache = new LRUCache(2); + lruCache.set(1, 2); + System.out.println(lruCache.get(1)); // Output: 2 + } + } + + ``` + + + + + + + ```cpp + #include + #include + #include + using namespace std; + + class LRUCache { + private: + int capacity; + list> cache; + unordered_map>::iterator> map; + + public: + LRUCache(int capacity) : capacity(capacity) {} + + int get(int key) { + if (map.find(key) == map.end()) { + return -1; + } else { + cache.splice(cache.begin(), cache, map[key]); + return map[key]->second; + } + } + + void set(int key, int value) { + if (map.find(key) != map.end()) { + cache.splice(cache.begin(), cache, map[key]); + map[key]->second = value; + return; + } + if (cache.size() == capacity) { + int k = cache.back().first; + cache.pop_back(); + map.erase(k); + } + cache.push_front({key, value}); + map[key] = cache.begin(); + } + }; + + int main() { + LRUCache lruCache(2); + lruCache.set(1, 2); + cout << lruCache.get(1) << endl; // Output: 2 + return 0; + } + ``` + + + + +## References + +- **GeekForGeeks Problem**: [LRU Cache](https://www.geeksforgeeks.org/problems/lru-cache/1) \ No newline at end of file diff --git a/solutions/gfg-solutions/Hard/0101-0200/111-Maximum-Number-of-coins.md b/solutions/gfg-solutions/Hard/0101-0200/111-Maximum-Number-of-coins.md new file mode 100644 index 0000000..472aa1a --- /dev/null +++ b/solutions/gfg-solutions/Hard/0101-0200/111-Maximum-Number-of-coins.md @@ -0,0 +1,118 @@ +--- +id: 111-maximum-number-of-coins +title: Maximum Number of coins (Geeks for Geeks) +sidebar_label: Maximum Number of coins Problem +tags: + - Intermediate + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Maximum Number of coins Problem on Geeks for Geeks." +--- + +## Problem Description + +We have been given N balloons, each with a number of coins associated with it. On bursting a balloon i, the number of coins gained is equal to A[i-1]*A[i]*A[i+1]. +Also, balloons i-1 and i+1 now become adjacent. Find the maximum possible profit earned after bursting all the balloons. Assume an extra 1 at each boundary. + +## Examples + +**Example:** + +Consider the following graph: + +**Input:** ` N=2 , a[]={5, 10}` +**Output:** `60` +**Explanation:** First Burst `5`, Coins = `1*5*10` , Then burst `10`, Coins+=` 1*10*1` , Total = `60` + +**Example:** + +**Input:** `N=4 , a[] = {3,1,5,8}` +**Output:** 167 +**Explanation:** +`nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []` +`coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167.` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function maxCoins() which takes the array arr[], its size N, and returns the maximum number of coins that can be collected. + +Expected Time Complexity: $O(N^3)$ +Expected Space Complexity: $O(N^2)$ + +## Constraints +- `1 <= N <= 400` +- `0 <= a[i] <= 100` + +## Problem Explanation + +Here's the step-by-step breakdown of the Maximum Number of coins process: + +There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows: + +**Step 1:** In each step, you will choose any 3 piles of coins (not necessarily consecutive). +**Step 2 :**Of your choice, Alice will pick the pile with the maximum number of coins. +**Step 3 :**You will pick the next pile with the maximum number of coins. +**Step 4 :**Your friend Bob will pick the last pile. +**Step 5 :**Repeat until there are no more piles of coins. + +Given an array of integers piles where piles[i] is the number of coins in the ith pile. Return the maximum number of coins that you can have. + +### Code Implementation + + + + + ```python + +class Solution: + def maxCoins(self, piles: List[int]) -> int: + piles.sort() + return sum(piles[-2:(len(piles)//3)-1:-2]) + + ``` + + + + ```cpp + class Solution { +public: + + int maxCoins(vector& piles) { + // sort the piles in non-increasing order + sort(piles.begin(), piles.end(), greater()); + + // greedy using two-pointers + int sum = 0; + for (int l = 0, r = piles.size() - 1; l < r; l += 2, r--) { + sum += piles[l + 1]; + } + return sum; + } +}; + ``` + + + + +## Solution Logic + - Sort the piles in non-increasing order + - Greedy using two-pointers + + +## Time Complexity + +$$O(N^3)$$. + +## Space Complexity + +$$O(N^2)$$. + +## Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/problems/maximum-number-of-coins--170647/1) +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/maximum-number-of-coins-you-can-get/description/) +- **Author's Geeks for Geeks Profile:** | [DaminiChachane](https://leetcode.com/u/divcxl15/) | + +This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow. diff --git a/solutions/gfg-solutions/Hard/0101-0200/image-1.png b/solutions/gfg-solutions/Hard/0101-0200/image-1.png new file mode 100644 index 0000000..e31c4ad Binary files /dev/null and b/solutions/gfg-solutions/Hard/0101-0200/image-1.png differ diff --git a/solutions/gfg-solutions/Hard/0101-0200/image.png b/solutions/gfg-solutions/Hard/0101-0200/image.png new file mode 100644 index 0000000..9b90792 Binary files /dev/null and b/solutions/gfg-solutions/Hard/0101-0200/image.png differ diff --git a/solutions/gfg-solutions/Hard/0101-0200/median-of-2-sorted-arrays-of-different-sizes b/solutions/gfg-solutions/Hard/0101-0200/median-of-2-sorted-arrays-of-different-sizes new file mode 100644 index 0000000..93f84f0 --- /dev/null +++ b/solutions/gfg-solutions/Hard/0101-0200/median-of-2-sorted-arrays-of-different-sizes @@ -0,0 +1,197 @@ + +--- +id: median-of-2-sorted-arrays-of-different-sizes +title: Median of Two Sorted Arrays Problem (gfg) +sidebar_label: 0004 - Median of Two Sorted Arrays +tags: + - Intermediate + - Array + - Binary Search + - LeetCode + - CPP + - Python + - DSA +description: "This is a solution to the Median of Two Sorted Arrays problem on LeetCode." +--- + +This tutorial contains a complete walk-through of the Median of Two Sorted Arrays problem from the LeetCode website. It features the implementation of the solution code in two programming languages: Python and C++. + +## Problem Description + +Given two sorted arrays array1 and array2 of size m and n respectively, find the median of the two sorted arrays. + +## Examples + +**Example 1:** + +``` +Input : array1 = [1, 3], array2 = [2] +Output : 2.0 +Explanation : The median is 2.0. +``` + +**Example 2:** + +``` +Input : array1 = [1, 2], array2 = [3, 4] +Output : 2.5 +Explanation : The median is (2 + 3)/2 = 2.5. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `MedianOfArrays()` which takes the arrays `array1`, `array2` and their sizes `m` and `n` as inputs and return the median of the two sorted arrays. + +Expected Time Complexity: $O(log(min(m, n)))$ + +Expected Auxiliary Space: $O(1)$ + +## Constraints + +* `0 ≀ m, n ≀ 1000` +* `1 ≀ array1[i], array2[i] ≀ 1000000` + +## Problem Explanation + +The problem is to find the median of two sorted arrays. The median is the middle value in the sorted order of the combined array. If the total number of elements is even, the median is the average of the two middle numbers. + +## Code Implementation + + + + + + ```py + class Solution: + def MedianOfArrays(self, array1, array2): + if len(array1) > len(array2): + array1, array2 = array2, array1 + + m, n = len(array1), len(array2) + imin, imax, half_len = 0, m, (m + n + 1) // 2 + + while imin <= imax: + i = (imin + imax) // 2 + j = half_len - i + + if i < m and array1[i] < array2[j-1]: + imin = i + 1 + elif i > 0 and array1[i-1] > array2[j]: + imax = i - 1 + else: + if i == 0: max_of_left = array2[j-1] + elif j == 0: max_of_left = array1[i-1] + else: max_of_left = max(array1[i-1], array2[j-1]) + + if (m + n) % 2 == 1: + return max_of_left + + if i == m: min_of_right = array2[j] + elif j == n: min_of_right = array1[i] + else: min_of_right = min(array1[i], array2[j]) + + return (max_of_left + min_of_right) / 2.0 + ``` + + + + + + ```cpp + #include + #include + #include + #include + #include + + class Solution { + public: + double MedianOfArrays(std::vector& array1, std::vector& array2) { + if (array1.size() > array2.size()) { + return MedianOfArrays(array2, array1); + } + + int m = array1.size(); + int n = array2.size(); + int low = 0, high = m; + + while (low <= high) { + int partition1 = (low + high) / 2; + int partition2 = (m + n + 1) / 2 - partition1; + + int maxLeft1 = (partition1 == 0) ? INT_MIN : array1[partition1 - 1]; + int minRight1 = (partition1 == m) ? INT_MAX : array1[partition1]; + + int maxLeft2 = (partition2 == 0) ? INT_MIN : array2[partition2 - 1]; + int minRight2 = (partition2 == n) ? INT_MAX : array2[partition2]; + + if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) { + if ((m + n) % 2 == 0) { + return (std::max(maxLeft1, maxLeft2) + std::min(minRight1, minRight2)) / 2.0; + } else { + return std::max(maxLeft1, maxLeft2); + } + } else if (maxLeft1 > minRight2) { + high = partition1 - 1; + } else { + low = partition1 + 1; + } + } + + throw std::invalid_argument("Input arrays are not sorted"); + } + }; + + // Example usage: + int main() { + std::vector array1 = {1, 3}; + std::vector array2 = {2}; + + Solution sol; + double median = sol.MedianOfArrays(array1, array2); + std::cout << "Median: " << median << std::endl; // Expected output: 2.0 + + return 0; + } + ``` + + + + + +## Example Walkthrough + +For the arrays `array1 = [1, 3]` and `array2 = [2]`: + +1. Combined array would be `[1, 2, 3]`. +2. The median is `2.0`. + +For the arrays `array1 = [1, 2]` and `array2 = [3, 4]`: + +1. Combined array would be `[1, 2, 3, 4]`. +2. The median is `(2 + 3) / 2 = 2.5`. + +## Solution Logic: + +1. Ensure `array1` is the smaller array to minimize the number of binary search steps. +2. Perform binary search on the smaller array. +3. Calculate partitions for both arrays such that left and right parts of the partitions can be merged to form the sorted order. +4. Handle edge cases where partitions are at the boundaries of the arrays. +5. If the total number of elements is even, the median is the average of the maximum of the left parts and the minimum of the right parts. +6. If the total number of elements is odd, the median is the maximum of the left parts. + +## Time Complexity + +* The primary operation is binary search, which has a time complexity of $O(log(min(m, n)))$, where m and n are the sizes of the arrays. + +## Space Complexity + +Auxiliary Space: The auxiliary space complexity is $O(1)$ because we are not using any extra space proportional to the size of the input arrays. + +## References + +- **gfg Problem:** [gfg Problem](https://www.geeksforgeeks.org/problems/median-of-2-sorted-arrays-of-different-sizes/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=bottom_sticky_on_article) +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) +``` + +In this format, the tutorial includes a description of the problem, examples, expected time and space complexity, constraints, detailed problem explanation, and complete code implementations in both Python and C++. It ends with a walkthrough of examples to illustrate the logic of the solution. diff --git a/solutions/gfg-solutions/_category_.json b/solutions/gfg-solutions/_category_.json new file mode 100644 index 0000000..c91d982 --- /dev/null +++ b/solutions/gfg-solutions/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "GFG Solutions", + "position": 4, + "link": { + "type": "generated-index", + "description": "All Geeks for Geeks solutions in one place. Sorted by difficulty. Contains problem description, solution, and explanation." + } +} \ No newline at end of file diff --git a/solutions/gfg-solutions/easy/armstrong-numbers.md b/solutions/gfg-solutions/easy/armstrong-numbers.md new file mode 100644 index 0000000..d231bd6 --- /dev/null +++ b/solutions/gfg-solutions/easy/armstrong-numbers.md @@ -0,0 +1,86 @@ +--- +id: armstrong-numbers +title: Armstrong Numbers +sidebar_label: 0104-Armstrong Numbers + +tags: + - Mathematical + - Algorithms +description: "A solution to the problem of determining whether the given number is armstrong number or not" +--- + +In this page, we will solve the problem of determining whether the given number is armstrong number or not. + +## Problem Description + +You are given a 3-digit number n, Find whether it is an Armstrong number or not. + +An Armstrong number of three digits is a number such that the sum of the cubes of its digits is equal to the number itself. 371 is an Armstrong number since 33 + 73 + 13 = 371. + +Note: Return "true" if it is an Armstrong number else return "false". + +### Examples + +**Example 1:** + +```plaintext +Input: n = 153 +Output: true +Explanation: 153 is an Armstrong number since 13 + 53 + 33 = 153. Hence answer is "true". +``` + +**Example 2:** + +```plaintext +Input: n = 372 +Output: false +Explanation: 372 is not an Armstrong number since 33 + 73 + 23 = 378. Hence answer is "false". +``` + +### Constraints + +- $100 \leq N < 1000$ + +## Solution + +### Intuition and Approach + +This problem can be solved by running a while loop three time and get the unit digit every time and add the cube of that digit into ans after the loop if the sum result is same as that of givrn num than return "true" and if not then return "false". + +### Approach: + +1. First we initialize three variables i,Sum,and temp. + - 'i' is initialized to 0. This variable will be used as a counter to keep track of the number of digits processed. + - 'Sum' is initialized to 0. This variable will accumulate the sum of the cubes of the digits of n. + - 'temp' is assigned the value of n. This is to store the original number for comparison later. +2. Next we run a while loop runs as long as i is less than or equal to 3. Since we're dealing with 3-digit numbers, this ensures that we process exactly 3 digits. + - In each iteration of the loop: + - The last digit of n is obtained using n % 10. + - The cube of this digit is added to Sum. + - n is then divided by 10 using integer division (n //= 10), effectively removing the last digit. + - i is incremented by 1. +3. After the loop, Sum contains the sum of the cubes of the digits of n.The original number (temp) is compared with Sum. + - If temp is equal to Sum, the function returns "true", indicating that n is an Armstrong number. + - Otherwise, it returns "false". +#### Code in Python +```python +class Solution: + def armstrongNumber (self, n): + i=0 + Sum=0 + temp=n + while(i<=3): + Sum+=(n%10)**3 + n=n//10 + i+=1 + if temp==Sum: + return "true" + return "false" + +``` + +#### Complexity Analysis + +- **Time Complexity:** $O(1)$ +- **Space Complexity:** $O(1)$ + diff --git a/solutions/gfg-solutions/easy/count-distinct-elements-in-every-window.md b/solutions/gfg-solutions/easy/count-distinct-elements-in-every-window.md new file mode 100644 index 0000000..4c1d24d --- /dev/null +++ b/solutions/gfg-solutions/easy/count-distinct-elements-in-every-window.md @@ -0,0 +1,108 @@ +--- +id: count-distinct-elements-in-every-window +title: Count Distinct Elements in Every Window +sidebar_label: 0101-Count Distinct Elements in Every Window +tags: + - sliding-window + - hash + - data-structures + - algorithms +description: "A solution to the problem of determining the count of distinct elements in every window of size k." +--- + +In this page, we will solve the problem of determining the count of distinct elements in every window of size k. + +## Problem Description + +Given an array of integers and a number K, find the count of distinct elements in every window of size K in the array. + +### Examples + +**Example 1:** + +```plaintext +Input: +N = 7, K = 4 +A[] = {1,2,1,3,4,2,3} + +Output: 3 4 4 3 + +Explanation: Window 1 of size k = 4 is +1 2 1 3. Number of distinct elements in +this window are 3. +Window 2 of size k = 4 is 2 1 3 4. Number +of distinct elements in this window are 4. +Window 3 of size k = 4 is 1 3 4 2. Number +of distinct elements in this window are 4. +Window 4 of size k = 4 is 3 4 2 3. Number +of distinct elements in this window are 3. +``` + +**Example 2:** + +```plaintext +Input: +N = 3, K = 2 +A[] = {4,1,1} + +Output: 2 1 +``` + +### Constraints + +- $1 \leq K \leq N \leq 10^5$ +- $1 \leq A[i] \leq 10^5$, for each valid $i$ + +--- + +## Solution + +### Intuition and Approach + +The problem can be solved using a sliding window approach combined with a hash map (dictionary) to efficiently track the frequency of elements within the current window. By maintaining the counts of elements and adjusting the window dynamically, the algorithm ensures that it only needs to process each element a limited number of times, resulting in a time complexity of $O(n)$, where $n$ is the length of the array. This approach is efficient for counting distinct elements in overlapping subarrays of a fixed size. + + + + +### Approach: Sliding Window + +1. Initialize the data structures and variables. `ans` is an empty list to store the count of distinct elements for each window. `freq` is an empty dictionary to keep track of the frequency of elements within the current window. `j` is a pointer representing the current end of the window, initialized to 0, and `i` is a pointer representing the current start of the window, also initialized to 0. +2. Use a while loop to iterate over the array. The loop continues until `j` reaches the end of the array (`N`). +3. For each element `A[j]`, update its count in the `freq` dictionary. If `A[j]` is already in `freq`, increment its count. If `A[j]` is not in `freq`, add it with a count of 1. +4. Check if the current window size is equal to `K` (`j - i + 1 == K`). If the condition is met, it means the window has reached the desired size. Append the number of distinct elements in the current window to the `ans` list. The number of distinct elements is the size of the `freq` dictionary. +5. Slide the window. Decrement the count of the element at the start of the window (`A[i]`) in the `freq` dictionary. If the count of `A[i]` becomes zero, remove it from the `freq` dictionary, as it is no longer in the current window. Move the start of the window forward by incrementing `i`. Move the end of the window forward by incrementing `j`. +6. After processing all windows, return the `ans` list containing the counts of distinct elements for each window. + +#### Code in Python +```python +def countDistinct(A, N, K): + ans = [] + freq = {} + j = 0 + i = 0 + + while j < N: + if A[j] in freq: + freq[A[j]] += 1 + else: + freq[A[j]] = 1 + + if j - i + 1 == K: + ans.append(len(freq)) + freq[A[i]] -= 1 + if freq[A[i]] == 0: + del freq[A[i]] + i += 1 + j += 1 + + return ans +``` + +#### Complexity Analysis + +- **Time Complexity:** $O(N)$ +- **Space Complexity:** $O(K)$ + + + +``` diff --git a/solutions/gfg-solutions/easy/count-pairs-whose-sum-is-equal-to-x.md b/solutions/gfg-solutions/easy/count-pairs-whose-sum-is-equal-to-x.md new file mode 100644 index 0000000..d83cf2a --- /dev/null +++ b/solutions/gfg-solutions/easy/count-pairs-whose-sum-is-equal-to-x.md @@ -0,0 +1,91 @@ +--- +id: count-pairs-whose-sum-is-equal-to-x +title: Count Pairs whose sum is equal to X +sidebar_label: 0109-Count Pairs whose sum is equal to X +tags: + - Linked List + - Data Structures +description: "A solution to the problem of finding the count of pairs which sum up to target x" +--- + +In this page, we will solve the problem of finding the count of pairs which sum up to target x. + +## Problem Description + +Given two linked list head1 and head2 with distinct elements, determine the count of all distinct pairs from both lists whose sum is equal to the given value x. + +Note: A valid pair would be in the form (x, y) where x is from first linked list and y is from second linked list. +### Examples + +**Example 1:** + +```plaintext +Input: +head1 = 1->2->3->4->5->6 +head2 = 11->12->13 +x = 15 +Output: 3 +Explanation: There are total 3 pairs whose sum is 15 : (4,11) , (3,12) and (2,13) +``` + +**Example 2:** + +```plaintext +Input: +head1 = 7->5->1->3 +head2 = 3->5->2->8 +x = 10 +Output: 2 +Explanation: There are total 2 pairs whose sum is 10 : (7,3) and (5,5) +``` + +### Constraints + +- $1 \leq$ length(head1), lenght(head2) $\leq10^5$ +- $1 \leq$ Value of elements of linked lists $\leq 10^9$ +- $1 \leq$ x $\leq 10^9$ +- Note : All elements in each linked list are unique. + +## Solution + +### Intuition and Approach + +This problem can be solved by using simple iterations over the both the linked list and usnig a hashmap. + +### Approach: + +1. We will first initialize + - a hashmap 'Map' is an empty dictionary that will store the difference between x and each element from the first linked list (head1). + - cnt is a counter initialized to 0, which will keep track of the number of valid pairs that sum up to x. +2. Next we will run a while loop by which we traverse the First Linked List (head1).For each node, the difference between x and the node's data (x - head1.data) is calculated and stored in the Map dictionary with the node's data as the value.This effectively maps each required complement value (x - head1.data) to its corresponding data value in the first linked list. +3. The second while loop iterates through each node in the linked list head2.For each node, it checks if the node's data exists in the Map dictionary.If it exists, it means there is a node in the first linked list whose value, when added to the current node's data from the second linked list, equals x. +4. Then we increase the counter cnt is incremented for each such valid pair found. +5. Return the count of valid pairs. + +#### Code in Python +```python +class Solution: + def countPair(self, head1, head2, n1, n2, x): + ''' + head1: head of linkedList 1 + head2: head of linkedList 2 + n1: len of linkedList 1 + n2: len of linkedList 1 + x: given sum + ''' + Map={} + cnt = 0 + while(head1): + Map[x-head1.data]=head1.data + head1=head1.next + while(head2): + if head2.data in Map: + cnt+=1 + head2=head2.next + return cnt +``` + +#### Complexity Analysis + +- **Time Complexity:** $O(length(head1)+lenght(head2))$ +- **Space Complexity:** $O(length(head1))$ or $O(length(head2))$ diff --git a/solutions/gfg-solutions/easy/count-the-zeros.md b/solutions/gfg-solutions/easy/count-the-zeros.md new file mode 100644 index 0000000..28b4502 --- /dev/null +++ b/solutions/gfg-solutions/easy/count-the-zeros.md @@ -0,0 +1,83 @@ +--- +id: count-the-zeros +title: Count The Zeros +sidebar_label: 0108-Count The Zeros +tags: + - Arrays + - Searching + - Data Structures + - Algorithms +description: "A solution to the problem of counting the number of zeros in the array" +--- + +In this page, we will solve the problem of counting the number of zeros in the array. + +## Problem Description + +Given an array arr of only 0's and 1's. The array is sorted in such a manner that all the 1's are placed first and then they are followed by all the 0's. Find the count of all the 0's. +### Examples + +**Example 1:** + +```plaintext +Input: arr[] = [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0] +Output: 3 +Explanation: There are 3 0's in the given array. +``` + +**Example 2:** + +```plaintext +Input: arr[] = [0, 0, 0, 0, 0] +Output: 5 +Explanation: There are 5 0's in the array. +``` + +### Constraints + +- $1 \leq$ arr.size $\leq10^5$ +- $0 \leq$ arr[i] $\leq1$ + +## Solution + +### Intuition and Approach + +This problem can be solved by using binary search and find the first index of zero and then return total length - index of first zero + +### Approach: + +1. Frist we will initialize variable: + - n which is the length of the array arr. + - high is initialized to n-1, which is the index of the last element in the array. + - low is initialized to 0, which is the index of the first element in the array. +2. Next we will runa a while loop runs as long as high is greater than or equal to low. +3. Then mid is calculated as the average of low and high to find the middle index of the current search range. +4. The first if statement checks if the element at mid is 0 and either mid is 0 (the start of the array) or the previous element (arr[mid-1]) is 1. If this condition is true, it means that mid is the first occurrence of 0 in the array then number of zeroes will be the difference between n (total number of elements) and mid (index of the first zero). +5. If the element at mid is 1, it means that if zeroes are present they will be right of mid. Thus, we update low to mid + 1 to search in the right half of the array. +6. If the element at mid is 0 but the condition in step 4 is not met, it means that there might be a zero to the left of mid. Thus, we update high to mid - 1 to search in the left half of the array. +7. If the loop completes without finding a 0, it means there are no zeroes in the array. The function returns 0. + + +#### Code in Python +```python + +class Solution: + def countZeroes(self, arr): + n = len(arr) + high = n-1 + low = 0 + while(high >= low): + mid = low + int((high - low) / 2) + if (( mid == 0 or arr[mid-1] == 1) and arr[mid] == 0): + return (n-mid) + if (arr[mid] == 1): + low = (mid + 1) + else: + high = mid-1 + return 0 + ``` + +#### Complexity Analysis + +- **Time Complexity:** $O(logn)$ +- **Space Complexity:** $O(1)$ diff --git a/solutions/gfg-solutions/easy/index-of-an-extra-element.md b/solutions/gfg-solutions/easy/index-of-an-extra-element.md new file mode 100644 index 0000000..62ddfaf --- /dev/null +++ b/solutions/gfg-solutions/easy/index-of-an-extra-element.md @@ -0,0 +1,77 @@ +--- +id: index-of-an-extra-element +title: Index of an Extra Element +sidebar_label: 0103-Index of an Extra Element + +tags: + - arrays + - searching + - data structures + - algorithms +description: "A solution to the problem of determining the index of the extra element in the array " +--- + +In this page, we will solve the problem of determining the index of the extra element in the array. + +## Problem Description + +You have given two sorted arrays arr1[] & arr2[] of distinct elements. The first array has one element extra added in between. Return the index of the extra element. + +Note: 0-based indexing is followed. + +### Examples + +**Example 1:** + +```plaintext +Input: n = 7, arr1[] = {2,4,6,8,9,10,12}, arr2[] = {2,4,6,8,10,12} + +Output: 4 + +Explanation: In the first array, 9 is extra added and it's index is 4. +``` + +**Example 2:** + +```plaintext +Input: n = 6, arr1[] = {3,5,7,8,11,13}, arr2[] = {3,5,7,11,13} + +Output: 3 + +Explanation: In the first array, 8 is extra and it's index is 3. +``` + +### Constraints + +- $1 \leq N \leq10^5$, where $N$ is number of nodes +- $1 \leq arr1[i], arr2[i] \leq 10^6$ +## Solution + +### Intuition and Approach + +This problem can be solved by iterating over the array by runnig the loop from o to the length of the smallest array + + + +### Approach: Inorder Traversal + +1. Run a for loop from 0 to length of the smallest array. +2. If at any point in loop the element on ith index of both arrays are different then return the index as it is the answer +3. If loop runs completely and didn't terminate this means the last index of the largest array is the answer and return that index + +#### Code in Python +```python +class Solution: + def findExtra(self,n,a,b): + for i in range(min(len(a),len(b))): + if a[i]!=b[i]:return i + return i+1 +``` + +#### Complexity Analysis + +- **Time Complexity:** $O(N)$ +- **Space Complexity:** $O(1)$ + + + diff --git a/solutions/gfg-solutions/easy/inorder_successor_in_bst.md b/solutions/gfg-solutions/easy/inorder_successor_in_bst.md new file mode 100644 index 0000000..885b623 --- /dev/null +++ b/solutions/gfg-solutions/easy/inorder_successor_in_bst.md @@ -0,0 +1,102 @@ +--- +id: inorder_successor_in_bst +title: Inorder Successor In BST +sidebar_label: 0102-Inorder Successor In BST +tags: + - binary search tree + - data-structures +description: "A solution to the problem of determining the inorder successor of given element in BST" +--- + +In this page, we will solve the problem of determining the inorder successor of given element in BST. + +## Problem Description + +Given a BST, and a reference to a Node x in the BST. Find the Inorder Successor of the given node in the BST. + +### Examples + +**Example 1:** + +```plaintext +Input: + 2 + / \ + 1 3 +K(data of x) = 2 + +Output: 3 + +Explanation: +Inorder traversal : 1 2 3 +Hence, inorder successor of 2 is 3. +``` + +**Example 2:** + +```plaintext +Input: + 20 + / \ + 8 22 + / \ + 4 12 + / \ + 10 14 +K(data of x) = 8 + +Output: 10 + +Explanation: +Inorder traversal: 4 8 10 12 14 20 22 +Hence, successor of 8 is 10. +``` + +### Constraints + +- $1 \leq N \leq10^5$, where $N$ is number of nodes + +## Solution + +### Intuition and Approach + +This problem can be solved by a simple approach of Inorder Traversal + + + +### Approach: Inorder Traversal + +1. Initialize an empty list 'traversal' to store the nodes of the tree in inorder traversal. +2. Then we define a helper function inorder_traversal to perform an inorder traversal of the tree and populate the traversal list. This function takes root as an argument. If root is None, it simply returns, indicating the base case of the recursion. +3. Within the helper function inorder_traversal, we first recursively call inorder_traversal on the left child of the current node. +4. We then append the current node to the traversal list. +5. Next, we recursively call inorder_traversal function on the right child of the current node. +6. After populating the traversal list, we iterate through the list to find the node whose value matches x.data. We do this using a for loop that iterate through the traversal list and find the successor of the element x by checking if the data of the current node (traversal[i].data) is equal to the data of the node x (x.data). +7. If the condition is met, it means we have found the node x. The inorder successor of x is the next node in the ans list (traversal[i + 1]). We return this node as the result. + +#### Code in Python +```python +class Solution: + # returns the inorder successor of the Node x in BST (rooted at 'root') + def inorderSuccessor(self, root, x): + # Code here + traversal_list=[] + def inorder_traversal(root): + if root is None:return + inorder_traversal(root.left) + traversal_list.append(root) + inorder_traversal(root.right) + inorder_traversal(root) + for i in range(len(traversal_list)-1): + if traversal_list[i].data==x.data: + return traversal_list[i+1] + return None +``` + +#### Complexity Analysis + +- **Time Complexity:** $O(N)$ +- **Space Complexity:** $O(N)$ + + + diff --git a/solutions/gfg-solutions/easy/is-binary-number-multiple-of-3.md b/solutions/gfg-solutions/easy/is-binary-number-multiple-of-3.md new file mode 100644 index 0000000..3a5f962 --- /dev/null +++ b/solutions/gfg-solutions/easy/is-binary-number-multiple-of-3.md @@ -0,0 +1,115 @@ +--- +id: is-binary-number-multiple-of-3 +title: Is Binary Number Multiple Of 3 +sidebar_label: 0109-Is Binary Number Multiple Of 3 +tags: + - Mathematical + - Bit Magic + - Data Structures + - Algorithms +description: "A solution to the problem of finding whether given binary number is divisible by 3 or not" +--- + +In this page, we will solve the problem of finding whether given binary number is divisible by 3 or not. + +## Problem Description + +Given a number in its binary form find if the given binary number is a multiple of 3. It is recommended to finish the task using one traversal of input binary number. + +### Examples + +**Example 1:** + +```plaintext +Input: S = "0011" +Output: 1 +Explanation: "0011" is 3, which is divisible by 3. +``` + +**Example 2:** + +```plaintext +Input: S = "100" +Output: 0 +Explanation: "100"'s decimal equivalent is 4, which is not divisible by 3. +``` + + +### Constraints + +- $1 \leq$ |S| $\leq10^5$ + +## Solution + +### Intuition and Approach + +The problem can be solved using two approaches one by converting the given binary string to decimal number and then find whether the given number is divisible by three or not +and another approach is by using Bit manipulation + + + +### Approach: Binary to Decimal + +1. The simplest approach is to convert the binary number into a decimal equivalent. And check if it is divisible by 3 or not. +2. For converting the binary string to decimal we will traverse the given string backwards and then + - if '1' we will add the power of 2 to the res + - if '0' we will do nothing +3. After traversing whole list we will check whether the decimal number res is divisible by 3 or not +#### Code in Python +```python +class Solution: + def isDivisible(self, s): + ans=0 + for i in range(len(s)-1,-1,-1): + if s[i]=='1': + ans+=2**(len(s)-1-i) + return int(ans%3==0) +``` + +#### Complexity Analysis + +- **Time Complexity:** $O(S)$ +- **Space Complexity:** $O(1)$ + + + + + +### Approach: Binary to Decimal + +1. we will initialize variable + - odd_sum is initialized to 0. This variable will store the count of '1's at odd positions (considering positions starting from 0 when counting from the rightmost bit). + - even_sum is initialized to 0. This variable will store the count of '1's at even positions (considering positions starting from 0 when counting from the rightmost bit). +2. The for loop iterates through each bit of the reversed binary string. enumerate(reversed(s)) gives both the index i and the bit bit.s[::-1] is used to process the string from right to left, which corresponds to the least significant bit first. +3. We then update sums based on bit position: + - For each bit, if the bit is '1': + - If the index i is even (0, 2, 4, ...), it corresponds to an odd position in the original string. Therefore, odd_sum is incremented by 1. + - If the index i is odd (1, 3, 5, ...), it corresponds to an even position in the original string. Therefore, even_sum is incremented by 1. +4. Next we will check divisibility by 3: After iterating through the entire binary string, the function calculates (odd_sum - even_sum) % 3. + The difference between odd_sum and even_sum is taken modulo 3 to check if it is divisible by 3. + - If (odd_sum - even_sum) % 3 == 0 is true, the binary number is divisible by 3, and the function returns 1 (integer representation of True). + - Otherwise, it returns 0 (integer representation of False). +#### Code in Python +```python +class Solution: + def isDivisible(self, s): + # code here + odd_sum = 0 + even_sum = 0 + for i, bit in enumerate(s[::-1]): + if bit == '1': + if i % 2 == 0: + odd_sum += 1 + else: + even_sum += 1 + return int((odd_sum - even_sum) % 3 == 0) +``` + +#### Complexity Analysis + +- **Time Complexity:** $O(log10​(n))$ +- **Space Complexity:** $O(1)$ + + + + diff --git a/solutions/gfg-solutions/easy/k-distance-from-root.md b/solutions/gfg-solutions/easy/k-distance-from-root.md new file mode 100644 index 0000000..b85a0bf --- /dev/null +++ b/solutions/gfg-solutions/easy/k-distance-from-root.md @@ -0,0 +1,119 @@ +--- +id: k-distance-from-root +title: K Distance From Root +sidebar_label: 0111-K Distance From Root +tags: + - Tree + - Data Structures +description: "A solution to the problem of finding all the nodes which are at a distance k from the root" +--- + +In this page, we will solve the problem of finding all the nodes which are at a distance k from the root. + +## Problem Description + +Given a binary tree having n nodes and an integer k. Print all nodes that are at distance k from the root (root is considered at distance 0 from itself). Nodes should be printed from left to right. +### Examples + +**Example 1:** + +```plaintext +Input: +k = 0 + 1 + / \ + 3 2 +Output: +1 +Explanation: +1 is the only node which is 0 distance from the root 1. +``` + +**Example 2:** + +```plaintext +Input: +k = 3 + 1 + / + 2 + \ + 1 + / \ + 5 3 +Output: +5 3 +Explanation: +5 and 3 are the nodes which are at distance 3 from the root 3. +Here, returning 3 5 will be incorrect. +``` + + +### Constraints + +- $1 \leq$ n $\leq10^4$ +- $0 \leq$ k $\leq30$ + +## Solution + +### Intuition and Approach + +The problem can be solved by using BFS traversal.This approach combines setting parent references to enable upward traversal and performing a breadth-first search to find nodes at the specified distance. +Adding parent references to each node, we can easily move from a node to its parent, facilitating traversal in all directions (up, left, right). +Starting from the target node, we explore all nodes at increasing distances. +By keeping track of visited nodes, we ensure that each node is processed only once, preventing cycles and redundant work. +When the distance from the target node matches k, we add the node's value to the result list. + +### Approach: BFS +1. We will first create a helper function make_parent that recursively traverses the tree, setting a parent attribute for each node. This allows upward traversal.Then we call make_parent with the root node and None as the parent. +2. We then initialize data structures + - ans: A list to store the values of nodes at distance k from the target node. + - seen: A set to track visited nodes and prevent reprocessing. +3. We will create a recursive traversal function trav. This function takes the current node and the distance from the target node as arguments. + - If the current node is None, already visited, or the distance exceeds k, the function returns. + - Add the current node to the seen set to mark it as visited. + - If the current distance matches k, add the node's value to the ans list. + - Then recursively call trav for the parent, left child, and right child, increasing the distance by 1 for each call. +4. Start the traversal from the root node with an initial distance of 0. +5. Return the ans list containing the values of nodes at distance k from the root. + +### Code in Python +```python +class Solution: + def KDistance(self,root,k): + ''' + :param root: root of given tree. + :param k: distance k from root + :return: list of all nodes that are at distance k from root. + ''' + # code here + def make_parent(node,parent): + if not node: + return + node.parent=parent + make_parent(node.left,node) + make_parent(node.right,node) + + make_parent(root,None) + ans=[] + seen=set() + + def trav(node,dist): + if not node or node in seen or dist>k: + return + seen.add(node) + if dist==k: + ans.append(node.data) + return + trav(node.parent,dist+1) + trav(node.left,dist+1) + trav(node.right,dist+1) + trav(root,0) + return ans +``` + +### Complexity Analysis + +- **Time Complexity:** $O(N)$ +- **Space Complexity:** $O(N)$ + diff --git a/solutions/gfg-solutions/easy/remove-duplicates.md b/solutions/gfg-solutions/easy/remove-duplicates.md new file mode 100644 index 0000000..47b534e --- /dev/null +++ b/solutions/gfg-solutions/easy/remove-duplicates.md @@ -0,0 +1,72 @@ +--- +id: remove-duplicates +title: Remove Duplicates +sidebar_label: 0107-Remoeve Duplicates +tags: + - Strings + - Data Structures +description: "A solution to the problem of finding the unique characters in the given string" +--- + +In this page, we will solve the problem of finding the unique characters in the given string. + +## Problem Description + +Given a string without spaces, the task is to remove duplicates from it. + +Note: The original order of characters must be kept the same. + +### Examples + +**Example 1:** + +```plaintext +Input: S = "zvvo" +Output: "zvo" +Explanation: Only keep the first +occurrence +``` + +**Example 2:** + +```plaintext +Input: S = "gfg" +Output: gf +Explanation: Only keep the first +occurrence +``` + +### Constraints + +- $1 \leq$ |S| $\leq10^5$ + +## Solution + +### Intuition and Approach + +This problem can be solved by using an empty string and traversing the given string and storing the unique element in the empty string and then return it. + +### Approach: + +1. The variable res is initialized to an empty string. This string will store the characters of S without duplicates. +2. We then Iterate through the input string: + - The for loop iterates through each character i in the string S. + - Inside the loop, there is an if statement that checks if the character i is not already in the result string ans. + If i is not in res, it means this character hasn't been added yet.and so we add unique characters in res variable +3. After the loop completes, the method returns the result string res, which now contains the characters of S without duplicates, in the order of their first appearance. +#### Code in Python +```python + +class Solution: + def removeDups(self, S): + res='' + for i in S: + if i not in res: + res+=i + return res + ``` + +#### Complexity Analysis + +- **Time Complexity:** $O(N^2)$ +- **Space Complexity:** $O(N)$ diff --git a/solutions/gfg-solutions/easy/reverse-a-doubly-linked-list.md b/solutions/gfg-solutions/easy/reverse-a-doubly-linked-list.md new file mode 100644 index 0000000..712014b --- /dev/null +++ b/solutions/gfg-solutions/easy/reverse-a-doubly-linked-list.md @@ -0,0 +1,78 @@ +--- +id: reverse-a-doubly-linked-list +title: Reverse a Doubly Linked List +sidebar_label: 0105-Reverse a Doubly Linked List + +tags: + - doubly-linked-list + - Linked List + - Data Structures +description: "A solution to the problem of reversing a doubly linked list " +--- + +In this page, we will solve the problem of reversing a doubly linked list. + +## Problem Description + +Given a doubly linked list of n elements. Your task is to reverse the doubly linked list in-place. + +### Examples + +**Example 1:** + +```plaintext +Input: +LinkedList: 3 <--> 4 <--> 5 +Output: 5 4 3 +``` + +**Example 2:** + +```plaintext +Input: +LinkedList: 75 <--> 122 <--> 59 <--> 196 +Output: 196 59 122 75 +``` + +### Constraints + +- $1 \leq$ number of nodes $\leq10^4$ +- $0 \leq$ value of nodes $\leq 10^4$ + +## Solution + +### Intuition and Approach + +This problem can be solved by iterating over the doubly linked list and interchanging the prev and the next pointer and then return the last node + + +### Approach: Inorder Traversal + +1. Base Case: we first checks if the head of the list is None, which means the list is empty and so we returns None. +2. Base Case: we then checks if the head.next is None, which means there is only one node in the list. If so, it returns the head itself, as reversing a single node doesn't change anything. +3. we next initializes two pointers: curr which is set to head, and prev which is set to None. curr will be used to traverse the list, and prev will eventually point to the new head of the reversed list. +4. Then we run a while loop until curr becomes None, meaning it has traversed the entire list. Inside the loop: + - prev is updated to curr, keeping track of the last processed node. + - then current node's next and prev pointers are swapped to reverse the direction of the list. + - curr is then moved to the original prev node, which is now curr.next after the swap. +5. Once the loop finishes, prev will be pointing to the new head of the reversed list and so we returned prev. +#### Code in Python +```python +class Solution: + def reverseDLL(self, head): + if head==None:return None + if head.next==None: + return head + curr=head + prev=None + while curr!=None: + prev=curr + curr.next,curr.prev=curr.prev,curr.next + curr=curr.prev + return prev +``` + +#### Complexity Analysis + +- **Time Complexity:** $O(N)$ +- **Space Complexity:** $O(1)$ diff --git a/solutions/gfg-solutions/easy/rightmost-different-bit.md b/solutions/gfg-solutions/easy/rightmost-different-bit.md new file mode 100644 index 0000000..128af76 --- /dev/null +++ b/solutions/gfg-solutions/easy/rightmost-different-bit.md @@ -0,0 +1,71 @@ +--- +id: rightmost-different-bit +title: Rightmost Different Bit +sidebar_label: 0106-Rightmost Different Bit +tags: + - Bit Magic + - Data Structures +description: "A solution to the problem of finding the rightmost position of the bit which is different in both numbers" +--- + +In this page, we will solve the problem of finding the rightmost position of the bit which is different in both numbers. + +## Problem Description + +Given two numbers M and N. The task is to find the position of the rightmost different bit in the binary representation of numbers. If both M and N are the same then return -1 in this case. + +### Examples + +**Example 1:** + +```plaintext +Input: +M = 11, N = 9 +Output: +2 +Explanation: +Binary representation of the given numbers are: 1011 and 1001, 2nd bit from right is different. +``` + +**Example 2:** + +```plaintext +Input: +M = 52, N = 4 +Output: +5 +Explanation: +Binary representation of the given numbers are: 110100 and 0100, 5th-bit from right is different. +``` + +### Constraints + +- $1 \leq$ M,N $\leq10^9$ + +## Solution + +### Intuition and Approach + +This problem can be solved by using bitwise operations + +### Approach: + +1. We will first XOR operation (^) between two integers, it will produce a result where each bit is set to 1 if the corresponding bits of m and n are different, and 0 if they are the same and then the result is stored in res variable +2. If res is 0, it means that m and n are identical and therefore we return -1 to indicate that there is no differing bit. +3. Now, To identify the position of the rightmost bit that is set to 1, the expression res & -res is used. This operation isolates the rightmost 1 bit in res. This works because -res is the two’s complement of res, which flips all bits of res and adds 1. +4. Then we use math.log2(res & -res) which computes the base-2 logarithm of the isolated rightmost 1 bit and gives the zero-based index of the rightmost differing bit. +5. Next we will add 1 converts this index to a one-based position and returned position. +#### Code in Python +```python + +class Solution: + def posOfRightMostDiffBit(self,m,n): + res = m^n + if res==0: return -1 + return math.log2(res & -res) + 1 + ``` + +#### Complexity Analysis + +- **Time Complexity:** $O(1)$ +- **Space Complexity:** $O(1)$ diff --git a/solutions/gfg-solutions/problems/BFS-traversal-of-graph.md b/solutions/gfg-solutions/problems/BFS-traversal-of-graph.md new file mode 100644 index 0000000..fdfdd1a --- /dev/null +++ b/solutions/gfg-solutions/problems/BFS-traversal-of-graph.md @@ -0,0 +1,144 @@ +--- +id: BFS-traversal-of-graph +title: BFS Traversal of Graph (Geeks for Geeks) +sidebar_label: BFS Traversal of Graph +tags: + - Intermediate + - Graph + - Breadth-First Search + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the BFS Traversal of Graph problem on Geeks for Geeks." +--- + +## Problem Description + +Given a graph, perform Breadth-First Search (BFS) traversal starting from a given source vertex. + +## Examples + +**Example:** + +Consider the following graph: + +``` + 1 + / \ + 2 3 + / \ + 4 5 +``` + +**Output:** 1 2 3 4 5 + +## Your Task + +Your task is to complete the function `bfs()`, which takes the graph, the number of vertices, and the source vertex as its arguments and prints the BFS traversal of the graph starting from the source vertex. + +Expected Time Complexity: $O(V + E)$, where V is the number of vertices and E is the number of edges in the graph. +Expected Auxiliary Space: $O(V)$. + +## Constraints + +- $1 <= number of vertices <= 10^3$ +- $0 <= value of vertices <= 10^3$ + +## Problem Explanation + +Here's the step-by-step breakdown of the BFS traversal process: + +1. **Initialize visited array**: Create a visited array to keep track of visited vertices. +2. **Initialize queue**: Create a queue to store vertices to be visited next. +3. **Perform BFS**: Start BFS traversal from the source vertex. +4. **Enqueue source**: Enqueue the source vertex into the queue and mark it as visited. +5. **Process vertices**: While the queue is not empty, dequeue a vertex, print it, and enqueue its unvisited adjacent vertices. + +### Code Implementation + + + + + ```python + from collections import deque + + def bfs(graph, v, source): + visited = [False] * v + queue = deque([source]) + visited[source] = True + + while queue: + u = queue.popleft() + print(u, end=" ") + + for neighbor in graph[u]: + if not visited[neighbor]: + visited[neighbor] = True + queue.append(neighbor) + + def bfsTraversal(graph, V, source): + bfs(graph, V, source) + ``` + + + + + ```cpp + #include + #include + #include + #include + using namespace std; + + void bfs(vector graph[], int v, int source) { + bool visited[v]; + memset(visited, false, sizeof(visited)); + queue q; + + q.push(source); + visited[source] = true; + + while (!q.empty()) { + int u = q.front(); + q.pop(); + cout << u << " "; + + for (int neighbor : graph[u]) { + if (!visited[neighbor]) { + visited[neighbor] = true; + q.push(neighbor); + } + } + } + } + + void bfsTraversal(vector graph[], int V, int source) { + bfs(graph, V, source); + } + ``` + + + +## Solution Logic + +1. **Initialize visited array and queue**: Create an array to mark visited vertices initially as False and a queue to store vertices to be visited. +2. **Perform BFS**: Start BFS traversal from the source vertex. +3. **Enqueue source**: Enqueue the source vertex into the queue and mark it as visited. +4. **Process vertices**: While the queue is not empty, dequeue a vertex, print it, and enqueue its unvisited adjacent vertices. + +## Time Complexity + +$O(V + E)$, where V is the number of vertices and E is the number of edges in the graph. Each vertex and edge are visited only once. + +## Space Complexity + +$O(V)$, where V is the number of vertices. The space is used to store the visited array and the queue. + +## Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/) +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) + +This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow. \ No newline at end of file diff --git a/solutions/gfg-solutions/problems/Check-for-balanced-tree.md b/solutions/gfg-solutions/problems/Check-for-balanced-tree.md new file mode 100644 index 0000000..fe0f3ac --- /dev/null +++ b/solutions/gfg-solutions/problems/Check-for-balanced-tree.md @@ -0,0 +1,146 @@ +--- +id: Check-for-balanced-tree +title: Check for Balanced Tree (Geeks for Geeks) +sidebar_label: Check for Balanced Tree +tags: + - Intermediate + - Tree + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Check for Balanced Tree problem on Geeks for Geeks." +--- + +## Problem Description + +Given a binary tree, determine if it is height-balanced. A binary tree is height-balanced if the left and right subtrees of every node differ in height by no more than 1. + +## Examples + +**Example 1:** +``` +Input: + 1 + / \ + 2 3 + / \ + 4 5 +Output: Yes +``` + +**Example 2:** +``` +Input: + 10 + / \ + 20 30 + / \ + 40 60 + \ + 70 +Output: No +``` + +## Your Task + +Your task is to complete the function `isBalanced()`, which takes the root of the binary tree as its argument and returns a boolean value indicating whether the tree is balanced or not. + +Expected Time Complexity: $O(N)$. +Expected Auxiliary Space: $O(h)$, where h is the height of the tree. + +## Constraints + +- $1 <= number of nodes <= 10^5$ +- $1 <= data of node <= 10^5$ + +## Problem Explanation + +Here's the step-by-step breakdown of the checking process: + +1. **Recursive depth calculation**: Create a helper function to calculate the depth of each subtree. +2. **Height difference check**: Check the difference in height between the left and right subtrees. +3. **Recursive balance check**: Recursively check if each subtree is balanced. +4. **Return result**: Return True if the tree is balanced, otherwise False. + +### Code Implementation + + + + + ```py + class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + def isBalanced(root): + def check(root): + if not root: + return 0, True + left_height, left_balanced = check(root.left) + right_height, right_balanced = check(root.right) + balanced = left_balanced and right_balanced and abs(left_height - right_height) <= 1 + return max(left_height, right_height) + 1, balanced + + return check(root)[1] + ``` + + + + + ```cpp + struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} + }; + + class Solution { + public: + bool isBalanced(TreeNode* root) { + return checkHeight(root) != -1; + } + + int checkHeight(TreeNode* root) { + if (root == NULL) return 0; + + int leftHeight = checkHeight(root->left); + if (leftHeight == -1) return -1; + + int rightHeight = checkHeight(root->right); + if (rightHeight == -1) return -1; + + if (abs(leftHeight - rightHeight) > 1) return -1; + + return max(leftHeight, rightHeight) + 1; + } + }; + ``` + + + +## Solution Logic + +1. **Recursive depth calculation**: A helper function calculates the height of the subtree rooted at each node. +2. **Height difference check**: For each node, the function checks if the height difference between the left and right subtrees is more than 1. +3. **Recursive balance check**: The function is recursively called on each subtree to ensure both are balanced. +4. **Return result**: The function returns True if all nodes are balanced, otherwise False. + +## Time Complexity + +$O(N)$, where N is the number of nodes in the tree. The function visits each node once. + +## Space Complexity + +$O(h)$, where h is the height of the tree. This is due to the recursive stack space used during the depth-first traversal. + +## Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/how-to-determine-if-a-binary-tree-is-balanced/) +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/balanced-binary-tree/) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) + +This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow. \ No newline at end of file diff --git a/solutions/gfg-solutions/problems/DFS-traversal-of-graph.md b/solutions/gfg-solutions/problems/DFS-traversal-of-graph.md new file mode 100644 index 0000000..6ae069d --- /dev/null +++ b/solutions/gfg-solutions/problems/DFS-traversal-of-graph.md @@ -0,0 +1,126 @@ +--- +id: DFS-traversal-of-graph +title: DFS Traversal of Graph (Geeks for Geeks) +sidebar_label: DFS Traversal of Graph +tags: + - Intermediate + - Graph + - Depth-First Search + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the DFS Traversal of Graph problem on Geeks for Geeks." +--- + +## Problem Description + +Given a graph, perform Depth-First Search (DFS) traversal starting from a given source vertex. + +## Examples + +**Example:** + +Consider the following graph: + +``` + 1 + / \ + 2 3 + / \ + 4 5 +``` + +**Output:** 1 2 4 5 3 + +## Your Task + +Your task is to complete the function `dfs()`, which takes the graph, the number of vertices, and the source vertex as its arguments and prints the DFS traversal of the graph starting from the source vertex. + +Expected Time Complexity: $O(V + E)$, where V is the number of vertices and E is the number of edges in the graph. +Expected Auxiliary Space: $O(V)$. + +## Constraints + +- $1 <= number of vertices <= 10^3$ +- $0 <= value of vertices <= 10^3$ + +## Problem Explanation + +Here's the step-by-step breakdown of the DFS traversal process: + +1. **Initialize visited array**: Create a visited array to keep track of visited vertices. +2. **Perform DFS**: Start DFS traversal from the source vertex. +3. **Mark visited**: Mark the current vertex as visited and print it. +4. **Visit neighbors**: Recursively visit all the adjacent vertices of the current vertex that are not visited yet. + +### Code Implementation + + + + + ```python + def dfs(graph, v, visited, source): + visited[source] = True + print(source, end=" ") + + for u in graph[source]: + if not visited[u]: + dfs(graph, v, visited, u) + + def dfsTraversal(graph, V, source): + visited = [False] * V + dfs(graph, V, visited, source) + ``` + + + + + ```cpp + #include + #include + #include + using namespace std; + + void dfs(vector graph[], int v, bool visited[], int source) { + visited[source] = true; + cout << source << " "; + + for (int u : graph[source]) { + if (!visited[u]) { + dfs(graph, v, visited, u); + } + } + } + + void dfsTraversal(vector graph[], int V, int source) { + bool visited[V]; + memset(visited, false, sizeof(visited)); + dfs(graph, V, visited, source); + } + ``` + + + +## Solution Logic + +1. **Initialize visited array**: Create an array to mark visited vertices initially as False. +2. **Perform DFS**: Start DFS traversal from the source vertex. +3. **Mark visited and print**: Mark the current vertex as visited and print it. +4. **Visit neighbors**: Recursively visit all the adjacent vertices of the current vertex that are not visited yet. + +## Time Complexity + +$O(V + E)$, where V is the number of vertices and E is the number of edges in the graph. Each vertex and edge are visited only once. + +## Space Complexity + +$O(V)$, where V is the number of vertices. The space is used to store the visited array. + +## Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/) +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) + +This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow. \ No newline at end of file diff --git a/solutions/gfg-solutions/problems/Delete-middle-of-linked-list.md b/solutions/gfg-solutions/problems/Delete-middle-of-linked-list.md new file mode 100644 index 0000000..53d4520 --- /dev/null +++ b/solutions/gfg-solutions/problems/Delete-middle-of-linked-list.md @@ -0,0 +1,139 @@ +--- +id: Delete-middle-of-linked-list +title: Delete Middle of Linked List (Geeks for Geeks) +sidebar_label: Delete Middle of Linked List +tags: + - Intermediate + - Linked List + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Delete Middle of Linked List problem on Geeks for Geeks." +--- + +## Problem Description + +Given a singly linked list, delete the middle node of the linked list. If the list has an even number of nodes, delete the second middle node. + +## Examples + +**Example 1:** +``` +Input: +LinkedList: 1 -> 2 -> 3 -> 4 -> 5 +Output: 1 -> 2 -> 4 -> 5 +``` + +**Example 2:** +``` +Input: +LinkedList: 1 -> 2 -> 3 -> 4 +Output: 1 -> 2 -> 4 +``` + +## Your Task + +Your task is to complete the function `deleteMid()`, which takes the head of the linked list as its argument and returns the head of the modified list after the middle node has been deleted. + +Expected Time Complexity: $O(N)$. +Expected Auxiliary Space: $O(1)$. + +## Constraints + +- $1 <= number of nodes <= 10^3$ +- $1 <= value of nodes <= 10^3$ + +## Problem Explanation + +Here's the step-by-step breakdown of the deletion process: + +1. **Find middle node**: Use two pointers (slow and fast) to find the middle node of the linked list. +2. **Update pointers**: Update the next pointer of the node just before the middle node to skip the middle node. +3. **Delete middle node**: Remove the middle node by updating pointers. + +### Code Implementation + + + + + ```py + class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + def deleteMid(head): + if not head or not head.next: + return None + + slow = head + fast = head + prev = None + + while fast and fast.next: + prev = slow + slow = slow.next + fast = fast.next.next + + if prev: + prev.next = slow.next + + return head + ``` + + + + + ```cpp + struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} + }; + + ListNode* deleteMid(ListNode* head) { + if (!head || !head->next) return NULL; + + ListNode* slow = head; + ListNode* fast = head; + ListNode* prev = NULL; + + while (fast && fast->next) { + prev = slow; + slow = slow->next; + fast = fast->next->next; + } + + if (prev) { + prev->next = slow->next; + } + + delete slow; + return head; + } + ``` + + + +## Solution Logic + +1. **Find middle node**: Initialize two pointers, slow and fast. Move the slow pointer one step at a time and the fast pointer two steps at a time. +2. **Update pointers**: When the fast pointer reaches the end, the slow pointer will be at the middle node. Keep track of the node just before the middle node using a previous pointer. +3. **Delete middle node**: Update the next pointer of the previous node to skip the middle node, effectively deleting it from the list. + +## Time Complexity + +$O(N)$, where N is the number of nodes in the list. The function traverses the list once to find the middle node. + +## Space Complexity + +$O(1)$, constant space complexity. The algorithm uses only a few additional pointers for traversal and modification, which does not depend on the input size. + +## Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/delete-middle-of-linked-list/) +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) + +This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow. \ No newline at end of file diff --git a/solutions/gfg-solutions/problems/Delete-without-head-pointer.md b/solutions/gfg-solutions/problems/Delete-without-head-pointer.md new file mode 100644 index 0000000..d805d9e --- /dev/null +++ b/solutions/gfg-solutions/problems/Delete-without-head-pointer.md @@ -0,0 +1,107 @@ +--- +id: Delete-without-head-pointer +title: Delete without Head Pointer (Geeks for Geeks) +sidebar_label: Delete without Head Pointer +tags: + - Beginner + - Linked List + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Delete without head pointer problem on Geeks for Geeks." +--- + +## Problem Description + +You are given a pointer/reference to a node to be deleted in a singly linked list. The task is to delete the node. Given you don't have access to the head of the linked list, you only have access to that node directly. + +Note: The solution should not be tail and it should be done in constant time. + +## Examples + +**Example 1:** +``` +Input: +LinkedList: 1 -> 2 -> 3 -> 4 +Node to be deleted: 3 +Output: 1 2 4 +``` + +**Example 2:** +``` +Input: +LinkedList: 10 -> 20 -> 4 -> 30 +Node to be deleted: 20 +Output: 10 4 30 +``` + +## Your Task + +Your task is to complete the function `deleteNode()`, which takes a reference to the node to be deleted and modifies the linked list directly. You should not return anything from the function. + +Expected Time Complexity: $O(1)$. +Expected Auxiliary Space: $O(1)$. + +## Constraints + +- $2 <= number of nodes <= 10^3$ +- $1 <= value of nodes <= 10^3$ + +## Problem Explanation + +Here's the step-by-step breakdown of the deletion process: + +1. **Copy data**: Copy the data from the next node to the current node to be deleted. +2. **Skip next node**: Change the next pointer of the current node to point to the next of the next node. +3. **Effectively delete**: The next node is effectively deleted as its data is copied to the current node and it is skipped in the list. + +### Code Implementation + + + + + ```py + def deleteNode(node): + if node.next: + node.data = node.next.data + node.next = node.next.next + ``` + + + + + ```cpp + void deleteNode(Node *node) { + if (node->next) { + Node* temp = node->next; + node->data = temp->data; + node->next = temp->next; + delete temp; + } + } + ``` + + + +## Solution Logic + +1. **Copy data from next node**: The data of the node to be deleted is replaced with the data of the next node. +2. **Skip the next node**: The next pointer of the current node is updated to point to the node after the next node. +3. **Delete next node**: The next node is effectively removed from the list. + +## Time Complexity + +$O(1)$, since the node is deleted in constant time by copying the data and updating pointers. + +## Space Complexity + +$O(1)$, constant space complexity, as no extra space is used beyond a few pointers. + +## Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/delete-without-head-pointer/) +- **HackerRank Problem:** [HackerRank](https://www.hackerrank.com/challenges/delete-a-node-from-a-linked-list/problem) +- **Author's LeetCode Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) + +This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow. \ No newline at end of file diff --git a/solutions/gfg-solutions/problems/Implement-two-stacks-in-an-array.md b/solutions/gfg-solutions/problems/Implement-two-stacks-in-an-array.md new file mode 100644 index 0000000..2e60394 --- /dev/null +++ b/solutions/gfg-solutions/problems/Implement-two-stacks-in-an-array.md @@ -0,0 +1,202 @@ +--- +id: Implement-two-stacks-in-an-array +title: Implement Two Stacks in an Array (Geeks for Geeks) +sidebar_label: Implement Two Stacks in an Array +tags: + - Intermediate + - Stack + - Array + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Implement Two Stacks in an Array problem on Geeks for Geeks." +--- + +## Problem Description + +You are given a single array of size `N`. You need to implement two stacks in this array efficiently. + +## Examples + +**Example 1:** +``` +Input: +push1(2) +push1(3) +push2(4) +pop1() +pop2() +Output: +3 4 +``` + +**Example 2:** +``` +Input: +push1(1) +push2(2) +push1(3) +pop1() +pop2() +Output: +3 2 +``` + +## Your Task + +Your task is to complete the class `TwoStacks` which should contain the following functions: +- `void push1(int x)`: Pushes `x` into the first stack. +- `void push2(int x)`: Pushes `x` into the second stack. +- `int pop1()`: Pops the top element from the first stack and returns it. Returns `-1` if the first stack is empty. +- `int pop2()`: Pops the top element from the second stack and returns it. Returns `-1` if the second stack is empty. + +Expected Time Complexity: $O(1)$ for all the operations. +Expected Auxiliary Space: $O(1)$ for all the operations. + +## Constraints + +- $1 <= N <= 100$ +- $1 <= x <= 100$ + +## Problem Explanation + +Here's the step-by-step breakdown of implementing two stacks in a single array: + +1. **Initialize pointers**: Use two pointers, one for each stack. +2. **Push operations**: Ensure elements are pushed to the respective stack areas. +3. **Pop operations**: Ensure elements are popped from the respective stack areas. +4. **Check overflow and underflow**: Ensure proper checks for stack overflow and underflow. + +### Code Implementation + + + + + ```python + class TwoStacks: + def __init__(self, n): # Initialize n as the size of array + self.size = n + self.arr = [None] * n + self.top1 = -1 + self.top2 = n + + def push1(self, x): + if self.top1 < self.top2 - 1: + self.top1 += 1 + self.arr[self.top1] = x + else: + print("Stack Overflow") + + def push2(self, x): + if self.top1 < self.top2 - 1: + self.top2 -= 1 + self.arr[self.top2] = x + else: + print("Stack Overflow") + + def pop1(self): + if self.top1 >= 0: + x = self.arr[self.top1] + self.top1 -= 1 + return x + else: + return -1 + + def pop2(self): + if self.top2 < self.size: + x = self.arr[self.top2] + self.top2 += 1 + return x + else: + return -1 + ``` + + + + + ```cpp + #include + using namespace std; + + class TwoStacks { + private: + int* arr; + int size; + int top1, top2; + + public: + TwoStacks(int n) { + size = n; + arr = new int[n]; + top1 = -1; + top2 = n; + } + + void push1(int x) { + if (top1 < top2 - 1) { + top1++; + arr[top1] = x; + } else { + cout << "Stack Overflow"; + } + } + + void push2(int x) { + if (top1 < top2 - 1) { + top2--; + arr[top2] = x; + } else { + cout << "Stack Overflow"; + } + } + + int pop1() { + if (top1 >= 0) { + int x = arr[top1]; + top1--; + return x; + } else { + return -1; + } + } + + int pop2() { + if (top2 < size) { + int x = arr[top2]; + top2++; + return x; + } else { + return -1; + } + } + }; + ``` + + + +## Solution Logic + +1. **Initialize pointers**: Use `top1` initialized to `-1` for Stack 1 and `top2` initialized to `size` for Stack 2. +2. **Push operations**: Check for space before pushing: + - For Stack 1, increment `top1` and insert the element. + - For Stack 2, decrement `top2` and insert the element. +3. **Pop operations**: Check if the stack is empty before popping: + - For Stack 1, return the element at `top1` and decrement `top1`. + - For Stack 2, return the element at `top2` and increment `top2`. +4. **Check overflow and underflow**: Ensure there is no overflow by checking if `top1` is less than `top2 - 1` before pushing. Ensure no underflow by checking the pointers before popping. + +## Time Complexity + +$O(1)$ for all the operations, as the operations of push and pop involve a fixed number of steps. + +## Space Complexity + +$O(1)$ auxiliary space, as the additional space used does not depend on the input size and is constant. + +## Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/implement-two-stacks-in-an-array/) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) + +This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow. \ No newline at end of file diff --git a/solutions/gfg-solutions/problems/Intersection-of-two-sorted-linked-lists.md b/solutions/gfg-solutions/problems/Intersection-of-two-sorted-linked-lists.md new file mode 100644 index 0000000..fae9e4e --- /dev/null +++ b/solutions/gfg-solutions/problems/Intersection-of-two-sorted-linked-lists.md @@ -0,0 +1,141 @@ +--- +id: Intersection-of-two-sorted-linked-lists +title: Intersection of Two Sorted Linked Lists (Geeks for Geeks) +sidebar_label: Intersection of Two Sorted Linked Lists +tags: + - Intermediate + - Linked List + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Intersection of Two Sorted Linked Lists problem on Geeks for Geeks." +--- + +## Problem Description + +Given two linked lists sorted in increasing order, create a new linked list representing the intersection of the two linked lists. The new linked list should be made with its own memory and be sorted in increasing order. + +## Examples + +**Example 1:** +``` +Input: +List1: 1 -> 2 -> 3 -> 4 -> 6 +List2: 2 -> 4 -> 6 -> 8 +Output: 2 -> 4 -> 6 +``` + +**Example 2:** +``` +Input: +List1: 1 -> 2 -> 3 -> 4 +List2: 6 -> 7 -> 8 -> 9 +Output: Empty List +``` + +## Your Task + +Your task is to complete the function `findIntersection()`, which takes the heads of both linked lists as arguments and returns the head of the new linked list representing their intersection. + +Expected Time Complexity: $O(N + M)$, where N and M are the lengths of the two linked lists. +Expected Auxiliary Space: $O(1)$. + +## Constraints + +- $1 <= number of nodes <= 10^5$ +- $1 <= value of nodes <= 10^5$ + +## Problem Explanation + +Here's the step-by-step breakdown of finding the intersection: + +1. **Initialize pointers**: Start with two pointers, each pointing to the head of one linked list. +2. **Traverse both lists**: Move through both linked lists simultaneously. +3. **Compare nodes**: At each step, compare the current nodes of both lists. +4. **Add common nodes**: If the nodes are the same, add it to the result list. +5. **Advance pointers**: Move the pointer(s) accordingly based on the comparison. + +### Code Implementation + + + + + ```py + class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + def findIntersection(head1, head2): + dummy = ListNode(0) + tail = dummy + while head1 and head2: + if head1.val == head2.val: + tail.next = ListNode(head1.val) + tail = tail.next + head1 = head1.next + head2 = head2.next + elif head1.val < head2.val: + head1 = head1.next + else: + head2 = head2.next + return dummy.next + ``` + + + + + ```cpp + struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} + }; + + ListNode* findIntersection(ListNode* head1, ListNode* head2) { + ListNode dummy(0); + ListNode* tail = &dummy; + + while (head1 && head2) { + if (head1->val == head2->val) { + tail->next = new ListNode(head1->val); + tail = tail->next; + head1 = head1->next; + head2 = head2->next; + } else if (head1->val < head2->val) { + head1 = head1->next; + } else { + head2 = head2->next; + } + } + return dummy.next; + } + ``` + + + +## Solution Logic + +1. **Initialize pointers**: Start with two pointers, each pointing to the head of one linked list. +2. **Traverse both lists**: Use a while loop to move through both linked lists simultaneously. +3. **Compare nodes**: At each step, compare the current nodes of both lists. +4. **Add common nodes**: If the nodes are the same, add the node value to the new linked list. +5. **Advance pointers**: Move the pointer(s) accordingly based on the comparison of node values. +6. **Return result**: Return the head of the new linked list representing the intersection. + +## Time Complexity + +$O(N + M)$, where N and M are the lengths of the two linked lists. The function visits each node in both linked lists once. + +## Space Complexity + +$O(1)$, constant space complexity. The algorithm uses only a few additional pointers for traversal and modification, which does not depend on the input size. + +## Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/intersection-of-two-sorted-linked-lists/) +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/intersection-of-two-linked-lists/) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) + +This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow. \ No newline at end of file diff --git a/solutions/gfg-solutions/problems/Reverse-a-doubly-linked-list.md b/solutions/gfg-solutions/problems/Reverse-a-doubly-linked-list.md new file mode 100644 index 0000000..6cd76c0 --- /dev/null +++ b/solutions/gfg-solutions/problems/Reverse-a-doubly-linked-list.md @@ -0,0 +1,129 @@ +--- +id: Reverse-a-doubly-linked-list +title: Reverse a Doubly Linked List (Geeks for Geeks) +sidebar_label: Reverse a Doubly LinkedList +tags: + - Beginner + - Doubly Linked List + - Array + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Reverse a Doubly linked list problem on Geeks for Geeks." +--- + +## Problem Description + +Reverse a given doubly linked list in-place. This means modifying the existing list's pointers (prev and next) to achieve the reversed order without creating a new list. + +## Examples +**Example 1:** +``` +Input: +LinkedList: 3 <--> 4 <--> 5 +Output: 5 4 3 +``` +**Example 2:** +``` +Input: +LinkedList: 75 <--> 122 <--> 59 <--> 196 +Output: 196 59 122 75 +``` + +## Your Task + +Your task is to complete the given function reverseDLL(), which takes head reference as argument and this function should reverse the elements such that the tail becomes the new head and all pointers are pointing in the right order. You need to return the new head of the reversed list. The printing and verification is done by the driver code. + +Expected Time Complexity: $O(n)$. +Expected Auxiliary Space: $O(1)$. + +## Constraints + +- $1 <= number of nodes <= 10^4$ +- $0 <= value of nodes <= 10^4$ + +## Problem Explanation + +Here's the step-by-step breakdown of the reversal process: + +Initialization: + +Create two pointers: current (initially pointing to the head) and prev (initially None). +Iteration: + +While current is not None: +Store the next pointer of the current node in a temporary variable next_node. +Reverse the pointers of the current node: +Set the current.next pointer to prev. +Set the current.prev pointer to next_node. +Update the prev pointer to the current node (prev = current). +Move the current pointer to the previously stored next_node (current = next_node). +Update Head: + +After the loop, the prev pointer will be pointing to the new head of the reversed list. Return prev. +This process effectively reverses the direction of the linked list by swapping the next and prev pointers of each node. + +6. Code Implementation + + + + + ```py +def reverse_doubly_linked_list(head): + current = head + prev = None + while current: + next_node = current.next + current.next = prev + current.prev = next_node + prev = current + current = next_node + return prev +``` + + + + + ```cpp + + Node* reverse_doubly_linked_list(Node* head) { + + Node* current = head; + Node* prev = nullptr; + while (current) { + Node* next_node = current->next; + current->next = prev; + current->prev = next_node; + prev = current; + current = next_node; + } + return prev; + } + ``` + + + +## Solution Logic + +1. The code iterates through the list using current. +2. For each node, it stores the next pointer for later use and then: +3. Reverses the next and prev pointers of the current node. +4. Updates prev to point to the current node, preparing for the next iteration. +5. Moves current to the previously stored next_node. +6. After the loop, prev points to the new head of the reversed list. + + +## Time Complexity + +$O(n)$, where n is the number of nodes in the list. This is because the loop iterates through each node once. + +## Space Complexity + +$O(1)$, constant space complexity. The algorithm uses only a few additional pointers for temporary storage, which does not depend on the input size. + +## Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/problems/reverse-a-doubly-linked-list/1) +- **HackerRank Problem:**[HackerRank](https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem) +- **Authors LeetCode Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) \ No newline at end of file diff --git a/solutions/gfg-solutions/problems/Reverse-a-linked-list.md b/solutions/gfg-solutions/problems/Reverse-a-linked-list.md new file mode 100644 index 0000000..1fbb4f2 --- /dev/null +++ b/solutions/gfg-solutions/problems/Reverse-a-linked-list.md @@ -0,0 +1,141 @@ +--- +id: Reverse-a-linked-list +title: Reverse a Linked List (Geeks for Geeks) +sidebar_label: Reverse a LinkedList +tags: + - Beginner + - Linked List + - Array + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Reverse a linked list problem on Geeks for Geeks." +--- + +## Problem Description + +Given a linked list of N nodes. The task is to reverse this list. +You are given the head of a singly linked list. Write a function to reverse the linked list and return the new head. + +## Examples + +**Example 1:** +``` +Input: +LinkedList: 1->2->3->4->5->6 +Output: 6 5 4 3 2 1 +Explanation: After reversing the list, +elements are 6->5->4->3->2->1. +``` + +**Example 2:** +``` +Input: +LinkedList: 2->7->8->9->10 +Output: 10 9 8 7 2 +Explanation: After reversing the list, +elements are 10->9->8->7->2. +``` + +## Your Task + +The task is to complete the function reverseList() with head reference as the only argument and should return new head after reversing the list. + +Expected Time Complexity: $O(N)$. +Expected Auxiliary Space: $O(1)$. + +## Constraints + +- $1 <= N <= 10^4$ + +## Problem Explanation + +1. Initialize pointers: Set prev to None, temp to the head of the linked list, and front to None. +2. Traverse the list: Iterate through the linked list until temp is None. +3. Store the next node: Assign temp.next to front to keep track of the next node. +4. Reverse the pointer: Set temp.next to prev to reverse the link. +5. Move prev forward: Update prev to temp. +6. Move temp forward: Update temp to front. +7. Repeat steps 3-6: Continue until the entire list is reversed. +8. Update head: Once the loop ends, prev will be the new head of the reversed list. +9. Return the new head: Return prev as the head of the reversed linked list. + +## Code Implementation + + + + + ```py + + def reverseList(head): + prev = None + curr = head + + while curr: + next = curr.next + curr.next = prev + prev = curr + curr = next + + return prev + ``` + + + + + + ```cpp + class Solution +{ + public: + struct Node* reverseList(struct Node *head) + { + if(head == NULL || head->next== NULL) return head; + Node* prev = NULL; + Node* temp = head; + while(temp != NULL){ + Node* front = temp->next; + temp->next = prev; + prev = temp; + temp = front; + } + return prev; + } + +}; +``` + + + + +## Solution Logic: + +1. Initialize pointers: Create three pointers: prev (previous), curr (current), and next (next node). +Set prev to None and curr to the head of the linked list. + +2. Iterate through the list: Start a loop that continues as long as curr is not None. + +3. Store the next node: Inside the loop, before modifying the next pointer of the current node, store the node pointed to by curr.next in a temporary variable next. This is crucial to avoid losing track of the next node in the original order. + +4. Reverse the link: Update the next pointer of the current node (curr) to point to the previous node (prev). This effectively reverses the direction of the link. + +5. Update pointers and iterate: Set prev to the current node (prev = curr). +Set curr to the previously stored next node (curr = next). +By repeating these steps, you traverse the linked list, reverse the links in place, and end up with the list reversed. + +## Time Complexity: + +1. Reversing a linked list involves iterating through the list to manipulate the pointers between nodes. In the worst case, you need to visit every single node in the list to reverse the connections. + +2. Any efficient reversal algorithm will require at least one pass through the entire list. This takes $O(n)$ time. + +## Space Complexity: + +The space complexity is typically denoted as $O(1)$, which signifies constant space. This means the extra memory usage doesn't depend on the input size. + +## References + +- **LeetCode Problem:** [Geeks for Geeks Problem](https://www.geeksforgeeks.org/problems/reverse-a-linked-list/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=bottom_sticky_on_article) +- **Solution Link:** [Fascinating Number on Geeks for Geeks](https://www.geeksforgeeks.org/reverse-a-linked-list/) +- **Authors LeetCode Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) diff --git a/solutions/gfg-solutions/problems/Square-root.md b/solutions/gfg-solutions/problems/Square-root.md new file mode 100644 index 0000000..325309d --- /dev/null +++ b/solutions/gfg-solutions/problems/Square-root.md @@ -0,0 +1,137 @@ +--- +id: Find-the-square-root +title: Find the Square Root (Geeks for Geeks) +sidebar_label: Find the Square Root +tags: + - Beginner + - Math + - Binary Search + - Geeks for Geeks + - CPP + - Python + - DSA +description: "This is a solution to the Find the Square Root problem on Geeks for Geeks." +--- + +## Problem Description + +Given an integer x, find the square root of x. If x is not a perfect square, then return the floor value of √x. + +## Examples + +**Example 1:** +``` +Input: x = 4 +Output: 2 +``` + +**Example 2:** +``` +Input: x = 8 +Output: 2 +Explanation: The square root of 8 is 2.82842..., and since we want the floor value, it is 2. +``` + +## Your Task + +Your task is to complete the function `sqrt()`, which takes an integer x as an argument and returns the floor value of its square root. + +Expected Time Complexity: $O(log x)$. +Expected Auxiliary Space: $O(1)$. + +## Constraints + +- $0 <= x <= 10^9$ + +## Problem Explanation + +Here's the step-by-step breakdown of finding the square root: + +1. **Initialize low and high**: Initialize two variables, low and high, to 0 and x, respectively. +2. **Binary Search**: Perform binary search within the range [0, x]. +3. **Calculate mid**: Calculate the mid-point of the range. +4. **Check square**: If mid*mid is equal to x, return mid. If mid*mid is less than x, move to the right half. Otherwise, move to the left half. +5. **Return floor value**: Continue until the range is exhausted. The low value will give the floor of the square root. + +### Code Implementation + + + + + ```python + def sqrt(x): + if x == 0 or x == 1: + return x + + low, high = 0, x + while low <= high: + mid = (low + high) // 2 + + # If mid is the perfect square root + if mid * mid == x: + return mid + + # Since we need floor, we update answer when mid*mid is less than x + if mid * mid < x: + low = mid + 1 + ans = mid + else: + high = mid - 1 + return ans + ``` + + + + + ```cpp + #include + using namespace std; + + int sqrt(int x) { + if (x == 0 || x == 1) return x; + + int low = 0, high = x, ans = 0; + while (low <= high) { + int mid = low + (high - low) / 2; + + // If mid is the perfect square root + if (mid*mid == x) + return mid; + + // Since we need floor, we update answer when mid*mid is less than x + if (mid*mid < x) { + low = mid + 1; + ans = mid; + } else { + high = mid - 1; + } + } + return ans; + } + ``` + + + +## Solution Logic + +1. **Initialize low and high**: Set low to 0 and high to x. +2. **Binary Search**: Use a binary search approach to find the square root. +3. **Calculate mid**: Compute the mid-point of the current range. +4. **Check square**: If mid squared equals x, return mid. If mid squared is less than x, search the right half. Otherwise, search the left half. +5. **Return floor value**: Continue the search until low exceeds high. Return the latest computed mid that satisfies the condition as the floor of the square root. + +## Time Complexity + +$O(log x)$, where x is the input number. The binary search approach reduces the search space logarithmically. + +## Space Complexity + +$O(1)$, constant space complexity. The algorithm uses a fixed amount of extra space regardless of the input size. + +## Resources + +- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/square-root-of-an-integer/) +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/sqrtx/) +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) + +This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow. \ No newline at end of file diff --git a/solutions/gfg-solutions/problems/_category_.json b/solutions/gfg-solutions/problems/_category_.json new file mode 100644 index 0000000..59f1d11 --- /dev/null +++ b/solutions/gfg-solutions/problems/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Easy problems GFG", + "position": 10, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problems in Easy problem folder" + } + } \ No newline at end of file diff --git a/solutions/index.md b/solutions/index.md new file mode 100644 index 0000000..5967e29 --- /dev/null +++ b/solutions/index.md @@ -0,0 +1,50 @@ +--- +title: Data Structures and Algorithms Solutions +sidebar_label: DSA Solutions +sidebar_position: 1 +--- + +In this section, you will learn about the solutions of the problems of Data Structures and Algorithms. + +## Data Structures + +- [Array](#): Array is a collection of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. +- [String](#): A string is a sequence of characters. +- [Linked List](#): A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. +- [Stack](#): A stack is a linear data structure that follows the Last In First Out (LIFO) principle. +- [Queue](#): A queue is a linear data structure that follows the First In First Out (FIFO) principle. +- [Tree](#): A tree is a non-linear data structure that is used to store data in a hierarchical manner. +- [Graph](#): A graph is a non-linear data structure that consists of a finite set of vertices and edges. +- [Hashing](#): Hashing is a technique that is used to uniquely identify a specific object from a group of similar objects. +- [Heap](#): A heap is a complete binary tree that satisfies the heap property. +- [Trie](#): A trie is a tree-like data structure that is used to store a dynamic set of strings. + +## Algorithms + +- [Searching](#): Searching is the process of finding a specific element in a collection of elements. +- [Sorting](#): Sorting is the process of arranging the elements of a collection in a specific order. +- [Recursion](#): Recursion is a technique in which a function calls itself to solve a smaller instance of the same problem. +- [Dynamic Programming](#): Dynamic Programming is a technique used to solve problems by breaking them down into smaller subproblems. +- [Greedy Algorithms](#): Greedy Algorithms are algorithms that make a series of choices that are locally optimal at each step. +- [Backtracking](#): Backtracking is a technique used to solve problems by making a series of choices and backtracking when a choice leads to a dead end. +- [Divide and Conquer](#): Divide and Conquer is a technique used to solve problems by breaking them down into smaller subproblems, solving the subproblems, and combining the solutions to solve the original problem. +- [Bit Manipulation](#): Bit Manipulation is the act of algorithmically manipulating bits or binary digits. +- [Graph Algorithms](#): Graph Algorithms are algorithms that operate on graphs to solve problems. +- [Mathematical Algorithms](#): Mathematical Algorithms are algorithms that solve mathematical problems. +- [String Algorithms](../dsa/category/string-algorithms): String Algorithms are algorithms that operate on strings to solve problems. + +## Problems + +- [LeetCode](#): LeetCode is a platform that provides a collection of coding problems to practice and improve your coding skills. +- [HackerRank](#): HackerRank is a platform that provides a collection of coding problems to practice and improve your coding skills. +- [Codeforces](#): Codeforces is a platform that provides a collection of coding problems to practice and improve your coding skills. +- [CodeChef](#): CodeChef is a platform that provides a collection of coding problems to practice and improve your coding skills. +- [AtCoder](#): AtCoder is a platform that provides a collection of coding problems to practice and improve your coding skills. +- [TopCoder](#): TopCoder is a platform that provides a collection of coding problems to practice and improve your coding skills. +- [InterviewBit](#): InterviewBit is a platform that provides a collection of coding problems to practice and improve your coding skills. +- [GeeksforGeeks](#): GeeksforGeeks is a platform that provides a collection of coding problems to practice and improve your coding skills. +- [Project Euler](#): Project Euler is a platform that provides a collection of mathematical problems to practice and improve your mathematical skills. + +## Resources + +- [Books](#): Books are a great way to learn about Data Structures and Algorithms. \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0001-two-sum.md b/solutions/lc-solutions/0000-0099/0001-two-sum.md new file mode 100644 index 0000000..687dbe2 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0001-two-sum.md @@ -0,0 +1,643 @@ +--- +id: two-sum +title: Two Sum Solution +sidebar_label: 0001 - Two Sum +tags: + - Two Sum + - Hash Table + - Two Pointer + - Array + - JavaScript + - TypeScript +description: "This is a solution to the Two Sum problem on LeetCode." +sidebar_position: 1 +--- + +In this tutorial, we will solve the Two Sum problem using three different approaches :brute force, hash table, and two-pointer technique. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`. + +You may assume that each input would have exactly one solution, and you may not use the same element twice. + +You can return the answer in any order. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [2,7,11,15], target = 9 +Output: [0,1] +``` + +**Example 2:** + +```plaintext +Input: nums = [3,2,4], target = 6 +Output: [1,2] +``` + +**Example 3:** + +```plaintext +Input: nums = [3,3], target = 6 +Output: [0,1] +``` + +### Constraints + +- $2 \leq \text{nums.length} \leq 10^4$ +- $-10^9 \leq \text{nums[i]} \leq 10^9$ +- $-10^9 \leq \text{target} \leq 10^9$ +- Only one valid answer exists. + +**Follow up:** Can you come up with an algorithm that is less than $O(n^2)$ time complexity? + +--- + +## Solution for Two Sum Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach, a hash table, or the two-pointer technique. The brute force approach has a time complexity of $O(n^2)$, while the hash table and two-pointer techniques have a time complexity of $O(n)$. The hash table approach is the most efficient and is recommended for large inputs. + + + + +### Approach 1: Brute Force (Naive) + +The brute force approach is simple. We iterate through each element `nums[i]` and check if there is another element `nums[j]` such that `nums[i] + nums[j] == target`. If we find such a pair, we return the indices `[i, j]`. + +#### Implementation + +```jsx live +function twoSumProblem() { + const nums = [2, 7, 11, 15]; + const target = 9; + const twoSum = function (nums, target) { + for (let i = 0; i < nums.length; i++) { + for (let j = i + 1; j < nums.length; j++) { + if (nums[i] + nums[j] === target) { + return [i, j]; + } + } + } + + return []; + }; + + const result = twoSum(nums, target); + return ( +
+

+ Input: nums = {"[" + nums.join(", ") + "]"}, target = {target} +

+

+ Output: {"[" + result.join(", ") + "]"} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function twoSum(nums, target) { + for (let i = 0; i < nums.length; i++) { + for (let j = i + 1; j < nums.length; j++) { + if (nums[i] + nums[j] === target) { + return [i, j]; + } + } + } + + return []; + } + ``` + + + + + ```typescript + function twoSum(nums: number[], target: number): number[] { + for (let i = 0; i < nums.length; i++) { + for (let j = i + 1; j < nums.length; j++) { + if (nums[i] + nums[j] === target) { + return [i, j]; + } + } + } + + return []; + } + ``` + + + + + ```python + class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + for i in range(len(nums)): + for j in range(i + 1, len(nums)): + if nums[i] + nums[j] == target: + return [i, j] + + return [] + ``` + + + + + ```java + class Solution { + public int[] twoSum(int[] nums, int target) { + for (int i = 0; i < nums.length; i++) { + for (int j = i + 1; j < nums.length; j++) { + if (nums[i] + nums[j] == target) { + return new int[] {i, j}; + } + } + } + + return new int[0]; + } + } + ``` + + + + + ```cpp + class Solution { + public: + vector twoSum(vector& nums, int target) { + for (int i = 0; i < nums.size(); i++) { + for (int j = i + 1; j < nums.size(); j++) { + if (nums[i] + nums[j] == target) { + return {i, j}; + } + } + } + + return {}; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n^2)$$ +- Space Complexity: $$O(1)$$ +- Where `n` is the length of the input array `nums`. +- The time complexity is $$O(n^2)$$ because we are iterating through the array twice. +- The space complexity is $$O(1)$$ because we are not using any extra space. +- This approach is not efficient and is not recommended for large inputs. + +
+ + +### Approach 2: Using Hash Table + +We can solve this problem more efficiently using a hash table. We iterate through the array and store the elements and their indices in a hash table. For each element `nums[i]`, we calculate the complement `target - nums[i]` and check if the complement is present in the hash table. If it is present, we return the indices `[i, numMap.get(complement)]`. If the complement is not present, we add the element `nums[i]` to the hash table. If no pair is found, we return an empty array. + +#### Implementation + +```jsx live +function twoSumProblem() { + const nums = [2, 7, 11, 15]; + const target = 9; + + const twoSum = function (nums, target) { + const numMap = new Map(); + + for (let i = 0; i < nums.length; i++) { + const complement = target - nums[i]; + if (numMap.has(complement)) { + return [numMap.get(complement), i]; + } + numMap.set(nums[i], i); + } + + return []; + }; + + const result = twoSum(nums, target); + return ( +
+

+ Input: nums = {"[" + nums.join(", ") + "]"}, target = {target} +

+

+ Output: {"[" + result.join(", ") + "]"} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function twoSum(nums, target) { + const numMap = new Map(); + + for (let i = 0; i < nums.length; i++) { + const complement = target - nums[i]; + if (numMap.has(complement)) { + return [numMap.get(complement), i]; + } + numMap.set(nums[i], i); + } + + return []; + } + ``` + + + + + ```typescript + function twoSum(nums: number[], target: number): number[] { + const numMap = new Map(); + + for (let i = 0; i < nums.length; i++) { + const complement = target - nums[i]; + if (numMap.has(complement)) { + return [numMap.get(complement)!, i]; + } + numMap.set(nums[i], i); + } + + return []; + } + ``` + + + + + ```python + class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + num_map = {} + for i, num in enumerate(nums): + complement = target - num + if complement in num_map: + return [num_map[complement], i] + num_map[num] = i + + return [] + ``` + + + + + ```java + class Solution { + public int[] twoSum(int[] nums, int target) { + Map numMap = new HashMap<>(); + + for (int i = 0; i < nums.length; i++) { + int complement = target - nums[i]; + if (numMap.containsKey(complement)) { + return new int[] {numMap.get(complement), i}; + } + numMap.put(nums[i], i); + } + + return new int[0]; + } + } + ``` + + + + + ```cpp + class Solution { + public: + vector twoSum(vector& nums, int target) { + unordered_map numMap; + + for (int i = 0; i < nums.size(); i++) { + int complement = target - nums[i]; + if (numMap.find(complement) != numMap.end()) { + return {numMap[complement], i}; + } + numMap[nums[i]] = i; + } + + return {}; + } + }; + ``` + + + + +#### Complexity Analysis + +- **Time Complexity:** $O(n)$ +- **Space Complexity:** $O(n)$ +- Where `n` is the length of the input array `nums`. +- The time complexity is $O(n)$ because we iterate through the array only once. +- The space complexity is $O(n)$ because we use a hash table to store the elements and their indices. +- This approach is more efficient than the brute force approach and is recommended for large inputs. +- The hash table lookup has an average time complexity of $O(1)$, which makes this approach efficient. +- The space complexity is $O(n)$ because we store at most `n` elements in the hash table. +- The total time complexity is $O(n)$. and the total space complexity is $O(n)$. + +
+ + +### Approach 3: Using Two Pointers + +We can also solve this problem using the two-pointer technique. We first sort the array and then use two pointers, `left` and `right`, to find the two numbers that add up to the target sum. We initialize `left` to `0` and `right` to `nums.length - 1`. We calculate the sum of the two numbers at the `left` and `right` pointers. If the sum is equal to the target, we return the indices `[left, right]`. If the sum is less than the target, we increment the `left` pointer. If the sum is greater than the target, we decrement the `right` pointer. If no pair is found, we return an empty array. + +#### Implementation + +```jsx live +function twoSumProblem() { + const nums = [2, 7, 11, 15]; + const target = 9; + + const twoSum = function (nums, target) { + const sortedNums = nums.map((num, index) => [num, index]); + sortedNums.sort((a, b) => a[0] - b[0]); + + let left = 0; + let right = sortedNums.length - 1; + + while (left < right) { + const sum = sortedNums[left][0] + sortedNums[right][0]; + if (sum === target) { + return [sortedNums[left][1], sortedNums[right][1]]; + } else if (sum < target) { + left++; + } else { + right--; + } + } + + return []; + }; + + const result = twoSum(nums, target); + return ( +
+

+ Input: nums = {"[" + nums.join(", ") + "]"}, target = {target} +

+

+ Output: {"[" + result.join(", ") + "]"} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function twoSum(nums, target) { + const sortedNums = nums.map((num, index) => [num, index]); + sortedNums.sort((a, b) => a[0] - b[0]); + + let left = 0; + let right = sortedNums.length - 1; + + while (left < right) { + const sum = sortedNums[left][0] + sortedNums[right][0]; + if (sum === target) { + return [sortedNums[left][1], sortedNums[right][1]]; + } else if (sum < target) { + left++; + } else { + right--; + } + } + + return []; + } + ``` + + + + + +```ts +function twoSum(nums: number[], target: number): number[] { + const sortedNums = nums.map((num, index) => [num, index]); + sortedNums.sort((a, b) => a[0] - b[0]); + + let left = 0; + let right = sortedNums.length - 1; + + while (left < right) { + const sum = sortedNums[left][0] + sortedNums[right][0]; + if (sum === target) { + return [sortedNums[left][1], sortedNums[right][1]]; + } else if (sum < target) { + left++; + } else { + right--; + } + } + + return []; +} +``` + + + + +```py + class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + sorted_nums = sorted(enumerate(nums), key=lambda x: x[1]) + + left, right = 0, len(sorted_nums) - 1 + + while left < right: + sum = sorted_nums[left][1] + sorted_nums[right][1] + if sum == target: + return [sorted_nums[left][0], sorted_nums[right][0]] + elif sum < target: + left += 1 + else: + right -= 1 + + return [] + +```` + + + + +```java +class Solution { + public int[] twoSum(int[] nums, int target) { + int[][] sortedNums = new int[nums.length][2]; + for (int i = 0; i < nums.length; i++) { + sortedNums[i] = new int[] {nums[i], i}; + } + + Arrays.sort(sortedNums, (a, b) -> Integer.compare(a[0], b[0])); + + int left = 0; + int right = sortedNums.length - 1; + + while (left < right) { + int sum = sortedNums[left][0] + sortedNums[right][0]; + if (sum == target) { + return new int[] {sortedNums[left][1], sortedNums[right][1]}; + } else if (sum < target) { + left++; + } else { + right--; + } + } + + return new int[0]; + } +} +```` + + + + + +```cpp + class Solution { + public: + vector twoSum(vector& nums, int target) { + vector> sortedNums(nums.size(), vector(2)); + for (int i = 0; i < nums.size(); i++) { + sortedNums[i] = {nums[i], i}; + } + + sort(sortedNums.begin(), sortedNums.end(), [](vector& a, vector& b) { + return a[0] < b[0]; + }); + + int left = 0; + int right = sortedNums.size() - 1; + + while (left < right) { + int sum = sortedNums[left][0] + sortedNums[right][0]; + if (sum == target) { + return {sortedNums[left][1], sortedNums[right][1]}; + } else if (sum < target) { + left++; + } else { + right--; + } + } + + return {}; + } + }; +``` + + + + +#### Complexity Analysis + +- **Time Complexity:** $O(n \log n)$ +- **Space Complexity:** $O(n)$ +- Where `n` is the length of the input array `nums`. +- The time complexity is $O(n \log n)$ because we sort the array. +- The space complexity is $O(n)$ because we store the indices of the elements in the sorted array. +- This approach is efficient and is recommended for large inputs. +- The total time complexity is $O(n \log n)$. and the total space complexity is $O(n)$. + +
+
+ +:::tip Note +**Which is the best approach? and why?** + +The hash table approach is the most efficient and is recommended for large inputs. The hash table lookup has an average time complexity of $O(1)$, which makes this approach efficient. The time complexity of the hash table approach is $$O(n)$$, which is better than the brute force approach with a time complexity of $O(n^2)$ and the two-pointer approach with a time complexity of $O(n \log n)$. The space complexity of the hash table approach is $O(n)$, which is the same as the two-pointer approach. Therefore, the hash table approach is the best approach for this problem. + +::: + +--- + +## Video Explanation of Two Sum Problem + + + + + +--- + + + + + + + + + + + + + + + + + + + + + + +--- + +

Authors:

+ +
+{['ajay-dhangar'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/0000-0099/0002-Add-Two-Numbers.md b/solutions/lc-solutions/0000-0099/0002-Add-Two-Numbers.md new file mode 100644 index 0000000..6b52419 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0002-Add-Two-Numbers.md @@ -0,0 +1,298 @@ +--- +id: add-two-numbers +title: Add Two Numbers Solution +sidebar_label: 0002 - Add Two Numbers +tags: + - Linked List + - Math + - Recursion + - Add Two Numbers + - LeetCode +description: "This is a solution to the Add Two Numbers problem on LeetCode." +sidebar_position: 2 +--- + +In this tutorial, we will solve the Add Two Numbers problem. We will provide an overview of the problem, the intuition and approach to solve it, the implementation, and the code in various languages, along with a detailed explanation of the solution and its complexity analysis. Let's start by understanding the problem. + +## Problem Statement + +You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. + +You may assume the two numbers do not contain any leading zero, except the number 0 itself. + +```mermaid +graph LR +M[(Input)] --> A([l1]) +M[(Input)] --> E([l2]) +A --> B((2)) +B --> C((4)) +C --> D((3)) +E --> F((5)) +F --> G((6)) +G --> H((4)) +I[(Output)] --> J((7)) +J --> K((0)) +K --> L((8)) +``` + +**Example 1:** + +```plaintext +Input: l1 = [2,4,3], l2 = [5,6,4] +Output: [7,0,8] +Explanation: 342 + 465 = 807. +``` + +**Example 2:** + +```plaintext +Input: l1 = [0], l2 = [0] +Output: [0] +``` + +**Example 3:** + +```plaintext +Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] +Output: [8,9,9,9,0,0,0,1] +``` + +### Constraints + +- The number of nodes in each linked list is in the range `[1, 100]`. +- $0 \leq \text{Node.val} \leq 9$ +- It is guaranteed that the list represents a number that does not have leading zeros. + +--- + +## Solution for Add Two Numbers Problem + +### Intuition and Approach + +We iterate through both linked lists, adding corresponding node values along with a carry from the previous addition. If the sum of the current node values and carry is 10 or more, we keep the carry for the next addition. We continue this process until we traverse both linked lists. + +### Flowchart + +```mermaid +flowchart TD + A[Start] --> B{l1 or l2 or carry} + B --> |Yes| C[Add values of l1, l2, and carry] + C --> D[Calculate new carry and current node value] + D --> E[Add node with value to result list] + E --> F{Move to next node in l1 and l2 if exist} + F --> |Next nodes exist| B + F --> |Next nodes do not exist| G[Return result list] + B --> |No| G +``` + +### Pseudocode + +```plaintext +1. Initialize a dummy node and a current node to keep track of the current node. +2. Initialize a carry variable to 0. +3. Iterate through both linked lists until both are empty. + 1. Calculate the sum of the current node values and carry. + 2. Update the carry and current node value. + 3. Add the new node to the result list. + 4. Move to the next nodes in l1 and l2 if they exist. +4. Return the next node of the dummy node. +``` + +### Implementation and Code + +Here is a live code editor for you to play around with the solution: + +```jsx live +function addTwoNumbersProblem() { + class ListNode { + constructor(val = 0, next = null) { + this.val = val; + this.next = next; + } + } + + const l1 = new ListNode(2, new ListNode(4, new ListNode(3))); + const l2 = new ListNode(5, new ListNode(6, new ListNode(4))); + + const addTwoNumbers = function (l1, l2) { + let dummyHead = new ListNode(0); + let p = l1, + q = l2, + curr = dummyHead; + let carry = 0; + + while (p !== null || q !== null) { + let x = p !== null ? p.val : 0; + let y = q !== null ? q.val : 0; + let sum = carry + x + y; + carry = Math.floor(sum / 10); + curr.next = new ListNode(sum % 10); + curr = curr.next; + if (p !== null) p = p.next; + if (q !== null) q = q.next; + } + + if (carry > 0) { + curr.next = new ListNode(carry); + } + + return dummyHead.next; + }; + + const result = addTwoNumbers(l1, l2); + const listToArray = (node) => { + const arr = []; + while (node) { + arr.push(node.val); + node = node.next; + } + return arr; + }; + + const resultArray = listToArray(result); + return ( +
+

+ Input: l1 = {"[" + listToArray(l1).join(", ") + "]"}, l2 ={" "} + {"[" + listToArray(l2).join(", ") + "]"} +

+

+ Output: {"[" + resultArray.join(", ") + "]"} +

+
+ ); +} +``` + +### Code in Different Languages + + + + + ```javascript + var addTwoNumbers = function(l1, l2) { + let dummy = new ListNode(0); + let curr = dummy; + let carry = 0; + while (l1 !== null || l2 !== null) { + let x = (l1 !== null) ? l1.val : 0; + let y = (l2 !== null) ? l2.val : 0; + let sum = x + y + carry; + carry = Math.floor(sum / 10); + curr.next = new ListNode(sum % 10); + curr = curr.next; + if (l1 !== null) l1 = l1.next; + if (l2 !== null) l2 = l2.next; + } + if (carry > 0) { + curr.next = new ListNode(carry); + } + return dummy.next; + }; + ``` + + + + + ```python + def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: + dummy = ListNode(0) + curr = dummy + carry = 0 + while l1 or l2: + x = l1.val if l1 else 0 + y = l2.val if l2 else 0 + sum = x + y + carry + carry = sum // 10 + curr.next = ListNode(sum % 10) + curr = curr.next + if l1: + l1 = l1.next + if l2: + l2 = l2.next + if carry > 0: + curr.next = ListNode(carry) + return dummy.next + ``` + + + + + ```java + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(0); + ListNode curr = dummy; + int carry = 0; + while (l1 != null || l2 != null) { + int x = (l1 != null) ? l1.val : 0; + int y = (l2 != null) ? l2.val : 0; + int sum = x + y + carry; + carry = sum / 10; + curr.next = new ListNode(sum % 10); + curr = curr.next; + if (l1 != null) l1 = l1.next; + if (l2 != null) l2 = l2.next; + } + if (carry > 0) { + curr.next = new ListNode(carry); + } + return dummy.next; + } + ``` + + + + + ```cpp + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode* dummy = new ListNode(0); + ListNode* curr = dummy; + int carry = 0; + while (l1 || l2) { + int x = (l1) ? l1->val : 0; + int y = (l2) ? l2->val : 0; + int sum = x + y + carry; + carry = sum / 10; + curr->next = new ListNode(sum % 10); + curr = curr->next; + if (l1) l1 = l1->next; + if (l2) l2 = l2->next; + } + if (carry > 0) { + curr->next = new ListNode(carry); + } + return dummy->next; + } + ``` + + + +## Complexity Analysis + +### Time Complexity +The time complexity of the solution is **O(n)**, where **n** is the maximum length of the input linked lists. + +### Space Complexity +The space complexity is **O(n)** due to the space required to store the resulting linked list. + +## Conclusion + +The solution provided efficiently adds two numbers represented by linked lists. By using dummy nodes and handling carry, we ensure that the solution is both easy to understand and efficient. The detailed explanation, flowchart, and code in multiple languages aim to help you understand and implement the solution effectively. + +--- + +## References + +- [LeetCode Problem](https://leetcode.com/problems/add-two-numbers/) +- [GeeksforGeeks Solution](https://www.geeksforgeeks.org/add-two-numbers-represented-by-linked-lists/) +- [YouTube Explanation](https://www.youtube.com/watch?v=wgFPrzTjm7s) + +--- + +

Authors:

+ +
+{['ajay-dhangar'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/0000-0099/0003-Longest-Substring-Without-Repeating-Characters.md b/solutions/lc-solutions/0000-0099/0003-Longest-Substring-Without-Repeating-Characters.md new file mode 100644 index 0000000..639f765 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0003-Longest-Substring-Without-Repeating-Characters.md @@ -0,0 +1,435 @@ +--- +id: longest-substrings-without-repeating-characters +title: Longest Substring Without Repeating Characters (LeetCode) +sidebar_label: 0003 - Longest Substring Without Repeating Characters +tags: + - Hash table + - String + - Sliding Window +description: "This is a solution to the Longest Substring Without Repeating Characters problem on LeetCode." +sidebar_position: 3 +--- + +In this page we will solve the problem [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) from LeetCode. + +## Problem Statement + +Given a string `s`, find the length of the longest substring without repeating characters. + +### Example 1 + +```plaintext +Input: s = "abcabcbb" +Output: 3 +Explanation: The answer is "abc", with the length of 3. +``` + +### Example 2 + +```plaintext +Input: s = "bbbbb" +Output: 1 +Explanation: The answer is "b", with the length of 1. +``` + +### Example 3 + +```plaintext +Input: s = "pwwkew" +Output: 3 +Explanation: The answer is "wke", with the length of 3. +Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. +``` + +### Constraints: + +- `0 <= s.length <= 5 * 10^4` +- `s` consists of English letters, digits, symbols and spaces. + +--- + +## Solution for Longest Substring Without Repeating Characters + +### Intuition and Approach + +We can solve this problem using the sliding window technique. We will use a hash table to store the characters and their indices. We will also use two pointers, `left` and `right`, to define the window. The `left` pointer will point to the start of the window, and the `right` pointer will point to the end of the window. + +We will iterate over the string `s` using the `right` pointer. If the character at the `right` pointer is not in the hash table, we will add it to the hash table with its index. We will then calculate the length of the current window by subtracting the `left` pointer from the `right` pointer and update the maximum length if needed. + +If the character at the `right` pointer is already in the hash table, we will move the `left` pointer to the right of the last occurrence of the character. We will also update the index of the character in the hash table. + +We will continue this process until we reach the end of the string `s`. The maximum length of the substring without repeating characters will be the answer. + +### Algorithm + +1. Initialize an empty hash table `charIndex` to store the characters and their indices. +2. Initialize the `left` and `right` pointers to 0. +3. Initialize the `maxLength` variable to store the maximum length of the substring without repeating characters. +4. Iterate over the string `s` using the `right` pointer: + - If `s[right]` is not in `charIndex`, add it to the hash table with its index. + - Calculate the length of the current window and update the `maxLength` if needed. + - If `s[right]` is already in `charIndex`, move the `left` pointer to the right of the last occurrence of `s[right]`. + - Update the index of `s[right]` in the hash table. +5. Continue this process until the end of the string `s`. +6. Return the `maxLength`. + +### Flowchart + +The flowchart below illustrates the steps involved in the algorithm: + +```mermaid +flowchart TD + Start --> Initialize; + Initialize --> Iterate; + Iterate --> |s right not in charIndex| AddToHashTable; + AddToHashTable --> CalculateLength; + CalculateLength --> UpdateMaxLength; + UpdateMaxLength --> |s right in charIndex| MoveLeftPointer; + MoveLeftPointer --> UpdateIndex; + UpdateIndex --> Iterate; + Iterate --> |End of string| ReturnMaxLength; + ReturnMaxLength --> End; +``` + +### Pseudocode + +```plaintext +function lengthOfLongestSubstring(s: string): number + let charIndex = new Map() + let left = 0 + let maxLength = 0 + + for right from 0 to s.length - 1 + if s[right] in charIndex + left = max(left, charIndex[s[right]] + 1) + charIndex[s[right]] = right + maxLength = max(maxLength, right - left + 1) + + return maxLength +``` + +### Implementation and Code + +Here is a live code editor for you to play around with the solution: + +```jsx live +function LongestSubstringProblem() { + const findLongestSubstring = (s) => { + let charIndexMap = {}; + let left = 0; + let maxLength = 0; + + for (let right = 0; right < s.length; right++) { + if (charIndexMap[s[right]] !== undefined) { + left = Math.max(left, charIndexMap[s[right]] + 1); + } + charIndexMap[s[right]] = right; + maxLength = Math.max(maxLength, right - left + 1); + } + + return maxLength; + }; + + const testCases = [ + { input: "abcabcbb", expected: 3 }, + { input: "bbbbb", expected: 1 }, + { input: "pwwkew", expected: 3 }, + ]; + + return ( +
+ {testCases.map((testCase, index) => ( +
+

+ Input: {testCase.input} +

+

+ Output: {findLongestSubstring(testCase.input)} +

+

+ Expected: {testCase.expected} +

+
+
+ ))} +
+ ); +} +``` + +### Code in Different Languages + + + + + ```jsx + /** + * @param {string} s + * @return {number} + */ + var lengthOfLongestSubstring = function(s) { + let charIndexMap = {}; + let left = 0; + let maxLength = 0; + + for (let right = 0; right < s.length; right++) { + if (charIndexMap[s[right]] !== undefined) { + left = Math.max(left, charIndexMap[s[right]] + 1); + } + charIndexMap[s[right]] = right; + maxLength = Math.max(maxLength, right - left + 1); + } + + return maxLength; + + }; + + ``` + + + + ```python + class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + char_index_map = {} + left = 0 + max_length = 0 + + for right in range(len(s)): + if s[right] in char_index_map: + left = max(left, char_index_map[s[right]] + 1) + char_index_map[s[right]] = right + max_length = max(max_length, right - left + 1) + + return max_length + ``` + + + + + ```java + class Solution { + public int lengthOfLongestSubstring(String s) { + Map charIndexMap = new HashMap<>(); + int left = 0; + int maxLength = 0; + + for (int right = 0; right < s.length(); right++) { + if (charIndexMap.containsKey(s.charAt(right))) { + left = Math.max(left, charIndexMap.get(s.charAt(right)) + 1); + } + charIndexMap.put(s.charAt(right), right); + maxLength = Math.max(maxLength, right - left + 1); + } + + return maxLength; + } + } + + ``` + + + + ```cpp + class Solution { + public: + int lengthOfLongestSubstring(string s) { + unordered_map charIndexMap; + int left = 0; + int maxLength = 0; + + for (int right = 0; right < s.length(); right++) { + if (charIndexMap.find(s[right]) != charIndexMap.end()) { + left = max(left, charIndexMap[s[right]] + 1); + } + charIndexMap[s[right]] = right; + maxLength = max(maxLength, right - left + 1); + } + + return maxLength; + } + }; + ``` + + + + + + ```c + int lengthOfLongestSubstring(char * s){ + int charIndexMap[256]; + memset(charIndexMap, -1, sizeof(charIndexMap)); + int left = 0; + int maxLength = 0; + + for (int right = 0; s[right] != '\0'; right++) { + if (charIndexMap[s[right]] != -1) { + left = fmax(left, charIndexMap[s[right]] + 1); + } + charIndexMap[s[right]] = right; + maxLength = fmax(maxLength, right - left + 1); + } + + return maxLength; + } + + ``` + + + + + ```ts + function lengthOfLongestSubstring(s: string): number { + const charIndexMap: Record = {}; + let left = 0; + let maxLength = 0; + + for (let right = 0; right < s.length; right++) { + if (charIndexMap[s[right]] !== undefined) { + left = Math.max(left, charIndexMap[s[right]] + 1); + } + charIndexMap[s[right]] = right; + maxLength = Math.max(maxLength, right - left + 1); + } + + return maxLength; + } + ``` + + + + + + + ```python + class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + n = len(s) + maxLength = 0 + charSet = set() + left = 0 + + for right in range(n): + if s[right] not in charSet: + charSet.add(s[right]) + maxLength = max(maxLength, right - left + 1) + else: + while s[right] in charSet: + charSet.remove(s[left]) + left += 1 + charSet.add(s[right]) + + return maxLength + ``` + + + + ```java + class Solution { + public int lengthOfLongestSubstring(String s) { + int n = s.length(); + int maxLength = 0; + Set charSet = new HashSet<>(); + int left = 0; + + for (int right = 0; right < n; right++) { + if (!charSet.contains(s.charAt(right))) { + charSet.add(s.charAt(right)); + maxLength = Math.max(maxLength, right - left + 1); + } else { + while (charSet.contains(s.charAt(right))) { + charSet.remove(s.charAt(left)); + left++; + } + charSet.add(s.charAt(right)); + } + } + + return maxLength; + } + } + ``` + + + + ```cpp + #include + #include + #include + + class Solution { + public: + int lengthOfLongestSubstring(string s) { + if (s.empty()) return 0; + + int maxLength = 0; + std::vector seen; + + for (char c : s) { + auto it = std::find(seen.begin(), seen.end(), c); + if (it == seen.end()) { + seen.push_back(c); + maxLength = std::max(maxLength, static_cast(seen.size())); + } else { + seen.erase(seen.begin(), it + 1); // Remove characters before the repeated character + seen.push_back(c); + } + } + + return maxLength; + } + }; + ``` + + + + + + +### Complexity Analysis + +- **Time Complexity:** The time complexity of this solution is $O(n)$, where n is the length of the input string `s`. We iterate over the string `s` once using the `right` pointer. + +- **Space Complexity:** The space complexity of this solution is $O(min(n, m))$, where n is the length of the input string `s` and m is the size of the character set (e.g., 26 for lowercase English letters). We use a hash table to store the characters and their indices, which can have a maximum of m entries. + +### Test Cases + +We will test the solution with the sample test cases provided in the problem statement. + + + + ```plaintext + Input: s = "abcabcbb" + Output: 3 + Explanation: The answer is "abc", with the length of 3. + ``` + + + ```plaintext + Input: s = "bbbbb" + Output: 1 + Explanation: The answer is "b", with the length of 1. + ``` + + + ```plaintext + Input: s = "pwwkew" + Output: 3 + Explanation: The answer is "wke", with the length of 3. + Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. + ``` + + + + +## Resources + +--- + +

Authors:

+ +
+{['ajay-dhangar'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0004-Median-of-two-Sorted-Array.md b/solutions/lc-solutions/0000-0099/0004-Median-of-two-Sorted-Array.md new file mode 100644 index 0000000..f32c98c --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0004-Median-of-two-Sorted-Array.md @@ -0,0 +1,817 @@ +--- +id: median-of-two-sorted-arrays +title: Median of Two Sorted Arrays(Leetcode) +sidebar_label: 0004 - Median of Two Sorted Arrays +tags: + - Array + - Binary Search + - Divide and Conquer0 + - LeetCode +description: Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. +sidebar_position: 4 +--- + +In this page, we will solve the problem [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/description/) from LeetCode. We will provide multiple approaches to solve the problem along with the code implementation and the complexity analysis of the code. + +## Problem Statement + +Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return the median of the two sorted arrays. + +The overall run time complexity should be $O(log (m+n))$. + +### Example 1 + +```plaintext +Input: nums1 = [1,3], nums2 = [2] +Output: 2.00000 +Explanation: merged array = [1,2,3] and median is 2. +``` + +### Example 2 + +```plaintext +Input: nums1 = [1,2], nums2 = [3,4] +Output: 2.50000 +Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. +``` + +### Constraints: + +- $nums1.length == m$ +- $nums2.length == n$ +- $0 <= m <= 1000$ +- $0 <= n <= 1000$ +- $1 <= m + n <= 2000$ +- $-10^6 <= nums1[i], nums2[i] <= 10^6$ + +--- + +## Solution for Median of Two Sorted Arrays + +The **Median of Two Sorted Arrays** is a classic algorithm problem on LeetCode ([Problem 4](https://leetcode.com/problems/median-of-two-sorted-arrays/description/)). It requires finding the median of two sorted arrays. Given two sorted arrays `nums1` and `nums2`, the task is to find the median of the two arrays combined. + +Here is an explanation of the intuition and approaches to solve this problem: + +### intuition + +The median is the middle value of a dataset. For an even number of elements, it is the average of the two middle values. If we have two sorted arrays, the naive approach would involve merging both arrays and then finding the median, but this approach does not take full advantage of the fact that the arrays are already sorted and is not efficient for large arrays. + +Instead, we can use a more advanced approach to find the median in $O(log(min(n, m)))$ time, where `n` and `m` are the lengths of the two arrays. This involves using a binary search method. The idea is to partition both arrays into two halves such that the combined left half and right half are both sorted and of equal length (or differing by one). + + + + +## Approach 1: Binary Search + +The binary search approach involves partitioning the two arrays such that the combined left half and right half are both sorted and of equal length (or differing by one). We can then find the median based on these partitions. + +### Pseudocode + +1. Ensure `nums1` is the smaller array. +2. Initialize `low` and `high` for binary search on `nums1`. +3. While `low <= high`: + - Calculate `partitionX` and `partitionY`. + - Set `maxX`, `minX`, `maxY`, `minY`. + - If `maxX <= minY` and `maxY <= minX`: + - If total number of elements is even + - Return average of `max(maxX, maxY)` and `min(minX, minY)`. + - Else + - Return `max(maxX, maxY)`. + - If `maxX > minY`: + - Move `high` to `partitionX - 1`. + - Else: + - Move `low` to `partitionX + 1`. +4. If no median is found, raise an error. + +### Implementation and Code + +Here is a live code editor for you to play around with the solution: + +```jsx live +function medianOfTwoSortedArraysProblem() { + const findMedianSortedArrays = (nums1, nums2) => { + // Ensure nums1 is the smaller array + if (nums1.length > nums2.length) { + [nums1, nums2] = [nums2, nums1]; + } + + const x = nums1.length; + const y = nums2.length; + let low = 0, high = x; + + while (low <= high) { + const partitionX = Math.floor((low + high) / 2); + const partitionY = Math.floor((x + y + 1) / 2) - partitionX; + + const maxX = (partitionX === 0) ? -Infinity : nums1[partitionX - 1]; + const minX = (partitionX === x) ? Infinity : nums1[partitionX]; + + const maxY = (partitionY === 0) ? -Infinity : nums2[partitionY - 1]; + const minY = (partitionY === y) ? Infinity : nums2[partitionY]; + + if (maxX <= minY && maxY <= minX) { + if ((x + y) % 2 === 0) { + return (Math.max(maxX, maxY) + Math.min(minX, minY)) / 2; + } else { + return Math.max(maxX, maxY); + } + } else if (maxX > minY) { + high = partitionX - 1; + } else { + low = partitionX + 1; + } + } + + throw new Error("Input arrays are not sorted."); + }; + + const nums1 = [1, 3]; + const nums2 = [2]; + const result = findMedianSortedArrays(nums1, nums2); + + return ( +
+

+ Input: nums1 = {"[" + nums1.join(", ") + "]"}, nums2 = {"[" + nums2.join(", ") + "]"} +

+

+ Output: {result} +

+
+ ); +} +``` + +### Code in Different Languages + + + + + ```js + var findMedianSortedArrays = function(nums1, nums2) { + if (nums1.length > nums2.length) { + [nums1, nums2] = [nums2, nums1]; + } + + let x = nums1.length; + let y = nums2.length; + let low = 0, high = x; + + while (low <= high) { + let partitionX = Math.floor((low + high) / 2); + let partitionY = Math.floor((x + y + 1) / 2) - partitionX; + + let maxX = (partitionX === 0) ? -Infinity : nums1[partitionX - 1]; + let minX = (partitionX === x) ? Infinity : nums1[partitionX]; + + let maxY = (partitionY === 0) ? -Infinity : nums2[partitionY - 1]; + let minY = (partitionY === y) ? Infinity : nums2[partitionY]; + + if (maxX <= minY && maxY <= minX) { + if ((x + y) % 2 === 0) { + return (Math.max(maxX, maxY) + Math.min(minX, minY)) / 2; + } else { + return Math.max(maxX, maxY); + } + } else if (maxX > minY) { + high = partitionX - 1; + } else { + low = partitionX + 1; + } + } + + throw new Error("Input arrays are not sorted."); + }; + ``` + + + + + ```python + class Solution: + def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: + if len(nums1) > len(nums2): + nums1, nums2 = nums2, nums1 + + x = len(nums1) + y = len(nums2) + low, high = 0, x + + while low <= high: + partitionX = (low + high) // 2 + partitionY = (x + y + 1) // 2 - partitionX + + maxX = float('-inf') if partitionX == 0 else nums1[partitionX - 1] + minX = float('inf') if partitionX == x else nums1[partitionX] + + maxY = float('-inf') if partitionY == 0 else nums2[partitionY - 1] + minY = float('inf') if partitionY == y else nums2[partitionY] + + if maxX <= minY and maxY <= minX: + if (x + y) % 2 == 0: + return (max(maxX, maxY) + min(minX, minY)) / 2 + else: + return max(maxX, maxY) + elif maxX > minY: + high = partitionX - 1 + else: + low = partitionX + 1 + + raise ValueError("Input arrays are not sorted.") + ``` + + + + ```java + class Solution { + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + if (nums1.length > nums2.length) { + int[] temp = nums1; + nums1 = nums2; + nums2 = temp; + } + + int x = nums1.length; + int y = nums2.length; + int low = 0, high = x; + + while (low <= high) { + int partitionX = (low + high) / 2; + int partitionY = (x + y + 1) / 2 - partitionX; + + int maxX = (partitionX == 0) ? Integer.MIN_VALUE : nums1[partitionX - 1]; + int minX = (partitionX == x) ? Integer.MAX_VALUE : nums1[partitionX]; + + int maxY = (partitionY == 0) ? Integer.MIN_VALUE : nums2[partitionY - 1]; + int minY = (partitionY == y) ? Integer.MAX_VALUE : nums2[partitionY]; + + if (maxX <= minY && maxY <= minX) { + if ((x + y) % 2 == 0) { + return (Math.max(maxX, maxY) + Math.min(minX, minY)) / 2.0; + } else { + return Math.max(maxX, maxY); + } + } else if (maxX > minY) { + high = partitionX - 1; + } else { + low = partitionX + 1; + } + } + + throw new IllegalArgumentException("Input arrays are not sorted."); + } + } + ``` + + + + ```cpp + class Solution { + public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + if (nums1.size() > nums2.size()) { + swap(nums1, nums2); + } + + int x = nums1.size(); + int y = nums2.size(); + int low = 0, high = x; + + while (low <= high) { + int partitionX = (low + high) / 2; + int partitionY = (x + y + 1) / 2 - partitionX; + + int maxX = (partitionX == 0) ? INT_MIN : nums1[partitionX - 1]; + int minX = (partitionX == x) ? INT_MAX : nums1[partitionX]; + + int maxY = (partitionY == 0) ? INT_MIN : nums2[partitionY - 1]; + int minY = (partitionY == y) ? INT_MAX : nums2[partitionY]; + + if (maxX <= minY && maxY <= minX) { + if ((x + y) % 2 == 0) { + return (max(maxX, maxY) + min(minX, minY)) / 2.0; + } else { + return max(maxX, maxY); + } + } else if (maxX > minY) { + high = partitionX - 1; + } else { + low = partitionX + 1; + } + } + + throw invalid_argument("Input arrays are not sorted."); + } + }; + ``` + + + + ```c + double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) { + if (nums1Size > nums2Size) { + int* temp = nums1; + nums1 = nums2; + nums2 = temp; + int tempSize = nums1Size; + nums1Size = nums2Size; + nums2Size = tempSize; + } + + int x = nums1Size; + int y = nums2Size; + int low = 0, high = x; + + while (low <= high) { + int partitionX = (low + high) / 2; + int partitionY = (x + y + 1) / 2 - partitionX; + + int maxX = (partitionX == 0) ? INT_MIN : nums1[partitionX - 1]; + int minX = (partitionX == x) ? INT_MAX : nums1[partitionX]; + + int maxY = (partitionY == 0) ? INT_MIN : nums2[partitionY - 1]; + int minY = (partitionY == y) ? INT_MAX : nums2[partitionY]; + + if (maxX <= minY && maxY <= minX) { + if ((x + y) % 2 == 0) { + return (fmax(maxX, maxY) + fmin(minX, minY)) / 2.0; + } else { + return fmax(maxX, maxY); + } + } else if (maxX > minY) { + high = partitionX - 1; + } else { + low = partitionX + 1; + } + } + + return -1; + } + ``` + + + + ```ts + function findMedianSortedArrays(nums1: number[], nums2: number[]): number { + if (nums1.length > nums2.length) { + [nums1, nums2] = [nums2, nums1]; + } + + let x = nums1.length; + let y = nums2.length; + let low = 0, high = x; + + while (low <= high) { + let partitionX = Math.floor((low + high) / 2); + let partitionY = Math.floor((x + y + 1) / 2) - partitionX; + + let maxX = (partitionX === 0) ? -Infinity : nums1[partitionX - 1]; + let minX = (partitionX === x) ? Infinity : nums1[partitionX]; + + let maxY = (partitionY === 0) ? -Infinity : nums2[partitionY - 1]; + let minY = (partitionY === y) ? Infinity : nums2[partitionY]; + + if (maxX <= minY && maxY <= minX) { + if ((x + y) % 2 === 0) { + return (Math.max(maxX, maxY) + Math.min(minX, minY)) / 2; + } else { + return Math.max(maxX, maxY); + } + } else if (maxX > minY) { + high = partitionX - 1; + } else { + low = partitionX + 1; + } + } + + throw new Error("Input arrays are not sorted."); + } + ``` + + + +### Complexity Analysis + +- **Time Complexity**: The time complexity of this approach is $O(log(min(n, m)))$, where `n` and `m` are the lengths of the two arrays. The binary search approach helps in reducing the search space and finding the median efficiently. +- **Space Complexity**: The space complexity of this approach is $O(1)$ as we are using constant extra space. + +### Test Cases + +Let's test the solution with the sample test cases: + + + +```plaintext +Input: nums1 = [1, 3], nums2 = [2] +Output: 2.00000 +Explanation: merged array = [1, 2, 3] and median is 2. +``` + + +```plaintext +Input: nums1 = [1, 2], nums2 = [3, 4] +Output: 2.50000 +Explanation: merged array = [1, 2, 3, 4] and median is (2 + 3) / 2 = 2.5. +``` + + +
+ + + +## Approach 2: Divide and Conquer + +The divide and conquer approach finds the median by recursively dividing the problem into smaller subproblems. It merges two sorted arrays by comparing and removing the smallest element from the two arrays until the median is found. + +### Pseudocode + +1. Ensure `nums1` is the smaller array. +2. If the total length of both arrays is even, find the k-th and (k+1)-th smallest elements and return their average. +3. If the total length is odd, find the k-th smallest element. +4. Define a helper function `getKth` to find the k-th smallest element in the combined array: + - Base cases: + - If one array is empty, return the k-th element from the other array. + - If k is 1, return the minimum of the first elements of both arrays. + - Recursive case: + - Divide k by 2, compare the k/2-th elements of both arrays, and discard the smaller half. + +### Implementation and Code + +Here is a live code editor for you to play around with the solution: + +```jsx live +function medianOfTwoSortedArraysProblem() { + const findMedianSortedArrays = (nums1, nums2) => { + const getKth = (nums1, nums2, k) => { + const len1 = nums1.length; + const len2 = nums2.length; + + if (len1 > len2) return getKth(nums2, nums1, k); + if (len1 === 0) return nums2[k - 1]; + if (k === 1) return Math.min(nums1[0], nums2[0]); + + const i = Math.min(len1, Math.floor(k / 2)); + const j = Math.min(len2, Math.floor(k / 2)); + + if (nums1[i - 1] > nums2[j - 1]) { + return getKth(nums1, nums2.slice(j), k - j); + } else { + return getKth(nums1.slice(i), nums2, k - i); + } + }; + + const len = nums1.length + nums2.length; + if (len % 2 === 1) { + return getKth(nums1, nums2, Math.floor(len / 2) + 1); + } else { + return ( + (getKth(nums1, nums2, Math.floor(len / 2)) + + getKth(nums1, nums2, Math.floor(len / 2) + 1)) / + 2 + ); + } + }; + + const nums1 = [1, 3]; + const nums2 = [2]; + const result = findMedianSortedArrays(nums1, nums2); + + return ( +
+

+ Input: nums1 = {"[" + nums1.join(", ") + "]"}, nums2 = {"[" + nums2.join(", ") + "]"} +

+

+ Output: {result} +

+
+ ); +} +``` + +### Code in Different Languages + + + + + ```js + var findMedianSortedArrays = function(nums1, nums2) { + const getKth = (nums1, nums2, k) => { + const len1 = nums1.length; + const len2 = nums2.length; + + if (len1 > len2) return getKth(nums2, nums1, k); + if (len1 === 0) return nums2[k - 1]; + if (k === 1) return Math.min(nums1[0], nums2[0]); + + const i = Math.min(len1, Math.floor(k / 2)); + const j = Math.min(len2, Math.floor(k / 2)); + + if (nums1[i - 1] > nums2[j - 1]) { + return getKth(nums1, nums2.slice(j), k - j); + } else { + return getKth(nums1.slice(i), nums2, k - i); + } + }; + + const len = nums1.length + nums2.length; + if (len % 2 === 1) { + return getKth(nums1, nums2, Math.floor(len / 2) + 1); + } else { + return (getKth(nums1, nums2, Math.floor(len / 2)) + + getKth(nums1, nums2, Math.floor(len / 2) + 1)) / 2; + } + }; + ``` + + + + ```python + class Solution: + def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: + def getKth(nums1, nums2, k): + if len(nums1) > len(nums2): + return getKth(nums2, nums1, k) + if len(nums1) == 0: + return nums2[k - 1] + if k == 1: + return min(nums1[0], nums2[0]) + + i = min(len(nums1), k // 2) + j = min(len(nums2), k // 2) + + if nums1[i - 1] > nums2[j - 1]: + return getKth(nums1, nums2[j:], k - j) + else: + return getKth(nums1[i:], nums2, k - i) + + len_combined = len(nums1) + len(nums2) + if len_combined % 2 == 1: + return getKth(nums1, nums2, len_combined // 2 + 1) + else: + return (getKth(nums1, nums2, len_combined // 2) + + getKth(nums1, nums2, len_combined // 2 + 1)) / 2 + ``` + + + + ```java + class Solution { + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + int len1 = nums1.length; + int len2 = nums2.length; + + if (len1 > len2) { + return findMedianSortedArrays(nums2, nums1); + } + + int len = len1 + len2; + if (len % 2 == 1) { + return getKth(nums1, nums2, len / 2 + 1); + } else { + return (getKth(nums1, nums2, len / 2) + getKth(nums1, nums2, len / 2 + 1)) / 2.0; + } + } + + private int getKth(int[] nums1, int[] nums2, int k) { + int len1 = nums1.length; + int len2 = nums2.length; + + if (len1 > len2) { + return getKth(nums2, nums1, k); + } + if (len1 == 0) { + return nums2[k - 1]; + } + if (k == 1) { + return Math.min(nums1[0], nums2[0]); + } + + int i = Math.min(len1, k / 2); + int j = Math.min(len2, k / 2); + + if (nums1[i - 1] > nums2[j - 1]) { + return getKth(nums1, Arrays.copyOfRange(nums2, j, len2), k - j); + } else { + return getKth(Arrays.copyOfRange(nums1, i, len1), nums2, k - i); + } + } + } + ``` + + + + ```cpp + class Solution { + public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + int len1 = nums1.size(); + int len2 = nums2.size(); + + if (len1 > len2) { + return findMedianSortedArrays(nums2, nums1); + } + + int len = len1 + len2; + if (len % 2 == 1) { + return getKth(nums1, nums2, len / 2 + 1); + } else { + return (getKth(nums1, nums2, len / 2) + getKth(nums1, nums2, len / 2 + 1)) / 2.0; + } + } + + private: + int getKth(vector& nums1, vector& nums2, int k) { + int len1 = nums1.size(); + int len2 = nums2.size(); + + if (len1 > len2) { + return getKth(nums2, nums1, k); + } + if (len 1 == 0) { + return nums2[k - 1]; + } + if (k == 1) { + return min(nums1[0], nums2[0]); + } + + int i = min(len1, k / 2); + int j = min(len2, k / 2); + + if (nums1[i - 1] > nums2[j - 1]) { + return getKth(nums1, vector(nums2.begin() + j, nums2.end()), k - j); + } else { + return getKth(vector(nums1.begin() + i, nums1.end()), nums2, k - i); + } + } + }; + ``` + + + + ```c + double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) { + if (nums1Size > nums2Size) { + return findMedianSortedArrays(nums2, nums2Size, nums1, nums1Size); + } + + int len = nums1Size + nums2Size; + if (len % 2 == 1) { + return getKth(nums1, nums1Size, nums2, nums2Size, len / 2 + 1); + } else { + return (getKth(nums1, nums1Size, nums2, nums2Size, len / 2) + getKth(nums1, nums1Size, nums2, nums2Size, len / 2 + 1)) / 2.0; + } + } + + double getKth(int* nums1, int nums1Size, int* nums2, int nums2Size, int k) { + if (nums1Size > nums2Size) { + return getKth(nums2, nums2Size, nums1, nums1Size, k); + } + if (nums1Size == 0) { + return nums2[k - 1]; + } + if (k == 1) { + return fmin(nums1[0], nums2[0]); + } + + int i = fmin(nums1Size, k / 2); + int j = fmin(nums2Size, k / 2); + + if (nums1[i - 1] > nums2[j - 1]) { + return getKth(nums1, nums1Size, nums2 + j, nums2Size - j, k - j); + } else { + return getKth(nums1 + i, nums1Size - i, nums2, nums2Size, k - i); + } + } + ``` + + + + ```ts + function findMedianSortedArrays(nums1: number[], nums2: number[]): number { + const getKth = (nums1: number[], nums2: number[], k: number): number => { + if (nums1.length > nums2.length) return getKth(nums2, nums1, k); + if (nums1.length === 0) return nums2[k - 1]; + if (k === 1) return Math.min(nums1[0], nums2[0]); + + const i = Math.min(nums1.length, Math.floor(k / 2)); + const j = Math.min(nums2.length, Math.floor(k / 2)); + + if (nums1[i - 1] > nums2[j - 1]) { + return getKth(nums1, nums2.slice(j), k - j); + } else { + return getKth(nums1.slice(i), nums2, k - i); + } + }; + + const len = nums1.length + nums2.length; + if (len % 2 === 1) { + return getKth(nums1, nums2, Math.floor(len / 2) + 1); + } else { + return ( + (getKth(nums1, nums2, Math.floor(len / 2)) + + getKth(nums1, nums2, Math.floor(len / 2) + 1)) / + 2 + ); + } + } + ``` + + + +### Complexity Analysis + +- **Time Complexity**: The time complexity of this approach is $O(log(min(n, m)))$, where `n` and `m` are the lengths of the two arrays. Each recursive call divides the problem into half. +- **Space Complexity**: The space complexity of this approach is $O(1)$ as we are using constant extra space. + +### Test Cases + +Let's test the solution with the sample test cases: + + + +```plaintext +Input: nums1 = [1, 3], nums2 = [2] +Output: 2.00000 +Explanation: merged array = [1, 2, 3] and median is 2. +``` + + +```plaintext +Input: nums1 = [1, 2], nums2 = [3, 4] +Output: 2.50000 +Explanation: merged array = [1, 2, 3, 4] and median is (2 + 3) / 2 = 2.5. +``` + + +
+
+ +:::info + +**Note**: The binary search approach is more efficient than the divide and conquer approach as it has a better time complexity of $O(log(min(n, m)))$ compared to the divide and conquer approach. However, both approaches provide a solution to the problem of finding the median of two sorted arrays. + +**Which approach is best for you?** + +The binary search approach is more efficient and recommended for solving the problem of finding the median of two sorted arrays. However, the divide and conquer approach is also a valid solution and can be used if needed. + +::: + +:::tip +When asked to find the median of two sorted arrays, a direct approach that merges the two arrays and then finds the median will work but isn't optimal. Given the problem's constraints, we can leverage the fact that the arrays are already sorted and use binary search to find the median in $$ O(\log(\min(n, m))) $$ time complexity. + +The key idea is to use binary search to partition the smaller array in such a way that we can easily find the median by comparing elements around the partition. + +#### Detailed Explanation + +1. **Ensure the Smaller Array is First**: + - This step is to make sure we always perform the binary search on the smaller array, which helps us manage the partition logic more easily. Let $$ \text{nums1} $$ be the smaller array and $$ \text{nums2} $$ be the larger array. + +2. **Set Up Binary Search**: + - Initialize $$ \text{low} $$ and $$ \text{high} $$ pointers for the binary search on $$ \text{nums1} $$. + - We aim to partition $$ \text{nums1} $$ and $$ \text{nums2} $$ such that the left side of the combined arrays contains half of the elements, and the right side contains the other half. + +3. **Partitioning the Arrays**: + - Calculate $$ \text{partitionX} $$ as the midpoint of $$ \text{nums1} $$. + - Calculate $$ \text{partitionY} $$ such that the left side of the combined arrays has the same number of elements as the right side. This can be achieved by: + $$ + \text{partitionY} = \frac{(x + y + 1)}{2} - \text{partitionX} + $$ + + where $$ x $$ and $$ y $$ are the lengths of $$ \text{nums1} $$ and $$ \text{nums2} $$ respectively. + +4. **Boundary Conditions**: + - Handle cases where partitions might go out of bounds. If $$ \text{partitionX} $$ is 0, it means there are no elements on the left side of $$ \text{nums1} $$. If $$ \text{partitionX} $$ is $$ x $$, it means there are no elements on the right side of $$ \text{nums1} $$. + +5. **Check Valid Partition**: + - A valid partition is one where the maximum element on the left side of both partitions is less than or equal to the minimum element on the right side of both partitions: + $$ + \text{maxX} \leq \text{minY} \quad \text{and} \quad \text{maxY} \leq \text{minX} + $$ + Here, $$ \text{maxX} $$ is the largest element on the left side of $$ \text{nums1} $$, $$ \text{minX} $$ is the smallest element on the right side of $$ \text{nums1} $$, and similarly for $$ \text{nums2} $$. + +6. **Calculate the Median**: + - If the total number of elements $$ (x + y) $$ is even, the median is the average of the two middle values: + $$ + \text{median} = \frac{\text{max(maxX, maxY)} + \text{min(minX, minY)}}{2} + $$ + - If the total number of elements is odd, the median is the maximum element of the left partition: + $$ + \text{median} = \text{max(maxX, maxY)} + $$ + +7. **Adjust Binary Search**: + - If $$ \text{maxX} > \text{minY} $$, it means we need to move the partition in $$ \text{nums1} $$ to the left, so adjust $$ \text{high} $$. + - If $$ \text{maxY} > \text{minX} $$, it means we need to move the partition in $$ \text{nums1} $$ to the right, so adjust $$ \text{low} $$. + +::: + +--- + +

Authors:

+ +
+{['ajay-dhangar'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0005-Longest-palindrome-substring.md b/solutions/lc-solutions/0000-0099/0005-Longest-palindrome-substring.md new file mode 100644 index 0000000..d8eff14 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0005-Longest-palindrome-substring.md @@ -0,0 +1,217 @@ +--- +id: longest-alindromic-substring +title: Longest Palindromic Substring(LeetCode) +sidebar_label: 0005-Longest Palindrome Substring +tags: + - String + - Dynamic Programming +description: Given a string s, return the longest palindromic substring in s. +sidebar_position: 5 +--- + +## Problem Statement + +Given a string `s`, return the longest palindromic substring in `s`. + +### Examples + +**Example 1:** + +```plaintext +Input: s = "babad" +Output: "bab" +Explanation: "aba" is also a valid answer. +``` + +**Example 2:** + +```plaintext +Input: s = "cbbd" +Output: "bb" +``` + +### Constraints + +- `1 <= s.length <= 1000` +- `s` consist of only digits and English letters. + +## Solution + +### Approach 1: Check All Substrings + +#### Intuition + +We can start with a brute-force approach. We will simply check if each substring is a palindrome, and take the longest one that is. + +#### Algorithm + +1. Create a helper method `check(i, j)` to determine if a substring is a palindrome. +2. Use two pointers to iterate from the start and end of the substring towards the center. +3. If characters at both pointers are equal, move the pointers inward. +4. Use nested loops to check all possible substrings and use the helper method to determine if they are palindromes. +5. Keep track of the longest palindrome found. + +#### Implementation + +```python +def longestPalindrome(s: str) -> str: + def check(l, r): + while l >= 0 and r < len(s) and s[l] == s[r]: + l -= 1 + r += 1 + return s[l+1:r] + + longest = "" + for i in range(len(s)): + odd_palindrome = check(i, i) + even_palindrome = check(i, i + 1) + longest = max(longest, odd_palindrome, even_palindrome, key=len) + + return longest +``` + +### Complexity Analysis + +- **Time complexity**: $O(n^3)$ - We check each substring, and checking each substring takes $O(n)$ time. +- **Space complexity**: $O(1)$ - We use a constant amount of extra space. + +### Approach 2: Dynamic Programming + +#### Intuition + +If we know a substring is a palindrome, we can extend it if the characters on both ends match. + +#### Algorithm + +1. Initialize a 2D DP table with `False`. +2. Mark all single-character substrings as palindromes. +3. Check substrings of length 2 and mark them if characters match. +4. Use the table to extend palindromes to longer substrings. +5. Keep track of the longest palindrome found. + +#### Implementation + +```python +def longestPalindrome(s: str) -> str: + n = len(s) + dp = [[False] * n for _ in range(n)] + longest = "" + + for i in range(n): + dp[i][i] = True + longest = s[i] + + for i in range(n-1): + if s[i] == s[i+1]: + dp[i][i+1] = True + longest = s[i:i+2] + + for length in range(3, n+1): + for i in range(n-length+1): + j = i + length - 1 + if s[i] == s[j] and dp[i+1][j-1]: + dp[i][j] = True + longest = s[i:j+1] + + return longest +``` + +### Complexity Analysis + +- **Time complexity**: $O(n^2)$ - We fill an `n * n` table. +- **Space complexity**: $O(n^2)$ - We use an `n * n` table to store the DP results. + +### Approach 3: Expand From Centers + +#### Intuition + +A palindrome mirrors around its center. We can expand around potential centers to find palindromes. + +#### Algorithm + +1. Consider each character and pair of characters as potential centers. +2. Expand around each center to find the longest palindrome. +3. Keep track of the longest palindrome found. + +#### Implementation + +```python +def longestPalindrome(s: str) -> str: + def expandAroundCenter(s, left, right): + while left >= 0 and right < len(s) and s[left] == s[right]: + left -= 1 + right += 1 + return s[left + 1:right] + + if not s: + return "" + + longest = s[0] + + for i in range(len(s)): + odd_palindrome = expandAroundCenter(s, i, i) + even_palindrome = expandAroundCenter(s, i, i + 1) + longest = max(longest, odd_palindrome, even_palindrome, key=len) + + return longest +``` + +### Complexity Analysis + +- **Time complexity**: $O(n^2)$ - We expand around each center, which takes $O(n)$ time. +- **Space complexity**: $O(1)$ - We use a constant amount of extra space. + +### Approach 4: Manacher's Algorithm + +#### Intuition + +Manacher's algorithm can find the longest palindromic substring in linear time. + +#### Algorithm + +1. Transform the string to handle even-length palindromes. +2. Use a helper array to store the length of the palindrome at each position. +3. Use the properties of palindromes and the helper array to efficiently find the longest palindrome. + +#### Implementation + +```python +def longestPalindrome(s: str) -> str: + if not s: + return "" + + # Transform s into new string with inserted boundaries + T = '#'.join(f"^{s}$") + n = len(T) + P = [0] * n + C = R = 0 + + for i in range(1, n - 1): + P[i] = (R > i) and min(R - i, P[2 * C - i]) + while T[i + P[i] + 1] == T[i - P[i] - 1]: + P[i] += 1 + if i + P[i] > R: + C, R = i, i + P[i] + + max_len, center_index = max((n, i) for i, n in enumerate(P)) + return s[(center_index - max_len) // 2: (center_index + max_len) // 2] +``` + +### Complexity Analysis + +- **Time complexity**: $O(n)$ - Manacher's algorithm runs in linear time. +- **Space complexity**: $O(n)$ - We use an array of length `n` to store the lengths of palindromes. + +### Conclusion + +We discussed four approaches to solve the "Longest Palindromic Substring" problem, each with varying complexities and trade-offs. The dynamic programming and center expansion approaches provide a good balance of simplicity and efficiency for practical use cases, while Manacher's algorithm offers the optimal theoretical performance. + +--- + +

Authors:

+ +
+{['Yashgabani845', 'ajay-dhangar'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0006-ZigZag-Conversion.md b/solutions/lc-solutions/0000-0099/0006-ZigZag-Conversion.md new file mode 100644 index 0000000..5455474 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0006-ZigZag-Conversion.md @@ -0,0 +1,236 @@ +--- +id: zigzag-conversion +title: Zigzag Conversion (LeetCode) +sidebar_label: 0006-Zigzag Conversion +tags: + - String + - Java + - C++ + - Python +description: Convert the given string into a zigzag pattern with a specified number of rows. +sidebar_position: 6 +--- + +## Problem Statement + +The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: + +```plaintext +P A H N +A P L S I I G +Y I R +``` + +And then read line by line: "PAHNAPLSIIGYIR" + +Write the code that will take a string and make this conversion given a number of rows: + +```python +string convert(string s, int numRows) +``` + +### Examples + +**Example 1:** + +Input: + +``` +s = "PAYPALISHIRING", numRows = 3 +``` + +Output: + +``` +"PAHNAPLSIIGYIR" +``` + +**Example 2:** + +Input: + +``` +s = "PAYPALISHIRING", numRows = 4 +``` + +Output: + +``` +"PINALSIGYAHRPI" +``` + +Explanation: + +``` +P I N +A L S I G +Y A H R +P I +``` + +**Example 3:** + +Input: + +``` +s = "A", numRows = 1 +``` + +Output: + +``` +"A" +``` + +### Constraints + +- 0 < s.length < 1001 +- s consists of English letters (lower-case and upper-case), ',' and '.'. +- 0 < numRows < 1000 + +## Intuition + +Just look at the top row what is the difference between each character, i.e., A and I, and I and Q = 8 (5*2-2 == number of rows * 2 - 2, the corner elements are excluded). Similarly for each row, i.e., B and J, the difference is 8. + +The interesting part comes when the character in the diagonal has to be added, but even this has a pattern: + +- There will be no character in between for row 0 and row n. +- There can be only one diagonal character, and the diagonal difference is original difference - 2 at each step or diff - (rowNumber\*2); + +## Approach + +1. Create an empty StringBuilder which is our answer. +2. Calculate the difference = numRows\*2 - 2. +3. Iterate over 0 to rowNumber in a for loop. +4. The first character will be row number or i (append to String). +5. Write a while loop in the above for loop: + - The first character will be row number or i (append to String). + - Calculate the diagonal difference if any and append to the String. + - Increase the index by diff and return ans. + +### Java Solution + +```java +class Solution { + public String convert(String s, int numRows) { + if (numRows == 1) { + return s; + } + + StringBuilder answer = new StringBuilder(); + int n = s.length(); + int diff = 2 * (numRows - 1); + int diagonalDiff = diff; + int secondIndex; + int index; + for (int i = 0; i < numRows; i++) { + index = i; + + while (index < n) { + answer.append(s.charAt(index)); + if (i != 0 && i != numRows - 1) { + diagonalDiff = diff-2*i; + secondIndex = index + diagonalDiff; + + if (secondIndex < n) { + answer.append(s.charAt(secondIndex)); + } + } + index += diff; + } + } + + return answer.toString(); + } +} +``` + +### C++ Solution + +```cpp +class Solution { +public: + string convert(string s, int numRows) { + if (numRows == 1) { + return s; + } + + stringstream answer; + int n = s.length(); + int diff = 2 * (numRows - 1); + int diagonalDiff = diff; + int secondIndex; + int index; + for (int i = 0; i < numRows; i++) { + index = i; + + while (index < n) { + answer << s[index]; + if (i != 0 && i != numRows - 1) { + diagonalDiff = diff-2*i; + secondIndex = index + diagonalDiff; + + if (secondIndex < n) { + answer << s[secondIndex]; + } + } + index += diff; + } + } + + return answer.str(); + } +}; +``` + +### Python Solution + +```python +class Solution: + def convert(self, s: str, numRows: int) -> str: + if numRows == 1: + return s + answer = '' + n = len(s) + diff = 2 * (numRows - 1) + diagonal_diff = diff + second_index = 0 + index = 0 + for i in range(numRows): + index = i + while index < n: + answer += s[index] + if i != 0 and i != numRows - 1: + diagonal_diff = diff - 2 * i + second_index = index + diagonal_diff + if second_index < n: + answer += s[second_index] + index += diff + return answer +``` + +### Complexity Analysis + +#### Approach 1: Iterative Approach + +- **Time Complexity**: $O(n)$, where n is the length of the input string `s`. We iterate through the entire string once. +- **Space Complexity**: $O(n)$, where n is the length of the input string `s`. We use a StringBuilder to store the output. + +#### Approach 2: Using StringBuilder Rows + +- **Time Complexity**: $O(n)$, where n is the length of the input string `s`. We iterate through the entire string once to fill the rows of the StringBuilder. +- **Space Complexity**:$O(n)$, where n is the length of the input string `s`. We use a StringBuilder to store the output. + +#### Approach 3: Direct Construction + +- **Time Complexity**: $O(n)$, where n is the length of the input string `s`. We iterate through the entire string once to construct the output string. +- **Space Complexity**: $O(n)$, where n is the length of the input string `s`. We use a StringBuilder to store the output. + +#### Approach 4: Using Mathematical Formula + +- **Time Complexity**: $O(n)$, where n is the length of the input string `s`. We iterate through the entire string once to construct the output string. +- **Space Complexity**: $O(n)$, where n is the length of the input string `s`. We use a StringBuilder to store the output. + +### Conclusion + +We explored four different approaches to solve the Zigzag Conversion problem, each offering a unique perspective and trade-offs in terms of simplicity and efficiency. All four approaches have a linear time complexity of $O(n)$, where n is the length of the input string `s`. The space complexity varies slightly among the approaches but remains linear in terms of the input size. diff --git a/solutions/lc-solutions/0000-0099/0007-Reverse-Integers.md b/solutions/lc-solutions/0000-0099/0007-Reverse-Integers.md new file mode 100644 index 0000000..39c0d54 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0007-Reverse-Integers.md @@ -0,0 +1,160 @@ +--- +id: reverse-integer +title: Reverse Integer(LeetCode) +sidebar_label: 0007-Reverse Integer +tags: + - Math + - Simulation +description: Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0. +sidebar_position: 7 +--- + +## Problem Statement +Given a signed 32-bit integer `x`, return `x` with its digits reversed. If reversing `x` causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0. + +### Examples + +**Example 1:** + +``` +Input: x = 123 +Output: 321 +``` + +**Example 2:** + +``` +Input: x = -123 +Output: -321 +``` + +**Example 3:** + +``` +Input: x = 120 +Output: 21 +``` + +### Constraints + +- `-2^31 <= x <= 2^31 - 1` + +## Solution + +### Approach 1: Pop and Push Digits & Check before Overflow + +#### Intuition + +We can build up the reverse integer one digit at a time while checking for overflow. + +#### Algorithm + +1. Repeatedly "pop" the last digit off of `x` and "push" it to the back of `rev`. +2. Before pushing, check if appending another digit would cause overflow. + +#### C++ Implementation + +```cpp +class Solution { +public: + int reverse(int x) { + int rev = 0; + while (x != 0) { + int pop = x % 10; + x /= 10; + if (rev > INT_MAX / 10 || (rev == INT_MAX / 10 && pop > 7)) + return 0; + if (rev < INT_MIN / 10 || (rev == INT_MIN / 10 && pop < -8)) + return 0; + rev = rev * 10 + pop; + } + return rev; + } +}; +``` + +#### Java Implementation + +```java +class Solution { + public int reverse(int x) { + int rev = 0; + while (x != 0) { + int pop = x % 10; + x /= 10; + if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) + return 0; + if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) + return 0; + rev = rev * 10 + pop; + } + return rev; + } +} +``` + +#### Python Implementation + +```python +def reverse(x: int) -> int: + rev = 0 + while x != 0: + pop = x % 10 + x //= 10 + if rev > 0 and (rev > 2**31 // 10 or (rev == 2**31 // 10 and pop > 7)): + return 0 + if rev < 0 and (rev < -2**31 // 10 or (rev == -2**31 // 10 and pop < -8)): + return 0 + rev = rev * 10 + pop + return rev +``` + +#### JavaScript Implementation + +```javascript +var reverse = function (x) { + let rev = 0; + while (x !== 0) { + let pop = x % 10; + x = (x - pop) / 10; + if ( + rev > Math.pow(2, 31) / 10 || + (rev == Math.pow(2, 31) / 10 && pop > 7) + ) + return 0; + if ( + rev < Math.pow(-2, 31) / 10 || + (rev == Math.pow(-2, 31) / 10 && pop < -8) + ) + return 0; + rev = rev * 10 + pop; + } + return rev; +}; +``` + +#### Python Class Implementation + +```python +class Solution: + def reverse(self, x: int) -> int: + sign = [1, -1][x < 0] + rev, x = 0, abs(x) + while x: + x, mod = divmod(x, 10) + rev = rev * 10 + mod + if rev > 2**31 - 1: + return 0 + return sign * rev +``` + +### Complexity Analysis + +- **Time Complexity**: $O(log(x))$. There are roughly log10(x) digits in `x`. +- **Space Complexity**: $O(1)$. + +### Conclusion + +We have successfully solved the "Reverse Integer" problem using a simple approach that reverses the digits of the given integer while handling overflow conditions. This solution provides an efficient way to reverse an integer without the need for any additional data structures. + +``` \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0008-String-to-Integer.md b/solutions/lc-solutions/0000-0099/0008-String-to-Integer.md new file mode 100644 index 0000000..3b4926c --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0008-String-to-Integer.md @@ -0,0 +1,145 @@ +--- +id: string-to-integer +title: String to Integer(LeetCode) +sidebar_label: 0008-String to Integer +tags: + - String + - Math +description: Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. +sidebar_position: 8 +--- + +## Problem Statement + +Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer. + +The algorithm for `myAtoi(string s)` is as follows: + +1. **Whitespace:** Ignore any leading whitespace (" "). +2. **Signedness:** Determine the sign by checking if the next character is '-' or '+', assuming positivity is neither present. +3. **Conversion:** Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0. +4. **Rounding:** If the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], then round the integer to remain in the range. Specifically, integers less than -2^31 should be rounded to -2^31, and integers greater than 2^31 - 1 should be rounded to 2^31 - 1. +5. Return the integer as the final result. + +### Examples + +**Example 1:** + +``` +Input: s = "42" +Output: 42 +``` + +**Example 2:** + +``` +Input: s = " -042" +Output: -42 +``` + +**Example 3:** + +``` +Input: s = "1337c0d3" +Output: 1337 +``` + +**Example 4:** + +``` +Input: s = "0-1" +Output: 0 +``` + +**Example 5:** + +``` +Input: s = "words and 987" +Output: 0 +``` + +### Constraints + +- 0 < s.length < 200 +- s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'. + +## Solution + +### Approach + +#### Intuition + +The function should iterate through the string, handling leading whitespaces, signs, and valid digits. It should accumulate the numerical value while checking for overflow conditions. + +#### Algorithm + +1. **Handling Empty String:** + - If `s.length() == 0`, return 0 as there's no numerical content. + +2. **Skipping Leading Whitespaces:** + - Iterate through characters (`s.charAt(i)`) as long as they are whitespaces (' ') and the index `i` is within the string bounds. This skips any leading whitespaces before the potential number. + +3. **Handling Optional Sign:** + - Check if the first non-whitespace character (`s.charAt(i)`) is a sign ('-' or '+'). + - If it's a minus sign, set the `sign` variable to -1 to indicate a negative number. + +4. **Converting Digits:** + - Iterate through characters as long as they are valid digits (between '0' and '9') and the index `i` is within the string bounds. + - Convert the current character (assumed to be a digit) to its corresponding integer value by subtracting the ASCII value of '0'. + +5. **Overflow Handling:** + - Check for potential overflow situations for positive numbers: + - Compare the current accumulated value (`ans`) with the maximum integer value (`max`) divided by 10 (considering the next digit) and the remainder (`max % 10`). + - If `ans` is already greater than the maximum divided by 10, or if `ans` is equal to the maximum divided by 10 and the current digit is greater than the remainder, it signifies overflow. + - In case of overflow, return the maximum positive value if the sign is positive, or the minimum negative value if the sign is negative. + +6. **Returning the Result:** + - After processing all valid digits, multiply the final `ans` by the `sign` (1 for positive, -1 for negative) and return it as the converted integer value. + +### Code + +#### Java Implementation + +```java +class Solution { + public int myAtoi(String s) { + int ans = 0; + int i = 0; + int sign = 1; + int max = Integer.MAX_VALUE; + int min = Integer.MIN_VALUE; + if (s.length() == 0) { + return 0; + } + while (i < s.length() && s.charAt(i) == ' ') { + i++; + } + if (i < s.length() && (s.charAt(i) == '-' || s.charAt(i) == '+')) { + if (s.charAt(i) == '-') { + sign = -1; + } + i++; + } + while (i < s.length() && s.charAt(i) - '0' <= 9 && s.charAt(i) - '0' >= 0) { + int digit = s.charAt(i) - '0'; + if (ans > max / 10 || (ans == max / 10 && digit > max % 10)) { + return (sign == 1) ? max : min; + } + ans = ans * 10 + digit; + i++; + } + return ans * sign; + } +} +``` + +### Complexity Analysis + +- **Time Complexity**: $O(n)$, where n is the length of the string `s`. +- **Space Complexity**: $O(1)$, due to the constant number of variables used. + +## Conclusion + +We have successfully implemented the `myAtoi` function to convert a string to a 32-bit signed integer. The solution handles leading whitespaces, signs, valid digits, and overflow conditions efficiently, providing a robust string-to-interger(atoi) + +``` \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0009-Palindrome-number.md b/solutions/lc-solutions/0000-0099/0009-Palindrome-number.md new file mode 100644 index 0000000..481852e --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0009-Palindrome-number.md @@ -0,0 +1,234 @@ +--- +id: palindrome-number +title: Palindrome Number (LeetCode) +sidebar_label: 0009 - Palindrome Number +tags: + - Math + - Palindrome +description: Given an integer x, return true if x is a palindrome, and false otherwise. +sidebar_position: 9 +--- + +## Problem Statement + +Given an integer `x`, return `true` if `x` is a palindrome, and `false` otherwise. + +### Examples + +**Example 1:** + +``` +Input: x = 121 +Output: true +Explanation: 121 reads as 121 from left to right and from right to left. +``` + +**Example 2:** + +``` +Input: x = -121 +Output: false +Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. +``` + +**Example 3:** + +``` +Input: x = 10 +Output: false +Explanation: Reads 01 from right to left. Therefore it is not a palindrome. +``` + +### Constraints + +- -2^31 < x < 2^31 - 1 + +## Solution + +### Approach 1: Reversing the Entire Number + +#### Intuition + +The intuition behind this approach is to reverse the entire input number and check if the reversed number is equal to the original number. If they are the same, then the number is a palindrome. + +#### Algorithm + +1. **Handling Special Cases:** + - If `x` is negative, return `false`, as negative numbers cannot be palindromes. +2. **Reversing the Number:** + - Initialize two variables: `reversed` and `temp`. + - Enter a loop that continues until `temp` becomes zero: + - Inside the loop: + - Extract the last digit of `temp` using modulo `%` and store it in `digit`. + - Reverse the number by multiplying `reversed` by 10 and adding the extracted `digit`. + - Divide `temp` by 10 to remove the last digit and move to the next iteration. +3. **Comparison:** + - Compare the reversed value `reversed` with the original input value `x`. + - If they are equal, return `true`; otherwise, return `false`. + +#### Code (C++) + +```cpp +class Solution { +public: + bool isPalindrome(int x) { + if (x < 0) { + return false; + } + + long long reversed = 0; + long long temp = x; + + while (temp != 0) { + int digit = temp % 10; + reversed = reversed * 10 + digit; + temp /= 10; + } + + return (reversed == x); + } +}; +``` + +#### Code (Java) + +```java +class Solution { + public boolean isPalindrome(int x) { + if (x < 0) { + return false; + } + + long reversed = 0; + long temp = x; + + while (temp != 0) { + int digit = (int) (temp % 10); + reversed = reversed * 10 + digit; + temp /= 10; + } + + return (reversed == x); + } +} +``` + +#### Code (Python) + +```python +class Solution: + def isPalindrome(self, x: int) -> bool: + if x < 0: + return False + + reversed_num = 0 + temp = x + + while temp != 0: + digit = temp % 10 + reversed_num = reversed_num * 10 + digit + temp //= 10 + + return reversed_num == x +``` + +### Approach 2: Reversing Half of the Number + +#### Intuition + +Instead of reversing the entire number, we can reverse only the last half of the number. This approach is more efficient in terms of time complexity and memory usage. + +#### Algorithm + +1. **Handling Special Cases:** + - If `x` is negative or ends with a zero, return `false`. +2. **Reversing the Second Half:** + - Initialize two variables: `reversed` and `original`. + - Enter a loop that continues until the first half of the digits (represented by `x`) becomes less than or equal to the reversed second half (`reversed`): + - Inside the loop: + - Extract the last digit of `x` using modulo `%` and add it to the `reversed` variable after multiplying it by 10 (shifting the existing digits to the left). + - Divide `x` by 10 to remove the last digit and move towards the center of the number. +3. **Comparison:** + - Compare the first half of the digits (`x`) with the reversed second half (`reversed`) to determine if the number is a palindrome: + - For an even number of digits, compare `x` with `reversed`. + - For an odd number of digits, compare `x` with `reversed / 10` (ignoring the middle digit). + - If the comparison holds true, return `true`; otherwise, return `false`. + +#### Code (C++) + +```cpp +class Solution { +public: + bool isPalindrome(int x) { + if (x < 0 || (x != 0 && x % 10 == 0)) { + return false; + } + + int reversed = 0; + int original = x; + + while (x > reversed) { + reversed = reversed * 10 + x % 10; + x /= 10; + } + + return (x == reversed) || (x == reversed / 10); + } +}; +``` + +#### Code (Java) + +```java +class Solution { + public boolean isPalindrome(int x) { + if (x < 0 || (x != 0 && x % 10 == 0)) { + return false; + } + + int reversed = 0; + int original = x; + + while (x > reversed) { + reversed = reversed * 10 + x % 10; + x /= 10; + } + + return (x == reversed) || (x == reversed / 10); + } +} +``` + +#### Code (Python) + +```python +class Solution: + def isPalindrome(self, x: int) -> bool: + if x < 0 or (x != 0 and x % 10 == 0): + return False + + reversed_num = 0 + original = x + + while x > reversed_num: + reversed_num = reversed_num * 10 + x % 10 + x //= 10 + + return x == reversed_num or x == reversed_num // 10 +``` + +## Complexity Analysis + +### Approach 1: Reversing the Entire Number + +- **Time Complexity**: $O(log10(x))$, where x is the input number. +- **Space Complexity**: $O(1)$. + +### Approach 2: Reversing Half of the Number + +- **Time Complexity**: $O(log10(x))$, where x is the input number. +- **Space Complexity**: $O(1)$. + +## Conclusion + +We have explored two approaches to determine whether an integer is a palindrome. Both approaches provide efficient solutions, with the second approach being slightly more optimized in terms of time and space complexity. These solutions offer different perspectives on how \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0010-Regular-Expression-Matching.md b/solutions/lc-solutions/0000-0099/0010-Regular-Expression-Matching.md new file mode 100644 index 0000000..f46d158 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0010-Regular-Expression-Matching.md @@ -0,0 +1,240 @@ +--- +id: regular-expression-matching +title: Regular Expression Matching (LeetCode) +sidebar_label: 0010 - Regular Expression Matching +tags: + - String + - Dynamic Programming + - Recursion +description: Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where '.' matches any single character and '*' matches zero or more of the preceding element. +sidebar_position: 10 +--- + +## Problem Description + +Given an input string `s` and a pattern `p`, implement regular expression matching with support for '.' and '*' where: + +- '.' Matches any single character. +- '*' Matches zero or more of the preceding element. + +The matching should cover the entire input string (not partial). + +### Examples + +**Example 1:** + +``` +Input: s = "aa", p = "a" +Output: false +Explanation: "a" does not match the entire string "aa". +``` + +**Example 2:** + +``` +Input: s = "aa", p = "a*" +Output: true +Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". +``` + +**Example 3:** + +``` +Input: s = "ab", p = ".*" +Output: true +Explanation: ".*" means "zero or more (*) of any character (.)". +``` + +### Constraints + +- 1 < s.length < 20 +- 1 < p.length < 20 +- `s` contains osnly lowercase English letters. +- `p` contains only lowercase English letters, '.', and '*'. +- It is guaranteed for each appearance of the character '*', there will be a previous valid character to match. + +## Solution + +### Approach 1: Recursion + +#### Intuition + +If there were no Kleene stars (the * wildcard character for regular expressions), the problem would be easier - we simply check from left to right if each character of the text matches the pattern. + +When a star is present, we may need to check many different suffixes of the text and see if they match the rest of the pattern. A recursive solution is a straightforward way to represent this relationship. + +#### Algorithm + +Without a Kleene star, our solution would look like this: + +```python +def match(text, pattern): + if not pattern: + return not text + first_match = bool(text) and pattern[0] in {text[0], "."} + return first_match and match(text[1:], pattern[1:]) +``` + +If a star is present in the pattern, it will be in the second position `pattern[1]`. Then, we may ignore this part of the pattern, or delete a matching character in the text. If we have a match on the remaining strings after any of these operations, then the initial inputs matched. + +#### Code (Java) + +```java +class Solution { + public boolean isMatch(String text, String pattern) { + if (pattern.isEmpty()) return text.isEmpty(); + boolean first_match = + (!text.isEmpty() && + (pattern.charAt(0) == text.charAt(0) || + pattern.charAt(0) == '.')); + + if (pattern.length() >= 2 && pattern.charAt(1) == '*') { + return ( + isMatch(text, pattern.substring(2)) || + (first_match && isMatch(text.substring(1), pattern)) + ); + } else { + return ( + first_match && isMatch(text.substring(1), pattern.substring(1)) + ); + } + } +} +``` + +#### Code (Python) + +```python +class Solution: + def isMatch(self, text: str, pattern: str) -> bool: + if not pattern: + return not text + + first_match = bool(text) and pattern[0] in {text[0], "."} + + if len(pattern) >= 2 and pattern[1] == "*": + return ( + self.isMatch(text, pattern[2:]) + or first_match + and self.isMatch(text[1:], pattern) + ) + else: + return first_match and self.isMatch(text[1:], pattern[1:]) +``` + +### Approach 2: Dynamic Programming + +#### Intuition + +As the problem has an optimal substructure, it is natural to cache intermediate results. We ask the question `dp(i, j)`: does `text[i:]` and `pattern[j:]` match? We can describe our answer in terms of answers to questions involving smaller strings. + +#### Top-Down Variation (Java) + +```java +enum Result { + TRUE, + FALSE, +} + +class Solution { + Result[][] memo; + + public boolean isMatch(String text, String pattern) { + memo = new Result[text.length() + 1][pattern.length() + 1]; + return dp(0, 0, text, pattern); + } + + public boolean dp(int i, int j, String text, String pattern) { + if (memo[i][j] != null) { + return memo[i][j] == Result.TRUE; + } + boolean ans; + if (j == pattern.length()) { + ans = i == text.length(); + } else { + boolean first_match = + (i < text.length() && + (pattern.charAt(j) == text.charAt(i) || + pattern.charAt(j) == '.')); + + if (j + 1 < pattern.length() && pattern.charAt(j + 1) == '*') { + ans = (dp(i, j + 2, text, pattern) || + (first_match && dp(i + 1, j, text, pattern))); + } else { + ans = first_match && dp(i + 1, j + 1, text, pattern); + } + } + memo[i][j] = ans ? Result.TRUE : Result.FALSE; + return ans; + } +} +``` + +#### Bottom-Up Variation (Java) + +```java +class Solution { + public boolean isMatch(String text, String pattern) { + boolean[][] dp = new boolean[text.length() + 1][pattern.length() + 1]; + dp[text.length()][pattern.length()] = true; + + for (int i = text.length(); i >= 0; i--) { + for (int j = pattern.length() - 1; j >= 0; j--) { + boolean first_match = + (i < text.length() && + (pattern.charAt(j) == text.charAt(i) || + pattern.charAt(j) == '.')); + if (j + 1 < pattern.length() && pattern.charAt(j + 1) == '*') { + dp[i][j] = dp[i][j + 2] || (first_match && dp[i + 1][j]); + } else { + dp[i][j] = first_match && dp[i + 1][j + 1]; + } + } + } + return dp[0][0]; + } +} +``` + +#### Code (Python) + +```python +class Solution: + def isMatch(self, text: str, pattern: str) -> bool: + memo = {} + + def dp(i: int, j: int) -> bool: + if (i, j) not in memo: + if j == len(pattern): + ans = i == len(text) + else: + first_match = i < len(text) and pattern[j] in {text[i], "."} + if j + 1 < len(pattern) and pattern[j + 1] == "*": + ans = dp(i, j + 2) or first_match and dp(i + 1, j) + else: + ans = first_match and dp(i + 1, j + 1) + + memo[i, j] = ans + return memo[i, j] + + return dp(0, 0) +``` +Complexity Analysis +Time Complexity +Let T, P be the lengths of the text and the pattern respectively. The work for every call to dp(i, j) for i=0,...,T; j=0,...,P is done once, and it is $O(1)$ work. Hence, the time complexity is $O(TP)$. + +Space Complexity +The only memory we use is the $O(TP)$ boolean entries in our cache. Hence, the space complexity is $O(TP)$ + + +Now, just as you asked, the last part should include the summary and links to the problem, solution, and profile. Let's add that: + +## Summary + +This problem involves implementing regular expression matching with support for '.' and '*', where '.' matches any single character and '*' matches zero or more of the preceding element. Two approaches are commonly used to solve this problem: + +1. **Recursion**: This approach involves a straightforward recursive solution. If there were no Kleene stars, checking from left to right if each character of the text matches the pattern would suffice. When a star is present, we may need to check many different suffixes of the text and see if they match the rest of the pattern. + +2. **Dynamic Programming**: As the problem has an optimal substructure, we can use dynamic programming to cache intermediate results. We can describe our answer in terms of answers to questions involving smaller strings. + + diff --git a/solutions/lc-solutions/0000-0099/0011-Container-with-most-water.md b/solutions/lc-solutions/0000-0099/0011-Container-with-most-water.md new file mode 100644 index 0000000..7e03d44 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0011-Container-with-most-water.md @@ -0,0 +1,166 @@ +--- +id: container-with-most-water +title: Container With Most Water (LeetCode) +sidebar_label: 0011 - Container With Most Water +tags: + - Array + - Two Pointers + - Greedy +description: Given n non-negative integers representing the heights of vertical lines, find the two lines that together with the x-axis form a container, such that the container contains the most water. +sidebar_position: 11 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :----------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------- | +| [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | [Container With Most Water Solution on LeetCode](https://leetcode.com/problems/container-with-most-water/solutions/3701708/best-method-c-java-python-beginner-friendly/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | + +## Problem Statement + +You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the ith line are `(i, 0)` and `(i, height[i])`. + +Find two lines that together with the x-axis form a container, such that the container contains the most water. + +Return the maximum amount of water a container can store. + +Notice that you may not slant the container. + +### Examples + +**Example 1:** + +![Example 1](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/17/question_11.jpg) + +- **Input**: `height = [1,8,6,2,5,4,8,3,7]` +- **Output**: `49` +- **Explanation**: The above vertical lines are represented by array `[1,8,6,2,5,4,8,3,7]`. In this case, the max area of water (blue section) the container can contain is `49`. + +**Example 2:** + +- **Input**: `height = [1,1]` +- **Output**: `1` + +### Constraints + +- `n == height.length` +- `2 <= n <= 10^5` +- `0 <= height[i] <= 10^4` + +## Solution + +### Approach + +#### Intuition + +The two-pointer technique starts with the widest container and moves the pointers inward based on the comparison of heights. Increasing the width of the container can only lead to a larger area if the height of the new boundary is greater. By moving the pointers towards the center, we explore containers with the potential for greater areas. + +#### Algorithm + +1. **Initialize the variables**: + - `left` to represent the left pointer, starting at the beginning of the container (index 0). + - `right` to represent the right pointer, starting at the end of the container (index `height.size() - 1`). + - `maxArea` to keep track of the maximum area found, initially set to 0. + +2. **Enter a loop using the condition `left < right`**, which means the pointers have not crossed each other yet. + +3. **Calculate the current area**: + - Use the `min` function to find the minimum height between the left and right pointers. + - Multiply the minimum height by the width, which is the difference between the indices of the pointers: `(right - left)`. + - Store this value in the `currentArea` variable. + +4. **Update the maximum area**: + - Use the `max` function to compare the `currentArea` with the `maxArea`. + - If the `currentArea` is greater than the `maxArea`, update `maxArea` with the `currentArea`. + +5. **Move the pointers inward**: + - Check if the height at the `left` pointer is smaller than the height at the `right` pointer. + - If so, increment the `left` pointer, moving it towards the center of the container. + - Otherwise, decrement the `right` pointer, also moving it towards the center. + +6. **Repeat steps 3 to 5** until the pointers meet (`left >= right`), indicating that all possible containers have been explored. + +7. **Return the `maxArea`**, which represents the maximum area encountered among all the containers. + +### Code + +#### C++ Implementation + +```cpp +class Solution { +public: + int maxArea(vector& height) { + int left = 0; + int right = height.size() - 1; + int maxArea = 0; + + while (left < right) { + int currentArea = min(height[left], height[right]) * (right - left); + maxArea = max(maxArea, currentArea); + + if (height[left] < height[right]) { + left++; + } else { + right--; + } + } + + return maxArea; + } +}; +``` + +#### Java Implementation + +```java +class Solution { + public int maxArea(int[] height) { + int left = 0; + int right = height.length - 1; + int maxArea = 0; + + while (left < right) { + int currentArea = Math.min(height[left], height[right]) * (right - left); + maxArea = Math.max(maxArea, currentArea); + + if (height[left] < height[right]) { + left++; + } else { + right--; + } + } + + return maxArea; + } +} +``` + +#### Python Implementation + +```python +class Solution: + def maxArea(self, height: List[int]) -> int: + left = 0 + right = len(height) - 1 + maxArea = 0 + + while left < right: + currentArea = min(height[left], height[right]) * (right - left) + maxArea = max(maxArea, currentArea) + + if height[left] < height[right]: + left += 1 + else: + right -= 1 + + return maxArea +``` + +### Complexity Analysis + +- **Time Complexity**: $O(n)$, where n is the length of the array `height`. We traverse the list only once using two pointers from both ends of the array towards the center. +- **Space Complexity**: $O(1)$, we use a constant amount of extra space for the pointers and variables. + +## Conclusion + +The two-pointer approach is efficient for solving the Container With Most Water problem, allowing us to explore all possible containers by adjusting the pointers based on the heights of the lines, ensuring that we find the container with the maximum possible area. diff --git a/solutions/lc-solutions/0000-0099/0012-integer-to-roman.md b/solutions/lc-solutions/0000-0099/0012-integer-to-roman.md new file mode 100644 index 0000000..5f032a1 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0012-integer-to-roman.md @@ -0,0 +1,154 @@ +--- +id: integer-to-roman +title: Integer to Roman (LeetCode) +sidebar_label: 0012 - Integer to Roman +tags: + - Hash Table + - Math + - String +description: Convert a given integer to a Roman numeral using specific rules for the Roman numeral system. +sidebar_position: 12 +--- + +## Problem Statement + +Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D`, and `M`. + +| Symbol | Value | +| :----- | :---- | +| I | 1 | +| V | 5 | +| X | 10 | +| L | 50 | +| C | 100 | +| D | 500 | +| M | 1000 | + +Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five, we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: + +- `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. +- `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. +- `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. + +Given an integer, convert it to a Roman numeral. + +### Examples + +**Example 1:** + +- **Input**: `num = 3749` +- **Output**: `"MMMDCCXLIX"` +- **Explanation**: + - 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) + - 700 = DCC as 500 (D) + 100 (C) + 100 (C) + - 40 = XL as 10 (X) less than 50 (L) + - 9 = IX as 1 (I) less than 10 (X) + +**Example 2:** + +- **Input**: `num = 58` +- **Output**: `"LVIII"` +- **Explanation**: + - 50 = L + - 8 = VIII + +**Example 3:** + +- **Input**: `num = 1994` +- **Output**: `"MCMXCIV"` +- **Explanation**: + - 1000 = M + - 900 = CM + - 90 = XC + - 4 = IV + +### Constraints + +- `1 <= num <= 3999` + +## Solution + +### Approach + +#### Intuition + +To convert an integer to a Roman numeral, we need to repeatedly subtract the largest possible Roman numeral value from the integer while appending the corresponding symbol to the result string. We use predefined pairs of integers and their Roman numeral representations to guide this process. + +#### Algorithm + +1. **Initialize the Roman numeral string**: + - Create an empty string `Roman` to store the resulting Roman numeral. + +2. **Create a list of integer-Roman pairs**: + - Use a list of pairs to store the values and symbols of Roman numerals in descending order of values. + +3. **Iterate through the list of pairs**: + - For each pair, check if the input integer is greater than or equal to the Roman numeral value. + - If it is, add the corresponding symbol to the `Roman` string and subtract the corresponding value from the input integer. + - Repeat this process until the input integer becomes zero. + +4. **Return the Roman numeral string**: + - After processing all the pairs, return the `Roman` string containing the converted Roman numeral. + +### Code + +#### C++ Implementation + +```cpp +class Solution { +public: + string intToRoman(int num) { + string Roman = ""; + vector> storeIntRoman = {{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}}; + for (int i = 0; i < storeIntRoman.size(); i++) { + while (num >= storeIntRoman[i].first) { + Roman += storeIntRoman[i].second; + num -= storeIntRoman[i].first; + } + } + return Roman; + } +}; +``` + +#### Java Implementation + +```java +class Solution { + public String intToRoman(int num) { + String Roman = ""; + int[][] storeIntRoman = {{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}}; + for (int i = 0; i < storeIntRoman.length; i++) { + while (num >= storeIntRoman[i][0]) { + Roman += storeIntRoman[i][1]; + num -= storeIntRoman[i][0]; + } + } + return Roman; + } +} +``` + +#### Python Implementation + +```python +class Solution: + def intToRoman(self, num: int) -> str: + Roman = "" + storeIntRoman = [[1000, "M"], [900, "CM"], [500, "D"], [400, "CD"], [100, "C"], [90, "XC"], [50, "L"], [40, "XL"], [10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"]] + for i in range(len(storeIntRoman)): + while num >= storeIntRoman[i][0]: + Roman += storeIntRoman[i][1] + num -= storeIntRoman[i][0] + return Roman +``` + +### Complexity Analysis + +- **Time Complexity**: $O(1)$ - The algorithm iterates through a constant number of values (13 in this case), so the time complexity is constant. +- **Space Complexity**: $O(1)$ - The amount of extra space used is constant, determined by the fixed size of the `storeIntRoman` vector. + +## Conclusion + +The provided solutions efficiently convert an integer to a Roman numeral by iterating through predefined Roman numeral values and symbols. This approach ensures that the conversion adheres to the rules of the Roman numeral system while maintaining constant time and space complexity. + diff --git a/solutions/lc-solutions/0000-0099/0013-roman-to-integer.md b/solutions/lc-solutions/0000-0099/0013-roman-to-integer.md new file mode 100644 index 0000000..5300e3f --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0013-roman-to-integer.md @@ -0,0 +1,180 @@ +--- +id: roman-to-integer +title: Roman to Integer (LeetCode) +sidebar_label: 0013 - Roman to Integer +tags: + - Hash Table + - Math + - String +description: Convert a given Roman numeral to an integer using specific rules for the Roman numeral system. +sidebar_position: 13 +--- + +## Problem Statement + +Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D`, and `M`. + +| Symbol | Value | +| :----- | :---- | +| I | 1 | +| V | 5 | +| X | 10 | +| L | 50 | +| C | 100 | +| D | 500 | +| M | 1000 | + +For example, 2 is written as `II` in Roman numeral, just two ones added together. 12 is written as `XII`, which is simply X + II. The number 27 is written as `XXVII`, which is XX + V + II. + +Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five, we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: + +- `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. +- `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. +- `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. + +Given a Roman numeral, convert it to an integer. + +### Examples + +**Example 1:** + +- **Input**: `s = "III"` +- **Output**: `3` +- **Explanation**: III = 3. + +**Example 2:** + +- **Input**: `s = "LVIII"` +- **Output**: `58` +- **Explanation**: L = 50, V= 5, III = 3. + +**Example 3:** + +- **Input**: `s = "MCMXCIV"` +- **Output**: `1994` +- **Explanation**: M = 1000, CM = 900, XC = 90, and IV = 4. + +### Constraints + +- `1 <= s.length <= 15` +- `s` contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M'). +- It is guaranteed that `s` is a valid Roman numeral in the range [1, 3999]. + +## Solution + +### Approach + +#### Intuition + +The key intuition is that in Roman numerals, when a smaller value appears before a larger value, it represents subtraction, while when a smaller value appears after or equal to a larger value, it represents addition. + +#### Explanation + +The unordered map `m` is created and initialized with mappings between Roman numeral characters and their corresponding integer values. For example, 'I' is mapped to 1, 'V' to 5, 'X' to 10, and so on. + +The variable `ans` is initialized to 0. This variable will accumulate the final integer value of the Roman numeral string. + +The for loop iterates over each character in the input string `s`. + +For example, for the string "IX": +- When `i` is 0, the current character `s[i]` is 'I'. Since there is a next character ('X'), and the value of 'I' (1) is less than the value of 'X' (10), the condition `m[s[i]] < m[s[i+1]]` is true. In this case, we subtract the value of the current character from `ans`. +- When `i` is 1, the current character `s[i]` is 'X'. This is the last character in the string, so there is no next character to compare. In this case, we add the value of the current character to `ans`. + +For the string "XI": +- When `i` is 0, the current character `s[i]` is 'X'. Since there is a next character ('I'), and the value of 'X' (10) is greater than the value of 'I' (1), the condition `m[s[i]] < m[s[i+1]]` is false. In this case, we add the value of the current character to `ans`. +- When `i` is 1, the current character `s[i]` is 'I'. This is the last character in the string, so there is no next character to compare. In this case, we add the value of the current character to `ans`. + +After the for loop, the accumulated value in `ans` represents the integer conversion of the Roman numeral string, and it is returned as the result. + +### Code + +#### C++ Implementation + +```cpp +class Solution { +public: + int romanToInt(string s) { + unordered_map m = { + {'I', 1}, + {'V', 5}, + {'X', 10}, + {'L', 50}, + {'C', 100}, + {'D', 500}, + {'M', 1000} + }; + + int ans = 0; + for (int i = 0; i < s.length(); i++) { + if (i < s.length() - 1 && m[s[i]] < m[s[i+1]]) { + ans -= m[s[i]]; + } else { + ans += m[s[i]]; + } + } + return ans; + } +}; +``` + +#### Java Implementation + +```java +class Solution { + public int romanToInt(String s) { + Map m = new HashMap<>(); + m.put('I', 1); + m.put('V', 5); + m.put('X', 10); + m.put('L', 50); + m.put('C', 100); + m.put('D', 500); + m.put('M', 1000); + + int ans = 0; + for (int i = 0; i < s.length(); i++) { + if (i < s.length() - 1 && m.get(s.charAt(i)) < m.get(s.charAt(i+1))) { + ans -= m.get(s.charAt(i)); + } else { + ans += m.get(s.charAt(i)); + } + } + return ans; + } +} +``` + +#### Python Implementation + +```python +class Solution: + def romanToInt(self, s: str) -> int: + m = { + 'I': 1, + 'V': 5, + 'X': 10, + 'L': 50, + 'C': 100, + 'D': 500, + 'M': 1000 + } + + ans = 0 + for i in range(len(s)): + if i < len(s) - 1 and m[s[i]] < m[s[i+1]]: + ans -= m[s[i]] + else: + ans += m[s[i]] + + return ans +``` + +### Complexity Analysis + +- **Time Complexity**: $O(n)$ - The algorithm iterates through each character in the input string once, where `n` is the length of the string. +- **Space Complexity**: $O(1)$ - The amount of extra space used is constant, determined by the fixed size of the `m` map. + +## Conclusion + +The provided solutions efficiently convert a Roman numeral to an integer by iterating through the characters and using a map to handle the conversion based on the rules of the Roman numeral system. This approach ensures that the conversion adheres to the rules while maintaining linear time complexity and constant space complexity. + diff --git a/solutions/lc-solutions/0000-0099/0014-longest-comman-prefix.md b/solutions/lc-solutions/0000-0099/0014-longest-comman-prefix.md new file mode 100644 index 0000000..3bfd0e7 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0014-longest-comman-prefix.md @@ -0,0 +1,266 @@ +--- +id: Longest Comman Prefix +title: Longest Comman Prefix (LeetCode) +sidebar_label: 0014-Longest Comman Prefix +tags: + - Hash Table + - Math + - String +description: finds logest comman prefix for a given string. +sidebar_position: 14 +--- + +## Problem Statement + +Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". + +#### Example 1: + +- Input: `strs = ["flower","flow","flight"]` +- Output: `"fl"` + +#### Example 2: + +- Input: `strs = ["dog","racecar","car"]` +- Output: `""` +- Explanation: There is no common prefix among the input strings. + +### Constraints: + +- `1 <= strs.length <= 200` +- `0 <= strs[i].length <= 200` +- `strs[i]` consists of only lowercase English letters. + +## Approaches and Solutions + +### Approach 1: Horizontal Scanning + +**Intuition:** +Iteratively find the longest common prefix (LCP) of the first two strings, then find the LCP of the result with the next string, and so on. + +**Algorithm:** +1. Initialize the prefix as the first string in the list. +2. Iterate through the rest of the strings. +3. Update the prefix by comparing it with the current string. +4. If at any point the prefix becomes an empty string, return `""`. + +**Time Complexity:** $O(S)$, where S is the sum of all characters in all strings. + +**Space Complexity:** $O(1)$, since we use only constant extra space. + +**C++ Implementation:** +```cpp +class Solution { +public: + string longestCommonPrefix(vector& strs) { + if (strs.empty()) return ""; + string prefix = strs[0]; + for (int i = 1; i < strs.size(); i++) { + while (strs[i].find(prefix) != 0) { + prefix = prefix.substr(0, prefix.length() - 1); + if (prefix.empty()) return ""; + } + } + return prefix; + } +}; +``` + +**Java Implementation:** +```java +class Solution { + public String longestCommonPrefix(String[] strs) { + if (strs.length == 0) return ""; + String prefix = strs[0]; + for (int i = 1; i < strs.length; i++) { + while (strs[i].indexOf(prefix) != 0) { + prefix = prefix.substring(0, prefix.length() - 1); + if (prefix.isEmpty()) return ""; + } + } + return prefix; + } +} +``` + +**Python Implementation:** +```python +class Solution: + def longestCommonPrefix(self, strs: List[str]) -> str: + if len(strs) == 0: + return "" + prefix = strs[0] + for i in range(1, len(strs)): + while strs[i].find(prefix) != 0: + prefix = prefix[0 : len(prefix) - 1] + if prefix == "": + return "" + return prefix +``` + +### Approach 2: Vertical Scanning + +**Intuition:** +Compare characters from top to bottom on the same column (i.e., same character index across all strings) before moving on to the next column. + +**Algorithm:** +1. Iterate through the characters of the first string. +2. Compare the current character with the corresponding character of the other strings. +3. If they all match, continue; otherwise, return the common prefix up to the current column. + +**Time Complexity:** $O(S)$, where S is the sum of all characters in all strings. + +**Space Complexity:** $O(1)$, since we use only constant extra space. + +**C++ Implementation:** +```cpp +class Solution { +public: + string longestCommonPrefix(vector& strs) { + if (strs.empty()) return ""; + for (int i = 0; i < strs[0].size(); i++) { + char c = strs[0][i]; + for (int j = 1; j < strs.size(); j++) { + if (i == strs[j].size() || strs[j][i] != c) + return strs[0].substr(0, i); + } + } + return strs[0]; + } +}; +``` + +**Java Implementation:** +```java +class Solution { + public String longestCommonPrefix(String[] strs) { + if (strs == null || strs.length == 0) return ""; + for (int i = 0; i < strs[0].length(); i++) { + char c = strs[0].charAt(i); + for (int j = 1; j < strs.length; j++) { + if (i == strs[j].length() || strs[j].charAt(i) != c) + return strs[0].substring(0, i); + } + } + return strs[0]; + } +} +``` + +**Python Implementation:** +```python +class Solution: + def longestCommonPrefix(self, strs: List[str]) -> str: + if strs == None or len(strs) == 0: + return "" + for i in range(len(strs[0])): + c = strs[0][i] + for j in range(1, len(strs)): + if i == len(strs[j]) or strs[j][i] != c: + return strs[0][0:i] + return strs[0] +``` + +### Approach 3: Divide and Conquer + +**Intuition:** +Use the divide and conquer technique, where the problem is divided into two subproblems, find their LCP, and then combine their results. + +**Algorithm:** +1. Divide the list of strings into two halves. +2. Recursively find the LCP of each half. +3. Merge the results by finding the LCP of the two halves. + +**Time Complexity:** $O(S)$, where S is the sum of all characters in all strings. + +**Space Complexity:** $O(m log n)$, where m is the length of the shortest string and n is the number of strings. + +**C++ Implementation:** +```cpp +class Solution { +public: + string longestCommonPrefix(vector& strs) { + if (strs.empty()) return ""; + return longestCommonPrefix(strs, 0, strs.size() - 1); + } + +private: + string longestCommonPrefix(vector& strs, int l, int r) { + if (l == r) { + return strs[l]; + } else { + int mid = (l + r) / 2; + string lcpLeft = longestCommonPrefix(strs, l, mid); + string lcpRight = longestCommonPrefix(strs, mid + 1, r); + return commonPrefix(lcpLeft, lcpRight); + } + } + + string commonPrefix(string left, string right) { + int min = std::min(left.length(), right.length()); + for (int i = 0; i < min; i++) { + if (left[i] != right[i]) return left.substr(0, i); + } + return left.substr(0, min); + } +}; +``` + +**Java Implementation:** +```java +class Solution { + public String longestCommonPrefix(String[] strs) { + if (strs == null || strs.length == 0) return ""; + return longestCommonPrefix(strs, 0, strs.length - 1); + } + + private String longestCommonPrefix(String[] strs, int l, int r) { + if (l == r) { + return strs[l]; + } else { + int mid = (l + r) / 2; + String lcpLeft = longestCommonPrefix(strs, l, mid); + String lcpRight = longestCommonPrefix(strs, mid + 1, r); + return commonPrefix(lcpLeft, lcpRight); + } + } + + private String commonPrefix(String left, String right) { + int min = Math.min(left.length(), right.length()); + for (int i = 0; i < min; i++) { + if (left.charAt(i) != right.charAt(i)) return left.substring(0, i); + } + return left.substring(0, min); + } +} +``` + +**Python Implementation:** +```python +class Solution: + def longestCommonPrefix(self, strs): + if not strs: + return "" + + def LCP(left, right): + min_len = min(len(left), len(right)) + for i in range(min_len): + if left[i] != right[i]: + return left[:i] + return left[:min_len] + + def divide_and_conquer(strs, l, r): + if l == r: + return strs[l] + else: + mid = (l + r) // 2 + lcpLeft = divide_and_conquer(strs, l, mid) + lcpRight = divide_and_conquer(strs, mid + 1, r) + return LCP(lcpLeft, lcpRight) + + return divide_and_conquer(strs, 0, len(strs) - 1) +``` + +## Conclusion + +We've discussed three different approaches to solving the problem of finding the longest common prefix among an array of strings. Each approach has its own merits, and the choice of which to use depends on the specific requirements and constraints of the problem. The provided implementations in C++, Java, and Python cover horizontal scanning, vertical scanning, and divide and conquer methods. \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0015-3sum.md b/solutions/lc-solutions/0000-0099/0015-3sum.md new file mode 100644 index 0000000..7c436ec --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0015-3sum.md @@ -0,0 +1,335 @@ +--- +id: 3Sum +title: 3Sum (LeetCode) +sidebar_label: 0015-3Sum +tags: + - Hash Table + - Math + - String + - python + - javascript + - java + - c++ +description: find the number of triplets with given sum . +sidebar_position: 15 +--- + +## Problem Description + +Given an integer array `nums`, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`. + +Notice that the solution set must not contain duplicate triplets. + +### Example 1: + +- **Input:** `nums = [-1,0,1,2,-1,-4]` +- **Output:** `[[-1,-1,2],[-1,0,1]]` +- **Explanation:** + - `nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0`. + - `nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0`. + - `nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0`. + - The distinct triplets are `[-1,0,1]` and `[-1,-1,2]`. + - Notice that the order of the output and the order of the triplets does not matter. + +### Example 2: + +- **Input:** `nums = [0,1,1]` +- **Output:** `[]` +- **Explanation:** The only possible triplet does not sum up to 0. + +### Example 3: + +- **Input:** `nums = [0,0,0]` +- **Output:** `[[0,0,0]]` +- **Explanation:** The only possible triplet sums up to 0. + +### Constraints + +- `3 <= nums.length <= 3000` +- `-10^5 <= nums[i] <= 10^5` + +## Approach + +To solve the problem, we can use the two-pointer technique combined with sorting. Here is the step-by-step approach: + +1. **Sort the Input Array:** + + - Sort the array to enable the two-pointer technique and to handle duplicates easily. + +2. **Iterate Through the Array:** + + - Use a loop to fix the first element (`i`). + - Use two pointers (`j` starting from `i + 1` and `k` starting from the end of the array) to find pairs that, along with the element at `i`, sum to zero. + +3. **Avoid Duplicates:** + + - Skip duplicate elements to avoid duplicate triplets. + +4. **Calculate and Adjust Pointers:** + + - Calculate the sum of the elements at `i`, `j`, and `k`. + - If the sum is zero, add the triplet to the result and move both pointers. + - If the sum is greater than zero, move the `k` pointer left to reduce the sum. + - If the sum is less than zero, move the `j` pointer right to increase the sum. + +5. **Return the Result:** + - Return the list of unique triplets. + +### Solution Code + +#### Python + +```python +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + res = [] + nums.sort() + + for i in range(len(nums)): + if i > 0 and nums[i] == nums[i-1]: + continue + + j = i + 1 + k = len(nums) - 1 + + while j < k: + total = nums[i] + nums[j] + nums[k] + + if total > 0: + k -= 1 + elif total < 0: + j += 1 + else: + res.append([nums[i], nums[j], nums[k]]) + j += 1 + + while j < k and nums[j] == nums[j-1]: + j += 1 + + return res +``` + +#### JavaScript + +```javascript +var threeSum = function (nums) { + let res = []; + nums.sort((a, b) => a - b); + + for (let i = 0; i < nums.length; i++) { + if (i > 0 && nums[i] === nums[i - 1]) { + continue; + } + + let j = i + 1; + let k = nums.length - 1; + + while (j < k) { + let total = nums[i] + nums[j] + nums[k]; + + if (total > 0) { + k--; + } else if (total < 0) { + j++; + } else { + res.push([nums[i], nums[j], nums[k]]); + j++; + + while (j < k && nums[j] === nums[j - 1]) { + j++; + } + } + } + } + return res; +}; +``` + +#### Java + +```java +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +class Solution { + public List> threeSum(int[] nums) { + List> res = new ArrayList<>(); + Arrays.sort(nums); + + for (int i = 0; i < nums.length; i++) { + if (i > 0 && nums[i] == nums[i-1]) { + continue; + } + + int j = i + 1; + int k = nums.length - 1; + + while (j < k) { + int total = nums[i] + nums[j] + nums[k]; + + if (total > 0) { + k--; + } else if (total < 0) { + j++; + } else { + res.add(Arrays.asList(nums[i], nums[j], nums[k])); + j++; + + while (j < k && nums[j] == nums[j-1]) { + j++; + } + } + } + } + return res; + } +} +``` + +#### C++ + +```cpp +#include +#include + +using namespace std; + +class Solution { +public: + vector> threeSum(vector& nums) { + vector> res; + sort(nums.begin(), nums.end()); + + for (int i = 0; i < nums.size(); i++) { + if (i > 0 && nums[i] == nums[i-1]) { + continue; + } + + int j = i + 1; + int k = nums.size() - 1; + + while (j < k) { + int total = nums[i] + nums[j] + nums[k]; + + if (total > 0) { + k--; + } else if (total < 0) { + j++; + } else { + res.push_back({nums[i], nums[j], nums[k]}); + j++; + + while (j < k && nums[j] == nums[j-1]) { + j++; + } + } + } + } + return res; + } +}; +``` + +### Step-by-Step Algorithm + +1. **Initialize Result List:** + + - Create an empty list `res` to store the triplets whose sum is zero. + + ```python + res = [] + ``` + +2. **Sort the Input Array :** + + - Sort the input array `nums` in non-decreasing order. + + ```python + nums.sort() + ``` + +3. **Iterate Through the Array :** + + - Iterate through each element in the sorted array `nums`. + + ```python + for i in range(len(nums)): + ``` + +4. **Skip Duplicate Elements :** + + - Check if the current element is a duplicate of the previous element and skip it if it is. + + ```python + if i > 0 and nums[i] == nums[i-1]: + continue + ``` + +5. **Initialize Pointers :** + + - Initialize two pointers `j` and `k` to point to the elements next to the current element `i` and at the end of the array, respectively. + + ```python + j = i + 1 + k = len(nums) - 1 + ``` + +6. **Two-Pointer Approach :** + + - Use a two-pointer approach with pointers `j` and `k` to find triplets whose sum equals zero. + + ```python + while j < k: + ``` + +7. **Calculate Total :** + + - Calculate the total sum of the current triplet. + + ```python + total = nums[i] + nums[j] + nums[k] + ``` + +8. **Adjust Pointers Based on Total :** + + - If the total sum is greater than zero, decrement the `k` pointer to decrease the total sum. + + ```python + if total > 0: + k -= 1 + ``` + + - If the total sum is less than zero, increment the `j` pointer to increase the total sum. + + ```python + elif total < 0: + j += 1 + ``` + + - If the total sum equals zero, add the triplet `[nums[i], nums[j], nums[k]]` to the result list `res`. + + ```python + else: + res.append([nums[i], nums[j], nums[k]]) + j += 1 + ``` + +9. **Handle Duplicate Triplets :** + + - Increment the `j` pointer to skip any duplicate elements. + + ```python + while j < k and nums[j] == nums[j-1]: + j += 1 + ``` + +10. **Return Result :** + - Return the list `res` containing all the unique triplets whose sum is zero. + ```python + return res + ``` + +This algorithm efficiently finds all unique trip + +lets in the given array `nums` whose sum equals zero using a two-pointer approach. It avoids duplicate triplets by skipping duplicate elements during traversal. diff --git a/solutions/lc-solutions/0000-0099/0016-3sum-closest.md b/solutions/lc-solutions/0000-0099/0016-3sum-closest.md new file mode 100644 index 0000000..bf22079 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0016-3sum-closest.md @@ -0,0 +1,232 @@ +--- +id: 3Sum Closest +title: 3Sum losest (LeetCode) +sidebar_label: 0016-3Sum Closest +tags: + - Array + - two pointers + - Sorting +description: Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. +sidebar_position: 16 +--- + +## Problem Description + +Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`. + +Return the sum of the three integers. + +You may assume that each input would have exactly one solution. + +### Example 1 + +- **Input:** `nums = [-1,2,1,-4]`, `target = 1` +- **Output:** `2` +- **Explanation:** The sum that is closest to the target is `2` (`-1 + 2 + 1 = 2`). + +### Example 2 + +- **Input:** `nums = [0,0,0]`, `target = 1` +- **Output:** `0` +- **Explanation:** The sum that is closest to the target is `0` (`0 + 0 + 0 = 0`). + +### Constraints + +- `3 <= nums.length <= 500` +- `-1000 <= nums[i] <= 1000` +- `-10^4 <= target <= 10^4` + +### Topics + +- Array +- Two Pointers +- Sorting + +### Intuition + +- Sorting combined with the two-pointer technique. + +### Complexity + +- **Time Complexity:** $O(N \log N + N^2)$ approx $O(N^2)$ +- **Space Complexity:** $(O(1))$ + +### Solution Code and Explanation + +#### C++ + +```cpp +#include +#include +#include + +class Solution { +public: + int threeSumClosest(std::vector& nums, int target) { + int mindiff = INT_MAX; + int n = nums.size(); + std::sort(nums.begin(), nums.end()); + int ans = 0; + + for (int i = 0; i < n; i++) { + int j = i + 1; + int k = n - 1; + + while (j < k) { + int sum = nums[i] + nums[j] + nums[k]; + + if (sum == target) return target; + else { + int diff = std::abs(target - sum); + + if (diff < mindiff) { + mindiff = diff; + ans = sum; + } + } + + if (sum < target) j++; + else if (sum > target) k--; + } + } + return ans; + } +}; +``` + +#### Java + +```java +import java.util.Arrays; + +class Solution { + public int threeSumClosest(int[] nums, int target) { + int mindiff = Integer.MAX_VALUE; + int n = nums.length; + Arrays.sort(nums); + int ans = 0; + + for (int i = 0; i < n; i++) { + int j = i + 1; + int k = n - 1; + + while (j < k) { + int sum = nums[i] + nums[j] + nums[k]; + + if (sum == target) return target; + + else { + int diff = Math.abs(target - sum); + + if (diff < mindiff) { + mindiff = diff; + ans = sum; + } + } + + if (sum < target) j++; + else if (sum > target) k--; + } + } + return ans; + } +} +``` + +#### Python + +```python +from typing import List + +class Solution: + def threeSumClosest(self, nums: List[int], target: int) -> int: + mindiff = float('inf') + nums.sort() + n = len(nums) + ans = 0 + + for i in range(n): + j = i + 1 + k = n - 1 + + while j < k: + sum_val = nums[i] + nums[j] + nums[k] + + if sum_val == target: + return target + else: + diff = abs(target - sum_val) + + if diff < mindiff: + mindiff = diff + ans = sum_val + + if sum_val < target: + j += 1 + elif sum_val > target: + k -= 1 + + return ans +``` + +### Explanation + +1. **Sort the Array:** + + - The array `nums` is sorted to facilitate the two-pointer technique. + + ```python + nums.sort() + ``` + +2. **Initialize Variables:** + + - `mindiff` is initialized to infinity to keep track of the minimum difference found. + - `ans` is initialized to 0 to store the closest sum. + +3. **Iterate Through the Array:** + + - For each element `nums[i]`, use two pointers `j` and `k` to find the other two elements. + + ```python + for i in range(n): + j = i + 1 + k = n - 1 + ``` + +4. **Two-Pointer Approach:** + + - Calculate the sum of `nums[i]`, `nums[j]`, and `nums[k]`. + - If the sum equals the target, return the target immediately. + - If the sum does not equal the target, calculate the difference between the target and the sum. + - If the difference is less than `mindiff`, update `mindiff` and `ans`. + - Adjust the pointers `j` and `k` based on whether the sum is less than or greater than the target. + + ```python + while j < k: + sum_val = nums[i] + nums[j] + nums[k] + + if sum_val == target: + return target + else: + diff = abs(target - sum_val) + + if diff < mindiff: + mindiff = diff + ans = sum_val + + if sum_val < target: + j += 1 + elif sum_val > target: + k -= 1 + ``` + +5. **Return the Closest Sum:** + - After checking all possible triplets, return the closest sum found. + ```python + return ans + ``` + +### Conclusion + +The above solution efficiently finds the sum of three integers in the array `nums` that is closest to the given `target`. It employs a combination of sorting and the two-pointer technique to achieve a time complexity of $(O(N^2))$ and a space complexity of $(O(1))$. This ensures that the algorithm can handle input sizes up to the upper limit specified in the constraints efficiently. diff --git a/solutions/lc-solutions/0000-0099/0017-letter-combination.md b/solutions/lc-solutions/0000-0099/0017-letter-combination.md new file mode 100644 index 0000000..f2eb4ec --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0017-letter-combination.md @@ -0,0 +1,217 @@ +--- +id: letter-combination +title: Letter Combinations of a Phone Number (LeetCode) +sidebar_label: 0017 - letter-combination +tags: + - Array + - Backtracking + - String +description: "Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent." +--- + +## Problem Description + +Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. + +A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. + + +### Examples + +**Example 1:** + +``` +Input +digits = " +Output +["ad","ae","af","bd","be","bf","cd","ce","cf"] + +``` +**Example 2:** + +``` +Input: digits = "" +Output: [] +``` +**Example 3:** + +``` +Input: digits = "2" +Output: ["a","b","c"] +``` +### Constraints + +- `0 <= digits.length <= 4` +- `digits[i] is a digit in the range ['2', '9']` + + +## Solution for Letter combination of phone number + +### Intuition +Using backtracking to create all possible combinations + + + + +### Complexity Analysis + +#### Time Complexity: $O(3^n)$ + +#### Space Complexity: $O(N)$ + + +## Approach + +- This is based on a Python solution. Other implementations might differ a bit. + +- Initialize an empty list `res` to store the generated combinations. + +- Check if the `digits` string is empty. If it is, return an empty list since there are no digits to process. + +- Create a dictionary `digit_to_letters` that maps each digit from '2' to '9' to the corresponding letters on a phone keypad. + +- Define a recursive function `backtrack(idx, comb)` that takes two parameters: + - `idx`: The current index of the digit being processed in the `digits` string. + - `comb`: The current combination being formed by appending letters. + +- Inside the `backtrack` function: + - Check if `idx` is equal to the length of the `digits` string. If it is, it means a valid combination has been formed, so append the current `comb` to the `res` list. + - If not, iterate through each letter corresponding to the digit at `digits[idx]` using the `digit_to_letters` dictionary. + - For each letter, recursively call `backtrack` with `idx + 1` to process the next digit and `comb + letter` to add the current letter to the combination. + +- Initialize the `res` list. + +- Start the initial call to `backtrack` with `idx` set to 0 and an empty string as `comb`. This will start the process of generating combinations. + +- After the recursive calls have been made, return the `res` list containing all the generated combinations. + +- The algorithm works by iteratively exploring all possible combinations of letters that can be formed from the given input digits. It uses a recursive approach to generate combinations, building them one letter at a time. The base case for the recursion is when all digits have been processed, at which point a combination is complete and added to the `res` list. The backtracking nature of the algorithm ensures that all possible combinations are explored. + + +### Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +public: + int cherryPickup(std::vector>& grid) { + int N = grid.size(); + std::vector> dp(N, std::vector(N, INT_MIN)); + dp[0][0] = grid[0][0]; + + for (int t = 1; t <= 2 * N - 2; ++t) { + std::vector> dp2(N, std::vector(N, INT_MIN)); + + for (int i = std::max(0, t - (N - 1)); i <= std::min(N - 1, t); ++i) { + for (int j = std::max(0, t - (N - 1)); j <= std::min(N - 1, t); ++j) { + if (grid[i][t - i] == -1 || grid[j][t - j] == -1) { + continue; + } + int val = grid[i][t - i]; + if (i != j) { + val += grid[j][t - j]; + } + for (int pi = i - 1; pi <= i; ++pi) { + for (int pj = j - 1; pj <= j; ++pj) { + if (pi >= 0 && pj >= 0) { + dp2[i][j] = std::max(dp2[i][j], dp[pi][pj] + val); + } + } + } + } + } + dp = std::move(dp2); + } + return std::max(0, dp[N - 1][N - 1]); + } +}; + + +``` + + + + +```java +class Solution { + public int cherryPickup(int[][] grid) { + int N = grid.length; + int[][] dp = new int[N][N]; + for (int[] row: dp) { + Arrays.fill(row, Integer.MIN_VALUE); + } + dp[0][0] = grid[0][0]; + + for (int t = 1; t <= 2*N - 2; ++t) { + int[][] dp2 = new int[N][N]; + for (int[] row: dp2) { + Arrays.fill(row, Integer.MIN_VALUE); + } + + for (int i = Math.max(0, t - (N - 1)); i <= Math.min(N - 1, t); ++i) { + for (int j = Math.max(0, t - (N - 1)); j <= Math.min(N - 1, t); ++j) { + if (grid[i][t - i] == -1 || grid[j][t - j] == -1) { + continue; + } + int val = grid[i][t-i]; + if (i != j) { + val += grid[j][t - j]; + } + for (int pi = i - 1; pi <= i; ++pi) { + for (int pj = j - 1; pj <= j; ++pj) { + if (pi >= 0 && pj >= 0) { + dp2[i][j] = Math.max(dp2[i][j], dp[pi][pj] + val); + } + } + } + } + } + dp = dp2; + } + return Math.max(0, dp[N - 1][N - 1]); + } +} +``` + + + + + +```python +class Solution(object): + def cherryPickup(self, grid): + N = len(grid) + dp = [[float('-inf')] * N for _ in xrange(N)] + dp[0][0] = grid[0][0] + for t in xrange(1, 2 * N - 1): + dp2 = [[float('-inf')] * N for _ in xrange(N)] + for i in xrange(max(0, t - (N - 1)), min(N - 1, t) + 1): + for j in xrange(max(0, t - (N - 1)), min(N - 1, t) + 1): + if grid[i][t - i] == -1 or grid[j][t - j] == -1: + continue + val = grid[i][t - i] + if i != j: + val += grid[j][t - j] + dp2[i][j] = max(dp[pi][pj] + val + for pi in (i - 1, i) for pj in (j - 1, j) + if pi >= 0 and pj >= 0) + dp = dp2 + return max(0, dp[N - 1][N - 1]) +``` + + + + + +## References + +- **LeetCode Problem**: [Letter combinatino of Phone number](https://leetcode.com/problems/cherry-pickup/description/) + +- **Solution Link**: [letter combination of phone number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/solutions/5125020/video-simple-solution/) diff --git a/solutions/lc-solutions/0000-0099/0018-4Sum.md b/solutions/lc-solutions/0000-0099/0018-4Sum.md new file mode 100644 index 0000000..b143c01 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0018-4Sum.md @@ -0,0 +1,263 @@ +--- +id: four-sum +title: 4Sum (LeetCode) +sidebar_label: 0018-4Sum +tags: + - Two Pointers +description: "Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]]" +sidebar_position: 18 +--- + +## Problem Description + +Given an array `nums` of `n` integers, return an array of all the unique quadruplets `[nums[a], nums[b], nums[c], nums[d]]` such that: + +- `0 <= a, b, c, d < n` +- `a, b, c, and d are distinct` +- `nums[a] + nums[b] + nums[c] + nums[d] == target` + +You may return the answer in any order. + +### Example 1 + +- **Input:** `nums = [1,0,-1,0,-2,2], target = 0` +- **Output:** `[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]` + +### Example 2 + +- **Input:** `nums = [2,2,2,2,2], target = 8` +- **Output:** `[[2,2,2,2]]` + +### Constraints + +- $1 \leq \text{nums.length} \leq 200$ +- $-10^9 \leq \text{nums[i]} \leq 10^9$ +- $-10^9 \leq \text{target} \leq 10^9$ + +### Approach + +To solve the problem, we can use the following approach: + +1. Sort the input array in non-decreasing order. +2. Traverse the array from 0 to n-3 and use a variable i to keep track of the first element in the quadruplet. +3. If the current element is the same as the previous element, skip it to avoid duplicates. +4. Traverse the array from i+1 to n-2 and use a variable j to keep track of the second element in the quadruplet. +5. If the current element is the same as the previous element, skip it to avoid duplicates. +6. Use two pointers, left = j+1 and right = n-1, to find the other two elements in the quadruplet whose sum equals the target value. +7. If the sum of the four elements is less than the target value, increment left pointer. +8. If the sum of the four elements is greater than the target value, decrement right pointer. +9. If the sum of the four elements is equal to the target value, add the quadruplet to the result and increment left and decrement right pointers. +10. Skip duplicate values of left and right pointers to avoid duplicate quadruplets. +11. Return the result. + +### Solution Code + +#### Python + +```python +class Solution(object): + def fourSum(self, nums, target): + quadruplets = [] + n = len(nums) + # Sorting the array + nums.sort() + for i in range(n - 3): + # Skip duplicates + if i > 0 and nums[i] == nums[i - 1]: + continue + for j in range(i + 1, n - 2): + # Skip duplicates + if j > i + 1 and nums[j] == nums[j - 1]: + continue + left = j + 1 + right = n - 1 + while left < right: + sum = nums[i] + nums[j] + nums[left] + nums[right] + if sum < target: + left += 1 + elif sum > target: + right -= 1 + else: + quadruplets.append([nums[i], nums[j], nums[left], nums[right]]) + while left < right and nums[left] == nums[left + 1]: + left += 1 + while left < right and nums[right] == nums[right - 1]: + right -= 1 + left += 1 + right -= 1 + return result + + while left < right and nums[left] == nums[left + 1]: + left += 1 + while left < right and nums[right] == nums[right - 1]: + right -= 1 + + left += 1 + right -= 1 + elif sum_ < target: + left += 1 + else: + right -= 1 + + return result +``` + +#### C++ + +```cpp +class Solution { +public: + vector> fourSum(vector& nums, int target) { + vector> quadruplets; + int n = nums.size(); + // Sorting the array + sort(nums.begin(), nums.end()); + for (int i = 0; i < n - 3; i++) { + // Skip duplicates + if (i > 0 && nums[i] == nums[i - 1]){ + continue; + } + for (int j = i + 1; j < n - 2; j++) { + // Skip duplicates + if (j > i + 1 && nums[j] == nums[j - 1]){ + continue; + } + int left = j + 1; + int right = n - 1; + while (left < right) { + long long sum = static_cast(nums[i]) + nums[j] + nums[left] + nums[right]; + if (sum < target) { + left++; + } else if (sum > target) { + right--; + } else { + quadruplets.push_back({nums[i], nums[j], nums[left], nums[right]}); + // Skip duplicates + while (left < right && nums[left] == nums[left + 1]){ + left++; + } + while (left < right && nums[right] == nums[right - 1]){ + right--; + } + left++; + right--; + } + } + } + } + return quadruplets; + } +}; +``` + +#### Java + +```java +class Solution { + public List> fourSum(int[] nums, int target) { + List> quadruplets = new ArrayList<>(); + int n = nums.length; + // Sorting the array + Arrays.sort(nums); + for (int i = 0; i < n - 3; i++) { + // Skip duplicates + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + for (int j = i + 1; j < n - 2; j++) { + // Skip duplicates + if (j > i + 1 && nums[j] == nums[j - 1]) { + continue; + } + int left = j + 1; + int right = n - 1; + while (left < right) { + long sum = (long) nums[i] + nums[j] + nums[left] + nums[right]; + if (sum < target) { + left++; + } else if (sum > target) { + right--; + } else { + quadruplets.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right])); + // Skip duplicates + while (left < right && nums[left] == nums[left + 1]) { + left++; + } + while (left < right && nums[right] == nums[right - 1]) { + right--; + } + left++; + right--; + } + } + } + } + return quadruplets; + } +} +``` + +#### Javascript + +``` +var fourSum = function(nums, target) { + nums.sort((a, b) => a - b); + const quadruplets = []; + const n = nums.length; + for (let i = 0; i < n - 3; i++) { + if (i > 0 && nums[i] === nums[i - 1]) { + continue; + } + for (let j = i + 1; j < n - 2; j++) { + if (j > i + 1 && nums[j] === nums[j - 1]) { + continue; + } + let left = j + 1; + let right = n - 1; + while (left < right) { + const sum = BigInt(nums[i]) + BigInt(nums[j]) + BigInt(nums[left]) + BigInt(nums[right]); + if (sum < target) { + left++; + } else if (sum > target) { + right--; + } else { + quadruplets.push([nums[i], nums[j], nums[left], nums[right]]); + while (left < right && nums[left] === nums[left + 1]) { + left++; + } + while (left < right && nums[right] === nums[right - 1]) { + right--; + } + left++; + right--; + } + } + } + } + return quadruplets; +}; +``` + +### Conclusion + +The given solution sorts the input list and uses a nested loop structure with two pointers to find all unique quadruplets that sum up to the target. By using a set to store the quadruplets, it ensures that duplicates are avoided. The solution efficiently narrows down potential combinations by adjusting the pointers based on the current sum relative to the target. This approach is effective for generating the required output while maintaining uniqueness. + +## Step-by-Step Algorithm + +1. **Input Validation**: Check if the array is null or has fewer than 4 elements. If so, return an empty list. +2. **Sort the Array**: Sort the input array `nums`. +3. **Outer Loop**: Iterate over the array with index `i` from `0` to `n-4`. + - Skip duplicate elements by checking if `nums[i] == nums[i-1]` (for `i > 0`). +4. **Inner Loop**: For each `i`, iterate with index `j` from `i+1` to `n-3`. + - Skip duplicate elements by checking if `nums[j] == nums[j-1]` (for `j > i+1`). +5. **Two Pointers**: Initialize two pointers `left = j+1` and `right = n-1`. +6. **Finding Quadruplets**: + - While `left < right`: + - Calculate the sum of the quadruplet: `sum = nums[i] + nums[j] + nums[left] + nums[right]`. + - If the sum equals the target: + - Add `[nums[i], nums[j], nums[left], nums[right]]` to the result. + - Move `left` to the right, skipping duplicates. + - Move `right` to the left, skipping duplicates. + - If the sum is less than the target, move `left` to the right. + - If the sum is greater than the target, move `right` to the left. +7. **Return the Result**: After processing all elements, return the list of quadruplets. diff --git a/solutions/lc-solutions/0000-0099/0019-remove-nth-node-from-end-of-list.md b/solutions/lc-solutions/0000-0099/0019-remove-nth-node-from-end-of-list.md new file mode 100644 index 0000000..8102591 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0019-remove-nth-node-from-end-of-list.md @@ -0,0 +1,170 @@ +--- +id: remove-nth-node-from-end-of-list +title: Remove nth node from end of list (LeetCode) +sidebar_label: 0019-remove-nth-node-from-end-of-list +tags: + - Two Pointers + - Linked List +description: "Given the head of a linked list, remove the nth node from the end of the list and return its head." +sidebar_position: 19 +--- + +## Problem Description + +Given the head of a linked list, remove the nth node from the end of the list and return its head. + +### Example 1 + +- **Input:** `head = [1,2,3,4,5], n = 2` +- **Output:** `[1,2,3,5]` + +### Example 2 + +- **Input:** `head = [1], n = 1` +- **Output:** `[]` + +### Example 3 + +- **Input:** `head = [1,2], n = 1` +- **Output:** `[1]` + +### Constraints + +- The number of nodes in the list is sz. +- $1 <= sz <= 30$ +- $0 <= Node.val <= 100$ +- $1 <= n <= sz$ + +## Approach + +1. Calculate the size of the Single Linked List. We need to travel to the prev node of the node to be removed thus we perform reduce size by n +2. If the node to be removed is the first node (size == 0) then we can simply return the next node of head since it will be null if the list has only one node. +3. Traverse till the prev node using a loop again +4. Skip the next node by linking the prev node to the next of next node. If not present, assign null. +5. Finally return the head. + +## Solution Code + +#### Python + +```python +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution(object): + def removeNthFromEnd(self, head, n): + length = self.findLength(head) + i, traverseTill = 0, length - n - 1 + if traverseTill == -1: + return head.next + curr = head + while i < traverseTill: + curr = curr.next + i += 1 + curr.next = curr.next.next + return head + + def findLength(self, head): + count = 0 + if head is None: + return count + curr = head + while curr is not None: + count += 1 + curr = curr.next + return count +``` + +#### Java + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + int length = findLength(head); + int i = 0, traverseTill = length - n - 1; + if(traverseTill == -1) return head.next; + ListNode curr = head; + while(i < traverseTill){ + curr = curr.next; + i++; + } + curr.next = curr.next.next; + return head; + } + public int findLength(ListNode head){ + int count = 0; + if(head == null) return count; + ListNode curr = head; + while(curr != null){ + count++; + curr = curr.next; + } + return count; + } +} +``` + +#### C++ + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + int length = 0; + ListNode* curr = head; + + // Calculate the length of the linked list + while (curr != nullptr) { + length++; + curr = curr->next; + } + + // Find the position to remove + int traverseTill = length - n - 1; + int i = 0; + curr = head; + + // If the head needs to be removed + if (traverseTill == -1) { + head = head->next; + delete curr; + return head; + } + + // Traverse to the node before the one to be removed + while (i < traverseTill) { + curr = curr->next; + i++; + } + + // Remove the nth node from the end + ListNode* temp = curr->next; + curr->next = curr->next->next; + delete temp; + + return head; + } +}; +``` diff --git a/solutions/lc-solutions/0000-0099/0020-valid-parentheses.md b/solutions/lc-solutions/0000-0099/0020-valid-parentheses.md new file mode 100644 index 0000000..63d451f --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0020-valid-parentheses.md @@ -0,0 +1,172 @@ +--- +id: valid-parentheses +title: Valid Parentheses (LeetCode) +sidebar_label: 0020-valid-parentheses +tags: + - Stack + +description: "Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid." +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :--------------------------------------------------------------------------------- | :------------ | :--------------- | +| [Valid Parentheses ](https://leetcode.com/problems/valid-parentheses/description/) | + +### Problem Description + +Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. + +An input string is valid if: + +1. Open brackets must be closed by the same type of brackets. +2. Open brackets must be closed in the correct order. +3. Every close bracket has a corresponding open bracket of the same type. + +### Examples + +#### Example 1 + +- **Input:** `s = "()"` +- **Output:** true + +#### Example 2 + +- **Input:** `s = "()[]{}"` +- **Output:** true + +#### Example 3 + +- **Input:** `s = "(]"` +- **Output:** false + +### Constraints + +- $1 \leq \text{s.length} \leq 104$ +- s consists of parentheses only '()[]{}'. + +### Approach + +Here is the step-by-step approach of the algorithm: + +1. Initialize an empty stack. +2. Traverse the input string character by character. +3. If the current character is an opening bracket `(i.e., '(', '{', '[')`, push it onto the stack. +4. If the current character is a closing bracket `(i.e., ')', '}', ']')`, check if the stack is empty. If it is empty, return false, because the closing bracket does not have a corresponding opening bracket. Otherwise, pop the top element from the stack and check if it matches the current closing bracket. If it does not match, return false, because the brackets are not valid. +5. After traversing the entire input string, if the stack is empty, return true, because all opening brackets have been matched with their corresponding closing brackets. Otherwise, return false, because some opening brackets have not been matched with their corresponding closing brackets. + +### Solution Code + +#### Python + +```python +class Solution(object): + def isValid(self, s): + stack = [] # create an empty stack to store opening brackets + for c in s: # loop through each character in the string + if c in '([{': # if the character is an opening bracket + stack.append(c) # push it onto the stack + else: # if the character is a closing bracket + if not stack or \ + (c == ')' and stack[-1] != '(') or \ + (c == '}' and stack[-1] != '{') or \ + (c == ']' and stack[-1] != '['): + return False # the string is not valid, so return false + stack.pop() # otherwise, pop the opening bracket from the stack + return not stack # if the stack is empty, all opening brackets have been matched with their corresponding closing brackets, + # so the string is valid, otherwise, there are unmatched opening brackets, so return false +``` + +#### C++ + +```cpp +class Solution { +public: + bool isValid(string s) { + stack st; // create an empty stack to store opening brackets + for (char c : s) { // loop through each character in the string + if (c == '(' || c == '{' || c == '[') { // if the character is an opening bracket + st.push(c); // push it onto the stack + } else { // if the character is a closing bracket + if (st.empty() || // if the stack is empty or + (c == ')' && st.top() != '(') || // the closing bracket doesn't match the corresponding opening bracket at the top of the stack + (c == '}' && st.top() != '{') || + (c == ']' && st.top() != '[')) { + return false; // the string is not valid, so return false + } + st.pop(); // otherwise, pop the opening bracket from the stack + } + } + return st.empty(); // if the stack is empty, all opening brackets have been matched with their corresponding closing brackets, + // so the string is valid, otherwise, there are unmatched opening brackets, so return false + } +}; +``` + +#### Java + +```java +class Solution { + public boolean isValid(String s) { + // Create an empty stack to keep track of opening brackets + Stack stack = new Stack(); + + // Loop through every character in the string + for (char c : s.toCharArray()) { + // If the character is an opening bracket, push it onto the stack + if (c == '(' || c == '[' || c == '{') { + stack.push(c); + } else { // If the character is a closing bracket + // If the stack is empty, there is no matching opening bracket, so return false + if (stack.isEmpty()) { + return false; + } + // Otherwise, get the top of the stack and check if it's the matching opening bracket + char top = stack.peek(); + if ((c == ')' && top == '(') || (c == ']' && top == '[') || (c == '}' && top == '{')) { + // If it is, pop the opening bracket from the stack + stack.pop(); + } else { // Otherwise, the brackets don't match, so return false + return false; + } + } + } + // If the stack is empty, all opening brackets have been closed, so return true + // Otherwise, there are unmatched opening brackets, so return false + return stack.isEmpty(); + } +} +``` + +#### Javascript + +```javascript +/** + * @param {string} s + * @return {boolean} + */ +var isValid = function (s) { + let stack = []; // create an empty stack to store opening brackets + for (let c of s) { + // loop through each character in the string + if (c === "(" || c === "{" || c === "[") { + // if the character is an opening bracket + stack.push(c); // push it onto the stack + } else { + // if the character is a closing bracket + if ( + !stack.length || // if the stack is empty or + (c === ")" && stack[stack.length - 1] !== "(") || // the closing bracket doesn't match the corresponding opening bracket at the top of the stack + (c === "}" && stack[stack.length - 1] !== "{") || + (c === "]" && stack[stack.length - 1] !== "[") + ) { + return false; // the string is not valid, so return false + } + stack.pop(); // otherwise, pop the opening bracket from the stack + } + } + return !stack.length; // if the stack is empty, all opening brackets have been matched with their corresponding closing brackets, + // so the string is valid, otherwise, there are unmatched opening brackets, so return false +}; +``` diff --git a/solutions/lc-solutions/0000-0099/0021-Merge-two-sorted-lists.md b/solutions/lc-solutions/0000-0099/0021-Merge-two-sorted-lists.md new file mode 100644 index 0000000..a3141a2 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0021-Merge-two-sorted-lists.md @@ -0,0 +1,174 @@ +--- +id: merge-two-sorted-lists +title: Merge Two Sorted Lists (LeetCode) +sidebar_label: 0021-MergeTwoSortedLists +tags: + - Linked List + - Two Pointers +description: Given two sorted linked lists, merge them into a single sorted linked list. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/merge-two-sorted-lists/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +### Problem Description + +Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists. + +### Examples + +#### Example 1 + +- **Input:** list1 = [1,2,4], list2 = [1,3,4] +- **Output:** [1,1,2,3,4,4] + +#### Example 2 + +- **Input:** list1 = [], list2 = [] +- **Output:** [] + +#### Example 3 + +- **Input:** list1 = [], list2 = [0] +- **Output:** [0] + +### Constraints + +- The number of nodes in both lists is in the range [0, 50]. +- `-100 <= Node.val <= 100` +- Both `list1` and `list2` are sorted in non-decreasing order. + +### Approach + +To solve the problem, we can use the following approach: + +1. **Initialize Pointers:** + - Use a dummy node to form the new list and a tail pointer to keep track of the end of the merged list. + +2. **Iterate Through the Lists:** + - Compare the values of the current nodes in both lists and attach the smaller node to the merged list. + - Move the pointer forward in the list from which the node was taken. + +3. **Attach Remaining Nodes:** + - Once one of the lists is exhausted, attach the remaining nodes of the other list to the merged list. + +4. **Return Result:** + - The merged list is pointed to by the dummy node's next pointer. + +### Solution Code + +#### Python + +```python +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +class Solution: + def mergeTwoLists(self, list1, list2): + # Dummy node to form the new list + dummy = ListNode(0) + # Tail pointer for the new list + tail = dummy + + # While both lists are non-empty, compare the values and attach the smaller node to the new list + while list1 is not None and list2 is not None: + if list1.val <= list2.val: + tail.next = list1 + list1 = list1.next + else: + tail.next = list2 + list2 = list2.next + tail = tail.next + + # If either list is not empty, attach the remainder to the new list + if list1 is not None: + tail.next = list1 + else: + tail.next = list2 + + # The dummy node's next pointer points to the head of the merged list + return dummy.next +``` + +#### C++ + +```cpp +class Solution { +public: + ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { + // Dummy node to form the new list + ListNode dummy(0); + // Tail pointer for the new list + ListNode* tail = &dummy; + + // While both lists are non-empty, compare the values and attach the smaller node to the new list + while (list1 != nullptr && list2 != nullptr) { + if (list1->val <= list2->val) { + tail->next = list1; + list1 = list1->next; + } else { + tail->next = list2; + list2 = list2->next; + } + tail = tail->next; + } + + // If either list is not empty, attach the remainder to the new list + if (list1 != nullptr) { + tail->next = list1; + } else { + tail->next = list2; + } + + // The dummy node's next pointer points to the head of the merged list + return dummy.next; + } +}; +``` + +#### Java + +```java +class Solution { + public ListNode mergeTwoLists(ListNode list1, ListNode list2) { + // Dummy node to form the new list + ListNode dummy = new ListNode(0); + // Tail pointer for the new list + ListNode tail = dummy; + + // While both lists are non-empty, compare the values and attach the smaller node to the new list + while (list1 != null && list2 != null) { + if (list1.val <= list2.val) { + tail.next = list1; + list1 = list1.next; + } else { + tail.next = list2; + list2 = list2.next; + } + tail = tail.next; + } + + // If either list is not empty, attach the remainder to the new list + if (list1 != null) { + tail.next = list1; + } else { + tail.next = list2; + } + + // The dummy node's next pointer points to the head of the merged list + return dummy.next; + } +} +``` + +### Conclusion + +The above solution efficiently merges two sorted linked lists into a single sorted linked list. It employs a straightforward approach to compare the elements from both lists and attach the smaller element to the merged list. This ensures that the merged list maintains the sorted order of the input lists, providing a simple yet effective approach to solving the problem of merging two sorted linked lists. + + diff --git a/solutions/lc-solutions/0000-0099/0022-Generate-parentheses.md b/solutions/lc-solutions/0000-0099/0022-Generate-parentheses.md new file mode 100644 index 0000000..290e286 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0022-Generate-parentheses.md @@ -0,0 +1,432 @@ +--- + +id: generate-parentheses +title: Generate Parentheses Solution +sidebar_label: 0022-Generate-Parentheses +tags: + - Generate Parentheses + - Backtracking + - Dynamic Programming + - String + - LeetCode + - JavaScript + - TypeScript +description: "This is a solution to the Generate Parentheses problem on LeetCode." +--- + +In this page, we will solve the Generate Parentheses problem using different approaches: backtracking and dynamic programming. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +Given `n` pairs of parentheses, write a function to generate all combinations of well-formed parentheses. + +### Examples + +**Example 1:** + +```plaintext +Input: n = 3 +Output: ["((()))","(()())","(())()","()(())","()()()"] +``` + +**Example 2:** + +```plaintext +Input: n = 1 +Output: ["()"] +``` + +### Constraints + +- `1 <= n <= 8` + +**Follow up:** Can you come up with an algorithm that uses backtracking to generate all combinations of well-formed parentheses? + +--- + +## Solution for Generate Parentheses Problem + +### Intuition and Approach + +The problem can be solved using backtracking or dynamic programming. The backtracking approach is more intuitive and efficient for this problem. + + + + +### Approach 1: Backtracking + +The backtracking approach involves generating all possible combinations of parentheses and then filtering out the valid ones. Instead of generating all combinations, we can generate only valid combinations by ensuring that at any point in the recursion, the number of closing parentheses does not exceed the number of opening parentheses. + +#### Implementation + +```jsx live +function generateParentheses() { + const n = 3; + + const generateParenthesis = function(n) { + const result = []; + + const backtrack = (cur, open, close) => { + if (cur.length === n * 2) { + result.push(cur); + return; + } + + if (open < n) { + backtrack(cur + '(', open + 1, close); + } + if (close < open) { + backtrack(cur + ')', open, close + 1); + } + }; + + backtrack('', 0, 0); + return result; + }; + + const result = generateParenthesis(n); + return ( +
+

+ Input: n = {n} +

+

+ Output: {JSON.stringify(result)} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function generateParenthesis(n) { + const result = []; + + const backtrack = (cur, open, close) => { + if (cur.length === n * 2) { + result.push(cur); + return; + } + + if (open < n) { + backtrack(cur + '(', open + 1, close); + } + if (close < open) { + backtrack(cur + ')', open, close + 1); + } + }; + + backtrack('', 0, 0); + return result; + } + ``` + + + + + ```typescript + function generateParenthesis(n: number): string[] { + const result: string[] = []; + + const backtrack = (cur: string, open: number, close: number): void => { + if (cur.length === n * 2) { + result.push(cur); + return; + } + + if (open < n) { + backtrack(cur + '(', open + 1, close); + } + if (close < open) { + backtrack(cur + ')', open, close + 1); + } + }; + + backtrack('', 0, 0); + return result; + } + ``` + + + + + ```python + class Solution: + def generateParenthesis(self, n: int) -> List[str]: + result = [] + + def backtrack(cur: str, open: int, close: int): + if len(cur) == n * 2: + result.append(cur) + return + + if open < n: + backtrack(cur + '(', open + 1, close) + if close < open: + backtrack(cur + ')', open, close + 1) + + backtrack('', 0, 0) + return result + ``` + + + + + ```java + class Solution { + public List generateParenthesis(int n) { + List result = new ArrayList<>(); + + backtrack(result, "", 0, 0, n); + return result; + } + + private void backtrack(List result, String cur, int open, int close, int n) { + if (cur.length() == n * 2) { + result.add(cur); + return; + } + + if (open < n) { + backtrack(result, cur + "(", open + 1, close, n); + } + if (close < open) { + backtrack(result, cur + ")", open, close + 1, n); + } + } + } + ``` + + + + + ```cpp + class Solution { + public: + vector generateParenthesis(int n) { + vector result; + backtrack(result, "", 0, 0, n); + return result; + } + + private: + void backtrack(vector& result, string cur, int open, int close, int n) { + if (cur.length() == n * 2) { + result.push_back(cur); + return; + } + + if (open < n) { + backtrack(result, cur + "(", open + 1, close, n); + } + if (close < open) { + backtrack(result, cur + ")", open, close + 1, n); + } + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(4^n / \sqrt{n})$$ +- Space Complexity: $$O(4^n / \sqrt{n})$$ +- Where `n` is the number of pairs of parentheses. +- The time complexity is based on the number of valid combinations which is the nth Catalan number, $$C_n = \frac{1}{n+1}\binom{2n}{n} \approx \frac{4^n}{n\sqrt{n}}$$. +- The space complexity is determined by the number of valid combinations as well. + +
+ + +### Approach 2: Dynamic Programming + +We can also solve this problem using dynamic programming. The idea is to use the results of smaller subproblems to build the solution for the given `n`. + +#### Implementation + +```jsx live +function generateParentheses() { + const n = 3; + + const generateParenthesis = function(n) { + const dp = Array.from({ length: n + 1 }, () => []); + dp[0].push(''); + + for (let i = 1; i <= n; i++) { + for (let j = 0; j < i; j++) { + for (const left of dp[j]) { + for (const right of dp[i - 1 - j]) { + dp[i].push(`(${left})${right}`); + } + } + } + } + + return dp[n]; + }; + + const result = generateParenthesis(n); + return ( +
+

+ Input: n = {n} +

+

+ Output: {JSON.stringify(result)} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function generateParenthesis(n) { + const dp = Array.from({ length: n + 1 }, () => []); + dp[0].push(''); + + for (let i = 1; i <= n; i++) { + for (let j = 0; j < i; j++) { + for (const left of dp[j]) { + for (const right of dp[i - 1 - j]) { + dp[i].push(`(${left})${right}`); + } + } + } + } + + return dp[n]; + } + ``` + + + + + + + ```typescript + function generateParenthesis(n: number): string[] { + const dp: string[][] = Array.from({ length: n + 1 }, () => []); + dp[0].push(''); + + for (let i = 1; i <= n; i++) { + for (let j = 0; j < i; j++) { + for (const left of dp[j]) { + for (const right of dp[i - 1 - j]) { + dp[i].push(`(${left})${right}`); + } + } + } + } + + return dp[n]; + } + ``` + + + + + ```python + class Solution: + def generateParenthesis(self, n: int) -> List[str]: + dp = [[] for _ in range(n + 1)] + dp[0].append('') + + for i in range(1, n + 1): + for j in range(i): + for left in dp[j]: + for right in dp[i - 1 - j]: + dp[i].append(f'({left}){right}') + + return dp[n] + ``` + + + + + ```java + class Solution { + public List generateParenthesis(int n) { + List> dp = new ArrayList<>(); + for (int i = 0; i <= n; i++) { + dp.add(new ArrayList<>()); + } + dp.get(0).add(""); + + for (int i = 1; i <= n; i++) { + for (int j = 0; j < i; j++) { + for (String left : dp.get(j)) { + for (String right : dp.get(i - 1 - j)) { + dp.get(i).add("(" + left + ")" + right); + } + } + } + } + + return dp.get(n); + } + } + ``` + + + + + ```cpp + class Solution { + public: + vector generateParenthesis(int n) { + vector> dp(n + 1); + dp[0].push_back(""); + + for (int i = 1; i <= n; i++) { + for (int j = 0; j < i; j++) { + for (const string& left : dp[j]) { + for (const string& right : dp[i - 1 - j]) { + dp[i].push_back("(" + left + ")" + right); + } + } + } + } + + return dp[n]; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(4^n / \sqrt{n})$$ +- Space Complexity: $$O(4^n / \sqrt{n})$$ +- Where `n` is the number of pairs of parentheses. +- The time complexity is based on the number of valid combinations which is the nth Catalan number, $$C_n = \frac{1}{n+1}\binom{2n}{n} \approx \frac{4^n}{n\sqrt{n}}$$. +- The space complexity is determined by the number of valid combinations as well. + +
+
+ +:::tip Note + +By using both backtracking and dynamic programming approaches, we can efficiently solve the Generate Parentheses problem. The backtracking approach is more straightforward and intuitive, while the dynamic programming approach leverages previously computed results to build the solution. + +::: +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/generate-parentheses/) +- **Solution Link:** [Generate Parantheses Solution on LeetCode](https://leetcode.com/problems/generate-parentheses/solutions/5016750/easy-recursion-solution-in-c-100-beats-full-expanation-with-example/) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + +--- \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0023-merge-k-sorted.md b/solutions/lc-solutions/0000-0099/0023-merge-k-sorted.md new file mode 100644 index 0000000..0dadac5 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0023-merge-k-sorted.md @@ -0,0 +1,230 @@ +--- + +id: merge-k-sorted-list +title: Merge k Sorted Lists +sidebar_label: 0023-Merge-k-sorted-list +tags: + - Linked List + - Divide and Conquer + - Heap (Priority Queue) + - Merge Sort +description: "The given code provides a solution to merge k sorted linked lists into one sorted linked list. The approach used is a divide-and-conquer strategy." +--- + + + + +## Problem Description + +You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. + +Merge all the linked-lists into one sorted linked-list and return it. + +### Examples + +**Example 1:** + +```plaintext +Input: lists = [[1,4,5],[1,3,4],[2,6]] +Output: [1,1,2,3,4,4,5,6] +``` +Explanation: + - The linked-lists are: +``` +[ 1->4->5,1->3->4,2->6] +``` +merging them into one sorted list: +`1->1->2->3->4->4->5->6` + +**Example 2:** + +```plaintext +Input: lists = [[]] +Output:[] +``` + +### Constraints + +- `k == lists.length` +- `0 <= k <= 104` +- `0 <= lists[i].length <= 500` +- `-104 <= lists[i][j] <= 104` +- `lists[i] is sorted in ascending order` +- `he sum of lists[i].length will not exceed 104.` + + + +--- + +# Solution to Merge K Sorted Linked Lists + +The given code provides a solution to merge \( k \) sorted linked lists into one sorted linked list. The approach used is a divide-and-conquer strategy. + +## Approach + +### Divide and Conquer + +1. The `mergeKLists` function initiates the process by calling the `mergeKListsHelper` function with the entire list of linked lists. +2. The `mergeKListsHelper` function recursively divides the array of lists into halves until it reaches the base case where there is only one list or two lists. +3. If there are two lists, they are merged using the `merge` function. +4. If there is only one list, it is returned as is. +5. The merging process continues by combining the merged halves recursively until the entire list is merged into a single sorted list. + +### Merge Function + +1. The `merge` function takes two sorted linked lists and merges them into one sorted linked list. +2. A dummy node is used to simplify the merging process. +3. It iterates through both lists, attaching the smaller node to the current node, and moves the pointer of the list from which the node was taken. +4. After one of the lists is exhausted, the remaining nodes of the other list are attached to the merged list. +5. The merged list (starting from the node after the dummy node) is returned. + + + +## Code in Different Languages + + + + + ```python + class Solution: + def mergeKLists(self, lists: List[ListNode]) -> ListNode: + if not lists: + return None + if len(lists) == 1: + return lists[0] + + mid = len(lists) // 2 + left = self.mergeKLists(lists[:mid]) + right = self.mergeKLists(lists[mid:]) + + return self.merge(left, right) + + def merge(self, l1, l2): + dummy = ListNode(0) + curr = dummy + + while l1 and l2: + if l1.val < l2.val: + curr.next = l1 + l1 = l1.next + else: + curr.next = l2 + l2 = l2.next + curr = curr.next + + curr.next = l1 or l2 + + return dummy.next + ``` + + + + + ``` java + class Solution { + public ListNode mergeKLists(ListNode[] lists) { + if (lists == null || lists.length == 0) { + return null; + } + return mergeKListsHelper(lists, 0, lists.length - 1); + } + + private ListNode mergeKListsHelper(ListNode[] lists, int start, int end) { + if (start == end) { + return lists[start]; + } + if (start + 1 == end) { + return merge(lists[start], lists[end]); + } + int mid = start + (end - start) / 2; + ListNode left = mergeKListsHelper(lists, start, mid); + ListNode right = mergeKListsHelper(lists, mid + 1, end); + return merge(left, right); + } + + private ListNode merge(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(0); + ListNode curr = dummy; + + while (l1 != null && l2 != null) { + if (l1.val < l2.val) { + curr.next = l1; + l1 = l1.next; + } else { + curr.next = l2; + l2 = l2.next; + } + curr = curr.next; + } + + curr.next = (l1 != null) ? l1 : l2; + + return dummy.next; + } + } + ``` + + + + + ```cpp + class Solution { + public: + ListNode* mergeKLists(vector& lists) { + if (lists.empty()) { + return nullptr; + } + return mergeKListsHelper(lists, 0, lists.size() - 1); + } + + ListNode* mergeKListsHelper(vector& lists, int start, int end) { + if (start == end) { + return lists[start]; + } + if (start + 1 == end) { + return merge(lists[start], lists[end]); + } + int mid = start + (end - start) / 2; + ListNode* left = mergeKListsHelper(lists, start, mid); + ListNode* right = mergeKListsHelper(lists, mid + 1, end); + return merge(left, right); + } + + ListNode* merge(ListNode* l1, ListNode* l2) { + ListNode* dummy = new ListNode(0); + ListNode* curr = dummy; + + while (l1 && l2) { + if (l1->val < l2->val) { + curr->next = l1; + l1 = l1->next; + } else { + curr->next = l2; + l2 = l2->next; + } + curr = curr->next; + } + + curr->next = l1 ? l1 : l2; + + return dummy->next; + } + }; + ``` + + + + +### Complexity analysis + +- **Time Complexity**: \( O(n \log k) \), where \( n \) is the total number of nodes and \( k \) is the number of linked lists. +- **Space Complexity**: \( O(\log k) \) due to the recursion stack. + + + +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/merge-k-sorted-lists/description/) +- **Solution Link:** [Merge K sorted Lists Solution on LeetCode](https://leetcode.com/problems/merge-k-sorted-lists/solutions/3285930/100-faster-c-java-python/) + + diff --git a/solutions/lc-solutions/0000-0099/0024-swap-nodes-in-pairs.md b/solutions/lc-solutions/0000-0099/0024-swap-nodes-in-pairs.md new file mode 100644 index 0000000..6be6dfe --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0024-swap-nodes-in-pairs.md @@ -0,0 +1,156 @@ +--- +id: swap-nodes-in-pairs +title: Swap Nodes in Pairs (LeetCode) +sidebar_label: 0024-SwapNodesInPairs +description: Swap every two adjacent nodes in a linked list and return its head. The values in the nodes must not be modified, only the nodes themselves can be changed. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/swap-nodes-in-pairs/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/swap-nodes-in-pairs/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + + +## Problem Description + +Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed). + +### Examples + +#### Example 1 + +- **Input:** $head = [1,2,3,4]$ +- **Output:** $[2,1,4,3]$ +- **Explanation:** The linked list is $[1,2,3,4]$. After swapping pairs, it becomes $[2,1,4,3]$. + +#### Example 2 + +- **Input:** $head = []$ +- **Output:** $[]$ +- **Explanation:** The input linked list is empty, so the output is also empty. + +#### Example 3 + +- **Input:** $head = [1]$ +- **Output:** $[1]$ +- **Explanation:** There is only one node in the linked list, so no swapping occurs. + +### Constraints + +- The number of nodes in the list is in the range [0, 100]. +- $0 <= Node.val <= 100$ + +### Approach + +To solve this problem, we can use a recursive approach. We swap each pair of nodes in the linked list by recursively swapping the remaining linked list after the current pair. + +1. **Base Case:** + - If the current node or the next node is null, return the current node. + +2. **Swap Nodes:** + - Swap the current node with its next node. + - Recursively call the function on the remaining linked list. + +3. **Return Head:** + - Return the new head of the swapped pairs. + +### Solution Code + +#### Python + +```py +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +class Solution: + def swapPairs(self, head): + # If the list is empty or has only one node, no need to swap + if not head or not head.next: + return head + + # Dummy node to ease handling edge cases + dummy = ListNode(0) + dummy.next = head + prev = dummy + + while prev.next and prev.next.next: + first = prev.next + second = prev.next.next + + # Swapping + prev.next = second + first.next = second.next + second.next = first + + # Move the pointer two steps forward + prev = first + + return dummy.next +``` + +#### Java + +```java +class Solution { + public ListNode swapPairs(ListNode head) { + // If the list is empty or has only one node, no need to swap + if (head == null || head.next == null) { + return head; + } + // Dummy node to ease handling edge cases + ListNode dummy = new ListNode(0); + dummy.next = head; + ListNode prev = dummy; + while (prev.next != null && prev.next.next != null) { + ListNode first = prev.next; + ListNode second = prev.next.next; + // Swapping + prev.next = second; + first.next = second.next; + second.next = first; + + // Move the pointer two steps forward + prev = first; + } + return dummy.next; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + // If the list is empty or has only one node, no need to swap + if (!head || !head->next) { + return head; + } + + // Dummy node to ease handling edge cases + ListNode dummy(0); + dummy.next = head; + ListNode* prev = &dummy; + + while (prev->next && prev->next->next) { + ListNode* first = prev->next; + ListNode* second = prev->next->next; + // Swapping + prev->next = second; + first->next = second->next; + second->next = first; + // Move the pointer two steps forward + prev = first; + } + return dummy.next; + } +}; +``` + +### Conclusion + +The above solution effectively swaps every two adjacent nodes in a linked list without modifying the values in the nodes themselves. It utilizes a recursive approach to swap pairs of nodes, ensuring that the final linked list is correctly swapped. This solution has a time complexity of $O(n)$, where n is the number of nodes in the linked list, making it efficient for handling the given constraints. diff --git a/solutions/lc-solutions/0000-0099/0025-reverse-nodes-in-k-group.md b/solutions/lc-solutions/0000-0099/0025-reverse-nodes-in-k-group.md new file mode 100644 index 0000000..1bc5ad1 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0025-reverse-nodes-in-k-group.md @@ -0,0 +1,141 @@ +--- +id: remove-duplicates-from-sorted-list-2 +title: Reverse Nodes in k-Group (Leetcode) +sidebar_label: 0025-ReverseNodesInK-Group +description: Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.You may not alter the values in the list's nodes, only nodes themselves may be changed. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/description/) | [Reverse Nodes in k-Group Solution on LeetCode](https://leetcode.com/problems/reverse-nodes-in-k-group/solutions/) | [Aaradhya Singh ](https://leetcode.com/u/keira_09/) | + + +## Problem Description + +Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. + +k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. + +You may not alter the values in the list's nodes, only nodes themselves may be changed. + +### Examples + +#### Example 1 + +- **Input:** $head = [1,2,3,4,5], k = 2$ +- **Output:** $[2,1,4,3,5]$ + + +#### Example 2 + +- **Input:** $head = [1,2,3,4,5], k = 3$ +- **Output:** $[3,2,1,4,5]$ + + + +### Constraints + +- The number of nodes in the list is $n$. +- $1 <= k <= n <= 5000$ +- $0 <= Node.val <= 1000$ + + + +### Intuition + +The code aims to reverse nodes in a linked list in groups of $k$. It first checks if the length of the list is less than $k$ ; if so, it returns the head as-is. If the head is null or the list has only one node, or $k$ is less than 2, it returns the head. The core logic involves reversing the first $k$ nodes using a loop and recursively calling the function on the remaining nodes. The reversed portion is then linked with the result of the recursive call, ensuring the entire list is processed in $k$-sized groups. + + +### Approach + +1. **Calculate Length of the Linked List:** + + - Implement a helper function Length to calculate and return the size of the linked list. This function iterates through the list, incrementing a counter until the end of the list is reached. + +2. **Initial Checks:** + + - In the reverseKGroup function, first check if $k$ is greater than the length of the list using the Length function. If so, return the head as is since there are not enough nodes to form a group. + - Check if the head is null, the list has only one node, or if $k$ is less than 2. If any of these conditions are true, return the head as-is since no reversal is needed. + +3. **Reverse First k Nodes:** + + - Initialize three pointers: prev as null, curr as head, and next as null. + - Use a loop to reverse the first $k$ nodes. Within the loop: + - Store the next node of curr in next. + Reverse the link by setting curr->next to prev. + - Move the prev pointer to curr and curr to next. + - Increment the count to ensure only $k$ nodes are processed. + +3. **Recursive Call:** + + - After reversing the first $k$ nodes, if next is not null (indicating there are more nodes left to process), make a recursive call to reverseKGroup with curr (the node following the first $k$ nodes) and $k$. + - Link the last node of the reversed group (which is now the head) to the result of the recursive call. + +4. **Return New Head:** + + - Return prev as the new head of the reversed portion of the list. + +### Solution Code + + +#### C++ + +```cpp +#include + +// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +int Length(ListNode *head) { + int size = 0; + ListNode *temp = head; + while (temp != nullptr) { + temp = temp->next; + size++; + } + return size; +} + +class Solution { +public: + ListNode* reverseKGroup(ListNode* head, int k) { + if (k > Length(head)) { + return head; + } + if (head == nullptr || head->next == nullptr || k < 2) { + return head; + } + + int count = 0; + ListNode *prev = nullptr; + ListNode *curr = head; + ListNode *next = nullptr; + + while (count < k) { + next = curr->next; + curr->next = prev; + prev = curr; + curr = next; + count++; + } + + if (next != nullptr) { + head->next = reverseKGroup(curr, k); + } + + return prev; + } +}; +``` + +### Conclusion + +The provided code effectively reverses nodes in a linked list in groups of $k$. It first calculates the length of the linked list to ensure there are enough nodes to form a group. If the length is less than $k$, it returns the head as is. The code then uses a loop to reverse the first $k$ nodes and recursively processes the remaining nodes, ensuring the entire linked list is processed in groups of $k$ while maintaining the order and structure of the reversed segments. The time complexity of this approach is $O(n)$, where $n$ is the number of nodes in the linked list, as each node is processed exactly once. The space complexity is $O(n/k)$ due to the recursion stack, as in the worst case, the depth of the recursion stack can be $n/k$, where $n$ is the total number of nodes and $k$ is the group size. diff --git a/solutions/lc-solutions/0000-0099/0026-Remove-Duplicates-from-Sorted-Array.md b/solutions/lc-solutions/0000-0099/0026-Remove-Duplicates-from-Sorted-Array.md new file mode 100644 index 0000000..c3ad481 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0026-Remove-Duplicates-from-Sorted-Array.md @@ -0,0 +1,147 @@ +--- +id: remove-duplicates-from-sorted-array +title: Remove Duplicates from Sorted Array (LeetCode) +sidebar_label: 0026-RemoveDuplicatesFromSortedArray +tags: + - Array + - Two Pointers +description: Given a sorted integer array, remove duplicates in-place and return the new length of the array with unique elements. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :----------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------- | +| [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | [Remove Duplicates from Sorted Array Solution on LeetCode](https://leetcode.com/problems/remove-duplicates-from-sorted-array/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +### Problem Description + +Given an integer array `nums` sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in `nums`. + +Consider the number of unique elements of `nums` to be `k`, to get accepted, you need to do the following things: +- Change the array `nums` such that the first `k` elements of `nums` contain the unique elements in the order they were present in `nums` initially. +- The remaining elements of `nums` are not important as well as the size of `nums`. +- Return `k`. + +### Custom Judge + +The judge will test your solution with the following code: + +``` +int[] nums = [...]; // Input array +int[] expectedNums = [...]; // The expected answer with correct length + +int k = removeDuplicates(nums); // Calls your implementation + +assert k == expectedNums.length; +for (int i = 0; i < k; i++) { + assert nums[i] == expectedNums[i]; +} +``` + +If all assertions pass, then your solution will be accepted. + +### Examples + +#### Example 1 + +- **Input:** `nums = [1,1,2]` +- **Output:** `2, nums = [1,2,_]` +- **Explanation:** Your function should return `k = 2`, with the first two elements of `nums` being 1 and 2 respectively. It does not matter what you leave beyond the returned `k` (hence they are underscores). + +#### Example 2 + +- **Input:** `nums = [0,0,1,1,1,2,2,3,3,4]` +- **Output:** `5, nums = [0,1,2,3,4,_,_,_,_,_]` +- **Explanation:** Your function should return `k = 5`, with the first five elements of `nums` being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned `k` (hence they are underscores). + +### Constraints + +- `1 <= nums.length <= 3 * 10^4` +- `-100 <= nums[i] <= 100` +- `nums` is sorted in non-decreasing order. + +### Approach + +To solve the problem, we can use the two-pointer technique. Here is the step-by-step approach: + +1. **Initialize Pointers:** + - Use `uniqueIndex` to track the position to place the next unique element. + +2. **Iterate Through the Array:** + - Traverse the array starting from the second element. + - If the current element is different from the element at `uniqueIndex`, move `uniqueIndex` forward and update it with the current element. + +3. **Return Result:** + - The number of unique elements is `uniqueIndex + 1`. + +### Solution Code + +#### Python + +``` +class Solution(object): + def removeDuplicates(self, nums): + if len(nums) == 0: + return 0 + + unique_index = 0 # Pointer for placing unique elements + + for i in range(1, len(nums)): + if nums[i] != nums[unique_index]: + # Found a unique element, place it in the next position + unique_index += 1 + nums[unique_index] = nums[i] + + # The number of unique elements is one more than the index of the last unique element + return unique_index + 1 +``` + +#### Java +``` +class Solution { + public int removeDuplicates(int[] nums) { + if (nums.length == 0) return 0; + + int uniqueIndex = 0; // Pointer for placing unique elements + + for (int i = 1; i < nums.length; i++) { + if (nums[i] != nums[uniqueIndex]) { + // Found a unique element, place it in the next position + uniqueIndex++; + nums[uniqueIndex] = nums[i]; + } + } + + // The number of unique elements is one more than the index of the last unique element + return uniqueIndex + 1; + } +} +``` + +#### C++ +``` +class Solution { +public: + int removeDuplicates(vector& nums) { + if (nums.size() == 0) return 0; + + int uniqueIndex = 0; // Pointer for placing unique elements + + for (int i = 1; i < nums.size(); i++) { + if (nums[i] != nums[uniqueIndex]) { + // Found a unique element, place it in the next position + uniqueIndex++; + nums[uniqueIndex] = nums[i]; + } + } + + // The number of unique elements is one more than the index of the last unique element + return uniqueIndex + 1; + } +}; +``` + +### Conclusion + +The above solution efficiently removes duplicates from a sorted array in-place. It employs a two-pointer technique to achieve a time complexity of $O(N)$ and a space complexity of $O(1)$. This ensures that the algorithm can handle input sizes up to the upper limit specified in the constraints efficiently, providing a simple yet effective approach to solving the problem of removing duplicates from a sorted array. diff --git a/solutions/lc-solutions/0000-0099/0027-Remove-Element.md b/solutions/lc-solutions/0000-0099/0027-Remove-Element.md new file mode 100644 index 0000000..3708420 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0027-Remove-Element.md @@ -0,0 +1,154 @@ +--- +id: remove-element +title: Remove Element (LeetCode) +sidebar_label: 0027-RemoveElement +difficulty: Easy +--- + +## Problem Description + + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/remove-element/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/remove-element/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +## Problem Description + +Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` in-place. The order of the elements may be changed. Then return the number of elements in `nums` which are not equal to `val`. + +Consider the number of elements in `nums` which are not equal to `val` to be `k`. To get accepted, you need to do the following things: + +- Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. The remaining elements of `nums` are not important as well as the size of `nums`. +- Return `k`. + +### Custom Judge + +The judge will test your solution with the following code: + +``` +int[] nums = [...]; // Input array +int val = ...; // Value to remove +int[] expectedNums = [...]; // The expected answer with correct length. + // It is sorted with no values equaling val. + +int k = removeElement(nums, val); // Calls your implementation + +assert k == expectedNums.length; +sort(nums, 0, k); // Sort the first k elements of nums +for (int i = 0; i < actualLength; i++) { + assert nums[i] == expectedNums[i]; +} +``` + +If all assertions pass, then your solution will be accepted. + +### Examples + +#### Example 1 + +- **Input:** `nums = [3,2,2,3], val = 3` +- **Output:** `2, nums = [2,2,_,_]` +- **Explanation:** Your function should return `k = 2`, with the first two elements of `nums` being 2. It does not matter what you leave beyond the returned `k` (hence they are underscores). + +#### Example 2 + +- **Input:** `nums = [0,1,2,2,3,0,4,2], val = 2` +- **Output:** `5, nums = [0,1,4,0,3,_,_,_]` +- **Explanation:** Your function should return `k = 5`, with the first five elements of `nums` containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned `k` (hence they are underscores). + +### Constraints + +- `0 <= nums.length <= 100` +- `0 <= nums[i] <= 50` +- `0 <= val <= 100` + +### Approach + +To solve the problem, we can use the following approach: + +1. **Initialize Two Pointers:** + - Use two pointers, `slow` and `fast`, where `slow` points to the beginning of the array and `fast` moves forward to explore the array. + +2. **Iterate Through the Array:** + - While `fast` is within the bounds of the array: + - If `nums[fast]` is not equal to `val`, copy `nums[fast]` to `nums[slow]` and increment both pointers. + - If `nums[fast]` is equal to `val`, just increment `fast`. + +3. **Return Result:** + - The new length of the array without the elements equal to `val` is given by `slow`. + +### Solution Code + +#### Python + +``` +class Solution: + def removeElement(self, nums, val): + # Pointer to place the next non-val element + k = 0 + + # Iterate through all elements in the array + for i in range(len(nums)): + if nums[i] != val: + # Place the non-val element at the next position in the array + nums[k] = nums[i] + k += 1 + + return k + +def _driver(): + # Example usage + nums = [3, 2, 2, 3] + val = 3 + sol = Solution() + k = sol.removeElement(nums, val) + print("The number of elements not equal to val:", k) + print("The modified array:", nums[:k]) + +if __name__ == "__main__": + _driver() + +``` + +#### Java + +``` +class Solution { + public int removeElement(int[] nums, int val) { + int slow = 0; + + for (int fast = 0; fast < nums.length; fast++) { + if (nums[fast] != val) { + nums[slow] = nums[fast]; + slow++; + } + } + + return slow; + } +} +``` + +#### C++ + +``` +class Solution { +public: + int removeElement(vector& nums, int val) { + int slow = 0; + + for (int fast = 0; fast < nums.size(); fast++) { + if (nums[fast] != val) { + nums[slow] = nums[fast]; + slow++; + } + } + + return slow; + } +}; +``` + +### Conclusion + +The above solution efficiently removes all occurrences of a specified value from an integer array in-place. It employs a two-pointer technique to achieve a time complexity of $O(N)$ and a space complexity of $O(1)$. This ensures that the algorithm can handle input sizes up to the upper limit specified in the constraints efficiently, providing a simple yet effective approach to solving the problem of removing an element from an array. diff --git a/solutions/lc-solutions/0000-0099/0028-find-first-occurrence-in-string.md b/solutions/lc-solutions/0000-0099/0028-find-first-occurrence-in-string.md new file mode 100644 index 0000000..51a43bb --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0028-find-first-occurrence-in-string.md @@ -0,0 +1,112 @@ +--- +id: find-first-occurrence-in-string +title: Find the Index of the First Occurrence in a String +difficulty: Easy +sidebar_label: 0028-FindFirstOccurrenceInString +tags: + - String +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :----------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------- | +| [Remove Duplicates from Sorted Array](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/) | [Remove Duplicates from Sorted Array Solution on LeetCode](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +## Problem Description + +Given two strings `needle` and `haystack`, return the index of the first occurrence of `needle` in `haystack`, or -1 if `needle` is not part of `haystack`. + +### Examples + +#### Example 1: + +- **Input:** + - `haystack = "sadbutsad"` + - `needle = "sad"` +- **Output:** `0` +- **Explanation:** + - "sad" occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. + +#### Example 2: + +- **Input:** + - `haystack = "leetcode"` + - `needle = "leeto"` +- **Output:** `-1` +- **Explanation:** + - "leeto" did not occur in "leetcode", so we return -1. + +### Constraints + +- `1 <= haystack.length , needle.length <= 10^4 ` +- haystack and needle consist of only lowercase English characters. + +### Approach + +To solve the problem, we can use the following approach: + +1. **Sliding Window Technique:** + - We iterate through the `haystack` string with a window of size equal to the length of the `needle`. + - At each step, we check if the substring of the `haystack` starting at the current index and having the same length as the `needle` matches the `needle`. + - If a match is found, we return the current index. + - If no match is found after iterating through the entire `haystack`, we return -1. + +### Solution Code + +#### Python + +``` +class Solution(object): + def strStr(self, haystack, needle): + if not needle: + return 0 + if len(needle) > len(haystack): + return -1 + + for i in range(len(haystack) - len(needle) + 1): + if haystack[i:i + len(needle)] == needle: + return i + return -1 +``` + +#### Java + +``` +class Solution { + public int strStr(String haystack, String needle) { + if (needle.isEmpty()) return 0; + + for (int i = 0; i <= haystack.length() - needle.length(); i++) { + if (haystack.substring(i, i + needle.length()).equals(needle)) { + return i; + } + } + + return -1; + } +} +``` + +#### C++ + +``` +class Solution { +public: + int strStr(string haystack, string needle) { + if (needle.empty()) return 0; + + for (int i = 0; i <= haystack.length() - needle.length(); i++) { + if (haystack.substr(i, needle.length()) == needle) { + return i; + } + } + + return -1; + } +}; +``` + +### Conclusion + +The above solution efficiently finds the index of the first occurrence of a substring `needle` in the string `haystack`. It employs a sliding window technique to traverse the `haystack` string and compare substrings with the `needle`, providing a simple yet effective approach to solving the problem. diff --git a/solutions/lc-solutions/0000-0099/0029-divide-two-integers.md b/solutions/lc-solutions/0000-0099/0029-divide-two-integers.md new file mode 100644 index 0000000..938499a --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0029-divide-two-integers.md @@ -0,0 +1,149 @@ +--- +id: divide-two-integers +title: Divide Two Integers (LeetCode) +sidebar_label: 0029-DivideTwoIntegers +description: Divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/divide-two-integers/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/divide-two-integers/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +## Problem Description + +Given two integers `dividend` and `divisor`, divide two integers without using multiplication, division, and mod operator. + +The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. + +Return the quotient after dividing `dividend` by `divisor`. + +**Note:** Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [-2^31, 2^31 - 1]. For this problem, if the quotient is strictly greater than 2^31 - 1, then return 2^31 - 1, and if the quotient is strictly less than -2^31, then return -2^31. + +### Examples + +#### Example 1 + +- **Input:** `dividend = 10`, `divisor = 3` +- **Output:** `3` +- **Explanation:** 10/3 = 3.33333.. which is truncated to 3. + +#### Example 2 + +- **Input:** `dividend = 7`, `divisor = -3` +- **Output:** `-2` +- **Explanation:** 7/-3 = -2.33333.. which is truncated to -2. + +### Constraints + +- $-2^31 <= dividend, divisor <= 2^31 - 1$ +- $divisor != 0$ + +### Approach + +To divide two integers without using multiplication, division, and mod operator, we can use bit manipulation and subtraction to perform the division operation. + +1. **Handle Edge Cases:** + - Check for special cases where the dividend is the minimum integer value or the divisor is 1 or -1. + +2. **Calculate Sign of Result:** + - Determine the sign of the result by checking if either the dividend or the divisor is negative. + +3. **Perform Division:** + - Use bit manipulation and subtraction to perform the division operation, iterating until the dividend becomes less than the divisor. + - Keep track of the number of times subtraction is performed to determine the quotient. + +4. **Handle Overflow:** + - Handle overflow cases where the result is greater than the maximum or less than the minimum integer value. + +### Solution Code + +#### Python + +```py +class Solution: + def divide(self, dividend, divisor): + if dividend == 0: + return 0 + # Handle overflow cases + if dividend == -2**31 and divisor == -1: + return 2**31 - 1 + # Determine the sign of the result + sign = -1 if (dividend < 0) ^ (divisor < 0) else 1 + + # Convert dividend and divisor to positive numbers + dividend = abs(dividend) + divisor = abs(divisor) + quotient = 0 + while dividend >= divisor: + # Count the number of left shifts needed + shifts = 0 + while dividend >= (divisor << shifts): + shifts += 1 + # Update dividend and quotient + dividend -= divisor << (shifts - 1) + quotient += 1 << (shifts - 1) + return sign * quotient +``` + +#### Java + +```java +class Solution { + public int divide(int dividend, int divisor) { + if (dividend == Integer.MIN_VALUE && divisor == -1) + return Integer.MAX_VALUE; + + int sign = (dividend >= 0) == (divisor >= 0) ? 1 : -1; + long dvd = Math.abs((long) dividend); + long dvs = Math.abs((long) divisor); + + long quotient = 0; + while (dvd >= dvs) { + long temp = dvs, multiple = 1; + while (dvd >= temp << 1) { + temp <<= 1; + multiple <<= 1; + } + dvd -= temp; + quotient += multiple; + } + + return (int) (sign * quotient); + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + int divide(int dividend, int divisor) { + if (dividend == INT_MIN && divisor == -1) + return INT_MAX; + + int sign = (dividend >= 0) == (divisor >= 0) ? 1 : -1; + long dvd = labs(dividend); + long dvs = labs(divisor); + + long quotient = 0; + while (dvd >= dvs) { + long temp = dvs, multiple = 1; + while (dvd >= temp << 1) { + temp <<= 1; + multiple <<= 1; + } + dvd -= temp; + quotient += multiple; + } + + return sign * quotient; + } +}; +``` + +### Conclusion + +The above solution effectively divides two integers without using multiplication, division, and mod operators. It utilizes bit manipulation and subtraction to perform the division operation, ensuring that the integer division truncates toward zero as required. This solution handles edge cases such as overflow and returns the correct quotient within the specified range. diff --git a/solutions/lc-solutions/0000-0099/0030 - SubString-with-Concatenation-of-all-words.md b/solutions/lc-solutions/0000-0099/0030 - SubString-with-Concatenation-of-all-words.md new file mode 100644 index 0000000..1985d40 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0030 - SubString-with-Concatenation-of-all-words.md @@ -0,0 +1,371 @@ +--- +id: substring-with-concatenation-of-all-words +title: Substring with Concatenation of All Words +sidebar_label: 0030-Substring-with-Concatenation-of-All-Words +tags: + - Hard + - String + - Hash Table + - Two Pointers +description: A concatenated string is a string that exactly contains all the strings of any permutation of `words` concatenated. +--- + +## Problem Description +You are given a string `s` and an array of strings `words`. All the strings in `words` are of the same length. + +### Examples + +**Example 1:** + +- **Input:** `s = "barfoothefoobarman"`, `words = ["foo","bar"]` +- **Output:** `[0,9]` + +- **Explanation:** +- The substring starting at 0 is "barfoo". It is the concatenation of `["bar","foo"]` which is a permutation of `words`. +- The substring starting at 9 is "foobar". It is the concatenation of `["foo","bar"]` which is a permutation of `words`. + +**Example 2:** + +- **Input:** `s = "wordgoodgoodgoodbestword"`, `words = ["word","good","best","word"]` +- **Output:** `[]` + +- **Explanation:** +- There is no concatenated substring. + +**Example 3:** + +- **Input:** `s = "barfoofoobarthefoobarman"`, `words = ["bar","foo","the"]` +- **Output:** `[6,9,12]` + +- **Explanation:** +- The substring starting at 6 is "foobarthe". It is the concatenation of `["foo","bar","the"]`. +- The substring starting at 9 is "barthefoo". It is the concatenation of `["bar","the","foo"]`. +- The substring starting at 12 is "thefoobar". It is the concatenation of `["the","foo","bar"]`. + +### Constraints +- $1 \leq \text{s.length} \leq 10^4$ +- $1 \leq \text{words.length} \leq 5000$ +- $1 \leq \text{words[i].length} \leq 30$ +- s and words[i] consist of lowercase English letters. + +## Approach +We will use a sliding window approach to solve this problem. +1. First, we calculate the length of each word in the `words` array and the total length of the concatenated substring. +2. We create a hashmap to store the count of each word in `words`. +3. We iterate over each possible starting index in the string `s` using a sliding window of size equal to the total length of the concatenated substring. +4. For each substring, we check if it can be formed by concatenating all the words in `words`. +5. To check the validity of each window, we use another hashmap to count occurrences of words in the current window and compare it to the word count map. +6. If the current window is valid, we add its starting index to the result list. + +## Solution in Java +```java +import java.util.*; + +public class Solution { + public List findSubstring(String s, String[] words) { + List result = new ArrayList<>(); + if (s == null || s.length() == 0 || words == null || words.length == 0) { + return result; + } + + int wordLength = words[0].length(); + int wordCount = words.length; + int totalLength = wordLength * wordCount; + + // Create a map to count the words + Map wordMap = new HashMap<>(); + for (String word : words) { + wordMap.put(word, wordMap.getOrDefault(word, 0) + 1); + } + + // Slide the window over the string `s` + for (int i = 0; i <= s.length() - totalLength; i++) { + String currentSubstring = s.substring(i, i + totalLength); + if (isValid(currentSubstring, wordMap, wordLength, wordCount)) { + result.add(i); + } + } + + return result; + } + + private boolean isValid(String substring, Map wordMap, int wordLength, int wordCount) { + Map seen = new HashMap<>(); + for (int j = 0; j < wordCount; j++) { + int wordStartIndex = j * wordLength; + String word = substring.substring(wordStartIndex, wordStartIndex + wordLength); + if (!wordMap.containsKey(word)) { + return false; + } + seen.put(word, seen.getOrDefault(word, 0) + 1); + if (seen.get(word) > wordMap.get(word)) { + return false; + } + } + return true; + } +} +``` + +### Solution in Python +```python +class Solution: + def findSubstring(self, s: str, words: List[str]) -> List[int]: + result = [] + if not s or not words: + return result + + word_length = len(words[0]) + word_count = len(words) + total_length = word_length * word_count + + word_map = {} + for word in words: + word_map[word] = word_map.get(word, 0) + 1 + + for i in range(len(s) - total_length + 1): + current_substring = s[i:i + total_length] + if self.is_valid(current_substring, word_map, word_length, word_count): + result.append(i) + + return result + + def is_valid(self, substring, word_map, word_length, word_count): + seen = {} + for j in range(word_count): + word_start_index = j * word_length + word = substring[word_start_index:word_start_index + word_length] + if word not in word_map: + return False + seen[word] = seen.get(word, 0) + 1 + if seen[word] > word_map[word]: + return False + return True +``` + +### Solution in CPP +```cpp +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector findSubstring(string s, vector& words) { + vector result; + if (s.empty() || words.empty()) { + return result; + } + + int wordLength = words[0].length(); + int wordCount = words.size(); + int totalLength = wordLength * wordCount; + + unordered_map wordMap; + for (const string& word : words) { + wordMap[word]++; + } + + for (int i = 0; i <= s.length() - totalLength; i++) { + string currentSubstring = s.substr(i, totalLength); + if (isValid(currentSubstring, wordMap, wordLength, wordCount)) { + result.push_back(i); + } + } + + return result; + } + + bool isValid(string substring, unordered_map& wordMap, int wordLength, int wordCount) { + unordered_map seen; + for (int j = 0; j < wordCount; j++) { + string word = substring.substr(j * wordLength, wordLength); + if (wordMap.find(word) == wordMap.end()) { + return false; + } + seen[word]++; + if (seen[word] > wordMap[word]) { + return false; + } + } + return true; + } +}; + +int main() { + Solution solution; + string s = "barfoothefoobarman"; + vector words = {"foo", "bar"}; + vector result = solution.findSubstring(s, words); + for (int idx : result) { + cout << idx << " "; + } + cout << endl; + return 0; +} +``` + +### Solution in C +```c +#include +#include +#include + +#define MAX_WORD_LENGTH 30 + +int isValid(char* substring, char** words, int* wordMap, int wordLength, int wordCount) { + int seen[5000] = {0}; + for (int j = 0; j < wordCount; j++) { + char* word = substring + j * wordLength; + int index = -1; + for (int k = 0; k < wordCount; k++) { + if (strcmp(word, words[k]) == 0) { + index = k; + break; + } + } + if (index == -1 || wordMap[index] == 0) { + return 0; + } + seen[index]++; + if (seen[index] > wordMap[index]) { + return 0; + } + } + return 1; +} + +int* findSubstring(char* s, char** words, int wordsSize, int* returnSize) { + *returnSize = 0; + if (!s || !words || wordsSize == 0) { + return NULL; + } + + int wordLength = strlen(words[0]); + int wordCount = wordsSize; + int totalLength = wordLength * wordCount; + + int* result = (int*)malloc(sizeof(int) * 5000); + if (!result) { + return NULL; + } + + int wordMap[5000] = {0}; + for (int i = 0; i < wordCount; i++) { + int found = 0; + for (int j = 0; j < i; j++) { + if (strcmp(words[i], words[j]) == 0) { + found = 1; + wordMap[j]++; + break; + } + } + if (!found) { + wordMap[i]++; + } + } + + for (int i = 0; i <= strlen(s) - totalLength; i++) { + char currentSubstring[totalLength + 1]; + strncpy(currentSubstring, s + i, totalLength); + currentSubstring[totalLength] = '\0'; + if (isValid(currentSubstring, words, wordMap, wordLength, wordCount)) { + result[(*returnSize)++] = i; + } + } + + return result; +} + +int main() { + char* s = "barfoothefoobarman"; + char* words[2] = {"foo", "bar"}; + int wordsSize = 2; + int returnSize; + int* result = findSubstring(s, words, wordsSize, &returnSize); + for (int i = 0; i < returnSize; i++) { + printf("%d ", result[i]); + } + printf("\n"); + free(result); + return 0; +} +``` + +### Solution in JavaScript +```js +/** + * @param {string} s + * @param {string[]} words + * @return {number[]} + */ +var findSubstring = function(s, words) { + const result = []; + if (!s || !words || words.length === 0) { + return result; + } + + const wordLength = words[0].length; + const wordCount = words.length; + const totalLength = wordLength * wordCount; + + const wordMap = {}; + words.forEach(word => { + if (wordMap[word]) { + wordMap[word]++; + } else { + wordMap[word] = 1; + } + }); + + for (let i = 0; i <= s.length - totalLength; i++) { + const currentSubstring = s.substring(i, i + totalLength); + if (isValid(currentSubstring, wordMap, wordLength, wordCount)) { + result.push(i); + } + } + + return result; +}; + +function isValid(substring, wordMap, wordLength, wordCount) { + const seen = {}; + for (let j = 0; j < wordCount; j++) { + const word = substring.substr(j * wordLength, wordLength); + if (!wordMap[word]) { + return false; + } + if (!seen[word]) { + seen[word] = 1; + } else { + seen[word]++; + } + if (seen[word] > wordMap[word]) { + return false; + } + } + return true; +} + +// Example usage: +const s = "barfoothefoobarman"; +const words = ["foo", "bar"]; +console.log(findSubstring(s, words)); // Output: [0, 9] +``` + +### Step by Step Algorithm +1. Initialize an empty list `result` to store the starting indices of all the concatenated substrings. +2. Check for base cases: if `s` or `words` is empty, return the empty list `result`. +3. Calculate the length of each word in the `words` array and the total length of the concatenated substring. +4. Create a hashmap `word_map` to store the count of each word in `words`. +5. Iterate over each possible starting index in the string `s` using a sliding window of size equal to the total length of the concatenated substring. +6. For each substring, check if it can be formed by concatenating all the words in `words`. +7. To check the validity of each window, use another hashmap `seen` to count occurrences of words in the current window and compare it to the `word_map`. +8. If the current window is valid, add its starting index to the `result` list. +9. Return the `result` list. + +### Conclusion +This problem can be efficiently solved using a sliding window approach. By using a hashmap to store the count of words and iterating over each possible starting index in the string `s`, we can find all the concatenated substrings in `s` that are formed by concatenating all the strings of any permutation of `words`. The time complexity of this solution is O(NML), where N is the length of the string `s`, M is the number of words, and L is the length of each word. \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0031-next-permutation.md b/solutions/lc-solutions/0000-0099/0031-next-permutation.md new file mode 100644 index 0000000..32fd57d --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0031-next-permutation.md @@ -0,0 +1,144 @@ +--- +id: next-permutation +title: Next Permutation (LeetCode) +sidebar_label: 0031-NextPermutation +description: Find the next lexicographically greater permutation of an array of integers. The replacement must be in place and use only constant extra memory. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/next-permutation/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/next-permutation/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + + +## Problem Description + +Given an array of integers `nums`, find the next lexicographically greater permutation of the elements. If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order). + +### Examples + +#### Example 1 + +- **Input:** $nums = [1,2,3]$ +- **Output:** $[1,3,2]$ +- **Explanation:** The next permutation of $[1,2,3]$ is $[1,3,2]$. + +#### Example 2 + +- **Input:** $nums = [3,2,1]$ +- **Output:** $[1,2,3]$ +- **Explanation:** The next permutation of $[3,2,1]$ is $[1,2,3]$ because $[3,2,1]$ does not have a lexicographically larger rearrangement. + +#### Example 3 + +- **Input:** $nums = [1,1,5]$ +- **Output:** $[1,5,1]$ +- **Explanation:** The next permutation of $[1,1,5]$ is $[1,5,1]$. + +### Constraints + +- $1 <= nums.length <= 100$ +- $0 <= nums[i] <= 100$ + +### Approach + +To find the next lexicographically greater permutation of an array of integers, we can follow these steps: + +1. **Find Pivot Point:** + - Start from the right end of the array and find the first element `nums[i]` such that `nums[i] < nums[i+1]`. If no such element exists, then the array is sorted in descending order, and we return the array sorted in ascending order. + +2. **Find Swap Candidate:** + - Start from the right end of the array again and find the first element `nums[j]` such that `nums[j] > nums[i]`. Swap `nums[i]` with `nums[j]`. + +3. **Reverse Remaining Elements:** + - Reverse the elements from index `i+1` to the end of the array. + +### Solution Code + +#### Python + +```py +class Solution: + def nextPermutation(self, nums: List[int]) -> None: + i = len(nums) - 2 + while i >= 0 and nums[i] >= nums[i + 1]: + i -= 1 + + if i >= 0: + j = len(nums) - 1 + while j >= 0 and nums[j] <= nums[i]: + j -= 1 + nums[i], nums[j] = nums[j], nums[i] + + self.reverse(nums, i + 1) + + def reverse(self, nums: List[int], start: int) -> None: + end = len(nums) - 1 + while start < end: + nums[start], nums[end] = nums[end], nums[start] + start += 1 + end -= 1 +``` + +#### Java + +```java +class Solution { + public void nextPermutation(int[] nums) { + int i = nums.length - 2; + while (i >= 0 && nums[i] >= nums[i + 1]) + i--; + + if (i >= 0) { + int j = nums.length - 1; + while (j >= 0 && nums[j] <= nums[i]) + j--; + swap(nums, i, j); + } + + reverse(nums, i + 1); + } + + private void swap(int[] nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } + + private void reverse(int[] nums, int start) { + int end = nums.length - 1; + while (start < end) { + swap(nums, start, end); + start++; + end--; + } + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + void nextPermutation(vector& nums) { + int i = nums.size() - 2; + while (i >= 0 && nums[i] >= nums[i + 1]) + i--; + + if (i >= 0) { + int j = nums.size() - 1; + while (j >= 0 && nums[j] <= nums[i]) + j--; + swap(nums[i], nums[j]); + } + + reverse(nums.begin() + i + 1, nums.end()); + } +}; +``` + +### Conclusion + +The above solution effectively finds the next lexicographically greater permutation of an array of integers. It follows a simple algorithm to find the pivot point, swap candidates, and reverse the remaining elements, ensuring that the replacement is in place and uses only constant extra memory. This solution handles all edge cases and constraints specified in the problem statement. diff --git a/solutions/lc-solutions/0000-0099/0032-longest-valid-parentheses.md b/solutions/lc-solutions/0000-0099/0032-longest-valid-parentheses.md new file mode 100644 index 0000000..0088a36 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0032-longest-valid-parentheses.md @@ -0,0 +1,196 @@ +--- +id: longest-valid-parentheses +title: longest-valid-parentheses +sidebar_label: 0032 longest-valid-parentheses +tags: + - stack + - LeetCode + - Java + - Python + - C++ +description: This is a solution to the longest-valid-parentheses on LeetCode +--- + +## Problem Description + +Given a string containing just the characters `'('` and `')'`, return the length of the longest valid (well-formed) parentheses +`substring` + + +### Examples + +**Example 1:** + +``` + +Input: s = "(()" +Output: 2 +Explanation: The longest valid parentheses substring is "()". + +``` + +**Example 2:** + + +``` +Input: s = ")()())" +Output: 4 +Explanation: The longest valid parentheses substring is "()()". +``` + +**Example 3:** + + +``` +Input: s = "" +Output: 0 +``` + + +### Constraints + +- $1 \leq \text{nums.length} \leq 105$ + + +--- + +## Solution for Longest Valid Parentheses + + +### Intuition + +The intuition behind the given code is to use a stack to efficiently track the indices of opening parentheses. + + +### Approach + + + - It initializes a variable maxCount to 0 to store the length of the longest valid parentheses substring. + + - It initializes a stack (st) and pushes -1 onto the stack. The stack is used to keep track of the indices of opening parentheses. + + - It iterates through each character in the input string s. + + - If the current character is an opening parenthesis '(', it pushes its index onto the stack. + + - If the current character is a closing parenthesis ')', it pops the top element from the stack, representing the index of the matching opening parenthesis. + + - If the stack becomes empty after popping, it pushes the current index onto the stack (unmatched closing parenthesis). + + - If the stack is not empty, it calculates the length of the valid parentheses substring by subtracting the index of the matching opening parenthesis from the current index. It updates maxCount with the maximum length encountered so far. + + - After iterating through all characters, it returns maxCount, representing the length of the longest valid parentheses substring. + + + + + +#### Code in Different Languages + + + + + + ```python +//python + +class Solution: + def longestValidParentheses(self, s: str) -> int: + max_length = 0 + stck=[-1] # initialize with a start index + for i in range(len(s)): + if s[i] == '(': + stck.append(i) + else: + stck.pop() + if not stck: # if popped -1, add a new start index + stck.append(i) + else: + max_length=max(max_length, i-stck[-1]) # update the length of the valid substring + return max_length +``` + + + + + ```java +//java + + +class Solution { + public int longestValidParentheses(String s) { + Stack stack = new Stack<>(); + stack.push(-1); + int max=0; + for(int i=0;i + + + + ```cpp +//cpp +class Solution { +public: + int longestValidParentheses(string s) { + int n = s.size(); + stack st; + st.push(-1); + int len_max = 0; + for(int i=0;i + + + +# Complexity + + - Time complexity: + `$O(n)$` time complexity as we iterate over the string + + - Space complexity: + `$O(n)$` space complexity because we used stack +## References + +- **LeetCode Problem:** [Continuous Subarray Sum](https://leetcode.com/problems/longest-valid-parentheses/) +- **Solution Link:** [Continuous Subarray Sum](https://leetcode.com/problems/longest-valid-parentheses/submissions/) +- **Authors GeeksforGeeks Profile:** [parikhit kurmi](https://www.geeksforgeeks.org/user/sololeveler673/) +- **Authors Leetcode:** [parikhit kurmi](https://leetcode.com/u/parikhitkurmi14/) \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0033-search-in-rotated-sorted-array.md b/solutions/lc-solutions/0000-0099/0033-search-in-rotated-sorted-array.md new file mode 100644 index 0000000..8375189 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0033-search-in-rotated-sorted-array.md @@ -0,0 +1,145 @@ +--- +id: search-in-rotated-sorted-array +title: Search in Rotated Sorted Array (LeetCode) +sidebar_label: 0033-SearchInRotatedSortedArray +description: Search for a target element in a rotated sorted array with distinct values using an algorithm with O(log n) runtime complexity. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/search-in-rotated-sorted-array/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/search-in-rotated-sorted-array/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +## Problem Description + +There is an integer array nums sorted in ascending order (with distinct values). + +Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed)`. + +Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. + +You must write an algorithm with $O(log n)$ runtime complexity. + +### Examples + +#### Example 1 + +- **Input:** nums = [4,5,6,7,0,1,2], target = 0 +- **Output:** 4 +- **Explanation:** 0 is located at index 4 in the rotated sorted array [4,5,6,7,0,1,2]. + +#### Example 2 + +- **Input:** nums = [4,5,6,7,0,1,2], target = 3 +- **Output:** -1 +- **Explanation:** 3 is not in nums, so return -1. + +#### Example 3 + +- **Input:** nums = [1], target = 0 +- **Output:** -1 +- **Explanation:** 0 is not in nums, so return -1. + +### Constraints + +- $v1 <= nums.length <= 5000$ +- $-10^4 <= nums[i] <= 10^4$ +- All values of $nums$ are unique. +- nums is an ascending array that is possibly rotated. +- $-10^4 <= target <= 10^4$ + +### Approach + +To search for a target element in a rotated sorted array with distinct values with $O(log n)$ runtime complexity, we can use the binary search algorithm. + +1. **Find the Pivot Point:** + - Perform binary search to find the pivot element, which is the smallest element in the array. This element divides the array into two sorted subarrays. + +2. **Perform Binary Search:** + - Based on the pivot element, determine which half of the array the target might be in. + - Perform binary search in the appropriate half to find the target element. + +### Solution Code + +#### Python + +```py +class Solution: + def search(self, nums: List[int], target: int) -> int: + left, right = 0, len(nums) - 1 + while left <= right: + mid = (left + right) // 2 + if nums[mid] == target: + return mid + elif nums[left] <= nums[mid]: + if nums[left] <= target < nums[mid]: + right = mid - 1 + else: + left = mid + 1 + else: + if nums[mid] < target <= nums[right]: + left = mid + 1 + else: + right = mid - 1 + return -1 +``` + +#### Java + +```java +class Solution { + public int search(int[] nums, int target) { + int left = 0, right = nums.length - 1; + while (left <= right) { + int mid = (left + right) / 2; + if (nums[mid] == target) + return mid; + else if (nums[left] <= nums[mid]) { + if (nums[left] <= target && target < nums[mid]) + right = mid - 1; + else + left = mid + 1; + } else { + if (nums[mid] < target && target <= nums[right]) + left = mid + 1; + else + right = mid - 1; + } + } + return -1; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + int search(vector& nums, int target) { + int left = 0, right = nums.size() - 1; + while (left <= right) { + int mid = (left + right) / 2; + if (nums[mid] == target) + return mid; + else if (nums[left] <= nums[mid]) { + if (nums[left] <= target && target < nums[mid]) + right = mid - 1; + else + left = mid + 1; + } else { + if (nums[mid] < target && target <= nums[right]) + left = mid + 1; + else + right = mid - 1; + } + } + return -1; + } +}; +``` + +### Conclusion + +The above solution effectively searches for a target element in a rotated sorted array with distinct values using the binary search algorithm with $O(log n)$ runtime complexity. It handles all edge cases and constraints specified in the problem statement. diff --git a/solutions/lc-solutions/0000-0099/0034-Find-first-and-last-position-in-sorted-array.md b/solutions/lc-solutions/0000-0099/0034-Find-first-and-last-position-in-sorted-array.md new file mode 100644 index 0000000..92882ae --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0034-Find-first-and-last-position-in-sorted-array.md @@ -0,0 +1,170 @@ +--- +id: find-first-and-last-position-of-element-in-sorted-array +title: Find First and Last Position of Element in Sorted Array(LeetCode) +sidebar_label: 0034-Find First and Last Position of Element in Sorted Array +tags: + - Array + - Binary Search +description: Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. +sidebar_position: 34 +--- + +## Problem Statement + +Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value. + +If `target` is not found in the array, return [-1, -1]. + +You must write an algorithm with O(log n) runtime complexity. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [5,7,7,8,8,10], target = 8 +Output: [3,4] +``` + +**Example 2:** + +```plaintext +Input: nums = [5,7,7,8,8,10], target = 6 +Output: [-1,-1] +``` + +**Example 3:** + +```plaintext +Input: nums = [], target = 0 +Output: [-1,-1] +``` + +### Constraints + +- `0 <= nums.length <= 105` +- `109 <= nums[i] <= 109` +- `nums` is a non-decreasing array. +- `109 <= target <= 109` + +## Solution + +When solving the problem of finding the starting and ending position of a target value in a sorted array, we can use +two main approaches: Linear Search (Brute Force) and Binary Search (Optimized). Below, both approaches are explained along with their time and space complexities. + +### Approach 1: Linear Search (Brute Force) + +#### Explanation: + +1. Traverse the array from the beginning to find the first occurrence of the target. +2. Traverse the array from the end to find the last occurrence of the target. +3. Return the indices of the first and last occurrences. + +#### Algorithm + +1. Initialize `startingPosition` and `endingPosition` to -1. +2. Loop through the array from the beginning to find the first occurrence of the target and set `startingPosition`. +3. Loop through the array from the end to find the last occurrence of the target and set `endingPosition`. +4. Return `{startingPosition, endingPosition}`. + +#### Implementation + +```C++ +class Solution { +public: + vector searchRange(vector& nums, int target) { + int startingPosition = -1, endingPosition = -1; + int n = nums.size(); + for(int i = 0; i < n; i++) { + if(nums[i] == target) { + startingPosition = i; + break; + } + } + for(int i = n - 1; i >= 0; i--) { + if(nums[i] == target) { + endingPosition = i; + break; + } + } + return {startingPosition, endingPosition}; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: O(N), where N is the size of the array. In the worst case, we might traverse all elements of the array. +- **Space complexity**: O(1), as we are using a constant amount of extra space. + +### Approach 2: Binary Search (Optimized) + +#### Explanation: + +1. Use binary search to find the lower bound (first occurrence) of the target. +2. Use binary search to find the upper bound (last occurrence) of the target by searching for the target + 1 and subtracting 1 from the result. +3. Check if the target exists in the array and return the indices of the first and last occurrences. + +#### Algorithm + +1. Define a helper function `lower_bound` to find the first position where the target can be inserted. +2. Use `lower_bound` to find the starting position of the target. +3. Use `lower_bound` to find the position where `target + 1` can be inserted, then subtract 1 to get the ending position. +4. Check if `startingPosition` is within bounds and equals the target. +5. Return `{startingPosition, endingPosition}` if the target is found, otherwise return `{-1, -1}`. + +#### Implementation (First Version) + +```C++ +class Solution { +private: + int lower_bound(vector& nums, int low, int high, int target) { + while(low <= high) { + int mid = (low + high) >> 1; + if(nums[mid] < target) { + low = mid + 1; + } else { + high = mid - 1; + } + } + return low; + } +public: + vector searchRange(vector& nums, int target) { + int low = 0, high = nums.size() - 1; + int startingPosition = lower_bound(nums, low, high, target); + int endingPosition = lower_bound(nums, low, high, target + 1) - 1; + if(startingPosition < nums.size() && nums[startingPosition] == target) { + return {startingPosition, endingPosition}; + } + return {-1, -1}; + } +}; +``` +#### Implementation (Second Version) + +```C++ +class Solution { +public: + vector searchRange(vector& nums, int target) { + int startingPosition = lower_bound(nums.begin(), nums.end(), target) - nums.begin(); + int endingPosition = lower_bound(nums.begin(), nums.end(), target + 1) - nums.begin() - 1; + if(startingPosition < nums.size() && nums[startingPosition] == target) { + return {startingPosition, endingPosition}; + } + return {-1, -1}; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: O(log N), where N is the size of the array. We perform binary search, which has a logarithmic time complexity. +- **Space complexity**: O(1), as we are using a constant amount of extra space. + +### Conclusion + +1. Linear Search is straightforward but less efficient with a time complexity of O(N). +2. Binary Search is more efficient with a time complexity of O(log N), making it suitable for large datasets. +Both approaches provide a clear way to find the starting and ending positions of a target value in a sorted array, with the Binary Search approach being the +optimized solution. diff --git a/solutions/lc-solutions/0000-0099/0035-search-insert-position.md b/solutions/lc-solutions/0000-0099/0035-search-insert-position.md new file mode 100644 index 0000000..11b76ed --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0035-search-insert-position.md @@ -0,0 +1,136 @@ +--- +id: search-insert-position +title: Search Insert Position +difficulty: Easy +sidebar_label: 0035-SearchInsertPosition +tags: + - Array + - Binary Search +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/search-insert-position/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/search-insert-position/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +## Problem Description + +Given a sorted array `nums` of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. + +You must write an algorithm with O(log n) runtime complexity. + +### Examples + +#### Example 1: + +- **Input:** + - `nums = [1,3,5,6]` + - `target = 5` +- **Output:** `2` + +#### Example 2: + +- **Input:** + - `nums = [1,3,5,6]` + - `target = 2` +- **Output:** `1` + +#### Example 3: + +- **Input:** + - `nums = [1,3,5,6]` + - `target = 7` +- **Output:** `4` + +### Constraints + +- `1 <= `nums.length` <= 10^4` +- `-10^4 <= `nums[i]` <= 10^4` +- `nums` contains distinct values sorted in ascending order. +- `-10^4 <= `target` <= 10^4` + +### Approach + +To solve the problem with O(log n) runtime complexity, we can use binary search to find the insertion position of the target value. + +1. **Binary Search:** + - Start with low = 0 and high = length of `nums` - 1. + - While `low <= high`, compute mid as (low + high) / 2. + - If the target value is equal to the value at index mid, return mid. + - If the target value is less than the value at index mid, set high = mid - 1. + - If the target value is greater than the value at index mid, set low = mid + 1. + - After the loop, if the target value is not found, return low (or high + 1). + +### Solution Code + +#### Python + +``` +class Solution(object): + def searchInsert(self, nums, target): + left, right = 0, len(nums) - 1 + + while left <= right: + mid = left + (right - left) // 2 + if nums[mid] == target: + return mid + elif nums[mid] < target: + left = mid + 1 + else: + right = mid - 1 + + return left + +``` + +#### Java + +``` +class Solution { + public int searchInsert(int[] nums, int target) { + int low = 0, high = nums.length - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + if (nums[mid] == target) { + return mid; + } else if (nums[mid] < target) { + low = mid + 1; + } else { + high = mid - 1; + } + } + + return low; + } +} +``` + +#### C++ + +``` +class Solution { +public: + int searchInsert(vector& nums, int target) { + int low = 0, high = nums.size() - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + if (nums[mid] == target) { + return mid; + } else if (nums[mid] < target) { + low = mid + 1; + } else { + high = mid - 1; + } + } + + return low; + } +}; +``` + +### Conclusion + +The above solution efficiently finds the insertion position of a target value in a sorted array using binary search. It achieves a runtime complexity of O(log n), providing an optimal solution to the problem. diff --git a/solutions/lc-solutions/0000-0099/0036-Valid-Sudoku.md b/solutions/lc-solutions/0000-0099/0036-Valid-Sudoku.md new file mode 100644 index 0000000..eda384d --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0036-Valid-Sudoku.md @@ -0,0 +1,169 @@ +--- +id: valid-sudoku +title: Valid Sudoku +difficulty: Medium +sidebar_label: 0036-ValidSudoku +tags: + - Array + - Hash Table + - Matrix +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/description/) | [Valid Sudoku Solution on LeetCode](https://leetcode.com/problems/valid-sudoku/description/) | [Abhishikta Ray](https://leetcode.com/u/Abhishikta03/) | + +## Problem Description + +Determine if a $9 \times 9$ Sudoku board is valid. Only the filled cells need to be validated according to the following rules: + +- Each row must contain the digits 1-9 without repetition. +- Each column must contain the digits 1-9 without repetition. +- Each of the nine $3 \times 3$ sub-boxes of the grid must contain the digits 1-9 without repetition. +Note: + +A Sudoku board (partially filled) could be valid but is not necessarily solvable. +Only the filled cells need to be validated according to the mentioned rules. + +### Examples + +#### Example 1: + +**Input**: board = +``` +[["5","3",".",".","7",".",".",".","."] +,["6",".",".","1","9","5",".",".","."] +,[".","9","8",".",".",".",".","6","."] +,["8",".",".",".","6",".",".",".","3"] +,["4",".",".","8",".","3",".",".","1"] +,["7",".",".",".","2",".",".",".","6"] +,[".","6",".",".",".",".","2","8","."] +,[".",".",".","4","1","9",".",".","5"] +,[".",".",".",".","8",".",".","7","9"]] +``` +**Output**: true +#### Example 2: + +- **Input:** board = +``` +[["8","3",".",".","7",".",".",".","."] +,["6",".",".","1","9","5",".",".","."] +,[".","9","8",".",".",".",".","6","."] +,["8",".",".",".","6",".",".",".","3"] +,["4",".",".","8",".","3",".",".","1"] +,["7",".",".",".","2",".",".",".","6"] +,[".","6",".",".",".",".","2","8","."] +,[".",".",".","4","1","9",".",".","5"] +,[".",".",".",".","8",".",".","7","9"]] +``` +**Output:** false + +**Explanation**: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left $3 \times 3$ sub-box, it is invalid. + + +### Constraints + +- board.length == 9 +- board[i].length == 9 +- board[i][j] is a digit 1-9 or '.'. + +### Approach + +βœ” HashSet Initialization: The algorithm uses a HashSet (seen) to keep track of unique elements encountered during the traversal of the Sudoku board. + +βœ” Traversing the Board: The algorithm uses nested loops to iterate through each cell of the 9x9 Sudoku board. + +βœ” Checking Rows, Columns, and Sub-boxes +πŸ‘‰ For each non-empty cell (cell value not equal to β€˜.’), the algorithm checks if the current digit is already present in the same row, column, or $3 \times 3$ sub-box using HashSet operations. + +πŸ‘‰ Unique string representations are used to identify rows, columns, and sub-boxes. (don’t worry, will explain it 😊) + +βœ” Returning Validity: + +πŸ‘‰ If all the checks pass for a given cell, the digit is added to the HashSet to mark it as seen. + +πŸ‘‰ The traversal continues until all cells have been processed. + +πŸ‘‰ If any violation is detected during the traversal (i.e., a digit is repeated in a row, column, or sub-box), the function returns false, indicating that the Sudoku board is not valid. + +πŸ‘‰ If the traversal completes without encountering any violations, the function returns true. That’s mean Sudolu board is valid. + +### Solution Code + +#### Python + +``` +class Solution(object): + def isValidSudoku(self, board): + res = [] + for i in range(9): + for j in range(9): + element = board[i][j] + if element != '.': + res += [(i, element), (element, j), (i // 3, j // 3, element)] + return len(res) == len(set(res)) + +``` + +#### Java + +``` +class Solution { + public boolean isValidSudoku(char[][] board) { + Set seen = new HashSet<>(); + + for (int i = 0; i < 9; ++i) + for (int j = 0; j < 9; ++j) { + if (board[i][j] == '.') + continue; + final char c = board[i][j]; + if (!seen.add(c + "@row" + i) || // + !seen.add(c + "@col" + j) || // + !seen.add(c + "@box" + i / 3 + j / 3)) + return false; + } + + return true; + } +} +``` + +#### C++ + +``` +class Solution { +public: + bool isValidSudoku(vector>& board) { + unordered_set rows[9]; + unordered_set cols[9]; + unordered_set boxes[9]; + + for (int r = 0; r < 9; ++r) { + for (int c = 0; c < 9; ++c) { + if (board[r][c] == '.') { + continue; + } + + char value = board[r][c]; + int boxIndex = (r / 3) * 3 + (c / 3); + + if (rows[r].count(value) || cols[c].count(value) || boxes[boxIndex].count(value)) { + return false; + } + + rows[r].insert(value); + cols[c].insert(value); + boxes[boxIndex].insert(value); + } + } + + return true; + } +}; +``` + +### Conclusion + +The above solution efficiently finds if the sudoku configuration is valid or not in $O(1)$ time complexity. diff --git a/solutions/lc-solutions/0000-0099/0037-Sudoku-Solver.md b/solutions/lc-solutions/0000-0099/0037-Sudoku-Solver.md new file mode 100644 index 0000000..dbddef4 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0037-Sudoku-Solver.md @@ -0,0 +1,231 @@ +--- +id: sudoku-solver +title: Sudoku Solver +sidebar_label: 0037-ValidSudoku +tags: + - Array + - Hash Table + - Matrix + - Backtracking +--- + +## Problem Description + +Write a program to solve a Sudoku puzzle by filling the empty cells. + +A sudoku solution must satisfy all of the following rules: + +1. Each of the digits 1-9 must occur exactly once in each row. +2. Each of the digits 1-9 must occur exactly once in each column. +3. Each of the digits 1-9 must occur exactly once in each of the 9 $3 \times 3$ sub-boxes of the grid. + +The '.' character indicates empty cells. + +### Examples + +#### Example 1: + +**Input**: board = + +``` +[["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]] +``` + +**Output**: + +``` +[["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]] +``` + +**Explanation**: The input board is shown above and the only valid solution is shown below: + +### Constraints + +- board.length == 9 +- board[i].length == 9 +- board[i][j] is a digit 1-9 or '.'. +- It is guaranteed that the input board has only one solution. + +### Approach + +πŸ‘‰ Iterate Through Each Cell: The algorithm iterates through each cell of the Sudoku board + +πŸ‘‰ Empty Cell Check: If the current cell is empty (contains β€˜.’), the algorithm proceeds to try different numbers (from β€˜1’ to β€˜9’) in that cell + +πŸ‘‰ Number Placement: For each number, the algorithm checks if placing that number in the current cell is valid according to the Sudoku rules (no repetition in the same row, column, or $3 \times 3$ sub-box). + +πŸ‘‰ Recursive Exploration: If placing a number is valid, the algorithm sets that number in the cell and recursively explores the next empty cell. + +πŸ‘‰ Backtracking: If the recursive exploration leads to an invalid solution, the algorithm backtracks by undoing the choice (resetting the cell to β€˜.’) and trying the next number. + +πŸ‘‰ Solution Check: The algorithm continues exploring possibilities until a valid solution is found, or it exhaustively searches all possibilities. + +### Solution Code + +#### Python + +``` +class Solution: + def solveSudoku(self, board: List[List[str]]) -> None: + def isValid(row: int, col: int, c: str) -> bool: + for i in range(9): + if board[i][col] == c or \ + board[row][i] == c or \ + board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] == c: + return False + return True + + def solve(s: int) -> bool: + if s == 81: + return True + + i = s // 9 + j = s % 9 + + if board[i][j] != '.': + return solve(s + 1) + + for c in string.digits[1:]: + if isValid(i, j, c): + board[i][j] = c + if solve(s + 1): + return True + board[i][j] = '.' + + return False + + solve(0) + +``` + +#### Java + +``` +class Solution { + public void solveSudoku(char[][] board) { + int[][] f=new int[9][10]; + int[][] row=new int[9][10]; + int[][] col=new int[9][10]; + int cell=0; + for(int i=0;i<9;i++){ + for(int j=0;j<9;j++){ + cell=((i/3)*3)+j/3; + if(board[i][j]!='.'){ + f[cell][(int)(board[i][j]-'0')]=1; + row[i][(int)(board[i][j]-'0')]=1; + col[j][(int)(board[i][j]-'0')]=1; + }} + } + get(f,board,0,0,row,col); + return; + + } + static boolean get(int[][] f,char[][] board, int i, int j, int[][] row, int[][] col ){ + if(i==9)return true; + if(board[i][j]!='.'){ + if(j==8){ + return get(f,board,i+1,0,row,col); + }else{ + return get(f,board,i,j+1,row,col); + } + }else{ + boolean t=false; + int cell=((i/3)*3) + j/3; + for(int k=1;k<=9;k++){ + if(f[cell][k]==0 && row[i][k]==0 && col[j][k]==0){ + f[cell][k]=1; + row[i][k]=1; + col[j][k]=1; + board[i][j]=(char) (k + '0'); + if(j==8){ + t=get(f,board,i+1,0,row,col); + }else{ + t=get(f,board,i,j+1,row,col); + } + if(t)return true; + f[cell][k]=0; + row[i][k]=0; + col[j][k]=0; + board[i][j]='.'; + } + } + } + return false; + } + + +} +``` + +#### C++ + +``` +class Solution { +public: + void solveSudoku(vector>& board) { + solve(board); + } + bool solve(vector>& board){ + for(int i=0;i>& board,int row,int col, char c) + { + for(int i=0;i<9;i++) + { + if((board[row][i]==c) || (board[i][col]==c) || (board[3*(row/3) + i/3][3*(col/3) + i%3] ==c)) + return false; + } + return true; + } +}; + +``` + +### Conclusion + +βœ… Time Complexity: + +βœ” The solve method uses a backtracking approach to explore the solution space. + +βœ” In the worst case, the algorithm tries out all possibilities for each empty cell until a valid solution is found or all possibilities are exhausted. + +βœ” The time complexity of the backtracking algorithm is typically exponential, but in practice, it tends to be much less than the worst case. + +βœ” The algorithm explores 9 possibilities for each of the 81 cells, resulting in a time complexity of $O(9^m)$, where m represents the number of empty cells. + +βœ… Space Complexity: + +βœ” The algorithm uses a recursive approach to explore the solution space. + +βœ” The recursive stack depth is proportional to the number of empty cells in the Sudoku board. + +βœ” The space complexity of the backtracking algorithm is typically linear, but in practice, it tends to be much less. + +βœ” The algorithm explores 9 possibilities for each of the 81 cells, resulting in a space complexity of $O(m)$, where m represents the number of empty cells. + +βœ… The algorithm solves the Sudoku puzzle by backtracking through the solution space, exploring possibilities until a valid solution is found or all possibilities are exhausted. + +βœ… The algorithm uses a recursive approach to explore the solution space, setting numbers in empty cells and checking if the placement is valid according to the Sudoku rules. + +βœ… The algorithm backtracks when an invalid solution is found, undoing the choice and trying the next number. diff --git a/solutions/lc-solutions/0000-0099/0038-Count-And-Say.md b/solutions/lc-solutions/0000-0099/0038-Count-And-Say.md new file mode 100644 index 0000000..3646bb8 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0038-Count-And-Say.md @@ -0,0 +1,128 @@ +--- +id: count-and-say +title: Count and Say (LeetCode) +difficulty: Medium +sidebar_label: 0038-CountAndSay +topics: + - String + - Recursion +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/count-and-say/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/count-and-say/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +## Problem Description + +The count-and-say sequence is a sequence of digit strings defined by the recursive formula: + +- countAndSay(1) = "1" +- countAndSay(n) is the run-length encoding of countAndSay(n - 1). + +Run-length encoding (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "3322251" we replace "33" with "23", replace "222" with "32", replace "5" with "15" and replace "1" with "11". Thus the compressed string becomes "23321511". + +Given a positive integer n, return the nth element of the count-and-say sequence. + +### Examples + +#### Example 1 + +- **Input:** n = 4 +- **Output:** "1211" +- **Explanation:** + - countAndSay(1) = "1" + - countAndSay(2) = RLE of "1" = "11" + - countAndSay(3) = RLE of "11" = "21" + - countAndSay(4) = RLE of "21" = "1211" + +#### Example 2 + +- **Input:** n = 1 +- **Output:** "1" +- **Explanation:** This is the base case. + +### Constraints + +- `1 <= n <= 30` + +### Approach + +To solve this problem, we can use a recursive approach. Here's how the algorithm works: + +1. Initialize a base case where if n equals 1, return "1". +2. For any value of n greater than 1, recursively call the function countAndSay(n-1). +3. Convert the result of countAndSay(n-1) into the count-and-say format. + +### Solution Code + +#### Python + +``` +class Solution(object): + def countAndSay(self, n): + if n == 1: + return "1" + prev = self.countAndSay(n - 1) + result = "" + count = 1 + for i in range(len(prev)): + if i + 1 < len(prev) and prev[i] == prev[i + 1]: + count += 1 + else: + result += str(count) + prev[i] + count = 1 + return result +``` + +#### C++ + +``` +class Solution { +public: + string countAndSay(int n) { + if (n == 1) + return "1"; + string prev = countAndSay(n - 1); + string result = ""; + int count = 1; + for (int i = 0; i < prev.length(); ++i) { + if (i + 1 < prev.length() && prev[i] == prev[i + 1]) { + count++; + } else { + result += to_string(count) + prev[i]; + count = 1; + } + } + return result; + } +}; +``` + +#### Java + +``` +class Solution { + public String countAndSay(int n) { + if (n == 1) + return "1"; + String prev = countAndSay(n - 1); + StringBuilder result = new StringBuilder(); + int count = 1; + for (int i = 0; i < prev.length(); ++i) { + if (i + 1 < prev.length() && prev.charAt(i) == prev.charAt(i + 1)) { + count++; + } else { + result.append(count).append(prev.charAt(i)); + count = 1; + } + } + return result.toString(); + } +} +``` + +### Conclusion + +The count-and-say sequence is generated based on the previous sequence using run-length encoding. This problem can be efficiently solved using a recursive approach where each step generates the next sequence based on the previous one. The provided solution code effectively implements this recursive algorithm to generate the nth element of the count-and-say sequence. \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0039-Combination-Sum.md b/solutions/lc-solutions/0000-0099/0039-Combination-Sum.md new file mode 100644 index 0000000..5492e82 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0039-Combination-Sum.md @@ -0,0 +1,194 @@ +--- +id: combination-sum +title: Combination Sum(LeetCode) +sidebar_label: 0039-Combination Sum +tags: + - Array + - Backtracking +description: Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. +sidebar_position: 39 +--- + +## Problem Statement + +Given an array of distinct integers `candidates` and a target integer `target`, return a list of all unique combinations of `candidates` where the chosen numbers +sum to `target`. You may return the combinations in any order. + +The same number may be chosen from `candidates` an unlimited number of times. Two combinations are unique if the +frequency + of at least one of the chosen numbers is different. + +The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. + +### Examples + +**Example 1:** + +```plaintext +Input: candidates = [2,3,6,7], target = 7 +Output: [[2,2,3],[7]] +Explanation: +2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. +7 is a candidate, and 7 = 7. +These are the only two combinations. +``` + +**Example 2:** + +```plaintext +Input: candidates = [2,3,5], target = 8 +Output: [[2,2,2,2],[2,3,3],[3,5]] +``` + +**Example 3:** + +```plaintext +Input: candidates = [2], target = 1 +Output: [] +``` + +### Constraints + +- `1 <= candidates.length <= 30` +- `2 <= candidates[i] <= 40` +- All elements of `candidates` are distinct. +- `1 <= target <= 40` + +## Solution + +The Combination Sum problem involves finding all unique combinations in a list of candidates where the candidate numbers sum to a given target. Each number in the list may be used an +unlimited number of times. Below, we discuss three approaches to solve this problem: DFS (Backtracking), Dynamic Programming (Slow), and Dynamic Programming (Fast). + +### Approach 1: DFS (Backtracking) + +#### Explanation: + +1. Use a recursive function to explore all possible combinations. +2. Track the current combination (`cur`) and its sum (`cur_sum`). +3. If `cur_sum` exceeds the target, backtrack. +4. If `cur_sum` equals the target, add the current combination to the result list. + +#### Algorithm + +1. Initialize an empty list `ans` to store the results. +2. Define a recursive function `dfs(cur, cur_sum, idx)` to explore combinations. +3. In `dfs`, if `cur_sum` exceeds the target, return. +4. If `cur_sum` equals the target, add `cur` to `ans` and return. +5. Loop through candidates starting from `idx`, and recursively call `dfs` with updated `cur` and `cur_sum`. +6. Start the DFS with an empty combination, a sum of 0, and starting index 0. +7. Return the list `ans`. + +#### Implementation + +```python +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + ans = [] + n = len(candidates) + def dfs(cur, cur_sum, idx): + if cur_sum > target: return + if cur_sum == target: + ans.append(cur) + return + for i in range(idx, n): + dfs(cur + [candidates[i]], cur_sum + candidates[i], i) + dfs([], 0, 0) + return ans +``` + +### Complexity Analysis + +- **Time complexity**: O(N^(M/min_cand + 1)), where N is the number of candidates, M is the target, and min_cand is the + smallest candidate. +- **Space complexity**: O(M/min_cand), as the recursion depth can go up to the target divided by the smallest + candidate. + +### Approach 2: Dynamic Programming (Slow) + +#### Explanation: + +1. Use a list `dp` where `dp[i]` contains combinations that sum up to `i`. +2. Build the `dp` list by iterating through all possible sums up to the target. +3. For each sum, update the combinations by considering each candidate. + +#### Algorithm + +1. Create a dictionary `idx_d` to map each candidate to its index. +2. Initialize a list `dp` with empty lists for all sums from 0 to the target. +3. For each sum `i` from 1 to the target: +* Iterate through all previous sums `j` from 0 to `i-1`. +* For each combination in `dp[j]`, update combinations in `dp[i]`. +* Add combinations directly from candidates if they equal `i`. +4. Return the list `dp[-1]`. + +#### Implementation + +```python +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + idx_d = {val: idx for idx, val in enumerate(candidates)} + n = len(candidates) + dp = [[] for _ in range(target + 1)] + for i in range(1, target + 1): + for j in range(i): + for comb in dp[j]: + start_idx = idx_d[comb[-1]] + for val in candidates[start_idx:]: + if val + j == i: + dp[i].append(comb + [val]) + for candidate in candidates: + if candidate == i: + dp[i].append([candidate]) + return dp[-1] +``` + +### Complexity Analysis + +- **Time complexity**: O(MMM*N), where N is the number of candidates and M is the target. +- **Space complexity**: O(M*M), due to the storage of combinations for each sum up to the target. + +### Approach 3: Dynamic Programming (Fast) + +#### Explanation: + +1. Use a list `dp` where `dp[i]` contains combinations that sum up to `i`. +2. For each candidate, update the combinations for all possible sums up to the target. + +#### Algorithm + +1. Initialize a list `dp` with empty lists for all sums from 0 to the target. +2. For each candidate `c`: +3. For each sum `i` from `c` to the target: +* If `i` equals `c`, add `[c]` to `dp[i]`. +* For each combination in `dp[i - c]`, add `comb + [c]` to `dp[i]`. +4. Return the list `dp[-1]`. + +#### Implementation + +```python +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + dp = [[] for _ in range(target + 1)] + for c in candidates: + for i in range(c, target + 1): + if i == c: + dp[i].append([c]) + for comb in dp[i - c]: + dp[i].append(comb + [c]) + return dp[-1] +``` + +### Complexity Analysis + +- **Time complexity**: O(MMN), where N is the number of candidates and M is the target. +- **Space complexity**: O(M*M), due to the storage of combinations for each sum up to the target. + +### Conclusion + +In solving the Combination Sum problem: + +1. DFS (Backtracking) is simple and intuitive but can be slow for large inputs due to its exponential time complexity. +2. Dynamic Programming (Slow) uses a structured approach but has higher time complexity (O(MMM*N)) and memory usage. +3. Dynamic Programming (Fast) is more efficient (O(MMN)), making it suitable for larger inputs, though it still uses significant memory. + +Choose DFS (Backtracking) for smaller datasets, DP (Slow) for a structured approach within manageable limits, and DP (Fast) for larger datasets where efficiency is critical. diff --git a/solutions/lc-solutions/0000-0099/0040-Combination-sum-II.md b/solutions/lc-solutions/0000-0099/0040-Combination-sum-II.md new file mode 100644 index 0000000..c5bf5de --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0040-Combination-sum-II.md @@ -0,0 +1,324 @@ +--- +id: combination-sum-II +title: Combination Sum-II(LeetCode) +sidebar_label: 0040-Combination Sum-II +tags: + - Array + - Backtracking +description: Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. +sidebar_position: 40 +--- + +## Problem Statement + +Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. + +Each number in candidates may only be used once in the combination. + +Note: The solution set must not contain duplicate combinations. + +Example 1: + +Input: candidates = [10,1,2,7,6,1,5], target = 8 +Output: +[ +[1,1,6], +[1,2,5], +[1,7], +[2,6] +] +Example 2: + +Input: candidates = [2,5,2,1,2], target = 5 +Output: +[ +[1,2,2], +[5] +] + +Constraints: + +- 1 `<=` candidates.length `<=` 100 +- 1 `<=` candidates[i] `<=` 50 +- 1 `<=` target `<=` 30 + +## Solutions: + +### Intuition + + The intuition behind the solution involves a backtracking technique, which is similar to depth-first search (DFS). + + Since we need to find all combinations that add up to the target and any number in the candidates can be used only once, we sort the candidates first. Sorting the array helps us to easily skip over duplicate elements and avoid generating duplicate combinations. + + Then, we perform **DFS with backtracking**, starting from the beginning of the candidates array and exploring each possibility by either including or excluding a candidate. After including a candidate in the combination, we call the function recursively, reducing the target by the value of that candidate and moving to the next index. + + While exploring, we keep track of the current sum of the combination, and when the sum equals the target, we add the current combination to the answer. If at any point, the sum exceeds target or we reach the end of the candidates array, we backtrack. + + To prevent duplicates, we skip subsequent candidates that are the same as the previous one at each stage in the loop. This way, we ensure that if a number has been used in a combination, the same number is not used immediately again to form another similar combination. + + The result of the function will be a list of lists, where each inner list is a unique combination of numbers that sum to the target value. + + Learn more about Backtracking patterns. + +### Solution Approach + +The solution uses depth-first search (DFS), backtracking, and sorting to effectively find all unique combinations. Let's break down how each part of the code contributes to the solution: + +1. **Sorting the Candidates:** The candidates array is first sorted to ensure that we can easily skip duplicates. + + - `candidates.sort()` + +2. **Depth-First Search (DFS) Function:** The dfs function is defined to handle the recursion, taking two parameters: i (the current index in the candidates list) and s (the remaining sum needed to reach the target). + + - `def dfs(i: int, s: int):` + +3. **Condition to Add to the Answer:** Inside the dfs function, we check if the remaining sum s is zero, meaning we found a valid combination that sums to the target. In that case, we add a copy of the current combination to the answer list. + + - `if s == 0:` + - `ans.append(t[:])` + +4. **Base Cases for Termination:** We return if the index i moves beyond the length of the candidates or if the remaining sum s is less than the current candidate, which means we can't reach the desired total with the current and subsequent candidates since they are all larger. + + - `if i >= len(candidates) or s < candidates[i]:` + - return + +5. **Loop Over the Candidates:** Starting from the current index to the end of candidates, we try to include the candidate in the combination: + + - `for j in range(i, len(candidates)):` + +6. **Skipping Duplicates:** Before including a candidate in the combination, we skip over it if it's the same as its predecessor to avoid duplicates in our answer list (since we’ve already considered this value in the previous steps). + + - `if j > i and candidates[j] == candidates[j - 1]:` + - continue + +7. **Backtracking:** After including a candidate, the dfs function is called recursively with the updated index (j+1) and the updated remaining sum (s - candidates[j]). After this recursive call, we backtrack by removing the last candidate from the combination and moving on to the next candidate. + + - `t.append(candidates[j])` + - `dfs(j + 1, s - candidates[j])` + - `t.pop()` + +The solution utilizes a list ans to store all the unique combinations and a temporary list t to store the current combination being constructed. + +After defining dfs, the solution begins the search with: + +1. `ans = []` +2. `t = []` +3. `dfs(0, target)` + +The DFS and backtracking continue until all possible combinations that meet the criteria have been explored, after which ans is returned, containing all the valid combinations. + +This approach efficiently explores all possible combinations and prunes the search space to avoid duplicates and unnecessary searches, thereby finding the solution set in an optimal manner. + + + + + ```cpp + #include + #include + #include + + using namespace std; + + void findCombination(int ind, int target, vector& arr, vector>& ans, vector& ds) { + if (target == 0) { + ans.push_back(ds); + return; + } + + for (int i = ind; i < arr.size(); i++) { + if (i > ind && arr[i] == arr[i - 1]) + continue; + if (arr[i] > target) + break; + + ds.push_back(arr[i]); + findCombination(i + 1, target - arr[i], arr, ans, ds); + ds.pop_back(); + } + } + + class Solution { + public: + vector> combinationSum2(vector& candidates, int target) { + sort(candidates.begin(), candidates.end()); + vector> ans; + vector ds; + findCombination(0, target, candidates, ans, ds); + return ans; + } + }; + ``` + + + + ```java + import java.util.*; + + public class Solution { + public void findCombination(int ind, int target, int[] arr, List> ans, List ds) { + if (target == 0) { + ans.add(new ArrayList<>(ds)); + return; + } + + for (int i = ind; i < arr.length; i++) { + if (i > ind && arr[i] == arr[i - 1]) + continue; + if (arr[i] > target) + break; + + ds.add(arr[i]); + findCombination(i + 1, target - arr[i], arr, ans, ds); + ds.remove(ds.size() - 1); + } + } + + public List> combinationSum2(int[] candidates, int target) { + Arrays.sort(candidates); + List> ans = new ArrayList<>(); + findCombination(0, target, candidates, ans, new ArrayList<>()); + return ans; + } + + public static void main(String[] args) { + Solution sol = new Solution(); + int[] candidates = {10, 1, 2, 7, 6, 1, 5}; + int target = 8; + List> result = sol.combinationSum2(candidates, target); + for (List combination : result) { + System.out.println(combination); + } + } + } + ``` + + + + ```python + def findCombination(ind, target, arr, ans, ds): + if target == 0: + ans.append(list(ds)) + return + + for i in range(ind, len(arr)): + if i > ind and arr[i] == arr[i - 1]: + continue + if arr[i] > target: + break + + ds.append(arr[i]) + findCombination(i + 1, target - arr[i], arr, ans, ds) + ds.pop() + + class Solution: + def combinationSum2(self, candidates, target): + candidates.sort() + ans = [] + findCombination(0, target, candidates, ans, []) + return ans + + # Driver code + if __name__ == "__main__": + sol = Solution() + candidates = [10, 1, 2, 7, 6, 1, 5] + target = 8 + result = sol.combinationSum2(candidates, target) + for combination in result: + print(combination) + ``` + + + + ```c + #include + #include + + void findCombination(int ind, int target, int* arr, int arrSize, int** ans, int* returnSize, int* ds, int dsSize) { + if (target == 0) { + ans[*returnSize] = (int*)malloc(dsSize * sizeof(int)); + for (int i = 0; i < dsSize; i++) { + ans[*returnSize][i] = ds[i]; + } + (*returnSize)++; + return; + } + + for (int i = ind; i < arrSize; i++) { + if (i > ind && arr[i] == arr[i - 1]) + continue; + if (arr[i] > target) + break; + + ds[dsSize] = arr[i]; + findCombination(i + 1, target - arr[i], arr, arrSize, ans, returnSize, ds, dsSize + 1); + } + } + + int** combinationSum2(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes) { + qsort(candidates, candidatesSize, sizeof(int), cmpfunc); + int** ans = (int**)malloc(1000 * sizeof(int*)); + int* ds = (int*)malloc(1000 * sizeof(int)); + *returnSize = 0; + + findCombination(0, target, candidates, candidatesSize, ans, returnSize, ds, 0); + + *returnColumnSizes = (int*)malloc(*returnSize * sizeof(int)); + for (int i = 0; i < *returnSize; i++) { + (*returnColumnSizes)[i] = returnColumnSizes[i]; + } + + return ans; + } + + int cmpfunc(const void* a, const void* b) { + return (*(int*)a - *(int*)b); + } + + // Driver code + int main() { + int candidates[] = {10, 1, 2, 7, 6, 1, 5}; + int target = 8; + int returnSize; + int* returnColumnSizes; + int** result = combinationSum2(candidates, sizeof(candidates) / sizeof(candidates[0]), target, &returnSize, &returnColumnSizes); + for (int i = 0; i < returnSize; i++) { + for (int j = 0; j < returnColumnSizes[i]; j++) { + printf("%d ", result[i][j]); + } + printf("\n"); + } + return 0; + } + ``` + + + + +## Time and Space Complexity + +The provided Python code solves the combination sum problem where each number in the array candidates can only be used once to find all unique combinations that sum up to a given target. + +### Time Complexity + +The time complexity of this code primarily depends on the depth of the recursion and the number of recursive calls made at each level. + + 1. The recursion depth is at most the target value if we choose candidates with a value of 1 every time. However, since the same candidate cannot be used repeatedly, the recursion depth is constrained by the number of candidates in the worst case. + + 2. At every level of recursion, we iterate over the remaining candidates, so, in the worst case, the number of recursive calls can be exponential in nature, implied by $O(2^n)$, where n is the number of candidates. However, since we skip duplicates after sorting, the number of branches in the recursion tree can be less than that. + + 3. A more accurate bound is not straightforward because it depends on the candidates and the target value. The worst-case time complexity, without considering duplicates, is $O(2^n)$, where n is the number of candidates. + + 4. The sorting operation at the start of the code takes $O(n*log(n))$ time. + Combining the sorting with the recursion leads to a worst-case time complexity of $O(n*log(n) + 2^n)$. Considering that the exponential part is more dominant, we can approximate it as $O(2^n)$. + +### Space Complexity + +The space complexity of the code consists of: + + 1. Space used by the recursion stack, which in the worst case is equivalent to the depth of recursion, at most $O(n)$ if all candidates are used. + + 2. Space for the temporary list t, which stores the current combination, will at most contain n values, adding another $O(n)$. + + 3. Finally, the output list ans that could potentially hold all unique combinations of candidates. In the worst case, this could be all possible combinations which can be exponential, represented as $O(2^n)$. + + 4. Hence, the overall space complexity, considering the output space and the recursion stack depth, is $O(n + 2^n)$. Typically, the output space can be a separate consideration, and if we exclude it, the space complexity for computation is $O(n)$. However, if we include the space needed for the output, it would be $O(2^n)$ due to the possibility of storing all combinations. diff --git a/solutions/lc-solutions/0000-0099/0041-First-Missing-Positive.md b/solutions/lc-solutions/0000-0099/0041-First-Missing-Positive.md new file mode 100644 index 0000000..0fce1bf --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0041-First-Missing-Positive.md @@ -0,0 +1,155 @@ +--- +id: 41FirstMissingPositive +title: First Missing Positive (LeetCode) +sidebar_label: 0041-First Missing Positive +tags: + - Array + - Hash Table +description: Find the smallest missing positive integer. +sidebar_position: 41 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [First Missing Positive](https://leetcode.com/problems/first-missing-positive/description/) | [First Missing Positive Solution on LeetCode](https://leetcode.com/problems/first-missing-positive/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + + +## Problem Description + +Given an unsorted integer array `nums`, return the smallest missing positive integer. + +You must implement an algorithm that runs in `O(n)` time and uses constant extra space. + +### Example 1 + +- **Input:** `nums = [1,2,0]` +- **Output:** `3` +- **Explanation:** The smallest missing positive integer is `3`. + +### Example 2 + +- **Input:** `nums = [3,4,-1,1]` +- **Output:** `2` +- **Explanation:** The smallest missing positive integer is `2`. + +### Example 3 + +- **Input:** `nums = [7,8,9,11,12]` +- **Output:** `1` +- **Explanation:** The smallest missing positive integer is `1`. + +### Constraints + +- `1 <= nums.length <= 10^5` +- `-2^31 <= nums[i] <= 2^31 - 1` + +## Approach + +To solve the problem, we can use the following approach: + +1. **Mark Elements Out of Range**: + - Iterate through the array and mark elements that are out of the range `[1, n]` by setting them to a number greater than `n`. + +2. **Use Indices as Markers**: + - Use the indices of the array to mark the presence of numbers by negating the value at the corresponding index. + +3. **Identify the Missing Positive**: + - Iterate through the array again to find the first positive value, which indicates the missing positive integer. + +### Solution Code + +#### Python + +```python +class Solution: + def firstMissingPositive(self, nums: List[int]) -> int: + n = len(nums) + + for i in range(n): + if nums[i] <= 0 or nums[i] > n: + nums[i] = n + 1 + + for i in range(n): + num = abs(nums[i]) + if num <= n: + nums[num - 1] = -abs(nums[num - 1]) + + for i in range(n): + if nums[i] > 0: + return i + 1 + + return n + 1 +``` + +#### Java + +```java +class Solution { + public int firstMissingPositive(int[] nums) { + int n = nums.length; + + for (int i = 0; i < n; i++) { + if (nums[i] <= 0 || nums[i] > n) { + nums[i] = n + 1; + } + } + + for (int i = 0; i < n; i++) { + int num = Math.abs(nums[i]); + if (num <= n) { + nums[num - 1] = -Math.abs(nums[num - 1]); + } + } + + for (int i = 0; i < n; i++) { + if (nums[i] > 0) { + return i + 1; + } + } + + return n + 1; + } +} +``` + +#### C++ + +```c++ +#include +#include + +using namespace std; + +class Solution { +public: + int firstMissingPositive(vector& nums) { + int n = nums.size(); + + for (int i = 0; i < n; i++) { + if (nums[i] <= 0 || nums[i] > n) { + nums[i] = n + 1; + } + } + + for (int i = 0; i < n; i++) { + int num = abs(nums[i]); + if (num <= n) { + nums[num - 1] = -abs(nums[num - 1]); + } + } + + for (int i = 0; i < n; i++) { + if (nums[i] > 0) { + return i + 1; + } + } + + return n + 1; + } +}; +``` + +### Conclusion: +This approach ensures that the smallest missing positive integer is found efficiently, using constant extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0042-trapping-rain-water.md b/solutions/lc-solutions/0000-0099/0042-trapping-rain-water.md new file mode 100644 index 0000000..a13e2c9 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0042-trapping-rain-water.md @@ -0,0 +1,212 @@ +--- +id: trapping-rain-water +title: Trapping Rain Water(LeetCode) +sidebar_label: 0042-Trapping Rain Water +tags: + - Array + - Two Pointers + - Dynamic Programming + - Stack + - Monotonic Stack +description: Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. +sidebar_position: 42 +--- + +## Problem Statement + +Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining. + +### Examples + +**Example 1:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/bbfea3b4-4ed2-4d9c-ab6f-551d3a935a49) +```plaintext +Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] +Output: 6 +Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. +In this case, 6 units of rain water (blue section) are being trapped. +``` + +**Example 2:** + +```plaintext +Input: height = [4,2,0,3,2,5] +Output: 9 +``` + +### Constraints + +- `n == height.length` +- `1 <= n <= 2 * 104` +- `0 <= height[i] <= 105` + +## Solution + +The Trapping Rain Water problem involves calculating how much water can be trapped between bars after raining, +given an array representing the elevation map. + +### Approach : Two-Pointer Technique + +This approach uses two pointers to traverse the height array from both ends, maintaining the maximum height encountered from the left and the right. +The trapped water is calculated based on the minimum of these maximum heights. + +#### Explanation: + +1. Initialize two pointers: `left` at the start of the array and `right` at the end. +2. Maintain two variables: `leftMax` for the maximum height encountered from the left and `rightMax` for the maximum height from the right. +3. Iterate through the array using the two pointers: +4. If the height at the left pointer is less than the height at the right pointer: +* Move the left pointer to the right. +* Update `leftMax` if the new height is greater than `leftMax`. +* Calculate trapped water at the left pointer if the new height is less than `leftMax`. +5. If the height at the right pointer is less than or equal to the height at the left pointer: +* Move the right pointer to the left. +* Update `rightMax` if the new height is greater than `rightMax`. +* Calculate trapped water at the right pointer if the new height is less than `rightMax`. +6. Continue this process until the left and right pointers meet. +7. The total trapped water is the sum of water calculated at each step. + +#### Algorithm + +1. Initialize `left` at 0, `right` at the end of the array. +2. Set `leftMax` to the first element, `rightMax` to the last element. +3. While `left` is less than `right`: +4. If `leftMax` is less than `rightMax`: +* Increment `left`. +* Update `leftMax` if the new height is greater. +* Add the difference between `leftMax` and the current height to the water. +4. Else: +* Decrement `right`. +* Update `rightMax` if the new height is greater. +* Add the difference between `rightMax` and the current height to the water. +5. Return the total trapped water. + +#### Implementation + +C++ Solution: + +```C++ +class Solution { +public: + int trap(vector& height) { + int n = height.size(); + int lmax = height[0]; + int rmax = height[n-1]; + int lpos = 1; + int rpos = n-2; + int water = 0; + while (lpos <= rpos) { + if (height[lpos] >= lmax) { + lmax = height[lpos]; + lpos++; + } else if (height[rpos] >= rmax) { + rmax = height[rpos]; + rpos--; + } else if (lmax <= rmax && height[lpos] < lmax) { + water += lmax - height[lpos]; + lpos++; + } else { + water += rmax - height[rpos]; + rpos--; + } + } + return water; + } +}; +``` + +Java Solution: + +```Java +class Solution { + public int trap(int[] height) { + int left = 0, right = height.length - 1; + int leftMax = height[0], rightMax = height[height.length - 1]; + int water = 0; + while (left < right) { + if (leftMax < rightMax) { + left++; + if (leftMax < height[left]) { + leftMax = height[left]; + } else { + water += leftMax - height[left]; + } + } else { + right--; + if (rightMax < height[right]) { + rightMax = height[right]; + } else { + water += rightMax - height[right]; + } + } + } + return water; + } +} +``` + +Python Solution: + +```Python +class Solution: + def sumBackets(self, height: list[int], left, right): + minHeightLeft = height[left] + total = 0 + leftBacket = 0 + locationMinLeft = left + + while left < right: + if height[left] < minHeightLeft: + leftBacket += minHeightLeft - height[left] + else: + minHeightLeft = height[left] + total += leftBacket + leftBacket = 0 + locationMinLeft = left + left += 1 + + if minHeightLeft <= height[right]: + return total + leftBacket, right + else: + return total, locationMinLeft + + def sumBacketsReverce(self, height: list[int], left, right): + minHeightRight = height[right] + total = 0 + rightBacket = 0 + locationMinRight = right + + while left < right: + if height[right] < minHeightRight: + rightBacket += minHeightRight - height[right] + else: + minHeightRight = height[right] + total += rightBacket + rightBacket = 0 + locationMinRight = right + right -= 1 + + if minHeightRight <= height[left]: + return total + rightBacket, left + else: + return total, locationMinRight + + def trap(self, height: List[int]) -> int: + right = len(height) - 1 + left = 0 + totalSum = 0 + + while left < right - 1: + if height[left] < height[right]: + total, left = self.sumBackets(height, left, right) + else: + total, right = self.sumBacketsReverce(height, left, right) + totalSum += total + + return totalSum +``` +### Complexity Analysis + +- **Time complexity**: O(n), where n is the number of elements in the height array. The array is traversed once. +- **Space complexity**: O(1), as no extra space is used except for variables. diff --git a/solutions/lc-solutions/0000-0099/0043-Multiple-Strings.md b/solutions/lc-solutions/0000-0099/0043-Multiple-Strings.md new file mode 100644 index 0000000..b2ea619 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0043-Multiple-Strings.md @@ -0,0 +1,238 @@ +--- +id: Multiple-Strings +title: Multiple-Strings(LeetCode) +sidebar_label: 0043-Multiple-Strings +tags: + - Array + - strings +description: Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. +sidebar_position: 43 +--- + +## Problem Statement: + +Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. + +Note: You must not use any built-in BigInteger library or convert the inputs to integer directly. + +Example 1: + +Input: num1 = "2", num2 = "3" +Output: "6" +Example 2: + +Input: num1 = "123", num2 = "456" +Output: "56088" + +Constraints: + +- `1 <= num1.length, num2.length <= 200` +- `num1 and num2 consist of digits only.` +- `Both num1 and num2 do not contain any leading zero, except the number 0 itself` + +## Solutions: + +### Intuition + +The intuition behind the solution is based on how we perform multiplication by hand between two numbers. More precisely, when we multiply, say, a three-digit number by a two-digit number, we do it digit by digit and keep track of the carries. This process results in a series of partial products, which are then added together to form the final product. + +To implement this in code, we need a data structure to store intermediate results. The approach is to use an array arr to store the digits of the partial products. The length of this array is the sum of the lengths of num1 and num2 because that's the maximum possible length of the result (e.g., 99 \* 99 is 9801, four digits long, which is the sum of the lengths of the numbers being multiplied). + +Next, we iterate over each digit of `num1` and `num2` in nested loops, and for each pair of digits, we multiply them and add the result to the corresponding position in arr. The key formula for the index in arr where we should accumulate the product of digits at positions i and j is `arr[i+j+1]`. + +After we have all the partial products, we then iterate through the arr array to handle carries at each position, adjusting each digit so that it represents a proper digit in a number (less than 10), and propagating the carry to the next position. + +Finally, we need to return the string representation of the number stored in the array, but we skip any leading zeroes, as they don't contribute to the magnitude of the number. We join the remaining digits together to form the resulting product string to be returned. + +### Solution Approach + +The solution follows these steps: + +1. Check for Zero: If either num1 or num2 is "0", the product is "0". We catch this case early to simplify further logic. + +2. Initialization: Determine the lengths `m` and `n` of `num1` and `num2`, respectively. Initialize an array arr of length `m + n` to hold the digits of the product. + +3. Digit-by-Digit Multiplication: + + - Iterate through the digits of num1 and num2 in descending order using two nested loops, with indices i and j. + - Convert current digits to integers and multiply them: a \* b. + - Add the multiplication result to an appropriate position in the array arr: arr[i + j + 1] += a \* b. + - The position i + j + 1 comes from the fact that when you multiply a digit at position i of num1 with a digit at position j of num2, the result will contribute to the digits at positions i + j and i + j + 1 of the product. + +4. Handling Carries: + + - Iterate backwards through arr, starting from the end, to process carries. + - For each position, if the value is greater than 9, divide by 10 to find the carry and keep the remainder: + - `arr[i - 1] += arr[i]` // 10: This propagates the carry to the next higher position. + - `arr[i] %= 10`: This ensures that the current position has only a single digit. + +5. Converting Array to String: + + - If the digit at the highest position (arr[0]) is zero, it's a leading zero and should be omitted. Determine the starting index for the conversion (i), which is 0 if there's no leading zero, and 1 otherwise. + - Join the digits from the arr starting at the right index i to form a string without leading zeros: "".join(str(x) for x in arr[i:]). + +This implementation doesn't use any special algorithms or data structuresβ€”it uses simple arrays and elementary math operations to simulate digit-by-digit multiplication, carefully considering the placement of each partial product and the handling of carries, just like manual multiplication on paper. + + + + + ```cpp + #include + #include + + using namespace std; + + string multiply(string num1, string num2) { + string sum(num1.size() + num2.size(), '0'); + + for (int i = num1.size() - 1; 0 <= i; --i) { + int carry = 0; + for (int j = num2.size() - 1; 0 <= j; --j) { + int tmp = (sum[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry; + sum[i + j + 1] = tmp % 10 + '0'; + carry = tmp / 10; + } + sum[i] += carry; + } + + size_t startpos = sum.find_first_not_of("0"); + if (string::npos != startpos) { + return sum.substr(startpos); + } + return "0"; + } + + // Driver code + int main() { + string num1 = "123"; + string num2 = "456"; + cout << multiply(num1, num2) << endl; // Output: "56088" + return 0; + } + ``` + + + + ```java + public class Solution { + public String multiply(String num1, String num2) { + int m = num1.length(), n = num2.length(); + int[] pos = new int[m + n]; + + for (int i = m - 1; i >= 0; i--) { + for (int j = n - 1; j >= 0; j--) { + int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); + int p1 = i + j, p2 = i + j + 1; + int sum = mul + pos[p2]; + + pos[p1] += sum / 10; + pos[p2] = sum % 10; + } + } + + StringBuilder sb = new StringBuilder(); + for (int p : pos) if (!(sb.length() == 0 && p == 0)) sb.append(p); + return sb.length() == 0 ? "0" : sb.toString(); + } + + // Driver code + public static void main(String[] args) { + Solution sol = new Solution(); + String num1 = "123"; + String num2 = "456"; + System.out.println(sol.multiply(num1, num2)); // Output: "56088" + } + } + ``` + + + + ```python + def multiply(num1: str, num2: str) -> str: + if num1 == "0" or num2 == "0": + return "0" + + result = [0] * (len(num1) + len(num2)) + + for i in range(len(num1) - 1, -1, -1): + for j in range(len(num2) - 1, -1, -1): + mul = (ord(num1[i]) - ord('0')) * (ord(num2[j]) - ord('0')) + p1, p2 = i + j, i + j + 1 + summation = mul + result[p2] + + result[p1] += summation // 10 + result[p2] = summation % 10 + + for i, num in enumerate(result): + if num != 0: + break + + result = ''.join(map(str, result[i:])) + return result + + # Driver code + if __name__ == "__main__": + num1 = "123" + num2 = "456" + print(multiply(num1, num2)) # Output: "56088" + ``` + + + + ```c + #include + #include + #include + + char* multiply(char* num1, char* num2) { + int len1 = strlen(num1); + int len2 = strlen(num2); + int* result = (int*)calloc(len1 + len2, sizeof(int)); + char* resStr = (char*)malloc((len1 + len2 + 1) * sizeof(char)); + memset(resStr, '0', len1 + len2); + resStr[len1 + len2] = '\0'; + + for (int i = len1 - 1; i >= 0; i--) { + for (int j = len2 - 1; j >= 0; j--) { + int mul = (num1[i] - '0') * (num2[j] - '0'); + int p1 = i + j; + int p2 = i + j + 1; + int sum = mul + result[p2]; + + result[p1] += sum / 10; + result[p2] = sum % 10; + } + } + + for (int i = 0; i < len1 + len2; i++) { + resStr[i] = result[i] + '0'; + } + + while (*resStr == '0' && *(resStr + 1) != '\0') { + resStr++; + } + + return resStr; + } + + // Driver code + int main() { + char num1[] = "123"; + char num2[] = "456"; + printf("%s\n", multiply(num1, num2)); // Output: "56088" + return 0; + } + ``` + + + + +## Time and Space Complexity + +### Time Complexity: + +The time complexity of the given code is $O(m * n)$, where m and n are the lengths of the input strings num1 and num2 respectively. The code involves a double loop where the outer loop runs m times and the inner loop runs n times, leading to `m * n` multiplication operations. Additionally, there is a loop for carrying over the values, which runs in $O(m + n)$ time. However, since $O(m * n)$ dominates $O(m + n)$, the overall time complexity stays $O(m * n)$. + +### Space Complexity: + +The space complexity is $O(m + n)$, as an additional array arr of size `m + n` is used to store the intermediate results of the multiplication before they are converted to the final string result. diff --git a/solutions/lc-solutions/0000-0099/0044-Wildcard-Matching.md b/solutions/lc-solutions/0000-0099/0044-Wildcard-Matching.md new file mode 100644 index 0000000..529aea7 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0044-Wildcard-Matching.md @@ -0,0 +1,198 @@ +--- +id: wildcard-matching +title: Wildcard Matching (LeetCode Problem - solution) +sidebar_label: 44 Wildcard Matching +tags: + - Array + - strings +description: Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where. +sidebar_position: 44 +--- + +## Problem Statement + +Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for `'?'` and `'*'` where: + +- `'?'` Matches any single character. +- `'*'` Matches any sequence of characters (including the empty sequence). + +The matching should cover the entire input string (not partial). + +## Examples + +### Example 1 + +```plaintext +Input: s = "aa", p = "a" +Output: false +Explanation: "a" does not match the entire string "aa". +``` + +### Example 2 + +```plaintext +Input: s = "aa", p = "*" +Output: true +Explanation: '*' matches any sequence. +``` + +### Example 3 + +```plaintext +Input: s = "cb", p = "?a" +Output: false +Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. +``` + +## Constraints + +- $0 \leq \text{s.length}, \text{p.length} \leq 2000$ +- `s` contains only lowercase English letters. +- `p` contains only lowercase English letters, `'?'` or `'*'`. +- It is guaranteed for each appearance of the character `'*'` there will be a previous valid character to match. + +--- + +## Solution + +The problem can be solved using dynamic programming. We can create a 2D array `dp` of size `n+1` x `m+1` where `n` is the length of the string `s` and `m` is the length of the pattern `p`. The value of `dp[i][j]` will be `true` if the first `i` characters of the string `s` match the first `j` characters of the pattern `p`. + +The base case will be `dp[0][0] = true` as an empty string matches an empty pattern. The value of `dp[i][0]` will be `false` as an empty pattern cannot match a non-empty string. The value of `dp[0][j]` will be `true` if the pattern `p` consists of only `*` characters. + +For each cell `dp[i][j]`, we will check the following conditions: + +1. If the $i^{th}$ character of the string `s` matches the $j^{th}$ character of the pattern `p` or the $j^{th}$ character of the pattern `p` is `?`, then `dp[i][j] = dp[i-1][j-1]`. +2. If the $j^{th}$ character of the pattern `p` is `*`, then `dp[i][j] = dp[i-1][j] || dp[i][j-1]`. + +Finally, the value of `dp[n][m]` will be the answer. + + + + + ```js + /** + * @param {string} s + * @param {string} p + * @return {boolean} + */ + + var isMatch = function(s, p) { + let n = s.length; + let m = p.length; + let dp = new Array(n+1).fill(false).map(() => new Array(m+1).fill(false)); + dp[0][0] = true; + + for (let j = 1; j <= m; j++) { + if (p[j-1] === '*') { + dp[0][j] = dp[0][j-1]; + } + } + + for (let i = 1; i <= n; i++) { + for (let j = 1; j <= m; j++) { + if (s[i-1] === p[j-1] || p[j-1] === '?') { + dp[i][j] = dp[i-1][j-1]; + } else if (p[j-1] === '*') { + dp[i][j] = dp[i-1][j] || dp[i][j-1]; + } + } + } + + return dp[n][m]; + }; + ``` + + + + + ```python + def isMatch(s: str, p: str) -> bool: + n, m = len(s), len(p) + dp = [[False] * (m+1) for _ in range(n+1)] + dp[0][0] = True + + for j in range(1, m+1): + if p[j-1] == '*': + dp[0][j] = dp[0][j-1] + + for i in range(1, n+1): + for j in range(1, m+1): + if s[i-1] == p[j-1] or p[j-1] == '?': + dp[i][j] = dp[i-1][j-1] + elif p[j-1] == '*': + dp[i][j] = dp[i-1][j] or dp[i][j-1] + + return dp[n][m] + ``` + + + + + ```java + class Solution { + public boolean isMatch(String s, String p) { + int n = s.length(); + int m = p.length(); + boolean[][] dp = new boolean[n+1][m+1]; + dp[0][0] = true; + + for (int j = 1; j <= m; j++) { + if (p.charAt(j-1) == '*') { + dp[0][j] = dp[0][j-1]; + } + } + + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + if (s.charAt(i-1) == p.charAt(j-1) || p.charAt(j-1) == '?') { + dp[i][j] = dp[i-1][j-1]; + } else if (p.charAt(j-1) == '*') { + dp[i][j] = dp[i-1][j] || dp[i][j-1]; + } + } + } + + return dp[n][m]; + } + } + ``` + + + + +## Complexity Analysis + +The time complexity for the above approach is $O(n \times m)$ where `n` is the length of the string `s` and `m` is the length of the pattern `p`. + +The space complexity is $O(n \times m)$ as we are using a 2D array of size `n+1` x `m+1`. + +## Video Content For Better Understanding + + + +## Related Problems + +- [Regular Expression Matching (LeetCode)](https://leetcode.com/problems/regular-expression-matching/) +- [Longest Common Subsequence (LeetCode)](https://leetcode.com/problems/longest-common-subsequence/) +- [Longest Common Subsequence (GeeksForGeeks)](https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/) + +## References + +- [LeetCode](https://leetcode.com/problems/wildcard-matching/) +- [GeeksForGeeks](https://www.geeksforgeeks.org/wildcard-pattern-matching/) + + +--- + +

Authors:

+ +
+{['ajay-dhangar', 'SadafKausar2025'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0045-jump-game-II.md b/solutions/lc-solutions/0000-0099/0045-jump-game-II.md new file mode 100644 index 0000000..e14a27f --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0045-jump-game-II.md @@ -0,0 +1,153 @@ +--- +id: jump-game-II +title: Jump Game II(LeetCode) +sidebar_label: 0045-Jump-Game-II +tags: + - Array + - Dynamic Programming + - Greedy +description: You are given a 0-indexed array of integers nums of length `n`. Return the minimum number of jumps to reach `nums[n - 1]`. +sidebar_position: 45 +--- + +## Problem Statement + +You are given a 0-indexed array of integers `nums` of length `n`. You are initially positioned at `nums[0]`. + +Each element `nums[i]` represents the maximum length of a forward jump from index `i`. In other words, if you are at `nums[i]`, you can jump to any `nums[i + j]` where: + +- `0 <= j <= nums[i]` and +- `i + j < n` +Return the minimum number of jumps to reach `nums[n - 1]`. The test cases are generated such that you can reach `nums[n - 1]`. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [2,3,1,1,4] +Output: 2 +Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. +``` + +**Example 2:** + +```plaintext +Input: nums = [2,3,0,1,4] +Output: 2 +``` + +### Constraints + +- `1 <= nums.length <= 104` +- `0 <= nums[i] <= 1000` +- It's guaranteed that you can reach `nums[n - 1]`. + +## Solution + +In this problem, we aim to find the minimum number of jumps required to reach the end of the array, starting from the first element. We explore three main approaches: Recursive Dynamic Programming with +Memoization, Iterative Dynamic Programming with Tabulation, and a Greedy BFS approach. + +### Approach 1: Recursive Dynamic Programming (Memoization) +Concept: Store the solutions for each position to avoid redundant calculations. + +#### Algorithm + +1. Initialize `dp` array with a large value to indicate uncomputed positions. +2. Call the recursive function `solve` starting from position 0. +3. In `solve`: +* If the position is at or beyond the end, return 0. +* If `dp[pos]` is already computed, return its value. +* Explore all possible jumps from the current position. +* Store and return the minimum jumps required. + +#### Implementation + +```C++ +int jump(vector& nums) { + vector dp(size(nums), 10001); + return solve(nums, dp, 0); +} + +int solve(vector& nums, vector& dp, int pos) { + if(pos >= size(nums) - 1) return 0; + if(dp[pos] != 10001) return dp[pos]; + for(int j = 1; j <= nums[pos]; j++) + dp[pos] = min(dp[pos], 1 + solve(nums, dp, pos + j)); + return dp[pos]; +} +``` + +### Complexity Analysis + +- **Time complexity**: O(N^2) +- **Space complexity**: O(N) + +### Approach 2: Iterative Dynamic Programming (Tabulation) + +Concept: Start from the last index and iteratively compute the minimum jumps required for each position. + +#### Algorithm + +1. Initialize `dp` array with large values and set `dp[n-1]` to 0. +2. Iterate from the second last index to the start. +3. For each index, explore all possible jumps and store the minimum jumps required. + +#### Implementation + +```C++ +int jump(vector& nums) { + int n = size(nums); + vector dp(n, 10001); + dp[n - 1] = 0; + for(int i = n - 2; i >= 0; i--) + for(int jumpLen = 1; jumpLen <= nums[i]; jumpLen++) + dp[i] = min(dp[i], 1 + dp[min(n - 1, i + jumpLen)]); + return dp[0]; +} +``` + +### Complexity Analysis + +- **Time complexity**: O(N^2) +- **Space complexity**: O(N) + +### Approach 3: Greedy BFS + +Concept: Use two pointers to track the furthest reachable position +and the currently furthest reached position. Update the jump count when moving to a new level. + +#### Algorithm + +1. Initialize `maxReachable`, `lastJumpedPos`, and `jumps`. +2. Iterate over the array until the lastJumpedPos reaches or exceeds the last index. +3. Update `maxReachable` with the furthest position reachable from the current index. +4. When `i` equals `lastJumpedPos`, move to `maxReachable` and increment jumps. + +#### Implementation + +```C++ +int jump(vector& nums) { + int n = size(nums), i = 0, maxReachable = 0, lastJumpedPos = 0, jumps = 0; + while(lastJumpedPos < n - 1) { + maxReachable = max(maxReachable, i + nums[i]); + if(i == lastJumpedPos) { + lastJumpedPos = maxReachable; + jumps++; + } + i++; + } + return jumps; +} +``` + +### Complexity Analysis + +- **Time complexity**: O(N) +- **Space complexity**: O(1) + +### Conclusion + +1. Recursive DP with Memoization: Efficiently avoids redundant calculations but has higher time complexity. +2. Iterative DP with Tabulation: Iteratively solves for each position but has quadratic time complexity. +3. Greedy BFS: Provides the most optimal solution with linear time complexity and constant space, making it the best approach for this problem. diff --git a/solutions/lc-solutions/0000-0099/0046-Permutations.md b/solutions/lc-solutions/0000-0099/0046-Permutations.md new file mode 100644 index 0000000..c4840d3 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0046-Permutations.md @@ -0,0 +1,215 @@ +--- +id: permutations +title: Permutations(LeetCode) +sidebar_label: 0046-Permutations +tags: + - Array + - Backtracking +description: Given an array `nums` of distinct integers, return all the possible permutations. You can return the answer in any order. + +sidebar_position: 46 +--- + +## Problem Statement + +Given an array `nums` of distinct integers, return all the possible permutations. You can return the answer in any order. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [1,2,3] +Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] +``` + +**Example 2:** + +```plaintext +Input: nums = [0,1] +Output: [[0,1],[1,0]] +``` + +**Example 3:** + +```plaintext +Input: nums = [1] +Output: [[1]] +``` + +### Constraints: + +- `1 <= nums.length <= 6` +- `10 <= nums[i] <= 10` +- All the integers of `nums` are unique. + +## Solution + +In this problem, we aim to find all the possible permutations from an array of distinct integers. We explore two main approaches: Recursive approach and Backtracking approach. + +### Approach 1: Recursive +We have given the nums array, so we will declare an ans vector of vector that will store all the permutations also declare a data structure. + +Declare a map and initialize it to zero and call the recursive function + +Base condition : + +When the data structure's size is equal to n(size of nums array) then it is a permutation and stores that permutation in our ans, then returns it. + +Recursion: + +Run a for loop starting from 0 to nums.size() - 1. Check if the frequency of i is unmarked, if it is unmarked then it means it has not been picked and then we pick. And make sure it is marked as picked. + +Call the recursion with the parameters to pick the other elements when we come back from the recursion make sure you throw that element out. And unmark that element in the map. + +#### Implementation + +```C++ +class Solution { + private: + void recurPermute(vector < int > & ds, vector < int > & nums, vector < vector < int >> & ans, int freq[]) { + if (ds.size() == nums.size()) { + ans.push_back(ds); + return; + } + for (int i = 0; i < nums.size(); i++) { + if (!freq[i]) { + ds.push_back(nums[i]); + freq[i] = 1; + recurPermute(ds, nums, ans, freq); + freq[i] = 0; + ds.pop_back(); + } + } + } + public: + vector < vector < int >> permute(vector < int > & nums) { + vector < vector < int >> ans; + vector < int > ds; + int freq[nums.size()]; + for (int i = 0; i < nums.size(); i++) freq[i] = 0; + recurPermute(ds, nums, ans, freq); + return ans; + } +}; +``` + +```Java +class Solution { + private void recurPermute(int index, int[] nums, List < List < Integer >> ans) { + if (index == nums.length) { + // copy the ds to ans + List < Integer > ds = new ArrayList < > (); + for (int i = 0; i < nums.length; i++) { + ds.add(nums[i]); + } + ans.add(new ArrayList < > (ds)); + return; + } + for (int i = index; i < nums.length; i++) { + swap(i, index, nums); + recurPermute(index + 1, nums, ans); + swap(i, index, nums); + } + } + private void swap(int i, int j, int[] nums) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } + public List < List < Integer >> permute(int[] nums) { + List < List < Integer >> ans = new ArrayList < > (); + recurPermute(0, nums, ans); + return ans; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: N! x N +- **Space complexity**: O(N) + +### Approach 2: With Backtracking + +We have given the nums array, so we will declare an ans vector of vector that will store all the permutations. + +Call a recursive function that starts with zero, nums array, and ans vector. + +Declare a map and initialize it to zero and call the recursive function + +Base condition: + +Whenever the index reaches the end take the nums array and put it in ans vector and return. + +Recursion: + +Go from index to n - 1 and swap once the swap has been done call recursion for the next state. After coming back from the recursion make sure you re-swap it because, for the next element, the swap will not take place. + +#### Implementation + +```C++ +class Solution { + private: + void recurPermute(int index, vector < int > & nums, vector < vector < int >> & ans) { + if (index == nums.size()) { + ans.push_back(nums); + return; + } + for (int i = index; i < nums.size(); i++) { + swap(nums[index], nums[i]); + recurPermute(index + 1, nums, ans); + swap(nums[index], nums[i]); + } + } + public: + vector < vector < int >> permute(vector < int > & nums) { + vector < vector < int >> ans; + recurPermute(0, nums, ans); + return ans; + } +}; +``` + +```Java +class Solution { + private void recurPermute(int index, int[] nums, List < List < Integer >> ans) { + if (index == nums.length) { + // copy the ds to ans + List < Integer > ds = new ArrayList < > (); + for (int i = 0; i < nums.length; i++) { + ds.add(nums[i]); + } + ans.add(new ArrayList < > (ds)); + return; + } + for (int i = index; i < nums.length; i++) { + swap(i, index, nums); + recurPermute(index + 1, nums, ans); + swap(i, index, nums); + } + } + private void swap(int i, int j, int[] nums) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } + public List < List < Integer >> permute(int[] nums) { + List < List < Integer >> ans = new ArrayList < > (); + recurPermute(0, nums, ans); + return ans; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: O(N! X N) +- **Space complexity**: O(1) + + +### Conclusion + +1. Recursive DP with Memoization: Efficiently avoids redundant calculations but has higher time complexity. +2. Iterative DP with Tabulation: Iteratively solves for each position but has quadratic time complexity. +3. Greedy BFS: Provides the most optimal solution with linear time complexity and constant space, making it the best approach for this problem. diff --git a/solutions/lc-solutions/0000-0099/0047-Permutations-ll.md b/solutions/lc-solutions/0000-0099/0047-Permutations-ll.md new file mode 100644 index 0000000..6c40cde --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0047-Permutations-ll.md @@ -0,0 +1,230 @@ +--- +id: permutations-ll +title: Permutation-2 +sidebar_label: 0047-Permutations 2 +tags: + - Array + - Backtracking + - String +description: "Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order." +--- + +## Problem Description + +Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order. + + +### Examples + +**Example 1:** + +``` +Input +nums = [1,1,2] +Output +[[1,1,2], + [1,2,1], + [2,1,1]] +``` +**Example 2:** + +``` +Input: nums = [1,2,3] +Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] +``` + +### Constraints + +- `1 <= nums.length <= 8` +- `-10 <= nums[i] <= 10` + + +## Solution for Letter combination of phone number + +### Intuition +As the name of the problem suggests, this problem is an extension of the Permutation problem. +The problem is different from the previous permutation problem on the condition that the input array can contain duplicates. + +The key to solve the problem is still the backtracking algorithm. +However, we need some adaptation to ensure that the enumerated solutions generated from our backtracking exploration do not have any duplicates. + + + + +### Complexity Analysis + +1. Time Complexity: +- n! is the number of permutations. +- n is the time to construct each permutation. + +2. Space Complexity: +- - We need space to store the frequency counter, the recursion stack, and the current permutation. Each of these requires \(O(n)\) space. + + + + + +## Approach + +### Backtracking with Groups of Numbers + +#### Intuition + +First of all, let us review the general idea of permutation with an example. + +Given the input array [1, 1, 2], to generate a permutation of the array, we could follow the Depth-First Search (DFS) approach, or more precisely the backtracking technique as one will see later. + +Let us walk through the example with paper and pencil, as follows: + +- Given the input of [1, 1, 2], at the first stage, we have 2 choices to pick a number as the first number in the final permutation, i.e. 1 and 2. +- Suppose that we pick the number 1, now the remaining numbers would become [1, 2]. +Note: The reason that we have only 2 choices instead of 3, is that there is a duplicate in the given input. +- Picking any of the duplicate numbers as the first number of the permutation would lead us to the same permutation at the end. +- Should the numbers in the array be all unique, we would then have the same number of choices as the length of the array. + +- At the second stage, we now then have again 2 choices, i.e. [1, 2]. +Let us pick again the number 1, which leaves us the only remaining number 2. + +- Now at the third stage, we have only one candidate number left, i.e. [2]. We then pick the last remaining number, which leads to a final permutation sequence of [1, 1, 2]. + +- Moreover, we need to revisit each of the above stages, and make a different choice in order to try out all possibilities. +- The reversion of the choices is what we call backtracking. + +- We illustrate all potential exploration in the following graph where each node represents a choice at a specific stage: + + +### Algorithm + +Given the above insight, in order to find out all the unique numbers at each stage, we can build a hash table (denoted as counter), with each unique number as the key and its occurrence as the corresponding value. + +To implement the algorithm, first we define a function called backtrack(comb, counter) which generates all permutations, starting from the current combination (comb) and the remaining numbers (counter). + +Once the function is implemented, it suffices to invoke the function with the initial empty combination and the hash table we built out of the input array, to solve the problem. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector> permuteUnique(vector& nums) { + vector> results; + unordered_map counter; + for (int num : nums) counter[num]++; + vector comb; + backtrack(counter, comb, nums.size(), results); + return results; + } + void backtrack(unordered_map& counter, vector& comb, int N, + vector>& results) { + if (comb.size() == N) { + results.push_back(comb); + return; + } + for (auto& item : counter) { + int num = item.first; + int count = item.second; + if (count == 0) continue; + comb.push_back(num); + counter[num]--; + backtrack(counter, comb, N, results); + comb.pop_back(); + counter[num]++; + } + } +}; + + +``` + + + + +```java +class Solution { + public List> permuteUnique(int[] nums) { + List> results = new ArrayList<>(); + + HashMap counter = new HashMap<>(); + for (int num : nums) { + if (!counter.containsKey(num)) counter.put(num, 0); + counter.put(num, counter.get(num) + 1); + } + + LinkedList comb = new LinkedList<>(); + this.backtrack(comb, nums.length, counter, results); + return results; + } + + protected void backtrack( + LinkedList comb, + Integer N, + HashMap counter, + List> results + ) { + if (comb.size() == N) { + results.add(new ArrayList(comb)); + return; + } + + for (Map.Entry entry : counter.entrySet()) { + Integer num = entry.getKey(); + Integer count = entry.getValue(); + if (count == 0) continue; + comb.addLast(num); + counter.put(num, count - 1); + + backtrack(comb, N, counter, results); + + comb.removeLast(); + counter.put(num, count); + } + } +} +``` + + + + + +```python +class Solution: + def permuteUnique(self, nums: List[int]) -> List[List[int]]: + results = [] + + def backtrack(comb, counter): + if len(comb) == len(nums): + # make a deep copy of the resulting permutation, + # since the permutation would be backtracked later. + results.append(list(comb)) + return + + for num in counter: + if counter[num] > 0: + comb.append(num) + counter[num] -= 1 + backtrack(comb, counter) + comb.pop() + counter[num] += 1 + + backtrack([], Counter(nums)) + + return results +``` + + + + + +## Conclusion +This solution ensures that all unique permutations are generated by carefully tracking and using the frequency of each element in the input array. The use of a counter helps to manage duplicates effectively, and the backtracking approach explores all possible permutations while maintaining the uniqueness constraint. + + +## References + +- **LeetCode Problem**: [Letter combinatino of Phone number](https://leetcode.com/problems/permutations-ii/description/) + +- **Solution Link**: [letter combination of phone number](https://leetcode.com/problems/permutations-ii/editorial/) \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0048-Rotate-Image.md b/solutions/lc-solutions/0000-0099/0048-Rotate-Image.md new file mode 100644 index 0000000..eb6d096 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0048-Rotate-Image.md @@ -0,0 +1,231 @@ +--- +id: 48-rotate-image +title: Rotate Image (LeetCode) +sidebar_label: 0048-RotateImage +tags: + - Array + - Math + - Matrix +description: given an 2D matrix which is representing an image, rotate the image by 90 degrees. +--- + +## Problem Description + +- You are given an `n x n` 2D `matrix` representing an image, rotate the image by 90 degrees (clockwise). +- You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO not allocate another 2D matrix and do the rotation. + +### Examples + +#### Example 1 + +```plaintext +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] +Output: [[7,4,1],[8,5,2],[9,6,3]] +``` + +#### Example 2: + +```plaintext +Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] +Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] +``` + +### Constraints: + +- $n == \text{matrix.length} == \text{matrix[i].length}$ +- $1 \leq n \leq 20$ +- $-1000 \leq \text{matrix[i][j]} \leq 1000$ + +### Approach + +**1. Initialize Variables:** `n` The dimension of the matrix (assuming it is an n x n matrix). + +**2. Transpose the Matrix:** Loop through each element of the matrix and swap elements symmetrically around the diagonal. + +**3. Reverse Each Row:** Loop through each row and reverse the elements in place. + +### Solution Codes + +#### Codes in Different Languages + + + + + +```cpp +class Solution { +public: + void rotate(vector>& matrix) { + vector ans; + + int row = matrix.size(); // no of rows + int col = matrix[0].size(); // no of cols + + int count = 0; // no of ele + int total = row * col; // total ele + + int startingrow = 0; + int startingcol = 0; + int endingrow = row - 1; + int endingcol = col - 1; + + while (count < total) { + // print starting row -> ending col + for (int index = startingcol; count < total && index <= endingcol; + index++) { + ans.push_back(matrix[index][endingrow]); + count++; + } + endingrow--; //++ + + // print ending col -> ending row + for (int index = startingrow; count < total && index <= endingrow; + index++) { + ans.push_back(matrix[endingcol][index]); + count++; + } + endingcol--; + + // ending row -> starting col + for (int index = endingcol; count < total && index >= startingcol; + index--) { + ans.push_back(matrix[index][startingrow]); + count++; + } + startingrow++; + + // sarting column -> starting row + for (int index = endingrow; count < total && index >= startingrow; + index--) { + ans.push_back(matrix[startingcol][index]); + count++; + } + startingcol++; + } + + } +}; +``` + + + + + +```py + class Solution: + def rotate(self, matrix): + ans = [] + # number of rows + row = len(matrix) + # number of columns + col = len(matrix[0]) + + count = 0 + total = row * col + + starting_row = 0 + starting_col = 0 + ending_row = row - 1 + ending_col = col - 1 + + while count < total: + #starting row -> ending col + for index in range(starting_col, ending_col + 1): + if count < total: + ans.append(matrix[index][ending_row]) + count += 1 + ending_row -= 1 + + # ending col -> ending row + for index in range(starting_row, ending_row + 1): + if count < total: + ans.append(matrix[ending_col][index]) + count += 1 + ending_col -= 1 + + # ending row -> starting col + for index in range(ending_col, starting_col - 1, -1): + if count < total: + ans.append(matrix[index][starting_row]) + count += 1 + starting_row += 1 + + # starting column -> starting row + for index in range(ending_row, starting_row - 1, -1): + if count < total: + ans.append(matrix[starting_col][index]) + count += 1 + starting_col += 1 + + return ans +``` + + + + + +```java +import java.util.ArrayList; +import java.util.List; + +class Solution { + public List rotate(int[][] matrix) { + List ans = new ArrayList<>(); + + // number of rows + int row = matrix.length; + // number of columns + int col = matrix[0].length; + + int count = 0; + int total = row * col; + + int startingRow = 0; + int startingCol = 0; + int endingRow = row - 1; + int endingCol = col - 1; + + while (count < total) { + // starting row -> ending col + for (int index = startingCol; count < total && index <= endingCol; index++) { + ans.add(matrix[index][endingRow]); + count++; + } + endingRow--; + + // ending col -> ending row + for (int index = startingRow; count < total && index <= endingRow; index++) { + ans.add(matrix[endingCol][index]); + count++; + } + endingCol--; + + // ending row -> starting col + for (int index = endingCol; count < total && index >= startingCol; index--) { + ans.add(matrix[index][startingRow]); + count++; + } + startingRow++; + + // starting column -> starting row + for (int index = endingRow; count < total && index >= startingRow; index--) { + ans.add(matrix[startingCol][index]); + count++; + } + startingCol++; + } + + return ans; + } +} +``` + + + + +### Conclusion + +The above solution will help you to rotate an 2D Array (Image) with + +- Time Complexity: $O(n^2)$ +- Space Complexity: $O(1)$ diff --git a/solutions/lc-solutions/0000-0099/0049-Group-Anagrams.md b/solutions/lc-solutions/0000-0099/0049-Group-Anagrams.md new file mode 100644 index 0000000..420f346 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0049-Group-Anagrams.md @@ -0,0 +1,144 @@ +--- +id: group-anagrams +title: Group Anagrams (LeetCode) +sidebar_label: 0049-Group Anagrams +tags: + - Array + - Hash Table + - String + - Sorting +description: Given an array of strings , group the anagrams together. +sidebar_position: 0049 +--- + +## Problem Description + +The task is to write a function that takes an array (list) of strings called strs and groups the anagrams together. An anagram is a word obtained by rearranging the letters of another word to form a new word using all the original characters exactly once. For example, "taste" and "state" are anagrams of each other. The function can return the groups in any order, meaning the sequence of the groups is not important, and within each group, the sequence of strings is not important either. + +### Example 1 + +- **Input:** `strs = ["eat","tea","tan","ate","nat","bat"]` +- **Output:** `[["bat"],["nat","tan"],["ate","eat","tea"]]` +- **Explanation:** + - ["ate", "eat","tea"](when sorted all these strings are "aet"), + - ["nat","tan"](when sorted all these strings are "ant"), + - ["bat"](this string has no other string as anagram so it is appended as only 1) + +### Example 2 + +- **Input:** ` strs = [""]` +- **Output:** `[[""]]` +- **Explanation:** There are no strings so empty vector is returned. + +### Example 3 + +- **Input:** ` strs = ["a"]` +- **Output:** `[["a"]]` +- **Explanation:** There is only one string "a" it is returned. + +### Constraints + +- `1 <= strs.length <= 10^4` +- `0 <= strs[i].length <= 100` +- `strs[i] consists of lowercase English letters.` + +## Approach +- 1. Create a defaultdict of lists: d = defaultdict(list). This will store our anagrams. + +- 2. Iterate through each string in the array: + + - "bat": When sorted, becomes "abt". We append "bat" to d["abt"]. + - "ate": When sorted, becomes "aet". We append "ate" to d["aet"]. + - "eat": When sorted, becomes "aet". We append "eat" to d["aet"]. + - "tea": When sorted, becomes "aet". We append "tea" to d["aet"]. + - "tan": When sorted, becomes "ant". We append "tan" to d["ant"]. + - "nat": When sorted, becomes "ant". We append "nat" to d["ant"]. +- 3. Now, d looks like this: `{ + "abt": ["bat" ], + "aet": ["eat", "tea" , "ate"], + "ant": ["tan", "nat"] + }` + - Each key corresponds to a sorted string, and the values are the original strings that are anagrams. + +- 4. Finally, we return the dictionary values as a list of lists: + + - [ + ["bat"], + ["eat", "tea" , "ate"], + ["tan", "nat"] + ] + +### Solution Code + +#### Python + +```python +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + anagrams = defaultdict(list) + for s in strs: + key = "".join(sorted(s)) + anagrams[key].append(s) + return list(anagrams.values()) +``` + +#### C++ +```c++ +class Solution { +public: + vector> groupAnagrams(vector& strs) { + unordered_map> anagramGroups; + for (auto& str : strs) { + string key = str; + sort(key.begin(), key.end()); + anagramGroups[key].emplace_back(str); + } + vector> groupedAnagrams; + for (auto& pair : anagramGroups) { + groupedAnagrams.emplace_back(pair.second); + } + return groupedAnagrams; + } +}; +``` + +#### Java +```Java +import java.util.*; + +class Solution { + public List> groupAnagrams(String[] strs) { + Map> anagramsMap = new HashMap<>(); + for (String str : strs) { + char[] charArray = str.toCharArray(); + Arrays.sort(charArray); + String sortedStr = String.valueOf(charArray); + anagramsMap.computeIfAbsent(sortedStr, key -> new ArrayList<>()).add(str); + } + return new ArrayList<>(anagramsMap.values()); + } +} + +``` + + + + +#### Conclusion +- Time Complexity +The time complexity of the code is primarily determined by two operations: the sorting operation for each string and the insertion into the dictionary. + + - 1. Sorting Each String: Assuming the average length of the strings is n and there are m strings to sort, the time complexity of sorting each is O(n log n). Since we need to sort m such strings, the total time complexity for this part is O(m * n log n). + + - 2. Inserting into Dictionary: The insertion of m strings into the dictionary has a time complexity of O(m), since each insertion operation into a dictionary is O(1) on average. + + - The total time complexity as O(m * n log n). + +- Space Complexity +The space complexity is due to the storage of m entries in the dictionary and the lists of anagrams. + + - 1. Dictionary Storage (HashMap): The dictionary stores lists of anagrams. In the worst case, all strings are anagrams of each other, requiring O(m * n) space (since each of the m strings of length n can be in the same list). + + - 2. Sorted String Keys: Additionally, for each string, we create a sorted copy to use as a key. Since we sort each string in place and only have m keys at any point in time, the space for the keys would be O(m * n). + + - The total space complexity of the algorithm is O(m * n), \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0050-pow(x,n).md b/solutions/lc-solutions/0000-0099/0050-pow(x,n).md new file mode 100644 index 0000000..b752e9c --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0050-pow(x,n).md @@ -0,0 +1,139 @@ +--- +id: powx-n +title: Pow(x,n) +difficulty: Medium +sidebar_label: 0050-powxn +tags: + - Math + - Recursion +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Pow(x,n)](https://leetcode.com/problems/powx-n/description/) | [Pow(x,n) Solution on LeetCode](https://leetcode.com/problems/powx-n/solutions/) | [Leetcode Profile](https://leetcode.com/u/debangi_29/) | + +## Problem Description + +Implement pow(x, n), which calculates x raised to the power n (i.e., $x^n$). + + + +### Examples + +### Example 1: + +**Input**: x = 2.00000, n = 10 + +**Output**: 1024.00000 + + +### Example 2: + +**Input**: x = 2.10000, n = 3 + +**Output**: 9.26100 + +### Example 3: + +**Input**: x = 2.00000, n = -2 + +**Output**: 0.25000 + +**Explanation**: 2-2 = 1/22 = 1/4 = 0.25 + + +### Constraints + +- $-100.0 < x < 100.0$ +- $-2^{31} \leq n \leq 2^{31} - 1$ +- $n$ is an integer. +- Either $x$ is not zero or $n > 0$. +- $-10^{4} \leq x^{n} \leq 10^{4}$ + +### Approach +Initialize ans as 1.0 and store a duplicate copy of n i.e nn using to avoid overflow + +Check if nn is a negative number, in that case, make it a positive number. + +Keep on iterating until nn is greater than zero, now if nn is an odd power then multiply x with ans ans reduce nn by 1. Else multiply x with itself and divide nn by two. + +Now after the entire binary exponentiation is complete and nn becomes zero, check if n is a negative value we know the answer will be 1 by and. + +### Solution Code + +#### Python + +``` +class Solution: + def myPow(x: float, n: int) -> float: + ans = 1.0 + nn = n + if nn < 0: + nn = -1 * nn + while nn: + if nn % 2: + ans = ans * x + nn = nn - 1 + else: + x = x * x + nn = nn // 2 + if n < 0: + ans = 1.0 / ans + return ans +``` + +#### Java + +``` +class Solution { + public static double myPow(double x, int n) { + double ans = 1.0; + long nn = n; + if (nn < 0) nn = -1 * nn; + while (nn > 0) { + if (nn % 2 == 1) { + ans = ans * x; + nn = nn - 1; + } else { + x = x * x; + nn = nn / 2; + } + } + if (n < 0) ans = (double)(1.0) / (double)(ans); + return ans; + } +} +``` + +#### C++ + +``` +class Solution { + public: + double myPow(double x, int n) { + double ans = 1.0; + long long nn = n; + if (nn < 0) nn = -1 * nn; + while (nn) { + if (nn % 2) { + ans = ans * x; + nn = nn - 1; + } else { + x = x * x; + nn = nn / 2; + } + } + if (n < 0) ans = (double)(1.0) / (double)(ans); + return ans; +} +}; + +``` + +### Conclusion + +- Time Complexity: $O(log n)$ , where n is the exponent; Using Binary exponentiation. + +- Space Complexity: $O(1)$ as we are not using any extra space. diff --git a/solutions/lc-solutions/0000-0099/0051-N-queens-Puzzle.md b/solutions/lc-solutions/0000-0099/0051-N-queens-Puzzle.md new file mode 100644 index 0000000..d0196db --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0051-N-queens-Puzzle.md @@ -0,0 +1,302 @@ +--- +id: n-queens-uzzle +title: N-Queens Puzzle +sidebar_label: N-Queens Puzzle +tags: + - Backtracking + - Recursion + - Algorithm +description: The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [n-queens-puzzle](https://leetcode.com/problems/N-Queens-Puzzle/description/) | [N-Queens-Puzzle Solution on LeetCode](https://leetcode.com/problems/N-Queens-Puzzle/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description: + +The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. + +Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively. + +### Example 1 + +- **Input:** `n = 4` +- **Output:** `[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]` +- **Explanation:** `There exist two distinct solutions to the 4-queens puzzle as shown above` + +### Example 2 + +- **Input:** `n = 1` +- **Output:** `[["Q"]]` + +### Constraints + +- $1 \leq n \leq 9$ + +### Approach +The problem can be solved using a backtracking approach. The idea is to place queens one by one on the board and check if the current placement is safe. If it is, we proceed to place the next queen. If it is not, we backtrack and try the next possible position. + +### Solution in different languages + +### Solution in Python +```python +def solveNQueens(n): + def is_not_under_attack(row, col): + return not (cols[col] or hills[row - col] or dales[row + col]) + + def place_queen(row, col): + queens.add((row, col)) + cols[col] = 1 + hills[row - col] = 1 + dales[row + col] = 1 + + def remove_queen(row, col): + queens.remove((row, col)) + cols[col] = 0 + hills[row - col] = 0 + dales[row + col] = 0 + + def add_solution(): + solution = [] + for _, col in sorted(queens): + solution.append('.' * col + 'Q' + '.' * (n - col - 1)) + solutions.append(solution) + + def backtrack(row = 0): + for col in range(n): + if is_not_under_attack(row, col): + place_queen(row, col) + if row + 1 == n: + add_solution() + else: + backtrack(row + 1) + remove_queen(row, col) + + solutions = [] + queens = set() + cols = [0] * n + hills = [0] * (2 * n - 1) + dales = [0] * (2 * n - 1) + backtrack() + return solutions +``` + +### Solution in Java +```java +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +class Solution { + public List> solveNQueens(int n) { + List> solutions = new ArrayList<>(); + Set cols = new HashSet<>(); + Set hills = new HashSet<>(); + Set dales = new HashSet<>(); + backtrack(solutions, new ArrayList<>(), cols, hills, dales, n, 0); + return solutions; + } + + private void backtrack(List> solutions, List queens, Set cols, Set hills, Set dales, int n, int row) { + if (row == n) { + solutions.add(createBoard(queens, n)); + return; + } + for (int col = 0; col < n; col++) { + if (cols.contains(col) || hills.contains(row - col) || dales.contains(row + col)) { + continue; + } + queens.add(col); + cols.add(col); + hills.add(row - col); + dales.add(row + col); + backtrack(solutions, queens, cols, hills, dales, n, row + 1); + queens.remove(queens.size() - 1); + cols.remove(col); + hills.remove(row - col); + dales.remove(row + col); + } + } + + private List createBoard(List queens, int n) { + List board = new ArrayList<>(); + for (int i = 0; i < n; i++) { + char[] row = new char[n]; + for (int j = 0; j < n; j++) { + row[j] = '.'; + } + row[queens.get(i)] = 'Q'; + board.add(new String(row)); + } + return board; + } +} +``` + +### Solution in C++ +```cpp +class Solution { +public: + vector> solveNQueens(int n) { + vector> solutions; + vector queens(n, -1); + vector cols(n, 0), hills(2 * n - 1, 0), dales(2 * n - 1, 0); + backtrack(solutions, queens, n, 0, cols, hills, dales); + return solutions; + } + +private: + void backtrack(vector>& solutions, vector& queens, int n, int row, vector& cols, vector& hills, vector& dales) { + if (row == n) { + solutions.push_back(createBoard(queens, n)); + return; + } + for (int col = 0; col < n; col++) { + if (cols[col] || hills[row - col + n - 1] || dales[row + col]) { + continue; + } + queens[row] = col; + cols[col] = hills[row - col + n - 1] = dales[row + col] = 1; + backtrack(solutions, queens, n, row + 1, cols, hills, dales); + cols[col] = hills[row - col + n - 1] = dales[row + col] = 0; + } + } + + vector createBoard(vector& queens, int n) { + vector board; + for (int i = 0; i < n; i++) { + string row(n, '.'); + row[queens[i]] = 'Q'; + board.push_back(row); + } + return board; + } +}; +``` + +### Solution in C +```c +#include +#include + +void addSolution(int **solutions, int *queens, int n, int *returnSize) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + solutions[*returnSize][i * n + j] = (queens[i] == j) ? 'Q' : '.'; + } + } + (*returnSize)++; +} + +void backtrack(int **solutions, int *queens, int *cols, int *hills, int *dales, int n, int row, int *returnSize) { + if (row == n) { + addSolution(solutions, queens, n, returnSize); + return; + } + for (int col = 0; col < n; col++) { + if (cols[col] || hills[row - col + n - 1] || dales[row + col]) { + continue; + } + queens[row] = col; + cols[col] = hills[row - col + n - 1] = dales[row + col] = 1; + backtrack(solutions, queens, cols, hills, dales, n, row + 1, returnSize); + cols[col] = hills[row - col + n - 1] = dales[row + col] = 0; + } +} + +char*** solveNQueens(int n, int* returnSize, int** returnColumnSizes) { + *returnSize = 0; + int totalSolutions = 1; + for (int i = 1; i <= n; i++) totalSolutions *= i; + + char ***solutions = (char ***)malloc(totalSolutions * sizeof(char **)); + *returnColumnSizes = (int *)malloc(totalSolutions * sizeof(int)); + + for (int i = 0; i < totalSolutions; i++) { + solutions[i] = (char **)malloc(n * sizeof(char *)); + for (int j = 0; j < n; j++) { + solutions[i][j] = (char *)malloc((n + 1) * sizeof(char)); + } + (*returnColumnSizes)[i] = n; + } + + int *queens = (int *)malloc(n * sizeof(int)); + int *cols = (int *)malloc(n * sizeof(int)); + int *hills = (int *)malloc((2 * n - 1) * sizeof(int)); + int *dales = (int *)malloc((2 * n - 1) * sizeof(int)); + for (int i = 0; i < n; i++) cols[i] = 0; + for (int i = 0; i < 2 * n - 1; i++) hills[i] = dales[i] = 0; + + backtrack(solutions, queens, cols, hills, dales, n, 0, returnSize); + + return solutions; +} +``` + +### Solution in JavaScript +```js +var solveNQueens = function(n) { + const solutions = []; + const queens = []; + const cols = new Set(); + const hills = new Set(); + const dales = new Set(); + + const backtrack = (row = 0) => { + if (row === n) { + solutions.push(createBoard(queens, n)); + return; + } + for (let col = 0; col < n; col++) { + if (cols.has(col) || hills.has(row - col) || dales.has(row + col)) { + continue; + } + queens.push(col); + cols.add(col); + hills.add(row - col); + dales.add(row + col); + backtrack(row + 1); + queens.pop(); + cols.delete(col); + hills.delete(row - col); + dales.delete(row + col); + } + }; + + const createBoard = (queens, n) => { + const board = []; + for (let i = 0; i < n; i++) { + let row = '.'.repeat(n).split(''); + row[queens[i]] = 'Q'; + board.push(row.join('')); + } + return board; + }; + + backtrack(); + return solutions; +}; +``` + +### Step-by-step Algorithm + +1. Initialize Data Structures: +- Create a list to store the solutions. +- Create sets to keep track of columns, hills (main diagonals), and dales (anti-diagonals) that are under attack. + +2. Backtracking Function: +- Try placing a queen in each column of the current row. +- Check if the current column, hill, or dale is under attack using the sets. +- If placing a queen is safe, add the column to the list of queens and mark the column, hill, and dale as occupied. +- Recursively call the backtracking function for the next row. +- If a valid solution is found (when row equals n), add the solution to the list of solutions. +- Backtrack by removing the queen and unmarking the column, hill, and dale. +3. Create Board Representation: +- Convert the list of queen positions into the board representation as a list of strings. + +### Conclusion +The n-queens puzzle, solved using backtracking, ensures no two queens attack each other on an n x n chessboard. Solutions are efficiently implemented in Python, Java, C++, C, and JavaScript. diff --git a/solutions/lc-solutions/0000-0099/0052-N-queens-ll.md b/solutions/lc-solutions/0000-0099/0052-N-queens-ll.md new file mode 100644 index 0000000..3f693d7 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0052-N-queens-ll.md @@ -0,0 +1,221 @@ +--- +id: n-queens-ll +title: N Queens-2 +difficulty: Hard +sidebar_label: 0052-N-queens-2 +topics: + - Array + - Divide and Conquer +companies: + - "" +description: | + The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. +--- + + + +## Problem Description + +The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. + +Given an integer n, return the number of distinct solutions to the n-queens puzzle. + +### Examples + +#### Example 1 +- **Input:** n = 4 +- **Output:** 2 +- **Explanation:** TThere are two distinct solutions to the 4-queens puzzle as shown. + + +#### Example 2 + +- **Input:** n=1 +- **Output:** 1 + +### Constraints + +- `1 <= n <= 9` + + + +### Approach to Solve the N-Queens Problem + +#### Problem Overview + +The N-Queens problem requires placing N queens on an NΓ—N chessboard such that no two queens threaten each other. A queen can attack any piece that lies in the same row, column, or diagonal. + +### Approach Explanation + +#### Base Cases Handling + +- **If `n == 1`**: Directly return `1` because there is only one way to place a queen on a 1x1 board. +- **If `n <= 3`**: Return `0` because for `n = 2` and `n = 3`, no valid placement of queens exists. + +#### Initialization + +- Initialize three boolean arrays (`col`, `dig`, `crdig`) to track columns and diagonals: + - `col[i]`: Tracks whether column `i` is occupied by a queen. + - `dig[j]`: Tracks whether diagonal \( j \) (from top-left to bottom-right) is occupied by a queen. + - `crdig[k]`: Tracks whether diagonal \( k \) (from top-right to bottom-left) is occupied by a queen. +- These arrays efficiently check if a queen can be placed at a specific position on the board without conflicting with other queens. + +#### Backtracking Function (`backTrack`) + +- **Parameters**: `backTrack` takes `n` (board size) and `lvl` (current level/row being considered). +- **Base Case**: If `lvl == n`, all rows from `0` to `n-1` have queens placed successfully. Increment the `ans` counter (total number of valid solutions) and return. +- **Recursive Backtracking**: + - Iterate through each column (`i`) of the current row (`lvl`). + - Check if placing a queen at position `(lvl, i)` is valid: + - Ensure `col[i]`, `dig[lvl + i]`, and `crdig[lvl - i + n - 1]` are all `false`. + - If valid, mark these positions as occupied (`true`), recursively call `backTrack` for the next row (`lvl + 1`), and then backtrack by marking these positions as unoccupied (`false`). + +#### Constraints Application + +- The arrays `col`, `dig`, and `crdig` are crucial for quickly determining if a position is under attack by any previously placed queens, thereby minimizing unnecessary checks and improving efficiency. + +#### Counting Solutions + +- After all recursive calls from `backTrack` return, `ans` contains the total number of distinct solutions found. + + + +### Complexity Analysis +#### Time Complexity +The time complexity of the algorithm is \( O(n^n) \). + +#### Space Complexity +The space complexity of the algorithm is \( O(n) \). + + + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int totalNQueens(int n) { + if (n == 1) + return 1; + if (n <= 3) + return 0; + col = vector (n, false); + dig = vector (2*n - 1, false); + crdig = vector (2*n - 1, false); + + backTrack(n, 0); + return ans; + } +private: + int ans; + vector col; + vector dig; + vector crdig; + + void backTrack(int n, int lvl) { + if (lvl == n) { + ans++; + return; + } + int toAdd = n - 1; + for (int i = 0; i < n; i++) { + if (!col[i] && !dig[lvl + i] && !crdig[lvl - i + toAdd]) { + col[i] = dig[lvl + i] = crdig[lvl - i + toAdd] = true; + backTrack(n, lvl + 1); + col[i] = dig[lvl + i] = crdig[lvl - i + toAdd] = false; + } + } + + } +}; + +``` + + + + +```java +class Solution { + public int totalNQueens(int n) { + return this.helper(new boolean[n * 2], new boolean[n * 2], new boolean[n], 0, n); + } + + private int helper(final boolean[] diag1, final boolean[] diag2, final boolean[] col, final int row, final int n) { + if(row == n) + return 1; + + int result = 0; + + for(int i = 0; i < n; ++i) { + if(!diag1[row + i] && !diag2[n - row + i] && !col[i]) { + diag1[row + i] = true; + diag2[n - row + i] = true; + col[i] = true; + + result += this.helper(diag1, diag2, col, row + 1, n); + + diag1[row + i] = false; + diag2[n - row + i] = false; + col[i] = false; + } + } + + return result; + } +} +``` + + + + + +```python +class Solution: + def totalNQueens(self, n: int) -> int: + rows = [0 for _ in range(n)] + ldiags = [0 for _ in range(2 * n + 1)] + rdiags = [0 for _ in range(2 * n + 1)] + total = 0 + + def backtrack(i, j_range=None): + nonlocal rows + nonlocal ldiags + nonlocal rdiags + nonlocal total + + for j in range(*j_range) if j_range else range(n): + if not ( + rows[j] or rdiags[(r := i + j)] or ldiags[(l := i - j + n - 1)] + ): + if i + 1 == n: + total += 1 + else: + rows[j] = 1 + ldiags[l] = 1 + rdiags[r] = 1 + backtrack(i + 1) + rows[j] = 0 + ldiags[l] = 0 + rdiags[r] = 0 + + backtrack(0, (0, n // 2)) + total *= 2 + if n % 2: + backtrack(0, (n // 2, n // 2 + 1)) + + return total +``` + + + + + +## References + +- **LeetCode Problem**: [N - Queens-2](https://leetcode.com/problems/cherry-pickup/description/) + +- **Solution Link**: [N- Queens-2](https://leetcode.com/problems/n-queens-ii/solutions/5205950/beats-100-c-backtracking/) diff --git a/solutions/lc-solutions/0000-0099/0053-Maximum-Subarray.md b/solutions/lc-solutions/0000-0099/0053-Maximum-Subarray.md new file mode 100644 index 0000000..1e2e9d0 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0053-Maximum-Subarray.md @@ -0,0 +1,118 @@ +--- +id: maximum-subarray +title: Maximum Subarray (LeetCode) +difficulty: Medium +sidebar_label: 0053-MaximumSubarray +topics: + - Array + - Divide and Conquer +companies: + - "" +description: | + Given an integer array nums, find the subarray with the largest sum, and return its sum. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/maximum-subarray/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/maximum-subarray/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +## Problem Description + +Given an integer array `nums`, find the subarray with the largest sum, and return its sum. + +### Examples + +#### Example 1 + +- **Input:** nums = [-2,1,-3,4,-1,2,1,-5,4] +- **Output:** 6 +- **Explanation:** The subarray [4,-1,2,1] has the largest sum 6. + +#### Example 2 + +- **Input:** nums = [1] +- **Output:** 1 +- **Explanation:** The subarray [1] has the largest sum 1. + +#### Example 3 + +- **Input:** nums = [5,4,-1,7,8] +- **Output:** 23 +- **Explanation:** The subarray [5,4,-1,7,8] has the largest sum 23. + +### Constraints + +- `1 <= nums.length <= 10^5` +- `-10^4 <= nums[i] <= 10^4` + +### Approach + +To find the subarray with the largest sum, we can utilize the Kadane's algorithm, which efficiently solves this problem in linear time complexity O(n). + +#### Kadane's Algorithm + +1. Initialize two variables `max_sum` and `current_sum` to store the maximum sum found so far and the current sum of subarray, respectively. +2. Iterate through the array: + - Update `current_sum` by adding the current element to it. + - If `current_sum` becomes negative, reset it to 0 (indicating the start of a new potential subarray). + - Update `max_sum` if `current_sum` is greater than `max_sum`. +3. Finally, return `max_sum`. + +### Solution Code + +#### Python + +``` +class Solution(object): + def maxSubArray(self, nums): + if not nums: + return 0 + max_sum = curr_sum = nums[0] + for num in nums[1:]: + curr_sum = max(num, curr_sum + num) + max_sum = max(max_sum, curr_sum) + return max_sum +``` + +#### C++ + +``` +class Solution { +public: + int maxSubArray(vector& nums) { + int max_sum = nums[0]; + int current_sum = 0; + for (int num : nums) { + current_sum += num; + max_sum = max(max_sum, current_sum); + if (current_sum < 0) + current_sum = 0; + } + return max_sum; + } +}; +``` + +#### Java + +``` +class Solution { + public int maxSubArray(int[] nums) { + int max_sum = nums[0]; + int current_sum = 0; + for (int num : nums) { + current_sum += num; + max_sum = Math.max(max_sum, current_sum); + if (current_sum < 0) + current_sum = 0; + } + return max_sum; + } +} +``` + +### Conclusion + +The Maximum Subarray problem can be efficiently solved using Kadane's algorithm, which finds the subarray with the largest sum in linear time complexity O(n). The provided solution code implements this algorithm in Python, C++, and Java, providing an optimal solution to the problem. \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0054-spiral-matrix.md b/solutions/lc-solutions/0000-0099/0054-spiral-matrix.md new file mode 100644 index 0000000..ba90eb3 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0054-spiral-matrix.md @@ -0,0 +1,242 @@ +--- +id: spiral-matrix +title: Spiral Matrix +sidebar_label: 0054-Spiral-Matrix +tags: +- Array +- Matrix +- Simulation +- C++ +- Java +- Python +description: "This document provides a solution to the Spiral Matrix problem, where the goal is to traverse a matrix in spiral order." +--- + +## Problem + +Given an `m x n` matrix, return all elements of the matrix in spiral order. + +### Example 1: + +Input: +matrix = [ +[ 1, 2, 3 ], +[ 4, 5, 6 ], +[ 7, 8, 9 ] +] + +Output: +[1, 2, 3, 6, 9, 8, 7, 4, 5] + +### Example 2: + +Input: +matrix = [ +[1, 2, 3, 4], +[5, 6, 7, 8], +[9, 10, 11, 12] +] + +Output: +[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] + +### Constraints: + +- `m == matrix.length` +- `n == matrix[i].length` +- `1 <= m, n <= 10` +- `-100 <= matrix[i][j] <= 100` + +## Solution + +To solve this problem, we need to simulate the traversal of the matrix in spiral order. We can define four boundaries to keep track of the rows and columns that we have already traversed: `top`, `bottom`, `left`, and `right`. We start at the top-left corner and move in the following order: + +1. Traverse from left to right. +2. Traverse downwards. +3. Traverse from right to left. +4. Traverse upwards. + +We continue this process while adjusting the boundaries until all elements have been traversed. + +### Step-by-Step Approach + +1. Initialize `top`, `bottom`, `left`, and `right` boundaries. +2. Use a loop to traverse the matrix until all elements are visited: + - Traverse from left to right within the `top` boundary and increment `top`. + - Traverse downwards within the `right` boundary and decrement `right`. + - Traverse from right to left within the `bottom` boundary and decrement `bottom`. + - Traverse upwards within the `left` boundary and increment `left`. + +### Code in Different Languages + +### C++ Solution + +```cpp + +#include +using namespace std; + +vector spiralOrder(vector>& matrix) { + if (matrix.empty()) return {}; + + int m = matrix.size(), n = matrix[0].size(); + vector result; + int top = 0, bottom = m - 1; + int left = 0, right = n - 1; + + while (top <= bottom && left <= right) { + // Traverse from left to right + for (int i = left; i <= right; ++i) { + result.push_back(matrix[top][i]); + } + ++top; + + // Traverse downwards + for (int i = top; i <= bottom; ++i) { + result.push_back(matrix[i][right]); + } + --right; + + if (top <= bottom) { + // Traverse from right to left + for (int i = right; i >= left; --i) { + result.push_back(matrix[bottom][i]); + } + --bottom; + } + + if (left <= right) { + // Traverse upwards + for (int i = bottom; i >= top; --i) { + result.push_back(matrix[i][left]); + } + ++left; + } + } + + return result; +} + +int main() { + vector> matrix = { + {1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12} + }; + vector result = spiralOrder(matrix); + for (int num : result) { + cout << num << " "; + } + return 0; +} + +``` +### JAVA Solution +```java +import java.util.ArrayList; +import java.util.List; + +public class SpiralMatrix { + public List spiralOrder(int[][] matrix) { + List result = new ArrayList<>(); + if (matrix.length == 0) return result; + + int top = 0, bottom = matrix.length - 1; + int left = 0, right = matrix[0].length - 1; + + while (top <= bottom && left <= right) { + for (int i = left; i <= right; i++) { + result.add(matrix[top][i]); + } + top++; + + for (int i = top; i <= bottom; i++) { + result.add(matrix[i][right]); + } + right--; + + if (top <= bottom) { + for (int i = right; i >= left; i--) { + result.add(matrix[bottom][i]); + } + bottom--; + } + + if (left <= right) { + for (int i = bottom; i >= top; i--) { + result.add(matrix[i][left]); + } + left++; + } + } + + return result; + } + + public static void main(String[] args) { + SpiralMatrix sm = new SpiralMatrix(); + int[][] matrix = { + {1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12} + }; + System.out.println(sm.spiralOrder(matrix)); // Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] + } +} + +``` +### Python Solution + +```python + def spiralOrder(matrix): + if not matrix: + return [] + + result = [] + top, bottom = 0, len(matrix) - 1 + left, right = 0, len(matrix[0]) - 1 + + while top <= bottom and left <= right: + # Traverse from left to right + for i in range(left, right + 1): + result.append(matrix[top][i]) + top += 1 + + # Traverse downwards + for i in range(top, bottom + 1): + result.append(matrix[i][right]) + right -= 1 + + if top <= bottom: + # Traverse from right to left + for i in range(right, left - 1, -1): + result.append(matrix[bottom][i]) + bottom -= 1 + + if left <= right: + # Traverse upwards + for i in range(bottom, top - 1, -1): + result.append(matrix[i][left]) + left += 1 + + return result + +matrix = [ + [1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12] +] +print(spiralOrder(matrix)) # Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] + +``` + +### Complexity Analysis +#### Time Complexity: O(m * n) +>Reason: We visit every element in the matrix exactly once. + +**Space Complexity:** O(1) +>Reason: We only use a fixed amount of extra space, regardless of the input size. +### References +**LeetCode Problem:** Spiral Matrix + + diff --git a/solutions/lc-solutions/0000-0099/0055-jump-game.md b/solutions/lc-solutions/0000-0099/0055-jump-game.md new file mode 100644 index 0000000..fc7e3df --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0055-jump-game.md @@ -0,0 +1,248 @@ +--- +id: jump-game +title: Jump Game +sidebar_label: 0055 - Jump-Game +tags: + - Array + - Dynamic programming + - Greedy +description: "You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position." +--- + +## Problem Description + +You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. + +Return true if you can reach the last index, or false otherwise. + + +### Examples + +**Example 1:** + +``` +Input nums = [2,3,1,1,4] +Output true +``` +**Explanation:** +``` +Jump 1 step from index 0 to 1, then 3 steps to the last index. +``` + +**Example 2:** + +``` +Input: nums = [3,2,1,0,4] +Output: false +``` +**Explanation :** + +``` +You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. +``` +### Constraints + +- `1 <= nums.length <= 104` +- `0 <= nums[i] <= 105` + + +### Solution for Jump Game + +### Intuition +Move goal position to the left if we meet a simple condition. + + +## Approach +We have several ways to reach goal(= the last index) or other index from a current position, so my strategy is to move goal to left position if we meet a simple condition. + +The condition is + +- if current position + maximum jump >= goal +- If we meet the condition we update goal with current index. + +- Let's see how it works. + +- Input: `nums = [2,3,1,1,4]` +We start at the second position from the last. +``` +[2,3,1,1,4] + i g + +i = current position +g = goal +``` + +- Let's use the formula above. + +```current position + maximum jump >= goal += 3 + 1 >= 4 += true``` + +- We can reach the current goal(= index 4) from current position(= index 3), that means if we reach index 3, we are sure that we can definitely reach the goal(= the last index). + +- That's why we can move goal to index 3. + +Next, +``` +[2,3,1,1,4] + i g +current position + maximum jump >= goal += 2 + 1 >= 3 += true +``` +- If true, we are sure we can reach index 3 from index 2. We know that if we reach index 3, we can reach the last index, so update goal with index 2. In the next time, if we can reach index 2, that means we can reach the last index(= 4) + +Next, +``` +[2,3,1,1,4] + i g +I'll speed up. + +current position + maximum jump >= goal += 1 + 3 >= 2 += true +[2,3,1,1,4] + i g +current position + maximum jump >= goal += 0 + 2 >= 1 += true +In the end, + +[2,3,1,1,4] + g + ``` +- Now, goal is index 0. That means we can reach the goal because we start from index 0, so before we return true or false, we check this condition. + +```if goal == 0 +In this case + +return true +``` + +### Complexity Analysis + +#### Time Complexity: $O(n)$ + +#### Space Complexity: $O(1)$ + + + +## Step by Step Algorithm + +1. ### Initialization: + +```goal = len(nums) - 1``` +`goal = len(nums) - 1: ` +Initialize the variable goal to the last index of the array nums. This represents the goal position we want to reach. + +2. ### Main Loop: +```for i in range(len(nums) - 2, -1, -1):``` + +`for i in range(len(nums) - 2, -1, -1):` Iterate backward through the array nums, starting from the second to last element down to the first element. + +3. ### Checking Jumpability: + +```if i + nums[i] >= goal:``` +`if i + nums[i] >= goal: `Check if the current index i plus the maximum jump length at that position (nums[i]) is greater than or equal to the goal. If it is, it means we can jump from index i to the goal or beyond. + +4. ### Updating Goal: + +```goal = i``` +`goal = i:` If the condition in step 3 is met, update the goal to the current index i. This means we have found a new closer position from which we can reach the previous goal position. + +5. ### Return Result: + +```return True if goal == 0 else False``` +`return True if goal == 0 else False:` If we successfully reach the first index (i.e., `goal == 0`), return True, indicating that it's possible to reach the last index from the first index. Otherwise, return `False`. + + + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + bool canJump(vector& nums) { + int goal = nums.size() - 1; + + for (int i = nums.size() - 2; i >= 0; i--) { + if (i + nums[i] >= goal) { + goal = i; + } + } + + return goal == 0; + } +}; + + +``` + + + + +```java +class Solution { + public boolean canJump(int[] nums) { + int goal = nums.length - 1; + + for (int i = nums.length - 2; i >= 0; i--) { + if (i + nums[i] >= goal) { + goal = i; + } + } + + return goal == 0; + } +} +``` + + + + + +```python +class Solution: + def canJump(self, nums: List[int]) -> bool: + goal = len(nums) - 1 + + for i in range(len(nums) - 2, -1, -1): + if i + nums[i] >= goal: + goal = i + + return True if goal == 0 else False +``` + + + + +```Javascript +var canJump = function(nums) { + let goal = nums.length - 1; + + for (let i = nums.length - 2; i >= 0; i--) { + if (i + nums[i] >= goal) { + goal = i; + } + } + + return goal === 0; +}; + +``` + + + + + + + +## References + +- **LeetCode Problem**: [Jump game](https://leetcode.com/problems/jump-game/description/) + +- **Solution Link**: [Jump Game](https://leetcode.com/problems/jump-game/solutions/5130181/video-move-goal-position/) \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0056-merge-intervals.md b/solutions/lc-solutions/0000-0099/0056-merge-intervals.md new file mode 100644 index 0000000..b582ba5 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0056-merge-intervals.md @@ -0,0 +1,143 @@ +--- +id: merge-intervals +title: Merge Intervals(LeetCode) +sidebar_label: 0056-Merge Intervals +tags: + - Array + - Sorting +description: Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. +--- + +## Problem Statement + +Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. + +### Examples + +**Example 1:** + +```plaintext +Input: intervals = [[1,3],[2,6],[8,10],[15,18]] +Output: [[1,6],[8,10],[15,18]] +Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. +``` + +**Example 2:** + +```plaintext +Input: intervals = [[1,4],[4,5]] +Output: [[1,5]] +Explanation: Intervals [1,4] and [4,5] are considered overlapping. +``` + +### Constraints + +- `1 <= intervals.length <= 104` +- `intervals[i].length == 2` +- `0 <= starti <= endi <= 104` + +## Solution + +### Approach + +#### Algorithm + +1. Edge Case Handling: +* If the input list of intervals is empty or contains only one interval, return the input as there is nothing to merge. +2. Sorting: +* Sort the intervals based on their starting points. This makes it easier to merge overlapping intervals as they will be adjacent. +3. Merging Intervals: +* Initialize a new interval with the first interval and start iterating through the sorted intervals. +* For each interval, check if it overlaps with the current new interval (i.e., the start of the current interval is less than or equal to the end of the new interval). +* If they overlap, update the end of the new interval to be the maximum of the current interval's end and the new interval's end. +* If they don't overlap, add the current new interval to the result list and start a new interval with the current interval. +4. Final Step: +* After the loop, add the last interval to the result list as it won't be added inside the loop. + +#### Implementation + +Efficient In-Place Solution with Arrays in Java + +```Java +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +class Solution { + public int[][] merge(int[][] intervals) { + if (intervals.length <= 1) + return intervals; + + // Sort by ascending starting point + Arrays.sort(intervals, (i1, i2) -> Integer.compare(i1[0], i2[0])); + + List result = new ArrayList<>(); + int[] newInterval = intervals[0]; + result.add(newInterval); + + for (int[] interval : intervals) { + if (interval[0] <= newInterval[1]) { // Overlapping intervals, move the end if needed + newInterval[1] = Math.max(newInterval[1], interval[1]); + } else { // Disjoint intervals, add the new interval to the list + newInterval = interval; + result.add(newInterval); + } + } + + return result.toArray(new int[result.size()][]); + } +} +``` + +Previous Version Using Lists + +```Java +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +public class Interval { + int start; + int end; + + Interval() { start = 0; end = 0; } + Interval(int s, int e) { start = s; end = e; } +} + +public class Solution { + public List merge(List intervals) { + if (intervals.size() <= 1) + return intervals; + + // Sort by ascending starting point using an anonymous Comparator + Collections.sort(intervals, (i1, i2) -> Integer.compare(i1.start, i2.start)); + + List result = new LinkedList<>(); + int start = intervals.get(0).start; + int end = intervals.get(0).end; + + for (Interval interval : intervals) { + if (interval.start <= end) // Overlapping intervals, move the end if needed + end = Math.max(end, interval.end); + else { // Disjoint intervals, add the previous one and reset bounds + result.add(new Interval(start, end)); + start = interval.start; + end = interval.end; + } + } + + // Add the last interval + result.add(new Interval(start, end)); + return result; + } +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(NlogN)$ +- **Space complexity**: $O(N)$ + +### Conclusion + +The presented solution efficiently merges overlapping intervals using sorting and iteration. The overall time complexity is O(n log n) due to the sorting step, and the space complexity is optimized by reusing the input array for storing the result. This method ensures a fast and memory-efficient approach to solving the interval merging problem. diff --git a/solutions/lc-solutions/0000-0099/0057-insert-interval.md b/solutions/lc-solutions/0000-0099/0057-insert-interval.md new file mode 100644 index 0000000..c7218d8 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0057-insert-interval.md @@ -0,0 +1,122 @@ +--- +id: insert-interval +title: Insert Interval(LeetCode) +sidebar_label: 0057-Insert Interval +tags: + - Array +description: You are given an array of non-overlapping intervals intervals. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals. Return intervals after the insertion. +--- + +## Problem Statement + +You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval. + +Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping `intervals` (merge overlapping intervals if necessary). + +Return `intervals` after the insertion. + +Note that you don't need to modify `intervals` in-place. You can make a new array and return it. + +### Examples + +**Example 1:** + +```plaintext +Input: intervals = [[1,3],[6,9]], newInterval = [2,5] +Output: [[1,5],[6,9]] +``` + +**Example 2:** + +```plaintext +Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] +Output: [[1,2],[3,10],[12,16]] +Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. +``` + +### Constraints + +- `0 <= intervals.length <= 104` +- `intervals[i].length == 2` +- `0 <= starti <= endi <= 105` +- `intervals` is sorted by `starti` in ascending order. +- `newInterval.length == 2` +- `0 <= start <= end <= 105` + +## Solution + +### Approach + +#### Algorithm + +1. Initialize the Result List: +* Create an empty list result to store the final merged intervals. +2. Add Non-overlapping Intervals Before the New Interval: +* Iterate through the list of intervals and add all intervals that end before the new interval starts to the result list. +3. Merge Overlapping Intervals: +* Continue iterating through the list and merge all intervals that overlap with the new interval. This is done by updating the new interval's start and end to be the minimum start and maximum end of the overlapping intervals. +* Once all overlapping intervals are merged, add the new interval to the result list. +4. Add Remaining Intervals: +* Finally, add all the remaining intervals that start after the new interval ends to the result list. + +#### Implementation + +```Java +import java.util.List; +import java.util.LinkedList; + +public class Interval { + int start; + int end; + + Interval() { + start = 0; + end = 0; + } + + Interval(int s, int e) { + start = s; + end = e; + } +} + +public class Solution { + public List insert(List intervals, Interval newInterval) { + List result = new LinkedList<>(); + int i = 0; + + // Add all the intervals ending before newInterval starts + while (i < intervals.size() && intervals.get(i).end < newInterval.start) { + result.add(intervals.get(i++)); + } + + // Merge all overlapping intervals to one considering newInterval + while (i < intervals.size() && intervals.get(i).start <= newInterval.end) { + newInterval = new Interval( + Math.min(newInterval.start, intervals.get(i).start), + Math.max(newInterval.end, intervals.get(i).end) + ); + i++; + } + + // Add the union of intervals we got + result.add(newInterval); + + // Add all the rest + while (i < intervals.size()) { + result.add(intervals.get(i++)); + } + + return result; + } +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(N)$ +- **Space complexity**: $O(N)$ + +### Conclusion + +The algorithm efficiently inserts a new interval into a sorted list of non-overlapping intervals by handling non-overlapping intervals before and after the new interval separately and merging overlapping intervals in the middle. The overall time complexity is O(n) and the space complexity is O(n), making it both time-efficient and space-efficient. diff --git a/solutions/lc-solutions/0000-0099/0058-length-of-last-word.md b/solutions/lc-solutions/0000-0099/0058-length-of-last-word.md new file mode 100644 index 0000000..6bc463b --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0058-length-of-last-word.md @@ -0,0 +1,112 @@ +--- +id: length-of-last-word +title: Length of Last Word (LeetCode) +difficulty: Easy +sidebar_label: 0058-LengthOfLastWord +topics: + - String +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/length-of-last-word/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/length-of-last-word/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + + +## Problem Description + +Given a string `s` consisting of words and spaces, return the length of the last word in the string. + +### Examples + +#### Example 1 + +- **Input:** s = "Hello World" +- **Output:** 5 +- **Explanation:** The last word is "World" with length 5. + +#### Example 2 + +- **Input:** s = " fly me to the moon " +- **Output:** 4 +- **Explanation:** The last word is "moon" with length 4. + +#### Example 3 + +- **Input:** s = "luffy is still joyboy" +- **Output:** 6 +- **Explanation:** The last word is "joyboy" with length 6. + +### Constraints + +- `1 <= s.length <= 10^4` +- `s` consists of only English letters and spaces ' '. +- There will be at least one word in `s`. + +### Approach + +To find the length of the last word in the string `s`, we can follow these steps: + +1. Trim any trailing spaces from the string. +2. Initialize a variable `length` to store the length of the last word. +3. Iterate over the string from right to left: + - When encountering a non-space character, increment `length`. + - Break the loop when encountering the first space character after a non-space character. +4. Return `length`. + +### Solution Code + +#### Python + +``` +class Solution(object): + def lengthOfLastWord(self, s): + return len(s.split()[-1]) +``` + +#### C++ + +``` +class Solution { +public: + int lengthOfLastWord(string s) { + int length = 0; + int n = s.length(); + while (n > 0 && s[n - 1] == ' ') { + n--; // Trim trailing spaces + } + for (int i = n - 1; i >= 0; --i) { + if (s[i] != ' ') { + length++; + } else if (length != 0) { + break; + } + } + return length; + } +}; +``` + +#### Java + +``` +class Solution { + public int lengthOfLastWord(String s) { + int length = 0; + s = s.trim(); // Trim trailing spaces + for (int i = s.length() - 1; i >= 0; --i) { + if (s.charAt(i) != ' ') { + length++; + } else if (length != 0) { + break; + } + } + return length; + } +} +``` + +### Conclusion + +The Length of Last Word problem can be efficiently solved by trimming any trailing spaces from the string and iterating over the string from right to left to find the length of the last word. The provided solution code implements this approach in Python, C++, and Java, providing an optimal solution to the problem. \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0059-spiral-matrix-II.md b/solutions/lc-solutions/0000-0099/0059-spiral-matrix-II.md new file mode 100644 index 0000000..89d676c --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0059-spiral-matrix-II.md @@ -0,0 +1,130 @@ +--- +id: spiral-matrix-II +title: Spiral Matrix II(LeetCode) +sidebar_label: 0059-Spiral Matrix II +tags: + - Array + - Matric + - Simulation +description: Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. +--- + +## Problem Statement + +Given a positive integer `n`, generate an `n x n` matrix filled with elements from `1` to `n2` in spiral order. + +### Examples + +**Example 1:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/946cfd25-b503-4cce-8d8d-b8dca3f91631) + +```plaintext +Input: n = 3 +Output: [[1,2,3],[8,9,4],[7,6,5]] +``` + +**Example 2:** + +```plaintext +Input: n = 1 +Output: [[1]] +``` + +### Constraints + +- `1 <= n <= 20` + +## Solution + +Generating a spiral matrix is an interesting problem that involves filling a matrix in a spiral order. Here, we will discuss three solutions: building the matrix inside-out using two different approaches and walking the spiral path. + +### Approach 1: Build it Inside-Out + +#### Algorithm + +1. Initialize an empty list `A` and set `lo` to `n*n + 1`. +2. While `lo > 1`: +* Calculate `lo` and `hi`. +* Add a new row of numbers ranging from `lo` to `hi` to `A`. +* Rotate `A` clockwise by using `zip` and list slicing. +3. Return the constructed matrix `A`. + +#### Implementation + +```Python +def generateMatrix(self, n): + A, lo = [], n*n+1 + while lo > 1: + lo, hi = lo - len(A), lo + A = [range(lo, hi)] + list(zip(*A[::-1])) + return A +``` + +### Complexity Analysis + +- **Time complexity**: $O(N^2)$ +- **Space complexity**: $O(N^2)$ + +### Approach 2: Ugly Inside-Out + +#### Algorithm + +1. Initialize `A` with a single element `n*n`. +2. While the first element of `A` is greater than 1: +* Add a new row of numbers from `A[0][0] - len(A)` to `A[0][0]`. +* Rotate `A` clockwise by using `zip` and list slicing. +3. Return `A` multiplied by `(n > 0)` to handle the `n=0` case. + +#### Implementation + +```Python +def generateMatrix(self, n): + A = [[n*n]] + while A[0][0] > 1: + A = [range(A[0][0] - len(A), A[0][0])] + list(zip(*A[::-1])) + return A * (n > 0) + +``` + +### Complexity Analysis + +- **Time complexity**: $O(N^2)$ +- **Space complexity**: $O(N^2)$ + +### Approach 3: Walk the Spiral + +#### Algorithm + +1. Initialize the matrix `A` with zeros. +2. Set the initial position and direction. +3. For each number from 1 to `n*n`: +* Fill the current cell with the current number. +* Check if the next cell in the current direction is out of bounds or already filled. +* If so, change the direction. +* Move to the next cell. +4. Return the filled matrix `A`. + +#### Implementation + +```Python +def generateMatrix(self, n): + A = [[0] * n for _ in range(n)] + i, j, di, dj = 0, 0, 0, 1 + for k in range(n*n): + A[i][j] = k + 1 + if A[(i + di) % n][(j + dj) % n]: + di, dj = dj, -di + i += di + j += dj + return A +``` + +### Complexity Analysis + +- **Time complexity**: $O(N^2)$ +- **Space complexity**: $O(N^2)$ + +### Conclusion + +All three solutions effectively generate a spiral matrix, with varying approaches and code readability. The inside-out solutions (Solutions 1 and 2) leverage matrix rotation and range operations, while the spiral walk solution (Solution 3) explicitly manages the matrix and directions to fill the numbers. Each approach has its own merits and can be chosen based on preference for readability and code complexity. diff --git a/solutions/lc-solutions/0000-0099/0060-permutation-sequence.md b/solutions/lc-solutions/0000-0099/0060-permutation-sequence.md new file mode 100644 index 0000000..44f59d2 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0060-permutation-sequence.md @@ -0,0 +1,119 @@ +--- +id: permutation-sequence +title: Permutation Sequence(LeetCode) +sidebar_label: 0060-Permutation Sequence +tags: + - Math + - Recursion +description: The set [1, 2, 3, ..., n] contains a total of n! unique permutations. Given n and k, return the kth permutation sequence. +--- + +## Problem Statement + +The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations. + +By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`: + +1. `"123"` +2. `"132"` +3. `"213"` +4. `"231"` +5. `"312"` +6. `"321"` +Given `n` and `k`, return the `kth` permutation sequence. + +### Examples + +**Example 1:** + +```plaintext +Input: n = 3, k = 3 +Output: "213" +``` + +**Example 2:** + +```plaintext +Input: n = 4, k = 9 +Output: "2314" +``` + +**Example 3:** + +```plaintext +Input: n = 3, k = 1 +Output: "123" +``` + +### Constraints + +- `1 <= n <= 9` +- `1 <= k <= n!` + +## Solution + +### Approach + +#### Algorithm + +1. Initialize Factorial Values: +* Precompute and store the factorial values of integers from 0 to 9 in a vector `factVal` to get factorials in O(1) time. +2. Initialize Array: +* Create a vector `v` containing elements from 1 to `n`. +3. Recursive Function `setPerm`: +* Base Case: If `n == 1`, append the last remaining element in `v` to `ans` and return. +* Calculate the required index using `k / factVal[n-1]`. +* Handle the corner case where if `k` is a multiple of `(n-1)!`, decrement the index by 1. +* Append the element at the calculated index from `v` to `ans`. +* Remove the selected element from `v`. +* Adjust the value of `k` to be the remainder after dividing by `factVal[n-1]`. +* Make a recursive call with updated values of `n`, `k`, `v`, and `ans`. +4. Construct Result: +* Initialize an empty string `ans`. +* Call the recursive function setPerm with initial values of `v`, `ans`, `n`, `k`, and `factVal`. +* Return the result `ans`. + +#### Implementation + +```C++ +class Solution { +public: + void setPerm(vector& v, string& ans, int n, int k, vector& factVal) { + if (n == 1) { + ans += to_string(v.back()); + return; + } + + int index = (k / factVal[n-1]); + if (k % factVal[n-1] == 0) { + index--; + } + + ans += to_string(v[index]); + v.erase(v.begin() + index); + k -= factVal[n-1] * index; + setPerm(v, ans, n-1, k, factVal); + } + + string getPermutation(int n, int k) { + if (n == 1) return "1"; + + vector factVal = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880}; + string ans = ""; + vector v; + for (int i = 1; i <= n; i++) v.emplace_back(i); + + setPerm(v, ans, n, k, factVal); + return ans; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: $O(N^2)$ +- **Space complexity**: $O(N)$ + +### Conclusion + +This algorithm efficiently finds the k-th permutation of a set of n elements by using a combination of precomputed factorials and recursive selection. The approach ensures that the computation is done in a systematic manner without generating all permutations. diff --git a/solutions/lc-solutions/0000-0099/0061-rotate-list.md b/solutions/lc-solutions/0000-0099/0061-rotate-list.md new file mode 100644 index 0000000..0e7f77e --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0061-rotate-list.md @@ -0,0 +1,231 @@ +--- +id: rotate-list +title: Rotate List (LeetCode) +sidebar_label: 0061-rotate-list +tags: + - Linked List + - Two Pointers +description: "The rotate list is the problem to rotate the list to the right by k places." +--- + +### Problem Description + +Given the `head` of a linked list, rotate the list to the right by `k` places. + +### Examples + +#### Example 1 + +```plaintext +Input: head = [1,2,3,4,5], k = 2 +Output: [4,5,1,2,3] +``` + +#### Example 2 + +```plaintext +Input: head = [0,1,2], k = 4 +Output: [2,0,1] +``` + +### Constraints + +- The number of nodes in the list is in the range `[0, 500]`. +- `-100 <= Node.val <= 100` +- `0 <= k <= 2 * 109` + +### Approach + +Brute Force Approach : We have to move the last element to first for each k. +For each k, find the last element from the list. Move it to the first. + +Let’s take an example. + +head = [1,2,3,4,5] k = 2000000000 + +If we see a brute force approach, it will take O(5*2000000000) which is not a good time complexity when we can optimize it. + +We can see that for every k which is multiple of the length of the list, we get back the original list. Try to operate brute force on any linked list for k as a multiple of the length of the list. + +This gives us a hint that for k greater than the length of the list, we have to rotate the list for k%length of the list. This reduces our time complexity. + +Steps to the algorithm:- + +1. Calculate the length of the list. +2. Connect the last node to the first node, converting it to a circular linked list. +3. Iterate to cut the link of the last node and start a node of k%length of the list rotated list. + +### Solution Code + +#### Python + +``` +class Node: + def __init__(self, val): + self.val = val + self.next = None + +# utility function to insert node at the end of the linked list +def insertNode(head, val): + newNode = Node(val) + if head == None: + head = newNode + return head + temp = head + while temp.next != None: + temp = temp.next + temp.next = newNode + return head + +# utility function to rotate list by k times +def rotateRight(head, k): + if head == None or head.next == None or k == 0: + return head + # calculating length + temp = head + length = 1 + while temp.next != None: + length += 1 + temp = temp.next + # link last node to first node + temp.next = head + k = k % length # when k is more than length of list + end = length - k # to get end of the list + while end: + temp = temp.next + end -= 1 + # breaking last node link and pointing to NULL + head = temp.next + temp.next = None + + return head + +# utility function to print list +def printList(head): + while head.next != None: + print(head.val, end='->') + head = head.next + print(head.val) + return + +if __name__ == '__main__': + head = None + # inserting Node + head = insertNode(head, 1) + head = insertNode(head, 2) + head = insertNode(head, 3) + head = insertNode(head, 4) + head = insertNode(head, 5) + + print("Original list: ", end='') + printList(head) + + k = 2 + # calling function for rotating right of the nodes by k times + newHead = rotateRight(head, k) + + print("After", k, "iterations: ", end='') + printList(newHead) # list after rotating nodes +``` + +#### Java +``` +//utility function to insert node at the end of the list +static Node insertNode(Node head,int val) { + Node newNode = new Node(val); + if(head == null) { + head = newNode; + return head; + } + Node temp = head; + while(temp.next != null) temp = temp.next; + + temp.next = newNode; + return head; +} +//utility function to rotate list by k times +static Node rotateRight(Node head,int k) { + if(head == null||head.next == null||k == 0) return head; + //calculating length + Node temp = head; + int length = 1; + while(temp.next != null) { + ++length; + temp = temp.next; + } + //link last node to first node + temp.next = head; + k = k%length; //when k is more than length of list + int end = length-k; //to get end of the list + while(end--!=0) temp = temp.next; + //breaking last node link and pointing to NULL + head = temp.next; + temp.next = null; + + return head; +} + +//utility function to print list +static void printList(Node head) { + while(head.next != null) { + System.out.print(head.num+"->"); + head = head.next; + } + System.out.println(head.num); + +} +``` + +#### C++ +``` +//utility function to insert node at the end of the list +void insertNode(node* &head,int val) { + node* newNode = new node(val); + if(head == NULL) { + head = newNode; + return; + } + node* temp = head; + while(temp->next != NULL) temp = temp->next; + + temp->next = newNode; + return; +} +//utility function to rotate list by k times +node* rotateRight(node* head,int k) { + if(head == NULL||head->next == NULL||k == 0) return head; + //calculating length + node* temp = head; + int length = 1; + while(temp->next != NULL) { + ++length; + temp = temp->next; + } + //link last node to first node + temp->next = head; + k = k%length; //when k is more than length of list + int end = length-k; //to get end of the list + while(end--) temp = temp->next; + //breaking last node link and pointing to NULL + head = temp->next; + temp->next = NULL; + + return head; +} + +//utility function to print list +void printList(node* head) { + while(head->next != NULL) { + cout<num<<"->"; + head = head->next; + } + cout<num< Down -> Down +2. Down -> Down -> Right +3. Down -> Right -> Down + +``` + + +### Constraints +- `1 <= m, n <= 100` + + +## Solution for Unique Paths +### Approach +#### Brute Force +- The brute force approach uses recursion to explore all possible paths from the top-left to the bottom-right corner of the grid. At each cell, the robot has two choices: move right or move down. + +**Recursive function:** +```cpp +int uniquePathsBruteForce(int m, int n) { + if (m == 1 || n == 1) { + return 1; + } + return uniquePathsBruteForce(m - 1, n) + uniquePathsBruteForce(m, n - 1); +} + +``` + +**Complexity:** +- Time Complexity: `O(2^(m+n))` - Each recursive call generates two more recursive calls, leading to an exponential number of calls. +- Space Complexity: `O(m+n)` - The recursion stack can go as deep as the sum of `m` and `n`. + +**Corner Cases:** +- If `m` or `n` is 1, there's only one path straight to the destination. +- The function assumes valid input where `m` and `n` are positive integers. + +#### Optimized Approach +- The optimized approach uses dynamic programming to avoid redundant calculations. We create a 2D array `dp` where `dp[i][j]` represents the number of unique paths to reach cell `(i, j)`. + +**Dynamic Programming Solution:** + +```cpp +int uniquePaths(int m, int n) { + vector> dp(m, vector(n, 1)); + + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + dp[i][j] = dp[i-1][j] + dp[i][j-1]; + } + } + + return dp[m-1][n-1]; +} +``` + +**Complexity:** +- Time Complexity: `O(m*n)` because We fill in each cell of the `m x n` matrix exactly once. +- Space Complexity: `O(m*n)` We use a 2D array to store the number of paths for each cell. + + +**Further Optimization** +We can further optimize the space complexity to `O(n)` by using a single array to keep track of the current row's path counts. +```cpp +int uniquePaths(int m, int n) { + vector dp(n, 1); + + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + dp[j] += dp[j-1]; + } + } + + return dp[n-1]; +} +``` +**Complexity of Optimized Approach:** +- Time Complexity: `O(m*n)` - Still filling in each cell exactly once. +- Space Complexity: `O(n)` - Using a single array of size `n`. + +**Corner Cases:** +- If either `m` or `n` is 1, the function should return 1 since there's only one path straight to the destination. +- TThe function handles cases where `m` or `n` is very large efficiently within the constraints + + + + + + +#### Implementation + + ```jsx live + function Solution(a,b) { + var uniquePaths = function(m, n) { + if (m === 0 || n === 0) return 0; + + let dp = new Array(n).fill(1); + + for (let i = 1; i < m; i++) { + for (let j = 1; j < n; j++) { + dp[j] += dp[j - 1]; + } + } + + return dp[n - 1]; + }; + + const m = 3; + const n = 7; + const output = uniquePaths(m, n); + return ( +
+

+ Input: + {m,' ',n} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + +#### Complexity Analysis + + - Time Complexity: $O(m*n)$ + - Space Complexity: $O(n)$ + + ## Code in Different Languages + + + + + + + ```javascript + var uniquePaths = function(m, n) { + if (m === 0 || n === 0) return 0; + + let dp = new Array(n).fill(1); + + for (let i = 1; i < m; i++) { + for (let j = 1; j < n; j++) { + dp[j] += dp[j - 1]; + } + } + return dp[n - 1]; + }; + ``` + + + + + + + ```typescript + function uniquePaths(m: number, n: number): number { + if (m === 0 || n === 0) return 0; + + let dp: number[] = new Array(n).fill(1); + + for (let i = 1; i < m; i++) { + for (let j = 1; j < n; j++) { + dp[j] += dp[j - 1]; + } + } + + return dp[n - 1]; + }; + ``` + + + + + + + ```python + class Solution(object): + def uniquePaths(self, m, n): + if m == 0 or n == 0: + return 0 + + dp = [1] * n + + for i in range(1, m): + for j in range(1, n): + dp[j] += dp[j - 1] + + return dp[-1] + ``` + + + + + + + ```java + class Solution { + public int uniquePaths(int m, int n) { + if (m == 0 || n == 0) return 0; + + int[] dp = new int[n]; + Arrays.fill(dp, 1); + + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + dp[j] += dp[j - 1]; + } + } + + return dp[n - 1]; + } + } + ``` + + + + + + + ```cpp + class Solution { + public: + int uniquePaths(int m, int n) { + if (m == 0 || n == 0) return 0; + + vector dp(n, 1); + + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + dp[j] += dp[j - 1]; + } + } + + return dp[n - 1]; + } + }; + ``` + + + + +
+
+ +## References + +- **LeetCode Problem**: [Unique Paths](https://leetcode.com/problems/unique-paths/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/unique-paths/solutions/) \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0063-unique-paths-II.md b/solutions/lc-solutions/0000-0099/0063-unique-paths-II.md new file mode 100644 index 0000000..e5fe982 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0063-unique-paths-II.md @@ -0,0 +1,94 @@ +--- +id: unique-paths-II +title: Unique Paths II(LeetCode) +sidebar_label: 0063-Unique Paths II +tags: + - Array + - Dynamic Programming + - Matrix +description: There is a robot initially located at the top-left corner. The robot tries to move to the bottom-right corner. Return the number of possible unique paths that the robot can take to reach the bottom-right corner. +--- + +## Problem Statement + +You are given an `m x n` integer array `grid`. There is a robot initially located at the top-left corner (i.e., `grid[0][0]`). The robot tries to move to the bottom-right corner (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. + +An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include any square that is an obstacle. + +Return the number of possible unique paths that the robot can take to reach the bottom-right corner. + +The testcases are generated so that the answer will be less than or equal to `2 * 109`. + +### Examples + +**Example 1:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/a0dd405c-20e8-4f5f-88a4-f39ab1f1bb4e) + +```plaintext +Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] +Output: 2 +Explanation: There is one obstacle in the middle of the 3x3 grid above. +There are two ways to reach the bottom-right corner: +1. Right -> Right -> Down -> Down +2. Down -> Down -> Right -> Right +``` + +**Example 2:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/da914756-753c-4bfb-897a-f734807fea8f) + +```plaintext +Input: obstacleGrid = [[0,1],[0,0]] +Output: 1 +``` + +### Constraints + +- `m == obstacleGrid.length` +- `n == obstacleGrid[i].length` +- `1 <= m, n <= 100` +- `obstacleGrid[i][j]` is `0` or `1`. + +## Solution + +When faced with the problem of finding the number of unique paths in a grid with obstacles, we need an efficient solution that accounts for the presence of obstacles and dynamically updates the number of paths available. Below is the Java solution to solve this problem using dynamic programming. + +### Approach + +#### Algorithm + +1. Dynamic Programming: We use a 1D array `dp` to keep track of the number of ways to reach each cell in the grid. +2. Initialization: Initialize `dp[0]` to 1, as there is only one way to be at the start if there is no obstacle. +3. Update DP Array: Traverse through each cell in the grid. +* If a cell contains an obstacle (`1`), set `dp[j]` to `0` as it is not reachable. +* Otherwise, update `dp[j]` to include the number of ways to reach the current cell from the left cell (`dp[j - 1]`). +4. Result: The value at `dp[width - 1]` will contain the number of unique paths to the bottom-right corner of the grid. + +#### Implementation + +```Java +public int uniquePathsWithObstacles(int[][] obstacleGrid) { + int width = obstacleGrid[0].length; + int[] dp = new int[width]; + dp[0] = 1; + for (int[] row : obstacleGrid) { + for (int j = 0; j < width; j++) { + if (row[j] == 1) + dp[j] = 0; + else if (j > 0) + dp[j] += dp[j - 1]; + } + } + return dp[width - 1]; +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(M*N)$ - where m is the number of rows and n is the number of columns. We traverse each cell in the grid once. +- **Space complexity**: $O(N)$ - where n is the number of columns. We use a 1D array dp of size equal to the width of the grid. + +### Conclusion + +This dynamic programming approach efficiently calculates the number of unique paths in a grid with obstacles by using a 1D array to store the number of ways to reach each cell. This approach ensures that we only use O(n) additional space, making it an optimized solution for this problem. diff --git a/solutions/lc-solutions/0000-0099/0064-minimum-path-sum.md b/solutions/lc-solutions/0000-0099/0064-minimum-path-sum.md new file mode 100644 index 0000000..2377904 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0064-minimum-path-sum.md @@ -0,0 +1,95 @@ +--- +id: minimum-path-sum +title: Minimum Path Sum(LeetCode) +sidebar_label: 0064-Minimum Path Sum +tags: + - Array + - Dynamic Programming + - Matrix +description: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. +--- + +## Problem Statement + +Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. + +Note: You can only move either down or right at any point in time. + +### Examples + +**Example 1:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/bd64e41b-d13f-4309-992a-2e6e6cae1bad) + +```plaintext +Input: grid = [[1,3,1],[1,5,1],[4,2,1]] +Output: 7 +Explanation: Because the path 1 β†’ 3 β†’ 1 β†’ 1 β†’ 1 minimizes the sum. +``` + +**Example 2:** + +```plaintext +Input: grid = [[1,2,3],[4,5,6]] +Output: 12 +``` + +### Constraints + +- `m == grid.length` +- `n == grid[i].length` +- `1 <= m, n <= 200` +- `0 <= grid[i][j] <= 200` + +## Solution + +The problem is to find the minimum path sum from the top-left corner to the bottom-right corner of a grid. You can only move either down or right at any point in time. Each cell in the grid contains a non-negative integer which represents the cost to traverse that cell. + +### Approach + +#### Algorithm + +1. Initialization: +* Create a 1D array `cur` of size `m` (the number of rows in the grid) to store the minimum path sum for the current column. +* Initialize `cur[0]` to `grid[0][0]` since the starting point is the cost of the top-left cell. +* Fill the first column of `cur` by accumulating the costs of the cells in the first column of the grid. +2. Dynamic Programming: +* Iterate through each column starting from the second column. +* For each column, update the first cell by adding the cost of the current cell to the value of the first cell in `cur` from the previous column. +* For the remaining cells in the column, update each cell by taking the minimum of the value from the left cell and the value from the top cell (stored in `cur`) and adding the cost of the current cell. +3. Result: +* After iterating through the grid, `cur[m-1]` will contain the minimum path sum to reach the bottom-right corner of the grid. + +#### Implementation + +```C++ +class Solution { +public: + int minPathSum(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + vector cur(m, grid[0][0]); + + // Initialize the first column + for (int i = 1; i < m; i++) + cur[i] = cur[i - 1] + grid[i][0]; + + // Fill the rest of the grid + for (int j = 1; j < n; j++) { + cur[0] += grid[0][j]; // Update the top cell of the current column + for (int i = 1; i < m; i++) + cur[i] = min(cur[i - 1], cur[i]) + grid[i][j]; + } + return cur[m - 1]; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: $O(M*N)$ - where `m` is the number of rows and `n` is the number of columns. Each cell in the grid is processed once. +- **Space complexity**: $O(M)$ - where `m` is the number of rows. We use a single 1D array of size `m` to store the minimum path sums for the current column. + +### Conclusion + +This dynamic programming solution efficiently computes the minimum path sum in a grid by maintaining only a 1D array to store the current state of the path sums, which significantly optimizes space usage. diff --git a/solutions/lc-solutions/0000-0099/0065-valid-number.md b/solutions/lc-solutions/0000-0099/0065-valid-number.md new file mode 100644 index 0000000..d31b922 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0065-valid-number.md @@ -0,0 +1,124 @@ +--- +id: valid-number +title: Valid Number(LeetCode) +sidebar_label: 0065-Valid Number +tags: + - String +description: Given a string s, return whether s is a valid number. +--- + +## Problem Statement + +Given a string `s`, return whether `s` is a valid number. + +For example, all the following are valid numbers: `"2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"`, while the following are not valid numbers: `"abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"`. + +Formally, a valid number is defined using one of the following definitions: + +1. An integer number followed by an optional exponent. +2. A decimal number followed by an optional exponent. +An integer number is defined with an optional sign `'-'` or `'+'` followed by digits. + +A decimal number is defined with an optional sign `'-'` or `'+'` followed by one of the following definitions: + +1. Digits followed by a dot `'.'`. +2. Digits followed by a dot `'.'` followed by digits. +3. A dot `'.'` followed by digits. +An exponent is defined with an exponent notation `'e'` or `'E'` followed by an integer number. + +The digits are defined as one or more digits. + +### Examples + +**Example 1:** + +```plaintext +Input: s = "0" +Output: true +``` + +**Example 2:** + +```plaintext +Input: s = "e" +Output: false +``` + +**Example 3:** + +```plaintext +Input: s = "." +Output: false +``` + +### Constraints + +- `1 <= s.length <= 20` +- `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`. + +## Solution + +### Approach + +#### Algorithm + +1. Trim the Input String: Remove leading and trailing whitespace using `s.trim()`. +2. Initialize Flags: +* `pointSeen`: Tracks if a decimal point has been encountered. +* `eSeen`: Tracks if an exponent 'e' has been encountered. +* `numberSeen`: Tracks if at least one digit has been encountered. +* `numberAfterE`: Tracks if at least one digit exists after an 'e'. +3. Iterate Over Each Character: +* If the character is a digit (`0-9`), set `numberSeen` and `numberAfterE` to `true`. +* If the character is a decimal point (`.`), ensure no 'e' or previous decimal point has been seen. +* If the character is an exponent (`e`), ensure no previous 'e' has been seen and that at least one digit has been encountered before it. Set numberAfterE to false. +* If the character is a sign (`+` or `-`), ensure it appears at the beginning or immediately after an 'e'. +* If any other character is encountered, return `false`. +4. Final Check: Ensure that at least one digit has been encountered (`numberSeen` is `true`) and if an 'e' was encountered, ensure there is at least one digit after it (`numberAfterE` is `true`). + +#### Implementation + +```Java +public boolean isNumber(String s) { + s = s.trim(); + + boolean pointSeen = false; + boolean eSeen = false; + boolean numberSeen = false; + boolean numberAfterE = true; + for(int i=0; i plusOne(vector& digits) { + int n = digits.size(); + int carry = 1; + for (int i = n - 1; i >= 0; --i) { + digits[i] += carry; + carry = digits[i] / 10; + digits[i] %= 10; + } + if (carry) { + digits.insert(digits.begin(), carry); + } + return digits; + } +}; +``` + +#### Java + +``` +class Solution { + public int[] plusOne(int[] digits) { + int n = digits.length; + int carry = 1; + for (int i = n - 1; i >= 0; --i) { + digits[i] += carry; + carry = digits[i] / 10; + digits[i] %= 10; + } + if (carry != 0) { + int[] result = new int[n + 1]; + result[0] = carry; + for (int i = 1; i < n + 1; ++i) { + result[i] = digits[i - 1]; + } + return result; + } + return digits; + } +} +``` + +### Conclusion + +The "Plus One" problem can be efficiently solved by incrementing the large integer represented by the digits array by one. The provided solution code implements this approach in Python, C++, and Java, providing an optimal solution to the problem. \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0067-Add-Binary.md b/solutions/lc-solutions/0000-0099/0067-Add-Binary.md new file mode 100644 index 0000000..5a474d0 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0067-Add-Binary.md @@ -0,0 +1,121 @@ +--- +id: add-binary +title: Add Binary (LeetCode) +difficulty: Easy +sidebar_label: 0067-AddBinary +topics: + - Math + - String +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/add-binary/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/add-binary/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +## Problem Description + +Given two binary strings `a` and `b`, return their sum as a binary string. + +### Examples + +#### Example 1: + +- **Input:** `a = "11"`, `b = "1"` +- **Output:** `"100"` +- **Explanation:** The sum of binary strings `11` and `1` is `100`. + +#### Example 2: + +- **Input:** `a = "1010"`, `b = "1011"` +- **Output:** `"10101"` +- **Explanation:** The sum of binary strings `1010` and `1011` is `10101`. + +### Constraints: + +- `1 <= a.length, b.length <= 10^4` +- `a` and `b` consist only of `'0'` or `'1'` characters. +- Each string does not contain leading zeros except for the zero itself. + +### Approach + +To add two binary strings `a` and `b`, we can follow these steps: + +1. Initialize variables `result` and `carry` to store the result and carry, respectively. +2. Start from the last digit of both strings and move towards the beginning. +3. Add the corresponding digits from `a` and `b` along with the carry and update the result accordingly. +4. If the sum exceeds 1, set the carry to 1; otherwise, set it to 0. +5. After processing all digits, if there's still a carry left, append it to the result. +6. Reverse the result string to get the final sum. + +### Solution Code + +#### Python + +``` +class Solution(object): + def addBinary(self, a, b): + return bin(int(a, 2) + int(b, 2))[2:] +``` + +#### C++ + +``` +class Solution { +public: + string addBinary(string a, string b) { + string result; + int carry = 0; + int i = a.length() - 1, j = b.length() - 1; + + while (i >= 0 || j >= 0) { + int digit_a = (i >= 0) ? a[i] - '0' : 0; + int digit_b = (j >= 0) ? b[j] - '0' : 0; + int current_sum = digit_a + digit_b + carry; + result = to_string(current_sum % 2) + result; + carry = current_sum / 2; + i--; + j--; + } + + if (carry) { + result = "1" + result; + } + + return result; + } +}; +``` + +#### Java + +``` +class Solution { + public String addBinary(String a, String b) { + StringBuilder result = new StringBuilder(); + int carry = 0; + int i = a.length() - 1, j = b.length() - 1; + + while (i >= 0 || j >= 0) { + int digit_a = (i >= 0) ? a.charAt(i) - '0' : 0; + int digit_b = (j >= 0) ? b.charAt(j) - '0' : 0; + int current_sum = digit_a + digit_b + carry; + result.insert(0, current_sum % 2); + carry = current_sum / 2; + i--; + j--; + } + + if (carry == 1) { + result.insert(0, '1'); + } + + return result.toString(); + } +} +``` + +### Conclusion + +The "Add Binary" problem can be efficiently solved by adding two binary strings digit by digit and considering the carry. The provided solution code implements this approach in Python, C++, and Java, providing an optimal solution to the problem. \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0068-text-justification.md b/solutions/lc-solutions/0000-0099/0068-text-justification.md new file mode 100644 index 0000000..ddf38c8 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0068-text-justification.md @@ -0,0 +1,218 @@ +--- +id: text-justification +title: Text Justification (LeetCode) +sidebar_label: 0068-TextJustification +topics: + - String + - Greedy +description: Solution to Leetcode 68 Text Justification +--- + +## Problem Description + +Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified. + +You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters. + +Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. + +For the last line of text, it should be left-justified, and no extra space is inserted between words. + +:::note +- A word is defined as a character sequence consisting of non-space characters only. +- Each word's length is guaranteed to be greater than 0 and not exceed `maxWidth`. +- The input array `words` contains at least one word. +::: + +### Examples + +**Example 1:** + +``` +Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16 +Output: +[ + "This is an", + "example of text", + "justification. " +] +``` + +**Example 2:** + +``` +Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16 +Output: +[ + "What must be", + "acknowledgment ", + "shall be " +] +Explanation: Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified. +Note that the second line is also left-justified because it contains only one word. +``` + +**Example 3:** + +``` +Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20 +Output: +[ + "Science is what we", + "understand well", + "enough to explain to", + "a computer. Art is", + "everything else we", + "do " +] +``` + +### Constraints + +- 1 < = words.length < = 300 +- 1 < = words[i].length < = 20 +- words[i] consists of only English letters and symbols. +- 1 <= maxWidth < = 100 +- words[i].length < = maxWidth + +### Approach + +1. Traverse through the words and group them into lines such that the total length of words in each line does not exceed `maxWidth`. +2. Distribute the extra spaces evenly among the words in each line. +3. For the last line, left-justify the text without adding extra spaces between the words. + + +## Solution + +#### Code in Different Languages + +#### Python + +```python +class Solution: + def fullJustify(self, words: list[str], maxWidth: int) -> list[str]: + result, current, num_of_letters = [], [], 0 + + for word in words: + if num_of_letters + len(word) + len(current) > maxWidth: + for i in range(maxWidth - num_of_letters): + current[i % (len(current) - 1 or 1)] += ' ' + result.append(''.join(current)) + current, num_of_letters = [], 0 + current += [word] + num_of_letters += len(word) + + result.append(' '.join(current).ljust(maxWidth)) + return result + +# Example usage: +words = ["This", "is", "an", "example", "of", "text", "justification."] +maxWidth = 16 +solution = Solution() +print(solution.fullJustify(words, maxWidth)) +``` + +#### C++ + +```cpp +#include +#include + +using namespace std; + +class Solution { +public: + vector fullJustify(vector& words, int maxWidth) { + vector result, current; + int num_of_letters = 0; + + for (const string& word : words) { + if (num_of_letters + word.size() + current.size() > maxWidth) { + for (int i = 0; i < maxWidth - num_of_letters; ++i) { + current[i % (current.size() - 1 ? current.size() - 1 : 1)] += ' '; + } + string line; + for (const string& w : current) { + line += w; + } + result.push_back(line); + current.clear(); + num_of_letters = 0; + } + current.push_back(word); + num_of_letters += word.size(); + } + string last_line; + for (const string& word : current) { + if (!last_line.empty()) last_line += ' '; + last_line += word; + } + last_line += string(maxWidth - last_line.size(), ' '); + result.push_back(last_line); + + return result; + } +}; + +// Example usage: +int main() { + Solution solution; + vector words = {"This", "is", "an", "example", "of", "text", "justification."}; + int maxWidth = 16; + vector justified_text = solution.fullJustify(words, maxWidth); + for (const string& line : justified_text) { + printf("\"%s\"\n", line.c_str()); + } + return 0; +} +``` + +#### Java + +```java +import java.util.ArrayList; +import java.util.List; + +class Solution { + public List fullJustify(String[] words, int maxWidth) { + List result = new ArrayList<>(); + List current = new ArrayList<>(); + int num_of_letters = 0; + + for (String word : words) { + if (num_of_letters + word.length() + current.size() > maxWidth) { + for (int i = 0; i < maxWidth - num_of_letters; ++i) { + current.set(i % (current.size() - 1 == 0 ? 1 : current.size() - 1), current.get(i % (current.size() - 1 == 0 ? 1 : current.size() - 1)) + " "); + } + result.add(String.join("", current)); + current.clear(); + num_of_letters = 0; + } + current.add(word); + num_of_letters += word.length(); + } + result.add(String.join(" ", current) + " ".repeat(maxWidth - num_of_letters - (current.size() - 1))); + return result; + } + + // Example usage + public static void main(String[] args) { + Solution solution = new Solution(); + String[] words = {"This", "is", "an", "example", "of", "text", "justification."}; + int maxWidth = 16; + List justified_text = solution.fullJustify(words, maxWidth); + for (String line : justified_text) { + System.out.println("\"" + line + "\""); + } + } +} +``` + +### Complexity Analysis + +- Time Complexity: $O(n)$, where n is the number of words. +- Space Complexity: $O(n)$, where n is the number of words. + +### References + +- **LeetCode Problem**: Text Justification \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0069-SqrtX.md b/solutions/lc-solutions/0000-0099/0069-SqrtX.md new file mode 100644 index 0000000..778fee4 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0069-SqrtX.md @@ -0,0 +1,129 @@ +--- +id: sqrt-x +title: Sqrt(x) (LeetCode) +difficulty: Easy +sidebar_label: 0069-SqrtX +topics: + - Math + - Binary Search +--- + + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/sqrtx/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/sqrtx/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +## Problem Description + +Given a non-negative integer `x`, return the square root of `x` rounded down to the nearest integer. The returned integer should be non-negative as well. + +You must not use any built-in exponent function or operator. + +### Examples + +#### Example 1: + +- **Input:** `x = 4` +- **Output:** `2` +- **Explanation:** The square root of 4 is 2, so we return 2. + +#### Example 2: + +- **Input:** `x = 8` +- **Output:** `2` +- **Explanation:** The square root of 8 is approximately 2.82842..., and since we round it down to the nearest integer, 2 is returned. + +### Constraints: + +- `0 <= x <= 2^31 - 1` + +### Approach + +To find the square root of a non-negative integer `x` without using built-in functions, we can use binary search within the range `[0, x]`. + +1. Initialize variables `left` and `right` to represent the search range `[0, x]`. +2. Perform binary search within this range, updating the `mid` value as `(left + right) / 2`. +3. If `mid * mid` is greater than `x`, update `right` to `mid - 1`. +4. If `mid * mid` is less than or equal to `x`, update `left` to `mid + 1`. +5. Repeat steps 2-4 until `left` is greater than `right`. +6. Return the value of `right`, which represents the largest integer whose square is less than or equal to `x`. + +### Solution Code + +#### Python + +``` +class Solution(object): + def mySqrt(self, x): + if x < 2: + return x + left, right = 1, x + while left <= right: + mid = (left + right) // 2 + if mid * mid == x: + return mid + elif mid * mid < x: + left = mid + 1 + else: + right = mid - 1 + return right +``` + +#### C++ + +``` +class Solution { +public: + int mySqrt(int x) { + if (x == 0) { + return 0; + } + + long left = 1, right = x; + while (left <= right) { + long mid = (left + right) / 2; + if (mid * mid == x) { + return mid; + } else if (mid * mid < x) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return right; + } +}; +``` + +#### Java + +``` +class Solution { + public int mySqrt(int x) { + if (x == 0) { + return 0; + } + + long left = 1, right = x; + while (left <= right) { + long mid = (left + right) / 2; + if (mid * mid == x) { + return (int)mid; + } else if (mid * mid < x) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return (int)right; + } +} +``` + +### Conclusion + +The "Sqrt(x)" problem can be efficiently solved using binary search within the range `[0, x]`. The provided solution code implements this approach in Python, C++, and Java, providing an optimal solution to the problem. \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0070-Climbing-Stairs.md b/solutions/lc-solutions/0000-0099/0070-Climbing-Stairs.md new file mode 100644 index 0000000..db0fe68 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0070-Climbing-Stairs.md @@ -0,0 +1,113 @@ +--- +id: climbing-stairs +title: Climbing Stairs (LeetCode) +difficulty: Easy +sidebar_label: 0070-ClimbingStairs +topics: + - Dynamic Programming +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/climbing-stairs/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/climbing-stairs/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +## Problem Description + +You are climbing a staircase. It takes `n` steps to reach the top. + +Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? + +### Examples + +#### Example 1: + +- **Input:** `n = 2` +- **Output:** `2` +- **Explanation:** There are two ways to climb to the top: + 1. 1 step + 1 step + 2. 2 steps + +#### Example 2: + +- **Input:** `n = 3` +- **Output:** `3` +- **Explanation:** There are three ways to climb to the top: + 1. 1 step + 1 step + 1 step + 2. 1 step + 2 steps + 3. 2 steps + 1 step + +### Constraints: + +- `1 <= n <= 45` + +### Approach + +To find the number of distinct ways to climb to the top of the staircase, we can use dynamic programming. + +1. Initialize an array `dp` of size `n+1` to store the number of distinct ways to reach each step. +2. Set `dp[0] = 1` and `dp[1] = 1` since there's only one way to reach the first step and the second step. +3. Iterate from `2` to `n`, updating `dp[i]` as the sum of `dp[i-1]` and `dp[i-2]`. +4. Finally, return `dp[n]`, which represents the number of distinct ways to reach the `n`-th step. + +### Solution Code + +#### Python + +``` +class Solution(object): + def climbStairs(self, n): + if n <= 2: + return n + dp = [0] * (n + 1) + dp[1] = 1 + dp[2] = 2 + + for i in range(3, n + 1): + dp[i] = dp[i - 1] + dp[i - 2] + return dp[n] +``` + +#### C++ + +``` +class Solution { +public: + int climbStairs(int n) { + if (n <= 2) { + return n; + } + vector dp(n + 1); + dp[1] = 1; + dp[2] = 2; + for (int i = 3; i <= n; ++i) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + return dp[n]; + } +}; +``` + +#### Java + +``` +class Solution { + public int climbStairs(int n) { + if (n <= 2) { + return n; + } + int[] dp = new int[n + 1]; + dp[1] = 1; + dp[2] = 2; + for (int i = 3; i <= n; ++i) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + return dp[n]; + } +} +``` + +### Conclusion + +The "Climbing Stairs" problem can be efficiently solved using dynamic programming, where the number of distinct ways to reach each step is calculated iteratively. The provided solution code implements this approach in Python, C++, and Java, providing an optimal solution to the problem. \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0071-simplify-path.md b/solutions/lc-solutions/0000-0099/0071-simplify-path.md new file mode 100644 index 0000000..331c9d9 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0071-simplify-path.md @@ -0,0 +1,393 @@ +--- +id: simplify-path +title: Simplify Path +sidebar_label: 0071 - Simplify Path + +tags: +- stack +- lifo +- queue +- dequeue + +description: "This is a solution to the Simplify Path problem on LeetCode." +--- + +## Problem Description +Given an absolute path for a Unix-style file system, which begins with a slash `'/'`, transform this path into its **simplified canonical path**. + +In Unix-style file system context, a single period `'.'` signifies the current directory, a double period `".."` denotes moving up one directory level, and multiple slashes such as `"//"` are interpreted as a single slash. In this problem, treat sequences of periods not covered by the previous rules (like `"..."`) as valid names for files or directories. + +The simplified canonical path should adhere to the following rules: +- It must start with a single slash `'/'`. +- Directories within the path should be separated by only one slash `'/'`. +- It should not end with a slash `'/'`, unless it's the root directory. +- It should exclude any single or double periods used to denote current or parent directories. +Return the new path. + +### Examples + +**Example 1:** + +``` +Input: path = "/home/" +Output: "/home" +Explanation: The trailing slash should be removed. +``` + +**Example 2:** +``` +Input: "/home//foo/" +Output: "/home/foo" +Explanation: +Multiple consecutive slashes are replaced by a single one. +``` + +**Example 3:** +``` +Input: path = "/home/user/Documents/../Pictures" +Output: "/home/user/Pictures" +Explanation: +A double period ".." refers to the directory up a level. +``` + +**Example 4:** +``` +Input: path = "/../" +Output: "/" +Explanation: +Going one level up from the root directory is not possible. +``` + +**Example 5:** +``` +Input: path = "/.../a/../b/c/../d/./" +Output: "/.../b/d" +Explanation: +"..." is a valid name for a directory in this problem. +``` + + +### Constraints +- `1 <= path.length <= 3000` +- `path` consists of English letters, digits, period `'.'`, slash `'/'` or `'_'` +- `path` is a valid absolute Unix path + + +## Solution for Simplify Path +### Approach +#### Brute Force +- The brute force approach involves iteratively processing each component of the path to build the simplified canonical path. + - **Splitting the Path**: Split the input path by '/' to separate out each directory or file name. + - **Using a Stack:** Utilize a stack to keep track of directories as you iterate through the split components of the path. + - Push directories onto the stack unless they are "." or an empty string (resulting from consecutive slashes). + - For "..", pop the top element from the stack if the stack is not empty (handling the parent directory). + - **Constructing the Result:** After processing all components, construct the simplified path using the elements in the stack. + - Join elements from the stack with '/' to form the final path string. + - **Edge Cases:** Handle cases like multiple consecutive slashes, leading and trailing slashes, and paths that move up beyond the root directory. + + +#### Optimized Approach +- The optimized approach aims to achieve the same result but with improved efficiency, primarily by avoiding unnecessary string manipulations and ensuring each component is processed only once. +- **Splitting and Processing:** Split the input path by '/' and iterate through each component. + - Use a deque (double-ended queue) instead of a stack for efficient popping from the front when necessary. +- **Directly Build the Result:** Instead of joining strings multiple times, directly construct the result path during the iteration. + - Append valid directory names to the result path and handle ".." by moving back in the result path string. +- **Complexity**: Both approaches involve O(n) time complexity, where n is the length of the input path, due to iterating through each component once. +- **Space Complexity:** The optimized approach may have slightly better space complexity due to minimizing the use of additional data structures for storing intermediate results. + +##### Example +Consider the path "/a/b/c/.././d/e/f/../../g/h/". The simplified canonical path should be "/a/b/d/e/g/h". + +**Corner Cases** +- Paths containing only slashes ("/"). +- Paths with consecutive slashes ("/a//b"). +- Paths with '.' and '..' in various combinations ("/../", "/a/b/./../c"). +- Paths that reduce to the root directory ("/../../"). +- Paths that don't reduce at all ("/a/b/c"). + +**Implementation** +```python +from collections import deque + +class Solution: + def simplifyPath(self, path: str) -> str: + components = path.split('/') + stack = deque() + + for comp in components: + if comp == '' or comp == '.': + continue + elif comp == '..': + if stack: + stack.pop() + else: + stack.append(comp) + + # Construct simplified path + if not stack: + return '/' + else: + return '/' + '/'.join(stack) + +# Example usage: +solution = Solution() +path = "/a/b/c/.././d/e/f/../../g/h/" +print(solution.simplifyPath(path)) # Output: "/a/b/d/e/g/h" +``` + + + + +#### Implementation + + ```jsx live + function Solution(arr) { + var simplifyPath = function(path) { + const components = path.split('/'); + const stack = []; + + for (let comp of components) { + if (comp === '' || comp === '.') { + continue; + } else if (comp === '..') { + if (stack.length > 0) { + stack.pop(); + } + } else { + stack.push(comp); + } + } + + // Construct simplified path + let simplifiedPath = '/' + stack.join('/'); + + // Ensure not ending with '/' + if (simplifiedPath.length > 1 && simplifiedPath.endsWith('/')) { + simplifiedPath = simplifiedPath.slice(0, -1); + } + + + return simplifiedPath; + }; + + const input = "/home//foo/" + const output = simplifyPath(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + + ## Code in Different Languages + + + + + + + ```javascript + /** + * @param {string} path + * @return {string} + */ + var simplifyPath = function(path) { + const components = path.split('/'); + const stack = []; + + for (let comp of components) { + if (comp === '' || comp === '.') { + continue; + } else if (comp === '..') { + if (stack.length > 0) { + stack.pop(); + } + } else { + stack.push(comp); + } + } + + // Construct simplified path + let simplifiedPath = '/' + stack.join('/'); + + // Ensure not ending with '/' + if (simplifiedPath.length > 1 && simplifiedPath.endsWith('/')) { + simplifiedPath = simplifiedPath.slice(0, -1); + } + + return simplifiedPath; + }; + ``` + + + + + + + ```typescript + function simplifyPath(path: string): string { + const components = path.split('/'); + const stack = []; + + for (let comp of components) { + if (comp === '' || comp === '.') { + continue; + } else if (comp === '..') { + if (stack.length > 0) { + stack.pop(); + } + } else { + stack.push(comp); + } + } + + // Construct simplified path + let simplifiedPath = '/' + stack.join('/'); + + // Ensure not ending with '/' + if (simplifiedPath.length > 1 && simplifiedPath.endsWith('/')) { + simplifiedPath = simplifiedPath.slice(0, -1); + } + + return simplifiedPath; + }; + ``` + + + + + + + ```python + class Solution(object): + def simplifyPath(self, path): + """ + :type path: str + :rtype: str + """ + components = path.split('/') + stack = [] + + for comp in components: + if comp == '' or comp == '.': + continue + elif comp == '..': + if stack: + stack.pop() + else: + stack.append(comp) + + # Construct simplified path + simplified_path = '/' + '/'.join(stack) + + # Ensure not ending with '/' + if len(simplified_path) > 1 and simplified_path.endswith('/'): + simplified_path = simplified_path[:-1] + + return simplified_path + ``` + + + + + + + ```java + class Solution { + public String simplifyPath(String path) { + String[] components = path.split("/"); + Deque stack = new ArrayDeque<>(); + + for (String comp : components) { + if (comp.equals("") || comp.equals(".")) { + continue; + } else if (comp.equals("..")) { + if (!stack.isEmpty()) { + stack.pop(); + } + } else { + stack.push(comp); + } + } + + // Construct simplified path + StringBuilder simplifiedPath = new StringBuilder(); + while (!stack.isEmpty()) { + simplifiedPath.append("/").append(stack.removeLast()); + } + + // Handle case when simplified path is empty + if (simplifiedPath.length() == 0) { + return "/"; + } else { + return simplifiedPath.toString(); + } + } + } + ``` + + + + + + + ```cpp + class Solution { + public: + string simplifyPath(string path) { + vector components; + stringstream ss(path); + string token; + + while (getline(ss, token, '/')) { + if (token == "" || token == ".") { + continue; + } else if (token == "..") { + if (!components.empty()) { + components.pop_back(); + } + } else { + components.push_back(token); + } + } + + // Construct simplified path + deque stack(components.begin(), components.end()); + stringstream result; + + while (!stack.empty()) { + result << '/' << stack.front(); + stack.pop_front(); + } + + string simplifiedPath = result.str(); + + // Ensure not ending with '/' + if (simplifiedPath.length() > 1 && simplifiedPath.back() == '/') { + simplifiedPath.pop_back(); + } + + return simplifiedPath.empty() ? "/" : simplifiedPath; + } + }; + ``` + + + + +
+
+ +## References + +- **LeetCode Problem**: [Simplify Path](https://leetcode.com/problems/simplify-path/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/simplify-path/solutions/) \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0072-edit-distance.md b/solutions/lc-solutions/0000-0099/0072-edit-distance.md new file mode 100644 index 0000000..ce6fc93 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0072-edit-distance.md @@ -0,0 +1,166 @@ +--- +id: edit-distance +title: Edit Distance(LeetCode) +sidebar_label: 0072-Edit-Distance +tags: + - String + - Dynamic Programming +description: Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. +sidebar_position: 72 +--- + +## Problem Statement + +Given two strings `word1` and `word2`, return the minimum number of operations required to convert `word1` to `word2`. + +You have the following three operations permitted on a word: + +- Insert a character +- Delete a character +- Replace a character + +### Examples + +**Example 1:** + +```plaintext +Input: word1 = "horse", word2 = "ros" +Output: 3 +Explanation: +horse -> rorse (replace 'h' with 'r') +rorse -> rose (remove 'r') +rose -> ros (remove 'e') +``` + +**Example 2:** + +```plaintext +Input: word1 = "intention", word2 = "execution" +Output: 5 +Explanation: +intention -> inention (remove 't') +inention -> enention (replace 'i' with 'e') +enention -> exention (replace 'n' with 'x') +exention -> exection (replace 'n' with 'c') +exection -> execution (insert 'u') +``` + +### Constraints + +- `0 <= word1.length, word2.length <= 500` +- `word1` and `word2` consist of lowercase English letters. + +## Solution + +We explore two main approaches: Recursive Dynamic Programming with +Memoization and Iterative Dynamic Programming with Tabulation. + +### Approach 1: Recursive Dynamic Programming (Memoization) +Concept: Store the solutions for each position to avoid redundant calculations. + +#### Algorithm + +For every index of string S1, we have three options to match that index with string S2, i.e replace the character, remove the character or insert some character at that index. Therefore, we can think in terms of string matching path as we have done already in previous questions. + +As there is no uniformity in data, there is no other way to find out than to try out all possible ways. To do so we will need to use recursion. + +Steps to memoize a recursize solution: +- Create a dp array of size [n][m]. The size of S1 and S2 are n and m respectively, so the variable i will always lie between β€˜0’ and β€˜n-1’ and the variable j between β€˜0’ and β€˜m-1’. +- We initialize the dp array to -1. +Whenever we want to find the answer to particular parameters (say f(i,j)), we first check whether the answer is already calculated using the dp array(i.e dp[i][j]!= -1 ). If yes, simply return the value from the dp array. +- If not, then we are finding the answer for the given value for the first time, we will use the recursive relation as usual but before returning from the function, we will set dp[i][j] to the solution we get. + +#### Implementation + +```C++ +int editDistanceUtil(string& S1, string& S2, int i, int j, vector>& dp) { + if (i < 0) + return j + 1; + if (j < 0) + return i + 1; + + if (dp[i][j] != -1) + return dp[i][j]; + + if (S1[i] == S2[j]) + return dp[i][j] = 0 + editDistanceUtil(S1, S2, i - 1, j - 1, dp); + + else + return dp[i][j] = 1 + min(editDistanceUtil(S1, S2, i - 1, j - 1, dp), + min(editDistanceUtil(S1, S2, i - 1, j, dp), + editDistanceUtil(S1, S2, i, j - 1, dp))); +} + +int editDistance(string& S1, string& S2) { + int n = S1.size(); + int m = S2.size(); + + vector> dp(n, vector(m, -1)); + + return editDistanceUtil(S1, S2, n - 1, m - 1, dp); +} +``` + +### Complexity Analysis + +- **Time complexity**: O(N*M) +Reason: There are N*M states therefore at max β€˜N*M’ new problems will be solved. +- **Space complexity**: O(N*M) + O(N+M) +Reason: We are using a recursion stack space(O(N+M)) and a 2D array ( O(N*M)). + +### Approach 2: Iterative Dynamic Programming (Tabulation) + +Concept: In the recursive logic, we set the base case to `if(i<0)` and `if(j<0)` but we can’t set the dp array’s index to -1. Therefore a hack for this issue is to shift every index by 1 towards the right. + +#### Algorithm + +1. First we initialise the dp array of size [n+1][m+1] as zero. +2. Next, we set the base condition (keep in mind 1-based indexing), we set the first column’s value as i and the first row as j( 1-based indexing). +3. Similarly, we will implement the recursive code by keeping in mind the shifting of indexes, therefore S1[i] will be converted to S1[i-1]. Same for S2. +4. At last, we will print dp[N][M] as our answer.required. + +#### Implementation + +```C++ +int editDistance(string& S1, string& S2) { + int n = S1.size(); + int m = S2.size(); + + // Create a DP table to store edit distances + vector> dp(n + 1, vector(m + 1, 0)); + + // Initialize the first row and column + for (int i = 0; i <= n; i++) { + dp[i][0] = i; + } + for (int j = 0; j <= m; j++) { + dp[0][j] = j; + } + + // Fill in the DP table + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + if (S1[i - 1] == S2[j - 1]) { + // If the characters match, no additional cost + dp[i][j] = dp[i - 1][j - 1]; + } else { + // Minimum of three choices: + // 1. Replace the character at S1[i-1] with S2[j-1] + // 2. Delete the character at S1[i-1] + // 3. Insert the character at S2[j-1] into S1 + dp[i][j] = 1 + min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])); + } + } + } + + // The value at dp[n][m] contains the edit distance + return dp[n][m]; +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(N \times M)$ +Reason: There are two nested loops +- **Space complexity**: $O(N \times M)$ +Reason: We are using an external array of size β€˜N*M’. Stack Space is eliminated. diff --git a/solutions/lc-solutions/0000-0099/0073-Set-Matrix-Zeroes.md b/solutions/lc-solutions/0000-0099/0073-Set-Matrix-Zeroes.md new file mode 100644 index 0000000..83e6915 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0073-Set-Matrix-Zeroes.md @@ -0,0 +1,215 @@ +--- +id: set-matrix-zeros +title: Set Matrix Zeros +difficulty: Medium +sidebar_label: 0073-SetMatrixZeros +tags: + - Array + - Hash Table + - Matrix +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Set Matrix Zeros](https://leetcode.com/problems/set-matrix-zeroes/description/) | [Set Matrix Zeros Solution on LeetCode](https://leetcode.com/problems/set-matrix-zeroes/solutions/) | [Leetcode Profile](https://leetcode.com/u/debangi_29/) | + +## Problem Description + +Given an $m \times n$ integer matrix matrix, if an element is 0, set its entire row and column to 0's. + +You must do it in place. + + + +### Examples + +#### Example 1: + +**Input**: +``` +Matrix = [[1,1,1],[1,0,1],[1,1,1]] +``` + +**Output**: +``` +[[1,0,1],[0,0,0],[1,0,1]] +``` + +#### Example 2: +**Input**: +``` +matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] +``` + +**Output**: +``` +[[0,0,0,0],[0,4,5,0],[0,3,1,0]] +``` + + +### Constraints + +- $m = \text {matrix.length}$ +- $n = \text {matrix[0].length}$ +- $1 \leq m, n \leq 200$ +- $-2^{31} \leq \text {matrix[i][j]} \leq 2^{31} - 1$ + +### Approach + +The steps are as follows: + +- First, we will traverse the matrix and mark the proper cells of 1st row and 1st column with 0 accordingly. The marking will be like this: if cell(i, j) contains 0, we will mark the i-th row i.e. matrix[i][0] with 0 and we will mark j-th column i.e. matrix[0][j] with 0. +If i is 0, we will mark matrix[0][0] with 0 but if j is 0, we will mark the col0 variable with 0 instead of marking matrix[0][0] again. + +- After step 1 is completed, we will modify the cells from (1,1) to (n-1, m-1) using the values from the 1st row, 1st column, and col0 variable. +We will not modify the 1st row and 1st column of the matrix here as the modification of the rest of the matrix(i.e. From (1,1) to (n-1, m-1)) is dependent on that row and column. + +- Finally, we will change the 1st row and column using the values from matrix[0][0] and col0 variable. Here also we will change the row first and then the column. +If matrix[0][0] = 0, we will change all the elements from the cell (0,1) to (0, m-1), to 0. +If col0 = 0, we will change all the elements from the cell (0,0) to (n-1, 0), to 0. + +### Solution Code + +#### Python + +``` +class Solution: + def setZeroes(self, matrix: List[List[int]]) -> None: + m = len(matrix) + n = len(matrix[0]) + shouldFillFirstRow = 0 in matrix[0] + shouldFillFirstCol = 0 in list(zip(*matrix))[0] + + # Store the information in the first row and the first column. + for i in range(1, m): + for j in range(1, n): + if matrix[i][j] == 0: + matrix[i][0] = 0 + matrix[0][j] = 0 + + # Fill 0s for the matrix except the first row and the first column. + for i in range(1, m): + for j in range(1, n): + if matrix[i][0] == 0 or matrix[0][j] == 0: + matrix[i][j] = 0 + + # Fill 0s for the first row if needed. + if shouldFillFirstRow: + matrix[0] = [0] * n + + # Fill 0s for the first column if needed. + if shouldFillFirstCol: + for row in matrix: + row[0] = 0 + +``` + +#### Java + +``` +class Solution { + public void setZeroes(int[][] matrix) { + final int m = matrix.length; + final int n = matrix[0].length; + boolean shouldFillFirstRow = false; + boolean shouldFillFirstCol = false; + + for (int j = 0; j < n; ++j) + if (matrix[0][j] == 0) { + shouldFillFirstRow = true; + break; + } + + for (int i = 0; i < m; ++i) + if (matrix[i][0] == 0) { + shouldFillFirstCol = true; + break; + } + + // Store the information in the first row and the first column. + for (int i = 1; i < m; ++i) + for (int j = 1; j < n; ++j) + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + + // Fill 0s for the matrix except the first row and the first column. + for (int i = 1; i < m; ++i) + for (int j = 1; j < n; ++j) + if (matrix[i][0] == 0 || matrix[0][j] == 0) + matrix[i][j] = 0; + + // Fill 0s for the first row if needed. + if (shouldFillFirstRow) + for (int j = 0; j < n; ++j) + matrix[0][j] = 0; + + // Fill 0s for the first column if needed. + if (shouldFillFirstCol) + for (int i = 0; i < m; ++i) + matrix[i][0] = 0; + } +} +``` + +#### C++ + +``` +class Solution { + public: + void setZeroes(vector>& matrix) { + const int m = matrix.size(); + const int n = matrix[0].size(); + bool shouldFillFirstRow = false; + bool shouldFillFirstCol = false; + + for (int j = 0; j < n; ++j) + if (matrix[0][j] == 0) { + shouldFillFirstRow = true; + break; + } + + for (int i = 0; i < m; ++i) + if (matrix[i][0] == 0) { + shouldFillFirstCol = true; + break; + } + + // Store the information in the first row and the first column. + for (int i = 1; i < m; ++i) + for (int j = 1; j < n; ++j) + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + + // Fill 0s for the matrix except the first row and the first column. + for (int i = 1; i < m; ++i) + for (int j = 1; j < n; ++j) + if (matrix[i][0] == 0 || matrix[0][j] == 0) + matrix[i][j] = 0; + + // Fill 0s for the first row if needed. + if (shouldFillFirstRow) + for (int j = 0; j < n; ++j) + matrix[0][j] = 0; + + // Fill 0s for the first column if needed. + if (shouldFillFirstCol) + for (int i = 0; i < m; ++i) + matrix[i][0] = 0; + } +}; + +``` + +### Conclusion + +- Time Complexity: $O(2*(N*M))$, where N = no. of rows in the matrix and M = no. of columns in the matrix. + + Reason: In this approach, we are also traversing the entire matrix 2 times and each traversal is taking $O(N*M)$ time complexity. + +- Space Complexity: $O(1)$ as we are not using any extra space. diff --git a/solutions/lc-solutions/0000-0099/0074-Search-a-2D-Matrix.md b/solutions/lc-solutions/0000-0099/0074-Search-a-2D-Matrix.md new file mode 100644 index 0000000..4736805 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0074-Search-a-2D-Matrix.md @@ -0,0 +1,159 @@ +--- +id: search-a-2D-matrix +title: Search a 2D matrix +difficulty: Medium +sidebar_label: 0074-search2Dmatrix +tags: + - Array + - Binary Search + - Matrix +--- + +## Problem + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Search a 2D matrix](https://leetcode.com/problems/search-a-2d-matrix/) | [Search a 2D matrix Solution on LeetCode](https://leetcode.com/problems/search-a-2d-matrix/solutions/) | [Leetcode Profile](https://leetcode.com/u/debangi_29/) | + +## Problem Description + +You are given an $m \times n$ integer matrix matrix with the following two properties: + +- Each row is sorted in non-decreasing order. +- The first integer of each row is greater than the last integer of the previous row. + +Given an integer target, return true if target is in matrix or false otherwise. + +You must write a solution in $O(log(m * n))$ time complexity. + + +### Examples + +#### Example 1: + +**Input**: +``` +Matrix = [[1,3,5,7], [10,11,16,20], [23,30,34,60]] +Target = 3 +``` + +**Output**: true + +#### Example 2: +**Input**: +``` +Matrix = [[1,3,5,7], [10,11,16,20], [23,30,34,60]] +Target = 13 +``` + +**Output**: false + + +### Constraints + +- $m == \text{matrix.length}$ +- $n == \text{matrix}[i].\text{length}$ +- $1 \leq m, n \leq 100$ +- $-10^{4} \leq \text{matrix}[i][j], \text{target} \leq 10^{4}$ + +### Approach + +The steps are as follows: + +- Place the 2 pointers i.e. low and high: Initially, we will place the pointers. The pointer low will point to 0 and the high will point to (NxM)-1. + +- Calculate the β€˜mid’: Now, inside the loop, we will calculate the value of β€˜mid’ using the following formula: +mid = (low+high) // 2 ( β€˜//’ refers to integer division) + +- Eliminate the halves based on the element at index mid: To get the element, we will convert index β€˜mid’ to the corresponding cell using the above formula. Here no. of columns of the matrix = M. +row = mid / M, col = mid % M. + - If matrix[row][col] == target: We should return true here, as we have found the β€˜target’. + + - If matrix[row][col] < target: In this case, we need bigger elements. So, we will eliminate the left half and consider the right half (low = mid+1). + - If matrix[row][col] > target: In this case, we need smaller elements. So, we will eliminate the right half and consider the left half (high = mid-1). + +- Steps 2-3 will be inside a while loop and the loop will end once low crosses high +(i.e. low > high). If we are out of the loop, we can say the target does not exist in the matrix. So, we will return false. + +### Solution Code + +#### Python + +``` +class Solution: + def searchMatrix(matrix, target): + n = len(matrix) + m = len(matrix[0]) + + # apply binary search: + low = 0 + high = n * m - 1 + while low <= high: + mid = (low + high) // 2 + row = mid // m + col = mid % m + if matrix[row][col] == target: + return True + elif matrix[row][col] < target: + low = mid + 1 + else: + high = mid - 1 + return False + +``` + +#### Java + +``` +class Solution { + public static boolean searchMatrix(ArrayList> matrix, int target) { + int n = matrix.size(); + int m = matrix.get(0).size(); + + //apply binary search: + int low = 0, high = n * m - 1; + while (low <= high) { + int mid = (low + high) / 2; + int row = mid / m, col = mid % m; + if (matrix.get(row).get(col) == target) return true; + else if (matrix.get(row).get(col) < target) low = mid + 1; + else high = mid - 1; + } + return false; + } +} +``` + +#### C++ + +``` +class Solution { + public: + bool searchMatrix(vector>& matrix, int target) { + int n = matrix.size(); + int m = matrix[0].size(); + + //apply binary search: + int low = 0, high = n * m - 1; + while (low <= high) { + int mid = (low + high) / 2; + int row = mid / m, col = mid % m; + if (matrix[row][col] == target) return true; + else if (matrix[row][col] < target) low = mid + 1; + else high = mid - 1; + } + return false; +} +}; + +``` + +### Conclusion + +Complexity Analysis + +- Time Complexity: $O(log(N.M))$, where N = given row number, M = given column number. + + Reason: We are applying binary search on the imaginary 1D array of size NxM. + +- Space Complexity: $O(1)$ as we are not using any extra space. diff --git a/solutions/lc-solutions/0000-0099/0075-sort-colors.md b/solutions/lc-solutions/0000-0099/0075-sort-colors.md new file mode 100644 index 0000000..2d75bc6 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0075-sort-colors.md @@ -0,0 +1,492 @@ +--- +id: sort-colors +title: Sort Colors +sidebar_label: 0075 - Sort Colors +tags: + - Array + - LeetCode + - JavaScript + - TypeScript +description: "This is a solution to the Two Sum problem on LeetCode." +--- + +In this page, we will be solve the Sort Colors problem using three different approaches: brute force, 3 Pointer, and Dutch National Flag Algo technique. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. + +We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. + +You must solve this problem without using the library's sort function. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [2,0,2,1,1,0] +Output: [0,0,1,1,2,2] +``` + +**Example 2:** + +```plaintext +Input: nums = [2,0,1] +Output: [0,1,2] +``` + +### Constraints + +- `n == nums.length` +- `1 <= n <= 300` +- `nums[i] is either 0, 1, or 2.` + + +**Follow up:** Could you come up with a one-pass algorithm using only constant extra space? + +--- + +## Solution for Sort Colors + +### Intuition and Approach + +The problem can be solved using a brute force approach by sorting vector, 3 pointers, or the Dutch National Flag Algo. The brute force approach has a time complexity of $$O(nlog(n))$$, while the 3 Pointer and Dutch National Flag Algo techniques have a time complexity of $$O(n)$$. The Dutch National Flag Algo approach is the most efficient and is recommended for large inputs. + + + + +### Approach 1: Brute Force (Naive) + +We can simply Sort the Array and get Answer of it. But the time complexity will be for this goes to O(N*logN). + +#### Codes in Different Languages + + + + + ```javascript + var sortColors = function(nums) { + nums.sort((a, b) => a - b); + }; + ``` + + + + + ```typescript + function sortColors(nums: number[]): void { + nums.sort((a, b) => a - b); + } + ``` + + + + + ```python + class Solution: + def sortColors(self, nums): + nums.sort() + ``` + + + + + ```java + import java.util.Arrays; + + public class Solution { + public void sortColors(int[] nums) { + Arrays.sort(nums); + } + } + ``` + + + + + ```cpp + class Solution { + public: + void sortColors(vector& nums) { + sort(nums.begin(),nums.end()); + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n log(n))$$ +- Space Complexity: $$O(1)$$ +- Where `n` is the length of the input array `nums`. + + + + +### Approach 2: Better + +Keeping count of values. There are only 3 distinct values in the array so it's easy to maintain the count of all, Like the count of 0, 1, and 2. + +1. Take 3 variables to maintain the count of 0, 1 and 2. +2. Travel the array once and increment the corresponding counting variables +3. In 2nd traversal of array, we will now over write the first β€˜a’ indices / positions in array with ’0’, the next β€˜b’ with β€˜1’ and the remaining β€˜c’ with β€˜2’. + +#### Code in Different Languages + + + + + ```javascript + var sortColors = function(nums) { + let zero = 0, one = 0, two = 0; + + for (let i = 0; i < nums.length; i++) { + if (nums[i] === 0) { + zero++; + } else if (nums[i] === 1) { + one++; + } else { + two++; + } + } + + let index = 0; + + while (zero > 0) { + nums[index] = 0; + index++; + zero--; + } + + while (one > 0) { + nums[index] = 1; + index++; + one--; + } + + while (two > 0) { + nums[index] = 2; + index++; + two--; + } + }; + ``` + + + + + ```typescript + function sortColors(nums: number[]): void { + let zero = 0, one = 0, two = 0; + + for (let i = 0; i < nums.length; i++) { + if (nums[i] === 0) { + zero++; + } else if (nums[i] === 1) { + one++; + } else { + two++; + } + } + + let index = 0; + + while (zero > 0) { + nums[index] = 0; + index++; + zero--; + } + + while (one > 0) { + nums[index] = 1; + index++; + one--; + } + + while (two > 0) { + nums[index] = 2; + index++; + two--; + } + } + ``` + + + + + ```python + class Solution(object): + def sortColors(self, nums): + + zero = 0 + one = 0 + two = 0 + + for num in nums: + if num == 0: + zero += 1 + elif num == 1: + one += 1 + else: + two += 1 + + index = 0 + while zero > 0: + nums[index] = 0 + index += 1 + zero -= 1 + + while one > 0: + nums[index] = 1 + index += 1 + one -= 1 + + while two > 0: + nums[index] = 2 + index += 1 + two -= 1 + ``` + + + + + ```java + class Solution { + public void sortColors(int[] nums) { + int zero = 0, one = 0, two = 0; + for (int i = 0; i < nums.length; i++) { + if (nums[i] == 0) + zero++; + else if (nums[i] == 1) + one++; + else + two++; + } + + int index = 0; + while (zero-- > 0) { + nums[index] = 0; + index++; + } + + while (one-- > 0) { + nums[index] = 1; + index++; + } + + while (two-- > 0) { + nums[index] = 2; + index++; + } + } + } + ``` + + + + + ```cpp + class Solution { +public: + void sortColors(vector& nums) { + + int zero = 0, one = 0, two = 0; + for(int i=0; i + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(1)$$ +- Where `n` is the length of the input array `nums`. + + + + +### Approach 3: Dutch National Flag Algo + +This problem can be further Optimize by Dutch National flag algorithm. + +This algorithm contains 3 pointers i.e. low, mid, and high, and 3 main rules. The rules are the following: + +arr[0….low-1] contains 0. [Extreme left part] +arr[low….mid-1] contains 1. +arr[high+1….n-1] contains 2. [Extreme right part], n = size of the array + +#### Code in Different Languages + + + + + ```javascript + var sortColors = function(nums) { + let start = 0; + let mid = 0; + let end = nums.length - 1; + + while (mid <= end) { + if (nums[mid] === 0) { + [nums[mid], nums[start]] = [nums[start], nums[mid]]; + mid++; + start++; + } else if (nums[mid] === 1) { + mid++; + } else { + [nums[mid], nums[end]] = [nums[end], nums[mid]]; + end--; + } + } + }; + + ``` + + + + + + ```ts + function sortColors(nums: number[]): void { + let start = 0; + let mid = 0; + let end = nums.length - 1; + + while (mid <= end) { + if (nums[mid] === 0) { + [nums[mid], nums[start]] = [nums[start], nums[mid]]; + mid++; + start++; + } else if (nums[mid] === 1) { + mid++; + } else { + [nums[mid], nums[end]] = [nums[end], nums[mid]]; + end--; + } + } + } + ``` + + + + + ```py + class Solution(object): + def sortColors(self, nums): + + start = 0 + mid = 0 + end = len(nums) - 1 + + while mid <= end: + if nums[mid] == 0: + nums[mid], nums[start] = nums[start], nums[mid] + mid += 1 + start += 1 + elif nums[mid] == 1: + mid += 1 + else: + nums[mid], nums[end] = nums[end], nums[mid] + end -= 1 + + ``` + + + + + ```java + class Solution { + public void sortColors(int[] nums) { + int start = 0, mid = 0, end = nums.length - 1; + + while (mid <= end) { + if (nums[mid] == 0) { + int temp = nums[mid]; + nums[mid] = nums[start]; + nums[start] = temp; + mid++; + start++; + } else if (nums[mid] == 1) { + mid++; + } else { + int temp = nums[mid]; + nums[mid] = nums[end]; + nums[end] = temp; + end--; + } + } + } + } + + ``` + + + + + + ```cpp + class Solution { + public: + void sortColors(vector& nums) { + int start=0, mid=0, end=nums.size()-1; + + while(mid<=end){ + if(nums[mid]==0){ + swap(nums[mid],nums[start]); + mid++; + start++; + } + else if(nums[mid]==1) mid++; + else{ + swap(nums[mid],nums[end]); + end--; + } + } + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(1)$$ +- Where `n` is the length of the input array `nums`. + + + + +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/sort-colors/description/) +- **Solution Link:** [Sort Colors Solution on LeetCode](https://leetcode.com/problems/sort-colors/solutions/2340558/c-brute-better-optimal/) diff --git a/solutions/lc-solutions/0000-0099/0076-minimum-window-substring.md b/solutions/lc-solutions/0000-0099/0076-minimum-window-substring.md new file mode 100644 index 0000000..da502b3 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0076-minimum-window-substring.md @@ -0,0 +1,168 @@ +--- +id: minimum-window-substring +title: Minimum Window Substring(LeetCode) +sidebar_label: 0076-Minimum Window Substring +tags: + - String + - Hash Table + - Sliding Window +description: Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". +--- + +## Problem Statement + +Given two strings `s` and `t` of lengths `m` and `n` respectively, return the minimum window substring of `s` such that every character in `t` (including duplicates) is included in the window. If there is no such substring, return the empty string `""`. + +The testcases will be generated such that the answer is unique. + +### Examples + +**Example 1:** + +```plaintext +Input: s = "ADOBECODEBANC", t = "ABC" +Output: "BANC" +Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t. +``` + +**Example 2:** + +```plaintext +Input: s = "a", t = "a" +Output: "a" +Explanation: The entire string s is the minimum window. +``` + +**Example 3:** + +```plaintext +Input: s = "a", t = "aa" +Output: "" +Explanation: Both 'a's from t must be included in the window. +Since the largest window of s only has one 'a', return empty string. +``` + +### Constraints + +- `m == s.length` +- `n == t.length` +- `1 <= m, n <= 105` +- `s` and `t` consist of uppercase and lowercase English letters. + +## Solution + +### Approach 1: C++ + +#### Algorithm + +1. Initialization: +* Create a `map` to count characters in `t`. +* Initialize `counter` to the length of `t`, begin and end pointers to 0, `d` (length of the minimum window) to `INT_MAX`, and `head` to 0. +2. Expand the Window: +* Move the `end` pointer to expand the window. +* Decrease the count in `map` for the current character in `s`. +* If the count in `map` is greater than 0, decrement `counter`. +3. Shrink the Window: +* When `counter` is 0, try to shrink the window by moving the `begin` pointer. +* If the new window size is smaller, update `head` and `d`. +* Increase the count in `map` for the character at `begin`. +* If the count in `map` becomes positive, increment `counter`. +4. Return Result: +* If `d` is still `INT_MAX`, return an empty string. +* Otherwise, return the substring starting from `head` with length `d`. + +#### Implementation + +```C++ +class Solution { +public: + string minWindow(string s, string t) { + vector map(128, 0); + for (char c : t) { + map[c]++; + } + + int counter = t.size(), begin = 0, end = 0, d = INT_MAX, head = 0; + while (end < s.size()) { + if (map[s[end++]]-- > 0) { + counter--; + } + while (counter == 0) { + if (end - begin < d) { + head = begin; + d = end - head; + } + if (map[s[begin++]]++ == 0) { + counter++; + } + } + } + return d == INT_MAX ? "" : s.substr(head, d); + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: $O(M+N)$ +- **Space complexity**: $O(1)$ + +### Approach 2: Python + +#### Algorithm + +1. Initialization: +* Create a `needstr` dictionary to count characters in `t`. +* Initialize `needcnt` to the length of `t`, `res` to store the result window, and `start` to 0. +2. Expand the Window: +* Move the `end` pointer to expand the window. +* Decrease the count in `needstr` for the current character in `s`. +* If the count in `needstr` is greater than 0, decrement `needcnt`. +3. Shrink the Window: +* When `needcnt` is 0, try to shrink the window by moving the `start` pointer. +* Adjust the count in `needstr` for the character at `start`. +* If the count in `needstr` becomes positive, increment `needcnt`. +4. Return Result: +* If the result window is valid, return the substring. +* Otherwise, return an empty string. + +#### Implementation + +```Python +class Solution: + def minWindow(self, s: str, t: str) -> str: + if len(s) < len(t): + return "" + needstr = collections.defaultdict(int) + for ch in t: + needstr[ch] += 1 + needcnt = len(t) + res = (0, float('inf')) + start = 0 + for end, ch in enumerate(s): + if needstr[ch] > 0: + needcnt -= 1 + needstr[ch] -= 1 + if needcnt == 0: + while True: + tmp = s[start] + if needstr[tmp] == 0: + break + needstr[tmp] += 1 + start += 1 + if end - start < res[1] - res[0]: + res = (start, end) + needstr[s[start]] += 1 + needcnt += 1 + start += 1 + return '' if res[1] > len(s) else s[res[0]:res[1]+1] +``` + +### Complexity Analysis + +- **Time complexity**: $O(M+N)$ +- **Space complexity**: $O(N)$ + +### Conclusion + +The C++ and Python approaches for finding the minimum window substring are quite similar in their methodology. Both utilize the two-pointer technique, also known as the sliding window approach, to efficiently traverse the string s and dynamically adjust the window to find the smallest valid substring containing all characters of the string t. They maintain a character count map to keep track of the required characters from t and adjust the counts as the window expands and contracts. Additionally, both solutions use a counter variable to monitor the number of characters still needed to form a valid window. diff --git a/solutions/lc-solutions/0000-0099/0077-combinations.md b/solutions/lc-solutions/0000-0099/0077-combinations.md new file mode 100644 index 0000000..05693f6 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0077-combinations.md @@ -0,0 +1,134 @@ +--- +id: combinations +title: Combinations(LeetCode) +sidebar_label: 0077-Combinations +tags: + - Backtracking +description: Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. +--- + +## Problem Statement + +Given two integers `n` and `k`, return all possible combinations of `k` numbers chosen from the range `[1, n]`. + +You may return the answer in any order. + +### Examples + +**Example 1:** + +```plaintext +Input: n = 4, k = 2 +Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] +Explanation: There are 4 choose 2 = 6 total combinations. +Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination. +``` + +**Example 2:** + +```plaintext +Input: n = 1, k = 1 +Output: [[1]] +Explanation: There is 1 choose 1 = 1 total combination. +``` + +### Constraints + +- `1 <= n <= 20` + `1 <= k <= n` + +## Solution + +### Approach 1: Minimum Window Substring (Java Implementation) + +#### Algorithm + +1. Initialization: +* Create a frequency map for characters in string `t`. +* Initialize counters and pointers: `counter` (number of characters still needed from `t`), `begin` (start pointer), `end` (end pointer), `d` (length of the minimum window), and `head` (starting index of the minimum window). +2. Expand the Window: +* Traverse through string `s` with the `end` pointer. +* If the current character is needed (frequency in `map` is greater than 0), decrement `counter`. +* Decrease the frequency of the current character in the map. +3. Contract the Window: +* When `counter` is 0 (all characters from `t` are found in the window): + * Check if the current window is smaller than the previously found minimum window (`d`). + * Move the `begin` pointer to find a smaller valid window. + * If the character at `begin` is in `t`, increment its frequency in the map and increment `counter` if the frequency becomes positive. +4. Return Result: +* Return the minimum window substring. + +#### Implementation + +```Java +def backtrack(candidate): + if find_solution(candidate): + output(candidate) + return + + # iterate all possible candidates + for next_candidate in list_of_candidates: + if is_valid(next_candidate): + # try this partial candidate solution + place(next_candidate) + # explore further with the given candidate + backtrack(next_candidate) + # backtrack + remove(next_candidate) +``` + +### Complexity Analysis + +- **Time complexity**: $O(N)$ +- **Space complexity**: $O(1)$ + +### Approach 2: Python Implementation + +#### Algorithm + +1. Initialization: +* Create a frequency map for characters in string `t`. +* Initialize counters and pointers: `needcnt` (number of characters still needed from `t`), `res` (tuple to store the start and end indices of the minimum window), and `start` (start pointer). +2. Expand the Window: +* Traverse through string `s` with the `end` pointer. +* If the current character is needed (frequency in `needstr` is greater than 0), decrement `needcnt`. +* Decrease the frequency of the current character in the map. +3. Contract the Window: +* When `needcnt` is 0 (all characters from `t` are found in the window): + * Move the `start` pointer to find a smaller valid window. + * If the character at `start` is in `t`, increment its frequency in the map and increment `needcnt` if the frequency becomes positive. + * Update the `res` tuple if a smaller valid window is found. +4. Return Result: +* Return the minimum window substring using the indices stored in res. + +#### Implementation + +```Python +def combine(self, n, k): + sol=[] + def backtrack(remain,comb,nex): + # solution found + if remain==0: + sol.append(comb.copy()) + else: + # iterate through all possible candidates + for i in range(nex,n+1): + # add candidate + comb.append(i) + #backtrack + backtrack(remain-1,comb,i+1) + # remove candidate + comb.pop() + + backtrack(k,[],1) + return sol +``` + +### Complexity Analysis + +- **Time complexity**: $O(N)$ +- **Space complexity**: $O(1)$ + +### Conclusion + +Both approaches for finding the minimum window substring are efficient, operating with a time complexity of O(n) and a space complexity of O(1). The Java and Python implementations utilize similar sliding window techniques, adjusting the window size dynamically to find the smallest substring containing all characters of t. The primary difference lies in language-specific syntax and data structures, but the underlying algorithm remains consistent. diff --git a/solutions/lc-solutions/0000-0099/0078-Subsets.md b/solutions/lc-solutions/0000-0099/0078-Subsets.md new file mode 100644 index 0000000..c2635af --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0078-Subsets.md @@ -0,0 +1,587 @@ +--- +id: subsets +title: Subsets Solution +sidebar_label: 0078 - Subsets +tags: + - Subsets + - Bit Manipulation + - Backtracking + - Array + - LeetCode + - JavaScript + - TypeScript +description: "This is a solution to the Subsets problem on LeetCode." +--- + +In this page, we will solve the Subsets problem using three different approaches: brute force, hash table, and two-pointer technique. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +Given an integer array `nums` of unique elements, return all possible subsets (the power set). + +The solution set must not contain duplicate subsets. Return the solution in any order. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [1,2,3] +Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] +``` + +**Example 2:** + +```plaintext +Input: nums = [0] +Output: [[],[0]] +``` + +### Constraints + +- `1 <= nums.length <= 10` +- `-10 <= nums[i] <= 10` +- All the numbers of `nums` are unique. + +--- + +## Solution for Subsets Problem + +### Intuition and Approach + +The Subsets problem asks us to generate all possible subsets of a given set of unique integers. This involves considering every possible combination of elements, including the empty set and the set itself. The total number of subsets for a set with 𝑛 elements is $$2^n$$. + + + + +### Approach 1: Brute Force (Naive) + + The brute force approach to solve the Subsets problem involves generating all possible combinations of the elements in the input array. This can be done by iterating through every possible subset size, from 0 to the size of the array, and using combinations to generate the subsets of each size. + +#### Implementation + +```jsx live +function SubsetsGenerator() { + const nums = [1, 2, 3]; + + const generateSubsets = (nums) => { + const result = [[]]; + for (let i = 0; i < nums.length; i++) { + const len = result.length; + for (let j = 0; j < len; j++) { + result.push([...result[j], nums[i]]); + } + } + return result; + }; + + const result = generateSubsets(nums); + + return ( +
+

+ Input: nums = [{nums.join(", ")}] +

+

+ Output: [ + {result.map((subset, index) => ( + + [{subset.join(", ")}] + {index < result.length - 1 ? ', ' : ''} + + ))} + ] +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + var subsets = function(nums) { + let result = [[]]; + for (let i = 0; i < nums.length; i++) { + const len = result.length; + for (let j = 0; j < len; j++) { + result.push([...result[j], nums[i]]); + } + } + return result; +}; + ``` + + + + + ```typescript + function subsets(nums: number[]): number[][] { + let result: number[][] = [[]]; + for (let i = 0; i < nums.length; i++) { + const len = result.length; + for (let j = 0; j < len; j++) { + result.push([...result[j], nums[i]]); + } + } + return result; +} + ``` + + + + + ```python + class Solution: + def subsets(nums): + result = [[]] + for num in nums: + for subset in result[:]: + result.append(subset + [num]) + return result + ``` + + + + + ```java + class Solution { + public List> subsets(int[] nums) { + List> result = new ArrayList<>(); + result.add(new ArrayList<>()); + for (int num : nums) { + int size = result.size(); + for (int i = 0; i < size; i++) { + List subset = new ArrayList<>(result.get(i)); + subset.add(num); + result.add(subset); + } + } + return result; + } + } + ``` + + + + + ```cpp + class Solution { + public: + vector> subsets(vector& nums) { + vector> result = {{}}; + for (int num : nums) { + int size = result.size(); + for (int i = 0; i < size; i++) { + vector subset = result[i]; + subset.push_back(num); + result.push_back(subset); + } + } + return result; + } +}; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n^2)$$ +- Space Complexity: $$O(1)$$ +- Where `n` is the length of the input array `nums`. +- The time complexity is $$O(n^2)$$ because we are iterating through the array twice. +- The space complexity is $$O(1)$$ because we are not using any extra space. +- This approach is not efficient and is not recommended for large inputs. + +
+ + +### Approach 2: Using Bit Manipulation + +To generate all subsets of a given array `nums` using bit manipulation, follow this approach: + +Calculate the total number of subsets as $$2^n$$, where `n` is the length of the array. Iterate through all numbers from $$0$$ to $$2^n -1$$, each representing a unique subset. For each number, use bit manipulation to determine which elements are included in the subset by checking each bit position. If a bit is set, include the corresponding element from `nums` in the subset. Construct the subset and add it to the list of all subsets. This efficiently generates all possible subsets by leveraging the binary representation of numbers. + +#### Implementation + +```jsx live +function subsets() { + const SubsetsGenerator = () => { + const [nums, setNums] = useState([1, 2, 3]); + const [subsets, setSubsets] = useState([]); + + const generateSubsets = (nums) => { + const n = nums.length; + const result = []; + for (let i = 0; i < (1 << n); i++) { + const subset = []; + for (let j = 0; j < n; j++) { + if (i & (1 << j)) { + subset.push(nums[j]); + } + } + result.push(subset); + } + return result; + }; + + const result = generateSubsets(nums); + + return ( +
+

+ Input: nums = [{nums.join(", ")}] +

+

+ Output: [ + {result.map((subset, index) => ( + + [{subset.join(", ")}] + {index < result.length - 1 ? ', ' : ''} + + ))} + ] +

+
+ ); + } + + return ( +
+ +
+ ); +} + + +``` + +#### Code in Different Languages + + + + + ```javascript + var subsets = function(nums) { + const n = nums.length; + const result = []; + for (let i = 0; i < (1 << n); i++) { + const subset = []; + for (let j = 0; j < n; j++) { + if (i & (1 << j)) { + subset.push(nums[j]); + } + } + result.push(subset); + } + return result; +}; + ``` + + + + + ```typescript + function subsets(nums: number[]): number[][] { + const n = nums.length; + const result: number[][] = []; + + for (let i = 0; i < (1 << n); i++) { + const subset: number[] = []; + for (let j = 0; j < n; j++) { + if (i & (1 << j)) { + subset.push(nums[j]); + } + } + result.push(subset); + } + +return result; +} + ``` + + + + + ```python + class Solution(object): + def subsets(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + n = len(nums) + result = [] + + for i in range(1 << n): # 1 << n is 2^n + subset = [] + for j in range(n): + if i & (1 << j): + subset.append(nums[j]) + result.append(subset) + + return result + ``` + + + + + ```java + class Solution { + public List> subsets(int[] nums) { + int n = nums.length; + List> result = new ArrayList<>(); + + for (int i = 0; i < (1 << n); i++) { + List subset = new ArrayList<>(); + for (int j = 0; j < n; j++) { + if ((i & (1 << j)) != 0) { + subset.add(nums[j]); + } + } + result.add(subset); + } + + return result; + } + } + ``` + + + + + ```cpp + class Solution { + public: + std::vector> subsets(std::vector& nums) { + int n = nums.size(); + std::vector> result; + + for (int i = 0; i < (1 << n); i++) { + std::vector subset; + for (int j = 0; j < n; j++) { + if (i & (1 << j)) { + subset.push_back(nums[j]); + } + } + result.push_back(subset); + } + + return result; + } +}; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n.2^n)$$ +- Space Complexity: $$O(n.2^n)$$ +- Where `n` is the length of the input array `nums`. +- The time complexity is $$O(n.2^n)$$ because we generate all possible subsets, and for each subset, we iterate through the array of length `n`. +- The space complexity is $$O(n.2^n)$$ because we store all the generated subsets, and the average size of each subset is `n/2`. +- This approach is more efficient than naive recursive or iterative approaches and is recommended for generating all subsets efficiently. +- Bit manipulation provides a fast method to generate subsets, with each subset being generated in linear time +- The total time complexity is $$O(n.2^n)$$. and the total space complexity is $$O(n.2^n)$$. + +
+ + +### Approach 3: Using Backtracking + +We employ backtracking to systematically explore all combinations of elements in the array `nums` of size `n`,starting with an empty subset and recursively including or excluding each element until all possibilities are explored, resulting in a collection of subsets. + +#### Implementation + +```jsx live +function SubsetsGenerator() { + const [nums, setNums] = useState([1, 2, 3]); + const [subsets, setSubsets] = useState([]); + + useEffect(() => { + generateSubsets(nums); + }, []); + + const generateSubsets = (nums) => { + const result = []; + + const backtrack = (subset, index) => { + result.push(subset.slice()); + for (let i = index; i < nums.length; i++) { + subset.push(nums[i]); + backtrack(subset, i + 1); + subset.pop(); + } + }; + + backtrack([], 0); + setSubsets(result); + }; + + return ( +
+

Input: nums = [{nums.join(", ")}]

+

Output:

+
+ {[subsets.map((subset, index) => ( + + [{subset.join(', ')}] {index < subsets.length - 1 ? ', ' : ''} + + ))]} +
+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + var subsets = function(nums) { + const result = []; + + const backtrack = (subset, index) => { + result.push(subset.slice()); + for (let i = index; i < nums.length; i++) { + subset.push(nums[i]); + backtrack(subset, i + 1); + subset.pop(); + } + }; + + backtrack([], 0); + return result; + +}; + ``` + + + + + + ```ts + function subsets(nums: number[]): number[][] { + const result: number[][] = []; + + const backtrack = (subset: number[], index: number): void => { + result.push(subset.slice()); + for (let i = index; i < nums.length; i++) { + subset.push(nums[i]); + backtrack(subset, i + 1); + subset.pop(); + } + }; + + backtrack([], 0); + return result; +}; + ``` + + + + + ```py + class Solution(object): + def subsets(self, nums): + result = [] + + def backtrack(subset, index): + result.append(subset[:]) + for i in range(index, len(nums)): + subset.append(nums[i]) + backtrack(subset, i + 1) + subset.pop() + + backtrack([], 0) + return result + ``` + + + + + ```java + class Solution { + public List> subsets(int[] nums) { + List> result = new ArrayList<>(); + + backtrack(result, new ArrayList<>(), nums, 0); + + return result; + } + + private void backtrack(List> result, List subset, int[] nums, int index) { + result.add(new ArrayList<>(subset)); + for (int i = index; i < nums.length; i++) { + subset.add(nums[i]); + backtrack(result, subset, nums, i + 1); + subset.remove(subset.size() - 1); + } + } +} + ``` + + + + + + ```cpp + class Solution { + public: + vector> subsets(vector& nums) { + vector> result; + vector subset; + backtrack(nums, result, subset, 0); + return result; + } + + private: + void backtrack(vector& nums, vector>& result, vector& subset, int index) { + result.push_back(subset); + for (int i = index; i < nums.size(); ++i) { + subset.push_back(nums[i]); + backtrack(nums, result, subset, i + 1); + subset.pop_back(); + } + } +}; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n.2^n)$$ +- Space Complexity: $$O(n.2^n)$$ +- Where `n` is the length of the input array `nums`. +- The time complexity is $$O(n.2^n)$$ because we explore all possible combinations of elements to generate subsets. At each step of the recursion, we either include or exclude an element, resulting in a binary tree of height `n`. The number of nodes in this tree is `2^n`, and at each node, we perform a linear operation to copy the current subset, resulting in a total time complexity of $$O(n.2^n)$$. +- The space complexity is $$O(n.2^n)$$ because we store all generated subsets. In the worst case, we have `2^n` subsets, each with an average size of `n`. +- This approach efficiently generates all subsets without the need for sorting, making it suitable for various input sizes. +- The total time complexity is $$O(n.2^n)$$. and the total space complexity is $$O(n.2^n)$$. + +
+
+ +:::tip Note +**Which is the best approach? and why?** + +In general, for small to medium-sized input sets (say, up to 30 or 40 elements), bit manipulation can be more efficient and concise. However, for larger input sets or when you have additional constraints or filtering conditions, backtracking may be a better choice due to its memory efficiency and flexibility. +Ultimately, the decision between bit manipulation and backtracking depends on the specific requirements of your problem, the size of the input set, and any additional constraints or conditions that need to be considered. + +::: + +## References + +- **LeetCode Problem:** [Subsets Problem](https://leetcode.com/problems/subsets/) +- **Solution Link:** [Subsets Solution on LeetCode](https://leetcode.com/problems/subsets/submissions/1147007689/) +- **Authors LeetCode Profile:** [Ajay Dhangar](https://leetcode.com/ajaydhangar49/) \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0079-word-search.md b/solutions/lc-solutions/0000-0099/0079-word-search.md new file mode 100644 index 0000000..e5f48a8 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0079-word-search.md @@ -0,0 +1,118 @@ +--- +id: word-search +title: Word Search(LeetCode) +sidebar_label: 0079-Word Search +tags: + - Array + - String + - Backtracking + - Matrix +description: Given an m x n grid of characters board and a string word, return true if word exists in the grid. +--- + +## Problem Statement + +Given an `m x n` grid of characters `board` and a string `word`, return `true` if `word` exists in the grid. + +The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. + +### Examples + +**Example 1:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/dc23f6be-e216-4ad1-89bc-178cf3039262) + +```plaintext +Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" +Output: true +``` + +**Example 2:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/c3905a94-2a40-4dee-a4bf-42b77ba2b91a) + +```plaintext +Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" +Output: true +``` + +**Example 3:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/c56f9ea3-8247-484b-943a-0c38ea32465c) + +```plaintext +Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" +Output: false +``` + +### Constraints + +- `m == board.length` +- `n = board[i].length` +- `1 <= m, n <= 6` +- `1 <= word.length <= 15` +- `board` and `word` consists of only lowercase and uppercase English letters. + +## Solution + +### Approach + +#### Algorithm + +1. Initialization: +* Convert the input word to a character array `w`. +* Iterate through each cell in the board using nested loops. +2. Recursive Search: +* For each cell in the board, call the recursive function `exist`. +* The recursive function `exist` takes parameters: the board, current cell coordinates `(y, x)`, the word array, and the current index `i` in the word array. +* Base cases: + * If `i` equals the length of the word, return `true` (all characters are matched). + * If the current cell `(y, x)` is out of bounds or does not match the current character in the word array, return `false`. +* Mark the current cell as visited by toggling the 8th bit using `board[y][x] ^= 256`. +* Recursively check all four possible directions (right, left, down, up) from the current cell. +* After the recursive calls, unmark the current cell by toggling the 8th bit again using `board[y][x] ^= 256`. +* Return `true` if any of the recursive calls return `true`, indicating that the word exists in the board starting from the current cell. +3. Return Result: +* Return `true` if the word is found starting from any cell, otherwise return `false`. + +#### Implementation + +```Java +public boolean exist(char[][] board, String word) { + char[] w = word.toCharArray(); + for (int y=0; y& nums) { + int j = 1; + for (int i = 1; i < nums.size(); i++) { + if (j == 1 || nums[i] != nums[j - 2]) { + nums[j++] = nums[i]; + } + } + return j; + } +}; +``` + +Python: + +```Python +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + j = 1 + for i in range(1, len(nums)): + if j == 1 or nums[i] != nums[j - 2]: + nums[j] = nums[i] + j += 1 + return j +``` + +Rust: + +```Rust +impl Solution { + pub fn remove_duplicates(nums: &mut Vec) -> i32 { + let mut j = 1; + for i in 1..nums.len() { + if j == 1 || nums[i] != nums[j - 2] { + nums[j] = nums[i]; + j += 1; + } + } + j as i32 + } +} +``` +### Complexity Analysis + +- **Time complexity**: $O(N)$ +- **Space complexity**: $O(1)$ + +### Conclusion + +The two-pointer approach effectively removes duplicates from a sorted array in-place such that each element appears at most twice. By maintaining two pointers, i for iteration and j for tracking the position in the modified array, the algorithm efficiently achieves the desired result with a single pass through the array. The time complexity is O(n), and the space complexity is O(1), making this solution both time and space efficient. diff --git a/solutions/lc-solutions/0000-0099/0081-search-in-rotated-sorted-array-II.md b/solutions/lc-solutions/0000-0099/0081-search-in-rotated-sorted-array-II.md new file mode 100644 index 0000000..cf2a67b --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0081-search-in-rotated-sorted-array-II.md @@ -0,0 +1,106 @@ +--- +id: search-in-rotated-sorted-array-II +title: Search in Rotated Sorted Array II(LeetCode) +sidebar_label: 0081-Search in Rotated Sorted Array II +tags: + - Array + - Binary Search +description: Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums. +--- + +## Problem Statement + +There is an integer array `nums` sorted in non-decreasing order (not necessarily with distinct values). + +Before being passed to your function, `nums` is rotated at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (0-indexed). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index 5 and become `[4,5,6,6,7,0,1,2,4,4]`. + +Given the array `nums` after the rotation and an integer `target`, return `true` if `target` is in `nums`, or `false` if it is not in `nums`. + +You must decrease the overall operation steps as much as possible. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [2,5,6,0,0,1,2], target = 0 +Output: true +``` + +**Example 2:** + +```plaintext +Input: nums = [2,5,6,0,0,1,2], target = 3 +Output: false +``` + +### Constraints + +- `1 <= nums.length <= 5000` + `-104 <= nums[i] <= 104` +- `nums` is guaranteed to be rotated at some pivot. +- `-104 <= target <= 104` + +## Solution + +### Approach + +#### Algorithm + +1. Initialization: +* Initialize `left` to 0 and `right` to `nums.size() - 1`. +2. Binary Search Loop: +* While `left` is less than or equal to `right`: + * Compute `mid` as `(left + right) >> 1`. + * If `nums[mid]` equals the target, return true. + * Handle Duplicates: If `nums[left]`, `nums[mid]`, and `nums[right]` are the same, increment `left` and decrement `right`. + * Check Sorted Halves: + * If the left half (`nums[left]` to `nums[mid]`) is sorted: + * If the target is within the range of the left half, adjust `right` to `mid - 1`. + * Otherwise, adjust `left` to `mid + 1`. + * Otherwise, the right half (`nums[mid]` to `nums[right]`) must be sorted: + * If the target is within the range of the right half, adjust `left` to `mid + 1`. + * Otherwise, adjust `right` to `mid - 1`. +3. Final Check: +* If the loop exits without finding the target, return `false`. + +#### Implementation + +```C++ +class Solution { +public: + bool search(vector& nums, int target) { + int left = 0, right = nums.size()-1, mid; + + while(left<=right) + { + mid = (left + right) >> 1; + if(nums[mid] == target) return true; + + // the only difference from the first one, trickly case, just updat left and right + if( (nums[left] == nums[mid]) && (nums[right] == nums[mid]) ) {++left; --right;} + + else if(nums[left] <= nums[mid]) + { + if( (nums[left]<=target) && (nums[mid] > target) ) right = mid-1; + else left = mid + 1; + } + else + { + if((nums[mid] < target) && (nums[right] >= target) ) left = mid+1; + else right = mid-1; + } + } + return false; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: $O(N)$ +- **Space complexity**: $O(1)$ + +### Conclusion + +The solution uses a modified binary search to efficiently search for a target value in a rotated sorted array with duplicates. The key steps involve adjusting the search range based on whether the left or right half of the array is sorted, and handling duplicates by narrowing the search range when necessary. The time complexity can degrade to O(n) in the worst case due to duplicates, but the space complexity remains O(1). This approach balances efficiency with the complexity of handling rotated and duplicated elements in the array. diff --git a/solutions/lc-solutions/0000-0099/0082-remove-duplicates-from-sorted-list-2.md b/solutions/lc-solutions/0000-0099/0082-remove-duplicates-from-sorted-list-2.md new file mode 100644 index 0000000..09f6872 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0082-remove-duplicates-from-sorted-list-2.md @@ -0,0 +1,188 @@ +--- +id: 82-remove-duplicates-from-sorted-list-2 +title: Remove Duplicates from Sorted List II (Leetcode) +sidebar_label: 0082-RemoveDuplicatesFromSortedListII +description: Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. +sidebar_position: 82 +--- + +## Problem Description + +Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. + +### Examples + +#### Example 1 + +- **Input:** $head = [1,2,3,3,4,4,5]$ +- **Output:** $[1,2,5]$ + + +#### Example 2 + +- **Input:** $head = [1,1,1,2,3]$ +- **Output:** $[2,3]$ + + + +### Constraints + +- The number of nodes in the list is in the range [0, 300]. +- $-100 <= Node.val <= 100$ +- The list is guaranteed to be sorted in ascending order. + + +### Intuition + + +The goal is to remove all elements from a sorted linked list that have duplicate values, ensuring that each element appears only once. We use a dummy node to simplify handling edge cases and traverse the list, removing duplicates as we encounter them. + + +### Approach + +1. **Initialization:** + + - Create a dummy node to handle edge cases where the head itself might be a duplicate. + - Initialize two pointers, prev (starting at dummy) and curr (starting at head). + +2. **Traversal and Duplicate Removal:** + + - Traverse the linked list using the curr pointer. + - For each node, check if the current value matches the next node's value. + - If duplicates are detected, use a loop to skip all nodes with that value, deleting them. + - Update the prev pointer's next to point to the first non-duplicate node after the series of duplicates. + - If no duplicates are found, move both prev and curr pointers forward. + +3. **Completion:** + + - After the loop, update the head to point to the node after the dummy. + - Delete the dummy node to free memory. + Return the updated head of the linked list. + +### Solution Code + +#### Python + +```py +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + if not head or not head.next: + return head + + dummy = ListNode(0) # Dummy node to handle the case when head is a duplicate + dummy.next = head + + prev = dummy + curr = head + + while curr and curr.next: + if prev.next.val == curr.next.val: + val = curr.next.val + while curr and curr.val == val: + temp = curr + curr = curr.next + del temp # Marking the node for garbage collection + prev.next = curr + else: + prev = prev.next + curr = curr.next + + head = dummy.next # Update head in case it has changed + del dummy # Marking the dummy node for garbage collection + return head +``` + +#### Java + +```java +class ListNode { + int val; + ListNode next; + ListNode() {} + ListNode(int val) { this.val = val; } + ListNode(int val, ListNode next) { this.val = val; this.next = next; } +} + +class Solution { + public ListNode deleteDuplicates(ListNode head) { + if (head == null || head.next == null) { + return head; + } + + ListNode dummy = new ListNode(0); // Dummy node to handle the case when head is a duplicate + dummy.next = head; + + ListNode prev = dummy; + ListNode curr = head; + + while (curr != null && curr.next != null) { + if (prev.next.val == curr.next.val) { + int val = curr.next.val; + while (curr != null && curr.val == val) { + ListNode temp = curr; + curr = curr.next; + temp = null; // Marking the node for garbage collection + } + prev.next = curr; + } else { + prev = prev.next; + curr = curr.next; + } + } + + head = dummy.next; // Update head in case it has changed + dummy = null; // Marking the dummy node for garbage collection + return head; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + if (head == nullptr || head->next == nullptr) { + return head; + } + + ListNode* dummy = new ListNode(0); // Dummy node to handle the case when head is a duplicate + dummy->next = head; + + ListNode* prev = dummy; + ListNode* curr = head; + + while (curr != nullptr && curr->next != nullptr) + { + if (prev->next->val == curr->next->val) + { + int val = curr->next->val; + while (curr != nullptr && curr->val == val) + { + ListNode* temp = curr; + curr = curr->next; + delete temp; + } + prev->next = curr; + } else { + prev = prev->next; + curr = curr->next; + } + } + + head = dummy->next; // Update head in case it has changed + delete dummy; // Delete the dummy node + return head; + } +}; +``` + +### Conclusion + +The provided code effectively removes duplicates from a sorted linked list by iterating through the list and adjusting the pointers accordingly to skip duplicate nodes. It uses a dummy node to handle cases where the head itself is a duplicate and performs the deletion in place without modifying the values within the nodes. The solution has a time complexity of $O(n)$, where n is the number of nodes in the linked list, due to the linear traversal required to identify and remove duplicates. The space complexity is $O(1)$ since the algorithm operates in constant space, only using a few pointers and temporary variables regardless of the input size. Overall, this solution offers an efficient and straightforward approach to handling duplicate removal in a sorted linked list. diff --git a/solutions/lc-solutions/0000-0099/0083-remove-duplicates-from-sorted-list.md b/solutions/lc-solutions/0000-0099/0083-remove-duplicates-from-sorted-list.md new file mode 100644 index 0000000..ce0022b --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0083-remove-duplicates-from-sorted-list.md @@ -0,0 +1,121 @@ +--- +id: remove-duplicates-from-sorted-list +title: Remove Duplicates from Sorted List Solution +sidebar_label: 0083 Remove Duplicates from Sorted List +tags: + - Linked List + - Two Pointers + - LeetCode + - Python + - Java + - C++ +description: "This is a solution to the Remove Duplicates from Sorted List problem on LeetCode." +--- + +## Problem Description + +Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. + +### Examples + +**Example 1:** +``` +Input: head = [1,1,2] +Output: [1,2] +``` + +**Example 2:** + +``` +Input: head = [1,1,2,3,3] +Output: [1,2,3] +``` + +### Approach for Removing Duplicates from Sorted List + +**Intuition:** +The problem requires removing duplicates from a sorted singly-linked list. The approach involves iterating through the list and removing duplicates while maintaining the sorted order. + +**Approach:** +- Initialize a pointer `current` to the head of the linked list to traverse the list. +- Start a `while` loop that continues until `current` reaches the end of the list or `current.next` reaches null. +- Inside the loop, compare the value of the current node `current.val` with the value of the next node `current.next.val`. +- If the values are equal, it indicates a duplicate node. In this case, update the next pointer of the current node `current.next` to skip the next node (remove the duplicate). +- If the values are not equal, move the `current` pointer to the next node, continuing the traversal. +- Repeat the loop until the end of the list is reached, ensuring that all duplicates are removed while maintaining the sorted order of the remaining nodes. +- After the loop, return the modified linked list, which contains no duplicates. + + +### Code in Different Languages + +#### Java (code): + +```java +class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode current = head; + + while (current != null && current.next != null) { + if (current.val == current.next.val) { + current.next = current.next.next; + } else { + current = current.next; + } + } + + return head; + } +} +``` + +#### Python (code) + +```python +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + current = head + + while current and current.next: + if current.val == current.next.val: + current.next = current.next.next + else: + current = current.next + + return head +``` + +#### CPP (code) ; + +```cpp +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode* current = head; + + while (current && current->next) { + if (current->val == current->next->val) { + current->next = current->next->next; + } else { + current = current->next; + } + } + + return head; + } +}; +``` + +#### Complexity Analysis + +- **Time Complexity:** O(n) + + - The algorithm iterates through the linked list once, where n is the number of nodes in the list. Each node is examined once to identify and remove duplicates. + +- **Space Complexity:** O(1) + - The algorithm uses a constant amount of additional memory space for variables, regardless of the size of the input linked list, making its space complexity constant. + +## References + +- **LeetCode Problem**: [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/balanced-binary-tree/solution/) +- **Authors GeeksforGeeks Profile:** [Vipul lakum](https://leetcode.com/u/vipul_lakum_02/) \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0084-largest-rectangle-in-histogram.md b/solutions/lc-solutions/0000-0099/0084-largest-rectangle-in-histogram.md new file mode 100644 index 0000000..7ad78f9 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0084-largest-rectangle-in-histogram.md @@ -0,0 +1,251 @@ +--- +id: largest-rectangle-in-histogram +title: Largest Rectangle in Histogram (Leetcode) +sidebar_label: 0084-Largest Rectangle In Histogram +description: Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Largest Rectangle in Histogram ](https://leetcode.com/problems/largest-rectangle-in-histogram/description/) | [Largest Rectangle in Histogram Solution on LeetCode](https://leetcode.com/problems/largest-rectangle-in-histogram/solutions) | [Aaradhya Singh ](https://leetcode.com/u/keira_09/) | + + +## Problem Description + +Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. + +### Examples + +#### Example 1 + +- **Input:** $heights = [2,1,5,6,2,3]$ +- **Output:** $10$ +- **Explanation:** The above is a histogram where width of each bar is 1. +The largest rectangle is shown in the red area, which has an $area = 10$ units. + + +#### Example 2 + +- **Input:** $heights = [2,4]$ +- **Output:** $4$ + +### Constraints + + +- $1 <= heights.length <= 105$ +- $0 <= heights[i] <= 104$ + + +### Intuition + + +The code uses stacks to find the next smaller and previous smaller elements for each height in a histogram. It then computes the area of the largest rectangle that can be formed using each height as the base, considering the width as the difference between the indices of the next smaller and previous smaller elements. The maximum area among all rectangles is returned as the result, representing the largest rectangle area in the histogram. + + +### Approach + +1. **Next Smaller Element Calculation:** + + - Use a stack to find the indices of the next smaller elements for each height in the histogram, iterating from right to left. + +2. **Previous Smaller Element Calculation:** + + - Similarly, use a stack to find the indices of the previous smaller elements for each height, iterating from left to right. + +3. **Largest Rectangle Area Calculation:** + + - Calculate the largest rectangle area in the histogram using the indices of next and previous smaller elements obtained from the previous steps. + - Determine the width of each rectangle as the difference between these indices. + - Compute the area for each rectangle and track the maximum area found. + +### Solution Code + +#### Python + +```py +class Solution: + def next_smaller_element(self, arr, n): + ans = [-1] * n + stack = [-1] + + for i in range(n - 1, -1, -1): + curr = arr[i] + while stack[-1] != -1 and arr[stack[-1]] >= curr: + stack.pop() + ans[i] = stack[-1] + stack.append(i) + return ans + + def prev_smaller_element(self, arr, n): + ans = [-1] * n + stack = [-1] + + for i in range(n): + curr = arr[i] + while stack[-1] != -1 and arr[stack[-1]] >= curr: + stack.pop() + ans[i] = stack[-1] + stack.append(i) + return ans + + def largestRectangleArea(self, heights): + n = len(heights) + + next_smaller = self.next_smaller_element(heights, n) + prev_smaller = self.prev_smaller_element(heights, n) + + area = float("-inf") + + for i in range(n): + l = heights[i] + if next_smaller[i] == -1: + next_smaller[i] = n + b = next_smaller[i] - prev_smaller[i] - 1 + new_area = l * b + area = max(area, new_area) + + return area +``` + +#### Java + +```java + +import java.util.*; + +class Solution { + private int[] nextSmallerElement(int[] arr, int n) { + int[] ans = new int[n]; + Stack stack = new Stack<>(); + stack.push(-1); + + for (int i = n - 1; i >= 0; i--) { + int curr = arr[i]; + while (stack.peek() != -1 && arr[stack.peek()] >= curr) { + stack.pop(); + } + ans[i] = stack.peek(); + stack.push(i); + } + return ans; + } + + private int[] prevSmallerElement(int[] arr, int n) { + int[] ans = new int[n]; + Stack stack = new Stack<>(); + stack.push(-1); + + for (int i = 0; i < n; i++) { + int curr = arr[i]; + while (stack.peek() != -1 && arr[stack.peek()] >= curr) { + stack.pop(); + } + ans[i] = stack.peek(); + stack.push(i); + } + return ans; + } + + public int largestRectangleArea(int[] heights) { + int n = heights.length; + + int[] next = nextSmallerElement(heights, n); + int[] prev = prevSmallerElement(heights, n); + + int area = Integer.MIN_VALUE; + + for (int i = 0; i < n; i++) { + int l = heights[i]; + if (next[i] == -1) { + next[i] = n; + } + int b = next[i] - prev[i] - 1; + int newArea = l * b; + area = Math.max(area, newArea); + } + + return area; + } +} +``` + +#### C++ + +```cpp +#include + +#include +#include +#include // for max function +#include // for INT_MIN + +class Solution { +private: + vector next_smaller_element(vector arr, int n) { + vector ans(n); + stack s; + s.push(-1); + + for (int i = n - 1; i >= 0; i--) + { + int curr = arr[i] ; + while (s.top() != -1 && arr[s.top()] >= curr) + { + s.pop(); + } + ans[i] = s.top(); + s.push(i); + } + return ans; + } + + vector prev_smaller_element(vector arr, int n) { + vector ans(n); + stack s; + s.push(-1); + + for (int i = 0; i < n; i++) + { + int curr = arr[i]; + while (s.top() != -1 && arr[s.top()] >= curr) + { + s.pop(); + } + ans[i] = s.top(); + s.push(i); + } + return ans; + } + +public: + int largestRectangleArea(vector& heights) { + int n = heights.size(); + + vector next(n); + next = next_smaller_element(heights, n); + + vector prev(n); + prev = prev_smaller_element(heights, n); + + int area = INT_MIN; + + for (int i = 0; i < n; i++) { + int l = heights[i]; + if (next[i] == -1) + { + next[i] = n; + } + int b = next[i] - prev[i] - 1; + int newarea = l * b; + area = max(area, newarea); + } + return area; + } +}; +``` + +### Conclusion + +The provided code efficiently calculates the largest rectangle area in a histogram using stack-based techniques. It implements functions to find the next smaller and previous smaller elements for each height in the histogram, which are crucial for computing the area of the largest rectangle. The code has a time complexity of $O(n)$ and a space complexity of $O(n)$, where n is the number of elements in the input array representing the histogram. Overall, this code offers an effective approach to solving the largest rectangle area problem in a histogram.removal in a sorted linked list. diff --git a/solutions/lc-solutions/0000-0099/0085-Maximal-Rectangle.md b/solutions/lc-solutions/0000-0099/0085-Maximal-Rectangle.md new file mode 100644 index 0000000..3935f35 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0085-Maximal-Rectangle.md @@ -0,0 +1,270 @@ +--- +id: Maximal-Rectangle +title: Maximal Rectangle +sidebar_label: 085-Maximal Rectangle +tags: + - algorithms + - dynamic programming + - stack + - matrix + - binary matrix + - rectangle +description: This gives the solution for maximal Rectangle problem of leetcode +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Maximal-Rectangle](https://leetcode.com/problems/Maximal-Rectangle/description/) | [Maximal-Rectangle Solution on LeetCode](https://leetcode.com/problems/Maximal-Rectangle/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +### Problem Description + +Given a `rows x cols` binary matrix filled with `0's` and `1's`, find the largest rectangle containing only `1's` and return its area. + +### Examples + +#### Example 1: +**Input:** `matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]` +**Output:** `6` +**Explanation:** `The maximal rectangle is shown in the above picture.` + +#### Example 2: +**Input:** `matrix = [["0"]]` +**Output:** `0` + + +#### Example 3: +**Input:** `matrix = [["1"]]` +**Output:** `1` + + +### Constraints + +- `rows == matrix.length` +- `cols == matrix[i].length` +- `1 <= rows, cols <= 200` +- `matrix[i][j]` is `'0'` or `'1'`. + +## Approach + +1. **Transform the Matrix into Histograms**: For each row in the matrix, treat each column as the height of a histogram bar. +2. **Use Histogram Technique**: Apply the largest rectangle in histogram technique for each row. +3. **Dynamic Update**: Update the heights of the histogram bars dynamically while iterating over rows. + +### Step-by-Step Algorithm + +1. **Initialization**: + - Create a list `heights` of zeros with a length equal to the number of columns in the matrix. + +2. **Iterate over Rows**: + - For each row, update the `heights` where: + - If `matrix[i][j] == '1'`, increment `heights[j]` by 1. + - If `matrix[i][j] == '0'`, reset `heights[j]` to 0. + +3. **Calculate Maximum Rectangle**: + - For each updated `heights` array, use a stack to find the maximum rectangle area in the histogram. + +### Python Solution + +```python +def maximalRectangle(matrix): + if not matrix: + return 0 + max_area = 0 + heights = [0] * len(matrix[0]) + + for row in matrix: + for i in range(len(row)): + if row[i] == '1': + heights[i] += 1 + else: + heights[i] = 0 + + max_area = max(max_area, largestRectangleArea(heights)) + + return max_area + +def largestRectangleArea(heights): + stack = [] + max_area = 0 + heights.append(0) + + for i in range(len(heights)): + while stack and heights[i] < heights[stack[-1]]: + h = heights[stack.pop()] + w = i if not stack else i - stack[-1] - 1 + max_area = max(max_area, h * w) + stack.append(i) + + heights.pop() + return max_area +``` + +### Java Solution +```Java +import java.util.Stack; + +class Solution { + public int maximalRectangle(char[][] matrix) { + if (matrix.length == 0) return 0; + int maxArea = 0; + int[] heights = new int[matrix[0].length]; + + for (char[] row : matrix) { + for (int i = 0; i < row.length; i++) { + heights[i] = row[i] == '1' ? heights[i] + 1 : 0; + } + maxArea = Math.max(maxArea, largestRectangleArea(heights)); + } + + return maxArea; + } + + private int largestRectangleArea(int[] heights) { + Stack stack = new Stack<>(); + int maxArea = 0; + int[] h = new int[heights.length + 1]; + System.arraycopy(heights, 0, h, 0, heights.length); + + for (int i = 0; i < h.length; i++) { + while (!stack.isEmpty() && h[i] < h[stack.peek()]) { + int height = h[stack.pop()]; + int width = stack.isEmpty() ? i : i - stack.peek() - 1; + maxArea = Math.max(maxArea, height * width); + } + stack.push(i); + } + + return maxArea; + } +} +``` + +### C++ Solution +```cpp +#include +#include +#include + +class Solution { +public: + int maximalRectangle(std::vector>& matrix) { + if (matrix.empty()) return 0; + int maxArea = 0; + std::vector heights(matrix[0].size(), 0); + + for (const auto& row : matrix) { + for (size_t i = 0; i < row.size(); ++i) { + heights[i] = row[i] == '1' ? heights[i] + 1 : 0; + } + maxArea = std::max(maxArea, largestRectangleArea(heights)); + } + + return maxArea; + } + +private: + int largestRectangleArea(const std::vector& heights) { + std::stack stack; + int maxArea = 0; + std::vector h = heights; + h.push_back(0); + + for (size_t i = 0; i < h.size(); ++i) { + while (!stack.empty() && h[i] < h[stack.top()]) { + int height = h[stack.top()]; + stack.pop(); + int width = stack.empty() ? i : i - stack.top() - 1; + maxArea = std::max(maxArea, height * width); + } + stack.push(i); + } + + return maxArea; + } +}; +``` + +### C Solution +```c +#include +#include +#include + +int maximalRectangle(char** matrix, int matrixSize, int* matrixColSize) { + if (matrixSize == 0) return 0; + int maxArea = 0; + int heights[*matrixColSize]; + memset(heights, 0, sizeof(heights)); + + for (int i = 0; i < matrixSize; i++) { + for (int j = 0; j < *matrixColSize; j++) { + heights[j] = matrix[i][j] == '1' ? heights[j] + 1 : 0; + } + maxArea = fmax(maxArea, largestRectangleArea(heights, *matrixColSize)); + } + + return maxArea; +} + +int largestRectangleArea(int* heights, int size) { + int maxArea = 0; + int* stack = (int*)malloc((size + 1) * sizeof(int)); + int top = -1; + heights[size] = 0; + + for (int i = 0; i <= size; i++) { + while (top != -1 && heights[i] < heights[stack[top]]) { + int height = heights[stack[top--]]; + int width = top == -1 ? i : i - stack[top] - 1; + maxArea = fmax(maxArea, height * width); + } + stack[++top] = i; + } + + free(stack); + return maxArea; +} +``` + +### JavaScript Solution +```js +var maximalRectangle = function(matrix) { + if (matrix.length === 0) return 0; + let maxArea = 0; + let heights = new Array(matrix[0].length).fill(0); + + for (let row of matrix) { + for (let i = 0; i < row.length; i++) { + heights[i] = row[i] === '1' ? heights[i] + 1 : 0; + } + maxArea = Math.max(maxArea, largestRectangleArea(heights)); + } + + return maxArea; +}; + +var largestRectangleArea = function(heights) { + let stack = []; + let maxArea = 0; + heights.push(0); + + for (let i = 0; i < heights.length; i++) { + while (stack.length && heights[i] < heights[stack[stack.length - 1]]) { + let height = heights[stack.pop()]; + let width = stack.length === 0 ? i : i - stack[stack.length - 1] - 1; + maxArea = Math.max(maxArea, height * width); + } + stack.push(i); + } + + heights.pop(); + return maxArea; +}; +``` + +### Conclusion +This problem combines concepts from dynamic programming and stack-based approaches to efficiently calculate the largest rectangle containing only 1's in a binary matrix. By converting the problem to a series of histogram problems and using an optimized approach to find the largest rectangle in a histogram, we achieve a time-efficient solution. + + diff --git a/solutions/lc-solutions/0000-0099/0086-partition-list.md b/solutions/lc-solutions/0000-0099/0086-partition-list.md new file mode 100644 index 0000000..6336ab9 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0086-partition-list.md @@ -0,0 +1,104 @@ +--- +id: partition-list +title: Partition List +sidebar_label: 0086-Partition List +description: partition it such that all nodes less than x come before nodes greater than or equal to x. +--- + +## Problem Description +Given the `head` of a linked list and a value `x`, partition it such that all nodes less than x come before nodes greater than or equal to `x`. + +You should preserve the original relative order of the nodes in each of the two partitions. + + +### Examples + +#### Example 1 + +``` +- Input: head = [1,4,3,2,5,2], x = 3 +- Output: [1,2,2,4,3,5] + +``` +#### Example 2 + +``` +- Input: head = [2,1], x = 2 +- Output: [1,2] +``` + +### Constraints + +- The number of nodes in the list is in the range `[0, 200].` +- `100 <= Node.val <= 100` +- `200 <= x <= 200` + +### Approach +Using two pointer, to iterate through the nodes and dettach the nodes that needs to be moved + + +### Solution Code + +#### C++ + +```cpp + + +class Solution { +public: + ListNode* partition(ListNode* head, int x) { + ListNode*temp=head; + ListNode*dummy=new ListNode (-1); + ListNode*ans=dummy; + while(temp!=NULL){ + if(temp->valnext=new ListNode(temp->val); + dummy=dummy->next; + } + temp=temp->next; + } + temp=head; + while(temp!=NULL){ + if(temp->val>=x){ + dummy->next=new ListNode(temp->val); + dummy=dummy->next; + } + temp=temp->next; + + } + return ans->next; + } +}; + +``` +#### Java + +```java + +class Solution { + public ListNode partition(ListNode head, int x) { + ListNode beforeHead = new ListNode(0), afterHead = new ListNode(0); + ListNode before = beforeHead, after = afterHead; + for (; head != null; head = head.next) + if (head.val < x) { + before.next = head; + before = head; + } else { + after.next = head; + after = head; + } + + after.next = null; + before.next = afterHead.next; + return beforeHead.next; + } +} + +``` + +### Conclusion +- Time complexity: +`O(n)` + +- Space complexity: +`O(1)` \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0087-scramble-string.md b/solutions/lc-solutions/0000-0099/0087-scramble-string.md new file mode 100644 index 0000000..e7fb9de --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0087-scramble-string.md @@ -0,0 +1,209 @@ +--- +id: scramble-string +title: Scramble String +sidebar_label: 0087-Scramble String +description: We can scramble a string s to get a string t using the following algorithm +--- + +## Problem Description +We can scramble a string s to get a string t using the following algorithm: + +If the length of the string is 1, stop. +If the length of the string is > 1, do the following: +Split the string into two non-empty substrings at a random index, i.e., if the string is `s`, divide it to `x` and y where `s = x + y`. +Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, s may become `s = x + y` or `s = y + x.` +Apply step 1 recursively on each of the two substrings `x` and `y`. +Given two strings `s1` and `s2` of the same length, return `true` if `s2` is a scrambled string of `s1`, otherwise, return `false`. + + + +### Examples + +#### Example 1 + +``` +Input: s1 = "great", s2 = "rgeat" +Output: true +Explanation: One possible scenario applied on s1 is: +"great" --> "gr/eat" // divide at random index. +"gr/eat" --> "gr/eat" // random decision is not to swap the two substrings and keep them in order. +"gr/eat" --> "g/r / e/at" // apply the same algorithm recursively on both substrings. divide at random index each of them. +"g/r / e/at" --> "r/g / e/at" // random decision was to swap the first substring and to keep the second substring in the same order. +"r/g / e/at" --> "r/g / e/ a/t" // again apply the algorithm recursively, divide "at" to "a/t". +"r/g / e/ a/t" --> "r/g / e/ a/t" // random decision is to keep both substrings in the same order. +The algorithm stops now, and the result string is "rgeat" which is s2. +As one possible scenario led s1 to be scrambled to s2, we return true. +``` +#### Example 2 + +``` +Input: s1 = "abcde", s2 = "caebd" +Output: false +``` + +#### Example 3 +``` +Input: s1 = "a", s2 = "a" +Output: true +``` + +### Constraints + +- `s1.length == s2.length` +- `1 <= s1.length <= 30` +- `s1 and s2` consist of lowercase English letters. + + + +### Approach +We will first check the base cases i.e., if the two strings are equal or not or if they are of different sizes. +Then, we will create a key for the current problem by concatenating the two strings and storing it in a dictionary to avoid repeated computations. +We will iterate over all possible splits of the current string and check whether we need to swap the left and right substrings or not. +We will then make recursive calls on these two substrings and return true if any of the calls return true. + + +### Solution Code + +#### C++ + +```cpp + +class Solution { +private: + int dp[40][40][40]; + bool solve(string &s1,string &s2,int l1,int l2,int len){ + if(len == 0){ + return dp[l1][l2][len]=true; + } + if(dp[l1][l2][len]!=-1){ + return dp[l1][l2][len]; + } + for(int i=l1,j=l2;i<=len+l1;i++,j++){ + if(i==l1+len){ + return dp[l1][l2][len]=true; + } + if(s1[i]!=s2[j]){ + break; + } + } + vectorv(26,0); + for(int i=l1,j=l2;i map = new HashMap<>(); + + public boolean isScramble(String s1, String s2) { + int n = s1.length(); + // check if the two strings are equal + if (s1.equals(s2)) { + return true; + } + // initialize frequency arrays for s1, s2, and current substring + int[] a = new int[26], b = new int[26], c = new int[26]; + // check if the current substring has already been computed + if (map.containsKey(s1 + s2)) { + return map.get(s1 + s2); + } + // check all possible splits of the two strings + for (int i = 1; i <= n - 1; i++) { + int j = n - i; + // update frequency arrays for s1, s2, and current substring + a[s1.charAt(i - 1) - 'a']++; + b[s2.charAt(i - 1) - 'a']++; + c[s2.charAt(j) - 'a']++; + // check if the current substring has the same characters + if (Arrays.equals(a, b) && isScramble(s1.substring(0, i), s2.substring(0, i)) && isScramble(s1.substring(i), s2.substring(i))) { + // if the substrings are scrambled versions of each other, return true + map.put(s1 + s2, true); + return true; + } + // check if the current substring and its complement have the same characters + if (Arrays.equals(a, c) && isScramble(s1.substring(0, i), s2.substring(j)) && isScramble(s1.substring(i), s2.substring(0, j))) { + // if the substrings are scrambled versions of each other, return true + map.put(s1 + s2, true); + return true; + } + } + // if none of the splits result in scrambled versions, return false + map.put(s1 + s2, false); + return false; + } +} + +``` + +#### Python + +```py + +class Solution: + # dictionary to store previously computed substrings + map = {} + + def isScramble(self, s1: str, s2: str) -> bool: + n = len(s1) + # check if the two strings are equal + if s1 == s2: + return True + # initialize frequency lists for s1, s2, and current substring + a, b, c = [0] * 26, [0] * 26, [0] * 26 + # check if the current substring has already been computed + if (s1 + s2) in self.map: + return self.map[s1 + s2] + # check all possible splits of the two strings + for i in range(1, n): + j = n - i + # update frequency lists for s1, s2, and current substring + a[ord(s1[i - 1]) - ord('a')] += 1 + b[ord(s2[i - 1]) - ord('a')] += 1 + c[ord(s2[j]) - ord('a')] += 1 + # check if the current substring has the same characters + if a == b and self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]): + # if the substrings are scrambled versions of each other, return True + self.map[s1 + s2] = True + return True + # check if the current substring and its complement have the same characters + if a == c and self.isScramble(s1[:i], s2[j:]) and self.isScramble(s1[i:], s2[:j]): + # if the substrings are scrambled versions of each other, return True + self.map[s1 + s2] = True + return True + # if none of the splits result in scrambled versions, return False + self.map[s1 + s2] = False + return False + +``` + +### Conclusion +- Time complexity: +`O(n^4)` + +- Space complexity: +`O(n^2)` \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0088-merge-sorted-array.md b/solutions/lc-solutions/0000-0099/0088-merge-sorted-array.md new file mode 100644 index 0000000..012c06c --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0088-merge-sorted-array.md @@ -0,0 +1,138 @@ +--- +id: merge-sorted-array +title: Merge Sorted Array (LeetCode) +sidebar_label: 0088-MergeSortedArray +--- + +## Problem Description + + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-sorted-array/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/merge-sorted-array/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + + +## Problem Description + +You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. + +Merge nums1 and nums2 into a single array sorted in non-decreasing order. + +The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n. + +### Examples + +#### Example 1 + +- **Input:** nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 +- **Output:** [1,2,2,3,5,6] +- **Explanation:** The arrays being merged are [1,2,3] and [2,5,6]. The result of the merge is [1,2,2,3,5,6]. + +#### Example 2 + +- **Input:** nums1 = [1], m = 1, nums2 = [], n = 0 +- **Output:** [1] +- **Explanation:** The arrays being merged are [1] and []. The result of the merge is [1]. + +#### Example 3 + +- **Input:** nums1 = [0], m = 0, nums2 = [1], n = 1 +- **Output:** [1] +- **Explanation:** The arrays being merged are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. + +### Constraints + +- $nums1.length == m + n$ +- $nums2.length == n$ +- $0 <= m, n <= 200$ +- $1 <= m + n <= 200$ +- $-10^9 <= nums1[i], nums2[j] <= 10^9$ + +### Approach + +To merge the two arrays efficiently in-place, we can use a two-pointer approach starting from the end of both arrays. By comparing elements from the end of both arrays and placing the larger element at the end of nums1, we can achieve the desired result in $O(m + n)$ time. + +1. **Initialize Pointers:** + - Initialize two pointers, p1 and p2, to the end of nums1 and nums2 respectively. + +2. **Merge Arrays:** + - Compare elements at nums1[p1] and nums2[p2], and place the larger element at the end of nums1. + - Decrement the pointer of the array from which the larger element was taken. + - Repeat this process until all elements from nums2 are merged into nums1. + +### Solution Code + +#### Python + +```py +class Solution(object): + def merge(self, nums1, m, nums2, n): + p1, p2, p = m - 1, n - 1, m + n - 1 + while p1 >= 0 and p2 >= 0: + if nums1[p1] > nums2[p2]: + nums1[p] = nums1[p1] + p1 -= 1 + else: + nums1[p] = nums2[p2] + p2 -= 1 + p -= 1 + nums1[:p2 + 1] = nums2[:p2 + 1] +``` + +#### Java + +```java +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + int p1 = m - 1; + int p2 = n - 1; + int p = m + n - 1; + + while (p1 >= 0 && p2 >= 0) { + if (nums1[p1] > nums2[p2]) { + nums1[p] = nums1[p1]; + p1--; + } else { + nums1[p] = nums2[p2]; + p2--; + } + p--; + } + + System.arraycopy(nums2, 0, nums1, 0, p2 + 1); + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + int p1 = m - 1; + int p2 = n - 1; + int p = m + n - 1; + + while (p1 >= 0 && p2 >= 0) { + if (nums1[p1] > nums2[p2]) { + nums1[p] = nums1[p1]; + p1--; + } else { + nums1[p] = nums2[p2]; + p2--; + } + p--; + } + + while (p2 >= 0) { + nums1[p--] = nums2[p2--]; + } + } +}; +``` + +### Conclusion + +The above solution efficiently merges two sorted integer arrays nums1 and nums2 into a single array nums1 in non-decreasing order. It utilizes a two-pointer approach to achieve a time complexity of $O(m + n)$, where m and n are the lengths of nums1 and nums2 respectively. This approach allows for an in-place merge of the arrays, meeting the requirements of the problem. + diff --git a/solutions/lc-solutions/0000-0099/0089-gray-code.md b/solutions/lc-solutions/0000-0099/0089-gray-code.md new file mode 100644 index 0000000..bf3bab8 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0089-gray-code.md @@ -0,0 +1,102 @@ +--- +id: gray-code +title: Gray Code (LeetCode) +difficulty: Medium +sidebar_label: 0089-GrayCode +topics: + - Math + - Bit Manipulation +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Gray Code](https://leetcode.com/problems/gray-code/) | [Gray Code Solution on LeetCode](https://leetcode.com/problems/gray-code/solutions/) | [YourLeetCodeProfile](https://leetcode.com/your-profile/) | + +## Problem Description + +The gray code is a binary numeral system where two successive values differ in only one bit. + +Given an integer `n`, return an array of gray code sequence for `n` bits. + +### Examples + +#### Example 1: + +- **Input:** `n = 2` +- **Output:** `[0,1,3,2]` +- **Explanation:** + ``` + 00 - 0 + 01 - 1 + 11 - 3 + 10 - 2 + ``` + +#### Example 2: + +- **Input:** `n = 1` +- **Output:** `[0,1]` +- **Explanation:** + ``` + 0 - 0 + 1 - 1 + ``` + +### Constraints + +- `1 <= n <= 16` + +### Approach + +To generate the gray code sequence for `n` bits: +1. Start with the base case for `n = 0`, which is `[0]`. +2. Use a recursive approach or iterative method to generate gray codes for increasing values of `n`. +3. Utilize properties of gray codes where each successive value differs from the previous by only one bit. + +### Solution Code + +#### Python + +```python +class Solution: + def grayCode(self, n: int) -> List[int]: + result = [0] + for i in range(n): + result += [x + (1 << i) for x in reversed(result)] + return result +``` + +#### Java + +```java +class Solution { + public List grayCode(int n) { + List result = new ArrayList<>(); + for (int i = 0; i < (1 << n); i++) { + result.add(i ^ (i >> 1)); + } + return result; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + vector grayCode(int n) { + vector result; + for (int i = 0; i < (1 << n); i++) { + result.push_back(i ^ (i >> 1)); + } + return result; + } +}; +``` + +### Conclusion + +The "Gray Code" problem involves generating a sequence of binary numbers such that each successive number differs by only one bit. The provided solutions in Python, Java, and C++ efficiently generate the gray code sequence based on the given constraints, offering different implementations for handling bit manipulation and sequence generation. diff --git a/solutions/lc-solutions/0000-0099/0090-subsets-ii.md b/solutions/lc-solutions/0000-0099/0090-subsets-ii.md new file mode 100644 index 0000000..e9b1d57 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0090-subsets-ii.md @@ -0,0 +1,157 @@ +--- +id: subsets-ii +title: Subsets II +difficulty: Medium +sidebar_label: 0090-Subsets-II +tags: + - Array + - Backtracking + - LeetCode Medium +--- + +## Problem Description +Given an integer array `nums` that may contain duplicates, return all possible subsets (the power set). + +The solution set must not contain duplicate subsets. Return the solution in any order. + +### Example +**Example 1:** +```plaintext +Input: nums = [1,2,2] +Output: [[],[1],[1,2],[1,2,2],[2],[2,2]] +``` +**Example 2:** +```plaintext +Input: nums = [0] +Output: [[],[0]] +``` + +### Constraints +- `1 <= nums.length <= 10` +- `-10 <= nums[i] <= 10` + +## Solution Approach + +### Approach Overview +The problem can be solved using backtracking. To handle duplicates, we need to sort the array first and then ensure that we do not include the same element twice in the same position within the subset. + +### Detailed Steps + +1. **Sort the Input Array**: + - Sorting helps in easily skipping duplicates. + +2. **Backtracking Function**: + - Use a helper function to generate all subsets. + - Skip over duplicate elements by checking the previous element in the sorted array. + +3. **Generate Subsets**: + - Initialize an empty list to store all subsets. + - Start backtracking from the first index. + +## Code Examples + +### C++ +```cpp +class Solution { +public: + vector> subsetsWithDup(vector& nums) { + vector> result; + vector subset; + sort(nums.begin(), nums.end()); + backtrack(nums, 0, subset, result); + return result; + } + +private: + void backtrack(vector& nums, int start, vector& subset, vector>& result) { + result.push_back(subset); + for (int i = start; i < nums.size(); ++i) { + if (i > start && nums[i] == nums[i - 1]) continue; + subset.push_back(nums[i]); + backtrack(nums, i + 1, subset, result); + subset.pop_back(); + } + } +}; +``` + +### Python +```python +class Solution: + def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: + def backtrack(start, path): + res.append(path) + for i in range(start, len(nums)): + if i > start and nums[i] == nums[i - 1]: + continue + backtrack(i + 1, path + [nums[i]]) + + nums.sort() + res = [] + backtrack(0, []) + return res +``` + +### Java +```java +class Solution { + public List> subsetsWithDup(int[] nums) { + List> result = new ArrayList<>(); + Arrays.sort(nums); + backtrack(nums, 0, new ArrayList<>(), result); + return result; + } + + private void backtrack(int[] nums, int start, List subset, List> result) { + result.add(new ArrayList<>(subset)); + for (int i = start; i < nums.length; i++) { + if (i > start && nums[i] == nums[i - 1]) continue; + subset.add(nums[i]); + backtrack(nums, i + 1, subset, result); + subset.remove(subset.size() - 1); + } + } +} +``` + +### C +```c +#include + +// Function to sort the array +int compare(const void *a, const void *b) { + return (*(int*)a - *(int*)b); +} + +void backtrack(int* nums, int numsSize, int start, int* subset, int subsetSize, int** result, int* returnSize, int** columnSizes) { + result[*returnSize] = (int*)malloc(subsetSize * sizeof(int)); + for (int i = 0; i < subsetSize; i++) { + result[*returnSize][i] = subset[i]; + } + (*columnSizes)[*returnSize] = subsetSize; + (*returnSize)++; + + for (int i = start; i < numsSize; i++) { + if (i > start && nums[i] == nums[i - 1]) continue; + subset[subsetSize] = nums[i]; + backtrack(nums, numsSize, i + 1, subset, subsetSize + 1, result, returnSize, columnSizes); + } +} + +int** subsetsWithDup(int* nums, int numsSize, int* returnSize, int** columnSizes) { + qsort(nums, numsSize, sizeof(int), compare); + int** result = (int**)malloc(1000 * sizeof(int*)); + *returnSize = 0; + *columnSizes = (int*)malloc(1000 * sizeof(int)); + int* subset = (int*)malloc(numsSize * sizeof(int)); + backtrack(nums, numsSize, 0, subset, 0, result, returnSize, columnSizes); + free(subset); + return result; +} +``` + +## Complexity + +- **Time Complexity**: `O(2^n * n)`, where `n` is the length of the input array. This accounts for generating all subsets and sorting the array. + +- **Space Complexity**: `O(2^n * n)`, as we need to store all subsets. Each subset can be of length `n` and there \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0091-Decode-Ways.md b/solutions/lc-solutions/0000-0099/0091-Decode-Ways.md new file mode 100644 index 0000000..0a12d91 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0091-Decode-Ways.md @@ -0,0 +1,206 @@ +--- +id: decode-ways +title: Decode Ways +sidebar_label: 0091 - Decode Ways +tags: + - dyp + - Leetcode + +description: "This is a solution to the Decode Ways on LeetCode." +--- + +## Problem Statement + +A message containing letters from A-Z can be encoded into numbers using the following mapping: + +``` +'A' -> "1" +'B' -> "2" +... +'Z' -> "26" +``` + +To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: + +"AAJF" with the grouping (1 1 10 6) +"KJF" with the grouping (11 10 6) +Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". + +Given a string s containing only digits, return the number of ways to decode it. + +The test cases are generated so that the answer fits in a 32-bit integer. + +### Examples + +**Example 1:** + +``` +Input: s = "12" +Output: 2 +Explanation: "12" could be decoded as "AB" (1 2) or "L" (12). +``` + +**Example 2:** + +``` +Input: s = "226" +Output: 3 +Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). +``` + +**Example 3:** + +``` +Input: s = "06" +Output: 0 +Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06"). +``` + +### Constraints: + +- $1 <= s.length <= 100$ +- s contains only digits and may contain leading zero(s). + +### Algorithm + +1. If the string `s` is empty or starts with '0', return 0 as it cannot be decoded. +2. Initialize a `dyp` array where `dyp[i]` represents the number of ways to decode the substring `s[0:i]`. +3. Set `dyp[0]` to 1 (base case for the empty string). +4. Set `dyp[1]` based on the first character of the string (1 if the first character is not '0', otherwise 0). +5. Iterate through the string from the second character to the end: + - For each character, check if it forms a valid single-digit number (between '1' and '9'). If it does, add `dyp[i-1]` to `dyp[i]`. + - Check if the two-digit number formed with the previous character is valid (between "10" and "26"). If it does, add `dyp[i-2]` to `dyp[i]`. +6. The result is in `dyp[n]`, where `n` is the length of the string. + +### Pseudocode + +``` +function decode(s): + if s is empty or s[0] is '0': + return 0 + + n = length of s + dyp = array of size (n + 1) initialized to 0 + dyp[0] = 1 + dyp[1] = 1 if s[0] != '0' else 0 + + for i from 2 to n: + if s[i-1] != '0': + dyp[i] += dyp[i-1] + + twodigit = integer value of s[i-2:i] + if 10 <= twodigit <= 26: + dyp[i] += dyp[i-2] + + return dyp[n] +``` + +### Python + +```python +class Solution: + def decode(self, s: str) -> int: + if not s or s[0] == '0': + return 0 + + n = len(s) + dyp = [0] * (n + 1) + dyp[0] = 1 + dyp[1] = 1 if s[0] != '0' else 0 + + for i in range(2, n + 1): + if s[i - 1] != '0': + dyp[i] += dyp[i - 1] + + twodigit = int(s[i - 2:i]) + if 10 <= twodigit <= 26: + dyp[i] += dyp[i - 2] + + return dyp[n] +``` + +### C++ + +```cpp +class Solution { +public: + int decode(string s) { + if (s.empty() || s[0] == '0') return 0; + + int n = s.size(); + vector dyp(n + 1, 0); + dyp[0] = 1; + dyp[1] = s[0] != '0' ? 1 : 0; + + for (int i = 2; i <= n; ++i) { + if (s[i - 1] != '0') { + dyp[i] += dyp[i - 1]; + } + + int twodigit = stoi(s.substr(i - 2, 2)); + if (10 <= twodigit && twodigit <= 26) { + dyp[i] += dyp[i - 2]; + } + } + + return dyp[n]; + } +}; + +``` + +### Java + +```java +class Solution { + public int decode(String s) { + if (s == null || s.length() == 0 || s.charAt(0) == '0') { + return 0; + } + + int n = s.length(); + int[] dyp = new int[n + 1]; + dyp[0] = 1; + dyp[1] = s.charAt(0) != '0' ? 1 : 0; + + for (int i = 2; i <= n; ++i) { + if (s.charAt(i - 1) != '0') { + dyp[i] += dyp[i - 1]; + } + + int twoDigit = Integer.parseInt(s.substring(i - 2, i)); + if (10 <= twoDigit && twoDigit <= 26) { + dyp[i] += dyp[i - 2]; + } + } + + return dyp[n]; + } +} +``` + +### JavaScript + +```javascript +var decode = function (s) { + if (!s || s[0] === "0") return 0; + + let n = s.length; + let dyp = new Array(n + 1).fill(0); + dyp[0] = 1; + dyp[1] = s[0] !== "0" ? 1 : 0; + + for (let i = 2; i <= n; i++) { + if (s[i - 1] !== "0") { + dyp[i] += dyp[i - 1]; + } + + let twoDigit = parseInt(s.substring(i - 2, i), 10); + if (10 <= twoDigit && twoDigit <= 26) { + dyp[i] += dyp[i - 2]; + } + } + + return dyp[n]; +}; +``` diff --git a/solutions/lc-solutions/0000-0099/0092-Reverse-LinkedList-II.md b/solutions/lc-solutions/0000-0099/0092-Reverse-LinkedList-II.md new file mode 100644 index 0000000..f56a33f --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0092-Reverse-LinkedList-II.md @@ -0,0 +1,241 @@ +--- +id: reverse-linked-list-II +title: Reverse Linked List II +sidebar_label: 0092 - Reverse Linked List II +tags: + - Linked List + - Leetcode +description: "This is a solution to the Reverse Linked List II problem on LeetCode." +--- + +## Problem Statement + +Given the head of a singly linked list and two integers left and right where `left <= right`, reverse the nodes of the list from position left to position right, and return the reversed list. + +### Examples + +**Example 1:** + +``` +Input: head = [1,2,3,4,5], left = 2, right = 4 +Output: [1,4,3,2,5] +``` + +**Example 2:** + +``` +Input: head = [5], left = 1, right = 1 +Output: [5] +``` + +### Constraints: + +- The number of nodes in the list is `n`. +- $1 <= n <= 500$ +- $-500 <= Node.val <= 500$ +- $1 <= left <= right <= n$ + +### Algorithm + +1. Create a dummy node pointing to the head of the list to handle edge cases easily. +2. Find the node just before the `left` position (`leftNode`) and the node at the `left` position (`curr`). +3. Reverse the sublist from `left` to `right`. +4. Reconnect the reversed sublist back to the list. +5. Return the new head of the list (`dummy.next`). + +### Pseudocode + +``` +function reverseLinkedList(head, left, right): + if head is null: + return null + + dummy = new ListNode(0) + dummy.next = head + leftNode = dummy + curr = head + + for i from 0 to left-2: + leftNode = leftNode.next + curr = curr.next + + subhead = curr + preNode = null + + for i from 0 to right-left: + nextNode = curr.next + curr.next = preNode + preNode = curr + curr = nextNode + + leftNode.next = preNode + subhead.next = curr + + return dummy.next +``` + +### Python + +```python +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +class Solution: + def reverseLinkedList(self, head: ListNode, left: int, right: int) -> ListNode: + if not head: + return None + + dummy = ListNode(0) + dummy.next = head + leftNode = dummy + curr = head + + for i in range(left - 1): + leftNode = leftNode.next + curr = curr.next + + subhead = curr + preNode = None + + for i in range(right - left + 1): + nextNode = curr.next + curr.next = preNode + preNode = curr + curr = nextNode + + leftNode.next = preNode + subhead.next = curr + + return dummy.next +``` + +### Java + +```java +class ListNode { + int val; + ListNode next; + ListNode() {} + ListNode(int val) { this.val = val; } + ListNode(int val, ListNode next) { this.val = val; this.next = next; } +} + +class Solution { + public ListNode reverseLinkedList(ListNode head, int left, int right) { + if (head == null) return null; + + ListNode dummy = new ListNode(0); + dummy.next = head; + ListNode leftNode = dummy; + ListNode curr = head; + + for (int i = 0; i < left - 1; i++) { + leftNode = leftNode.next; + curr = curr.next; + } + + ListNode subhead = curr; + ListNode preNode = null; + + for (int i = 0; i <= right - left; i++) { + ListNode nextNode = curr.next; + curr.next = preNode; + preNode = curr; + curr = nextNode; + } + + leftNode.next = preNode; + subhead.next = curr; + + return dummy.next; + } +} +``` + +### C++ + +```cpp +class ListNode { +public: + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* reverseLinkedList(ListNode* head, int left, int right) { + if (!head) return nullptr; + + ListNode* dummy = new ListNode(0); + dummy->next = head; + + ListNode* leftNode = dummy; + ListNode* curr = head; + + for (int i = 0; i < left - 1; i++) { + leftNode = leftNode->next; + curr = curr->next; + } + + ListNode* subhead = curr; + ListNode* preNode = nullptr; + + for (int i = 0; i <= right - left; i++) { + ListNode* nextNode = curr->next; + curr->next = preNode; + preNode = curr; + curr = nextNode; + } + + leftNode->next = preNode; + subhead->next = curr; + + return dummy->next; + } +}; +``` + +### JavaScript + +```javascript +class ListNode { + constructor(val = 0, next = null) { + this.val = val; + this.next = next; + } +} + +var reverseLinkedList = function (head, left, right) { + if (!head) return null; + + let dummy = new ListNode(0); + dummy.next = head; + let leftNode = dummy; + let curr = head; + + for (let i = 0; i < left - 1; i++) { + leftNode = leftNode.next; + curr = curr.next; + } + + let subhead = curr; + let preNode = null; + + for (let i = 0; i <= right - left; i++) { + let nextNode = curr.next; + curr.next = preNode; + preNode = curr; + curr = nextNode; + } + + leftNode.next = preNode; + subhead.next = curr; + + return dummy.next; +}; +``` diff --git a/solutions/lc-solutions/0000-0099/0093-restore-ip-addresses.md b/solutions/lc-solutions/0000-0099/0093-restore-ip-addresses.md new file mode 100644 index 0000000..1675f81 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0093-restore-ip-addresses.md @@ -0,0 +1,160 @@ +--- +id: restore-ip-addresses +title: Restore IP Addresses +difficulty: Medium +sidebar_label: 0093-Restore-IP-Addresses +tags: + - String + - Backtracking + - LeetCode Medium +--- + +## Problem Description +Given a string `s` containing only digits, return all possible valid IP addresses that can be obtained from `s`. You can return them in any order. + +A valid IP address consists of exactly four integers, each integer is between `0` and `255`, separated by single dots and cannot have leading zeros. For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses and "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses. + +### Example +**Example 1:** +```plaintext +Input: s = "25525511135" +Output: ["255.255.11.135", "255.255.111.35"] +``` +**Example 2:** +```plaintext +Input: s = "0000" +Output: ["0.0.0.0"] +``` +**Example 3:** +```plaintext +Input: s = "101023" +Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"] +``` + +### Constraints +- `1 <= s.length <= 20` +- `s` consists of digits only. + +## Approach + +# Restoring Valid IP Addresses + +This solution defines a class `Solution` containing a method `restoreIpAddresses` which generates all possible valid IP addresses from the given string `s` using backtracking. + +## Implementation Steps + +### Step 1: Define the `Solution` Class + +Define a class `Solution` containing a method `restoreIpAddresses` which takes a string `s` as input and returns a list of strings. + +### Step 2: Initialize Result List + +Initialize an empty list called `result` to store the valid IP addresses. + +### Step 3: Define the Backtracking Function + +Define a function called `backtrack` which takes three parameters: `start` (the current index in `s`), `path` (the current segments of the IP address being generated), and `dots` (the number of dots used so far). + +### Step 4: Base Case Check + +Check if `dots` equals 4 and `start` equals the length of `s`. If so, append the `path` to the `result`. + +### Step 5: Loop Through the Possible Segments + +Loop through each possible segment length (1 to 3): + - Check if the current segment is valid (length is 1 or the first digit is not '0' and the segment value is less than or equal to 255). + - If valid, recursively call the `backtrack` function with the next index, updated path, and incremented dots. + +### Step 6: Call the Backtrack Function + +Initially call the `backtrack` function with `start` set to 0, an empty `path`, and `dots` set to 0. + +### Step 7: Return Result + +Return the `result` list. + +This algorithm generates all possible valid IP addresses by using backtracking to explore different segment lengths and ensuring that each segment is a valid integer between 0 and 255 without leading zeros. + +## Code + +### C++ +```cpp +class Solution { +public: + vector restoreIpAddresses(string s) { + vector result; + backtrack(s, 0, "", 0, result); + return result; + } + +private: + void backtrack(const string& s, int start, string path, int dots, vector& result) { + if (dots == 4 && start == s.size()) { + result.push_back(path.substr(0, path.size() - 1)); // Remove the last dot + return; + } + if (dots > 4) return; + + for (int len = 1; len <= 3 && start + len <= s.size(); ++len) { + string segment = s.substr(start, len); + if ((segment.size() > 1 && segment[0] == '0') || stoi(segment) > 255) continue; + backtrack(s, start + len, path + segment + ".", dots + 1, result); + } + } +}; +``` + +### Python +```python +class Solution: + def restoreIpAddresses(self, s: str) -> List[str]: + def backtrack(start, path, dots): + if dots == 4 and start == len(s): + result.append(path[:-1]) # Remove the last dot + return + if dots > 4: + return + + for length in range(1, 4): + if start + length > len(s): + break + segment = s[start:start + length] + if (length > 1 and segment[0] == '0') or int(segment) > 255: + continue + backtrack(start + length, path + segment + ".", dots + 1) + + result = [] + backtrack(0, "", 0) + return result +``` + +### Java +```java +class Solution { + public List restoreIpAddresses(String s) { + List result = new ArrayList<>(); + backtrack(s, 0, "", 0, result); + return result; + } + + private void backtrack(String s, int start, String path, int dots, List result) { + if (dots == 4 && start == s.length()) { + result.add(path.substring(0, path.length() - 1)); // Remove the last dot + return; + } + if (dots > 4) return; + + for (int len = 1; len <= 3 && start + len <= s.length(); ++len) { + String segment = s.substring(start, start + len); + if ((segment.length() > 1 && segment.startsWith("0")) || Integer.parseInt(segment) > 255) continue; + backtrack(s, start + len, path + segment + ".", dots + 1, result); + } + } +} +``` + +## Complexity +- Time complexity: `O(3^4 * n)` where `n` is the length of the string `s`. +- Space complexity: `O(n)` + +This solution generates all possible valid IP addresses from a given string `s` by using backtracking to explore different segment lengths and ensuring that each segment is a valid integer between 0 and 255 without leading zeros. The complexity is driven by the number of segments and the length of the string. \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0094-Binary-Tree-Inorder-Traversal.md b/solutions/lc-solutions/0000-0099/0094-Binary-Tree-Inorder-Traversal.md new file mode 100644 index 0000000..f480031 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0094-Binary-Tree-Inorder-Traversal.md @@ -0,0 +1,120 @@ +--- +id: binary-tree-inorder-traversal +title: Binary Tree Inorder Traversal +difficulty: Easy +sidebar_label: 0094-Binary Tree Inorder Traversal +tags: + - Binary Tree + - Inorder + - Traversal + - LeetCode Easy +--- + +## Problem + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Binary Tree Inorder Traversal ](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [Binary Tree Inorder Traversal Solution on LeetCode](https://leetcode.com/problems/solutions/) | [Khushi Kalra](https://leetcode.com/u/abckhush/) | + +## Problem Description +Given the root of a binary tree, return the inorder traversal of its nodes' values. +### Example +**Example 1:** +```plaintext +Input: root = [1,null,2,3] +Output: [1,3,2] +``` +**Example 2:** +```plaintext +Input: root = [] +Output: [] +``` +**Example 3:** +```plaintext +Input: root = [1] +Output: [1] +``` + +### Constraints +1. The number of nodes in the tree is in the range `[0, 100]`. +2. `-100 <= Node.val <= 100` + +## Approach: Recursion +The problem is to perform an inorder traversal of a binary tree and return the values in a list. An inorder traversal visits the nodes of the binary tree in the following order: left subtree, root node, right subtree. + +We use a helper function traversal to perform the inorder traversal recursively. The main function inorderTraversal initializes the result list and calls the helper function. + +1. Initialization: +- Create an empty vector inOrder to store the result of the inorder traversal. + +2. Recursive Traversal: +- Define a helper function traversal that takes a TreeNode* and a reference to the inOrder vector. +- If the current node (root) is NULL, return immediately (base case). +- Recursively call traversal on the left subtree (root->left). +- Push the value of the current node (root->val) to the inOrder vector. +- Recursively call traversal on the right subtree (root->right). + +3. Main Function: +- In the inorderTraversal function, create an empty vector inOrder. +- Call the traversal function with the root of the binary tree and the inOrder vector. +- Return the inOrder vector containing the inorder traversal result. + +## Complexity +1. Time Complexity : $$O(h)$$ +2. Space Complexity : $$O(n)$$ + +## Code + +### C++ +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + void traversal(TreeNode* root, vector&inOrder){ + if(root==NULL) return; + traversal(root->left, inOrder); + inOrder.push_back(root->val); + traversal(root->right, inOrder); + } + vector inorderTraversal(TreeNode* root) { + vectorinOrder; + traversal(root, inOrder); + return inOrder; + } +}; +``` + +### Python +```python +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def traversal(self, root, inOrder): + if root is None: + return + self.traversal(root.left, inOrder) + inOrder.append(root.val) + self.traversal(root.right, inOrder) + + def inorderTraversal(self, root): + inOrder = [] + self.traversal(root, inOrder) + return inOrder +``` + + diff --git a/solutions/lc-solutions/0000-0099/0095-unique-binary-search-tree-II.md b/solutions/lc-solutions/0000-0099/0095-unique-binary-search-tree-II.md new file mode 100644 index 0000000..964137b --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0095-unique-binary-search-tree-II.md @@ -0,0 +1,278 @@ +--- +id: unique-binary-search-tree-II +title: Unique binary search tree II +difficulty: Medium +sidebar_label: 0095-Unique-BST-II +tags: + - Binary Tree + - Inorder + - Traversal + - LeetCode Easy +--- + + +## Problem Description +Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order. + +### Example +**Example 1:** +![alt text](https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg) +```plaintext +Input: n = 3 +Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]] +``` +**Example 2:** +```plaintext +Input: n = 1 +Output: [[1]] +``` + +### Constraints +- `1 <= n <= 8` + + +## Institution +There 3 important things. + +One is we try to create subtrees with some range between start(minimum) and end(maximum) value. + +Second is calculation of the range. left range should be between start and current root - 1 as end value because all values of left side must be smaller than current root. right range should be between current root + 1 and end becuase all values on the right side should be greater than current root value. + +Thrid is we call the same funtion recursively, so it's good idea to keep results of current start and end, so that we can use the results later. It's time saving. + + + +## Approach: + +# Generating All Unique Binary Search Trees + +This solution defines a class `Solution` containing a method `generateTrees` which generates all possible unique binary search trees (BSTs) with `n` nodes. The algorithm utilizes memoization to store previously computed results and avoid redundant calculations, thus improving efficiency. + +## Implementation Steps + +### Step 1: Define the `Solution` Class + +Define a class `Solution` containing a method `generateTrees` which takes an integer `n` as input and returns a list of optional `TreeNode` objects. + +### Step 2: Base Case Check + +Check if `n` is 0. If it is, return an empty list since there are no possible trees with 0 nodes. + +### Step 3: Initialize Memoization Dictionary + +Initialize an empty dictionary called `memo`. This dictionary will be used to store previously computed results for specific ranges of values to avoid redundant calculations. + +### Step 4: Define the Inner Function + +Define an inner function called `generate_trees` that takes two parameters: `start` and `end`, which represent the range of values for which binary search trees need to be generated. + +### Step 5: Memoization Check + +Inside the `generate_trees` function: + +- Check if the tuple `(start, end)` exists as a key in the `memo` dictionary. If it does, return the corresponding value from the `memo` dictionary. + +### Step 6: Initialize Trees List + +- Initialize an empty list called `trees`. This list will store the generated trees for the current range. +- If `start` is greater than `end`, append `None` to the `trees` list, indicating an empty subtree, and return the `trees` list. + +### Step 7: Loop Through Root Values + +- Loop through each value `root_val` in the range `[start, end]` (inclusive): + - Recursively call the `generate_trees` function for the left subtree with the range `[start, root_val - 1]` and store the result in `left_trees`. + - Recursively call the `generate_trees` function for the right subtree with the range `[root_val + 1, end]` and store the result in `right_trees`. + +### Step 8: Generate Trees + +- Nested loop through each combination of `left_tree` in `left_trees` and `right_tree` in `right_trees`: + - Create a new `TreeNode` instance with `root_val` as the value, `left_tree` as the left child, and `right_tree` as the right child. + - Append the new `TreeNode` to the `trees` list. + +### Step 9: Memoize and Return Trees + +- Store the `trees` list in the `memo` dictionary with the key `(start, end)`. +- Return the `trees` list. + +### Step 10: Generate All Trees + +- Outside the `generate_trees` function, call `generate_trees` initially with arguments `1` and `n` to generate all unique binary search trees with `n` nodes. + +### Step 11: Return Result + +- Return the list of generated trees. + +This algorithm generates all possible unique binary search trees with `n` nodes by considering different ranges of root values and recursively generating left and right subtrees for each possible root value. The `memo` dictionary is used to store previously computed results, reducing redundant calculations and improving the efficiency of the algorithm. + + + + +## Code + +### C++ +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector generateTrees(int n) { + if (n == 0) { + return vector(); + } + + unordered_map> memo; + + return generateTreesHelper(1, n, memo); + } + +private: + vector generateTreesHelper(int start, int end, unordered_map>& memo) { + string key = to_string(start) + "-" + to_string(end); + if (memo.find(key) != memo.end()) { + return memo[key]; + } + + vector trees; + if (start > end) { + trees.push_back(nullptr); + return trees; + } + + for (int rootVal = start; rootVal <= end; rootVal++) { + vector leftTrees = generateTreesHelper(start, rootVal - 1, memo); + vector rightTrees = generateTreesHelper(rootVal + 1, end, memo); + + for (TreeNode* leftTree : leftTrees) { + for (TreeNode* rightTree : rightTrees) { + TreeNode* root = new TreeNode(rootVal); + root->left = leftTree; + root->right = rightTree; + trees.push_back(root); + } + } + } + + memo[key] = trees; + return trees; + } +}; +``` + +### Python +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def generateTrees(self, n: int) -> List[Optional[TreeNode]]: + if n == 0: + return [] + + memo = {} + + def generate_trees(start, end): + if (start, end) in memo: + return memo[(start, end)] + + trees = [] + if start > end: + trees.append(None) + return trees + + for root_val in range(start, end + 1): + left_trees = generate_trees(start, root_val - 1) + right_trees = generate_trees(root_val + 1, end) + + for left_tree in left_trees: + for right_tree in right_trees: + root = TreeNode(root_val, left_tree, right_tree) + trees.append(root) + + memo[(start, end)] = trees + return trees + + return generate_trees(1, n) +``` + +### Java +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List generateTrees(int n) { + if (n == 0) { + return new ArrayList<>(); + } + + Map> memo = new HashMap<>(); + + return generateTreesHelper(1, n, memo); + } + + private List generateTreesHelper(int start, int end, Map> memo) { + String key = start + "-" + end; + if (memo.containsKey(key)) { + return memo.get(key); + } + + List trees = new ArrayList<>(); + if (start > end) { + trees.add(null); + return trees; + } + + for (int rootVal = start; rootVal <= end; rootVal++) { + List leftTrees = generateTreesHelper(start, rootVal - 1, memo); + List rightTrees = generateTreesHelper(rootVal + 1, end, memo); + + for (TreeNode leftTree : leftTrees) { + for (TreeNode rightTree : rightTrees) { + TreeNode root = new TreeNode(rootVal); + root.left = leftTree; + root.right = rightTree; + trees.add(root); + } + } + } + + memo.put(key, trees); + return trees; + } +} +``` + +## Conclusion + +## Complexity +- Time complexity: `O(C(n))` +C is Catalan number. + +- Space complexity: `O(C(n))` +C is Catalan number. + + diff --git a/solutions/lc-solutions/0000-0099/0096-Unique-Binary-Search-Trees.md b/solutions/lc-solutions/0000-0099/0096-Unique-Binary-Search-Trees.md new file mode 100644 index 0000000..d268da7 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0096-Unique-Binary-Search-Trees.md @@ -0,0 +1,115 @@ +--- +id: unique-binary-search-tree +title: Unique Binary Search Tree +difficulty: Medium +sidebar_label: 0096- Unique Binary Search Tree +tags: + - Binary Search Tree + - LeetCode Medium +--- + +## Problem + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Unique Binary Search Tree ](https://leetcode.com/problems/unique-binary-search-trees/description/) | [Unique Binary Search Tree Solution on LeetCode](https://leetcode.com/problems/unique-binary-search-trees/solutions/4945144/easy-recursion-dynamic-programming-c-solution-beats-100) | [Khushi Kalra](https://leetcode.com/u/abckhush/) | + +## Problem Description +Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. + +### Examples +**Example 1:** +```plaintext +Input: n = 3 +Output: 5 +``` +**Example 2:** +```plaintext +Input: n = 1 +Output: 1 +``` + +### Constraints: +`1 <= n <= 19` + +## Approach#1 : RECURSION +We use a recursive function numTrees(n) where numTrees(n) returns the number of unique BSTs that can be formed with n nodes. The following steps outline the approach: + +1. Base Cases: +If n is 0 or 1, return 1. There is exactly one unique BST that can be formed with 0 or 1 nodes: +- numTrees(0) = 1: An empty tree is considered one unique BST. +- numTrees(1) = 1: A single-node tree is also one unique BST. + +2. Recursive Calculation: +- Initialize count to 0. This variable will accumulate the total number of unique BSTs for n nodes. +- For each i from 1 to n, consider i as the root of the BST: + - The left subtree will have i-1 nodes. + - The right subtree will have n-i nodes. +- The total number of unique BSTs with i as the root is the product of the number of unique BSTs for the left and right subtrees. +- Accumulate the results in count by adding the product of the number of unique BSTs for the left and right subtrees: +`count += numTrees(i-1) * numTrees(n-i)` + +3. Return the Result: +- After computing the total count for all possible roots from 1 to n, return count. + +### Complexity +1. Time complexity: $$O(2^n)$$ +2. Space complexity: $$O(n)$$ + +### Code +```cpp +class Solution { +public: + int numTrees(int n) { + if(n==0 || n==1) return 1; + int count=0; + for(int i=1; i<=n; i++){ + count= count + (numTrees(i-1)*numTrees(n-i)); + } + return count; + } +}; +``` + +## Approach#2: DYNAMIC PROGRAMMING +We use a dynamic programming array dp where dp[i] represents the number of unique BSTs that can be formed with i nodes. The following steps outline the approach: + +1. Initialization: +- Create a dynamic programming array dp of size n+1 initialized with zeros. +- Set the base cases: + - dp[0] = 1: An empty tree is considered one unique BST. + - dp[1] = 1: A single-node tree is also one unique BST. + +2. Filling the DP Array: +- Iterate over the number of nodes from 2 to n (let's call this i). +- For each i, consider each node j (from 1 to i) as the root of the BST. +- The number of unique BSTs with i nodes can be computed as the sum of all possible left and right subtrees: +- The left subtree will have j-1 nodes. +- The right subtree will have i-j nodes. +- Update the dp[i] value as the sum of the products of the number of unique BSTs for the left and right subtrees: +`dp[i] += dp[j-1] * dp[i-j]` + +3. Return the Result: +- After filling the dp array, dp[n] will contain the number of unique BSTs that can be formed with n nodes. + +### Complexity +1. Time complexity: $$O(n^2)$$ +2. Space complexity: $$O(n)$$ + +### Code +```cpp +class Solution { +public: + int numTrees(int n) { + vectordp(n+1, 0); + dp[0]=1; + dp[1]=1; + for(int i=2; i<=n; i++){ + for(int j=1; j<=i; j++){ + dp[i]= dp[i]+ dp[i-j]*dp[j-1]; + } + } + return dp[n]; + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/0000-0099/0097-Interleaving-String.md b/solutions/lc-solutions/0000-0099/0097-Interleaving-String.md new file mode 100644 index 0000000..f79ed96 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0097-Interleaving-String.md @@ -0,0 +1,225 @@ +--- +id: Interleaving-Strings +title: Interleaving Strings +sidebar_label: Interleaving Strings +tags: + - Dynamic Programming + - Strings + - Interleaving String +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Interleaving-Strings](https://leetcode.com/problems/Interleaving-Strings/description/) | [Interleaving-Strings Solution on LeetCode](https://leetcode.com/problems/Interleaving-Strings/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +Given strings `s1`, `s2`, and `s3`, determine whether `s3` is formed by an interleaving of `s1` and `s2`. + +An interleaving of two strings `s` and `t` is a configuration where `s` and `t` are divided into `n` and `m` substrings respectively, such that: + +- `s = s1 + s2 + ... + sn` +- `t = t1 + t2 + ... + tm` +- `|n - m| <= 1` + +The interleaving is `s1 + t1 + s2 + t2 + s3 + t3 + ...` or `t1 + s1 + t2 + s2 + t3 + s3 + ...`. + +**Note:** `a + b` is the concatenation of strings `a` and `b`. + +### Examples + +#### Example 1: + +**Input:** `s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"` +**Output:** `true` +**Explanation:** +One way to obtain `s3` is: +Split `s1` into `s1 = "aa" + "bc" + "c"`, and `s2` into `s2 = "dbbc" + "a"`. +Interleaving the two splits, we get `"aa" + "dbbc" + "bc" + "a" + "c" = "aadbbcbcac"`. +Since `s3` can be obtained by interleaving `s1` and `s2`, we return `true`. + +#### Example 2: + +**Input:** `s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"` +**Output:** `false` +**Explanation:** +Notice how it is impossible to interleave `s2` with any other string to obtain `s3`. + +#### Example 3: + +**Input:** `s1 = "", s2 = "", s3 = ""` +**Output:** `true` + + +### Constraints +- $0 \leq \text{s1.length}, \text{s2.length} \leq 100$ +- $0 \leq \text{s3.length} \leq 200$ +- $\text{s1}$, $\text{s2}$, and $\text{s3}$ consist of lowercase English letters.$ + +## Approach + +To determine if `s3` is an interleaving of `s1` and `s2`, we can use dynamic programming. We define a 2D boolean DP array `dp` where `dp[i][j]` represents whether `s3[0:i+j]` can be formed by interleaving `s1[0:i]` and `s2[0:j]`. + +### Step-by-Step Algorithm + +1. Initialize a 2D DP array `dp` of size `(len(s1) + 1) x (len(s2) + 1)`. +2. `dp[0][0]` is `True` because an empty `s3` can be formed by interleaving two empty strings. +3. Fill the first row and column of `dp`: + - `dp[i][0]` is `True` if `s1[:i]` matches `s3[:i]`. + - `dp[0][j]` is `True` if `s2[:j]` matches `s3[:j]`. +4. Fill the rest of the `dp` array: + - `dp[i][j]` is `True` if either of the following is `True`: + - `dp[i-1][j]` is `True` and `s1[i-1] == s3[i+j-1]` + - `dp[i][j-1]` is `True` and `s2[j-1] == s3[i+j-1]` +5. The result is `dp[len(s1)][len(s2)]`. + +## Solution in Python + +```python +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + if len(s1) + len(s2) != len(s3): + return False + + dp = [[False] * (len(s2) + 1) for _ in range(len(s1) + 1)] + dp[0][0] = True + + for i in range(1, len(s1) + 1): + dp[i][0] = dp[i-1][0] and s1[i-1] == s3[i-1] + + for j in range(1, len(s2) + 1): + dp[0][j] = dp[0][j-1] and s2[j-1] == s3[j-1] + + for i in range(1, len(s1) + 1): + for j in range(1, len(s2) + 1): + dp[i][j] = (dp[i-1][j] and s1[i-1] == s3[i+j-1]) or (dp[i][j-1] and s2[j-1] == s3[i+j-1]) + + return dp[len(s1)][len(s2)] +``` + +## Solution in Java +```java +class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + if (s1.length() + s2.length() != s3.length()) { + return false; + } + + boolean[][] dp = new boolean[s1.length() + 1][s2.length() + 1]; + dp[0][0] = true; + + for (int i = 1; i <= s1.length(); i++) { + dp[i][0] = dp[i-1][0] && s1.charAt(i-1) == s3.charAt(i-1); + } + + for (int j = 1; j <= s2.length(); j++) { + dp[0][j] = dp[0][j-1] && s2.charAt(j-1) == s3.charAt(j-1); + } + + for (int i = 1; i <= s1.length(); i++) { + for (int j = 1; j <= s2.length(); j++) { + dp[i][j] = (dp[i-1][j] && s1.charAt(i-1) == s3.charAt(i+j-1)) || (dp[i][j-1] && s2.charAt(j-1) == s3.charAt(i+j-1)); + } + } + + return dp[s1.length()][s2.length()]; + } +} +``` + +## Solution in C++ +```cpp +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + if (s1.length() + s2.length() != s3.length()) { + return false; + } + + vector> dp(s1.length() + 1, vector(s2.length() + 1, false)); + dp[0][0] = true; + + for (int i = 1; i <= s1.length(); i++) { + dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]; + } + + for (int j = 1; j <= s2.length(); j++) { + dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]; + } + + for (int i = 1; i <= s1.length(); i++) { + for (int j = 1; j <= s2.length(); j++) { + dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1]); + } + } + + return dp[s1.length()][s2.length()]; + } +}; +``` + +## Solution in C +```c +#include +#include + +bool isInterleave(char* s1, char* s2, char* s3) { + int len1 = strlen(s1), len2 = strlen(s2), len3 = strlen(s3); + if (len1 + len2 != len3) { + return false; + } + + bool dp[len1 + 1][len2 + 1]; + memset(dp, false, sizeof(dp)); + dp[0][0] = true; + + for (int i = 1; i <= len1; i++) { + dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]; + } + + for (int j = 1; j <= len2; j++) { + dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]; + } + + for (int i = 1; i <= len1; i++) { + for (int j = 1; j <= len2; j++) { + dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1]); + } + } + + return dp[len1][len2]; +} +``` + +## Solution in JavaScript +```js +var isInterleave = function(s1, s2, s3) { + if (s1.length + s2.length !== s3.length) { + return false; + } + + const dp = Array(s1.length + 1).fill(false).map(() => Array(s2.length + 1).fill(false)); + dp[0][0] = true; + + for (let i = 1; i <= s1.length; i++) { + dp[i][0] = dp[i-1][0] && s1[i-1] === s3[i-1]; + } + + for (let j = 1; j <= s2.length; j++) { + dp[0][j] = dp[0][j-1] && s2[j-1] === s3[j-1]; + } + + for (let i = 1; i <= s1.length; i++) { + for (let j = 1; j <= s2.length; j++) { + dp[i][j] = (dp[i-1][j] && s1[i-1] === s3[i+j-1]) || (dp[i][j-1] && s2[j-1] === s3[i+j-1]); + } + } + + return dp[s1.length][s2.length]; +}; +``` + +## Conclusion +By utilizing dynamic programming, we can efficiently determine whether a given string `s3` is an interleaving of two other strings `s1` and `s2`. This approach ensures that we consider all possible ways to form `s3` from `s1` and `s2` while adhering to the interleaving constraints. diff --git a/solutions/lc-solutions/0000-0099/0098-validate-binary-search-tree.md b/solutions/lc-solutions/0000-0099/0098-validate-binary-search-tree.md new file mode 100644 index 0000000..094fc11 --- /dev/null +++ b/solutions/lc-solutions/0000-0099/0098-validate-binary-search-tree.md @@ -0,0 +1,96 @@ +--- +id: validate-binary-search-tree +title: Validate Binary Search Tree +sidebar_label: 0098 Validate Binary Search Tree +tags: + - tree + - tree traversal + - LeetCode + - C++ +description: "This is a solution to the Validate Binary Search Tree problem on LeetCode." + +--- + +## Problem Description + +Given the root of a binary tree, determine if it is a valid binary search tree (BST). + +A valid BST is defined as follows: + +* The left subtree of a node contains only nodes with keys less than the node's key. +* The right subtree of a node contains only nodes with keys greater than the node's key. +* Both the left and right subtrees must also be binary search trees. + +### Examples + +**Example 1:** + +``` + +Input: root = [2,1,3] +Output: true +``` + +**Example 2:** + +``` +Input: root = [5,1,4,null,null,3,6] +Output: false +``` + +### Constraints + +- The number of nodes in the tree is in the range $[1, 10^4]$. +- $-2^(31) \leq \text{Node.val} \leq 2^(31) - 1$. + +### Approach + +To solve this problem(valid BST) we will do the inorder traversal of the tree as we know in a binary search tree the array of elements which we get after inorder traversal they will be in sorted order so after the inorder traversal we will just have check if the inorder traversal of the given binary search is in sorted order or not. + +#### Code in C++ + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), + * right(right) {} + * }; + */ +class Solution { +public: + // Function for inorder traversal + void inorder(TreeNode* root , vector&a){ + if(root==NULL){ + return; + } + inorder(root->left,a); + a.push_back(root->val); + inorder(root->right,a); + } + bool isValidBST(TreeNode* root) { + vectora,b; + inorder(root,a); + b=a; + for(int i=1;ileft, prev, first, last); + if (prev != NULL) { + if (prev->val > root->val) { + if (first == NULL) { // storing where the order is disturbed + first = prev; + } + + last = root; + } + } + prev = root; + recover(root->right, prev, first, last); + } + void recoverTree(TreeNode* root) { + TreeNode *prev = NULL, *first = NULL, *last = NULL; + recover(root, prev, first, last); + swap(first->val, last->val); //swapping after we get final values where order is distrubed + return; + } +}; +``` + + diff --git a/solutions/lc-solutions/0000-0099/_category_.json b/solutions/lc-solutions/0000-0099/_category_.json new file mode 100644 index 0000000..e4330cf --- /dev/null +++ b/solutions/lc-solutions/0000-0099/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "0000-0099", + "position": 2, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (0000 - 0099)" + } +} diff --git a/solutions/lc-solutions/0000-0099/image-1.png b/solutions/lc-solutions/0000-0099/image-1.png new file mode 100644 index 0000000..50b1fe2 Binary files /dev/null and b/solutions/lc-solutions/0000-0099/image-1.png differ diff --git a/solutions/lc-solutions/0000-0099/image-6.png b/solutions/lc-solutions/0000-0099/image-6.png new file mode 100644 index 0000000..1d08112 Binary files /dev/null and b/solutions/lc-solutions/0000-0099/image-6.png differ diff --git a/solutions/lc-solutions/0000-0099/image.png b/solutions/lc-solutions/0000-0099/image.png new file mode 100644 index 0000000..36b3a7a Binary files /dev/null and b/solutions/lc-solutions/0000-0099/image.png differ diff --git a/solutions/lc-solutions/0100-0199/0100-same-tree.md b/solutions/lc-solutions/0100-0199/0100-same-tree.md new file mode 100644 index 0000000..2bd3a23 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0100-same-tree.md @@ -0,0 +1,142 @@ +--- +id: same-tree +title: Same Tree Solution +sidebar_label: 0100 Same Tree +tags: + - Binary Tree + - Recursion + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Same Tree problem on LeetCode." +--- + +## Problem Description + +Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not. + +Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. + +### Examples + +**Example 1:** + +``` +Input: p = [1,2,3], q = [1,2,3] +Output: true +``` + +**Example 2:** + +``` +Input: p = [1,2], q = [1,null,2] +Output: false +``` + +**Example 3:** + +``` +Input: p = [1,2,1], q = [1,1,2] +Output: false +``` + +### Constraints + +- The number of nodes in both trees is in the range `[0, 100]`. +- $-10^4 <=$ Node.val $<= 10^4$ + +## Solution for Same Tree Problem + +### Intuition + +The intuition behind the solution is to recursively check if two binary trees are identical. If both trees are empty (null), they are considered identical. If only one tree is empty or the values of the current nodes are different, the trees are not identical. Otherwise, we recursively check if the left and right subtrees of both trees are identical. + +### Approach + +1. Check the base case: if both trees are null, return true. +2. Check if only one tree is null or the values of the current nodes are different, return false. +3. Recursively check if the left subtrees of both trees are identical. +4. Recursively check if the right subtrees of both trees are identical. +5. Return the logical AND of the results from steps 3 and 4. + +#### Code in Different Languages + + + + + ```javascript + function isSameTree(p, q) { + if (p === null && q === null) { + return true; + } + if (p === null || q === null || p.val !== q.val) { + return false; + } + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } + ``` + + + + + + ```python + class Solution: + def isSameTree(self, p, q): + if p is None and q is None: + return True + if p is None or q is None or p.val != q.val: + return False + return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) + ``` + + + + + ```java + class Solution { + public boolean isSameTree(TreeNode p, TreeNode q) { + if (p == null && q == null) { + return true; + } + if (p == null || q == null || p.val != q.val) { + return false; + } + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } + } + ``` + + + + + ```cpp + class Solution { + public: + bool isSameTree(TreeNode* p, TreeNode* q) { + if (p == nullptr && q == nullptr) { + return true; + } + if (p == nullptr || q == nullptr || p->val != q->val) { + return false; + } + return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); + } + }; + ``` + + + + +### Complexity Analysis + +- **Time complexity**: The time complexity of the solution is $O(min(N,M))$, where N and M are the number of nodes in the two trees, respectively. This is because we need to visit each node once in order to compare their values. +- **Space complexity**: The space complexity of the solution is $O(min(H1,H2))$, where H1 and H2 are the heights of the two trees, respectively. This is because the space used by the recursive stack is determined by the height of the smaller tree. + +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/generate-parentheses/) +- **Solution Link:** [Generate Parantheses Solution on LeetCode](https://leetcode.com/problems/generate-parentheses/solutions/5016750/easy-recursion-solution-in-c-100-beats-full-expanation-with-example/) +- **Authors GeeksforGeeks Profile:** [Vipul lakum](https://leetcode.com/u/vipul_lakum_02/) + diff --git a/solutions/lc-solutions/0100-0199/0101-symmetric-tree.md b/solutions/lc-solutions/0100-0199/0101-symmetric-tree.md new file mode 100644 index 0000000..44b46e7 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0101-symmetric-tree.md @@ -0,0 +1,311 @@ +--- +id: symmetric-tree +title: Symmetric Tree Solution +sidebar_label: 0101 Symmetric Tree +tags: + - Binary Tree + - Recursion + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Symmetric Tree problem on LeetCode." +--- + +## Problem Description + +Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). + +### Examples + +**Example 1:** + +![LeetCode Problem - Symmetric Tree](https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg) +``` +Input: root = [1,2,2,3,4,4,3] +Output: true +``` + +**Example 2:** + +![LeetCode Problem - Symmetric Tree](https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg) + +``` +Input: root = [1,2,2,null,3,null,3] +Output: false +``` + +### Constraints + +- The number of nodes in the tree is in the range `[1, 1000]`. +- `-100 <= Node.val <= 100` + +--- + +## Solution for Symmetric Tree Problem + +### Intuition And Approach + +To check if a binary tree is symmetric, we need to compare its left subtree and right subtree. We can define a recursive helper function that takes two nodes as input, one from the left subtree and one from the right subtree. The helper function returns true if both nodes are null, or if their values are equal and their subtrees are symmetric. + + + + +### Approach 1 : Recursive + +1. Define a recursive helper function `isMirror(node1, node2)` that returns true if both nodes are null or if their values are equal and their subtrees are symmetric. +2. Start the recursion from the root of the tree using `isMirror(root.left, root.right)`. +3. Return the result of the recursive check. + +#### Code in Different Languages + + + + + ```java + public boolean isSymmetric(TreeNode root) { + return root == null || isSymmetricHelp(root.left, root.right); + } + + private boolean isSymmetricHelp(TreeNode left, TreeNode right) { + if (left == null || right == null) + return left == right; + if (left.val != right.val) + return false; + return isSymmetricHelp(left.left, right.right) && isSymmetricHelp(left.right, right.left); + } + ``` + + + + + ```python + def isSymmetric(self, root: TreeNode) -> bool: + if root is None: + return True + + def isSymmetricHelp(left, right): + if left is None or right is None: + return left == right + if left.val != right.val: + return False + return isSymmetricHelp(left.left, right.right) and isSymmetricHelp(left.right, right.left) + + return isSymmetricHelp(root.left, root.right) + ``` + + + + + ```cpp + bool isSymmetric(TreeNode* root) { + if (root == nullptr) { + return true; + } + return isSymmetricHelp(root->left, root->right); + } + + bool isSymmetricHelp(TreeNode* left, TreeNode* right) { + if (left == nullptr || right == nullptr) + return left == right; + if (left->val != right->val) + return false; + return isSymmetricHelp(left->left, right->right) && isSymmetricHelp(left->right, right->left); + } + ``` + + + + +#### Complexity Analysis + +- Time Complexity: O(n) where n is the number of nodes in the binary tree. +- Space Complexity: O(h) where h is the height of the binary tree. + + + + +### Approach 2 : Non-Recursive (Stack-based) + +1. If the root is null, return true as an empty tree is symmetric. +2. Initialize a stack to store nodes for comparison. +3. If the root's left child is not null, check if the root's right child is also not null. If either is null while the other is not, return false. +4. Push both the left and right children of the root onto the stack. +5. While the stack is not empty: + - If the size of the stack is odd, return false as nodes should be in pairs. + - Pop two nodes from the stack. These nodes should be symmetric. + - Compare their values. If they are not equal, return false. + - For each popped pair of nodes, push their left and right children in the symmetric order onto the stack: + - Push the left child of the left node and the right child of the right node. + - Push the right child of the left node and the left child of the right node. + - If one node has a child while the other does not, return false. +6. If all nodes are processed without mismatch, return true as the tree is symmetric. + +#### Code in Different Languages + + + + + ```java + public boolean isSymmetric(TreeNode root) { + if (root == null) + return true; + + Stack stack = new Stack<>(); + TreeNode left, right; + if (root.left != null) { + if (root.right == null) + return false; + stack.push(root.left); + stack.push(root.right); + } else if (root.right != null) { + return false; + } + + while (!stack.empty()) { + if (stack.size() % 2 != 0) + return false; + right = stack.pop(); + left = stack.pop(); + if (right.val != left.val) + return false; + + if (left.left != null) { + if (right.right == null) + return false; + stack.push(left.left); + stack.push(right.right); + } else if (right.right != null) { + return false; + } + + if (left.right != null) { + if (right.left == null) + return false; + stack.push(left.right); + stack.push(right.left); + } else if (right.left != null) { + return false; + } + } + + return true; + } + ``` + + + + + ```python + def isSymmetric(self, root: TreeNode) -> bool: + if root is None: + return True + + stack = [] + left, right = None, None + if root.left is not None: + if root.right is None: + return False + stack.append(root.left) + stack.append(root.right) + elif root.right is not None: + return False + + while stack: + if len(stack) % 2 != 0: + return False + right = stack.pop() + left = stack.pop() + if right.val != left.val: + return False + + if left.left is not None: + if right.right is None: + return False + stack.append(left.left) + stack.append(right.right) + elif right.right is not None: + return False + + if left.right is not None: + if right.left is None: + return False + stack.append(left.right) + stack.append(right.left) + elif right.left is not None: + return False + + return True + ``` + + + + + ```cpp + bool isSymmetric(TreeNode* root) { + if (root == nullptr) { + return true; + } + + stack stack; + TreeNode *left, *right; + if (root->left != nullptr) { + if (root->right == nullptr) + return false; + stack.push(root->left); + stack.push(root->right); + } else if (root->right != nullptr) { + return false; + } + + while (!stack.empty()) { + if (stack.size() % 2 != 0) + return false; + right = stack.top(); + stack.pop(); + left = stack.top(); + stack.pop(); + if (right->val != left->val) + return false; + + if (left->left != nullptr) { + if (right->right == nullptr) + return false; + stack.push(left->left); + stack.push(right->right); + } else if (right->right != nullptr) { + return false; + } + + if (left->right != nullptr) { + if (right->left == nullptr) + return false; + stack.push(left->right); + stack.push(right->left); + } else if (right->left != nullptr) { + return false; + } + } + + return true; + } + ``` + + + + +#### Complexity Analysis + +- Time Complexity: O(n) where n is the number of nodes in the binary tree. +- Space Complexity: O(n) in the worst case due to the stack. + + + + +## References + +- **LeetCode Problem:** [Symmetric Tree Problem](https://leetcode.com/problems/symmetric-tree/) +- **Solution Link:** [Symmetric Tree Solution on LeetCode](https://leetcode.com/problems/symmetric-tree/solutions/5016750/easy-recursion-solution-in-c-100-beats-full-expanation-with-example/) +- **Authors GeeksforGeeks Profile:** [Vipul lakum](https://leetcode.com/u/vipul_lakum_02/) + +--- diff --git a/solutions/lc-solutions/0100-0199/0102-binary-tree-level-order-traversal.md b/solutions/lc-solutions/0100-0199/0102-binary-tree-level-order-traversal.md new file mode 100644 index 0000000..e256190 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0102-binary-tree-level-order-traversal.md @@ -0,0 +1,520 @@ +--- +id: binary-tree-level-order-traversal +title: Binary Tree Level Order Traversal Solution +sidebar_label: 0102 Binary Tree Level Order Traversal +tags: + - Tree + - Breadth First Search + - Queue + - LeetCode + - Python + - Java + - C++ +description: "This is a solution to the Binary Tree Level Order Traversal problem on LeetCode." +--- + +## Problem Description + +Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). + +### Examples + +**Example 1:** + +![input Tree](https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg) +``` +Input: root = [3,9,20,null,null,15,7] +Output: [[3],[9,20],[15,7]] +``` + +**Example 2:** + +``` +Input: root = [1] +Output: [[1]] +``` + +**Example 3:** + +``` +Input: root = [] +Output: [] +``` + +**Constraints:** + +- The number of nodes in the tree is in the range [0, 2000]. +- $ -1000 <= $ Node.val $ <= 1000 $ + +## Solution for Binary Tree Level Order Traversal Problem + +### Intuition + +To perform a level-order traversal on a binary tree and store the nodes’ values in a 2D vector representing each level, start by initialising an empty queue to hold the level by level nodes. Enqueue the root node into the queue and traverse until the queue is empty. For each level, track the number of nodes in that level, creating a temporary vector to deque and store them. At each node, store its value in the temporary vector and enqueue its left and right children if they exist. Once all the nodes at a level are processed add this 1D temporary vector to the final 2D vector, representing that level. This process repeats until all levels are traversed. Finally, return this 2D vector containing the level order traversal of the binary tree. + +### Algorithm: + +**Step 1:** Initialise an empty queue data structure to store the nodes during traversal. Create a 2D array or a vector of a vector to store the level order traversal. If the tree is empty, return this empty 2D vector. + +**Step 2:** Enqueue the root node i.e. Add the root node of the binary tree to the queue. + +**Step 3:** + +Iterate until the queue is empty: + +- Get the current size of the queue. This size indicates the number of nodes at the current level. +- Create a vector β€˜level’ to store the nodes at the current level. +- Iterate through β€˜size’ number of nodes at the current level: + - Pop the front node from the queue. + - Store the node’s value in the level vector. + - Enqueue the left and right child nodes of the current node (if they exist) into the queue. +- After processing all the nodes at the current level, add the β€˜level’ vector to the β€˜ans’ 2D vector, representing the current level. + +**Step 4:** Once the traversal loop completes i.e. all levels have been processed, return the β€˜ans’ 2D vector containing the level-order traversal. + +### Code in Different Languages + + + + + ```cpp + #include + #include + #include + + using namespace std; + + // TreeNode struct represents + // a node in a binary tree + struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + + // Default constructor for TreeNode + TreeNode() : val(0), left(nullptr), right(nullptr) {} + + // Constructor with a value + // parameter for TreeNode + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + + // Constructor with value, left + // child, and right child + // parameters for TreeNode + TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} + }; + + + class Solution { + public: + // Function to perform level-order + // traversal of a binary tree + vector> levelOrder(TreeNode* root) { + // Create a 2D vector to store levels + vector> ans; + if (root == nullptr) { + // If the tree is empty, + // return an empty vector + return ans; + } + + // Create a queue to store nodes + // for level-order traversal + queue q; + // Push the root node to the queue + q.push(root); + + while (!q.empty()) { + // Get the size of the current level + int size = q.size(); + // Create a vector to store + // nodes at the current level + vector level; + + for (int i = 0; i < size; i++) { + // Get the front node in the queue + TreeNode* node = q.front(); + // Remove the front node from the queue + q.pop(); + // Store the node value + // in the current level vector + level.push_back(node->val); + + // Enqueue the child nodes if they exist + if (node->left != nullptr) { + q.push(node->left); + } + if (node->right != nullptr) { + q.push(node->right); + } + } + // Store the current level + // in the answer vector + ans.push_back(level); + } + // Return the level-order + // traversal of the tree + return ans; + } + }; + + // Function to print + // the elements of a vector + void printVector(const vector& vec) { + // Iterate through the + // vector and print each element + for (int num : vec) { + cout << num << " "; + } + cout << endl; + } + + // Main function + int main() { + // Creating a sample binary tree + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->right = new TreeNode(3); + root->left->left = new TreeNode(4); + root->left->right = new TreeNode(5); + + // Create an instance + // of the Solution class + Solution solution; + // Perform level-order traversal + vector> result = solution.levelOrder(root); + + cout << "Level Order Traversal of Tree: "<< endl; + + // Printing the level order traversal result + for (const vector& level : result) { + printVector(level); + } + + return 0; + } + ``` + + + + + + ``` + #include + #include + #include + + using namespace std; + + // TreeNode struct represents + // a node in a binary tree + struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + + // Default constructor for TreeNode + TreeNode() : val(0), left(nullptr), right(nullptr) {} + + // Constructor with a value + // parameter for TreeNode + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + + // Constructor with value, left + // child, and right child + // parameters for TreeNode + TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} + }; + + + class Solution { + public: + // Function to perform level-order + // traversal of a binary tree + vector> levelOrder(TreeNode* root) { + // Create a 2D vector to store levels + vector> ans; + if (root == nullptr) { + // If the tree is empty, + // return an empty vector + return ans; + } + + // Create a queue to store nodes + // for level-order traversal + queue q; + // Push the root node to the queue + q.push(root); + + while (!q.empty()) { + // Get the size of the current level + int size = q.size(); + // Create a vector to store + // nodes at the current level + vector level; + + for (int i = 0; i < size; i++) { + // Get the front node in the queue + TreeNode* node = q.front(); + // Remove the front node from the queue + q.pop(); + // Store the node value + // in the current level vector + level.push_back(node->val); + + // Enqueue the child nodes if they exist + if (node->left != nullptr) { + q.push(node->left); + } + if (node->right != nullptr) { + q.push(node->right); + } + } + // Store the current level + // in the answer vector + ans.push_back(level); + } + // Return the level-order + // traversal of the tree + return ans; + } + }; + + // Function to print + // the elements of a vector + void printVector(const vector& vec) { + // Iterate through the + // vector and print each element + for (int num : vec) { + cout << num << " "; + } + cout << endl; + } + + // Main function + int main() { + // Creating a sample binary tree + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->right = new TreeNode(3); + root->left->left = new TreeNode(4); + root->left->right = new TreeNode(5); + + // Create an instance + // of the Solution class + Solution solution; + // Perform level-order traversal + vector> result = solution.levelOrder(root); + + cout << "Level Order Traversal of Tree: "<< endl; + + // Printing the level order traversal result + for (const vector& level : result) { + printVector(level); + } + + return 0; + } + ``` + + + + + + ``` + from collections import deque + + # TreeNode class represents + # a node in a binary tree + class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + class Solution: + def levelOrder(self, root): + # Create a list to store levels + ans = [] + if not root: + # If the tree is empty, + # return an empty list + return ans + + # Create a queue to store nodes + # for level-order traversal + q = deque() + # Enqueue the root node + q.append(root) + + while q: + # Get the size of the current level + size = len(q) + # Create a list to store + # nodes at the current level + level = [] + + for i in range(size): + # Get the front node in the queue + node = q.popleft() + # Store the node value + # in the current level list + level.append(node.val) + + # Enqueue the child nodes if they exist + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + + # Store the current level + # in the answer list + ans.append(level) + # Return the level-order + # traversal of the tree + return ans + + # Function to print + # the elements of a list + def printList(lst): + # Iterate through the + # list and print each element + for num in lst: + print(num, end=" ") + print() + + # Main function + if __name__ == "__main__": + # Creating a sample binary tree + root = TreeNode(1) + root.left = TreeNode(2) + root.right = TreeNode(3) + root.left.left = TreeNode(4) + root.left.right = TreeNode(5) + + # Create an instance + # of the Solution class + solution = Solution() + # Perform level-order traversal + result = solution.levelOrder(root) + + print("Level Order Traversal of Tree:") + + # Printing the level order traversal result + for level in result: + printList(level) + ``` + + + + + + ```javascript + // TreeNode class represents + // a node in a binary tree + class TreeNode { + constructor(val = 0, left = null, right = null) { + this.val = val; + this.left = left; + this.right = right; + } + } + + class Solution { + // Function to perform level-order + // traversal of a binary tree + levelOrder(root) { + // Create an array to store levels + let ans = []; + if (!root) { + // If the tree is empty, + // return an empty array + return ans; + } + + // Create a queue to store + // nodes for level-order traversal + let q = []; + // Push the root node to the queue + q.push(root); + + while (q.length > 0) { + // Get the size of the current level + let size = q.length; + // Create an array to store + // nodes at the current level + let level = []; + + for (let i = 0; i < size; i++) { + // Get the front node in the queue + let node = q.shift(); + // Store the node value + // in the current level array + level.push(node.val); + + // Enqueue the child + // nodes if they exist + if (node.left !== null) { + q.push(node.left); + } + if (node.right !== null) { + q.push(node.right); + } + } + // Store the current level + // in the answer array + ans.push(level); + } + // Return the level-order + // traversal of the tree + return ans; + } + } + + // Function to print the + // elements of an array + function printArray(arr) { + // Iterate through the + // array and print each element + for (let num of arr) { + console.log(num + " "); + } + console.log("\n"); + } + + // Creating a sample binary tree + let root = new TreeNode(1); + root.left = new TreeNode(2); + root.right = new TreeNode(3); + root.left.left = new TreeNode(4); + root.left.right = new TreeNode(5); + + // Create an instance of the Solution class + let solution = new Solution(); + // Perform level-order traversal + let result = solution.levelOrder(root); + + console.log("Level Order Traversal of Tree: \n"); + + // Printing the level order traversal result + for (let level of result) { + printArray(level); + } + ``` + + + + +#### Complexity Analysis + +- **Time Complexity:** O(N) where N is the number of nodes in the binary tree. Each node of the binary tree is enqueued and dequeued exactly once, hence all nodes need to be processed and visited. Processing each node takes constant time operations which contributes to the overall linear time complexity. + +- **Space Complexity:** O(N) where N is the number of nodes in the binary tree. In the worst case, the queue has to hold all the nodes of the last level of the binary tree, the last level could at most hold N/2 nodes hence the space complexity of the queue is proportional to O(N). The resultant vector answer also stores the values of the nodes level by level and hence contains all the nodes of the tree contributing to O(N) space as well. + +--- + +## References + +- **LeetCode Problem:** [Symmetric Tree Problem](https://leetcode.com/problems/symmetric-tree/) +- **Solution Link:** [Symmetric Tree Solution on LeetCode](https://leetcode.com/problems/symmetric-tree/solutions/5016750/easy-recursion-solution-in-c-100-beats-full-expanation-with-example/) +- **Authors GeeksforGeeks Profile:** [Vipul lakum](https://leetcode.com/u/vipul_lakum_02/) diff --git a/solutions/lc-solutions/0100-0199/0103-zigzag-order-traversal.md b/solutions/lc-solutions/0100-0199/0103-zigzag-order-traversal.md new file mode 100644 index 0000000..b76fa14 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0103-zigzag-order-traversal.md @@ -0,0 +1,133 @@ +--- +id: binary-tree-zigzag-level-order-traversal +title: Binary Tree Zigzag Level Order Traversal +sidebar_label: 0103-Zigzag Level Order +tags: + - Tree + - Breadth-First-Search + - C++ +description: "Given a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between)." +--- + +## Problem Description + +Given a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between). + + +### Examples + +**Example 1:** + +![LeetCode Problem - Binary Tree](https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg) +``` +Input: root = [3,9,20,null,null,15,7] +Output: [[3],[20,9],[15,7]] +``` + + +### Constraints + +- The number of nodes in the tree is in the range $[0, 2000]$. +- $-100 \leq \text{Node.val} \leq 100$ + +--- + +## Solution for Binary Tree Problem + +### Intuition And Approach + +To perform a zigzag level order traversal, we can use a breadth-first search (BFS) with a queue. We'll use a boolean flag to determine the direction of traversal at each level. + +1. **Breadth-First Search (BFS):** Traverse the tree level by level. +2. **Direction Toggle:** Use a flag to toggle the direction of traversal for each level (left-to-right or right-to-left). + + + + + +#### Code in Different Languages + + + + + ```java + class Solution { + public int minDepth(TreeNode root) { + if (root == null) return 0; + Queue queue = new LinkedList<>(); + queue.offer(root); + int depth = 1; + while (!queue.isEmpty()) { + int levelSize = queue.size(); + for (int i = 0; i < levelSize; i++) { + TreeNode node = queue.poll(); + if (node.left == null && node.right == null) return depth; + if (node.left != null) queue.offer(node.left); + if (node.right != null) queue.offer(node.right); + } + depth++; + } + return depth; + } +} + ``` + + + + + ```python + class Solution: + def minDepth(self, root): + if not root: + return 0 + queue = collections.deque([(root, 1)]) + while queue: + node, depth = queue.popleft() + if not node.left and not node.right: + return depth + if node.left: + queue.append((node.left, depth + 1)) + if node.right: + queue.append((node.right, depth + 1)) + ``` + + + + + ```cpp + class Solution { +public: + int minDepth(TreeNode* root) { + if (!root) return 0; + queue q; + q.push(root); + int depth = 1; + while (!q.empty()) { + int levelSize = q.size(); + for (int i = 0; i < levelSize; ++i) { + TreeNode* node = q.front(); + q.pop(); + if (!node->left && !node->right) return depth; // Leaf node found + if (node->left) q.push(node->left); + if (node->right) q.push(node->right); + } + ++depth; + } + return depth; + } +}; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ where n is the number of nodes in the binary tree. +- Space Complexity: $O(h)$ where h is the height of the binary tree. + + + + + +--- diff --git a/solutions/lc-solutions/0100-0199/0104-maximum-depth-of-binary-tree.md b/solutions/lc-solutions/0100-0199/0104-maximum-depth-of-binary-tree.md new file mode 100644 index 0000000..34f2960 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0104-maximum-depth-of-binary-tree.md @@ -0,0 +1,409 @@ +--- +id: max-depth-binary-tree +title: Maximum Depth of Binary Tree Solution +sidebar_label: 0104 Maximum Depth of Binary Tree +tags: + - Binary Tree + - Depth-First Search + - Breadth-First Search + - Recursion + - LeetCode + - C++ + - Java + - Python +description: "This is a solution to the Maximum Depth of Binary Tree problem on LeetCode." +--- + + +## Problem Description + +Given the root of a binary tree, return its maximum depth. + +A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. + +### Examples + +**Example 1:** + +![Input Tree](https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg) + +``` +Input: root = [3,9,20,null,null,15,7] +Output: 3 +``` + +**Example 2:** + +``` +Input: root = [1,null,2] +Output: 2 +``` + +### Constraints + +- The number of nodes in the tree is in the range `[0, 104]`. +- `-100 <= Node.val <= 100` + +## Solution for Maximum Depth of Binary Tree Problem + + + + +### Recursive (DFS) Approach + +#### Intuition + +To find the maximum depth of a binary tree, we can use a depth-first search (DFS) approach. We recursively find the maximum depth of the left and right subtrees and return the maximum of the two depths plus one (to account for the current level). + +#### Approach + +1. Implement a recursive function `maxDepth(root)` that returns the maximum depth of the binary tree rooted at `root`. +2. If the root is `null`, return 0. +3. Recursively find the maximum depth of the left and right subtrees. +4. Return the maximum of the left and right subtree depths plus one. + +#### Implementation + +```jsx live +function MaxDepthOfBinaryTree() { + class TreeNode { + constructor(val = 0, left = null, right = null) { + this.val = val; + this.left = left; + this.right = right; + } + } + + const maxDepth = function (root) { + if (!root) return 0; + const leftDepth = maxDepth(root.left); + const rightDepth = maxDepth(root.right); + return Math.max(leftDepth, rightDepth) + 1; + }; + + const root = new TreeNode(3); + root.left = new TreeNode(9); + root.right = new TreeNode(20); + root.right.left = new TreeNode(15); + root.right.right = new TreeNode(7); + + const result = maxDepth(root); + return ( +
+

+ Input: root = [3,9,20,null,null,15,7] +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function maxDepth(root) { + if (!root) return 0; + const maxLeft = maxDepth(root.left); + const maxRight = maxDepth(root.right); + return Math.max(maxLeft, maxRight) + 1; + } + ``` + + + + + ```typescript + class TreeNode { + val: number; + left: TreeNode | null; + right: TreeNode | null; + constructor(val: number) { + this.val = val; + this.left = null; + this.right = null; + } + } + + function maxDepth(root: TreeNode | null): number { + if (!root) return 0; + const maxLeft: number = maxDepth(root.left); + const maxRight: number = maxDepth(root.right); + return Math.max(maxLeft, maxRight) + 1; + } + ``` + + + + + ```java + public int maxDepth(TreeNode root) { + if (root == null) + return 0; + int maxLeft = maxDepth(root.left); + int maxRight = maxDepth(root.right); + return Math.max(maxLeft, maxRight) + 1; + } + ``` + + + + + ```python + def maxDepth(self, root: TreeNode) -> int: + if root is None: + return 0 + maxLeft = self.maxDepth(root.left) + maxRight = self.maxDepth(root.right) + return max(maxLeft, maxRight) + 1 + ``` + + + + + ```cpp + int maxDepth(TreeNode* root) { + if (!root) + return 0; + int maxLeft = maxDepth(root->left); + int maxRight = maxDepth(root->right); + return max(maxLeft, maxRight) + 1; + } + ``` + + + + +#### Complexity Analysis + +- **Time complexity**: O(n), where n is the number of nodes in the tree. We visit each node once. +- **Space complexity**: O(h), where h is the height of the tree. The space used by the recursive call stack is proportional to the height of the tree. + +
+ + +### Breadth-First Search (BFS) Approach + +#### Intuition + +Another approach to find the maximum depth of a binary tree is to use breadth-first search (BFS). We start from the root node and traverse the tree level by level, incrementing the depth at each level until we reach the deepest leaf node. + +#### Approach + +1. Initialize a queue and push the root node into it. +2. Initialize a variable `depth` to store the maximum depth, initially set to 0. +3. Perform BFS traversal: + - Increment `depth` for each level visited. + - Push all the children of the current level into the queue. +4. Return `depth` after traversing all levels. + +#### Implementation + +```jsx live +function MaxDepthOfBinaryTree() { + class TreeNode { + constructor(val) { + this.val = val; + this.left = null; + this.right = null; + } + } + + // Creating the binary tree + const root = new TreeNode(3); + root.left = new TreeNode(9); + root.right = new TreeNode(20); + root.right.left = new TreeNode(15); + root.right.right = new TreeNode(7); + + const maxDepth = function (root) { + if (!root) return 0; + + let depth = 0; + const queue = [root]; + + while (queue.length) { + const size = queue.length; + for (let i = 0; i < size; i++) { + const node = queue.shift(); + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } + depth++; + } + + return depth; + }; + + const result = maxDepth(root); + return ( +
+

+ Binary Tree: {JSON.stringify(root)} +

+

+ Maximum Depth: {result} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function maxDepth(root) { + if (!root) return 0; + + let depth = 0; + const queue = [root]; + + while (queue.length) { + depth++; + const levelSize = queue.length; + for (let i = 0; i < levelSize; ++i) { + const node = queue.shift(); + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } + } + + return depth; + } + ``` + + + + + ```typescript + class TreeNode { + val: number; + left: TreeNode | null; + right: TreeNode | null; + constructor(val: number) { + this.val = val; + this.left = null; + this.right = null; + } + } + + function maxDepth(root: TreeNode | null): number { + if (!root) return 0; + + let depth = 0; + const queue: TreeNode[] = [root]; + + while (queue.length) { + depth++; + const levelSize = queue.length; + for (let i = 0; i < levelSize; ++i) { + const node = queue.shift()!; + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } + } + + return depth; + } + ``` + + + + + ```java + public int maxDepth(TreeNode root) { + if (root == null) + return 0; + + int depth = 0; + Queue queue = new LinkedList<>(); + queue.offer(root); + while (!queue.isEmpty()) { + ++depth; + int levelSize = queue.size(); + for (int i = 0; i < levelSize; ++i) { + TreeNode node = queue.poll(); + if (node.left != null) + queue.offer(node.left); + if (node.right != null) + queue.offer(node.right); + } + } + return depth; + } + ``` + + + + + ```python + def maxDepth(self, root: TreeNode) -> int: + if root is None: + return 0 + + depth = 0 + queue = [root] + while queue: + depth += 1 + for _ in range(len(queue)): + node = queue.pop(0) + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + return depth + ``` + + + + + ```cpp + int maxDepth(TreeNode *root) { + if (root == NULL) + return 0; + + int depth = 0; + queue q; + q.push(root); + while (!q.empty()) { + ++depth; + int levelSize = q.size(); + for (int i = 0; i < levelSize; ++i) { + TreeNode *node = q.front(); + q.pop(); + if (node->left) + q.push(node->left); + if (node->right) + q.push(node->right); + } + } + return depth; + } + ``` + + + + +#### Complexity Analysis + +- **Time complexity**: O(n), where n is the number of nodes in the tree. We visit each node once. +- **Space complexity**: O(w), where w is the maximum width of the tree (i.e., the number of nodes at the maximum level). In the worst case, the maximum width could be n/2 in a complete binary tree, so the space complexity is O(n). + +
+
+ +## References + +- **LeetCode Problem**: [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/maximum-depth-of-binary-tree/solution/) +- **Authors GeeksforGeeks Profile:** [Vipul lakum](https://leetcode.com/u/vipul_lakum_02/) + +--- diff --git a/solutions/lc-solutions/0100-0199/0105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.md b/solutions/lc-solutions/0100-0199/0105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.md new file mode 100644 index 0000000..c150f59 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.md @@ -0,0 +1,128 @@ +--- +id: Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal +title: Construct Binary Tree from Preorder and Inorder Traversal +sidebar_label: 0105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal +tags: + - Array + - Hash Tabel + - Divide and Conquer + - Tree + - Binary Tree +description: "Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree." +--- + + +### Problem Description + +Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree. + +### Examples + +#### Example 1 + +- **Input:** `preorder = [3,9,20,15,7], inorder=[9,3,15,20,7]` +- **Output:** `[3,9,30,null,null,15,7]` + +#### Example 2 + +- **Input:** `preorder = [-1], inorder=[-1]` +- **Output:** `[-1]` + +### Constraints + +- $1 \leq \text{preorder.length} \leq 3000$ +- $\text{inorder.length} == \text{preorder.length}$ +- $-3000 \leq \text{preorder}[i], \text{inorder}[i] \leq 3000$ +- preorder and inorder consist of unique values. +- Each value of inorder also appears in preorder. +- preorder is guaranteed to be the preorder traversal of the tree. +- inorder is guaranteed to be the inorder traversal of the tree. + +### Solution Code + +#### Python + +```python +class Solution: + def buildTree(self, P: List[int], I: List[int]) -> TreeNode: + M = {I[i]: i for i in range(len(I))} + return self.splitTree(P, M, 0, 0, len(P)-1) + + def splitTree(self, P: List[int], M: dict, pix: int, ileft: int, iright: int) -> TreeNode: + rval = P[pix] + root, imid = TreeNode(rval), M[rval] + if imid > ileft: + root.left = self.splitTree(P, M, pix+1, ileft, imid-1) + if imid < iright: + root.right = self.splitTree(P, M, pix+imid-ileft+1, imid+1, iright) + return root +``` + +#### Java + +```java +class Solution { + public TreeNode buildTree(int[] P, int[] I) { + Map M = new HashMap<>(); + for (int i = 0; i < I.length; i++) + M.put(I[i], i); + return splitTree(P, M, 0, 0, I.length-1); + } + + private TreeNode splitTree(int[] P, Map M, int pix, int ileft, int iright) { + int rval = P[pix], imid = M.get(rval); + TreeNode root = new TreeNode(rval); + if (imid > ileft) + root.left = splitTree(P, M, pix+1, ileft, imid-1); + if (imid < iright) + root.right = splitTree(P, M, pix+imid-ileft+1, imid+1, iright); + return root; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + TreeNode* buildTree(vector& P, vector& I) { + unordered_map M; + for (int i = 0; i < I.size(); i++) + M[I[i]] = i; + return splitTree(P, M, 0, 0, I.size()-1); + } + +private: + TreeNode* splitTree(vector& P, unordered_map& M, int pix, int ileft, int iright) { + int rval = P[pix], imid = M[rval]; + TreeNode* root = new TreeNode(rval); + if (imid > ileft) + root->left = splitTree(P, M, pix+1, ileft, imid-1); + if (imid < iright) + root->right = splitTree(P, M, pix+imid-ileft+1, imid+1, iright); + return root; + } +}; +``` +#### Javascript + +```javascript +var buildTree = function(P, I) { + let M = new Map() + for (let i = 0; i < I.length; i++) + M.set(I[i], i) + return splitTree(P, M, 0, 0, I.length-1) +}; + +var splitTree = function(P, M, pix, ileft, iright) { + let rval = P[pix], + root = new TreeNode(rval), + imid = M.get(rval) + if (imid > ileft) + root.left = splitTree(P, M, pix+1, ileft, imid-1) + if (imid < iright) + root.right = splitTree(P, M, pix+imid-ileft+1, imid+1, iright) + return root +} +``` \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0106-construct-binary-tree-from-inorder.md b/solutions/lc-solutions/0100-0199/0106-construct-binary-tree-from-inorder.md new file mode 100644 index 0000000..e2d77e1 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0106-construct-binary-tree-from-inorder.md @@ -0,0 +1,195 @@ +--- +id: Construct-Binary-Tree-from-Inorder-and-postorder-Traversal +title: Construct Binary Tree from Inorder and Postorder Traversal +sidebar_label: 0106-Construct-Binary-Tree-from-Inorder-and-postorder-Traversal +tags: + - Array + - Hash Tabel + - Divide and Conquer + - Tree + - Binary Tree +description: "Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree. + + " +--- + + + +### Problem Description + +Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree. + + +### Examples + +#### Example 1 + +- **Input:** `inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]` +- **Output:** `[3,9,20,null,null,15,7]` + +#### Example 2 + +- **Input:** `inorder = [-1], postorder=[-1]` +- **Output:** `[-1]` + +### Constraints + +- $1 \leq \text{inorder.length} \leq 3000$ +- $\text{postorder.length} == \text{inorder.length}$ +- $-3000 \leq \text{inorder}[i], \text{postorder}[i] \leq 3000$ +- postorder and inorder consist of unique values. +- Each value of postorder also appears in inorder. +- postorder is guaranteed to be the postorder traversal of the tree. +- inorder is guaranteed to be the inorder traversal of the tree. + +### Solution Code + +#### Python + +```python +class Solution: + def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: + n=len(inorder) + poststart=instart=0 + postend=inend=n-1 + d={} + for i in range(n): + d[inorder[i]]=i + return self.constructTree(postorder,poststart,postend,inorder,instart,inend,d) + + def constructTree(self,postorder,poststart,postend,inorder,instart,inend,d): + if poststart>postend or instart>inend: + return None + root=TreeNode(postorder[postend]) + elem=d[root.val] + nelem=elem-instart + root.left=self.constructTree(postorder,poststart,poststart+nelem-1,inorder,instart,elem-1,d) + root.right=self.constructTree(postorder,poststart+nelem,postend-1,inorder,elem+1,inend,d) + return root +``` + +#### Java + +```java +class Solution +{ + public TreeNode buildTree(int[] inorder, int[] postorder) { + // If either of the input arrays are empty, the tree is empty, so return null + if (inorder.length == 0 || postorder.length == 0) return null; + + // Initialize indices to the last elements of the inorder and postorder traversals + int ip = inorder.length - 1; + int pp = postorder.length - 1; + + // Create an empty stack to help us build the binary tree + Stack stack = new Stack(); + // Initialize prev to null since we haven't processed any nodes yet + TreeNode prev = null; + // Create the root node using the last element in the postorder traversal + TreeNode root = new TreeNode(postorder[pp]); + // Push the root onto the stack and move to the next element in the postorder traversal + stack.push(root); + pp--; + + // Process the rest of the nodes in the postorder traversal + while (pp >= 0) { + // While the stack is not empty and the top of the stack is the current inorder element + while (!stack.isEmpty() && stack.peek().val == inorder[ip]) { + // The top of the stack is the parent of the current node, so pop it off the stack and update prev + prev = stack.pop(); + ip--; + } + // Create a new node for the current postorder element + TreeNode newNode = new TreeNode(postorder[pp]); + // If prev is not null, the parent of the current node is prev, so attach the node as the left child of prev + if (prev != null) { + prev.left = newNode; + // If prev is null, the parent of the current node is the current top of the stack, so attach the node as the right child of the current top of the stack + } else if (!stack.isEmpty()) { + TreeNode currTop = stack.peek(); + currTop.right = newNode; + } + // Push the new node onto the stack, reset prev to null, and move to the next element in the postorder traversal + stack.push(newNode); + prev = null; + pp--; + } + + // Return the root of the binary tree + return root; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + TreeNode* buildTree(vector& inorder, vector& postorder) { + // If either of the input vectors are empty, the tree is empty, so return null + if (inorder.size() == 0 || postorder.size() == 0) return nullptr; + + // Initialize indices to the last elements of the inorder and postorder traversals + int ip = inorder.size() - 1; + int pp = postorder.size() - 1; + + // Create an empty stack to help us build the binary tree + stack st; + // Initialize prev to null since we haven't processed any nodes yet + TreeNode* prev = nullptr; + // Create the root node using the last element in the postorder traversal + TreeNode* root = new TreeNode(postorder[pp]); + // Push the root onto the stack and move to the next element in the postorder traversal + st.push(root); + pp--; + + // Process the rest of the nodes in the postorder traversal + while (pp >= 0) { + // While the stack is not empty and the top of the stack is the current inorder element + while (!st.empty() && st.top()->val == inorder[ip]) { + // The top of the stack is the parent of the current node, so pop it off the stack and update prev + prev = st.top(); + st.pop(); + ip--; + } + // Create a new node for the current postorder element + TreeNode* newNode = new TreeNode(postorder[pp]); + // If prev is not null, the parent of the current node is prev, so attach the node as the left child of prev + if (prev != nullptr) { + prev->left = newNode; + // If prev is null, the parent of the current node is the current top of the stack, so attach the node as the right child of the current top of the stack + } else if (!st.empty()) { + TreeNode* currTop = st.top(); + currTop->right = newNode; + } + // Push the new node onto the stack, reset prev to null, and move to the next element in the postorder traversal + st.push(newNode); + prev = nullptr; + pp--; + } + + // Return the root of the binary tree + return root; + } +}; +``` +#### Javascript + +```javascript +var buildTree = function(inorder, postorder) { + if (inorder.length == 0 || postorder.length == 0) { + return null; + } + var rootVal = postorder[postorder.length - 1]; + var root = new TreeNode(rootVal); + var rootIndex = inorder.indexOf(rootVal); + var leftInorder = inorder.slice(0, rootIndex); + var rightInorder = inorder.slice(rootIndex + 1); + var leftPostorder = postorder.slice(0, leftInorder.length); + var rightPostorder = postorder.slice(leftInorder.length, postorder.length - 1); + root.left = buildTree(leftInorder, leftPostorder); + root.right = buildTree(rightInorder, rightPostorder); + return root; +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0107-Binary-Tree-Level-Order-Traversal-II.md b/solutions/lc-solutions/0100-0199/0107-Binary-Tree-Level-Order-Traversal-II.md new file mode 100644 index 0000000..c9207db --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0107-Binary-Tree-Level-Order-Traversal-II.md @@ -0,0 +1,177 @@ +--- +id: Binary-Tree-Level-Order-Traversal-II +title: Binary Tree Level Order Traversal II +sidebar_label: 0107-Binary-Tree-Level-Order-Traversal-II +tags: + - Tree + - Breadth-First-Search + - Binary Tree +description: "Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root). + + " +--- + + +### Problem Description + +Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root). + + +### Examples + +#### Example 1 + +- **Input:** `root = [3,9,20,null,null,15,7]` +- **Output:** `[[15,7],[9,20],[3]]` + +#### Example 2 + +- **Input:** `root = [1]` +- **Output:** `[[1]]` + +#### Example 3 + +- **Input:** `root = []` +- **Output:** `[]` + +### Constraints + +- The number of nodes in the tree is in the range [0, 2000]. +- $-1000 \leq \text{Node.val} \leq 1000$ + +### Solution Code + +#### Python + +```python +class Solution: + def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]: + result = [] + + if not root: + return result + + queue = [root] + + while queue: + level_size = len(queue) + current_level = [] + + for _ in range(level_size): + node = queue.pop(0) + current_level.append(node.val) + + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + + result.insert(0, current_level) + + return result +``` + +#### Java + +```java +class Solution { + public List> levelOrderBottom(TreeNode root) { + List> lists = new ArrayList<>(); + levelOrderTraversal(root, lists); + Collections.reverse(lists); + return lists; + } + + void levelOrderTraversal(TreeNode root, List> lists) { + if (root == null) { + return; + } + + Queue queue = new LinkedList<>(); + queue.offer(root); + + while (!queue.isEmpty()) { + int levelSize = queue.size(); + List level = new ArrayList<>(); + + for (int i = 0; i < levelSize; i++) { + TreeNode node = queue.poll(); + level.add(node.val); + + if (node.left != null) { + queue.offer(node.left); + } + if (node.right != null) { + queue.offer(node.right); + } + } + + lists.add(level); + } + } +} +``` + +#### C++ + +```cpp + +class Solution { +public: + vector> levelOrderBottom(TreeNode* root) { + if (!root) return {}; + vector> ans; + queue q; + q.push(root); + q.push(NULL); + vector temp; + + while(!q.empty()){ + auto it=q.front(); + q.pop(); + if (it) + temp.push_back(it->val); + if (!it){ + ans.push_back(temp); + temp.clear(); + if (!q.empty()) + q.push(NULL); + } + else{ + if (it->left) + q.push(it->left); + if (it->right) + q.push(it->right); + } + + } + reverse(ans.begin(),ans.end()); + return ans; + }//Hope you would have got it! +}; +``` +#### Javascript + +```javascript +var levelOrderBottom = function (root) { + if(!root) return []; + + const results = []; + const queue = [root]; + + while(queue.length){ + const current_level_length = queue.length; + const current_level_values = []; + + for(let i=0; i < current_level_length; i++){ + const node = queue.shift(); + current_level_values.push(node.val) + if(node.left) queue.push(node.left) + if(node.right) queue.push(node.right) + } + results.unshift(current_level_values) + } + + return results; // we could have use .reverse() here, but using shift is o(n) & faster, whereas sort is n logn +} +``` diff --git a/solutions/lc-solutions/0100-0199/0108-convert-sorted-array-to-binary-search-tree.md b/solutions/lc-solutions/0100-0199/0108-convert-sorted-array-to-binary-search-tree.md new file mode 100644 index 0000000..792a2c2 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0108-convert-sorted-array-to-binary-search-tree.md @@ -0,0 +1,113 @@ +--- +id: convert-sorted-array-to-binary-search-tree +title: Convert Sorted Array to Binary Search Tree +sidebar_label: 0108-convert-sorted-array-to-binary-search-tree +tags: + - Array + - Binary search tree + - Divide and Conquer + - Tree + - Binary Tree +description: "Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree." +--- + + +### Problem Description + +Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. + +### Examples + +#### Example 1 + +- **Input:** ` nums = [-10,-3,0,5,9]` +- **Output:** `[0,-3,9,-10,null,5]` + +#### Example 2 + +- **Input:** ` nums = [1,3]` +- **Output:** `[3,1]` + +### Constraints + +- $1 \leq \text{nums.length} \leq 10^4$ +- $-10^4 \leq \text{nums}[i] \leq 10^4$ +- nums is sorted in a strictly increasing order + +### Solution Code + +#### Python + +```python +class Solution: + def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: + total_nums = len(nums) + if not total_nums: + return None + + mid_node = total_nums // 2 + return TreeNode( + nums[mid_node], + self.sortedArrayToBST(nums[:mid_node]), self.sortedArrayToBST(nums[mid_node + 1 :]) + ) +``` + +#### Java + +```java +class Solution { + public TreeNode sortedArrayToBST(int[] nums) { + int n=nums.length; + if (n ==0) return null; + if (n ==1) { + TreeNode head = new TreeNode(nums[0]); + return head; + } + + TreeNode head = buildBST(nums,0,n-1); + return head; + } + private TreeNode buildBST (int [] nums, int low, int high){ + if(low>high) return null; + + int mid =low+(high-low)/2; + TreeNode node = new TreeNode(nums[mid]); + node.left =buildBST(nums,low,mid-1); + node.right =buildBST(nums,mid+1,high); + return node; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + TreeNode* sortedArrayToBST(vector& nums) { + return constructBSTRecursive(nums, 0, nums.size() - 1); + } + + TreeNode* constructBSTRecursive(vector& nums, int left, int right) { + if(left > right) + return NULL; + int mid = left + (right - left) / 2; + TreeNode* node = new TreeNode(nums[mid]); + node->left = constructBSTRecursive(nums, left, mid - 1); + node->right = constructBSTRecursive(nums, mid + 1, right); + return node; + } +}; +``` +#### Javascript + +```javascript +var sortedArrayToBST = function(nums) { + if(!nums.length) return null; + let mid = Math.floor(nums.length / 2); + let root = new TreeNode(nums[mid]); + root.left = sortedArrayToBST(nums.slice(0, mid)); + root.right = sortedArrayToBST(nums.slice(mid + 1)); + return root; +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0109-convert-sorted-list-to-binary-search-tree.md b/solutions/lc-solutions/0100-0199/0109-convert-sorted-list-to-binary-search-tree.md new file mode 100644 index 0000000..f34b664 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0109-convert-sorted-list-to-binary-search-tree.md @@ -0,0 +1,100 @@ +--- +id: convert-sorted-list-to-binary-search-tree +title: Convert Sorted List to Binary Search Tree +sidebar_label: 0109 Convert Sorted List to Binary Search Tree +tags: + - tree + - tree traversal + - LeetCode + - C++ +description: "This is a solution to the Convert Sorted List to Binary Search Tree problem on LeetCode." +--- + +## Problem Description + +Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced +binary search tree. + +### Examples + +**Example 1:** + +``` + +Input: head = [-10,-3,0,5,9] +Output: [0,-3,9,-10,null,5] +``` + +**Example 2:** + +``` +Input: head = [] +Output: [] +``` + + + +### Constraints + +- The number of nodes in head is in the range $[0, 2 * 10^4]$. +- $-10^5 \leq \text{Node.val} \leq 10^5$. + +### Approach + +To solve this problem(recover BST) as we know that the inorder traversal of binary search tree give us sorted array so when we traverse the array from left to right we will get to know that at some node the previous value will be greater than current value and that will be our first point were order is disturbed store current and its previous node so that we can counter if its an adjacent swap and if the order is disturbed for the second time, just store that node.After all this just swap the first and last value as you can in the below given code. + +#### Code in C++ + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* tree(vector&a){ + if(a.size()==0){ + return NULL; + } + vectorq,w; + for(int i=0;ileft=tree(q); + p->right=tree(w); + return p; + } + TreeNode* sortedListToBST(ListNode* head) { + vectora; + while(head!=NULL){ + a.push_back(head->val); + head=head->next; + } + return tree(a); + + } +}; +``` + + diff --git a/solutions/lc-solutions/0100-0199/0110-balanced-binary-tree.md b/solutions/lc-solutions/0100-0199/0110-balanced-binary-tree.md new file mode 100644 index 0000000..7556e02 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0110-balanced-binary-tree.md @@ -0,0 +1,256 @@ +--- +id: balanced-binary-tree +title: Balanced Binary Tree Solution +sidebar_label: 0110 Balanced Binary Tree +tags: + - Binary Tree + - Depth-First Search + - Recursion + - LeetCode + - C++ + - Java + - Python +description: "This is a solution to the Balanced Binary Tree problem on LeetCode." +--- + +## Problem Description + +Given a binary tree, determine if it is height-balanced. + +A height-balanced binary tree is defined as: + +- A binary tree in which the left and right subtrees of every node differ in height by no more than 1. + +### Examples + +**Example 1:** + +![input Tree](https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg) + +``` +Input: root = [3,9,20,null,null,15,7] +Output: true +``` + +**Example 2:** + +![input Tree](https://assets.leetcode.com/uploads/2020/10/06/balance_2.jpg) +``` +Input: root = [1,2,2,3,3,null,null,4,4] +Output: false +``` + +**Example 3:** + +``` +Input: root = [] +Output: true +``` + +### Constraints + +- The number of nodes in the tree is in the range `[0, 5000]`. +- $ -10^4 <=$ Node.val $<= 10^4 $ + +--- + +## Solution for Balanced Binary Tree Problem + + + + +### Approach 1: Top-Down + +#### Intuition + +This method checks whether the tree is balanced strictly according to the definition of a balanced binary tree: the difference between the heights of the two subtrees is not greater than 1, and both the left and right subtrees are also balanced. With the helper function depth(), we can easily write the code. + +#### Implementation + +Implement a helper function `depth(root)` that returns the depth of the tree rooted at root. +Check if the absolute difference between the depths of the left and right subtrees is not greater than 1. +Recursively check if both the left and right subtrees are balanced. +Return true if the tree is balanced, otherwise return false. + +#### Code in Different Languages + + + + + ```java + class Solution { + public int depth(TreeNode root) { + if (root == null) return 0; + return Math.max(depth(root.left), depth(root.right)) + 1; + } + + public boolean isBalanced(TreeNode root) { + if (root == null) return true; + + int left = depth(root.left); + int right = depth(root.right); + + return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right); + } + } + ``` + + + + + ```python + class Solution: + def depth(self, root: TreeNode) -> int: + if root is None: + return 0 + return max(self.depth(root.left), self.depth(root.right)) + 1 + + def isBalanced(self, root: TreeNode) -> bool: + if root is None: + return True + + left = self.depth(root.left) + right = self.depth(root.right) + + return abs(left - right) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right) + ``` + + + + + ```cpp + class Solution { + public: + int depth(TreeNode* root) { + if (root == nullptr) return 0; + return max(depth(root->left), depth(root->right)) + 1; + } + + bool isBalanced(TreeNode* root) { + if (root == nullptr) return true; + + int left = depth(root->left); + int right = depth(root->right); + + return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right); + } + }; + ``` + + + + +#### Complexity Analysis + +- **Time Complexity**: O(n log n) in the worst case where n is the number of nodes in the tree. We visit each node once, and for each node, we calculate its depth. Since the depth calculation involves traversing the subtree, the overall time complexity is O(n log n). +- **Space Complexity**: O(n) for the recursive call stack. + + + + +### Approach 2: Bottom-Up + +#### Intuition + +The second method is based on DFS. Instead of calling depth() explicitly for each child node, we return the height of the current node in DFS recursion. When the subtree of the current node (inclusive) is balanced, the function dfsHeight() returns a non-negative value as the height. Otherwise, -1 is returned. According to the left height and right height of the two children, the parent node could check if the subtree is balanced and decide its return value. + +#### Implementation + +Implement a helper function dfsHeight(root) that returns the height of the tree rooted at root. +If the subtree rooted at root is balanced, return its height. Otherwise, return -1. +Check if the returned height is -1 to determine if the tree is balanced. + +#### Code in Different Languages + + + + + ```java + class Solution { + public int dfsHeight(TreeNode root) { + if (root == null) return 0; + + int leftHeight = dfsHeight(root.left); + if (leftHeight == -1) return -1; + int rightHeight = dfsHeight(root.right); + if (rightHeight == -1) return -1; + + if (Math.abs(leftHeight - rightHeight) > 1) return -1; + return Math.max(leftHeight, rightHeight) + 1; + } + + public boolean isBalanced(TreeNode root) { + return dfsHeight(root) != -1; + } + } + ``` + + + + + ```python + class Solution: + def dfsHeight(self, root: TreeNode) -> int: + if root is None: + return 0 + + leftHeight = self.dfsHeight(root.left) + if leftHeight == -1: + return -1 + right + + Height = self.dfsHeight(root.right) + if rightHeight == -1: + return -1 + + if abs(leftHeight - rightHeight) > 1: + return -1 + return max(leftHeight, rightHeight) + 1 + + def isBalanced(self, root: TreeNode) -> bool: + return self.dfsHeight(root) != -1 + ``` + + + + + ```cpp + class Solution { + public: + int dfsHeight(TreeNode* root) { + if (root == nullptr) return 0; + + int leftHeight = dfsHeight(root->left); + if (leftHeight == -1) return -1; + int rightHeight = dfsHeight(root->right); + if (rightHeight == -1) return -1; + + if (abs(leftHeight - rightHeight) > 1) return -1; + return max(leftHeight, rightHeight) + 1; + } + + bool isBalanced(TreeNode* root) { + return dfsHeight(root) != -1; + } + }; + ``` + + + + +#### Complexity Analysis + +- **Time Complexity**: O(n) in the worst case where n is the number of nodes in the tree. Each node is visited once. +- **Space Complexity**: O(n) for the recursive call stack. + + + + +## References + +- **LeetCode Problem**: [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/balanced-binary-tree/solution/) +- **Authors GeeksforGeeks Profile:** [Vipul lakum](https://leetcode.com/u/vipul_lakum_02/) + + +--- diff --git a/solutions/lc-solutions/0100-0199/0111-minimum-depth.md b/solutions/lc-solutions/0100-0199/0111-minimum-depth.md new file mode 100644 index 0000000..02bf33b --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0111-minimum-depth.md @@ -0,0 +1,133 @@ +--- +id: minimum-depth-of-binary-tree +title: Minimum Depth of Binary Tree +sidebar_label: 0111-Minimum Depth Of Binary tree +tags: + - Java + - Python + - C++ +description: "Find the minimum depth of a binary tree, which is the number of nodes along the shortest path from the root node down to the nearest leaf node." +--- + +## Problem Description + +Given a binary tree, find its minimum depth. + +The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. + +### Examples + +**Example 1:** + +![LeetCode Problem - Binary Tree](https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg) +``` +Input: root = [3,9,20,null,null,15,7] +Output: 2 +``` + + +### Constraints + +- The number of nodes in the tree is in the range [0, 105]. +- $-100 <= Node.val <= 100$ + +--- + +## Solution for Binary Tree Problem + +### Intuition And Approach + +To find the minimum depth of a binary tree, we can perform a depth-first search (DFS) or a breadth-first search (BFS). Here, we will use BFS for simplicity. + +Breadth-First Search (BFS): Traverse the tree level by level, stopping as soon as we encounter a leaf node. The depth of the first leaf node encountered will be the minimum depth of the tree. + + + + + +#### Code in Different Languages + + + + + ```java + class Solution { + public int minDepth(TreeNode root) { + if (root == null) return 0; + Queue queue = new LinkedList<>(); + queue.offer(root); + int depth = 1; + while (!queue.isEmpty()) { + int levelSize = queue.size(); + for (int i = 0; i < levelSize; i++) { + TreeNode node = queue.poll(); + if (node.left == null && node.right == null) return depth; + if (node.left != null) queue.offer(node.left); + if (node.right != null) queue.offer(node.right); + } + depth++; + } + return depth; + } +} + ``` + + + + + ```python + class Solution: + def minDepth(self, root): + if not root: + return 0 + queue = collections.deque([(root, 1)]) + while queue: + node, depth = queue.popleft() + if not node.left and not node.right: + return depth + if node.left: + queue.append((node.left, depth + 1)) + if node.right: + queue.append((node.right, depth + 1)) + ``` + + + + + ```cpp + class Solution { +public: + int minDepth(TreeNode* root) { + if (!root) return 0; + queue q; + q.push(root); + int depth = 1; + while (!q.empty()) { + int levelSize = q.size(); + for (int i = 0; i < levelSize; ++i) { + TreeNode* node = q.front(); + q.pop(); + if (!node->left && !node->right) return depth; // Leaf node found + if (node->left) q.push(node->left); + if (node->right) q.push(node->right); + } + ++depth; + } + return depth; + } +}; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ where n is the number of nodes in the binary tree. +- Space Complexity: $O(h)$ where h is the height of the binary tree. + + + + + +--- diff --git a/solutions/lc-solutions/0100-0199/0112-path-sum.md b/solutions/lc-solutions/0100-0199/0112-path-sum.md new file mode 100644 index 0000000..079780a --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0112-path-sum.md @@ -0,0 +1,139 @@ +--- +id: path-sum +title: Path Sum +sidebar_label: 0112-Path Sum +tags: + - Tree + - Depth-First Search + +description: "Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum." +--- + +## Problem Description + +Given the root of a binary tree and an integer `targetSum`, return `true` if the tree has a root-to-leaf path such that adding up all the values along the path equals `targetSum`. + + + +### Examples + +**Example 1:** + +![LeetCode Problem - Binary Tree](https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg) +``` +Input: root = [3,9,20,null,null,15,7] +Output: [[3],[20,9],[15,7]] +``` +**Example 2:** + +![LeetCode Problem - Binary Tree](https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg) +``` +Input: root = [1,2,3] targetSum = 5 +Output: false +``` + +### Constraints + +- The number of nodes in the tree is in the range $[0, 5000]$. + +- $-1000 \leq \text{Node.val} \leq 1000$ + +--- + +## Solution for Binary Tree Problem + +### Intuition And Approach + +To solve this problem, we can use a depth-first search (DFS) to traverse the tree from the root to the leaves, while keeping track of the sum of the values along the current path. + +1. **DFS Traversal:** Traverse the tree from the root to the leaves. +2. **Sum Tracking:** Keep track of the sum of the values along the current path. +3. **Leaf Check:** When a leaf node is reached, check if the path sum equals `targetSum`. + + + + + +#### Code in Different Languages + + + + + ```java + class Solution { + public boolean hasPathSum(TreeNode root, int targetSum) { + if (root == null) return false; + if (root.left == null && root.right == null) return targetSum == root.val; + return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val); + } +} + ``` + + + + + ```python + class Solution: + def hasPathSum(self, root, targetSum): + if not root: + return False + if not root.left and not root.right: + return targetSum == root.val + return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val) + + ``` + + + + + ```cpp + targetSum = 3 + +Output: true + +### Constraints + +- The number of nodes in the tree is in the range $[0, 5000]$. +- $-1000 \leq \text{Node.val} \leq 1000$. +- $-1000 \leq \text{targetSum} \leq 1000$. + +### Approach + +To solve this problem, we can use a depth-first search (DFS) to traverse the tree from the root to the leaves, while keeping track of the sum of the values along the current path. + +1. **DFS Traversal:** Traverse the tree from the root to the leaves. +2. **Sum Tracking:** Keep track of the sum of the values along the current path. +3. **Leaf Check:** When a leaf node is reached, check if the path sum equals `targetSum`. + +### Solution Codes + +#### Codes in Different Languages + + + + + +```cpp +class Solution { +public: + bool hasPathSum(TreeNode* root, int targetSum) { + if (root == nullptr) return false; + if (root->left == nullptr && root->right == nullptr) return targetSum == root->val; + return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val); + } +}; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ where n is the number of nodes in the binary tree. +- Space Complexity: $O(h)$ where h is the height of the tree. + + + + + +--- diff --git a/solutions/lc-solutions/0100-0199/0113-path-sum-II.md b/solutions/lc-solutions/0100-0199/0113-path-sum-II.md new file mode 100644 index 0000000..028abb7 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0113-path-sum-II.md @@ -0,0 +1,161 @@ +--- +id: path-sum-II +title: Path Sum-II +sidebar_label: 0113-Path Sum-II +tags: + - Tree + - Depth-First Search + +description: "Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references." +--- + +## Problem Description + +Given the `root` of a binary tree and an integer `targetSum`, return all `root-to-leaf `paths where the sum of the node values in the path equals `targetSum`. Each path should be returned as a list of the node values, not node references. + +A` root-to-leaf` path is a path starting from the root and ending at any leaf node. A leaf is a node with no children. + + + +### Examples + +**Example 1:** + +![LeetCode Problem - Binary Tree](https://assets.leetcode.com/uploads/2021/01/18/pathsumii1.jpg) +``` +Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 +Output: [[5,4,11,2],[5,8,4,5]] +Explanation: There are two paths whose sum equals targetSum: +5 + 4 + 11 + 2 = 22 +5 + 8 + 4 + 5 = 22 +``` +**Example 2:** + +![LeetCode Problem - Binary Tree](https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg) +``` +Input: root = [1,2,3], targetSum = 5 +Output: [] +``` + +**Example 3:** +``` +Input: root = [1,2], targetSum = 0 +Output: [] +``` + +### Constraints + +- The number of nodes in the tree is in the range `[0, 5000]`. +- `1000 <= Node.val <= 1000` +- `1000 <= targetSum <= 1000` + +#### Code in Different Languages + +### C++ +```c++ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> ans; + void helper(TreeNode* root,int targetsum,int currentsum,vector&v){ + if(root==nullptr){ + return; + } + v.push_back(root->val); + currentsum+=root->val; + if(targetsum==currentsum&&root->left==nullptr&&root->right==nullptr){ + ans.push_back(v); + } + helper(root->left,targetsum,currentsum,v); + helper(root->right,targetsum,currentsum,v); + v.pop_back(); + } + vector> pathSum(TreeNode* root, int targetSum) { + if(root==nullptr){ + return ans; + } + ans.clear(); + vector v; + helper(root,targetSum,0,v); + return ans; + } +}; +``` + +### Java +```java + +class Solution { + public void backtrack(TreeNode root,int target, List> ans, List list){ + if(root==null){ + return; + } + list.add(root.val); + if(root.left ==null && root.right==null && root.val==target){ + ans.add(new ArrayList<>(list)); + }else{ + backtrack(root.left,target-root.val,ans,list); + backtrack(root.right,target-root.val,ans,list); + } + list.remove(list.size()-1); + } + public List> pathSum(TreeNode root, int targetSum) { + List> ans = new ArrayList<>(); + backtrack(root,targetSum,ans, new ArrayList<>()); + return ans; + } +} +``` + +### Python +```Python + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]: + if not root: + return [] + # dfs function to find path from root to leaf + def dfs(root,path): + # to check if node is leaf + if not root.left and not root.right: + # if leaf then check if path sum matches target sum + if targetSum==sum(path+[root.val]): + # if yes then add path to result array + return res.append(path+[root.val]) + # recursively cal for left and right nodes till leaf node + if root.left: + dfs(root.left,path+[root.val]) + if root.right: + dfs(root.right,path+[root.val]) + # create a result array + res=[] + # call the function for root + dfs(root,[]) + return res +``` + +#### Complexity Analysis + +- Time complexity: +`O(n)` +Each node is visited once, so the time complexity is linear with respect to the number of nodes. + +- Space complexity: +`O(n)` +The space complexity is due to the recursion stack and the path list, both of which can go up to the depth of the tree (in the worst case, the depth is n for a skewed tree) diff --git a/solutions/lc-solutions/0100-0199/0114-flatten-binary-tree-to-linked-list.md b/solutions/lc-solutions/0100-0199/0114-flatten-binary-tree-to-linked-list.md new file mode 100644 index 0000000..efc71d7 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0114-flatten-binary-tree-to-linked-list.md @@ -0,0 +1,132 @@ +--- +id: flatten-binary-tree-to-linked-list +title: Flatten Binary Tree To Linked List +sidebar_label: 0114 Flatten Binary Tree To Linked List +tags: + - tree + - tree traversal + - Linked List + - LeetCode + - C++ +description: "This is a solution to the Flatten Binary Tree To Linked List problem on LeetCode." +--- + +## Problem Description + +Given the root of a binary tree, flatten the tree into a "linked list": + +- The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. +- The "linked list" should be in the same order as a pre-order traversal of the binary tree. + +### Examples + +**Example 1:** + +``` + +Input: root = [1,2,5,3,4,null,6] +Output: [1,null,2,null,3,null,4,null,5,null,6] +``` + +**Example 2:** + +``` +Input: root = [] +Output: [] +``` + +**Example 2:** + +``` +Input: root = [0] +Output: [0] +``` + +### Constraints + +- The number of nodes in the tree is in the range $[0, 2000]$. +- $-100 \leq \text{Node.val} \leq 100$. + +### Approach + +To solve this problem(flatten binary tree to linked list) first we will store binary tree nodes value in a vector using preorder traversal then we will convert this vector into another tree (simply linked list) which has no left child only right child as given in question description or we can also use recursion as used in java solution given below. + +#### Code in C++ + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), + * right(right) {} + * }; + */ +class Solution { +public: + + //Funtion to store tree node value in vector using preorder traversal + void preorder(TreeNode* root, vector& a) { + if (root == NULL) { + return; + } + a.push_back(root->val); + preorder(root->left, a); + preorder(root->right, a); + } + + void flatten(TreeNode* root) { // to flatten binary tree to linked list + if (root == NULL) { + return; + } + vector a; + preorder(root, a); + TreeNode* temp = root; + root->left = NULL; + int i = 1; + while (i < a.size()) { + temp->right = new TreeNode(a[i++]); + temp = temp->right; + } + } +}; +``` + + +#### Code in Java + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public void flatten(TreeNode root) { + if(root==null ||root.left==null && root.right==null) + return; + else{ + if(root.left!=null){ + TreeNode temp=root.right; + root.right=root.left; + root.left=null; + TreeNode temp1=root.right; + while(temp1.right!=null) + temp1=temp1.right; + temp1.right=temp; + } + flatten(root.right); + } + } +} + +``` + diff --git a/solutions/lc-solutions/0100-0199/0115-distinct-subsequence.md b/solutions/lc-solutions/0100-0199/0115-distinct-subsequence.md new file mode 100644 index 0000000..162197c --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0115-distinct-subsequence.md @@ -0,0 +1,141 @@ +--- +id: distinct-subsequence +title: Distinct SubSequence +sidebar_label: 0115 Distinct SubSequence +tags: + - String + - DP +description: "Given two strings s and t, return the number of distinct subsequences of s which equals t. +The test cases are generated so that the answer fits on a 32-bit signed integer." +--- + +## Problem Description + +Given two strings s and t, return the number of distinct subsequences of s which equals t. + +The test cases are generated so that the answer fits on a 32-bit signed integer. + +### Examples + +**Example 1:** + +``` +Input: s = "rabbbit", t = "rabbit" +Output: 3 +Explanation: +As shown below, there are 3 ways you can generate "rabbit" from s. +rabbbit +rabbbit +rabbbit +``` + +**Example 2:** + +``` +Input: s = "babgbag", t = "bag" +Output: 5 +Explanation: +As shown below, there are 5 ways you can generate "bag" from s. +babgbag +babgbag +babgbag +babgbag +babgbag +``` + +### Constraints + +- `1 <= s.length, t.length <= 1000` +- s and t consist of English letters. + + +### Institution +The problem is to find the number of distinct subsequences of string s that equal string t. This can be thought of as a dynamic programming problem where we keep track of the number of ways to form the substring t using the substring of s. + + +### Approach +- We use a dynamic programming table dp where dp[i][j] represents the number of distinct subsequences of the first i characters of s that equal the first j characters of t. + +Initialization: + +- If t is empty, there is exactly one subsequence of s that matches t (the empty subsequence). Hence, dp[i][0] = 1 for all i. +- If s is empty but t is not, no subsequences of s can match t. Hence, dp[0][j] = 0 for all j > 0. +Filling the DP Table: + +- If s[i-1] == t[j-1], then the number of ways to form t[0..j-1] from s[0..i-1] is the sum of: +- The number of ways to form t[0..j-1] from s[0..i-2] (excluding the current character of s). +- The number of ways to form t[0..j-2] from s[0..i-2] (including the current character of s). +- If s[i-1] != t[j-1], then the number of ways to form t[0..j-1] from s[0..i-1] is the same as the number of ways to form t[0..j-1] from s[0..i-2] (excluding the current character of s). + + +#### Code in C++ + +```cpp +class Solution { +public: + int numDistinct(string s, string t) { + vector> dp(s.size()+1,vector(t.size()+1,0)); + + for(int i=0;i<=s.size();i++){ + dp[i][0]=1; + } + // for(int j=1;j<=t.size();j++){ + // dp[0][j]=0; + // } + + for(int i=1;i<=s.size();i++){ + for(int j=1;j<=t.size();j++){ + if(s[i-1]==t[j-1]){ + dp[i][j]=dp[i-1][j-1]+dp[i-1][j]; + } + else{ + dp[i][j]=dp[i-1][j]; + } + } + } + return dp[s.size()][t.size()]; + + + } +}; +``` + +#### Code in Java +```Java +class Solution { + public int numDistinct(String s, String t) { + int l1 = s.length(); + int l2 = t.length(); + + int[] dp = new int[l2+1]; + + for(int i = 0; i <= l1; i++){ + + for(int j = l2; j >= 0; j--){ + if(j == 0){ + dp[j] = 1; + } + else if(i == 0){ + dp[j] = 0; + } + else{ + int notPick = dp[j]; + int pick = 0; + if(s.charAt(i-1) == t.charAt(j-1)){ + pick = dp[j - 1]; + } + dp[j] = pick + notPick; + } + } + } + + return dp[l2]; + } +} +``` + + +### Complexity Analysis +- Time complexity: `O(nΓ—m)` + +- Space complexity: `O(nΓ—m)` \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0116-populating-next-right-pointers-in-each-node.md b/solutions/lc-solutions/0100-0199/0116-populating-next-right-pointers-in-each-node.md new file mode 100644 index 0000000..832e1b4 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0116-populating-next-right-pointers-in-each-node.md @@ -0,0 +1,146 @@ +--- +id: 116-populating-next-right-pointers-in-each-node +title: Populating Next Right Pointers in Each Node +sidebar_label: 0116-Populating Next Right Pointers in Each Node +tags: + - Java + - Python + - C++ +description: "Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL." +--- + +## Problem Description + +You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. + +Initially, all next pointers are set to NULL. + +### Examples + +**Example 1:** + +![LeetCode Problem - Binary Tree](https://assets.leetcode.com/uploads/2019/02/14/116_sample.png) +``` +Input: root = [1,2,3,4,5,6,7] +Output: [1,#,2,3,#,4,5,6,7,#] +``` + +**Example 2:** + +``` +Input: root = [] +Output: [] +``` + +### Constraints + +- The number of nodes in the tree is in the range [0, 212 - 1]. +- $-1000 <= Node.val <= 1000$ + +--- + +## Solution for Binary Tree Problem + +### Intuition And Approach + +To populate each next pointer to point to its next right node in a perfect binary tree, we can perform a level order traversal and connect nodes at the same level. + + + + + +#### Code in Different Languages + + + + + ```java + class Solution { + public Node connect(Node root) { + if (root == null) return null; + Queue queue = new LinkedList<>(); + queue.offer(root); + while (!queue.isEmpty()) { + int levelSize = queue.size(); + Node prev = null; + for (int i = 0; i < levelSize; i++) { + Node curr = queue.poll(); + if (prev != null) { + prev.next = curr; + } + if (curr.left != null) queue.offer(curr.left); + if (curr.right != null) queue.offer(curr.right); + prev = curr; + } + } + return root; + } +} + ``` + + + + + ```python + class Solution: + def connect(self, root: 'Node') -> 'Node': + if not root: + return None + queue = collections.deque([root]) + while queue: + level_size = len(queue) + prev = None + for _ in range(level_size): + node = queue.popleft() + if prev: + prev.next = node + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + prev = node + return root + ``` + + + + + ```cpp + class Solution { +public: + Node* connect(Node* root) { + if (!root) return nullptr; + queue q; + q.push(root); + while (!q.empty()) { + int levelSize = q.size(); + Node* prev = nullptr; + for (int i = 0; i < levelSize; ++i) { + Node* node = q.front(); + q.pop(); + if (prev) { + prev->next = node; + } + if (node->left) q.push(node->left); + if (node->right) q.push(node->right); + prev = node; + } + } + return root; + } +}; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ where n is the number of nodes in the binary tree. +- Space Complexity: $O(m)$ where m is the maximum number of nodes at any level in the binary tree. In the worst case, the queue can contain all nodes at the last level, which is at most $2^{h-1}$ where h is the height of the tree. + + + + + +--- diff --git a/solutions/lc-solutions/0100-0199/0117-populating-next-right-pointers-to-each-node-2.md b/solutions/lc-solutions/0100-0199/0117-populating-next-right-pointers-to-each-node-2.md new file mode 100644 index 0000000..4622ded --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0117-populating-next-right-pointers-to-each-node-2.md @@ -0,0 +1,86 @@ +--- +id: 117-populating-next-right-pointer-2 +title: Populating Next Right Pointer To Each Node II +sidebar_label: 0117 Populating Next Right Pointer To Each Node II +tags: + - Java + - Python + - C++ +description: "Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL." +--- + +## Problem Description + +Given the root of a binary tree and an integer `targetSum`, return all root-to-leaf paths where the sum of the node values in the path equals `targetSum`. Each path should be returned as a list of node values, and paths are represented as lists of node values. + + +### Examples + +**Example 1:** + +![LeetCode Problem - Binary Tree](https://assets.leetcode.com/uploads/2019/02/15/117_sample.png) +``` +Input: root = [1,2,3,4,5,null,7] +Output: [1,#,2,3,#,4,5,7,#] +``` + +**Example 2:** + + +``` +Input: root = [] +Output: [] +``` + +### Constraints + +- The number of nodes in the tree is in the range [0, 6000]. +- $-100 <= Node.val <= 100$ +--- + +## Solution for Binary Tree Problem + +### Intuition And Approach + +To find all root-to-leaf paths where the sum equals targetSum, we can use Depth-First Search (DFS). We'll traverse the tree and keep track of the current path and its sum. When a leaf node is reached, we check if the current path's sum equals targetSum. If it does, we add the path to our result list. + + + + + +#### Code in Different Languages + + + + + ```java + private void dfs(TreeNode node, int sum, List path, List> result) { if (node == null) return; path.add(node.val); if (node.left == null && node.right == null && node.val == sum) { result.add(new ArrayList<>(path)); } else { dfs(node.left, sum - node.val, path, result); dfs(node.right, sum - node.val, path, result); } path.remove(path.size() - 1); } + ``` + + + + + ```python + class Solution: def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]: def dfs(node, current_path, current_sum): if not node: return current_path.append(node.val) current_sum += node.val if not node.left and not node.right and current_sum == targetSum: result.append(list(current_path)) else: dfs(node.left, current_path, current_sum) dfs(node.right, current_path, current_sum) current_path.pop() + ``` + + + + + ```cpp + void dfs(TreeNode* node, int sum, vector& path, vector>& result) { if (!node) return; path.push_back(node->val); if (!node->left && !node->right && node->val == sum) { result.push_back(path); } else { dfs(node->left, sum - node->val, path, result); dfs(node->right, sum - node->val, path, result); } path.pop_back(); } + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ where n is the number of nodes in the binary tree. +- Space Complexity: $O(h)$ where h is the height of the binary tree. + + + + + +--- \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0118-pascal's-triangle.md b/solutions/lc-solutions/0100-0199/0118-pascal's-triangle.md new file mode 100644 index 0000000..168ea7d --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0118-pascal's-triangle.md @@ -0,0 +1,146 @@ +--- +id: 118-pascals-triangle +title: Pascal's Triangle +sidebar_label: 0118-Pascal's Triangle +tags: + - C++ + - Java + - Python +description: "Generate the first n rows of Pascal's Triangle." +--- + +## Problem Description + +Given an integer numRows, return the first numRows of Pascal's triangle. + +In Pascal's triangle, each number is the sum of the two numbers directly above it. + +### Examples + +**Example 1:** + +``` +Input: numRows = 5 +Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] +``` + +**Example 2:** + +``` +Input: numRows = 1 +Output: [[1]] +``` + +### Constraints + +- $1 <= numRows <= 30$ + +--- + +## Solution for Binary Tree Problem + +### Intuition And Approach + +To generate Pascal's triangle, we start with the first row [1]. Each subsequent row is generated by adding the number above and to the left with the number above and to the right. We append 1 at the beginning and end of each row. + + + + + +#### Code in Different Languages + + + + + ```java + class Solution { + public List> generate(int numRows) { + List> triangle = new ArrayList<>(); + + if (numRows == 0) { + return triangle; + } + + // First row + triangle.add(new ArrayList<>()); + triangle.get(0).add(1); + + for (int rowNum = 1; rowNum < numRows; rowNum++) { + List row = new ArrayList<>(); + List prevRow = triangle.get(rowNum - 1); + + // First element is always 1 + row.add(1); + + // Each triangle element (except the first and last of each row) + for (int j = 1; j < rowNum; j++) { + row.add(prevRow.get(j - 1) + prevRow.get(j)); + } + + // Last element is always 1 + row.add(1); + + triangle.add(row); + } + + return triangle; + } +} + ``` + + + + + ```python + class Solution: + def generate(self, numRows: int) -> List[List[int]]: + triangle = [] + + for row_num in range(numRows): + row = [1] * (row_num + 1) + + for j in range(1, row_num): + row[j] = triangle[row_num - 1][j - 1] + triangle[row_num - 1][j] + + triangle.append(row) + + return triangle + ``` + + + + + ```cpp + class Solution { +public: + vector> generate(int numRows) { + vector> triangle; + + for (int row_num = 0; row_num < numRows; row_num++) { + vector row(row_num + 1, 1); + + for (int j = 1; j < row_num; j++) { + row[j] = triangle[row_num - 1][j - 1] + triangle[row_num - 1][j]; + } + + triangle.push_back(row); + } + + return triangle; + } +}; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n^2)$ where n is the number of rows. This is because we are generating each element in the triangle, and there are $\frac{n(n+1)}{2}$ elements in total. +- Space Complexity: $O(n^2)$, the space required to store the triangle. + + + + + +--- \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0119-pascal's-triangle-2.md b/solutions/lc-solutions/0100-0199/0119-pascal's-triangle-2.md new file mode 100644 index 0000000..41de9f8 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0119-pascal's-triangle-2.md @@ -0,0 +1,116 @@ +--- +id: 119-pascals-triangle-ii +title: Pascal's Triangle II +sidebar_label: 0119-Pascal's Triangle II +tags: + - C++ + - Java + - Python +description: "Return the kth row of Pascal's triangle." +--- + +## Problem Description + +Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. + +In Pascal's triangle, each number is the sum of the two numbers directly above it. + +### Examples + +**Example 1:** + +``` +Input: rowIndex = 3 +Output: [1,3,3,1] +``` + +**Example 2:** + +``` +Input: rowIndex = 0 +Output: 1 +``` + +### Constraints + +- $0 <= rowIndex <= 33$ + +--- + +## Solution for Balanced Binary Tree Problem + + + + +### Approach + +To generate the kth row of Pascal's Triangle, we can use a single list to iteratively build up the row. By updating the list from the end to the beginning, we ensure that we are always using values from the previous row (or the initial state). + + +#### Code in Different Languages + + + + + ```java + class Solution { + public List getRow(int rowIndex) { + List row = new ArrayList<>(rowIndex + 1); + for (int i = 0; i <= rowIndex; i++) { + row.add(0); + } + row.set(0, 1); + + for (int i = 1; i <= rowIndex; i++) { + for (int j = i; j > 0; j--) { + row.set(j, row.get(j) + row.get(j - 1)); + } + } + + return row; + } +} + ``` + + + + + ```python + class Solution: + def getRow(self, rowIndex: int) -> List[int]: + row = [1] * (rowIndex + 1) + for i in range(2, rowIndex + 1): + for j in range(i - 1, 0, -1): + row[j] += row[j - 1] + return row + ``` + + + + + ```cpp + class Solution { +public: + vector getRow(int rowIndex) { + vector row(rowIndex + 1, 1); + for (int i = 2; i <= rowIndex; i++) { + for (int j = i - 1; j > 0; j--) { + row[j] += row[j - 1]; + } + } + return row; + } +}; + ``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(k^2)$, where k is the given rowIndex. This is because we have nested loops, one iterating up to rowIndex and the other iterating backward up to i. +- **Space Complexity**: $O(k)$, where k is the given rowIndex. This is the space required to store the rowIndexth row. + + + +--- diff --git a/solutions/lc-solutions/0100-0199/0120-triangle.md b/solutions/lc-solutions/0100-0199/0120-triangle.md new file mode 100644 index 0000000..951bc14 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0120-triangle.md @@ -0,0 +1,177 @@ +--- +id: Min falling path sum in a Triangle +title: Min falling path sum in a Triangle +sidebar_label: 120-Min falling path sum in a Triangle +tags: +- Recursion +- Dynamic Programming +- Java +- Cpp +- Python +description: "Given a triangular type matrix we need to return the minimum sum for reaching the bottom from the top . in each step we can either move down or diagonally right" +--- + +## Problem + +Given a triangle array, return the minimum path sum from top to bottom. + +For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row. + +### Examples + +**Example 1:** + +**Input:** triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] +**Output:** 11 +**Explanation:** The triangle looks like: + 2 + 3 4 + 6 5 7 +4 1 8 3 +The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). + +**Example 2:** + +**Input:** triangle = [[-10]] +**Output:** -10 + +### Constraints + +- `1 <= triangle.length <= 200` +- `triangle[0].length == 1` +- `triangle[i].length == triangle[i - 1].length + 1` +- `-104 <= triangle[i][j] <= 104` + + +--- + +## Approach + + Memoization – Starting from the top node, traverse recursively with each node, till the pathsum of that node is calculated. And then store the result in an array. But this will take O(N^2) space to maintain the array. + +### Steps: + +Step 1: Initialize the Memoization Table + +Create a 2D array dp of size n x n, where n is the number of rows in the triangle. Initialize all elements in dp to INT_MAX (or a large negative number) except for the first row, which is set to the corresponding elements in the input triangle. + +Step 2: Fill the Memoization Table + +Iterate through each cell in the triangle, starting from the second row. For each cell (i, j), calculate the minimum sum of the falling path that ends at this cell by considering the two possible paths: + +Directly below: (i+1, j) +Diagonally right: (i+1, j+1) +Update dp[i][j] with the minimum sum of these three paths. + +Step 3: Return the Minimum Falling Path Sum + +The minimum falling path sum is the minimum value in the last row of the dp table. +### Solution + +#### Java Solution + +```java +import java.util.Arrays; + +class GFG { + + public static int helper(int A[][], int i, int j, int dp[][]) + { + if (i == A.length) { + return 0; + } + if (dp[i][j] != -1) return dp[i][j]; + return dp[i][j] = A[i][j] + Math.min(helper(A, i+1, j, dp), helper(A, i+1, j + 1, dp)); + } + + public static int minSumPath(int A[][]) { + int n = A.length; + + int dp[][] = new int[n][n]; + for(int[] row : dp) + Arrays.fill(row,-1); + + return helper(A, 0, 0, dp) ; + } +} + + +``` +### C++ Solution + +```cpp +#include +using namespace std; + +int helper(vector>& A, int i, int j, vector>& dp){ + // Base Case + if(i == A.size() ){ + return 0 ; + } + + // To avoid solving overlapping subproblem + if(dp[i][j] != -1){ + return dp[i][j] ; + } + + + // Add current to the minimum of the next paths + // and store it in dp matrix + return dp[i][j] = A[i][j] + min(helper(A, i+1,j, dp), helper(A,i+1, j+1, dp)) ; + + +} + + +int minSumPath(vector>& A) { + int n = A.size() ; + // Initializating of dp matrix + vector> dp(n, vector(n, -1) ) ; + // calling helper function + return helper(A, 0, 0, dp) ; +} + +``` +### Python Solution + +```python +class Solution: + + def helper(A, i, j, dp): + + # Base Case + if(i == len(A)): + return 0 + + # To avoid solving overlapping subproblem + if(dp[i][j] != -1): + return dp[i][j] + + # Add current to the minimum of the next paths + # and store it in dp matrix + dp[i][j] = A[i][j] + min(helper(A, i+1,j, dp), helper(A,i+1, j+1, dp)) + return dp[i][j] + +def minSumPath(A): + n = len(A) + + # Initializating of dp matrix + dp = [[-1]*n]*n + + # calling helper function + return helper(A, 0, 0, dp) + +# Driver program to test above functions +A = [ [ 2 ],[ 3, 9 ],[ 1, 6, 7 ] ] +print(minSumPath(A)) +``` + +### Complexity Analysis +**Time Complexity:** O(n * m) +>where n and m are no of rows and no of columns respectively. + +**Space Complexity:** O(n*n) +>Reason: We are using the extra space in the form of dp array. + +### References +**LeetCode Problem:** Min falling path sum in a triangle \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0120-trianglepath.md b/solutions/lc-solutions/0100-0199/0120-trianglepath.md new file mode 100644 index 0000000..1eb07c5 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0120-trianglepath.md @@ -0,0 +1,188 @@ +--- +id: Min-falling-path-sum-in-a-Triangle +title: Min falling path sum in a Triangle +sidebar_label: 120-Min falling path sum in a Triangle +tags: +- Recursion +- Dynamic Programming +- Java +- Cpp +- Python +description: "Given a triangular type matrix we need to return the minimum sum for reaching the bottom from the top . in each step we can either move down or diagonally right" +--- + +## Problem + +Given a triangle array, return the minimum path sum from top to bottom. + +For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row. + +### Examples + +**Example 1:** + +**Input:** triangle = [[2],[3,4],[6,5,7],[4,1,8,3]] +**Output:** 11 +**Explanation:** The triangle looks like: + 2 + 3 4 + 6 5 7 +4 1 8 3 +The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). + +**Example 2:** + +**Input:** triangle = [[-10]] +**Output:** -10 + +### Constraints + +- `1 <= triangle.length <= 200` +- `triangle[0].length == 1` +- `triangle[i].length == triangle[i - 1].length + 1` +- `-104 <= triangle[i][j] <= 104` + + +--- + +## Approach + + Memoization – Starting from the top node, traverse recursively with each node, till the pathsum of that node is calculated. And then store the result in an array. But this will take O(N^2) space to maintain the array. + +### Steps: + +Step 1: Initialize the Memoization Table + +Create a 2D array dp of size n x n, where n is the number of rows in the triangle. Initialize all elements in dp to INT_MAX (or a large negative number) except for the first row, which is set to the corresponding elements in the input triangle. + +Step 2: Fill the Memoization Table + +Iterate through each cell in the triangle, starting from the second row. For each cell (i, j), calculate the minimum sum of the falling path that ends at this cell by considering the two possible paths: + +Directly below: (i+1, j) +Diagonally right: (i+1, j+1) +Update dp[i][j] with the minimum sum of these three paths. + +Step 3: Return the Minimum Falling Path Sum + +The minimum falling path sum is the minimum value in the last row of the dp table. +### Solution + +#### Java Solution + +```java +class Solution { + public int minimumTotal(List> triangle) { + int n = triangle.size(); + int[][] dp = new int[n][n]; + + // Initialize the dp array with a large value + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + dp[i][j] = Integer.MAX_VALUE; + } + } + // Recursive function with memoization + return f(triangle, 0, 0, dp); + } + private int f(List> triangle, int i, int j, int[][] dp) { + int n = triangle.size(); + if (i == n - 1) { + return triangle.get(i).get(j); + } + if (dp[i][j] != Integer.MAX_VALUE) { + return dp[i][j]; + } + int down = triangle.get(i).get(j) + f(triangle, i + 1, j, dp); + int diag = triangle.get(i).get(j) + f(triangle, i + 1, j + 1, dp); + dp[i][j] = Math.min(down, diag); + return dp[i][j]; + } + public static void main(String[] args) { + Solution solution = new Solution(); + List> triangle = new ArrayList<>(); + triangle.add(List.of(2)); + triangle.add(List.of(3, 4)); + triangle.add(List.of(6, 5, 7)); + triangle.add(List.of(4, 1, 8, 3)); + System.out.println(solution.minimumTotal(triangle)); // Output: 11 + } +} + + +``` +### C++ Solution + +```cpp +class Solution { +public: + int minimumTotal(vector>& triangle) { + int n = triangle.size(); + vector> dp(n, vector(n, INT_MAX)); + + function f = [&](int i, int j) -> int { + if (i == n - 1) { + return triangle[i][j]; + } + if (dp[i][j] != INT_MAX) { + return dp[i][j]; + } + int down = triangle[i][j] + f(i + 1, j); + int diag = triangle[i][j] + f(i + 1, j + 1); + return dp[i][j] = min(down, diag); + }; + + return f(0, 0); + } +}; + +``` +### Python Solution + +```python +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + n = len(triangle) + dp = [[float('inf')] * n for _ in range(n)] + + def f(i: int, j: int) -> int: + if i == n - 1: + return triangle[i][j] + if dp[i][j] != float('inf'): + return dp[i][j] + down = triangle[i][j] + f(i + 1, j) + diag = triangle[i][j] + f(i + 1, j + 1) + dp[i][j] = min(down, diag) + return dp[i][j] + + return f(0, 0) +``` +### javascript Solution + +```javascript +var minimumTotal = function(triangle) { + + let n = triangle.length; + let dp = Array(n).fill(Number.MAX_VALUE).map(()=> Array(n).fill(Number.MAX_VALUE)); + //let min = Number.MAX_VALUE; + function f(i, j){ + + if(i == n-1){return triangle[i][j];} + if(dp[i][j] != Number.MAX_VALUE) return dp[i][j]; + let down = triangle[i][j] + f(i+1, j); + + let diag = triangle[i][j] + f(i+1, j+1); + return dp[i][j] = Math.min(down, diag); + } + return f(0, 0); +}; +``` +### Complexity Analysis +**Time Complexity:** O(n * m) +>where n and m are no of rows and no of columns respectively. + +**Space Complexity:** O(n*n) +>Reason: We are using the extra space in the form of dp array. + +### References +**LeetCode Problem:** Min falling path sum in a triangle diff --git a/solutions/lc-solutions/0100-0199/0121-best-time-to-buy-sell-stock.md b/solutions/lc-solutions/0100-0199/0121-best-time-to-buy-sell-stock.md new file mode 100644 index 0000000..06c7542 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0121-best-time-to-buy-sell-stock.md @@ -0,0 +1,219 @@ +--- +id: best-time-to-buy-sell-stock +title: Best Time to Buy and Sell Stock Solution +sidebar_label: 0121-Best-Time-to-Buy-and-Sell-Stock +tags: + - Best Time to Buy and Sell Stock + - Array + - LeetCode + - Python + - JavaScript + +description: "This is a solution to the Best Time to Buy and Sell Stock problem on LeetCode." +--- + +In this page, we will solve the Best Time to Buy and Sell Stock problem using a two-pointer approach. We will provide the implementation of the solution in Python and JavaScript. + +## Problem Description + +You are given an array `prices` where `prices[i]` is the price of a given stock on the `i`-th day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return `0`. + +### Examples + +**Example 1:** + +```plaintext +Input: prices = [7,1,5,3,6,4] +Output: 5 +Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. +``` + +**Example 2:** + +```plaintext +Input: prices = [7,6,4,3,1] +Output: 0 +Explanation: In this case, no transactions are done and the max profit = 0. +``` + +### Constraints + +- `1 <= prices.length <= 10^5` +- `0 <= prices[i] <= 10^4` + +--- + +## Solution for Best Time to Buy and Sell Stock Problem + +### Intuition and Approach + +The problem can be solved using a two-pointer approach where we track the minimum price to buy and the maximum profit we can achieve at each step. + + + + +### Approach: Two-pointer + +We use two pointers, `left` (to buy) and `right` (to sell), and iterate through the prices array to find the maximum profit. + +#### Implementation + +```jsx live +function BestTimeToBuyAndSellStock() { + const prices = [7, 1, 5, 3, 6, 4]; // Sample input + + const maxProfit = function (prices) { + let left = 0; // Buy + let right = 1; // Sell + let max_profit = 0; + + while (right < prices.length) { + if (prices[left] < prices[right]) { + let profit = prices[right] - prices[left]; // Our current profit + max_profit = Math.max(max_profit, profit); + } else { + left = right; + } + right++; + } + + return max_profit; + }; + + const result = maxProfit(prices); + return ( +
+

+ Input: prices = {JSON.stringify(prices)} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function maxProfit(prices) { + let left = 0; // Buy + let right = 1; // Sell + let max_profit = 0; + + while (right < prices.length) { + if (prices[left] < prices[right]) { + let profit = prices[right] - prices[left]; // our current profit + max_profit = Math.max(max_profit, profit); + } else { + left = right; + } + right++; + } + + return max_profit; + } + ``` + + + + + ```python + class Solution: + def maxProfit(self, prices: List[int]) -> int: + left, right = 0, 1 # Buy, Sell + max_profit = 0 + + while right < len(prices): + if prices[left] < prices[right]: + profit = prices[right] - prices[left] # our current profit + max_profit = max(max_profit, profit) + else: + left = right + right += 1 + + return max_profit + ``` + + + + + ```java + class Solution { + public int maxProfit(int[] prices) { + int left = 0; // Buy + int right = 1; // Sell + int max_profit = 0; + + while (right < prices.length) { + if (prices[left] < prices[right]) { + int profit = prices[right] - prices[left]; // our current profit + max_profit = Math.max(max_profit, profit); + } else { + left = right; + } + right++; + } + + return max_profit; + } + } + ``` + + + + + ```cpp + class Solution { + public: + int maxProfit(vector& prices) { + int left = 0; // Buy + int right = 1; // Sell + int max_profit = 0; + + while (right < prices.size()) { + if (prices[left] < prices[right]) { + int profit = prices[right] - prices[left]; // our current profit + max_profit = max(max_profit, profit); + } else { + left = right; + } + right++; + } + + return max_profit; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(1)$$ +- Where `n` is the length of the prices array. + +
+
+ +:::tip Note + +By using a two-pointer approach, we can efficiently solve the Best Time to Buy and Sell Stock problem with a linear time complexity. + +::: + +--- + +## References + +- **LeetCode Problem:** [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) +- **Solution Link:** [Best Time to Buy and Sell Stock Solution on LeetCode](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/solutions/) +- **Authors GeeksforGeeks Profile:** [Vipul lakum](https://www.geeksforgeeks.org/user/lakumvipwjge/) + +--- diff --git a/solutions/lc-solutions/0100-0199/0122-best-time-buy-sell-stock-II.md b/solutions/lc-solutions/0100-0199/0122-best-time-buy-sell-stock-II.md new file mode 100644 index 0000000..21f4980 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0122-best-time-buy-sell-stock-II.md @@ -0,0 +1,145 @@ +--- +id: best-time-to-buy-sell-stock-II +title: Best Time to Buy and Sell Stock Solution -II +sidebar_label: 0122 Best-Time-to-Buy-and-Sell-Stock -II +tags: + - Best Time to Buy and Sell Stock + +description: "This is a solution to the Best Time to Buy and Sell Stock problem -II on LeetCode." +--- + + +## Problem Description +You are given an integer array prices where prices[i] is the price of a given stock on the ith day. + +On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. + +Find and return the maximum profit you can achieve. + + +### Examples + +**Example 1:** + +```plaintext +Input: prices = [7,1,5,3,6,4] +Output: 7 +Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. +Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. +Total profit is 4 + 3 = 7. +``` + +**Example 2:** + +```plaintext +Input: prices = [1,2,3,4,5] +Output: 4 +Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. +Total profit is 4. +``` + +**Example 3:** +```plaintext +Input: prices = [7,6,4,3,1] +Output: 0 +Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. +``` + +### Constraints + +- `1 <= prices.length <= 3 * 10^4` +- `0 <= prices[i] <= 10^4` + +--- + +## Solution for Best Time to Buy and Sell Stock Problem +### Intuition +In the given problem, we are provided with an array named "prices," where prices[i] represents the current price of a stock on day i. The task is to determine the maximum profit that can be achieved from selling the stock. + +### Approach +- To solve this question we will use Greedy Algorithm. + +- Now if you don't know anything about Greedy algorithm here is the small explanation of the Greedy. + +- Greedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. In these algorithms, decisions are made based on the information available at the current moment without considering the consequences of these decisions in the future. The key idea is to select the best possible choice at each step, leading to a solution that may not always be the most optimal but is often good enough for many problems. + +### Code Explanation +- Variable Initialization: + +- max is initialized to 0. This variable will accumulate the maximum profit throughout the iteration. +- start is initialized to prices[0], the price of the stock on the first day. This variable represents the buying price of the stock. +- len is initialized to prices.length, the length of the prices array, representing the total number of days. +Iteration: A for loop iterates through the prices array starting from the second element (i = 1) to the end of the array (i < len). This loop is used to calculate the profit for each transaction. + +#### Profit Calculation: + +- Within the loop, there's an if statement checking if the current price (prices[i]) is greater than the buying price (start). If true, it indicates a potential profit opportunity. +- The difference between the current price and the buying price (prices[i] - start) is calculated and added to max. This step simulates selling the stock bought at start price, capturing the profit, and then considering the current price as a new buying price for potential future transactions. +- Regardless of whether a profit was made or not, the start is updated to the current price (prices[i]). This step prepares for the next iteration, considering the current day's price as the new buying price. +- Return Statement: After the loop finishes executing, the method returns the accumulated max value, which represents the maximum profit that could have been achieved based on the given stock prices. + + +### Code in Different languages +#### Code in C++ + +```c++ +class Solution { +public: + int maxProfit(vector& prices) { + int max = 0; + int start = prices[0]; + int len = prices.size(); + for(int i = 1;i& prices) { + int n = prices.size(); + if (n == 0) return 0; + + // Array to store maximum profit from day i to the end + std::vector maxProfitFromRight(n); + int maxPriceFromRight = 0; + int maxProfit = 0; + + // Calculate the maximum profit that can be obtained by one transaction + // starting from each day to the end + for (int i = n - 1; i >= 0; --i) { + maxPriceFromRight = std::max(maxPriceFromRight, prices[i]); + maxProfit = std::max(maxProfit, maxPriceFromRight - prices[i]); + maxProfitFromRight[i] = maxProfit; + } + + // Minimum price from the left + int minPriceFromLeft = INT_MAX; + int totalMaxProfit = 0; + + // Calculate the maximum profit with at most two transactions + for (int i = 0; i < n; ++i) { + minPriceFromLeft = std::min(minPriceFromLeft, prices[i]); + int profitWithCurrentTransaction = prices[i] - minPriceFromLeft; + totalMaxProfit = std::max(totalMaxProfit, profitWithCurrentTransaction + maxProfitFromRight[i]); + } + + return totalMaxProfit; + } +}; +``` + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + if not prices: + return 0 + + # initialize variables for first buy, first sell, second buy, and second sell + buy1, buy2 = float('inf'), float('inf') + sell1, sell2 = 0, 0 + + # iterate over prices to update buy and sell values + for price in prices: + # update first buy and sell values + buy1 = min(buy1, price) + sell1 = max(sell1, price - buy1) + # update second buy and sell values + buy2 = min(buy2, price - sell1) + sell2 = max(sell2, price - buy2) + + return sell2 +``` + + + + +### Complexity Analiysis + +- Time complexity:` O(n)` +- Space complexity: `O(n)` +--- \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0124-binary-tree-path-sum.md b/solutions/lc-solutions/0100-0199/0124-binary-tree-path-sum.md new file mode 100644 index 0000000..b6ee21d --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0124-binary-tree-path-sum.md @@ -0,0 +1,140 @@ +--- +id: binary-tree-path-sum +title: Binary Tree Maximum path sum +sidebar_label: 0124-Binary Tree maximum path sum +tags: + - Binary tree + - LeetCode + - Python + - JavaScript + +description: "This is a solution to the Binary Tree maximum path sum on LeetCode." +--- + + +## Problem Description +A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. + +The path sum of a path is the sum of the node's values in the path. + +Given the root of a binary tree, return the maximum path sum of any non-empty path. + + + +### Examples + +**Example 1:** +![alt](https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg) + +```plaintext +Input: root = [1,2,3] +Output: 6 +Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. +``` + +**Example 2:** + +![alt](https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg) +```plaintext +Input: root = [-10,9,20,null,null,15,7] +Output: 42 +Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. +``` + + +### Constraints + +- The number of nodes in the tree is in the range ${[1, 3 * 10^{4}]}$. +- `1000 <= Node.val <= 1000` + +--- + +## Solution + +### Intuition +Imagine you're an explorer in a magical forest (a binary tree). Each node of the tree is a treasure chest with some gold coins (node values). You want to find the path that gives you the maximum amount of gold. However, you can only travel down the tree, not back up, and you want to maximize your treasure by possibly starting and ending at any node. + +## Approach +Here's how you, the explorer, will find the path with the most gold: + +### Explore and Collect Gold +At each treasure chest (node), you decide whether to collect gold from the left path, the right path, or both. + +### Maximize Gold +As you collect gold from each path, you keep track of the maximum treasure you've found so far. + +### Avoid Negative Gold +If a path leads to a loss (negative value), you pretend it’s zero to avoid losing your precious gold. + +## Step-by-Step Plan + +1. **Recursive Function** + - Use a helper function that returns the maximum gold you can collect starting from any node downwards. + +2. **Track Max Sum** + - As you calculate the maximum gold from the left and right paths, update the global maximum if the total gold from the current node (including left and right paths) is higher. + +3. **Return Path Sum** + - For each node, return the maximum gold that can be collected starting from that node and going down one path (either left or right). + + +### Code in Different languages +#### Code in C++ + +```c++ +class Solution { +public: + + int pathsum(TreeNode* root, int &max_sum){ + + if(root == nullptr) return 0; + + int l_sum = max(0, pathsum(root->left, max_sum)); + int r_sum = max(0, pathsum(root->right, max_sum)); + + max_sum = max(max_sum, root->val + l_sum + r_sum); + + return root->val + max(l_sum , r_sum); + } + + int maxPathSum(TreeNode* root) { + + int max_sum = INT_MIN; + pathsum(root, max_sum); + + return max_sum; + + } +}; +``` + +```python +class Solution: + def maxPathSum(self, root: Optional[TreeNode]) -> int: + + res = root.val + + def dfs(node): + nonlocal res + if not node: return 0 + + leftMax = dfs(node.left) + rightMax = dfs(node.right) + leftMax = max(leftMax, 0) + rightMax = max(rightMax, 0) + + res = max(res, node.val + leftMax + rightMax) + + return node.val + max(leftMax , rightMax) + + dfs(root) + return res +``` + + + + +### Complexity +- Time complexity: $O(n)$ + +- Space complexity: $O(1)$ diff --git a/solutions/lc-solutions/0100-0199/0125-valid-palindrome.md b/solutions/lc-solutions/0100-0199/0125-valid-palindrome.md new file mode 100644 index 0000000..6c08ffd --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0125-valid-palindrome.md @@ -0,0 +1,371 @@ +--- +id: valid-palindrome +title: Valid Palindrome Solution +sidebar_label: 0125 Valid Palindrome +tags: + - String + - Two Pointer + - LeetCode + - Python + - Java + - C++ +description: "This is a solution to the Valid Palindrome problem on LeetCode." +--- + +## Problem Description + +A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. + +Given a string s, return true if it is a palindrome, or false otherwise. + +### Examples + +**Example 1:** + +``` +Input: "A man, a plan, a canal: Panama" +Output: true +Explanation: "amanaplanacanalpanama" is a palindrome. +``` + +**Example 2:** +``` +Input: "race a car" +Output: false +Explanation: "raceacar" is not a palindrome. +``` + +### Constraints +- $1 \leq s.length \leq 2 \times 105$ + +## Solution for Valid Palindrome Problem + + + + +### Approach 1: Brute Force + +#### Intuition + +The brute force approach involves stripping non-alphanumeric characters from the string and then checking if the resulting string is a palindrome by comparing it with its reverse. + +#### Implementation +#### Code in Different Languages + +``` +// JAVA + +class Solution { + public boolean isPalindrome(String s) { + String str = s.toLowerCase(); + str = str.replaceAll("\\s",""); // remove all space in string + str = str.replaceAll("[^a-z0-9]",""); // remove all non-alphanumerical + int i=0,j=str.length()-1; + while(i= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122); +} + ``` + + ``` + //python + + def is_palindrome(s: str) -> bool: + if not s: + return True + cleaned_s = ''.join(ch.lower() for ch in s if ch.isalnum()) + return cleaned_s == cleaned_s[::-1] + + input_str = "A man, a plan, a canal: Panama" + output = is_palindrome(input_str) + + print("Input:", input_str) + print("Output:", output) + +``` + + + ``` + //java + class Solution { + public boolean isPalindrome(String s) { + if (s == null || s.isEmpty()) { + return true; + } + + String cleanedS = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase(); + return cleanedS.equals(new StringBuilder(cleanedS).reverse().toString()); + } + } + ``` + + ``` + //cpp + + class Solution { + public: + bool isPalindrome(string s) { + if (s.empty()) { + return true; + } + + string cleanedS; + for (char ch : s) { + if (isalnum(ch)) { + cleanedS += tolower(ch); + } + } + + string reversedS = cleanedS; + reverse(reversedS.begin(), reversedS.end()); + + return cleanedS == reversedS; + } + }; + + ``` + + +#### Complexity Analysis + +- Time Complexity: O(n), where n is the length of the input string. We iterate through the string once. +- Space Complexity: O(n), where n is the length of the input string. We create a new string to store the cleaned version of the input. + + + + +### Approach 2: Two Pointer + +#### Intuition + +The two-pointer approach involves using two pointers, one starting from the beginning of the string and the other starting from the end. We move both pointers towards the center of the string, comparing characters at each step until they meet or cross each other. + +#### Implementation + +```jsx live +function ValidPalindromeBruteForce() { + const isPalindrome = function (s) { + if (!s) return true; + const cleanedS = s.replace(/[^A-Za-z0-9]/g, "").toLowerCase(); + return cleanedS === cleanedS.split("").reverse().join(""); + }; + + const input = "A man, a plan, a canal: Panama"; + const output = isPalindrome(input); + + return ( +
+

+ Input: {input} +

+

+ Output: {output.toString()} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function isPalindrome(s) { + if (!s) return true; + let left = 0, right = s.length - 1; + while (left < right) { + while (left < right && !s[left].match(/[a-zA-Z0-9]/)) left++; + while (left < right && !s[right].match(/[a-zA-Z0-9]/)) right--; + if (s[left].toLowerCase() !== s[right].toLowerCase()) return false; + left++; + right--; + } + return true; + } + ``` + + + + + ```typescript + function isPalindrome(s: string): boolean { + if (!s) return true; + let left = 0, right = s.length - 1; + while (left < right) { + while (left < right && !s[left].match(/[a-zA-Z0-9]/)) left++; + while (left < right && !s[right].match(/[a-zA-Z0-9]/)) right--; + if (s[left].toLowerCase() !== s[right].toLowerCase()) return false; + left++; + right--; + } + return true; + } + ``` + + + + + ```java + class Solution { + public boolean isPalindrome(String s) { + if (s == null || s.isEmpty()) { + return true; + } + + int left = 0, right = s.length() - 1; + while (left < right) { + while (left < right && !Character.isLetterOrDigit(s.charAt(left))) left++; + while (left < right && !Character.isLetterOrDigit(s.charAt(right))) right--; + if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) return false; + left++; + right--; + } + return true; + } + } + ``` + + + + + ```python + def is_palindrome(s: str) -> bool: + if not s: + return True + left, right = 0, len(s) - 1 + while left < right: + while left < right and not s[left].isalnum(): left += 1 + while left < right and not s[right].isalnum(): right -= 1 + if s[left].lower() != s[right].lower(): return False + left += 1 + right -= 1 + return True + ``` + + + + + ```cpp + class Solution { + public: + bool isPalindrome(string s) { + if (s.empty()) { + return true; + } + + int left = 0, right = s.length() - 1; + while (left < right) { + while (left < right && !isalnum(s[left])) left++; + while (left < right && !isalnum(s[right])) right--; + if (tolower(s[left]) != tolower(s[right])) return false; + left++; + right--; + } + return true; + } + }; + ``` + + + + + ```java + class Solution { + public boolean isPalindrome(String s) { + + String ans = ""; + + for(int i =0; i < s.length();i++){ + + //Check if charAt(i) is between 'A' to 'Z' then convert it to lower case and add it to ans + + if(s.charAt(i) >= 'A' && s.charAt(i) <= 'Z'){ + ans += Character.toLowerCase(s.charAt(i)); + } + + //Check if charAt(i) is between 'a' to 'z' then add it to ans + + else if(s.charAt(i) >= 'a' && s.charAt(i) <= 'z'){ + ans += s.charAt(i); + } + + //Check if charAt(i) is between '1' to '9' then add it to ans + + else if(s.charAt(i) >= '0' && s.charAt(i) <= '9'){ + ans += s.charAt(i); + } + } + + //Now Reverse the ans string + + String ans2 = ""; + + for(int i = 0; i < ans.length();i++){ + + ans2 = ans.charAt(i) + ans2; + } + + //after reversing check if ans is equal to ans2 then it is a palindrome string + + if(ans.equals(ans2)){ + return true; + } + return false; + } +} + ``` + + + + +#### Complexity Analysis + +- Time Complexity: O(n), where n is the length of the input string. We iterate through the string once. +- Space Complexity: O(1). We're not using any extra space. + +
+
+ +## References + +- **LeetCode Problem**: [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/valid-palindrome/solution/) + + diff --git a/solutions/lc-solutions/0100-0199/0126-word-ladder-II.md b/solutions/lc-solutions/0100-0199/0126-word-ladder-II.md new file mode 100644 index 0000000..ff91bc6 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0126-word-ladder-II.md @@ -0,0 +1,318 @@ +--- +id: word-ladder-II +title: Word ladder II solution +sidebar_label: 0126 Word ladder II +tags: + - String + - BFS (Breadth-First Search) + - Backtracking + - Graph + - LeetCode + - Python + - Java + - C++ +description: "This is a solution to the word ladder II problem on LeetCode." +--- + +## Problem Description + +A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord $s1 -> s2 -> ... -> sk$ such that: + +Every adjacent pair of words differs by a single letter. +Every si for $1 <= i <= k$ is in wordList. Note that beginWord does not need to be in wordList. +sk == endWord +Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk]. + +### Examples + +**Example 1:** + +``` +Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] +Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]] +Explanation: There are 2 shortest transformation sequences: +"hit" -> "hot" -> "dot" -> "dog" -> "cog" +"hit" -> "hot" -> "lot" -> "log" -> "cog" +``` + +**Example 2:** + +``` +Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] +Output: [] +Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence. +``` + +### Constraints + +- $1 <= beginWord.length <= 5$ +- $endWord.length == beginWord.length$ +- $1 <= wordList.length <= 500$ +- $wordList[i].length == beginWord.length$ +- beginWord, endWord, and wordList[i] consist of lowercase English letters. +- beginWord != endWord +- All the words in wordList are unique. +- The sum of all shortest transformation sequences does not exceed 105. + +## Solution for Word Ladder II Problem + + + + +### Approach : + +#### Intuition + +Define a helper function neighbors(word) that generates all the possible words by changing a single character in the given word. +Initialize a variable words as a dictionary with beginWord as the key and a lambda function returning [[beginWord]] as the value. This dictionary will keep track of all possible transformation sequences. +Initialize a set unvisited containing all words in wordList except beginWord. +Perform BFS: +While there are words in words and endWord is not yet found in words: +Increment a counter i. +Initialize a new dictionary new_words to store the next layer of words. +Iterate through each word s in words: +Generate all possible neighbors ss of s. +If ss is in unvisited, create a lambda function get_seqs that appends ss to each sequence of words ending with s, and add ss and get_seqs to new_words. +Update words to new_words. +Remove the keys of new_words from unvisited. +Return the transformation sequences ending with endWord. + + +#### Code in Different Languages + + + + + ```python3 + class Solution: + def findLadders( + self, beginWord: str, endWord: str, wordList: List[str] + ) -> List[List[str]]: + def neighbors(word): + for i in range(len(word)): + for char in "abcdefghijklmnopqrstuvwxyz": + yield word[:i] + char + word[i + 1 :] + + i = 1 + words = {beginWord: lambda: [[beginWord]]} + unvisited = set(wordList) + while words and endWord not in words: + i += 1 + new_words = defaultdict(lambda: lambda: []) + for s in words: + for ss in neighbors(s): + if ss in unvisited: + + def get_seqs(capture=(ss, new_words[ss], words[s])): + ss, ss_get_seqs, s_get_seqs = capture + seqs = ss_get_seqs() + for seq in s_get_seqs(): + seq.append(ss) + seqs.append(seq) + return seqs + + new_words[ss] = get_seqs + words = new_words + unvisited -= words.keys() + return words[endWord]() + + ``` + + + + + ```java + class Solution { + public List> findLadders(String beginWord, String endWord, List wordList) { + List> ans = new ArrayList<>(); + Map> reverse = new HashMap<>(); // reverse graph start from endWord + Set wordSet = new HashSet<>(wordList); // remove the duplicate words + wordSet.remove(beginWord); // remove the first word to avoid cycle path + Queue queue = new LinkedList<>(); // store current layer nodes + queue.add(beginWord); // first layer has only beginWord + Set nextLevel = new HashSet<>(); // store nextLayer nodes + boolean findEnd = false; // find endWord flag + while (!queue.isEmpty()) { // traverse current layer nodes + String word = queue.remove(); + for (String next : wordSet) { + if (isLadder(word, next)) { // is ladder words + // construct the reverse graph from endWord + Set reverseLadders = reverse.computeIfAbsent(next, k -> new HashSet<>()); + reverseLadders.add(word); + if (endWord.equals(next)) { + findEnd = true; + } + nextLevel.add(next); // store next layer nodes + } + } + if (queue.isEmpty()) { // when current layer is all visited + if (findEnd) break; // if find the endWord, then break the while loop + queue.addAll(nextLevel); // add next layer nodes to queue + wordSet.removeAll(nextLevel); // remove all next layer nodes in wordSet + nextLevel.clear(); + } + } + if (!findEnd) return ans; // if can't reach endWord from startWord, then return ans. + Set path = new LinkedHashSet<>(); + path.add(endWord); + // traverse reverse graph from endWord to beginWord + findPath(endWord, beginWord, reverse, ans, path); + return ans; + } + + + private void findPath(String endWord, String beginWord, Map> graph, + List> ans, Set path) { + Set next = graph.get(endWord); + if (next == null) return; + for (String word : next) { + path.add(word); + if (beginWord.equals(word)) { + List shortestPath = new ArrayList<>(path); + Collections.reverse(shortestPath); // reverse words in shortest path + ans.add(shortestPath); // add the shortest path to ans. + } else { + findPath(word, beginWord, graph, ans, path); + } + path.remove(word); + } + } + + private boolean isLadder(String s, String t) { + if (s.length() != t.length()) return false; + int diffCount = 0; + int n = s.length(); + for (int i = 0; i < n; i++) { + if (s.charAt(i) != t.charAt(i)) diffCount++; + if (diffCount > 1) return false; + } + return diffCount == 1; + }} + ``` + + + + + ```cpp + class Solution { +public: + vector> findLadders(string beginWord, string endWord, vector& wordList) { + int n=wordList.size(); + + unordered_set uset; + for(auto const &it:wordList){ + if(it!=beginWord) uset.insert(it); + } + + queue q; + q.push(beginWord); + + vector> levels; + int cnt=0; + bool flag=false; + + while(!q.empty()){ + int sz=q.size(); + + for(int i=0;i> ans; + + if(!flag){ + return ans; + } + + vector>::reverse_iterator it=levels.rbegin(); + + vector vec; + dfs(endWord,levels,ans,vec,it,cnt,beginWord); + + return ans; + } + +private: + + void dfs(string str,vector> &levels,vector> &ans,vector &vec,vector>::reverse_iterator it,int cnt,string &beginWord){ + if(str==beginWord){ + vec.push_back(str); + reverse(vec.begin(),vec.end()); + ans.push_back(vec); + reverse(vec.begin(),vec.end()); + vec.pop_back(); + + return; + } + + while(it!=levels.rend() && it->second==cnt){ + it++; + } + + while(it!=levels.rend() && it->second==cnt-1){ + if(isPossible(str,it->first)){ + vec.push_back(str); + dfs(it->first,levels,ans,vec,it,cnt-1,beginWord); + vec.pop_back(); + } + it++; + } + } + + bool isPossible(string str1,string str2){ + int n=str1.length(); + + int diff=0; + for(int i=0;i1) return false; + } + + return true; + } +}; + ``` + + + + + + + + + +## References + +- **LeetCode Problem**: [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/word-ladder-ii/solution/) + +- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) diff --git a/solutions/lc-solutions/0100-0199/0127-word-ladder.md b/solutions/lc-solutions/0100-0199/0127-word-ladder.md new file mode 100644 index 0000000..a9c3a0f --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0127-word-ladder.md @@ -0,0 +1,213 @@ +--- +id: word-ladder +title: Word ladder solution +sidebar_label: 0127 Word ladder +tags: + - String + - BFS (Breadth-First Search) + - Backtracking + - Graph + - LeetCode + - Python + - Java + - C++ +description: "This is a solution to the word ladder problem on LeetCode." +--- + +## Problem Description + +A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord $-> s1 -> s2 -> ... ->$ such that: + +Every adjacent pair of words differs by a single letter. +Every si for $1 <= i <= k$ is in wordList. Note that beginWord does not need to be in wordList. +sk == endWord +Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists. + +### Examples + +**Example 1:** + +``` +Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] +Output: 5 +Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long. +``` + +**Example 2:** + +``` +Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] +Output: 0 +Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence. +``` + + +### Constraints + +- $1 <= beginWord.length <= 10$ +- $endWord.length == beginWord.length$ +- $1 <= wordList.length <= 5000$ +- $wordList[i].length == beginWord.length$ +- beginWord, endWord, and $wordList[i]$ consist of lowercase English letters. +- $beginWord != endWord$ +- All the words in wordList are unique. + +## Solution for Word Ladder II Problem + + + + +### Approach : + +#### Intuition + +We can think of this problem as a graph problem, where each word in the wordList is a node, and there is an edge between two words if they differ by only one character. Our goal is to find the shortest transformation sequence from the beginWord to the endWord. + +To solve this problem, we can use a breadth-first search (BFS) approach. We start from the beginWord and explore all its neighboring words (words that differ by only one character). We then explore the neighbors of these neighbors, and so on, until we find the endWord. + +During the BFS traversal, we maintain a queue to keep track of the words we need to visit next, and a set to keep track of the words we have already visited. We also keep track of the level of the BFS traversal, which represents the length of the transformation sequence. + +Whenever we encounter the endWord during the BFS traversal, we return its level, which represents the length of the shortest transformation sequence. If we are unable to reach the endWord, we return 0. + +Overall, the BFS approach allows us to efficiently explore all possible transformation sequences and find the shortest one. + + +#### Code in Different Languages + + + + + ```python3 + from collections import deque + +class Solution: + def ladderLength(self, beginWord, endWord, wordList): + wordSet = set(wordList) + if endWord not in wordSet: + return 0 + + queue = deque([(beginWord, 1)]) + + while queue: + word, level = queue.popleft() + if word == endWord: + return level + + for i in range(len(word)): + for char in 'abcdefghijklmnopqrstuvwxyz': + next_word = word[:i] + char + word[i+1:] + if next_word in wordSet: + queue.append((next_word, level + 1)) + wordSet.remove(next_word) + + return 0 + + + ``` + + + + + ```java + import java.util.*; + +class Solution { + public int ladderLength(String beginWord, String endWord, List wordList) { + Set words = new HashSet<>(wordList); + if (!words.contains(endWord)) return 0; + + Queue queue = new LinkedList<>(); + queue.add(beginWord); + int level = 1; + + while (!queue.isEmpty()) { + int size = queue.size(); + for (int i = 0; i < size; i++) { + String word = queue.poll(); + char[] arr = word.toCharArray(); + for (int j = 0; j < arr.length; j++) { + char original = arr[j]; + for (char c = 'a'; c <= 'z'; c++) { + if (c == original) continue; + arr[j] = c; + String newWord = new String(arr); + if (newWord.equals(endWord)) return level + 1; + if (words.contains(newWord)) { + queue.add(newWord); + words.remove(newWord); + } + } + arr[j] = original; + } + } + level++; + } + + return 0; + } +} + + ``` + + + + + ```cpp + #include +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + int ladderLength(string beginWord, string endWord, vector& wordList) { + unordered_set words(wordList.begin(), wordList.end()); + if (words.find(endWord) == words.end()) return 0; + + queue> q; + q.push({beginWord, 1}); + + while (!q.empty()) { + auto [word, level] = q.front(); + q.pop(); + + if (word == endWord) return level; + + for (int i = 0; i < word.size(); ++i) { + char original = word[i]; + for (char c = 'a'; c <= 'z'; ++c) { + if (c == original) continue; + word[i] = c; + if (words.find(word) != words.end()) { + q.push({word, level + 1}); + words.erase(word); + } + } + word[i] = original; + } + } + + return 0; + } +}; + + ``` + + + + + + + + + +## References + +- **LeetCode Problem**: [Word Ladder II](https://leetcode.com/problems/word-ladder/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/word-ladder/solution/) + +- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) diff --git a/solutions/lc-solutions/0100-0199/0128-longest-consecutive-sequence.md b/solutions/lc-solutions/0100-0199/0128-longest-consecutive-sequence.md new file mode 100644 index 0000000..b959df0 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0128-longest-consecutive-sequence.md @@ -0,0 +1,229 @@ +--- +id: longest-consecutive-sequence +title: Longest Consecutive Sequence(LeetCode) +sidebar_label: 0128-Longest Consecutive Sequence +tags: + - Array + - Hash Table + - Union Find +description: Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. +--- + +## Problem Statement + +Given an unsorted array of integers `nums`, return the length of the longest consecutive elements sequence. + +You must write an algorithm that runs in `O(n)` time. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [100,4,200,1,3,2] +Output: 4 +Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. +``` + +**Example 2:** + +```plaintext +Input: nums = [0,3,7,2,5,8,4,6,0,1] +Output: 9 +``` + +### Constraints + +- `0 <= nums.length <= 105` +- `-109 <= nums[i] <= 109` + +## Solution + +We can solve the problem of finding the longest consecutive sequence in an array using four different approaches: Brute Force, Sorting, Hash Table with an unordered map, and Hash Table with an unordered set. Each approach has its own advantages and drawbacks in terms of time and space complexity. + +### Approach 1: Brute Force + +#### Algorithm + +1. Initialize a variable to keep track of the longest consecutive sequence. +2. Iterate through each element in the array. +3. For each element, use a nested loop to check if the next consecutive number exists in the array. +4. Keep track of the length of the current consecutive sequence. +5. Update the longest consecutive sequence if the current sequence is longer. +6. Return the length of the longest consecutive sequence. + +#### Implementation + +```C++ +class Solution { +private: + bool longestConsecutive(vector& nums, int target){ + int n = nums.size(); + for(int i=0; i& nums) { + int n = nums.size(); + int longestConsecutiveSequence = 0; + for(auto num : nums){ + int currentNumber = num; + int currentConsecutiveSequence = 1; + while(longestConsecutive(nums, currentNumber+1)){ + currentNumber += 1; + currentConsecutiveSequence += 1; + } + longestConsecutiveSequence = max(longestConsecutiveSequence, currentConsecutiveSequence); + } + return longestConsecutiveSequence; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: O(N^3) +- **Space complexity**: O(1) + +### Approach 2: Sorting + +#### Algorithm + +1. Sort the array. +2. Initialize variables to keep track of the current consecutive sequence and the longest consecutive sequence. +3. Iterate through the sorted array. +4. If the current element is consecutive to the previous element, increase the current sequence length. +5. If not, update the longest sequence length and reset the current sequence length. +6. Return the length of the longest consecutive sequence. + +#### Implementation + +```C++ +class Solution { +public: + int longestConsecutive(vector& nums) { + int n = nums.size(); + if(n == 0){ + return 0; + } + sort(nums.begin(), nums.end()); + int currentConsecutiveSequence = 1; + int longestConsecutiveSequence = 0; + for(int i=1; i& nums) { + unordered_map map; + for(int i = 0; i 0){ + map[nums[i]] = false; + } + } + int maxlen = 0; + for(int i=0; i 0){ + j++; + count++; + } + if(count>maxlen){ + maxlen = count; + } + } + } + return maxlen; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: O(N) +- **Space complexity**: O(N) + +### Approach 4: Hash Table with Unordered Set + +#### Algorithm + +1. Create an unordered set to store each element in the array. +2. Iterate through the array. +3. For each element, check if it is the start of a sequence. +4. If it is, count the length of the sequence it starts and update the maximum length. +5. Return the length of the longest consecutive sequence. + +#### Implementation + +```C++ +class Solution { +public: + int longestConsecutive(vector& nums) { + unordered_set set; + for(int num : nums){ + set.insert(num); + } + int longestConsecutiveSequence = 0; + for(int num : nums){ + if(set.find(num-1) == set.end()){ + int currentNumber = num; + int currentConsecutiveSequence = 1; + while(set.find(currentNumber+1) != set.end()){ + currentNumber++; + currentConsecutiveSequence++; + } + longestConsecutiveSequence = max(longestConsecutiveSequence, currentConsecutiveSequence); + } + } + return longestConsecutiveSequence; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: O(N) +- **Space complexity**: O(N) + + +### Conclusion + +Among the four approaches, the optimized approaches using hash tables (unordered map or unordered set) are the most efficient with a time complexity of O(N) and space complexity of O(N). The brute force approach, while straightforward, is inefficient with a time complexity of O(N^3). The sorting approach is better but still not as efficient as the hash table approaches. The hash table with unordered set approach is particularly simple and effective for solving the longest consecutive sequence problem in linear time. diff --git a/solutions/lc-solutions/0100-0199/0129-sum-root-to-leaf-numbers.md b/solutions/lc-solutions/0100-0199/0129-sum-root-to-leaf-numbers.md new file mode 100644 index 0000000..c1604b3 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0129-sum-root-to-leaf-numbers.md @@ -0,0 +1,126 @@ +--- +id: sum-root-to-leaf-numbers +title: Sum root to leaf numbers +sidebar_label: 0129-Sum root to leaf numbers +tags: + - Depth first search + - Tree +description: You are given the root of a binary tree containing digits from 0 to 9 only.Each root-to-leaf path in the tree represents a number. +--- + +## Problem Statement + +You are given the root of a binary tree containing digits from `0 to 9` only. + +Each root-to-leaf path in the tree represents a number. + +For example, the root-to-leaf path` 1 -> 2 -> 3` represents the number `123`. +Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer. + +A leaf node is a node with no children + +### Examples + +**Example 1:** + +![alt image](https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg) + +```plaintext +Input: root = [1,2,3] +Output: 25 +Explanation: +The root-to-leaf path 1->2 represents the number 12. +The root-to-leaf path 1->3 represents the number 13. +Therefore, sum = 12 + 13 = 25. +``` + +**Example 2:** + +![alt text](https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg) + +```plaintext +Input: root = [4,9,0,5,1] +Output: 1026 +Explanation: +The root-to-leaf path 4->9->5 represents the number 495. +The root-to-leaf path 4->9->1 represents the number 491. +The root-to-leaf path 4->0 represents the number 40. +Therefore, sum = 495 + 491 + 40 = 1026. +``` + +### Constraints + +- The number of nodes in the tree is in the range `[1, 1000]`. +- `0 <= Node.val <= 9` +- `The depth of the tree will not exceed 10.` + +## Solution +### Intuition + +The intuition behind this solution is to perform a level-order traversal of the binary tree using a queue. While traversing the tree level by level, we keep track of the current sum along the path from the root to each node. When we encounter a leaf node, we add its corresponding sum to the total sum of all root-to-leaf numbers. + +### Approach + +1. Initialize a total sum variable to keep track of the sum of all root-to-leaf numbers. +2. Initialize two queues: one for storing the tree nodes and another for storing the corresponding sums. +3. Enqueue the root node and its value into the respective queues. +4. While there are nodes in the queue, dequeue a node and its corresponding sum. +5. If the dequeued node is a leaf node, add its sum to the total sum. +6. If the dequeued node has left or right children, enqueue them along with their corresponding sums (formed by appending the child node’s value to the current sum multiplied by 10). +7. Repeat steps 4-6 until the queue is empty. +8. Return the total sum. + + +### C++ + +```c++ +class Solution { +private: + int totalSum = 0; + + void findSum(TreeNode* root, int currNum) { + if (root == nullptr) return; + if (root->left == nullptr && root->right == nullptr) + totalSum += (currNum * 10 + root->val); + currNum = currNum * 10 + root->val; + findSum(root->left, currNum); + findSum(root->right, currNum); + } + +public: + int sumNumbers(TreeNode* root) { + findSum(root, 0); + return totalSum; + } +}; +``` + +### Java +```java +class Solution { + private int totalSum = 0; + public int sumNumbers(TreeNode root) { + findSum(root, 0); + return totalSum; + } + private void findSum(TreeNode root, int currNum){ + if(root == null) return; + if(root.left == null && root.right == null) totalSum += (currNum * 10 + root.val); + currNum = currNum * 10 + root.val; + findSum(root.left, currNum); + findSum(root.right, currNum); + } +} +``` + + + + +### Conclusion + +### Complexity +- Time complexity: +Since we visit each node exactly once, the time complexity is O(n), where n is the number of nodes in the binary tree. + +- Space complexity: +In the worst case, when the tree is a complete binary tree, both queues can hold up to O(n/2) nodes, resulting in O(n) space complexity. However, in the average case, the space complexity is O(sqrt(n)), where n is the number of nodes in the binary tree. diff --git a/solutions/lc-solutions/0100-0199/0130-surrounded-regions.md b/solutions/lc-solutions/0100-0199/0130-surrounded-regions.md new file mode 100644 index 0000000..decdaff --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0130-surrounded-regions.md @@ -0,0 +1,194 @@ +--- +id: surrounded-regions +title: Surrounded Regions +sidebar_label: 0130-Surrounded Regions +tags: + - Depth first search + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Surrounded Regions problem on LeetCode." +--- + +## Problem Description + +You are given an m x n matrix board containing letters 'X' and 'O', capture regions that are surrounded: + +Connect: A cell is connected to adjacent cells horizontally or vertically. +Region: To form a region connect every 'O' cell. +Surround: The region is surrounded with 'X' cells if you can connect the region with 'X' cells and none of the region cells are on the edge of the board. +A surrounded region is captured by replacing all 'O's with 'X's in the input matrix board. + + +### Examples + +**Example 1:** + +``` +Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]] + +Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]] + +Explanation: +![alt](https://assets.leetcode.com/uploads/2021/02/19/xogrid.jpg) +In the above diagram, the bottom region is not captured because it is on the edge of the board and cannot be surrounded. + +``` + +**Example 2:** +``` +Input: board = [["X"]] + +Output: [["X"]] +``` + +### Constraints + +- `m == board.length` +- `n == board[i].length` +- `1 <= m, n <= 200` +- `board[i][j] is 'X' or 'O'` + +--- + +## Solution for Candy Distribution Problem +### Intuition + +Imagine your grid is a big, cozy blanket filled with 'O's and 'X's. The 'O's are like cozy spots, and the 'X's are the spots you don't want to sit on. Your mission, should you choose to accept it, is to find all the cozy spots that are surrounded by 'X's on all four sides and turn them into 'X's too, so no one gets fooled by a fake cozy spot! But wait, if a cozy spot is on the edge of the blanket, it’s safe, because it’s connected to the great beyond (or the edge, whatever works). + +### Approach + +Here’s how you tackle this: + +1. **Edge Patrol**: First, you check all the cozy spots ('O's) on the edges of the blanket. If you find an 'O' on the edge, you mark it as part of the Safe Cozy Spot Coalitionℒ️ by changing it temporarily to another character, say a '#'. +2. **DFS Adventure**: For each 'O' on the edge, embark on a Depth-First Search (DFS) to find all connected 'O's and mark them as safe too. +3. **Sweeping Change**: After marking all the safe 'O's with '#', go through the entire blanket. Turn all the remaining 'O's into 'X's because they are fake cozy spots. Then, turn all the '#' back into 'O's because they are genuinely safe. + + + + +#### Code in Different Languages + +### C++ +```c++ +class Solution { +public: + vector> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + + void dfs(int row, int col, vector>& board, vector>& visited){ + int n = board.size(); + int m = board[0].size(); + + board[row][col] = '#'; + visited[row][col] = 1; + + for (auto dir : directions) { + int nrow = row + dir.first; + int ncol = col + dir.second; + + if (nrow >= 0 && nrow < n && ncol >= 0 && ncol < m && + board[nrow][ncol] == 'O' && !visited[nrow][ncol]) { + dfs(nrow, ncol, board, visited); + } + } + } + + void solve(vector>& board) { + int n = board.size(); + int m = board[0].size(); + + vector> visited(n, vector(m, 0)); + + + for(int row = 0; row < n; row++) { + if(board[row][0] == 'O' && !visited[row][0]) { + dfs(row, 0, board, visited); + } + if(board[row][m-1] == 'O' && !visited[row][m-1]) { + dfs(row, m-1, board, visited); + } + } + + for(int col = 0; col < m; col++) { + if(board[0][col] == 'O' && !visited[0][col]) { + dfs(0, col, board, visited); + } + if(board[n-1][col] == 'O' && !visited[n-1][col]) { + dfs(n-1, col, board, visited); + } + } + + + for(int row = 0; row < n; row++) { + for(int col = 0; col < m; col++) { + if(board[row][col] == 'O'){ + board[row][col] = 'X'; + } + else if(board[row][col] == '#'){ + board[row][col] = 'O'; + } + } + } + } +}; +``` + +### Pyhton +```python +from collections import deque + +class Solution: + def solve(self, board: List[List[str]]) -> None: + """ + Do not return anything, modify board in-place instead. + """ + + o = "O" + + n = len(board) + m = len(board[0]) + + Q = deque() + + for i in range(n): + if board[i][0] == o: + Q.append((i,0)) + if board[i][m-1] == o: + Q.append((i, m-1)) + + for j in range(m): + if board[0][j] == o: + Q.append((0,j)) + if board[n-1][j] == o: + Q.append((n-1, j)) + + def inBounds(i,j): + return (0 <= i < n) and (0 <= j < m) + + while Q: + i,j = Q.popleft() + board[i][j] = "#" + + for ii, jj in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]: + if not inBounds(ii, jj): + continue + if board[ii][jj] != o: + continue + Q.append((ii,jj)) + board[ii][jj] = '#' + + for i in range(n): + for j in range(m): + if board[i][j] == o: + board[i][j] = 'X' + elif board[i][j] == '#': + board[i][j] = o +``` + + + +### Complexity + +- **Time complexity**: O(n * m), where n is the number of rows and m is the number of columns. We might have to visit every cell. +- **Space complexity**: O(n * m) for the visited matrix, and the call stack in DFS might go as deep as O(n * m) in the worst case. \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0131-palindrom-partitioning.md b/solutions/lc-solutions/0100-0199/0131-palindrom-partitioning.md new file mode 100644 index 0000000..c7f1d96 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0131-palindrom-partitioning.md @@ -0,0 +1,139 @@ +--- +id: palindrom-partitioning +title: Palindrom Partitioning +sidebar_label: 0131-Palindrom partitioning +tags: + - string + - DP + - BackTracking +description: "This is a solution to the Palindrom Partitioning problem on LeetCode." +--- + +## Problem Description +Given a string s, partition s such that every +substring + of the partition is a +palindrome +. Return all possible palindrome partitioning of s. + + +### Examples + +**Example 1:** + +``` +Input: s = "aab" +Output: [["a","a","b"],["aa","b"]] +``` + +**Example 2:** +``` +Input: s = "a" +Output: [["a"]] +``` + +### Constraints + +- `1 <= s.length <= 16` +- s contains only lowercase English letters. + +--- + +## Solution for Candy Distribution Problem +### Intuition + +We can use backtracking to solve this problem. Iterate over the string, and if a substring starting from the `beg` index to the current length is a palindrome, we can add it to a temporary list and move the `beg` index to the next pointer. + +### Approach + +Here’s how you tackle this: + +1. **Maintain a `beg` Index**: This index represents the starting index and the length of the substring. If this substring is a palindrome, push it to a temporary array `curr`. +2. **Increase the Length**: Expand the length to get other combinations starting from this index. +3. **Check for Palindromes**: If you reach the end of the original string, it means all substrings included are palindromes, so you can add this combination to your result set. + + + + +#### Code in Different Languages + +### C++ +```c++ +class Solution { +public: + int n; + vector> partition(string s) { + n=s.size(); + vector> res; + vector curr; + backTrack(s,0,1,curr,res); + return res; + } + + void backTrack(string& s, int beg, int len, vector curr, vector>& res) { + if(beg==n) { + res.push_back(curr); + return; + } + if((beg+len)>n)return; + + + backTrack(s,beg,len+1,curr,res); + + if(isPallindrome(s.substr(beg, len))) { + curr.push_back(s.substr(beg, len)); + backTrack(s, beg+len, 1, curr, res); + } + } + + bool isPallindrome(string s){ + int beg=0;int end = s.size()-1; + while(beg self.n: + return + + self.backTrack(s, beg, len + 1, curr, res) + + if self.isPalindrome(s[beg:beg + len]): + curr.append(s[beg:beg + len]) + self.backTrack(s, beg + len, 1, curr, res) + curr.pop() # Remove the last element to backtrack + + def isPalindrome(self, s): + beg, end = 0, len(s) - 1 + while beg < end: + if s[beg] != s[end]: + return False + beg += 1 + end -= 1 + return True +``` + + + +### Complexity + +- **Time complexity**: O((2^n) * n), where `n` is the length of the string. We are diverging into two branches at each step, and the palindrome check takes O(n). +- **Space complexity**: O(2^n), where space is used for the stack in backtracking. diff --git a/solutions/lc-solutions/0100-0199/0132-palindrom-partitioning-II.md b/solutions/lc-solutions/0100-0199/0132-palindrom-partitioning-II.md new file mode 100644 index 0000000..6dfa168 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0132-palindrom-partitioning-II.md @@ -0,0 +1,164 @@ +--- +id: palindrom-partitioning-II +title: Palindrom Partitioning -II +sidebar_label: 0132-Palindrom partitioning -II +tags: + - string + - DP + - BackTracking +description: "This is a solution to the Palindrom Partitioning -II problem on LeetCode." +--- + +## Problem Description +Given a string s, partition s such that every +substring of the partition is a palindrome. + +Return the minimum cuts needed for a palindrome partitioning of s. + + +### Examples + +**Example 1:** +``` +Input: s = "aab" +Output: 1 +Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. +``` + +**Example 2:** +``` +Input: s = "a" +Output: 0 +``` +**Example 3:** +``` +Input: s = "ab" +Output: 1 +``` + +### Constraints + +- `1 <= s.length <= 2000` +- s consists of lowercase English letters only. + +--- + + +## Approach to Min Cut for Palindrome Partitioning + +The `minCut` function solves the problem of determining the minimum number of cuts needed to partition a string such that every substring is a palindrome. The approach uses dynamic programming to achieve this efficiently. + +### Approach + +1. **Palindrome Check with DP Table:** + - A 2D DP table, `isPaldp`, is used where `isPaldp[s][e]` indicates whether the substring from index `s` to `e` is a palindrome. + - A recursive function `isPal` checks if a substring is a palindrome by comparing the characters at the current indices and checking the palindrome status of the inner substring. + +2. **Precompute Palindrome Substrings:** + - Iterate over all possible substrings of the input string `s` and populate the `isPaldp` table using the `isPal` function. + +3. **Dynamic Programming for Minimum Cuts:** + - An array `dp` is used where `dp[i]` represents the minimum number of cuts needed for the substring starting at index `i` to the end of the string. + - Initialize `dp[n]` to `0` because no cuts are needed for an empty substring. + - Iterate backwards from the end of the string, and for each position, compute the minimum cuts required by checking all substrings starting from that position that are palindromes. + +4. **Result Computation:** + - The final result is `dp[0] - 1` because `dp[0]` includes an extra cut for the initial partition. + + + + +#### Code in Different Languages + +### C++ +```c++ +class Solution { +public: + bool isPal(string& str, int s, int e, vector>& isPaldp) { + if (s >= e) return true; // Correct base case for palindrome check + + if (isPaldp[s][e] != -1) return isPaldp[s][e]; + + if (str[s] == str[e]) { + return isPaldp[s][e] = isPal(str, s + 1, e - 1, isPaldp); + } else { + return isPaldp[s][e] = false; + } + } + + int minCut(string s) { + int n = s.size(); + vector dp(n + 1, INT_MAX); // Initialize with INT_MAX for min comparison + vector> isPaldp(n, vector(n, -1)); + + // Precompute the palindrome status + for (int i = 0; i < n; ++i) { + for (int j = i; j < n; ++j) { + isPal(s, i, j, isPaldp); + } + } + + dp[n] = 0; // No cuts needed for an empty substring + + for (int i = n - 1; i >= 0; --i) { + int cuts = INT_MAX; + for (int j = i; j < n; ++j) { + if (isPaldp[i][j]) { + cuts = min(cuts, 1 + dp[j + 1]); + } + } + dp[i] = cuts; + } + + return dp[0] - 1; + } +}; +``` + +### Pyhton +```java +// Approach - 0 Recursion +class Solution { + public int minCut(String str) { + + int n = str.length(); + return f(0, n, str) - 1; + } + boolean isPalindrome(int i, int j, String s) { + + while (i < j) { + if (s.charAt(i) != s.charAt(j)) return false; + i++; + j--; + } + return true; + } + + int f(int i, int n, String str) { + // Base case: + if (i == n) return 0; + + int minCost = Integer.MAX_VALUE; + // String[i...j] + for (int j = i; j < n; j++) { + if (isPalindrome(i, j, str)) { + int cost = 1 + f(j + 1, n, str); + minCost = Math.min(minCost, cost); + } + } + return minCost; + } +} +``` + + +### Complexity + +- **Time Complexity:** O(n^2), where `n` is the length of the string. This is due to the palindrome checks and the nested loops for computing the minimum cuts. +- **Space Complexity:** O(n^2), due to the 2D DP table for storing palindrome statuses. + +### Example + +For the string `"aab"`, the function computes the minimum cuts required to partition the string into palindromic substrings. For `"aab"`, the optimal partitioning is `"a" | "a" | "b"`, resulting in 2 cuts. + + diff --git a/solutions/lc-solutions/0100-0199/0133-clone-graph.md b/solutions/lc-solutions/0100-0199/0133-clone-graph.md new file mode 100644 index 0000000..3f38a47 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0133-clone-graph.md @@ -0,0 +1,225 @@ +--- +id: clone-graph +title: Clone graph +sidebar_label: 0133-Clone graph +tags: + - string + - DP + - BackTracking +description: "This is a solution to the Clone graph problem on LeetCode." +--- + +## Problem Description +Given a reference of a node in a connected undirected graph. + +Return a deep copy (clone) of the graph. + +Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. + +```c++ +class Node { + public int val; + public List neighbors; +} +``` + + +#### Test case format: + +For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list. + +An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. + +The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph. + + +### Examples + +**Example 1:** + +![alt](https://assets.leetcode.com/uploads/2019/11/04/133_clone_graph_question.png) +``` +Input: adjList = [[2,4],[1,3],[2,4],[1,3]] +Output: [[2,4],[1,3],[2,4],[1,3]] +Explanation: There are 4 nodes in the graph. +1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). +2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). +3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). +4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). +``` + +**Example 2:** +![alt](https://assets.leetcode.com/uploads/2020/01/07/graph.png) +``` +Input: adjList = [[]] +Output: [[]] +Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. +``` +**Example 3:** +``` +Input: adjList = [] +Output: [] +Explanation: This an empty graph, it does not have any nodes. + +``` + +### Constraints + +- The number of nodes in the graph is in the range `[0, 100]`. +- `1 <= Node.val <= 100` +- Node.val is unique for each node. +- There are no repeated edges and no self-loops in the graph. +- The Graph is connected and all nodes can be visited starting from the given node. + +--- + + + +### Intuition + +Use a Depth-First Search (DFS) approach to traverse the original graph. During the traversal: +- Create a new node for each encountered node and maintain a mapping between the original nodes and their corresponding clones. +- When processing a node's neighbors, check if the clone of the neighbor has already been created. If so, use the clone from the mapping; otherwise, recursively explore the neighbor to create its clone. + +### Approach + +1. **Define a Helper Function `dfs`:** + + The `dfs` function performs the following tasks: + - **Parameters:** Takes a node `cur` from the original graph and a mapping `mp` which stores the relationship between original nodes and their clones. + - **Steps:** + 1. **Create a New Node:** + - Create a new clone node with the same value as `cur`. + 2. **Add Mapping:** + - Add an entry in the mapping `mp` to link the original node `cur` with the newly created `clone`. + 3. **Initialize Neighbors:** + - Initialize an empty vector `neighbour` to store the cloned neighbors of `cur`. + 4. **Process Neighbors:** + - Iterate through the neighbors of `cur`: + - **If the Neighbor is Already Cloned:** If `mp.find(it) != mp.end()`, use the clone from the mapping. + - **If the Neighbor is Not Cloned:** Recursively call `dfs` on the neighbor to get its clone. + 5. **Set Neighbors:** + - Set the `neighbours` of the `clone` to the `neighbour` vector. + 6. **Return Clone:** + - Return the `clone`. + +2. **Define the `cloneGraph` Function:** + + This function initializes the cloning process: + - **Steps:** + 1. **Initialize the Mapping:** + - Create an unordered map `mp` to store the mapping between original nodes and their clones. + 2. **Check for Null Node:** + - Check if the `node` is `NULL`, and if so, return `NULL`. + 3. **Call `dfs`:** + - Call the `dfs` function with the original node and the mapping `mp`. + +#### Code in Different Languages + +### C++ +```c++ +class Solution { +public: +Node* dfs(Node* cur,unordered_map& mp) + { + vector neighbour; + Node* clone=new Node(cur->val); + mp[cur]=clone; + for(auto it:cur->neighbors) + { + if(mp.find(it)!=mp.end()) //already in map + { + neighbour.push_back(mp[it]); + } + else + neighbour.push_back(dfs(it,mp)); + } + clone->neighbors=neighbour; + return clone; + } + Node* cloneGraph(Node* node) { + unordered_map mp; + if(node==NULL) + return NULL; + + return dfs(node,mp); + }}; +``` + +### Java +```java +/* +// Definition for a Node. +class Node { + public int val; + public List neighbors; + public Node() { + val = 0; + neighbors = new ArrayList(); + } + public Node(int _val) { + val = _val; + neighbors = new ArrayList(); + } + public Node(int _val, ArrayList _neighbors) { + val = _val; + neighbors = _neighbors; + } +} +*/ + +class Solution { + + HashMap visited = new HashMap<>(); + + public Node cloneGraph(Node node) { + Node ans = new Node(); + if(node == null){ + return null; + } + ans.val = node.val; + visited.put(node.val, ans); + for(int i=0; i 'Node': + if not node: return node + + q, clones = deque([node]), {node.val: Node(node.val, [])} + while q: + cur = q.popleft() + cur_clone = clones[cur.val] + + for ngbr in cur.neighbors: + if ngbr.val not in clones: + clones[ngbr.val] = Node(ngbr.val, []) + q.append(ngbr) + + cur_clone.neighbors.append(clones[ngbr.val]) + + return clones[node.val] +``` + +### Complexity Analysis + +- **Time Complexity:** O(V + E) + - V is the number of nodes and E is the number of edges. The DFS traverses each node and edge once. + +- **Space Complexity:** O(V) + - Space is used for the mapping between nodes and their clones, which requires O(V) space. + + diff --git a/solutions/lc-solutions/0100-0199/0134-gas-station.md b/solutions/lc-solutions/0100-0199/0134-gas-station.md new file mode 100644 index 0000000..fb56cb3 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0134-gas-station.md @@ -0,0 +1,160 @@ +--- +id: gas-station +title: Gas Station +sidebar_label: 0134-Gas station +tags: + - string + - DP + - BackTracking +description: "This is a solution to the Gas station problem on LeetCode." +--- + +## Problem Description + +There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. + +You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next $(i + 1)^{th}$ station. You begin the journey with an empty tank at one of the gas stations. + +Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique + + + +### Examples + +**Example 1:** +``` +Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2] +Output: 3 +Explanation: +Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 +Travel to station 4. Your tank = 4 - 1 + 5 = 8 +Travel to station 0. Your tank = 8 - 2 + 1 = 7 +Travel to station 1. Your tank = 7 - 3 + 2 = 6 +Travel to station 2. Your tank = 6 - 4 + 3 = 5 +Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. +Therefore, return 3 as the starting index. +``` +**Example 2:** +``` +Input: gas = [2,3,4], cost = [3,4,3] +Output: -1 +Explanation: +You can't start at station 0 or 1, as there is not enough gas to travel to the next station. +Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 +Travel to station 0. Your tank = 4 - 3 + 2 = 3 +Travel to station 1. Your tank = 3 - 3 + 3 = 3 +You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. +Therefore, you can't travel around the circuit once no matter where you start. +``` + +### Constraints: + + +- $n == \text{gas.length} == \text{cost.length}$ +- $1 \leq \text{n} \leq 105$ +- $0 \leq \text{gas[i], cost[i]} \leq 104$ +--- + +## Approach to Solve the Gas Station Problem + +To determine the starting gas station index from which you can complete a circuit around the gas stations, follow these steps: + +### Approach + +1. **Check Feasibility:** + - Compute the total amount of gas available and the total cost required to travel around the circuit. + - If the total gas is less than the total cost, return `-1` because completing the circuit is impossible. + +2. **Find the Starting Point:** + - Initialize a variable to track the current gas balance and another to track the potential starting station. + - Traverse through the gas stations: + - Update the current gas balance by subtracting the travel cost from the gas available. + - If the gas balance goes negative, it means the current start station cannot lead to a successful trip. Update the start station to the next station and reset the gas balance. + +3. **Return the Result:** + - After traversing all stations, the index stored for the start station will be the valid starting point, if there is one. + +#### Code in Different Languages + +### C++ +```c++ +class Solution { +public: + int canCompleteCircuit(vector& gas, vector& cost) { + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int n = cost.size(), bal = 0, start = 0, deficit = 0; + + for(int i = 0; i< n; i++){ + bal += gas[i] - cost[i]; + + if(bal < 0){ + + deficit += bal; + start = i+1; + bal = 0; + } + } + return bal + deficit >= 0 ? start : -1; + } +}; +``` + +### Java +```java +class Solution { + public int canCompleteCircuit(int[] gas, int[] cost) { + int sGas = 0, sCost = 0, res = 0, total = 0; + for (int i = 0; i < gas.length; i++) { + sGas += gas[i]; + sCost += cost[i]; + } + if (sGas < sCost) return -1; + for (int i = 0; i < gas.length; i++) { + total += gas[i] - cost[i]; + if (total < 0) { + total = 0; + res = i + 1; + } + } + return res; + } +} +``` +### Python +```python +class Solution: + def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: + if sum(gas) < sum(cost): return -1 + tank = idx = 0 + for i in range(len(gas)): + tank+= gas[i]-cost[i] + if tank < 0: tank, idx = 0, i+1 + return idx + + print(f"cost: {cost}") + print(f"gas: {gas}") + tank = 0 + for i in range(len(cost)): + # find where we can start + if cost[i] > gas[i]+tank: + continue + start = i + tank += gas[i] + print("tank", tank) + for j in range(start+1, len(cost)): + if cost[i] > gas[i]: + print("inside", j) + return -1 +``` + + +### Complexity + +- **Time Complexity:** $O(n)$ - A single pass through the gas stations. +- **Space Complexity:** $O(1)$ - Constant space usage. + +### Summary + +This approach efficiently determines the valid starting gas station index by checking if the total gas is sufficient and then finding the correct start index through a linear pass. + diff --git a/solutions/lc-solutions/0100-0199/0135-Candy.md b/solutions/lc-solutions/0100-0199/0135-Candy.md new file mode 100644 index 0000000..958ba06 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0135-Candy.md @@ -0,0 +1,188 @@ +--- +id: candy +title: Candy +sidebar_label: 0135 Candy +tags: + - Greedy + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Candy problem on LeetCode." +--- + +## Problem Description + +There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings. + +You are giving candies to these children subjected to the following requirements: + +- Each child must have at least one candy. +- Children with a higher rating get more candies than their neighbors. + +Return the minimum number of candies you need to have to distribute the candies to the children. + +### Examples + +**Example 1:** + +``` +Input: ratings = [1,0,2] +Output: 5 +Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. + +``` + +**Example 2:** + +Input: ratings = [1,2,2] +Output: 4 +Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. +The third child gets 1 candy because it satisfies the above two conditions. + +``` +Input: root = [1,2,2,null,3,null,3] +Output: false +``` + +### Constraints + +- $n == ratings.length$ +- $1 <= n <= 2 * 10^4$ +- $0 <= ratings[i] <= 2 * 10^4$ + +--- + +## Solution for Candy Distribution Problem + +### Intuition And Approach + +To solve this problem, we can use a greedy approach. We can start by assigning each child 1 candy. Then, we iterate over the ratings array twice, once from left to right and once from right to left, adjusting the number of candies as needed to satisfy the given conditions. + + + +#### Code in Different Languages + + + + + ```java +public class Solution { + public int candy(int[] ratings) { + int n = ratings.length; + int[] candies = new int[n]; + + // Initialize all candies to 1 + for (int i = 0; i < n; i++) { + candies[i] = 1; + } + + // Left to right pass + for (int i = 1; i < n; i++) { + if (ratings[i] > ratings[i - 1]) { + candies[i] = candies[i - 1] + 1; + } + } + + // Right to left pass + for (int i = n - 2; i >= 0; i--) { + if (ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) { + candies[i] = candies[i + 1] + 1; + } + } + + int totalCandies = 0; + for (int candy : candies) { + totalCandies += candy; + } + + return totalCandies; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + int[] ratings1 = {1, 0, 2}; + int[] ratings2 = {1, 2, 2}; + + System.out.println(solution.candy(ratings1)); // Output: 5 + System.out.println(solution.candy(ratings2)); // Output: 4 + } +} + ``` + + + + ```python +class Solution(object): + def candy(self, ratings): + """ + :type ratings: List[int] + :rtype: int + """ + n = len(ratings) + candies = [1] * n + + # Left to right pass + for i in range(1, n): + if ratings[i] > ratings[i - 1]: + candies[i] = candies[i - 1] + 1 + + # Right to left pass + for i in range(n - 2, -1, -1): + if ratings[i] > ratings[i + 1]: + candies[i] = max(candies[i], candies[i + 1] + 1) + + return sum(candies) + ``` + + + + ```cpp +#include +#include + +using namespace std; + +class Solution { +public: + int candy(vector& ratings) { + int n = ratings.size(); + vector candies(n, 1); + + // Left to right pass + for (int i = 1; i < n; i++) { + if (ratings[i] > ratings[i - 1]) { + candies[i] = candies[i - 1] + 1; + } + } + + // Right to left pass + for (int i = n - 2; i >= 0; i--) { + if (ratings[i] > ratings[i + 1]) { + candies[i] = max(candies[i], candies[i + 1] + 1); + } + } + + // Sum up all candies + int totalCandies = 0; + for (int candy : candies) { + totalCandies += candy; + } + + return totalCandies; + } +}; + ``` + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ where n is the number of children (length of the ratings array). +- Space Complexity: $O(n)$ for storing the candies array. + +## References + +- **LeetCode Problem:** [Candy Problem](https://leetcode.com/problems/candy/) +- **Solution Link:** [Candy Solution on LeetCode](https://leetcode.com/problems/candy/solutions/5273312/candy-solution) +- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) diff --git a/solutions/lc-solutions/0100-0199/0136-single-number.md b/solutions/lc-solutions/0100-0199/0136-single-number.md new file mode 100644 index 0000000..1bd606f --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0136-single-number.md @@ -0,0 +1,121 @@ +--- +id: single-number +title: Single Number +sidebar_label: 0136 Single Number +tags: + - Java + - Python + - C++ + - XOR +description: "This is a solution to the Single Number problem on LeetCode." +--- + +## Problem Description + +Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. + +You must implement a solution with a linear runtime complexity and use only constant extra space. + +### Examples + +**Example 1:** + +``` +Input: nums = [2,2,1] +Output: 1 + +``` + +**Example 2:** + +Input: nums = [4,1,2,1,2] +Output: 4 + +**Example 3:** + +``` +Input: nums = [1] +Output: 1 +``` + +### Constraints + +- $1 \leq nums.length \leq 3 * 10^4$ +- $-3 \times 10^4 \leq nums[i] \leq 3 \times 10^4$ +- Each element in the array appears twice except for one element which appears only once. + +--- + +## Solution for Single Number Problem + +### Intuition + +When faced with this problem, the first hurdle to overcome is the strict limitations imposed on the solution: linear time complexity and constant space complexity. This means traditional methods of identifying duplicates like hash tables or sorting won't cut it. Instead, we'll need to use a different kind of magic, one rooted in the world of bitwise operations! + +### Approach + +Our saviour here is the XOR operation. XOR stands for 'exclusive or', and the magic lies in its properties. When a number is XORed with itself, the result is 0. And when a number is XORed with 0, the result is the number itself. + +So, if we XOR all the numbers in the array, all the numbers appearing twice will cancel each other out and we'll be left with the single number that appears only once. + +#### Code in Different Languages + + + + + ```java + class Solution { + public int singleNumber(int[] nums) { + int result = 0; + for (int num : nums) { + result ^= num; + } + return result; + } +} + +````` + + + + +````python +class Solution: + def singleNumber(self, nums: List[int]) -> int: + result = 0 + for num in nums: + result ^= num + return result + +````` + + + + +```cpp +class Solution { +public: + int singleNumber(vector& nums) { + int result = 0; + for (int num : nums) { + result ^= num; + } + return result; + } +}; + +``` + + + +#### Complexity Analysis + +- Time complexity: $O(n)$, as we're iterating over the array only once. +- Space complexity: $O(1)$, because we're only using a single variable to store the result, irrespective of the size of the input. + +## References + +- **LeetCode Problem:** [Single Number](https://leetcode.com/problems/single-number/description/) +- **Solution Link:** [Single NUmber on LeetCode](https://leetcode.com/problems/single-number/solutions/3801367/video-single-number-a-bitwise-magic-trick/) +- **Authors Leetcode Profile:** [vanAmsen](https://leetcode.com/u/vanAmsen/) +``` diff --git a/solutions/lc-solutions/0100-0199/0137-single-number-2.md b/solutions/lc-solutions/0100-0199/0137-single-number-2.md new file mode 100644 index 0000000..7ec22df --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0137-single-number-2.md @@ -0,0 +1,113 @@ +--- +id: single-number-II +title: Single Number II +sidebar_label: 0137 Single Number II +tags: + - Java + - Python + - C++ + +description: "This is a solution to the Single Number ii problem on LeetCode." +--- + +## Problem Description + +Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it. + +You must implement a solution with a linear runtime complexity and use only constant extra space. + +### Examples + +**Example 1:** + +``` +Input: nums = [2,2,3,2] +Output: 3 + +``` + +**Example 2:** + +Input: nums = [0,1,0,1,0,1,99] +Output: 99 + + + +### Constraints + +- $1 \leq nums.length \leq 3 * 10^4$ +- $-3 \times 10^4 \leq nums[i] \leq 3 \times 10^4$ +- Each element in the array appears three times except for one element which appears only once. + +--- + +## Solution for Single Number ii Problem + +### Intuition + +The problem states that every element in the array appears exactly three times, except for one element that appears exactly once. To identify this unique element efficiently, we can leverage a hash map to count the occurrences of each element. The key observation here is that the unique element will have a count of one in the hash map, while all other elements will have a count of three. +### Approach + +First declare an empty hashmap then we store the each element and it's frequencies in hashmap after that we iterate to the keys of map if the value of particular key is 1 then we return the key. + +#### Code in Different Languages + + + + + + + + + ```Python + class Solution: + def singleNumber(self, nums: List[int]) -> int: + mp = {} + for num in nums: + if num in mp: + mp[num] += 1 + else: + mp[num] = 1 + + for num, c in mp.items(): + if c == 1: + return num +``` + + + + + ```Java + class Solution { + public int singleNumber(int[] nums) { + Map mp=new HashMap<>(); + //int[] a=new int[2]; + int a=0; + for(int i:nums){ + mp.put(i,1+mp.getOrDefault(i,0)); + } + for(int i:mp.keySet()){ + if(mp.get(i)==1){ + a=i; + break; + } + } + return a; + + } + } +``` + + + +#### Complexity Analysis + +- Time complexity: $O(n)$, as we're iterating over the array only once. +- Space complexity: $O(n)$, because here we are using Hashmap to count occurences of elements. + +## References + +- **LeetCode Problem:** [Single Number ii](https://leetcode.com/problems/single-number-ii/description/) +- **Solution Link:** [Single Number ii on LeetCode](https://leetcode.com/problems/single-number-ii/post-solution/?submissionId=1273177780) +- **Authors Leetcode Profile:** [SivaniImmidi](https://leetcode.com/u/SivaniImmidi/) + diff --git a/solutions/lc-solutions/0100-0199/0138-copy-list-with-random-pointer.md b/solutions/lc-solutions/0100-0199/0138-copy-list-with-random-pointer.md new file mode 100644 index 0000000..39b957a --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0138-copy-list-with-random-pointer.md @@ -0,0 +1,171 @@ +--- +id: copy-list-with-random-pointer +title: Copy List with Random Pointer +sidebar_label: 0138 Copy List with Random Pointer +tags: + - Java + - Python + - C++ + - JavaScript +description: "This is a solution to the Copy List with Random Pointer problem on LeetCode." +--- + +## Problem Description + +A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. + +Construct a deep copy of the list. The deep copy should consist of exactly `n` brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. + +For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. + +### Examples + +**Example 1:** + +![e1](https://github.com/user-attachments/assets/af16a7ff-3439-4683-8f77-9fdbb3332bef) + +``` +Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] +Output: [[7,null],[13,0],[11,4],[10,2],[1,0]] +``` + +**Example 2:** + +![e2](https://github.com/user-attachments/assets/f805c77f-c6cd-4b92-9f9a-c17665bfa317) + +``` +Input: head = [[1,1],[2,1]] +Output: [[1,1],[2,1]] +``` + +### Constraints: + +- The number of nodes in the list is in the range [0, 1000]. +- `-10000 <= Node.val <= 10000` +- Node.random is null or is pointing to some node in the linked list. +--- + +## Approach to Solve the Copy List with Random Pointer Problem + +### Understand the Problem: + +Create a deep copy of a linked list where each node has a `next` and a `random` pointer. The new list should be identical in structure to the original, but with all new nodes. Ensure the `random` pointers in the new list accurately reflect the original's `random` pointer relationships. + +### Approach + +1. **Interweaving Nodes**: Create and insert new nodes immediately after each original node, forming an interwoven list. +2. **Assigning Random Pointers**: Set the `random` pointers of the new nodes based on the `random` pointers of the original nodes. +3. **Separating Lists**: Restore the original list and extract the copied list by adjusting the `next` pointers of both original and new nodes. + +#### Code in Different Languages + + + + + + + + + ```python + +class Node: + def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): + self.val = x + self.next = next + self.random = random + +def copyRandomList(head: 'Node') -> 'Node': + if not head: + return None + + current = head + while current: + new_node = Node(current.val, current.next, None) + current.next = new_node + current = new_node.next + + current = head + while current: + if current.random: + current.next.random = current.random.next + current = current.next.next + + original = head + copy = head.next + copy_head = copy + + while original: + original.next = original.next.next + if copy.next: + copy.next = copy.next.next + original = original.next + copy = copy.next + + return copy_head + + ``` + + + + + + + ```JS +class Node { + constructor(val, next = null, random = null) { + this.val = val; + this.next = next; + this.random = random; + } +} + +function copyRandomList(head) { + if (!head) return null; + + let current = head; + while (current) { + const newNode = new Node(current.val); + newNode.next = current.next; + current.next = newNode; + current = newNode.next; + } + + current = head; + while (current) { + if (current.random) { + current.next.random = current.random.next; + } + current = current.next.next; + } + current = head; + const newHead = head.next; + let copyCurrent = newHead; + + while (current) { + current.next = current.next.next; + if (copyCurrent.next) { + copyCurrent.next = copyCurrent.next.next; + } + current = current.next; + copyCurrent = copyCurrent.next; + } + + return newHead; +} + +``` + + + + + +### Output + +![Screenshot from 2024-07-19 21-11-44](https://github.com/user-attachments/assets/2c2a7efb-711d-4f6e-aebd-8f540de015c3) + +### Complexity + +- **Time Complexity:** O(n), where `n` is the number of nodes in the linked list. The algorithm iterates through the list three times: once for interweaving nodes, once for setting random pointers, and once for separating the lists. + +- **Space Complexity:** O(1), since the algorithm uses a constant amount of extra space beyond the input list itself (e.g., pointers for traversal and temporary variables). + diff --git a/solutions/lc-solutions/0100-0199/0139-word-break.md b/solutions/lc-solutions/0100-0199/0139-word-break.md new file mode 100644 index 0000000..88a2d3b --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0139-word-break.md @@ -0,0 +1,112 @@ +--- +id: word-break +title: Word Break(LeetCode) +sidebar_label: 0139-Word Break +tags: + - Array + - Hash Table + - String + - Dynamic Programming + - Trie + - Memoization +description: Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. +--- + +## Problem Statement + +Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. + +Note that the same word in the dictionary may be reused multiple times in the segmentation. + +### Examples + +**Example 1:** + +```plaintext +Input: s = "leetcode", wordDict = ["leet","code"] +Output: true +Explanation: Return true because "leetcode" can be segmented as "leet code". +``` + +**Example 2:** + +```plaintext +Input: s = "applepenapple", wordDict = ["apple","pen"] +Output: true +Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". +Note that you are allowed to reuse a dictionary word. +``` + +**Example 3:** + +```plaintext +Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] +Output: false +``` + +### Constraints + +- `1 <= s.length <= 300` +- `1 <= wordDict.length <= 1000` +- `1 <= wordDict[i].length <= 20` +- `s` and `wordDict[i]` consist of only lowercase English letters. +- All the strings of `wordDict` are unique. + +## Solution + +The word break problem can be efficiently solved using dynamic programming. This approach uses a boolean vector `dp[]` where `dp[i]` is set to true if a valid word (or sequence of words) ends at the `i-th` position of the string. The key optimization here is to look backwards from the current position `i` and only consider substrings if a valid word ends at the preceding position `j` where `dp[j] == true`. + +### Approach + +#### Algorithm + +1. Initialize: +* If the dictionary is empty, return `false` as no word can be formed. +* Create a boolean vector `dp` of size `s.size() + 1` and initialize all values to `false`. +* Set `dp[0] = true` because an empty string can always be segmented (base case). +2. Iterate through the string: +* For each position `i` from 1 to `s.size()`: + * Iterate backwards from `i-1` to 0 for each position `j`: + * If `dp[j]` is `true`, it means a valid word sequence ends at `j`. + * Extract the substring `s[j:i]`. + * If this substring is found in the dictionary, set `dp[i]` to `true` and break out of the inner loop as we found a valid word ending at `i`. +3. Return Result: +* The value `dp[s.size()]` will be `true` if the string `s` can be segmented into valid words from the dictionary. + +#### Implementation + +```C++ +#include +#include +#include + +bool wordBreak(std::string s, std::unordered_set &dict) { + if(dict.size() == 0) return false; + + std::vector dp(s.size() + 1, false); + dp[0] = true; + + for(int i = 1; i <= s.size(); i++) { + for(int j = i - 1; j >= 0; j--) { + if(dp[j]) { + std::string word = s.substr(j, i - j); + if(dict.find(word) != dict.end()) { + dp[i] = true; + break; // Move to the next i + } + } + } + } + + return dp[s.size()]; +} +``` + +### Complexity Analysis + +- **Time complexity**: O(N^2 * M), where `N` is the length of the string `s` and `M` is the average length of the words in the dictionary. +- **Space complexity**: O(N), where `N` is the length of the string `s`. + +### Conclusion + +The dynamic programming approach to solving the word break problem is efficient and straightforward. By using a boolean vector to keep track of valid word endings, the algorithm ensures that each position in the string is only considered once for each potential word break. This reduces redundant computations and optimizes performance, making it feasible to solve even for relatively large strings and dictionaries. diff --git a/solutions/lc-solutions/0100-0199/0140-word-break-ii.md b/solutions/lc-solutions/0100-0199/0140-word-break-ii.md new file mode 100644 index 0000000..33f5eb3 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0140-word-break-ii.md @@ -0,0 +1,195 @@ +--- +id: word-break-ii +title: Word Break II +level: hard +sidebar_label: 0140 - Word Break II +tags: + - Dynamic Programming + - Backtracking +description: "This document provides solutions for the Word Break II problem." +--- + +## Problem Statement + +Given a string `s` and a dictionary of strings `wordDict`, add spaces in `s` to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order. + +Note that the same word in the dictionary may be reused multiple times in the segmentation. + +**Examples:** + +Example 1: + +Input: `s = "catsanddog"`, `wordDict = ["cat","cats","and","sand","dog"]` + +Output: `["cats and dog","cat sand dog"]` + +Example 2: + +Input: `s = "pineapplepenapple"`, `wordDict = ["apple","pen","applepen","pine","pineapple"]` + +Output: `["pine apple pen apple","pineapple pen apple","pine applepen apple"]` + +Explanation: Note that you are allowed to reuse a dictionary word. + +Example 3: + +Input: `s = "catsandog"`, `wordDict = ["cats","dog","sand","and","cat"]` + +Output: `[]` + +**Constraints:** + +- `1 <= s.length <= 20` +- `1 <= wordDict.length <= 1000` +- `1 <= wordDict[i].length <= 10` +- `s` and `wordDict[i]` consist of only lowercase English letters. +- All the strings of `wordDict` are unique. +- Input is generated in a way that the length of the answer doesn't exceed `105`. + +## Solutions + +### Approach + +To solve the problem of generating all possible sentences from `s` using words from `wordDict`, we can utilize a recursive backtracking approach combined with memoization for efficiency. + +1. **Recursive Backtracking with Memoization:** + - Use a recursive function `wordBreakHelper` to explore all possible segmentations of `s`. + - Use a `Set` for `wordDict` to achieve O(1) time complexity for word lookups. + - Maintain a `Map` (`memo`) to store results of already computed segmentations to avoid redundant computations. + +2. **Base Case and Recursive Case:** + - Base Case: When `index == s.length()`, if the current segmentation (`temp`) is empty (`"".equals(temp)`), add the segmented string from `sb` to the result list (`list`). + - Recursive Case: For each character in `s` starting from `index`, form a substring (`temp`) and check if it exists in `wordDict`. If it does, add it to `sb` and recursively call `wordBreakHelper` with updated `index` and `temp`. After recursion, backtrack by removing `temp` from `sb`. + +3. **Memoization:** + - Before making a recursive call, check if the current `index` and `sb.toString()` combination already exists in `memo`. If it does, directly retrieve the result from `memo` to avoid recomputation. + +### Code(C++): + +```cpp + +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector wordBreak(string s, vector& wordDict) { + unordered_set wordSet(wordDict.begin(), wordDict.end()); + unordered_map> memo; + return wordBreakHelper(s, wordSet, 0, memo); + } + +private: + vector wordBreakHelper(const string& s, const unordered_set& wordDict, int start, unordered_map>& memo) { + if (memo.find(start) != memo.end()) { + return memo[start]; + } + + vector result; + if (start == s.length()) { + result.push_back(""); + return result; + } + + for (int end = start + 1; end <= s.length(); ++end) { + string word = s.substr(start, end - start); + if (wordDict.find(word) != wordDict.end()) { + vector sublist = wordBreakHelper(s, wordDict, end, memo); + for (const string& sub : sublist) { + result.push_back(word + (sub.empty() ? "" : " ") + sub); + } + } + } + + memo[start] = result; + return result; + } +}; + +``` + + +### Code (Java): + +```java + +class Solution { + List list = new ArrayList<>(); + StringBuilder sb = new StringBuilder(); + Map> memo = new HashMap<>(); + + public List wordBreak(String s, List wordDict) { + Set wordSet = Set.copyOf(wordDict); + wordBreakHelper(s, wordSet, 0); + return list; + } + + private List wordBreakHelper(String s, Set wordDict, int index) { + if (index == s.length()) { + List temp = new ArrayList<>(); + if ("".equals(sb.toString())) { + temp.add(sb.substring(0, sb.length() - 1).toString()); + } + return temp; + } + + String current = s.substring(index); + if (memo.containsKey(current)) { + return memo.get(current); + } + + List sentences = new ArrayList<>(); + StringBuilder temp = new StringBuilder(); + + for (int i = index; i < s.length(); i++) { + temp.append(s.charAt(i)); + if (wordDict.contains(temp.toString())) { + int len = sb.length(); + sb.append(temp).append(' '); + List nextSentences = wordBreakHelper(s, wordDict, i + 1); + for (String sentence : nextSentences) { + sentences.add(sb.toString() + sentence); + } + sb.setLength(len); // Backtrack + } + } + + memo.put(current, sentences); + return sentences; + } +``` + +### Code (Python): + +```python + + class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: + self.result = [] + self.sb = [] + + def wordBreakHelper(index): + if index == len(s): + self.result.append(' '.join(self.sb)) + return + + temp = [] + for i in range(index, len(s)): + temp.append(s[i]) + if ''.join(temp) in wordDict: + self.sb.append(''.join(temp)) + wordBreakHelper(i + 1) + self.sb.pop() + + wordBreakHelper(0) + return self.result +``` + +### Complexity Analysis + +- **Time Complexity**: $O(nβ‹…2^n)$, in the worst case, where `n` is the length of the string `s`. +- **Space Complexity**: $O(nβ‹…2^n)$, in the worst case, where `n` is the length of the string `s`. diff --git a/solutions/lc-solutions/0100-0199/0141-linked-list-cycle.md b/solutions/lc-solutions/0100-0199/0141-linked-list-cycle.md new file mode 100644 index 0000000..3339474 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0141-linked-list-cycle.md @@ -0,0 +1,158 @@ +--- +id: linked-list-cycle +title: Linked List Cycle +sidebar_label: 0141- Linked List Cycle +tags: + - DSA + - Leetcode + - Linked List + +description: "This is a solution to the Linked List cycle on LeetCode." +--- + +## Problem Statement + +Given head, the head of a linked list, determine if the linked list has a cycle in it. + +There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. + +Return true if there is a cycle in the linked list. Otherwise, return false. + +### Examples + +**Example 1:** + +``` +Input: head = [3,2,0,-4], pos = 1 +Output: true +Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). +``` + +**Example 2:** + +``` +Input: head = [1,2], pos = 0 +Output: true +Explanation: There is a cycle in the linked list, where the tail connects to the 0th node. +``` + +**Example 3:** + +``` +Input: head = [1], pos = -1 +Output: false +Explanation: There is no cycle in the linked list. +``` + +### Constraints: + +- The number of the nodes in the list is in the range $[0, 10^4].$ +- $-105 <= Node.val <= 105$ +- $pos is -1 or a valid index in the linked-list.$ + +## Algorithm + +1. **Initialization**: + + - Initialize two pointers, `slow` and `fast`, both pointing to the head of the linked list. + +2. **Traversal**: + + - Move the `slow` pointer one step at a time. + - Move the `fast` pointer two steps at a time. + +3. **Cycle Detection**: + + - If there is a cycle, the `fast` pointer will eventually meet the `slow` pointer within the cycle. + - If there is no cycle, the `fast` pointer will reach the end of the list (NULL). + +4. **Return Result**: + - If the `fast` pointer meets the `slow` pointer, return `true` indicating a cycle is detected. + - If the `fast` pointer reaches the end of the list, return `false` indicating no cycle is detected. + +## Code Implementation + +### C++ + +```cpp +class Solution { +public: + bool hasCycle(ListNode *head) { + ListNode* fast = head; + ListNode* slow = head; + + while (fast != NULL && fast->next != NULL) { + fast = fast->next->next; + slow = slow->next; + if (fast == slow) { + return true; + } + } + + return false; + } +}; +``` + +### Python + +```python +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +class Solution: + def hasCycle(self, head: ListNode) -> bool: + fast = head + slow = head + + while fast is not None and fast.next is not None: + fast = fast.next.next + slow = slow.next + if fast == slow: + return True + + return False +``` + +### Java + +```java +public class Solution { + public boolean hasCycle(ListNode head) { + ListNode fast = head; + ListNode slow = head; + + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + if (fast == slow) { + return true; + } + } + + return false; + } +} +``` + +### JavaScript + +```javascript +var hasCycle = function (head) { + let fast = head; + let slow = head; + + while (fast !== null && fast.next !== null) { + fast = fast.next.next; + slow = slow.next; + if (fast === slow) { + return true; + } + } + + return false; +}; +``` + diff --git a/solutions/lc-solutions/0100-0199/0142-linked-list-cycle-II.md b/solutions/lc-solutions/0100-0199/0142-linked-list-cycle-II.md new file mode 100644 index 0000000..9cb15f8 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0142-linked-list-cycle-II.md @@ -0,0 +1,174 @@ +--- +id: linked-list-cycle--II +title: Linked List Cycle II +sidebar_label: 0142- Linked List Cycle II +tags: + - DSA + - Leetcode + - Linked List + +description: "This is a solution to the Linked List cycle II on LeetCode." +--- + +## Problem Statement + +Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. + +There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter. + +Do not modify the linked list. + +### Examples + +**Example 1:** + +``` +Input: head = [3,2,0,-4], pos = 1 +Output: tail connects to node index 1 +Explanation: There is a cycle in the linked list, where tail connects to the second node. +``` + +**Example 2:** + +``` +Input: head = [1,2], pos = 0 +Output: tail connects to node index 0 +Explanation: There is a cycle in the linked list, where tail connects to the first node. +``` + +**Example 3:** + +``` +Input: head = [1], pos = -1 +Output: no cycle +Explanation: There is no cycle in the linked list. +``` + +### Constraints: + +- The number of the nodes in the list is in the range $[0, 10^4].$ +- $-10^5 <= Node.val <= 10^5$ +- pos is `-1` or a valid index in the linked-list. + +## Algorithm for Detecting the Start of a Cycle in a Linked List + +1. **Initialization**: + + - Initialize two pointers, `slow` and `fast`, both pointing to the head of the linked list. + +2. **Cycle Detection**: + + - Move the `slow` pointer one step at a time. + - Move the `fast` pointer two steps at a time. + - If there is a cycle, the `fast` pointer will eventually meet the `slow` pointer within the cycle. + +3. **Finding the Cycle Start**: + + - If the `fast` pointer meets the `slow` pointer, reset the `slow` pointer to the head of the list. + - Move both pointers one step at a time until they meet again. + - The node where they meet is the start of the cycle. + +4. **Return Result**: + - If the `fast` pointer meets the `slow` pointer, return the meeting node. + - If there is no cycle, return `NULL`. + +## Code Implementations + +### C++ + +```cpp +class Solution { +public: + ListNode *detectCycle(ListNode *head) { + ListNode* fast = head; + ListNode* slow = head; + + while (fast != NULL && fast->next != NULL) { + slow = slow->next; + fast = fast->next->next; + if (slow == fast) { + slow = head; + while (slow != fast) { + slow = slow->next; + fast = fast->next; + } + return slow; + } + } + return NULL; + } +}; +``` + +### Python + +```python +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +class Solution: + def detectCycle(self, head: ListNode) -> ListNode: + fast = head + slow = head + + while fast is not None and fast.next is not None: + slow = slow.next + fast = fast.next.next + if slow == fast: + slow = head + while slow != fast: + slow = slow.next + fast = fast.next + return slow + return None +``` + +### Java + +```java +public class Solution { + public ListNode detectCycle(ListNode head) { + ListNode fast = head; + ListNode slow = head; + + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + if (slow == fast) { + slow = head; + while (slow != fast) { + slow = slow.next; + fast = fast.next; + } + return slow; + } + } + return null; + } +} +``` + +### JavaScript + +```javascript +var detectCycle = function (head) { + let fast = head; + let slow = head; + + while (fast !== null && fast.next !== null) { + slow = slow.next; + fast = fast.next.next; + if (slow === fast) { + slow = head; + while (slow !== fast) { + slow = slow.next; + fast = fast.next; + } + return slow; + } + } + return null; +}; +``` diff --git a/solutions/lc-solutions/0100-0199/0143-reorder-list.md b/solutions/lc-solutions/0100-0199/0143-reorder-list.md new file mode 100644 index 0000000..0937297 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0143-reorder-list.md @@ -0,0 +1,491 @@ +--- +id: reorder-list +title: Reorder List +sidebar_label: 0143 - Reorder List +tags: +- Linked List +- Two Pointers +- Stack +- Recursion +description: "This is a solution to the Reorder List problem on LeetCode." +--- + +## Problem Description +You are given the head of a singly linked-list. The list can be represented as: +`L0 β†’ L1 β†’ … β†’ Ln - 1 β†’ Ln` +Reorder the list to be on the following form: +`L0 β†’ Ln β†’ L1 β†’ Ln - 1 β†’ L2 β†’ Ln - 2 β†’ …` +You may not modify the values in the list's nodes. Only nodes themselves may be changed. + +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2021/03/04/reorder1linked-list.jpg) +``` +Input: head = [1,2,3,4] +Output: [1,4,2,3] +``` +**Example 2:** +![image](https://assets.leetcode.com/uploads/2021/03/09/reorder2-linked-list.jpg) +``` +Input: head = [1,2,3,4,5] +Output: [1,5,2,4,3] +``` +### Constraints +- The number of nodes in the list is in the range $([1, 5 * 10^4])$. +- `1 <= Node.val <= 1000` + + +## Solution for Reorder List + +### Intuition +#### Find the Middle: +- Use two pointers to traverse the list at different speeds (one moving one step at a time, the other two steps). When the faster pointer reaches the end, the slower pointer will be at the middle. This splits the list into two halves. + +#### Reverse the Second Half: +- Reverse the second half of the list. This means changing the direction of the links between nodes in this part of the list so that the last node becomes the first node of this half. + +#### Merge the Two Halves: +- Start from the beginning of the list and the beginning of the reversed second half. +- Alternate nodes from each half to weave them together into a single reordered list. +- Continue this process until all nodes are merged. + + + + +#### Implementation +```jsx live +function ListNode(val, next = null) { + this.val = val; + this.next = next; +} +// Function to reverse the linked list +function reverse(head) { + let curr = head; + let prev = null; + let ptr = null; + + while (curr !== null) { + ptr = curr.next; + curr.next = prev; + prev = curr; + curr = ptr; + } + return prev; +} + +// Function to reorder the linked list +function reorderList(head) { + if (!head || !head.next) return; + + // Find the middle of the linked list + let slow = head; + let fast = head; + let last = head; + + while (fast !== null && fast.next !== null) { + last = slow; + slow = slow.next; + fast = fast.next.next; + } + + // Split the list into two halves + last.next = null; + + // Reverse the second half of the list + let second = reverse(slow); + let first = head; + + // Merge the two halves + while (second) { + let temp1 = first.next; + let temp2 = second.next; + + first.next = second; + second.next = temp1; + + first = temp1; + second = temp2; + } +} + +const input = [1, 2, 3, 4, 5]; + +// Construct the linked list from the input array +let head = new Node(input[0]); +let current = head; +let stack = [head]; +for (let i = 1; i < input.length; i++) { + if (input[i] === null) continue; + let newNode = new Node(input[i]); + current.next = newNode; + newNode.prev = current; + current = newNode; + if (input[i] !== null) { + stack.push(current); + } +} + +// Flatten the linked list +let output = reorderList(head); + +return ( +
+

+ Input: {JSON.stringify(input)} +

+

+ Output: {output ? output.toString() : 'null'} +

+
+); +``` +### Code in Different Languages + + + + + ```javascript + function createNode(val, next = null) { + return { val, next }; +} + +function reverse(head) { + let curr = head; + let prev = null; + let ptr = null; + + while (curr !== null) { + ptr = curr.next; + curr.next = prev; + prev = curr; + curr = ptr; + } + + return prev; +} + +function findMiddle(head) { + let slow = head; + let fast = head; + + while (fast !== null && fast.next !== null) { + slow = slow.next; + fast = fast.next.next; + } + + return slow; +} + +function reorderList(head) { + let middle = findMiddle(head); + let second = reverse(middle); + let first = head; + + while (second !== null && first !== null) { + let temp1 = first.next; + let temp2 = second.next; + + if (first.next !== null) { + first.next = second; + } + if (second.next !== null) { + second.next = temp1; + } + + second = temp2; + first = temp1; + } +} + +// Example usage: +// Create a linked list +let head = createNode(1); +head.next = createNode(2); +head.next.next = createNode(3); +head.next.next.next = createNode(4); +head.next.next.next.next = createNode(5); + +reorderList(head); + +// Print the reordered list +let current = head; +while (current !== null) { + console.log(current.val); + current = current.next; +} + + ``` + + + + ```typescript + interface ListNode { + val: number; + next: ListNode | null; +} + +function createNode(val: number, next: ListNode | null = null): ListNode { + return { val, next }; +} + +function reverse(head: ListNode | null): ListNode | null { + let curr: ListNode | null = head; + let prev: ListNode | null = null; + let ptr: ListNode | null = null; + + while (curr !== null) { + ptr = curr.next; + curr.next = prev; + prev = curr; + curr = ptr; + } + + return prev; +} + +function findMiddle(head: ListNode | null): ListNode | null { + let slow: ListNode | null = head; + let fast: ListNode | null = head; + + while (fast !== null && fast.next !== null) { + slow = slow!.next; + fast = fast!.next.next; + } + + return slow; +} + +function reorderList(head: ListNode | null): void { + let middle: ListNode | null = findMiddle(head); + let second: ListNode | null = reverse(middle); + let first: ListNode | null = head; + + while (second !== null && first !== null) { + let temp1: ListNode | null = first.next; + let temp2: ListNode | null = second.next; + + if (first.next !== null) { + first.next = second; + } + if (second.next !== null) { + second.next = temp1; + } + + second = temp2; + first = temp1; + } +} + +// Example usage: +// Create a linked list +let head: ListNode = createNode(1); +head.next = createNode(2); +head.next.next = createNode(3); +head.next.next.next = createNode(4); +head.next.next.next.next = createNode(5); + +reorderList(head); + +// Print the reordered list +let current: ListNode | null = head; +while (current !== null) { + console.log(current.val); + current = current.next; +} + + + ``` + + + + ```python + class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +def reverse(head): + curr = head + prev = None + ptr = None + + while curr: + ptr = curr.next + curr.next = prev + prev = curr + curr = ptr + + return prev + +def reorderList(head): + slow = head + fast = head + last = head + + while fast: + last = slow + slow = slow.next + fast = fast.next + if fast: + fast = fast.next + + last.next = None + second = reverse(slow) + first = head + + while second: + temp1 = first.next + temp2 = second.next + + first.next = second + second.next = temp1 + + second = temp2 + first = temp1 + +# Example usage: +# Create a linked list +head = ListNode(1) +head.next = ListNode(2) +head.next.next = ListNode(3) +head.next.next.next = ListNode(4) +head.next.next.next.next = ListNode(5) + +reorderList(head) + +# Print the reordered list +current = head +while current: + print(current.val, end=" ") + current = current.next + + ``` + + + + +``` +class ListNode { + int val; + ListNode next; + ListNode(int x) { + val = x; + next = null; + } +} + +public class Solution { + public ListNode reverse(ListNode head) { + ListNode curr = head; + ListNode prev = null; + ListNode ptr = null; + + while (curr != null) { + ptr = curr.next; + curr.next = prev; + prev = curr; + curr = ptr; + } + return prev; + } + + public void reorderList(ListNode head) { + ListNode slow = head; + ListNode fast = head; + ListNode last = head; + + while (fast != null) { + last = slow; + slow = slow.next; + fast = fast.next; + if (fast != null) { + fast = fast.next; + } + } + + last.next = null; + ListNode second = reverse(slow); + ListNode first = head; + + while (second != null) { + ListNode temp1 = first.next; + ListNode temp2 = second.next; + + first.next = second; + second.next = temp1; + + second = temp2; + first = temp1; + } + } +} + +``` + + + +```cpp + ListNode* Reverse(ListNode* head) + { + ListNode* curr = head; + ListNode* prev = NULL; + ListNode* ptr = NULL; + + while(curr != NULL) + { + ptr = curr -> next; + curr -> next = prev; + prev = curr; + curr = ptr; + } + return prev; + } + + void reorderList(ListNode* head) { + ListNode* slow = head; + ListNode* fast = head; + ListNode* last = head; + while(fast != NULL) + { + last = slow; + slow = slow -> next; + fast = fast -> next; + if(fast != NULL) + { + fast = fast -> next; + } + } + + last -> next = NULL; + ListNode* second = Reverse(slow); + ListNode* first = head; + + while(second) + { + ListNode* temp1 = first -> next; + ListNode* temp2 = second -> next; + + first -> next = second; + second -> next = temp1; + + second = temp2; + first = temp1; + } + + } +``` + + + +#### Complexity Analysis +- Time Complexity: $ O(N)$ + - Space Complexity: $ O(1)$ +
+
+ +## References + +- **LeetCode Problem**: [Reorder List](https://leetcode.com/problems/reorder-list/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/reorder-list/solutions) diff --git a/solutions/lc-solutions/0100-0199/0144-binary-tree-preorder-traversal.md b/solutions/lc-solutions/0100-0199/0144-binary-tree-preorder-traversal.md new file mode 100644 index 0000000..f6654c6 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0144-binary-tree-preorder-traversal.md @@ -0,0 +1,164 @@ +--- +id: binary tree preorder traversal +title: Binary Tree Preorder Traversal +sidebar_label: 0144 Binary Tree Preorder Traversal +tags: + - tree + - DFS + - LeetCode + - Python + - Java + - C++ +description: "This is a solution to the Binary Tree Preorder Traversal problem on LeetCode." +--- + +## Problem Description + +Given the root of a binary tree, return the preorder traversal of its nodes' values. + +### Examples + +**Example 1:** + +``` + +Input: root = [1,null,2,3] +Output: [1,2,3] +``` + +**Example 2:** + +``` +Input: root = [] +Output: [] +``` +**Example 3:** + +``` +Input: root = [1] +Output: [1] +``` + +### Constraints + +- The number of nodes in the tree is in the range $[0, 100]$. +- $-100 <= Node.val <= 100$ + + +#### Code in Different Languages + + + + + ```python + # Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def preorderTraversal(self, root): + if not root: + return [] + result = [] + stack = [root] + while stack: + node = stack.pop() + result.append(node.val) + if node.right: + stack.append(node.right) + if node.left: + stack.append(node.left) + return result + + ``` + + + + + ```java + import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// Definition for a binary tree node. +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +class Solution { + public List preorderTraversal(TreeNode root) { + List result = new ArrayList<>(); + if (root == null) + return result; + Stack stack = new Stack<>(); + stack.push(root); + while (!stack.isEmpty()) { + TreeNode node = stack.pop(); + result.add(node.val); + if (node.right != null) + stack.push(node.right); + if (node.left != null) + stack.push(node.left); + } + return result; + } +} + + + + ``` + + + + + ```cpp +#include +#include +using namespace std; + +// Definition for a binary tree node provided by the precompiled header. +struct TreeNode; + +class Solution { +public: + vector preorderTraversal(TreeNode* root) { + if (!root) + return {}; + vector result; + stack s; + s.push(root); + while (!s.empty()) { + TreeNode* node = s.top(); + s.pop(); + result.push_back(node->val); + if (node->right) + s.push(node->right); + if (node->left) + s.push(node->left); + } + return result; + } +}; + + + + ``` + + + + + + +## References + +- **LeetCode Problem**: [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/binary-tree-preorder-traversal/solution/) + +- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) diff --git a/solutions/lc-solutions/0100-0199/0145-binary-tree-postorder-traversal.md b/solutions/lc-solutions/0100-0199/0145-binary-tree-postorder-traversal.md new file mode 100644 index 0000000..ae9512d --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0145-binary-tree-postorder-traversal.md @@ -0,0 +1,202 @@ +--- +id: binary-tree-postorder-traversal +title: Binary-Tree-Postorder-Traversal +sidebar_label: 0145 Binary-Tree-Postorder-Traversal +tags: + - DFS + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Binary-Tree-Postorder-Traversal problem on LeetCode." +--- + +## Problem Description + +Given the root of a binary tree, return the postorder traversal of its nodes' values. + +### Examples + +**Example 1:** + +``` + + +Input: root = [1,null,2,3] +Output: [3,2,1] + +``` + +**Example 2:** + + +``` +Input: root = [] +Output: [] +``` + +**Example 3:** + + +``` +Input: root = [1] +Output: [1] +``` + + +### Constraints + +- The number of the nodes in the tree is in the range [0, 100] +- $-100 <= Node.val <= 100$ + + +--- + +## Solution for Binary-Tree-Postorder-Traversal Problem + +### Intuition + +Imagine walking through the tree in a clockwise direction, starting from the left subtree, then moving to the right subtree, and finally reaching the root node. At each step, you collect the values of the nodes you visit, following the order: left, right, root. + + +### Approach + +### Recursive Approach (DFS - Depth First Search): + +- Perform postorder traversal recursively by visiting the left subtree, then the right subtree, and finally the root node. +- Base case: If the current node is null, return. +- Recursively call the function on the left subtree. +- Recursively call the function on the right subtree. +- Append the value of the current node to the result list. +- Return the result list. + +### Iterative Approach (Using Stack): + +- Start from the root node and initialize an empty stack. +- While the stack is not empty or the current node is not null: +- Traverse down the left subtree until you reach a leaf node, pushing each node onto the stack. +- Once you reach a leaf node, pop the top node from the stack. +- If the popped node has a right child and it is equal to the top of the stack, it means the right subtree has not been visited yet. In this case, pop the top node again and push the popped node back onto the stack, then move to its right child. +- If the popped node does not have a right child or its right child has already been visited, append its value to the result list. +- Return the result list. + + + +#### Code in Different Languages + + + + + ```python + # Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def postorderTraversal(self, root): + if not root: + return [] + result = [] + stack = [root] + while stack: + node = stack.pop() + result.append(node.val) + if node.left: + stack.append(node.left) + if node.right: + stack.append(node.right) + return result[::-1] + + + + ``` + + + + + ```java + import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +// Definition for a binary tree node. +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +class Solution { + public List postorderTraversal(TreeNode root) { + List result = new ArrayList<>(); + if (root == null) + return result; + Stack stack = new Stack<>(); + stack.push(root); + while (!stack.isEmpty()) { + TreeNode node = stack.pop(); + result.add(0, node.val); // Insert node.val at the beginning of the result list + if (node.left != null) + stack.push(node.left); + if (node.right != null) + stack.push(node.right); + } + return result; + } +} + + + ``` + + + + + ```cpp + #include +#include +using namespace std; + +// Definition for a binary tree node provided by the precompiled header. +struct TreeNode; + +class Solution { +public: + vector postorderTraversal(TreeNode* root) { + if (!root) + return {}; + vector result; + stack s; + s.push(root); + while (!s.empty()) { + TreeNode* node = s.top(); + s.pop(); + result.push_back(node->val); + if (node->left) + s.push(node->left); + if (node->right) + s.push(node->right); + } + reverse(result.begin(), result.end()); + return result; + } +}; + + + ``` + + + + + + + + +## References + +- **LeetCode Problem:** [Binary-Tree-Postorder-Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) +- **Solution Link:** [Binary-Tree-Postorder-Traversal Solution on LeetCode](https://leetcode.com/problems/binary-tree-postorder-traversal/solutions/5273312/binary-tree-postorder-traversal-solution) +- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) diff --git a/solutions/lc-solutions/0100-0199/0146-lru-cache.md b/solutions/lc-solutions/0100-0199/0146-lru-cache.md new file mode 100644 index 0000000..3000a86 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0146-lru-cache.md @@ -0,0 +1,292 @@ +--- +id: lru-cache +title: LRU Cache +sidebar_label: 0146-LRU Cache +tags: + - Linked list + - LeetCode + - Python + - Hash tree + +description: "This is a solution to the LRU Cache on LeetCode." +--- + + +## Problem Description +Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. + +Implement the `LRUCache` class: + +`LRUCache(int capacity)` Initialize the LRU cache with positive size capacity. +int get(int key) Return the value of the key if the key exists, otherwise `return -1`. +`void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value `pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key. +The functions `get` and `put` must each run in `O(1)` average time complexity. + + + +### Examples + +**Example 1:** + +```plaintext +Input +["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"] +[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]] +Output +[null, null, null, 1, null, -1, null, -1, 3, 4] + +Explanation +LRUCache lRUCache = new LRUCache(2); +lRUCache.put(1, 1); // cache is {1=1} +lRUCache.put(2, 2); // cache is {1=1, 2=2} +lRUCache.get(1); // return 1 +lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} +lRUCache.get(2); // returns -1 (not found) +lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} +lRUCache.get(1); // return -1 (not found) +lRUCache.get(3); // return 3 +lRUCache.get(4); // return 4 +``` + + +### Constraints + +- $1 <= capacity <= 3000$ +- $0 <= key <= {10^{4}}$ +- $0 <= value <= {10^{5}}$ +- At most ${2 * 10^{5}}$ calls will be made to `get` and `put`. + +--- + + +## Intuition +Track 2 things: + +1. Key, value pairs in a cache dictionary. +2. Key, counter (of key use) pairs in a use dictionary. + +Automatically track the least used key using a Heap/PriorityQueue. + +## Approach + +### Put Function: +1. If the key is in our cache dictionary, update its value. + - We initialize a counter variable that counts the timestamp of our LRU cache calls. We use this counter to update the value of the use dictionary and then increment the counter. + +2. If the key is not in the cache, we first check if the cache has reached capacity. If so: + 1. While the heap top element (i.e., the least recently used (lowest counter) key) doesn't match the counter in the use dictionary, we keep popping from the heap and updating its contents. (Note: this is done in 2 calls: `heappop` old counter, `heappush` new counter). + 2. Once the heap is updated, we pop one last time from the heap, as this is the least recently used key, and we delete this from the cache and use dictionaries. + 3. Finally, we add the new (key, value) pair in the cache and (key, counter) in the use dictionaries. + +### Get Function: +1. If the key is in the cache, update its counter value in the use dictionary, increment the counter, and return the value stored in the cache. +2. Else, return -1. + + +### Code in Different languages +#### Code in C++ + +```c++ +class LRUCache { +public: + class Node{ + public: + int key; + int val; + Node* prev; + Node* next; + + Node(int key, int val){ + this->key = key; + this->val = val; + } + }; + + Node* head = new Node(-1, -1); + Node* tail = new Node(-1, -1); + + int cap; + unordered_map m; + + LRUCache(int capacity) { + cap = capacity; + head -> next = tail; + tail -> prev = head; + } + + void addNode(Node* newnode){ + Node* temp = head -> next; + + newnode -> next = temp; + newnode -> prev = head; + + head -> next = newnode; + temp -> prev = newnode; + } + + void deleteNode(Node* delnode){ + Node* prevv = delnode -> prev; + Node* nextt = delnode -> next; + + prevv -> next = nextt; + nextt -> prev = prevv; + } + + int get(int key) { + if(m.find(key) != m.end()){ + Node* resNode = m[key]; + int ans = resNode -> val; + + m.erase(key); + deleteNode(resNode); + addNode(resNode); + + m[key] = head -> next; + return ans; + } + return -1; + } + + void put(int key, int value) { + if(m.find(key) != m.end()){ + Node* curr = m[key]; + m.erase(key); + deleteNode(curr); + } + + if(m.size() == cap){ + m.erase(tail -> prev -> key); + deleteNode(tail -> prev); + } + + addNode(new Node(key, value)); + m[key] = head -> next; + } +}; +``` + +#### Java +```java +class LRUCache { + class Node { + int key; + int val; + Node prev; + Node next; + + Node(int key, int val) { + this.key = key; + this.val = val; + } + } + + Node head = new Node(-1, -1); + Node tail = new Node(-1, -1); + int cap; + HashMap m = new HashMap<>(); + + public LRUCache(int capacity) { + cap = capacity; + head.next = tail; + tail.prev = head; + } + + private void addNode(Node newnode) { + Node temp = head.next; + + newnode.next = temp; + newnode.prev = head; + + head.next = newnode; + temp.prev = newnode; + } + + private void deleteNode(Node delnode) { + Node prevv = delnode.prev; + Node nextt = delnode.next; + + prevv.next = nextt; + nextt.prev = prevv; + } + + public int get(int key) { + if (m.containsKey(key)) { + Node resNode = m.get(key); + int ans = resNode.val; + + m.remove(key); + deleteNode(resNode); + addNode(resNode); + + m.put(key, head.next); + return ans; + } + return -1; + } + + public void put(int key, int value) { + if (m.containsKey(key)) { + Node curr = m.get(key); + m.remove(key); + deleteNode(curr); + } + + if (m.size() == cap) { + m.remove(tail.prev.key); + deleteNode(tail.prev); + } + + addNode(new Node(key, value)); + m.put(key, head.next); + } +} +``` + + +#### Python +```python +class LRUCache: + def __init__(self, capacity: int): + self.capacity = capacity + self.cache = {} + self.heap = [] + self.use = defaultdict(int) + self.counter = 0 + + def get(self, key: int) -> int: + if key in self.cache: + self.use[key] = self.counter + self.counter += 1 + return self.cache[key] + + return -1 + + def put(self, key: int, value: int) -> None: + + if key in self.cache: + self.cache[key] = value + self.use[key] = self.counter + self.counter += 1 + return + + if len(self.cache) >= self.capacity: + while self.heap[0][0] != self.use[self.heap[0][1]]: + _, k = heappop(self.heap) + heappush(self.heap, (self.use[k], k)) + _, k = heappop(self.heap) + del self.cache[k] + del self.use[k] + + self.cache[key] = value + self.use[key] = self.counter + heappush(self.heap, (self.use[key], key)) + self.counter += 1 +``` + + + + +### Complexity +- Time complexity: $O(n)$ + +- Space complexity: $O(1)$ diff --git a/solutions/lc-solutions/0100-0199/0147-insertion-sort-list.md b/solutions/lc-solutions/0100-0199/0147-insertion-sort-list.md new file mode 100644 index 0000000..ad4df21 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0147-insertion-sort-list.md @@ -0,0 +1,131 @@ +--- +id: insertion-sort-list +title: Insertion sort list +sidebar_label: 0147-Insertion sort list +tags: + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Insertion sort list problem on LeetCode." +--- + +## Problem Description + +Given the `head` of a singly linked list, sort the list using insertion sort, and return the sorted list's head. + +The steps of the insertion sort algorithm: + +1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. +2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. +3. It repeats until no input elements remain. +4. The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration. + +![alt](https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif) + +### Examples + +**Example 1:** + +![alt](https://assets.leetcode.com/uploads/2021/03/04/sort1linked-list.jpg) + +``` +Input: head = [4,2,1,3] +Output: [1,2,3,4] +``` + +**Example 2:** + +![alt](https://assets.leetcode.com/uploads/2021/03/04/sort2linked-list.jpg) + +``` +Input: head = [-1,5,3,4,0] +Output: [-1,0,3,4,5] +``` + + + + +### Constraints + +- The number of nodes in the list is in the range `[1, 5000]`. +- `5000 <= Node.val <= 5000` + + +--- + +## Solution + +## Approach + +1. **Extract Values:** + - Create a vector `v` to store the values of the linked list nodes. + - Traverse the linked list and push each node's value into the vector `v`. + +2. **Sort Values:** + - Use the `sort` function to sort the vector `v` in ascending order. + +3. **Reconstruct Sorted Linked List:** + - Initialize a new `ListNode` pointer `temp` with a dummy value. + - Use another pointer `temp1` to keep track of the new sorted linked list. + - Traverse the sorted vector `v` from the end to the beginning: + - Create a new node with the current value of `v`. + - Set the `next` pointer of the new node to `temp1`. + - Update `temp1` to point to the new node. + +4. **Return the Sorted List:** + - Return `temp1`, which now points to the head of the sorted linked list. + + + + +### Code in Different Languages + +### java +```java +class Solution { + public ListNode insertionSortList(ListNode head) { + ListNode dummy= new ListNode(0); + ListNode current=head; + + while(current != null){ + ListNode prev=dummy; + ListNode nextNode=current.next; + + while(prev.next!=null && prev.next.val < current.val){ + prev=prev.next; + } + + current.next=prev.next; + prev.next=current; + current=nextNode; + } + return dummy.next; + } +} + +``` + +### C++ +```cpp +class Solution { +public: + ListNode* insertionSortList(ListNode* head) { + vectorv; + while(head!=NULL){ + v.push_back(head->val); + head=head->next; + + } + sort(v.begin(),v.end()); + ListNode* temp=new ListNode(0); + ListNode* temp1=NULL; + for(int i=v.size()-1;i>=0;i--){ + temp=new ListNode(v[i]); + temp->next=temp1; + temp1=temp; + } + return temp1; + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0148-sort-list.md b/solutions/lc-solutions/0100-0199/0148-sort-list.md new file mode 100644 index 0000000..41f9491 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0148-sort-list.md @@ -0,0 +1,266 @@ +--- +id: sort-list +title: Sort List +sidebar_label: 0148- Sort List +tags: + - DSA + - Leetcode + - Linked List + +description: "This is a solution to the Sort List on LeetCode." +--- + +## Problem Statement + +Given the head of a linked list, return the list after sorting it in ascending order. + +**Example 1:** + +``` +Input: head = [4,2,1,3] +Output: [1,2,3,4] +``` + +**Example 2:** + +``` +Input: head = [-1,5,3,4,0] +Output: [-1,0,3,4,5] +``` + +**Example 3:** + +``` +Input: head = [] +Output: [] +``` + +### Constraints: + +- The number of nodes in the list is in the range $[0, 5 * 10^4].$ +- $-10^5 <= Node.val <= 10^5$ + +## Algorithm + +The algorithm uses the merge sort technique to sort a singly linked list. The steps involved are as follows: + +1. **Base Case**: + + - If the list is empty or contains only one element, it is already sorted. Return the head. + +2. **Splitting the List**: + + - Use two pointers, `slow` and `fast`, to find the middle of the list. + - Move `slow` one step at a time and `fast` two steps at a time. + - When `fast` reaches the end of the list, `slow` will be at the middle. + - Split the list into two halves at the middle. + +3. **Recursive Sorting**: + + - Recursively sort the two halves. + +4. **Merging**: + - Merge the two sorted halves into a single sorted list. + +## C++ Implementation + +```cpp +class Solution { +public: + ListNode* sortList(ListNode* head) { + if (head == NULL || head->next == NULL) + return head; + + ListNode *temp = NULL; + ListNode *slow = head; + ListNode *fast = head; + + while (fast != NULL && fast->next != NULL) { + temp = slow; + slow = slow->next; + fast = fast->next->next; + } + temp->next = NULL; + + ListNode* l1 = sortList(head); + ListNode* l2 = sortList(slow); + + return merge(l1, l2); + } + + ListNode* merge(ListNode *l1, ListNode *l2) { + ListNode *ptr = new ListNode(0); + ListNode *curr = ptr; + + while (l1 != NULL && l2 != NULL) { + if (l1->val <= l2->val) { + curr->next = l1; + l1 = l1->next; + } else { + curr->next = l2; + l2 = l2->next; + } + curr = curr->next; + } + if (l1 != NULL) { + curr->next = l1; + } + if (l2 != NULL) { + curr->next = l2; + } + return ptr->next; + } +}; +``` + +## Python Implementation + +```python +class ListNode: + def __init__(self, x=0, next=None): + self.val = x + self.next = next + +class Solution: + def sortList(self, head: ListNode) -> ListNode: + if not head or not head.next: + return head + + # Find the middle point + slow, fast = head, head + prev = None + while fast and fast.next: + prev = slow + slow = slow.next + fast = fast.next.next + + # Split the list into two halves + prev.next = None + + # Recursively sort the two halves + l1 = self.sortList(head) + l2 = self.sortList(slow) + + # Merge the sorted halves + return self.merge(l1, l2) + + def merge(self, l1: ListNode, l2: ListNode) -> ListNode: + dummy = ListNode() + curr = dummy + + while l1 and l2: + if l1.val <= l2.val: + curr.next = l1 + l1 = l1.next + else: + curr.next = l2 + l2 = l2.next + curr = curr.next + + if l1: + curr.next = l1 + if l2: + curr.next = l2 + + return dummy.next +``` + +## Java Implementation + +```java +class Solution { + public ListNode sortList(ListNode head) { + if (head == null || head.next == null) + return head; + + ListNode slow = head, fast = head, temp = null; + + while (fast != null && fast.next != null) { + temp = slow; + slow = slow.next; + fast = fast.next.next; + } + temp.next = null; + + ListNode l1 = sortList(head); + ListNode l2 = sortList(slow); + + return merge(l1, l2); + } + + private ListNode merge(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(0); + ListNode curr = dummy; + + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + curr.next = l1; + l1 = l1.next; + } else { + curr.next = l2; + l2 = l2.next; + } + curr = curr.next; + } + if (l1 != null) { + curr.next = l1; + } + if (l2 != null) { + curr.next = l2; + } + return dummy.next; + } +} +``` + +## JavaScript Implementation + +```javascript +function ListNode(val, next = null) { + this.val = val; + this.next = next; +} + +var sortList = function (head) { + if (!head || !head.next) return head; + + let slow = head, + fast = head, + temp = null; + + while (fast && fast.next) { + temp = slow; + slow = slow.next; + fast = fast.next.next; + } + temp.next = null; + + const l1 = sortList(head); + const l2 = sortList(slow); + + return merge(l1, l2); +}; + +function merge(l1, l2) { + const dummy = new ListNode(0); + let curr = dummy; + + while (l1 && l2) { + if (l1.val <= l2.val) { + curr.next = l1; + l1 = l1.next; + } else { + curr.next = l2; + l2 = l2.next; + } + curr = curr.next; + } + if (l1) { + curr.next = l1; + } + if (l2) { + curr.next = l2; + } + return dummy.next; +} +``` diff --git a/solutions/lc-solutions/0100-0199/0149-max-points-on-a-line.md b/solutions/lc-solutions/0100-0199/0149-max-points-on-a-line.md new file mode 100644 index 0000000..92bfcf6 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0149-max-points-on-a-line.md @@ -0,0 +1,179 @@ +--- +id: max-points-on-a-line.md +title: Max Points on a Line +sidebar_label: 0149- Max Points on a Line +tags: + - Leetcode +description: "This is a solution to the Max Point on a Line on LeetCode." +--- + +### Problem Satement + +Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line. + +### Examples + +**Example 1:** + +``` +Input: points = [[1,1],[2,2],[3,3]] +Output: 3 +``` + +**Example 2:** + +``` +Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] +Output: 4 +``` + +### Constraints: + +- $1 <= points.length <= 300$ +- $points[i].length == 2$ +- $-10^4 <= xi, yi <= 10^4$ +- All the points are unique. + +### Algorithm Explanation + +1. **Input Handling**: + + - If there are 2 or fewer points, all points will always lie on the same line, so we can directly return the number of points. + +2. **Initialization**: + + - Initialize `maxi` to 2, since at least two points can define a line. + +3. **Iterate through each pair of points**: + + - Use a nested loop to select pairs of points `(i, j)` where `i < j`. + +4. **Count points on the line**: + + - For each pair `(i, j)`, initialize a count of 2 (since the pair itself constitutes two points on the line). + - Check every other point `k` to see if it lies on the line defined by `(i, j)`. + - To determine if three points are collinear, use the slope comparison: + `(y2 - y1) \times (x1 - x3) = (y1 - y3) \times (x2 - x1)` + This equation avoids division and thus floating-point inaccuracies. + +5. **Update Maximum Count**: + + - Update `maxi` if the current line defined by points `(i, j)` has more points than the previously recorded maximum. + +6. **Return Result**: + - After checking all pairs, return the maximum number of collinear points found. + +### Code Implementation + +#### C++ Implementation + +```cpp +class Solution { +public: + int maxPoints(vector>& points) { + int n = points.size(); + + if(n <= 2) + return n; + + int maxi = 2; + for(int i = 0; i < n; i++) { + for(int j = i + 1; j < n; j++) { + int count = 2; + for(int k = 0; k < n; k++) { + if(k != i && k != j) { + if((points[j][1] - points[i][1]) * (points[i][0] - points[k][0]) == + (points[i][1] - points[k][1]) * (points[j][0] - points[i][0])) { + count++; + } + } + } + maxi = max(maxi, count); + } + } + return maxi; + } +}; +``` + +#### Python Implementation + +```python +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + n = len(points) + + if n <= 2: + return n + + maxi = 2 + for i in range(n): + for j in range(i + 1, n): + count = 2 + for k in range(n): + if k != i and k != j: + if (points[j][1] - points[i][1]) * (points[i][0] - points[k][0]) == \ + (points[i][1] - points[k][1]) * (points[j][0] - points[i][0]): + count += 1 + maxi = max(maxi, count) + return maxi +``` + +#### Java Implementation + +```java +class Solution { + public int maxPoints(int[][] points) { + int n = points.length; + + if (n <= 2) + return n; + + int maxi = 2; + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + int count = 2; + for (int k = 0; k < n; k++) { + if (k != i && k != j) { + if ((points[j][1] - points[i][1]) * (points[i][0] - points[k][0]) == + (points[i][1] - points[k][1]) * (points[j][0] - points[i][0])) { + count++; + } + } + } + maxi = Math.max(maxi, count); + } + } + return maxi; + } +} +``` + +#### JavaScript Implementation + +```javascript +var maxPoints = function (points) { + let n = points.length; + + if (n <= 2) return n; + + let maxi = 2; + for (let i = 0; i < n; i++) { + for (let j = i + 1; j < n; j++) { + let count = 2; + for (let k = 0; k < n; k++) { + if (k !== i && k !== j) { + if ( + (points[j][1] - points[i][1]) * (points[i][0] - points[k][0]) === + (points[i][1] - points[k][1]) * (points[j][0] - points[i][0]) + ) { + count++; + } + } + } + maxi = Math.max(maxi, count); + } + } + return maxi; +}; +``` diff --git a/solutions/lc-solutions/0100-0199/0150-Evaluate-Reverse-Polish-Notation.md b/solutions/lc-solutions/0100-0199/0150-Evaluate-Reverse-Polish-Notation.md new file mode 100644 index 0000000..70d497e --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0150-Evaluate-Reverse-Polish-Notation.md @@ -0,0 +1,238 @@ +--- +id: evaluate-reverse-polish-notation +title: Evaluate Reverse Polish Notation +sidebar_label: 150-Evaluate-Reverse-Polish_Notation +tags: + - Reverse Polish Notation + - Stack + - Evaluation +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Evaluate-Reverse-Polish_Notation](https://leetcode.com/problems/Evaluate-Reverse-Polish_Notation/description/) | [Evaluate-Reverse-Polish_Notation Solution on LeetCode](https://leetcode.com/problems/Evaluate-Reverse-Polish_Notation/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +You are given an array of strings `tokens` that represents an arithmetic expression in Reverse Polish Notation. + +Evaluate the expression and return an integer that represents the value of the expression. + +Note that: +- The valid operators are '+', '-', '*', and '/'. +- Each operand may be an integer or another expression. +- The division between two integers always truncates toward zero. +- There will not be any division by zero. +- The input represents a valid arithmetic expression in reverse polish notation. +- The answer and all the intermediate calculations can be represented in a 32-bit integer. + +### Examples + +#### Example 1 +**Input**: `tokens = ["2", "1", "+", "3", "*"]` +**Output**: `9` +**Explanation**: ((2 + 1) * 3) = 9 + +#### Example 2 +**Input**: `tokens = ["4", "13", "5", "/", "+"]` +**Output**: `6` +**Explanation**: (4 + (13 / 5)) = 6 + +#### Example 3 +**Input**: `tokens = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]` +**Output**: `22` +**Explanation**: +((10 * (6 / ((9 + 3) * -11))) + 17) + 5 += ((10 * (6 / (12 * -11))) + 17) + 5 += ((10 * (6 / -132)) + 17) + 5 += ((10 * 0) + 17) + 5 += (0 + 17) + 5 += 17 + 5 += 22 + +## Constraints + +- `1 <= tokens.length <= 10^4` +- `tokens[i]` is either an operator: `"+"`, `"-"`, `"*"` or `"/"`, or an integer in the range `[-200, 200]`. + +## Approach + +1. Initialize an empty stack. +2. Iterate over each token in the `tokens` array: + - If the token is an operand (integer), push it onto the stack. + - If the token is an operator, pop the necessary number of operands from the stack, apply the operator, and push the result back onto the stack. +3. The final result will be the only element left in the stack. + +## Solution in different languages: + +### Solution in Python +```python +def evalRPN(tokens): + stack = [] + for token in tokens: + if token in "+-*/": + b = stack.pop() + a = stack.pop() + if token == '+': + stack.append(a + b) + elif token == '-': + stack.append(a - b) + elif token == '*': + stack.append(a * b) + elif token == '/': + stack.append(int(a / b)) # use int() for truncating towards zero + else: + stack.append(int(token)) + return stack[0] +``` + +### Solution in Java +```java +import java.util.Stack; + +class Solution { + public int evalRPN(String[] tokens) { + Stack stack = new Stack<>(); + for (String token : tokens) { + if ("+-*/".contains(token)) { + int b = stack.pop(); + int a = stack.pop(); + switch (token) { + case "+": + stack.push(a + b); + break; + case "-": + stack.push(a - b); + break; + case "*": + stack.push(a * b); + break; + case "/": + stack.push(a / b); + break; + } + } else { + stack.push(Integer.parseInt(token)); + } + } + return stack.pop(); + } +} +``` + +### Solution in C++ +```cpp +#include +#include +#include + +class Solution { +public: + int evalRPN(std::vector& tokens) { + std::stack stack; + for (const std::string& token : tokens) { + if (token == "+" || token == "-" || token == "*" || token == "/") { + int b = stack.top(); stack.pop(); + int a = stack.top(); stack.pop(); + if (token == "+") stack.push(a + b); + else if (token == "-") stack.push(a - b); + else if (token == "*") stack.push(a * b); + else if (token == "/") stack.push(a / b); + } else { + stack.push(std::stoi(token)); + } + } + return stack.top(); + } +}; +``` + +### Solution in C +```c +#include +#include +#include + +#define STACK_SIZE 10000 + +typedef struct { + int data[STACK_SIZE]; + int top; +} Stack; + +void init(Stack* s) { + s->top = -1; +} + +void push(Stack* s, int value) { + s->data[++s->top] = value; +} + +int pop(Stack* s) { + return s->data[s->top--]; +} + +int evalRPN(char ** tokens, int tokensSize){ + Stack stack; + init(&stack); + for (int i = 0; i < tokensSize; i++) { + char *token = tokens[i]; + if (strcmp(token, "+") == 0 || strcmp(token, "-") == 0 || strcmp(token, "*") == 0 || strcmp(token, "/") == 0) { + int b = pop(&stack); + int a = pop(&stack); + if (strcmp(token, "+") == 0) push(&stack, a + b); + else if (strcmp(token, "-") == 0) push(&stack, a - b); + else if (strcmp(token, "*") == 0) push(&stack, a * b); + else if (strcmp(token, "/") == 0) push(&stack, a / b); + } else { + push(&stack, atoi(token)); + } + } + return pop(&stack); +} +``` + +### Solution in JavaScript +```js +var evalRPN = function(tokens) { + const stack = []; + for (const token of tokens) { + if ("+-*/".includes(token)) { + const b = stack.pop(); + const a = stack.pop(); + switch (token) { + case '+': + stack.push(a + b); + break; + case '-': + stack.push(a - b); + break; + case '*': + stack.push(a * b); + break; + case '/': + stack.push(Math.trunc(a / b)); + break; + } + } else { + stack.push(Number(token)); + } + } + return stack[0]; +}; +``` + +### Step-by-step Algorithm +1. Initialize an empty stack. +2. Iterate through each token in the `tokens` list. +3. If the token is an operand (number), push it onto the stack. +4. If the token is an operator, pop two operands from the stack. + - Apply the operator on the two operands. + - Push the result back onto the stack. +5. Continue this process until all tokens are processed. +6. The final result will be the last item remaining in the stack. + +### Conclusion +The Reverse Polish Notation evaluation is efficiently handled using a stack. This approach ensures that we can process the expression in a single pass through the tokens, leading to a time complexity of O(n) and a space complexity of O(n) where n is the number of tokens. \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0151-reverse-words-in-a-string.md b/solutions/lc-solutions/0100-0199/0151-reverse-words-in-a-string.md new file mode 100644 index 0000000..fc2097b --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0151-reverse-words-in-a-string.md @@ -0,0 +1,128 @@ +--- +id: reverse-words-in-a-string +title: Reverse Words in a String (LeetCode) +sidebar_label: 0151-Reverse Words in a String +tags: + - Two Pointers + - String +description: Given an input string s, reverse the order of the words. +sidebar_position: 0151 +--- + +## Problem Description + +A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. + +Return a string of the words in reverse order concatenated by a single space. + +Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. + +### Example 1 + +- **Input:** ` s = "the sky is blue" ` +- **Output:** `"blue is sky the"` +- **Explanation:** The reverse of the whole string is returned along with spaces. + +### Example 2 + +- **Input:** ` s = " hello world " ` +- **Output:** `"world hello"` +- **Explanation:** Your reversed string should not contain leading or trailing spaces. + +### Example 3 + +- **Input:** ` s = "a good example" ` +- **Output:** `"example good a"` +- **Explanation:** =You need to reduce multiple spaces between two words to a single space in the reversed string. + + + +### Constraints + +- `1 <= s.length <= 10^4` +- `s contains English letters (upper-case and lower-case), digits, and spaces ' '.` +- `There is at least one word in s.` + +## Approach + + - 1. The code starts by trimming the input string s to remove any leading and trailing spaces. + + - 2. It then splits the trimmed string into words based on spaces using a stringstream. The words are stored in the words vector. + + - 3. Next, it initializes an output string out. + + - 4. The code iterates through the words in reverse order (from the last word to the second word) and appends each word followed by a space to the output string. + + - 5. Finally, it appends the first word to the output string without a trailing space. + + + +### Solution Code + +#### C++ + +```c++ +class Solution { +public: + string reverseWords(string s) { + int i = 0, j = s.size() - 1; + while (i <= j && s[i] == ' ') i++; + while (j >= i && s[j] == ' ') j--; + s = s.substr(i, j - i + 1); + vector words; + stringstream ss(s); + string word; + while (ss >> word) { + words.push_back(word); + } + string out = ""; + for (int i = words.size() - 1; i > 0; i--) { + out += words[i] + " "; + } + return out + words[0]; + } +}; + +``` + +#### java +```java +public class Solution { + public String reverseWords(String s) { + int i = 0, j = s.length() - 1; + while (i <= j && s.charAt(i) == ' ') i++; + while (j >= i && s.charAt(j) == ' ') j--; + s = s.substring(i, j + 1); + String[] words = s.split("\\s+"); + StringBuilder out = new StringBuilder(); + for (int k = words.length - 1; k > 0; k--) { + out.append(words[k]).append(" "); + } + return out.append(words[0]).toString(); + } +} + +``` + +#### Python +```python +class Solution: + def reverseWords(self, s: str) -> str: + i, j = 0, len(s) - 1 + while i <= j and s[i] == ' ': + i += 1 + while j >= i and s[j] == ' ': + j -= 1 + s = s[i : j + 1] + words = s.split() + out = [] + for k in range(len(words) - 1, 0, -1): + out.append(words[k]) + out.append(words[0]) + return ' '.join(out) +``` + +#### Conclusion +The above solutions use two-pointers approach to reverse the string. + - 1. Time complexity: O(n) + - 2. Space complexity: O(m)( where M is the total number of words in the input string. ) \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0152-Maximum-Product-Subarray.md b/solutions/lc-solutions/0100-0199/0152-Maximum-Product-Subarray.md new file mode 100644 index 0000000..612657c --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0152-Maximum-Product-Subarray.md @@ -0,0 +1,159 @@ +--- +id: maximum-product-subarray +title: Maximum Product Subarray +sidebar_label: 0152 Maximum Product Subarray +tags: + - Array + - Dynamic Programming + - LeetCode + - Python + - Java + - C++ +description: "This is a solution to the Maximum Product Subarray problem on LeetCode." +--- + +## Problem Description + +Given an integer array nums, find a subarray that has the largest product, and return the product. + +The test cases are generated so that the answer will fit in a 32-bit integer. + +### Examples + +**Example 1:** + +``` +Input: nums = [2,3,-2,4] +Output: 6 +Explanation: [2,3] has the largest product 6. +``` + +**Example 2:** + +``` +Input: nums = [-2,0,-1] +Output: 0 +Explanation: The result cannot be 2, because [-2,-1] is not a subarray. +``` + +### Constraints + +- $1 <= nums.length <= 2 * 10**4$ +- $10 <= nums[i] <= 10$ +- The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. + + +#### Code in Different Languages + + + + + ```python + class Solution(object): + def maxProduct(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + if not nums: + return 0 + + max_prod = nums[0] + min_prod = nums[0] + result = max_prod + + for num in nums[1:]: + if num < 0: + max_prod, min_prod = min_prod, max_prod + + max_prod = max(num, max_prod * num) + min_prod = min(num, min_prod * num) + + result = max(result, max_prod) + + return result + + + + ``` + + + + + ```java + class Solution { + public int maxProduct(int[] nums) { + if (nums.length == 0) + return 0; + + int maxProd = nums[0]; + int minProd = nums[0]; + int result = maxProd; + + for (int i = 1; i < nums.length; ++i) { + if (nums[i] < 0) { + int temp = maxProd; + maxProd = minProd; + minProd = temp; + } + + maxProd = Math.max(nums[i], maxProd * nums[i]); + minProd = Math.min(nums[i], minProd * nums[i]); + + result = Math.max(result, maxProd); + } + + return result; + } +} + + + ``` + + + + + ```cpp + #include +#include + +class Solution { +public: + int maxProduct(vector& nums) { + if (nums.empty()) + return 0; + + int max_prod = nums[0]; + int min_prod = nums[0]; + int result = max_prod; + + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] < 0) + std::swap(max_prod, min_prod); + + max_prod = std::max(nums[i], max_prod * nums[i]); + min_prod = std::min(nums[i], min_prod * nums[i]); + + result = std::max(result, max_prod); + } + + return result; + } +}; + + + ``` + + + + + + + +## References + +- **LeetCode Problem**: [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/maximum-product-subarray/solution/) + +- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) diff --git a/solutions/lc-solutions/0100-0199/0153-find-minimum-in-rotated-sorted-array.md b/solutions/lc-solutions/0100-0199/0153-find-minimum-in-rotated-sorted-array.md new file mode 100644 index 0000000..eb9912f --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0153-find-minimum-in-rotated-sorted-array.md @@ -0,0 +1,107 @@ +--- +id: find-minimum-in-rotated-sorted-array +title: Find Minimum in Rotated Sorted Array(LeetCode) +sidebar_label: 0153-Find Minimum in Rotated Sorted Array +tags: + - Array + - Binary Search +description: Given the sorted rotated array nums of unique elements, return the minimum element of this array. +--- + +## Problem Statement + +Suppose an array of length `n` sorted in ascending order is rotated between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become: + +`[4,5,6,7,0,1,2]` if it was rotated 4 times. +`[0,1,2,4,5,6,7]` if it was rotated 7 times. +Notice that rotating an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`. + +Given the sorted rotated array `nums` of unique elements, return the minimum element of this array. + +You must write an algorithm that runs in `O(log n) time`. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [3,4,5,1,2] +Output: 1 +Explanation: The original array was [1,2,3,4,5] rotated 3 times. +``` + +**Example 2:** + +```plaintext +Input: nums = [4,5,6,7,0,1,2] +Output: 0 +Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times. +``` + +**Example 3:** + +```plaintext +Input: nums = [11,13,15,17] +Output: 11 +Explanation: The original array was [11,13,15,17] and it was rotated 4 times. +``` + +### Constraints + +- `n == nums.length` +- `1 <= n <= 5000` +- `-5000 <= nums[i] <= 5000` +- All the integers of `nums` are unique. +- `nums` is sorted and rotated between `1` and `n` times. + +## Solution + +This problem aims to find the minimum element in a rotated sorted array. The provided solution uses a binary search approach to efficiently find the minimum element. + +### Approach + +#### Algorithm + +1. Initialize two pointers, `low` at the beginning of the array and `high` at the end of the array. +2. Use a `while` loop with the condition `low < high`: +* Calculate the middle index `mid` as `low + (high - low) / 2`. +* Compare the element at index `mid` with the element at index `high`. +* If `num[mid] < num[high]`, it means the minimum element is in the left part, so update `high = mid`. +* If `num[mid] > num[high]`, it means the minimum element is in the right part, so update `low = mid + 1`. +3. When the `while` loop ends, low will be pointing to the minimum element, so return `num[low]`. + +#### Implementation + +```C++ +class Solution { +public: + int findMin(vector &num) { + int low = 0, high = num.size() - 1; + // loop invariant: 1. low < high + // 2. mid != high and thus A[mid] != A[high] (no duplicate exists) + // 3. minimum is between [low, high] + // The proof that the loop will exit: after each iteration either the 'high' decreases + // or the 'low' increases, so the interval [low, high] will always shrink. + while (low < high) { + auto mid = low + (high - low) / 2; + if (num[mid] < num[high]) + // the mininum is in the left part + high = mid; + else if (num[mid] > num[high]) + // the mininum is in the right part + low = mid + 1; + } + + return num[low]; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: O(log n) +- **Space complexity**: O(1) + +### Conclusion + +This algorithm effectively finds the minimum element in a rotated sorted array by using binary search. It maintains the loop invariant that the minimum is between the `low` and `high` indices, and ensures the interval `[low, high]` shrinks in each iteration. This solution is efficient and provides a clear way to handle such problems. diff --git a/solutions/lc-solutions/0100-0199/0154-find-minimum-in-rotated-sorted-array-II.md b/solutions/lc-solutions/0100-0199/0154-find-minimum-in-rotated-sorted-array-II.md new file mode 100644 index 0000000..f8afb7d --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0154-find-minimum-in-rotated-sorted-array-II.md @@ -0,0 +1,134 @@ +--- +id: find-minimum-in-rotated-sorted-array-II +title: Find Minimum in Rotated Sorted Array-II +sidebar_label: 0154-Find Minimum in Rotated Sorted Array-II +tags: + - Array + - Binary Search +description: Given the sorted rotated array nums of unique elements, return the minimum element of this array. +--- + +## Problem Statement + +Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array `nums =[0,1,4,4,5,6,7]` might become: + +`[4,5,6,7,0,1,4]` if it was rotated 4 times. +`[0,1,4,4,5,6,7]` if it was rotated 7 times. +Notice that rotating an array` [a[0], a[1], a[2], ..., a[n-1]] `1 time results in the array` [a[n-1], a[0], a[1], a[2], ..., a[n-2]].` + +Given the sorted rotated array `nums` that may contain duplicates, return the minimum element of this array. + +You must decrease the overall operation steps as much as possible. + +### Examples + +**Example 1:** +```plaintext +Input: nums = [1,3,5] +Output: 1 +``` + +**Example 2:** + +```plaintext +Input: nums = [2,2,2,0,1] +Output: 0 + +``` + + + +### Constraints + +- `n == nums.length` +- `1 <= n <= 5000` +- `-5000 <= nums[i] <= 5000` +- `nums is sorted and rotated between 1 and n times.` + +## Solution + +This problem aims to find the minimum element in a rotated sorted array. The provided solution uses a binary search approach to efficiently find the minimum element. + +### Intuition +- Use modified Binary Search. +- i.e. after finding middle element check if only right side is sorted completely or if only left side is sorted. +- i.e. if middle element is smaller than last element, then right is sorted , else left is sorted. +- The smallest element will lie in the unsorted side because the sorted elements have rotated in that region only. +REPEAT. + +### Approach +- Note : [element_index] = means the element at index [element_index] + +- First find the middle element. +- Now, we need to check which side of [m] is sorted completely i.e. if left is sorted, then the smallest element is on right side and vice versa. So, if `[m] <= [e]` i.e. middle element` <= `end element i.e. right is completely sorted so we need to find in left of [m] therefore `e = m` . +- Else, s = m + 1 i.e. the smallest element is in right side. +REPEAT till s < e and return [s] + +- EDGE-CASE : since array may contain dupicates -> + +- Now if [m] = [s] = [e] i.e. first, last and middle element are same, we can't tell whether left/ right side of [m] is completely sorted so we decreement e by 1 and increement s by 1 so to reduce the array to be searched. Only this edge case leads to the worst case of O(n/2) = O(n). + + + +#### Implementation +#### C++ +```C++ +class Solution { +public: + int findMin(vector& nums) { + int s = 0 , e = nums.size() - 1, m ; + while ( s < e ){ + m = s + (e - s ) / 2 ; + if ( nums[m] == nums[s] && nums[m] == nums[e]){ + s++; e--; + } + else if (nums[m] <= nums[e]) e = m ; + else s = m + 1 ; + } + return nums [s] ; + } +}; +``` + + +#### Java +```java +class Solution { + public int findMin(int[] nums) { + int s = 0 , e = nums.length - 1, m ; + while ( s < e ){ + m = s + (e - s ) / 2 ; + if ( nums[m] == nums[s] && nums[m] == nums[e]){ + s++; e--; + } + else if (nums[m] <= nums[e]) e = m ; + else s = m + 1 ; + } + return nums [s] ; + } +} +``` + +#### Javascript +```javascript +//Note: U need to add Math.floor function while calculating [mid] since JS doesn't implicitly typecast floating no. which may result in unexpected output +var findMin = function(nums) { + let s = 0 , e = nums.length - 1, m ; + while ( s < e ){ + m = Math.floor(s + (e - s ) / 2) ; + if ( nums[m] == nums[s] && nums[m] == nums[e]){ + s++; e--; + } + else if (nums[m] <= nums[e]) e = m ; + else s = m + 1 ; + } + return nums [s] ; +}; +``` + +### Complexity Analysis + +- **Time complexity**: $O(log n)$ +- **Space complexity**: $O(1)$ + + diff --git a/solutions/lc-solutions/0100-0199/0155-min-stack.md b/solutions/lc-solutions/0100-0199/0155-min-stack.md new file mode 100644 index 0000000..09648dc --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0155-min-stack.md @@ -0,0 +1,192 @@ +--- +id: min-stack +title: Min Stack +sidebar_label: 0155-Min stack +tags: + - Array + - Binary Search +description: Given the sorted rotated array nums of unique elements, return the minimum element of this array. +--- + +## Problem Statement +Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. + +Implement the `MinStack` class: + +`MinStack()` initializes the stack object. +`void push(int val)` pushes the element val onto the stack. +`void pop() `removes the element on the top of the stack. +`int top() `gets the top element of the stack. +`int getMin()` retrieves the minimum element in the stack. +You must implement a solution with` O(1)` time complexity for each function. + + + +### Examples + +**Example 1:** + +```plaintext +Input +["MinStack","push","push","push","getMin","pop","top","getMin"] +[[],[-2],[0],[-3],[],[],[],[]] + +Output +[null,null,null,null,-3,null,0,-2] + +Explanation +MinStack minStack = new MinStack(); +minStack.push(-2); +minStack.push(0); +minStack.push(-3); +minStack.getMin(); // return -3 +minStack.pop(); +minStack.top(); // return 0 +minStack.getMin(); // return -2 +``` + +### Constraints + +- `-231 <= val <= 231 - 1` +- Methods `pop`, `top` and `getMin` operations will always be called on non-empty stacks. +- At most `3 * 104` calls will be made to `push`, `pop`, `top`, and `getMin`. + +## Solution +# MinStack Implementation in C++ + +## Overview +The `MinStack` class is a custom stack that supports the following operations: +- `push(val)`: Pushes the element `val` onto the stack. +- `pop()`: Removes the element on the top of the stack. +- `top()`: Gets the top element of the stack. +- `getMin()`: Retrieves the minimum element in the stack. + +## Approach + +### Data Structure +- Use a `vector` of `vector` to implement the stack. +- Each inner vector contains two elements: the actual value being pushed onto the stack and the minimum value in the stack up to that point. + +### Constructor +- Initializes the stack without any specific setup required. + +### Push Operation +- When pushing a value, determine the current minimum value using the `getMin` method. +- If the stack is empty or the new value is smaller than the current minimum, update the minimum value. +- Push the value along with the updated minimum as a pair onto the stack. + +### Pop Operation +- Remove the top element from the stack. + +### Top Operation +- Retrieve the top element of the stack. If the stack is empty, return `-1`. + +### Get Minimum Operation +- Retrieve the minimum element in the stack. If the stack is empty, return `-1`. + +## Summary +The `MinStack` class uses a `vector` of pairs to store each element along with the minimum value at that point in time. This allows all stack operations (`push`, `pop`, `top`, and `getMin`) to be performed efficiently, ensuring constant time complexity for retrieving the minimum element. + + +#### Implementation +### C++ + +```cpp +class MinStack { +private: + vector> st; + +public: + MinStack() { + + } + + void push(int val) { + int min_val = getMin(); + if (st.empty() || min_val > val) { + min_val = val; + } + st.push_back({val, min_val}); + } + + void pop() { + st.pop_back(); + } + + int top() { + return st.empty() ? -1 : st.back()[0]; + } + + int getMin() { + return st.empty() ? -1 : st.back()[1]; + } +}; +``` +### Python +```python +class MinStack: + + def __init__(self): + self.st = [] + + def push(self, val: int) -> None: + min_val = self.getMin() + if min_val == None or min_val > val: + min_val = val + + self.st.append([val, min_val]) + + def pop(self) -> None: + self.st.pop() + + def top(self) -> int: + return self.st[-1][0] if self.st else None + + def getMin(self) -> int: + return self.st[-1][1] if self.st else None +``` + +### Java +```Java +class MinStack { + private List st; + + public MinStack() { + st = new ArrayList<>(); + } + + public void push(int val) { + int[] top = st.isEmpty() ? new int[]{val, val} : st.get(st.size() - 1); + int min_val = top[1]; + if (min_val > val) { + min_val = val; + } + st.add(new int[]{val, min_val}); + } + + public void pop() { + st.remove(st.size() - 1); + } + + public int top() { + return st.isEmpty() ? -1 : st.get(st.size() - 1)[0]; + } + + public int getMin() { + return st.isEmpty() ? -1 : st.get(st.size() - 1)[1]; + } +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(1)$ +- **Space complexity**: $O(n)$ + +### Conclusion +The `MinStack` class uses a `vector` of pairs to store each element along with the minimum value at that point in time. This allows all stack operations (`push`, `pop`, `top`, and `getMin`) to be performed efficiently, ensuring constant time complexity for retrieving the minimum element. + + + + + diff --git a/solutions/lc-solutions/0100-0199/0156-binary-tree-upside-down.md b/solutions/lc-solutions/0100-0199/0156-binary-tree-upside-down.md new file mode 100644 index 0000000..a157e0f --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0156-binary-tree-upside-down.md @@ -0,0 +1,136 @@ +--- +id: binary-tree-upside-down +title: Binary Tree Upside Down +sidebar_label: 0156-Binary Tree Upside Down +tags: + - Binary Tree + - Leet code +description: "Solution to leetocde 156" +--- + +## Problem Description + +Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root. + +### Example: + +``` +Input: [1,2,3,4,5] + + 1 + / \ + 2 3 + / \ +4 5 + +Output: return the root of the binary tree [4,5,2,#,#,3,1] + + 4 + / \ + 5 2 + / \ + 3 1 +``` + +### Algorithm + +1. **Base Case**: If the root is `None` or the root has no left child, return the root. +2. **Recursive Case**: Recursively process the left child of the root. +3. **Reassign Pointers**: Once you reach the new root, start reassigning the pointers: + - The left child's left pointer should point to the original root's right child. + - The left child's right pointer should point to the original root. +4. **Clear Original Pointers**: Set the original root's left and right pointers to `None`. +5. **Return the New Root**: Return the new root of the upside-down tree. + +### Python + +```python +from typing import Optional + +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def upsideDownBinaryTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + if root is None or root.left is None: + return root + new_root = self.upsideDownBinaryTree(root.left) + root.left.right = root + root.left.left = root.right + root.left = None + root.right = None + return new_root +``` + +### C++ + +```cpp +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + TreeNode* upsideDownBinaryTree(TreeNode* root) { + if (root == nullptr || root->left == nullptr) + return root; + TreeNode* new_root = upsideDownBinaryTree(root->left); + root->left->right = root; + root->left->left = root->right; + root->left = nullptr; + root->right = nullptr; + return new_root; + } +}; +``` + +### Java + +```java +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +public class Solution { + public TreeNode upsideDownBinaryTree(TreeNode root) { + if (root == null || root.left == null) return root; + TreeNode newRoot = upsideDownBinaryTree(root.left); + root.left.left = root.right; + root.left.right = root; + root.left = null; + root.right = null; + return newRoot; + } +} +``` + +### JavaScript + +```javascript +function TreeNode(val) { + this.val = val; + this.left = this.right = null; +} + +var upsideDownBinaryTree = function (root) { + if (root === null || root.left === null) return root; + let newRoot = upsideDownBinaryTree(root.left); + root.left.left = root.right; + root.left.right = root; + root.left = null; + root.right = null; + return newRoot; +}; +``` diff --git a/solutions/lc-solutions/0100-0199/0157-Read-n-characters-given.md b/solutions/lc-solutions/0100-0199/0157-Read-n-characters-given.md new file mode 100644 index 0000000..ffd24f3 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0157-Read-n-characters-given.md @@ -0,0 +1,219 @@ +--- +id: read-n-characters-given +title: Read N characters Given +sidebar_label: 0157-Read N Characters Given +tags: + - Leet code +description: "Solution to leetocde 157" +--- + +### Problem Description + +Given a file and assume that you can only read the file using a given method read4, implement a method to read n characters. + +### Examples + +Example 1: + +``` +Input: file = "abc", n = 4 +Output: 3 +Explanation: After calling your read method, buf should contain "abc". We read a total of 3 characters from the file, so return 3. Note that "abc" is the file's content, not buf. buf is the destination buffer that you will have to write the results to. +``` + +Example 2: + +``` +Input: file = "abcde", n = 5 +Output: 5 +Explanation: After calling your read method, buf should contain "abcde". We read a total of 5 characters from the file, so return 5. +``` + +Example 3: + +``` +Input: file = "abcdABCD1234", n = 12 +Output: 12 +Explanation: After calling your read method, buf should contain "abcdABCD1234". We read a total of 12 characters from the file, so return 12. +``` + +Example 4: + +``` +Input: file = "leetcode", n = 5 +Output: 5 +Explanation: After calling your read method, buf should contain "leetc". We read a total of 5 characters from the file, so return 5. +``` + +### Note: + +- Consider that you cannot manipulate the file directly, the file is only accesible for read4 but not for read. +- The read function will only be called once for each test case. +- You may assume the destination buffer array, buf, is guaranteed to have enough space for storing n characters. + +### Algorithm + +1. **Initialization**: + + - `buf4`: A temporary buffer that stores the characters read by `read4`. + - `i4`: Index for iterating over `buf4`. + - `n4`: Number of characters actually read by `read4`. + - `i`: Index for iterating over the destination buffer `buf`. + +2. **Reading Characters**: + + - The loop continues until `i` (number of characters written to `buf`) reaches `n` (the requested number of characters). + - If all characters in `buf4` are consumed (`i4 == n4`), `read4` is called again to refill `buf4` and reset `i4`. + - If `read4` returns 0 (`n4 == 0`), it means the end of the file has been reached, and the function returns the number of characters read so far. + - Characters from `buf4` are copied to `buf` one by one, and both indices (`i` and `i4`) are incremented accordingly. + +3. **Return**: + - The function returns the total number of characters read, which is the value of `i`. + +### Code Implementation + +### C++ + +```cpp + +class Solution { + public: + /** + * @param buf Destination buffer + * @param n Number of characters to read + * @return The number of actual characters read + */ + int read(char* buf, int n) { + char* buf4 = new char[4]; + int i4 = 0; // buf4's index + int n4 = 0; // buf4's size + int i = 0; // buf's index + + while (i < n) { + if (i4 == n4) { // All the characters in the buf4 are consumed. + i4 = 0; // Reset the buf4's index. + n4 = read4(buf4); // Read <= 4 characters from the file to the buf4. + if (n4 == 0) // Reach the EOF. + return i; + } + buf[i++] = buf4[i4++]; + } + + return i; + } +}; +``` + +### Python + +```python +class Solution: + def __init__(self): + self.buf4 = [''] * 4 # Temporary buffer to store characters read by read4 + self.i4 = 0 # Index for iterating over buf4 + self.n4 = 0 # Number of characters actually read by read4 + + def read4(self, buf4): + # This method is provided in the parent class or environment. + pass + + def read(self, buf, n): + i = 0 # Index for the destination buffer buf + + while i < n: + if self.i4 == self.n4: + self.n4 = self.read4(self.buf4) + self.i4 = 0 + if self.n4 == 0: + break + + while i < n and self.i4 < self.n4: + buf[i] = self.buf4[self.i4] + i += 1 + self.i4 += 1 + + return i +``` + +### Java + +```java +/** + * The read4 API is defined in the parent class Reader4. + * int read4(char[] buf4); + */ + +public class Solution extends Reader4 { + private char[] buf4 = new char[4]; + private int i4 = 0; + private int n4 = 0; + + /** + * @param buf Destination buffer + * @param n Number of characters to read + * @return The number of actual characters read + */ + public int read(char[] buf, int n) { + int i = 0; + + while (i < n) { + if (i4 == n4) { + n4 = read4(buf4); + i4 = 0; + if (n4 == 0) { + break; + } + } + + while (i < n && i4 < n4) { + buf[i++] = buf4[i4++]; + } + } + + return i; + } +} +``` + +### JavaScript + +```javascript +/** + * Definition for read4 API + * read4 = function(buf4) { + * // Reads 4 characters at a time and writes to buf4 + * // Returns the number of characters actually read + * } + */ + +var Solution = function () { + this.buf4 = new Array(4); + this.i4 = 0; + this.n4 = 0; +}; + +/** + * @param {character[]} buf Destination buffer + * @param {number} n Number of characters to read + * @return {number} The number of actual characters read + */ +Solution.prototype.read = function (buf, n) { + let i = 0; + + while (i < n) { + if (this.i4 === this.n4) { + this.n4 = read4(this.buf4); + this.i4 = 0; + if (this.n4 === 0) { + break; + } + } + + while (i < n && this.i4 < this.n4) { + buf[i++] = this.buf4[this.i4++]; + } + } + + return i; +}; +``` diff --git a/solutions/lc-solutions/0100-0199/0158-read-n-char-given-read4-II.md b/solutions/lc-solutions/0100-0199/0158-read-n-char-given-read4-II.md new file mode 100644 index 0000000..cc2f8ca --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0158-read-n-char-given-read4-II.md @@ -0,0 +1,186 @@ +--- +id: read-n-characters-given-read4-II +title: Read N characters Given Read4 -II +sidebar_label: 0158-Read N Characters Given Read4 -II +tags: + - Leet code +description: "Solution to leetocde 157" +--- + +### Problem Description + +#### Method read4: + +The API read4 reads 4 consecutive characters from the file, then writes those characters into the buffer array buf. + +The return value is the number of actual characters read. + +- Note that read4() has its own file pointer, much like FILE *fp in C. + +#### Definition of read4: +``` + Parameter: char[] buf + Returns: int +``` +- Note: buf[] is destination not source, the results from read4 will be copied to buf[] + +Below is a high level example of how read4 works: + +- File file("abcdefghijk"); // File is "abcdefghijk", initially file pointer (fp) points to 'a' +- char[] buf = new char[4]; // Create buffer with enough space to store characters +- read4(buf); // read4 returns 4. Now buf = "abcd", fp points to 'e' +- read4(buf); // read4 returns 4. Now buf = "efgh", fp points to 'i' +- read4(buf); // read4 returns 3. Now buf = "ijk", fp points to end of file + + +#### Method read: + +By using the read4 method, implement the method read that reads n characters from the file and store it in the buffer array buf. Consider that you cannot manipulate the file directly. + +- The return value is the number of actual characters read. + +#### Definition of read: +``` + Parameters: char[] buf, int n + Returns: int +``` +- Note: buf[] is destination not source, you will need to write the results to buf[] + +### Examples + +***Example 1:*** +``` +File file("abc"); +Solution sol; +// Assume buf is allocated and guaranteed to have enough space for storing all characters from the file. +sol.read(buf, 1); // After calling your read method, buf should contain "a". We read a total of 1 character from the file, so return 1. +sol.read(buf, 2); // Now buf should contain "bc". We read a total of 2 characters from the file, so return 2. +sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0. +``` + +***Example 2:*** +``` +File file("abc"); +Solution sol; +sol.read(buf, 4); // After calling your read method, buf should contain "abc". We read a total of 3 characters from the file, so return 3. +sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0. + ``` + + +#### Note: + +Consider that you cannot manipulate the file directly, the file is only accesible for read4 but not for read. +The read function may be called multiple times. +Please remember to RESET your class variables declared in Solution, as static/class variables are persisted across multiple test cases. Please see here for more details. +You may assume the destination buffer array, buf, is guaranteed to have enough space for storing n characters. +It is guaranteed that in a given test case the same buffer buf is called by read. + + + +### Code Implementation + +### C++ + +```cpp +/** + * The read4 API is defined in the parent class Reader4. + * int read4(char *buf4); + */ + +class Solution { + public: + /** + * @param buf Destination buffer + * @param n Number of characters to read + * @return The number of actual characters read + */ + int read(char* buf, int n) { + int i = 0; // buf's index + + while (i < n) { + if (i4 == n4) { // All the characters in the buf4 are consumed. + i4 = 0; // Reset the buf4's index. + n4 = read4(buf4); // Read <= 4 characters from the file to the buf4. + if (n4 == 0) // Reach the EOF. + return i; + } + buf[i++] = buf4[i4++]; + } + + return i; + } + + private: + char* buf4 = new char[4]; + int i4 = 0; // buf4's index + int n4 = 0; // buf4's size +}; +``` + +### Python + +```python +# The read4 API is already defined for you. +# Def read4(buf4: List[str]) -> int: + +class Solution: + def read(self, buf: List[str], n: int) -> int: + i = 0 # buf's index + + while i < n: + if self.i4 == self.n4: # All the characters in the buf4 are consumed. + self.i4 = 0 # Reset the buf4's index. + # Read <= 4 characters from the file to the buf4. + self.n4 = read4(self.buf4) + if self.n4 == 0: # Reach the EOF. + return i + buf[i] = self.buf4[self.i4] + i += 1 + self.i4 += 1 + + return i + + buf4 = [' '] * 4 + i4 = 0 # buf4's index + n4 = 0 # buf4's size +``` + +### Java + +```java +/** + * The read4 API is defined in the parent class Reader4. + * int read4(char[] buf4); + */ + +public class Solution extends Reader4 { + /** + * @param buf Destination buffer + * @param n Number of characters to read + * @return The number of actual characters read + */ + public int read(char[] buf, int n) { + int i = 0; // buf's index + + while (i < n) { + if (i4 == n4) { // All the characters in the buf4 are consumed. + i4 = 0; // Reset the buf4's index. + n4 = read4(buf4); // Read <= 4 characters from the file to the buf4. + if (n4 == 0) // Reach the EOF. + return i; + } + buf[i++] = buf4[i4++]; + } + + return i; + } + + private char[] buf4 = new char[4]; + private int i4 = 0; // buf4's index + private int n4 = 0; // buf4's size +} +``` + + +#### Source +(https://leetcode.ca/all/158.html) diff --git a/solutions/lc-solutions/0100-0199/0159-longest-substring-with-at.md b/solutions/lc-solutions/0100-0199/0159-longest-substring-with-at.md new file mode 100644 index 0000000..5225c9c --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0159-longest-substring-with-at.md @@ -0,0 +1,169 @@ +--- +id: longest-substring-with-at +title: Longest Substring Given At +sidebar_label: 0159-Longest Substring Given At +tags: + - Leet code +description: "Solution to leetocde 159" +--- + +### Problem Description + +Given a string s , find the length of the longest substring t that contains at most 2 distinct characters. + +### Examples + +**Example 1:** + +``` +Input: "eceba" +Output: 3 +Explanation: t is "ece" which its length is 3. +``` + +**Example 2:** + +``` +Input: "ccaabbb" +Output: 5 +Explanation: t is "aabbb" which its length is 5. +``` + +Certainly! Below is the complete algorithm with explanations, followed by the implementations in C++, Python, Java, and JavaScript. + +### Algorithm + +1. **Initialize**: + + - A hash map to count characters in the current window. + - Two pointers, `i` and `j`, to represent the current window. `i` is the right pointer, and `j` is the left pointer. + - A variable to keep track of the maximum length of the substring. + +2. **Expand the Window**: + + - Move the right pointer `i` to expand the window. + - Add the current character to the hash map and update its count. + +3. **Shrink the Window if Necessary**: + + - If the number of distinct characters in the hash map exceeds 2, move the left pointer `j` to shrink the window until the number of distinct characters is at most 2. + - Decrease the count of the character at the left pointer `j` in the hash map and remove it if its count becomes 0. + +4. **Update the Maximum Length**: + + - Update the maximum length of the substring after adjusting the window. + +5. **Return the Result**: + - Return the maximum length of the substring with at most two distinct characters. + +### C++ + +```cpp +#include +#include +#include + +using namespace std; + +class Solution { +public: + int lengthOfLongestSubstringTwoDistinct(string s) { + unordered_map cnt; + int n = s.size(); + int ans = 0; + int j = 0; + + for (int i = 0; i < n; ++i) { + cnt[s[i]]++; + while (cnt.size() > 2) { + cnt[s[j]]--; + if (cnt[s[j]] == 0) { + cnt.erase(s[j]); + } + ++j; + } + ans = max(ans, i - j + 1); + } + + return ans; + } +}; +``` + +### Python + +```python +class Solution: + def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int: + from collections import defaultdict + + cnt = defaultdict(int) + n = len(s) + ans = 0 + j = 0 + + for i in range(n): + cnt[s[i]] += 1 + while len(cnt) > 2: + cnt[s[j]] -= 1 + if cnt[s[j]] == 0: + del cnt[s[j]] + j += 1 + ans = max(ans, i - j + 1) + + return ans +``` + +### Java + +```java +import java.util.HashMap; + +public class Solution { + public int lengthOfLongestSubstringTwoDistinct(String s) { + HashMap cnt = new HashMap<>(); + int n = s.length(); + int ans = 0; + int j = 0; + + for (int i = 0; i < n; ++i) { + cnt.put(s.charAt(i), cnt.getOrDefault(s.charAt(i), 0) + 1); + while (cnt.size() > 2) { + cnt.put(s.charAt(j), cnt.get(s.charAt(j)) - 1); + if (cnt.get(s.charAt(j)) == 0) { + cnt.remove(s.charAt(j)); + } + ++j; + } + ans = Math.max(ans, i - j + 1); + } + + return ans; + } +} +``` + +### JavaScript + +```javascript +var lengthOfLongestSubstringTwoDistinct = function (s) { + let cnt = new Map(); + let n = s.length; + let ans = 0; + let j = 0; + + for (let i = 0; i < n; ++i) { + cnt.set(s[i], (cnt.get(s[i]) || 0) + 1); + while (cnt.size > 2) { + cnt.set(s[j], cnt.get(s[j]) - 1); + if (cnt.get(s[j]) === 0) { + cnt.delete(s[j]); + } + ++j; + } + ans = Math.max(ans, i - j + 1); + } + + return ans; +}; +``` diff --git a/solutions/lc-solutions/0100-0199/0160-intersection-of-two-linked-list.md b/solutions/lc-solutions/0100-0199/0160-intersection-of-two-linked-list.md new file mode 100644 index 0000000..8cd9204 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0160-intersection-of-two-linked-list.md @@ -0,0 +1,213 @@ +--- +id: intersection-of-two-linked-list. +title: Intersection of Two Linked Lists +sidebar_label: 0160-Intersection of Two Linked Lists +tags: + - Linked List + - Leet code +description: "Solution to leetocde 160" +--- + +### Problem Description + +Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. + +For example, the following two linked lists begin to intersect at node c1: + +The test cases are generated such that there are no cycles anywhere in the entire linked structure. + +Note that the linked lists must retain their original structure after the function returns. + +**Custom Judge:** + +The inputs to the judge are given as follows (your program is not given these inputs): + +- intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node. +- listA - The first linked list. +- listB - The second linked list. +- skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node. +- skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node. +- The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted. + +**Example 1:** + +``` +Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 +Output: Intersected at '8' +Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). +From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. + +- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory. +``` + +**Example 2:** + +``` +Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 +Output: Intersected at '2' +Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). +From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. +``` + +**Example 3:** + +``` +Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 +Output: No intersection +Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. +Explanation: The two lists do not intersect, so return null. +``` + +### Constraints: + +- The number of nodes of listA is in the m. +- The number of nodes of listB is in the n. +- $1 <= m, n <= 3*10^4$ +- $1 <= Node.val <= 10^5$ +- $0 <= skipA < m$ +- $0 <= skipB < n$ +- $intersectVal is 0 if listA and listB do not intersect.$ +- $intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.$ + +### Algorithm + +The algorithm to find the intersection of two linked lists uses the following steps: + +1. **Traverse the First List**: + + - Store each node in a hash map (or set). + +2. **Traverse the Second List**: + - Check if any node is already present in the hash map (or set). If found, that node is the intersection. + +### C++ Implementation + +```cpp +#include + +// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(nullptr) {} +}; + +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + std::unordered_map mpp; + + // Traverse list A and store each node in the map + for (ListNode *p = headA; p != nullptr; p = p->next) { + mpp[p] = p->val; + } + + // Traverse list B and check if any node is in the map + for (ListNode *p = headB; p != nullptr; p = p->next) { + if (mpp.find(p) != mpp.end()) { + return p; + } + } + + return nullptr; + } +}; +``` + +### Python Implementation + +```python +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +class Solution: + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: + node_set = set() + + # Traverse list A and store each node in the set + p = headA + while p: + node_set.add(p) + p = p.next + + # Traverse list B and check if any node is in the set + p = headB + while p: + if p in node_set: + return p + p = p.next + + return None +``` + +### Java Implementation + +```java +import java.util.HashSet; + +class ListNode { + int val; + ListNode next; + ListNode(int x) { + val = x; + next = null; + } +} + +public class Solution { + public ListNode getIntersectionNode(ListNode headA, ListNode headB) { + HashSet nodeSet = new HashSet<>(); + + // Traverse list A and store each node in the set + ListNode p = headA; + while (p != null) { + nodeSet.add(p); + p = p.next; + } + + // Traverse list B and check if any node is in the set + p = headB; + while (p != null) { + if (nodeSet.contains(p)) { + return p; + } + p = p.next; + } + + return null; + } +} +``` + +### JavaScript Implementation + +```javascript +function ListNode(val) { + this.val = val; + this.next = null; +} + +var getIntersectionNode = function (headA, headB) { + let nodeSet = new Set(); + + // Traverse list A and store each node in the set + let p = headA; + while (p !== null) { + nodeSet.add(p); + p = p.next; + } + + // Traverse list B and check if any node is in the set + p = headB; + while (p !== null) { + if (nodeSet.has(p)) { + return p; + } + p = p.next; + } + + return null; +}; +``` diff --git a/solutions/lc-solutions/0100-0199/0161-one-edit-distance.md b/solutions/lc-solutions/0100-0199/0161-one-edit-distance.md new file mode 100644 index 0000000..a897b6d --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0161-one-edit-distance.md @@ -0,0 +1,142 @@ +--- +id: one-edit-distance +title: One Edit Distance +sidebar_label: 0161-One Edit Distance +tags: + - Leet code +description: "Solution to leetocde 161" +--- + +### Problem Description +Given two strings s and t, determine if they are both one edit distance apart. + +#### Note: + +- There are 3 possiblities to satisify one edit distance apart: + +- Insert a character into s to get t +- Delete a character from s to get t +- Replace a character of s to get t + + +***Example 1:*** +``` + +Input: s = "ab", t = "acb" +Output: true +Explanation: We can insert 'c' into s to get t. +``` + +***Example 2:*** +``` +Input: s = "cab", t = "ad" +Output: false +Explanation: We cannot get t from s by only one step. +``` +***Example 3:*** +``` +Input: s = "1203", t = "1213" +Output: true +Explanation: We can replace '0' with '1' to get t. +``` + +### Approach + +The `isOneEditDistance` function checks if two strings `s` and `t` are at most one edit distance apart. An edit distance is defined as a single operation of insertion, deletion, or replacement. + +### Steps + +1. **Ensure |s| ≀ |t|**: + - If the length of `s` is greater than the length of `t`, swap them. This simplifies the problem to always handling the case where `|s| ≀ |t|`. + +2. **Compare Characters**: + - Iterate through both strings until the first differing character is found. + +3. **Check Edit Operations**: + - If the lengths of `s` and `t` are the same: + - Check if replacing the differing character makes the remaining substrings identical. + - If the lengths differ by one: + - Check if deleting the differing character from `t` makes the substrings identical. + +4. **Final Check**: + - After the loop, if no differing character is found, verify if the length of `t` is exactly one more than `s` (to account for the insertion case). + +### Summary + +The function compares the two strings to determine if they can be made identical with exactly one edit operation. It handles the three possible editsβ€”replacement, insertion, or deletionβ€”by examining the strings based on their lengths and differences. + + + + + +### Code Implementation + +### C++ + +```cpp +class Solution { + public: + bool isOneEditDistance(string s, string t) { + const int m = s.length(); + const int n = t.length(); + if (m > n) // Make sure that |s| <= |t|. + return isOneEditDistance(t, s); + + for (int i = 0; i < m; ++i) + if (s[i] != t[i]) { + if (m == n) + return s.substr(i + 1) == t.substr(i + 1); // Replace s[i] with t[i]. + return s.substr(i) == t.substr(i + 1); // Delete t[i]. + } + + return m + 1 == n; // Delete t[-1]. + } +}; +``` + +### Python + +```python +class Solution: + def isOneEditDistance(self, s: str, t: str) -> bool: + m = len(s) + n = len(t) + if m > n: # Make sure that |s| <= |t|. + return self.isOneEditDistance(t, s) + + for i in range(m): + if s[i] != t[i]: + if m == n: + return s[i + 1:] == t[i + 1:] # Replace s[i] with t[i]. + return s[i:] == t[i + 1:] # Delete t[i]. + + return m + 1 == n # Delete t[-1]. +``` + + + +### Java + +```java +class Solution { + public boolean isOneEditDistance(String s, String t) { + final int m = s.length(); + final int n = t.length(); + if (m > n) // Make sure that |s| <= |t|. + return isOneEditDistance(t, s); + + for (int i = 0; i < m; ++i) + if (s.charAt(i) != t.charAt(i)) { + if (m == n) + return s.substring(i + 1).equals(t.substring(i + 1)); // Replace s[i] with t[i]. + return s.substring(i).equals(t.substring(i + 1)); // Delete t[i]. + } + + return m + 1 == n; // Delete t[-1]. + } +} +``` + +### Complexity +- time complexity : $O(min(∣s∣,∣t∣))$ +- Space complexity : $O(1)$ \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0162-Find-Peak-Element.md b/solutions/lc-solutions/0100-0199/0162-Find-Peak-Element.md new file mode 100644 index 0000000..333b93d --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0162-Find-Peak-Element.md @@ -0,0 +1,133 @@ +--- +id: Find-Peak-Element +title: Find Peak Element +sidebar_label: 0162-Find-Peak-Element +tags: + - Array + - Binary Search +description: "A peak element is an element that is strictly greater than its neighbors. + +Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. + +You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. + +You must write an algorithm that runs in O(log n) time." +--- + + +### Problem Description + +A peak element is an element that is strictly greater than its neighbors. + +Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. + +You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. + +You must write an algorithm that runs in O(log n) time. + +### Examples + +#### Example 1 + +- **Input:** `nums = [1,2,3,1]` +- **Output:** `2` + +#### Example 2 + +- **Input:** `nums = [1,2,1,3,5,6,4]` +- **Output:** `5` + +### Constraints + +- `1 <= nums.length <= 1000` +- `-231 <= nums[i] <= 231 - 1` +- `nums[i] != nums[i + 1]` for all valid `i`. + +### Solution Code + +#### Python + +```python +class Solution: + def findPeakElement(self, nums: list[int]) -> int: + left, right = 0, len(nums) - 1 + + while left < right: + mid = (left + right) >> 1 + + if nums[mid - 1] <= nums[mid] >= nums[mid + 1]: + return mid + elif nums[mid] < nums[mid + 1]: + left = mid + 1 + else: + right = mid + + return left +``` + +#### Java + +```java +class Solution { + public int findPeakElement(int[] nums) { + int n=nums.length; + if(n==1)return 0; + if(nums[0]>nums[1])return 0; + if(nums[n-1]>nums[n-2])return n-1; + int low=1,high=n-2; + while(low<=high){ + int mid=(low+high)/2; + if(nums[mid]>nums[mid-1] && nums[mid]>nums[mid+1])return mid; + else if(nums[mid]>nums[mid-1])low=mid+1; + else high=mid-1; + } + return -1; + } +} +``` + +#### C++ + +```cpp + +class Solution { +public: + int findPeakElement(vector& nums) { + int low = 0, high = nums.size() - 1; + while (low < high) { + int mid = low + (high - low) / 2; + if (nums[mid] < nums[mid + 1]) { + low = mid + 1; + } else + high = mid; + } + return low; + } +}; +``` +#### Javascript + +```javascript +class Solution { + public int findPeakElement(int[] nums) { + int n = nums.length; + if(n == 1) + return 0; + else if(nums[0] > nums[1]) + return 0; + else if(nums[n-1] > nums[n-2]) + return n-1; + int low = 1, high = n-2; + while(low <= high) { + int mid = low + (high - low)/2; + if(nums[mid] > nums[mid-1] && nums[mid] > nums[mid+1]) + return mid; + else if(nums[mid] < nums[mid-1]) + high = mid-1; + else + low = mid+1; + } + return -1; + } +} +``` diff --git a/solutions/lc-solutions/0100-0199/0163-missing-range.md b/solutions/lc-solutions/0100-0199/0163-missing-range.md new file mode 100644 index 0000000..cbe90db --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0163-missing-range.md @@ -0,0 +1,131 @@ +--- +id: missing-range +title: Missing Range +sidebar_label: 0163-Missing Range +tags: [Dynamic Programming, Matrix] +description: Solution to the Missing range problem of leetcode +--- + +### Problem Description +Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, upper], return its missing ranges. + + + + +***Example 1:*** +``` +Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99, +Output: ["2", "4->49", "51->74", "76->99"] +``` + + +### Approach +1. If the input vector `nums` is empty, return a single range from `lower` to `upper`. +2. Initialize an empty vector `ans` to store the missing ranges. +3. Check if the first element of `nums` is greater than `lower`. If so, add a range from `lower` to `nums.front() - 1` to `ans`. +4. Iterate through the rest of the elements in `nums`. Whenever there's a gap between adjacent elements (i.e., `nums[i] > nums[i - 1] + 1`), add the range from `nums[i - 1] + 1` to `nums[i] - 1` to `ans`. +5. Finally, if the last element of `nums` is less than `upper`, add a range from `nums.back() + 1` to `upper` to `ans`. + +The `getRange` function constructs a string representation of a range given its lower and upper bounds. If the bounds are equal, it returns a single value; otherwise, it returns a range in the format "lo->hi". + + + +### Code Implementation + +### C++ + +```cpp +class Solution { + public: + vector findMissingRanges(vector& nums, int lower, int upper) { + if (nums.empty()) + return {getRange(lower, upper)}; + + vector ans; + + if (nums.front() > lower) + ans.push_back(getRange(lower, nums.front() - 1)); + + for (int i = 1; i < nums.size(); ++i) + if (nums[i] > nums[i - 1] + 1) + ans.push_back(getRange(nums[i - 1] + 1, nums[i] - 1)); + + if (nums.back() < upper) + ans.push_back(getRange(nums.back() + 1, upper)); + + return ans; + } + + private: + string getRange(int lo, int hi) { + if (lo == hi) + return to_string(lo); + return to_string(lo) + "->" + to_string(hi); + } +}; +``` + +### Python + +```python +class Solution: + def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]: + def getRange(lo: int, hi: int) -> str: + if lo == hi: + return str(lo) + return str(lo) + '->' + str(hi) + + if not nums: + return [getRange(lower, upper)] + + ans = [] + + if nums[0] > lower: + ans.append(getRange(lower, nums[0] - 1)) + + for prev, curr in zip(nums, nums[1:]): + if curr > prev + 1: + ans.append(getRange(prev + 1, curr - 1)) + + if nums[-1] < upper: + ans.append(getRange(nums[-1] + 1, upper)) + + return ans +``` + + + +### Java + +```Java +class Solution { + public List findMissingRanges(int[] nums, int lower, int upper) { + if (nums.length == 0) + return new ArrayList<>(Arrays.asList(getRange(lower, upper))); + + List ans = new ArrayList<>(); + + if (nums[0] > lower) + ans.add(getRange(lower, nums[0] - 1)); + + for (int i = 1; i < nums.length; ++i) + if (nums[i] > nums[i - 1] + 1) + ans.add(getRange(nums[i - 1] + 1, nums[i] - 1)); + + if (nums[nums.length - 1] < upper) + ans.add(getRange(nums[nums.length - 1] + 1, upper)); + + return ans; + } + + private String getRange(int lo, int hi) { + if (lo == hi) + return String.valueOf(lo); + return lo + "->" + hi; + } +} +``` + +### Complexity +- time complexity : $O(n)$ +- Space complexity : $O(n)$ \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0164-maximum-gap.md b/solutions/lc-solutions/0100-0199/0164-maximum-gap.md new file mode 100644 index 0000000..a064ede --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0164-maximum-gap.md @@ -0,0 +1,123 @@ +--- +id: maximum-gap +title: Maximum Gap(LeetCode) +sidebar_label: 0164-Maximum Gap +tags: + - Array + - Sorting + - Bucket Sort + - Radix Sort +description: Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0. +--- + +## Problem Statement + +Given an integer array `nums`, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return `0`. + +You must write an algorithm that runs in linear time and uses linear extra space. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [3,6,9,1] +Output: 3 +Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3. +``` + +**Example 2:** + +```plaintext +Input: nums = [10] +Output: 0 +Explanation: The array contains less than 2 elements, therefore return 0. +``` + +### Constraints + +- `1 <= nums.length <= 105` +- `0 <= nums[i] <= 109` + +## Solution + +### Approach + +The approach employs the concept of bucket sorting combined with the pigeonhole principle. The idea is to divide the range between the minimum and maximum values in the array into buckets and then find the maximum gap by comparing the minimum value of one bucket to the maximum value of the previous bucket. + +#### Algorithm + +1. Edge Case Handling: +* If the array is null or contains fewer than 2 elements, return 0 since no gap can be calculated. +2. Find Minimum and Maximum: +* Traverse the array to find the minimum and maximum values. +3. Calculate Gap and Create Buckets: +* Calculate the minimum possible gap as gap = ⌈ (max-min)/(N-1)βŒ‰. +* Create two arrays, bucketsMIN and bucketsMAX, to store the minimum and maximum values of each bucket, respectively. +* Initialize these arrays with extreme values (Integer.MAX_VALUE for bucketsMIN and Integer.MIN_VALUE for bucketsMAX). +4. Distribute Array Elements into Buckets: +* Iterate through the array and place each element (except the minimum and maximum) into the appropriate bucket based on its value. +5. Calculate Maximum Gap: +* Initialize the previous bucket's maximum as the minimum value. +* Traverse through the buckets and calculate the gap by comparing the current bucket's minimum value with the previous bucket's maximum value. +* Keep track of the maximum gap found. +* Finally, compare the maximum value with the last non-empty bucket's maximum to ensure no larger gap exists. + +#### Implementation + +```Java +import java.util.Arrays; + +public class Solution { + public int maximumGap(int[] num) { + if (num == null || num.length < 2) + return 0; + + // Find the min and max values + int min = num[0]; + int max = num[0]; + for (int i : num) { + min = Math.min(min, i); + max = Math.max(max, i); + } + + // Calculate the gap + int gap = (int) Math.ceil((double) (max - min) / (num.length - 1)); + int[] bucketsMIN = new int[num.length - 1]; + int[] bucketsMAX = new int[num.length - 1]; + Arrays.fill(bucketsMIN, Integer.MAX_VALUE); + Arrays.fill(bucketsMAX, Integer.MIN_VALUE); + + // Distribute the numbers into buckets + for (int i : num) { + if (i == min || i == max) + continue; + int idx = (i - min) / gap; + bucketsMIN[idx] = Math.min(i, bucketsMIN[idx]); + bucketsMAX[idx] = Math.max(i, bucketsMAX[idx]); + } + + // Calculate the maximum gap + int maxGap = Integer.MIN_VALUE; + int previous = min; + for (int i = 0; i < num.length - 1; i++) { + if (bucketsMIN[i] == Integer.MAX_VALUE && bucketsMAX[i] == Integer.MIN_VALUE) + continue; + maxGap = Math.max(maxGap, bucketsMIN[i] - previous); + previous = bucketsMAX[i]; + } + maxGap = Math.max(maxGap, max - previous); + + return maxGap; + } +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(N)$ +- **Space complexity**: $O(N)$ + +### Conclusion + +This approach efficiently finds the maximum gap between successive elements in an unsorted array using the concept of bucket sorting. It avoids the need for full sorting, thus achieving linear time complexity. This makes the solution suitable for large arrays where a more efficient method than O(NlogN) sorting is required. diff --git a/solutions/lc-solutions/0100-0199/0165-compare-version-numbers.md b/solutions/lc-solutions/0100-0199/0165-compare-version-numbers.md new file mode 100644 index 0000000..9ff53ab --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0165-compare-version-numbers.md @@ -0,0 +1,164 @@ +--- + +id: compare-version-numbers +title: Compare Version Numbers +sidebar_label: 165-compare-version-numbers +tags: +- Two Pointers +- String +- Java +- Cpp +- Python + +description: "Given two version strings, compare them. Return -1, 1, or 0 based on the comparison." +--- + +## Problem Description + +Given two version strings, `version1` and `version2`, compare them. A version string consists of revisions separated by dots `'.'`. The value of the revision is its integer conversion ignoring leading zeros. + +To compare version strings, compare their revision values in left-to-right order. If one of the version strings has fewer revisions, treat the missing revision values as 0. + +Return the following: +- If `version1 < version2`, return `-1`. +- If `version1 > version2`, return `1`. +- Otherwise, return `0`. + +#### Examples + +**Example 1:** +``` +Input: version1 = "1.2", version2 = "1.10" +Output: -1 +Explanation: +version1's second revision is "2" and version2's second revision is "10": 2 < 10, so version1 < version2. +``` +**Example 2:** +``` +Input: version1 = "1.01", version2 = "1.001" +Output: 0 +Explanation: +Ignoring leading zeroes, both "01" and "001" represent the same integer "1". +``` +**Example 3:** +``` +Input: version1 = "1.0", version2 = "1.0.0.0" +Output: 0 +Explanation: +version1 has fewer revisions, which means every missing revision is treated as "0". +``` +### Constraints + +- `1 <= version1.length, version2.length <= 500` +- `version1` and `version2` only contain digits and '.'. +- `version1` and `version2` are valid version numbers. +- All the given revisions in `version1` and `version2` can be stored in a 32-bit integer. + + +## Approach + +To compare the version numbers, we need to split both version strings into their respective revisions and convert these revisions to integers. We then compare the corresponding revisions from left to right. If one version string has fewer revisions, we treat the missing revisions as `0`. + +### Steps: + +1. **Split the Version Strings:** Use `split('.')` to break down the version strings into lists of revisions. +2. **Convert Revisions to Integers:** Convert each revision string to an integer to ignore leading zeros. +3. **Equalize the Lengths:** Append zeros to the shorter list of revisions to make both lists equal in length. +4. **Compare Revisions:** Iterate through the lists and compare the revisions. Return `1` if the first version is greater, `-1` if the second version is greater, and `0` if they are equal. + +### Solution + +#### Java Solution + +```java +class Solution { + public int compareVersion(String version1, String version2) { + String[] l1 = version1.split("\\."); + String[] l2 = version2.split("\\."); + int n = Math.max(l1.length, l2.length); + + for (int i = 0; i < n; i++) { + int v1 = i < l1.length ? Integer.parseInt(l1[i]) : 0; + int v2 = i < l2.length ? Integer.parseInt(l2[i]) : 0; + if (v1 > v2) return 1; + if (v1 < v2) return -1; + } + return 0; + } +} +``` + +#### C++ Solution + +```cpp +class Solution { +public: + int compareVersion(string version1, string version2) { + vector l1, l2; + stringstream ss1(version1), ss2(version2); + string token; + + while (getline(ss1, token, '.')) { + l1.push_back(stoi(token)); + } + + while (getline(ss2, token, '.')) { + l2.push_back(stoi(token)); + } + + int n = max(l1.size(), l2.size()); + + for (int i = 0; i < n; i++) { + int v1 = i < l1.size() ? l1[i] : 0; + int v2 = i < l2.size() ? l2[i] : 0; + if (v1 > v2) return 1; + if (v1 < v2) return -1; + } + return 0; + } +}; +``` + +#### Python Solution + +```python +class Solution: + def compareVersion(self, version1: str, version2: str) -> int: + l = version1.split(".") + l1 = [] + l2 = [] + for i in l: + l1.append(int(i)) + l = version2.split(".") + for i in l: + l2.append(int(i)) + if len(l1) > len(l2): + x = len(l1)-len(l2) + for i in range(1,x+1): + l2.append(0) + if len(l2) > len(l1): + x = len(l2)-len(l1) + for i in range(1,x+1): + l1.append(0) + ans = 0 + for i in range(0,len(l1)): + if l1[i]>l2[i]: + ans = 1 + break + elif l1[i] Splitting the strings and comparing the versions both take linear time relative to the length of the version strings. + +**Space Complexity:** O(n) +> Storing the split version numbers takes linear space. + +### References +**LeetCode Problem:** Compare Version Numbers diff --git a/solutions/lc-solutions/0100-0199/0166-fraction-to-recurring-decimal.md b/solutions/lc-solutions/0100-0199/0166-fraction-to-recurring-decimal.md new file mode 100644 index 0000000..242fed7 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0166-fraction-to-recurring-decimal.md @@ -0,0 +1,125 @@ +--- +id: Fraction to Recurring Decimal +title: Fraction to Recurring Decimal(LeetCode) +sidebar_label: 0166-Fraction to Recurring Decimal +tags: + - Math + - Hash Table + - String +description: Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. +--- + +## Problem Statement + +Given two integers representing the `numerator` and `denominator` of a fraction, return the fraction in string format. + +If the fractional part is repeating, enclose the repeating part in parentheses. + +If multiple answers are possible, return any of them. + +It is guaranteed that the length of the answer string is less than `10^4` for all the given inputs. + +### Examples + +**Example 1:** + +```plaintext +Input: numerator = 1, denominator = 2 +Output: "0.5" +``` + +**Example 2:** + +```plaintext +Input: numerator = 2, denominator = 1 +Output: "2" +``` + +**Example 3:** + +```plaintext +Input: numerator = 4, denominator = 333 +Output: "0.(012)" +``` + +### Constraints + +- `-231 <= numerator, denominator <= 231 - 1` +- `denominator != 0` + +## Solution + +### Approach + +#### Algorithm + +1. Handle Edge Cases: +* If the numerator is 0, the result is "0". +* Determine the sign of the result by checking if the numerator and denominator have different signs. +2. Convert to Positive Long: +* Use `long` to handle potential overflow and convert the numerator and denominator to their absolute values. +3. Integral Part: +* Compute the integral part of the division and append it to the result string. +4. Fractional Part: +* If there is no remainder after the integral division, return the result as is. +* Otherwise, proceed to calculate the fractional part: + * Use a `HashMap` to store the remainder and its associated index in the result string. + * Multiply the remainder by 10 and perform division again. + * Append the quotient to the result string. + * Check if the remainder has appeared before using the `HashMap`. + * If it has, it means the fractional part is repeating. Insert parentheses at the appropriate position. + * If not, continue the process and store the new remainder with its index in the `HashMap`. + +#### Implementation + +```Java +import java.util.HashMap; + +public class Solution { + public String fractionToDecimal(int numerator, int denominator) { + if (numerator == 0) { + return "0"; + } + StringBuilder res = new StringBuilder(); + // "+" or "-" + res.append(((numerator > 0) ^ (denominator > 0)) ? "-" : ""); + long num = Math.abs((long)numerator); + long den = Math.abs((long)denominator); + + // integral part + res.append(num / den); + num %= den; + if (num == 0) { + return res.toString(); + } + + // fractional part + res.append("."); + HashMap map = new HashMap<>(); + map.put(num, res.length()); + while (num != 0) { + num *= 10; + res.append(num / den); + num %= den; + if (map.containsKey(num)) { + int index = map.get(num); + res.insert(index, "("); + res.append(")"); + break; + } else { + map.put(num, res.length()); + } + } + return res.toString(); + } +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(k)$ , here k is the length of the fractional part. The while loop iterates over each digit of the fractional part. +- **Space complexity**: $O(k)$ , where k is the number of unique remainders stored in the HashMap. In the worst case, every remainder before repeating is unique. + +### Conclusion + +This algorithm effectively converts a fraction to its decimal representation and handles repeating fractional parts by using a HashMap to track remainders and their positions. This ensures that once a repeating sequence is detected, it is enclosed in parentheses. This solution is efficient in terms of both time and space complexity and accounts for potential edge cases such as negative values and overflow. diff --git a/solutions/lc-solutions/0100-0199/0167-two-sum-II.md b/solutions/lc-solutions/0100-0199/0167-two-sum-II.md new file mode 100644 index 0000000..64763fc --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0167-two-sum-II.md @@ -0,0 +1,103 @@ +--- +id: two-sum-II-input-array-is-sorted +title: Two Sum II - Input Array Is Sorted(LeetCode) +sidebar_label: 0167-Two Sum II - Input Array Is Sorted +tags: + - Array + - Two Pointers + - Binary Search +description: Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. +--- + +## Problem Statement + +Given a 1-indexed array of integers `numbers` that is already sorted in non-decreasing order, find two numbers such that they add up to a specific `target` number. Let these two numbers be `numbers[index1]` and `numbers[index2]` where `1 <= index1 < index2 <= numbers.length`. + +Return the indices of the two numbers, `index1` and `index2`, added by one as an integer array `[index1, index2]` of length 2. + +The tests are generated such that there is exactly one solution. You may not use the same element twice. + +Your solution must use only constant extra space. + +### Examples + +**Example 1:** + +```plaintext +Input: numbers = [2,7,11,15], target = 9 +Output: [1,2] +Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]. +``` + +**Example 2:** + +```plaintext +Input: numbers = [2,3,4], target = 6 +Output: [1,3] +Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3]. +``` + +**Example 3:** + +```plaintext +Input: numbers = [-1,0], target = -1 +Output: [1,2] +Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2]. +``` + +### Constraints + +- `2 <= numbers.length <= 3 * 104` +- `-1000 <= numbers[i] <= 1000` +- `numbers` is sorted in non-decreasing order. +- `-1000 <= target <= 1000` +- The tests are generated such that there is exactly one solution. + +## Solution + +### Approach + +The approach to this problem leverages the fact that the array is sorted, which allows for a more efficient solution compared to the classic Two Sum problem. By utilizing two pointers, we can efficiently search for the target sum. + +Key Observations +1. Smaller sums: Smaller sums can be found towards the left half of the array. +2. Larger sums: Larger sums can be found towards the right half of the array. +With this in mind, we can use two pointers starting at the endpoints of the array and adjust them based on the current sum compared to the target. + +#### Algorithm + +1. Initialization: +* Set two pointers, l at the beginning of the array and r at the end of the array. +2. Iterate through the array: +* Calculate the sum of the elements at the two pointers. +* If the sum is equal to the target, return the indices. +* If the sum is less than the target, increment the left pointer (l). +* If the sum is greater than the target, decrement the right pointer (r). +3. End Condition: +* The loop continues until the sum of the elements at the two pointers equals the target, ensuring the correct indices are found. + +#### Implementation + +```Java +public int[] twoSum(int[] nums, int target) { + int l = 0, r = nums.length - 1; + + while (nums[l] + nums[r] != target) { + if (nums[l] + nums[r] < target) l++; + else r--; + } + + return new int[] {l + 1, r + 1}; // Return 1-based indices +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(N)$ + * The while loop runs in linear time as each iteration moves one of the pointers closer to the middle of the array. +- **Space complexity**: $O(1)$ + * No extra space is used, making the space complexity constant. + +### Conclusion + +This solution efficiently finds the two numbers in a sorted array that add up to a given target by using a two-pointer approach. The method leverages the sorted property of the array, ensuring an optimal solution with linear time complexity and constant space complexity. This approach is particularly useful in interviews when dealing with sorted arrays, showcasing an understanding of efficient searching techniques and array manipulation. diff --git a/solutions/lc-solutions/0100-0199/0168-Excel-sheet-column-title.md b/solutions/lc-solutions/0100-0199/0168-Excel-sheet-column-title.md new file mode 100644 index 0000000..c6bbf1c --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0168-Excel-sheet-column-title.md @@ -0,0 +1,103 @@ +--- +id: excel-sheet-column-title +title: Excel Sheet Column Title +sidebar_label: 0168-Excel Sheet Column Title +tags: + - Math + - String +description: Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. +--- + +## Problem Statement + +Given an integer `columnNumber`, return its corresponding column title as it appears in an Excel sheet. + +For example: +A -> 1 +B -> 2 +C -> 3 +... +Z -> 26 +AA -> 27 +AB -> 28 +... + +### Examples + +**Example 1:** + +```plaintext +Input: columnNumber = 1 +Output: "A" +``` + +**Example 2:** + +```plaintext +Input: columnNumber = 28 +Output: "AB" +``` + +**Example 3:** + +```plaintext +Input: columnNumber = 701 +Output: "ZY" +``` + +### Constraints + +- $1 \leq \text{columnNumber} \leq 2^{23} - 1$ + +## Solution + +### Approach + +To solve the "Excel Sheet Column Title" problem using the iterative approach, we continuously divide the given number by 26 and determine the remainder. This remainder gives us the current character of the Excel title, starting from the least significant character. + + + +Key Data Structures +- **List (result)**: Used to store the characters of the Excel title. + +#### Algorithm + +1. Initialization: +- Create an empty list named result. +2. Processing Each Number: +- While columnNumber is not zero: + * Use the divmod function to get the quotient and remainder of columnNumber when divided by 26. + * Decrement the columnNumber by 1 and append the corresponding character to the result list. +3. Wrap-up: +- Reverse the result list and join the characters to form the final Excel title. + + + +#### Implementation + +```Java +public class Solution { + public String convertToTitle(int columnNumber) { + StringBuilder result = new StringBuilder(); + while (columnNumber > 0) { + columnNumber--; + char c = (char) ('A' + columnNumber % 26); + result.insert(0, c); + columnNumber /= 26; + } + return result.toString(); + } +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(log26n)$ + * The time complexity is O(log26n), where n is the given columnNumber. This is because we're continuously dividing the number by 26 until it becomes zero. + +- **Space complexity**: $O(1)$ + * The space complexity is O(log26n) due to the list we use to store the Excel title characters. + +### Conclusion + +This problem provides an elegant demonstration of how to convert base-10 numbers to another base, in this case, base-26. It's a great reminder that sometimes algorithmic problems can be rooted in simple number base conversions. diff --git a/solutions/lc-solutions/0100-0199/0169-Majority-Element.md b/solutions/lc-solutions/0100-0199/0169-Majority-Element.md new file mode 100644 index 0000000..dbdc8d9 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0169-Majority-Element.md @@ -0,0 +1,176 @@ +--- +id: Majority-Element +title: Majority Element +sidebar_label: 0169-Majority-Element +tags: + - Array + - Hash Table + - Sorting + - Counting +description: "Given an array nums of size n, return the majority element. + +The majority element is the element that appears more than ⌊n / 2βŒ‹ times. You may assume that the majority element always exists in the array." +--- + + + +## Problem Statement + +Given an array nums of size n, return the majority element. + +The majority element is the element that appears more than ⌊n / 2βŒ‹ times. You may assume that the majority element always exists in the array. + +**Follow-up:** Could you solve the problem in linear time and in O(1) space? + + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [3,2,3] +Output: 3 +``` + +**Example 2:** + +```plaintext +Input: nums = [2,2,1,1,1,2,2] +Output: 2 +``` + +### Constraints + +- `n == nums.length` +- `1 <= n <= 5 * 104` +- `-109 <= nums[i] <= 109` + + +## Solution + +If the array contains a majority element, its occurrence must be greater than the floor(N/2). +Now, we can say that the count of minority elements and majority elements is equal up to a certain point in the array. +So when we traverse through the array we try to keep track of the count of elements and the element itself for which we are tracking the count. + +After traversing the whole array, we will check the element stored in the variable. +The question states that the array must contain a majority element, so the stored element will be that one + +### Approach + +#### Algorithm + +1. Initialize 2 variables: + - Count – for tracking the count of element + - Element – for which element we are counting +2. Traverse through the given array. + - If Count is 0 then store the current element of the array as Element. + - If the current element and Element are the same increase the Count by 1. + - If they are different decrease the Count by 1. +3. The integer present in Element should be the result we are expecting + + + +#### Solution + +### Java Solution + +```Java +import java.util.*; + +public class tUf { + public static int majorityElement(int []v) { + //size of the given array: + int n = v.length; + int cnt = 0; // count + int el = 0; // Element + + //applying the algorithm: + for (int i = 0; i < n; i++) { + if (cnt == 0) { + cnt = 1; + el = v[i]; + } else if (el == v[i]) cnt++; + else cnt--; + } + + return el; + } + + public static void main(String args[]) { + int[] arr = {2, 2, 1, 1, 1, 2, 2}; + int ans = majorityElement(arr); + System.out.println("The majority element is: " + ans); + + } + +} + +``` + +### C++ Solution + +```cpp +#include +using namespace std; + +int majorityElement(vector v) { + + //size of the given array: + int n = v.size(); + int cnt = 0; // count + int el; // Element + + //applying the algorithm: + for (int i = 0; i < n; i++) { + if (cnt == 0) { + cnt = 1; + el = v[i]; + } + else if (el == v[i]) cnt++; + else cnt--; + } + +return el; +} + +int main() +{ + vector arr = {2, 2, 1, 1, 1, 2, 2}; + int ans = majorityElement(arr); + cout << "The majority element is: " << ans << endl; + return 0; +} +``` + +### Python Solution + +```python +def majorityElement(arr): + # Size of the given array + n = len(arr) + cnt = 0 # Count + el = None # Element + + # Applying the algorithm + for i in range(n): + if cnt == 0: + cnt = 1 + el = arr[i] + elif el == arr[i]: + cnt += 1 + else: + cnt -= 1 + + return el + + +arr = [2, 2, 1, 1, 1, 2, 2] +ans = majorityElement(arr) +print("The majority element is:", ans) +``` + +### Complexity Analysis + +- **Time complexity**: $O(N)$, where N = size of the given array. +- **Space complexity**: $O(1)$ as we are not using any extra space. + diff --git a/solutions/lc-solutions/0100-0199/0170-two-sum-III-data-structure-design.md b/solutions/lc-solutions/0100-0199/0170-two-sum-III-data-structure-design.md new file mode 100644 index 0000000..e18ea82 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0170-two-sum-III-data-structure-design.md @@ -0,0 +1,119 @@ +--- +id: two-sum-III-data-structure-design +title: Two Sum III - Data Structure Design +sidebar_label: 0170-Two Sum III - Data Structure Design +tags: [HashTable, ArrayList, Binary Search] +description: Design and implement a TwoSum class. + +--- + +## Problem Statement + +Design and implement a TwoSum class. It should support the following operations: `add` and `find`. + +`add` - Add the number to an internal data structure. +`find` - Find if there exists any pair of numbers which sum is equal to the value. + +### Examples + +**Example 1:** + +```plaintext +add(1); add(3); add(5); +find(4) -> true +find(7) -> false +``` + +**Example 2:** + +```plaintext +add(3); add(1); add(2); +find(3) -> true +find(6) -> false +``` + +**Example 3:** + +```plaintext +Input: numbers = [-1,0], target = -1 +Output: [1,2] +Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2]. +``` + +### Constraints +$$-10^5 \leq \text{number} \leq 10^5 - 1$$ + +$$-2^{31} \leq \text{number} \leq 2^{31} - 1$$ + +- At most 104 calls will be made to `add` and `find`. + +## Solution + +### Approach + +One hashmap for unique numbers, and their count (to tackle multiple duplicate numbers issue). + + +#### Algorithm + +`HashMap` to hold remainder. + +Establish a mapping between each `number` and the number of `occurrences`, and then traverse the HashMap. For each value, first find the difference `t` between this value and the target value, and then you need to look at it in two cases. + +- If the current value is `not equal` to the difference t, then return True as long as there is a difference t in the HashMap, or when the difference t is equal to the current value, + +- If the number of mapping times of the HashMap is `greater than 1`, it means that there is another number in the HashMap that is `equal` to the current value, and the addition of the two is the target value + + + +#### Implementation + +```Java +class TwoSum { + Map map; + List list; + int low = Integer.MAX_VALUE; + int high = Integer.MIN_VALUE; + /** Initialize your data structure here. */ + public TwoSum() { + map = new HashMap<>(); + list = new LinkedList<>(); + } + + /** Add the number to an internal data structure..*/ + public void add(int number) { + if(map.containsKey(number)){ + map.put(number,true); + }else{ + map.put(number,false); + list.add(number); + low = Math.min(low,number); + high = Math.max(high,number); + } + } + + /** Find if there exists any pair of numbers which sum is equal + * to the value. */ + public boolean find(int value) { + if(value < 2* low || value > 2*high) return false; + for(int num : list){ + int target = value - num; + if(map.containsKey(target)){ + if(num != target) return true; + else if(map.get(target)) return true; + } + } + return false; + } +} + +``` + +### Complexity Analysis + +- **Time complexity**: + * $O(N)$ - `find` + * $O(1)$ - `add` + +- **Space complexity**: $O(N)$ + * The HashMap takes the space of $O(N)$ diff --git a/solutions/lc-solutions/0100-0199/0172-Factorial-trailing-zeroes.md b/solutions/lc-solutions/0100-0199/0172-Factorial-trailing-zeroes.md new file mode 100644 index 0000000..220d5dc --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0172-Factorial-trailing-zeroes.md @@ -0,0 +1,86 @@ +--- +id: factorial-trailing-zeroes +title: Factorial Trailing Zeroes +sidebar_label: 0172-Factorial Trailing Zeroes +tags: [Math] +description: Given an integer n, return the number of trailing zeroes in n!. + +--- + +## Problem Statement + +Given an integer `n`, return the number of trailing zeroes in `n!`. + + +### Examples + +**Example 1:** + +```plaintext +Input: n = 3 +Output: 0 +Explanation: 3! = 6, no trailing zero. +``` + +**Example 2:** + +```plaintext +Input: n = 5 +Output: 1 +Explanation: 5! = 120, one trailing zero. +``` + +**Example 3:** + +```plaintext +Input: n = 0 +Output: 0 +``` + +### Constraints +$0 \leq n \leq 10^4$ + +## Solution + +### Approach + + +To find the number of trailing zeroes in `n!`, we need to count the number of times 10 is a factor in the numbers from 1 to `n`. Since 10 is the product of 2 and 5, and there are usually more factors of 2 than 5, the number of trailing zeroes is determined by the number of times 5 is a factor in the numbers from 1 to `n`. + + +#### Algorithm + +1. Initialize `count` to 0. This will hold the number of trailing zeroes. +2. While `n` is greater than 0: +- Divide `n` by 5. +- Add the result to `count`. +- Repeat the process with the updated value of `n`. +3. Return the final `count`. + +#### Implementation + +```Java +public class Solution { + public int trailingZeroes(int n) { + int count = 0; + while (n > 0) { + n /= 5; + count += n; + } + return count; + } +} + +``` + +### Complexity Analysis + +- **Time complexity**: $O(\log_5 n)$ + * The time complexity is $O(\log_5 n)$ because we repeatedly divide `n` by 5. + +- **Space complexity**: $O(1)$ + * The space complexity is $O(1)$ as we are using only a constant amount of extra space + +### Conclusion + +This solution efficiently calculates the number of trailing zeroes in `n!` by counting the factors of 5 in the numbers from 1 to `n`. The approach is both time and space efficient, making it suitable for handling large input sizes. diff --git a/solutions/lc-solutions/0100-0199/0173-binary-search-tree-iterator.md b/solutions/lc-solutions/0100-0199/0173-binary-search-tree-iterator.md new file mode 100644 index 0000000..7cf7850 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0173-binary-search-tree-iterator.md @@ -0,0 +1,131 @@ +--- +id: binary-search-tree-iterator +title: Binary Search Tree Iterator +sidebar_label: 0173-Binary Search Tree Iterator +tags: [Tree, Stack, Design] +description: Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. +--- + +## Problem Statement + +Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. + +Calling `next()` will return the next smallest number in the BST. + +### Examples + +**Example 1:** + +```plaintext +Input: +["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"] +[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []] + +Output: +[null, 3, 7, true, 9, true, 15, true, 20, false] + +Explanation: +BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); +bSTIterator.next(); // return 3 +bSTIterator.next(); // return 7 +bSTIterator.hasNext(); // return True +bSTIterator.next(); // return 9 +bSTIterator.hasNext(); // return True +bSTIterator.next(); // return 15 +bSTIterator.hasNext(); // return True +bSTIterator.next(); // return 20 +bSTIterator.hasNext(); // return False +``` + + +### Constraints + +- The number of nodes in the tree is in the range $[1, 10^5]$. +- $0 \leq Node.val \leq 10^6$ +- At most $10^5$ calls will be made to `hasNext` and `next`. + + +## Solution + +### Approach + +To implement the BST iterator, we will use an explicit stack to simulate the in-order traversal of the BST. The stack will store the nodes, and we will push all the left children of the current node onto the stack. The `next()` method will pop the top node from the stack, process it, and then push all the left children of its right child onto the stack. The `hasNext()` method will simply check if the stack is non-empty. + + + +#### Algorithm + +1. Initialization: +- Initialize an empty stack. +- Push all the left children of the root node onto the stack. + +2. `next()` Method: +- Pop the top node from the stack. +- If the node has a right child, push all the left children of the right child onto the stack. +- Return the value of the popped node. +3. `hasNext()` Method: +- Return true if the stack is non-empty, otherwise return false. + + + + +#### Implementation + +```Java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ + +public class BSTIterator { + private Stack stack; + + public BSTIterator(TreeNode root) { + stack = new Stack<>(); + pushAllLeft(root); + } + + /** @return the next smallest number */ + public int next() { + TreeNode node = stack.pop(); + pushAllLeft(node.right); + return node.val; + } + + /** @return whether we have a next smallest number */ + public boolean hasNext() { + return !stack.isEmpty(); + } + + private void pushAllLeft(TreeNode node) { + while (node != null) { + stack.push(node); + node = node.left; + } + } +} + +``` + +### Complexity Analysis + +- **Time complexity**: $O(1)$ on average for `next()` and `hasNext()`. + * Each node is pushed and popped from the stack exactly once, so the amortized time for each operation is constant. + +- **Space complexity**: $O(h)$, where `h` is the height of the tree. + * In the worst case, the stack will contain all the nodes along the path from the root to the leftmost leaf. + +### Conclusion + +The BST iterator efficiently simulates the in-order traversal of a BST using an explicit stack. This approach ensures that the `next()` and `hasNext()` methods operate in constant time on average, making the iterator suitable for handling large BSTs. diff --git a/solutions/lc-solutions/0100-0199/0174-dungeon-game.md b/solutions/lc-solutions/0100-0199/0174-dungeon-game.md new file mode 100644 index 0000000..eff6537 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0174-dungeon-game.md @@ -0,0 +1,111 @@ +--- +id: dungeon-game +title: Dungeon Game +sidebar_label: 0174-Dungeon Game +tags: [Dynamic Programming, Matrix] +description: Given a 2D array representing a dungeon, return the minimum initial health required for a knight to reach the bottom-right corner. +--- + +## Problem Statement + +The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess. + +The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. + +Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). + +To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. + +Return the knight's minimum initial health so that he can rescue the princess. + +### Examples + +**Example 1:** + +```plaintext +Input: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]] +Output: 7 +Explanation: The initial health of the knight must be at least 7 to ensure he can rescue the princess. +``` + +**Example 2:** + +```plaintext +Input: dungeon = [[0]] +Output: 1 +``` + +### Constraints + +- `m == dungeon.length` +- `n == dungeon[i].length` +- `1 <= m, n <= 200` +- `-1000 <= dungeon[i][j] <= 1000` + +## Solution + +### Approach + +To determine the knight's minimum initial health, we will use a dynamic programming approach. We'll start from the bottom-right corner of the dungeon (where the princess is located) and work our way back to the top-left corner. + + + +#### Algorithm + +1. Initialization: +- Create a 2D array `dp` of the same dimensions as the dungeon, where `dp[i][j]` represents the minimum health required to reach the bottom-right corner from cell `(i, j)`. + +2. Base Case: +- The minimum health required at the bottom-right corner is `max(1, 1 - dungeon[m-1][n-1])`. + +3. Filling the DP Table: +- Fill the last row and last column of `dp` using the base case logic. +- For the rest of the cells, use the formula: +`dp[i][j] = max(1, min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j])` +4. Result: +- The value at `dp[0][0]` will be the minimum initial health required for the knight. + + + + +#### Implementation + +```Java +public class Solution { + public int calculateMinimumHP(int[][] dungeon) { + int m = dungeon.length; + int n = dungeon[0].length; + int[][] dp = new int[m][n]; + + dp[m-1][n-1] = Math.max(1, 1 - dungeon[m-1][n-1]); + + for (int i = m - 2; i >= 0; i--) { + dp[i][n-1] = Math.max(1, dp[i+1][n-1] - dungeon[i][n-1]); + } + for (int j = n - 2; j >= 0; j--) { + dp[m-1][j] = Math.max(1, dp[m-1][j+1] - dungeon[m-1][j]); + } + + for (int i = m - 2; i >= 0; i--) { + for (int j = n - 2; j >= 0; j--) { + int minHealthOnExit = Math.min(dp[i+1][j], dp[i][j+1]); + dp[i][j] = Math.max(1, minHealthOnExit - dungeon[i][j]); + } + } + + return dp[0][0]; + } +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(m \cdot n)$ + * We fill each cell of the dp array once. + +- **Space complexity**: $O(m \cdot n)$ + * We use a 2D array dp of the same dimensions as the dungeon. + +### Conclusion + +This dynamic programming solution efficiently calculates the minimum initial health required for the knight to rescue the princess. By starting from the bottom-right corner and working backward, we ensure that the knight has enough health to survive each step of the way. \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0175-combine-two-tables.md b/solutions/lc-solutions/0100-0199/0175-combine-two-tables.md new file mode 100644 index 0000000..a07aac1 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0175-combine-two-tables.md @@ -0,0 +1,97 @@ +--- +id: combine-two-tables +title: Combine two tables +sidebar_label: 0175-Combine Two tables +tags: [Dynamic Programming, Matrix] +description: Solution to the combine two tables problem of leetcode +--- + +## Problem Statement + +Table: Person +``` ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| personId | int | +| lastName | varchar | +| firstName | varchar | ++-------------+---------+ +personId is the primary key (column with unique values) for this table. +This table contains information about the ID of some persons and their first and last names. +``` + +Table: Address + +``` ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| addressId | int | +| personId | int | +| city | varchar | +| state | varchar | ++-------------+---------+ +addressId is the primary key (column with unique values) for this table. +Each row of this table contains information about the city and state of one person with ID = PersonId. +``` + +Write a solution to report the first name, last name, city, and state of each person in the `Person` table. If the address of a `personId` is not present in the `Address` table, report null instead. + +Return the result table in any order. + +The result format is in the following example. + +### Examples + +**Example 1:** + +``` +Input: +Person table: ++----------+----------+-----------+ +| personId | lastName | firstName | ++----------+----------+-----------+ +| 1 | Wang | Allen | +| 2 | Alice | Bob | ++----------+----------+-----------+ +Address table: ++-----------+----------+---------------+------------+ +| addressId | personId | city | state | ++-----------+----------+---------------+------------+ +| 1 | 2 | New York City | New York | +| 2 | 3 | Leetcode | California | ++-----------+----------+---------------+------------+ +Output: ++-----------+----------+---------------+----------+ +| firstName | lastName | city | state | ++-----------+----------+---------------+----------+ +| Allen | Wang | Null | Null | +| Bob | Alice | New York City | New York | ++-----------+----------+---------------+----------+ +Explanation: +There is no address in the address table for the personId = 1 so we return null in their city and state. +addressId = 1 contains information about the address of personId = 2. +``` + + + +## Solution + +### Approach 1: Using outer join + +#### Intuition +- Since the PersonId in table Address is the foreign key of table Person, we can join these two tables to get the address information of a person. + +- Considering there might be no address information for every person, we should use outer join instead of the default inner join. + +#### Implementation +- Note: For MySQL, an outer join is performed either using left join or right join. +```sql +select FirstName, LastName, City, State +from Person left join Address +on Person.PersonId = Address.PersonId +; +``` + +- Note: Using the where clause to filter the records will fail if there is no address information for a person because it will not display the name information. \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0176-second-highest-salary.md b/solutions/lc-solutions/0100-0199/0176-second-highest-salary.md new file mode 100644 index 0000000..dbecebb --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0176-second-highest-salary.md @@ -0,0 +1,114 @@ +--- +id: second-highest-salary +title: Second highest salary +sidebar_label: 0176-Second highest salary +tags: + - Array + - Sorting + - Bucket Sort + - Radix Sort +description: Given the solution to leetcode second highest salary problem +--- + +## Problem Statement +Table: Employee + +``` ++-------------+------+ +| Column Name | Type | ++-------------+------+ +| id | int | +| salary | int | ++-------------+------+ +id is the primary key (column with unique values) for this table. +Each row of this table contains information about the salary of an employee. + ``` + +Write a solution to find the second highest salary from the Employee table. If there is no second highest salary, return null (return None in Pandas). + +The result format is in the following example. + +### Examples + +**Example 1:** + +```plaintext +Input: +Employee table: ++----+--------+ +| id | salary | ++----+--------+ +| 1 | 100 | +| 2 | 200 | +| 3 | 300 | ++----+--------+ +Output: ++---------------------+ +| SecondHighestSalary | ++---------------------+ +| 200 | ++---------------------+ +``` + +**Example 2:** + +```plaintext +Input: +Employee table: ++----+--------+ +| id | salary | ++----+--------+ +| 1 | 100 | ++----+--------+ +Output: ++---------------------+ +| SecondHighestSalary | ++---------------------+ +| null | ++---------------------+ +``` + + + +## Solution + +### Approach + +- first create one empty list +- append all salarys to that list +- sort that list +- in this qoestion there are only 9 test cases to pass that test cases +- use if loops to check whether the last salary and last but one salary equal or not +- return the second highest salaryets and then find the maximum gap by comparing the minimum value of one bucket to the maximum value of the previous bucket. + +#### Implementation + +### Using panda +```python +import pandas as pd + +def second_highest_salary(employee: pd.DataFrame) -> pd.DataFrame: + d=[] + for i in employee["salary"]: + d.append(i) + d.sort() + if(len(d)<=1): + e={"SecondHighestSalary":[None]} + elif(d[-1]==d[-2] and len(d)==2): + e={"SecondHighestSalary":[None]} + elif(d[-1]==d[-2] and len(d)>2): + e={"SecondHighestSalary":[d[-3]]} + else: + e={"SecondHighestSalary":[d[-2]]} + c=pd.DataFrame(e) + return c +``` + +### Using MYSQL +```sql +select +(select distinct Salary +from Employee order by salary desc +limit 1 offset 1) +as SecondHighestSalary; +``` diff --git a/solutions/lc-solutions/0100-0199/0177-nth-highest-salary.md b/solutions/lc-solutions/0100-0199/0177-nth-highest-salary.md new file mode 100644 index 0000000..dc30a8f --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0177-nth-highest-salary.md @@ -0,0 +1,112 @@ +--- +id: nth-highest-salary +title: Nth highest salary +sidebar_label: 0177-nth highest salary +tags: + - Array + - Sorting + - Bucket Sort + - Radix Sort +description: Given the solution to leetcode nth highest salary problem +--- + +## Problem Statement +Table: Employee +``` ++-------------+------+ +| Column Name | Type | ++-------------+------+ +| id | int | +| salary | int | ++-------------+------+ +id is the primary key (column with unique values) for this table. +Each row of this table contains information about the salary of an employee. + +``` +Write a solution to find the nth highest salary from the Employee table. If there is no nth highest salary, return null. + +The result format is in the following example. +### Examples +***Example 1:*** +``` +Input: +Employee table: ++----+--------+ +| id | salary | ++----+--------+ +| 1 | 100 | +| 2 | 200 | +| 3 | 300 | ++----+--------+ +n = 2 +Output: ++------------------------+ +| getNthHighestSalary(2) | ++------------------------+ +| 200 | ++------------------------+ +``` + +***Example 2:*** +``` +Input: +Employee table: ++----+--------+ +| id | salary | ++----+--------+ +| 1 | 100 | ++----+--------+ +n = 2 +Output: ++------------------------+ +| getNthHighestSalary(2) | ++------------------------+ +| null | ++------------------------+ +``` +## Solution + +### Approach + +- take one set function add all salaries to that one using for loop +- convert set to list and sort +- if N is negitive or salaries are `Null or len(c) pd.DataFrame: + d=set() + for i in employee["salary"]: + d.add(i) + c=list(set(d)) + c.sort() + if(len(c) pd.DataFrame: + # Use the rank method to assign ranks to the scores in descending order with no gaps + scores['rank'] = scores['score'].rank(method='dense', ascending=False) + + # Drop id column & Sort the DataFrame by score in descending order + result_df = scores.drop('id',axis=1).sort_values(by='score', ascending=False) + + return result_df +``` + +### Using MYSQL +```sql +SELECT + Score, + (SELECT count(*) FROM (SELECT distinct Score s FROM Scores) tmp WHERE s >= Score) Rank +FROM Scores +ORDER BY Score desc +``` diff --git a/solutions/lc-solutions/0100-0199/0179-largest-number.md b/solutions/lc-solutions/0100-0199/0179-largest-number.md new file mode 100644 index 0000000..a35420b --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0179-largest-number.md @@ -0,0 +1,113 @@ +--- +id: largest-number +title: Largest Number(LeetCode) +sidebar_label: 0179-Largest Number +tags: + - Array + - String + - Greedy + - Sorting +description: Given a list of non-negative integers nums, arrange them such that they form the largest number and return it. +--- + +## Problem Statement + +Given a list of non-negative integers `nums`, arrange them such that they form the largest number and return it. + +Since the result may be very large, so you need to return a string instead of an integer. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [10,2] +Output: "210" +``` + +**Example 2:** + +```plaintext +Input: nums = [3,30,34,5,9] +Output: "9534330" +``` + +### Constraints + +- `1 <= nums.length <= 100` +- `0 <= nums[i] <= 109` + +## Solution + +The goal of this approach is to arrange a set of numbers such that they form the largest possible number when concatenated. The idea is to use a custom string comparator to determine the order of concatenation. + +### Approach + +#### Algorithm + +1. Convert Integers to Strings: +Convert the array of integers to an array of strings to facilitate custom sorting. +2. Custom Comparator: +Define a custom comparator to compare two strings (`str1` and `str2`). The comparator should decide the order based on the concatenated result of the strings: +* If `str1 + str2` is greater than `str2 + str1`, then `str1` should come before `str2`. +* Otherwise, `str2` should come before `str1`. +3. Sort the Array: +Use the custom comparator to sort the array of strings. +4. Handle Edge Cases: +If the largest number after sorting is '0', the result should be '0' (to handle cases like `[0, 0]`). +5. Build the Result: +Append all the sorted strings to form the final result. +6. Return the Result: +Convert the `StringBuilder` to a string and return it. + +#### Implementation + +```Java +import java.util.Arrays; +import java.util.Comparator; + +public class Solution { + public String largestNumber(int[] num) { + if (num == null || num.length == 0) + return ""; + + // Convert int array to String array for sorting + String[] s_num = new String[num.length]; + for (int i = 0; i < num.length; i++) + s_num[i] = String.valueOf(num[i]); + + // Custom comparator to decide the order of strings + Comparator comp = new Comparator() { + @Override + public int compare(String str1, String str2) { + String s1 = str1 + str2; + String s2 = str2 + str1; + return s2.compareTo(s1); // Reverse order + } + }; + + Arrays.sort(s_num, comp); + + // Handle the edge case where the largest number is '0' + if (s_num[0].charAt(0) == '0') + return "0"; + + // Build the result + StringBuilder sb = new StringBuilder(); + for (String s : s_num) + sb.append(s); + + return sb.toString(); + } +} + +``` + +### Complexity Analysis + +- **Time complexity**: $O(n k log n)$ - where k is the average length of the strings. +- **Space complexity**: $O(N)$ + +### Conclusion + +This approach efficiently solves the problem of forming the largest possible number by leveraging custom sorting based on string concatenation. It handles edge cases and ensures the correct order of numbers for the maximum concatenated value. The time complexity of `O(n k log n)` is reasonable given the constraints, and the space complexity is `O(n)`, which is manageable for typical input sizes. diff --git a/solutions/lc-solutions/0100-0199/0180-consecutive-numbers.md b/solutions/lc-solutions/0100-0199/0180-consecutive-numbers.md new file mode 100644 index 0000000..4a9b17c --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0180-consecutive-numbers.md @@ -0,0 +1,92 @@ +--- +id: consecutive-numbers +title: Consecutive Numbers(LeetCode) +sidebar_label: 0180-Consecutive Numbers +tags: + - Database +description: Given a table named Logs with two columns id and num we have to find all the numbers which are repeated three times consecutively. +--- + +## Problem Statement +``` ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| id | int | +| num | varchar | ++-------------+---------+ +``` +In SQL, id is the primary key for this table. +id is an autoincrement column. + + +Find all numbers that appear at least three times consecutively. + +Return the result table in any order. + +### Examples + +**Example 1:** +Input: +```plaintext +Logs table: ++----+-----+ +| id | num | ++----+-----+ +| 1 | 1 | +| 2 | 1 | +| 3 | 1 | +| 4 | 2 | +| 5 | 1 | +| 6 | 2 | +| 7 | 2 | ++----+-----+ +``` +Output: +``` ++-----------------+ +| ConsecutiveNums | ++-----------------+ +| 1 | ++-----------------+ +``` +Explanation: +1 is the only number that appears consecutively for at least three times. + +## Solution + +### Approach +1. We will first make creates three different aliases (log_1, log_2, and log_3) for the same table logs. It allows us to compare different rows within the same table. +2. Then simply use WHERE clause to get the result where id's and num in a row are consecutive and occurence of number is 3 times. + The conditions that must be met for the rows to be included in the result:
+ + * log_1.id = log_2.id + 1: The id of log_1 should be one more than the id of log_2. This means log_1 is immediately Β Β Β Β Β after log_2.
+ * log_2.id = log_3.id + 1: Similarly, the id of log_2 should be one more than the id of log_3. This means log_2 is Β Β Β Β Β immediately after log_3.
+ * log_1.num = log_2.num: The num value of log_1 should be equal to the num value of log_2.
+ * log_2.num = log_3.num: The num value of log_2 should be equal to the num value of log_3.
+ +Β Β Β Β Β Β Β Β Together, these conditions ensure that the three rows have consecutive id values and the same num value.
+ +3. Then from the result we will select the distinct numbers and then put inside a column named 'ConsecutiveNums'. +numbers + +#### Implementation + +```MySQL +SELECT distinct + log_1.num as ConsecutiveNums +FROM + logs log_1, + logs log_2, + logs log_3 +WHERE + log_1.id=log_2.id+1 AND + log_2.id=log_3.id+1 AND + log_1.num=log_2.num AND + log_2.num=log_3.num +``` + + +### Conclusion + +This approach efficiently solves the problem of finding out the consecutive numbers. diff --git a/solutions/lc-solutions/0100-0199/0181-employee-earning.md b/solutions/lc-solutions/0100-0199/0181-employee-earning.md new file mode 100644 index 0000000..894387b --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0181-employee-earning.md @@ -0,0 +1,70 @@ +--- +id: employee-earning +title: Employees Earning More Than Their Managers +sidebar_label: 0181-Employees Earning More Than Their Managers +tags: + - SQL +description: Given the solution to leetcode consecutive numbers problem +--- + +## Problem Statement +Table: Employee +``` ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| id | int | +| name | varchar | +| salary | int | +| managerId | int | ++-------------+---------+ +id is the primary key (column with unique values) for this table. +Each row of this table indicates the ID of an employee, their name, salary, and the ID of their manager. +``` +Write a solution to find the employees who earn more than their managers. + +Return the result table in any order. + +The result format is in the following example. + + + +### Examples +***Example 1:*** +``` +Input: +Employee table: ++----+-------+--------+-----------+ +| id | name | salary | managerId | ++----+-------+--------+-----------+ +| 1 | Joe | 70000 | 3 | +| 2 | Henry | 80000 | 4 | +| 3 | Sam | 60000 | Null | +| 4 | Max | 90000 | Null | ++----+-------+--------+-----------+ +Output: ++----------+ +| Employee | ++----------+ +| Joe | ++----------+ +Explanation: Joe is the only employee who earns more than his manager. +``` + +## Solution + +### Approach + +- select e1.name as employee: This selects the name of the employee from the employee table e1. +- from employee e1: This specifies the primary table e1 from which we are selecting the data. +- join employee e2 on e2.id = e1.managerid: This joins the employee table e2 with e1 on the condition that the id of e2 (which represents the manager's ID) matches the managerid of e1 (which represents the employee's manager ID). +- where e1.salary > e2.salary: This filters the results to include only those employees whose salary is greater than their manager's salary. + + +#### Implementation + +### Using MYSQL +```sql +select e1.name as employee from employee e1 +join employee e2 on e2.id=e1.managerid and e1.salary> e2.salary +``` diff --git a/solutions/lc-solutions/0100-0199/0182-Duplicate-Emails.md b/solutions/lc-solutions/0100-0199/0182-Duplicate-Emails.md new file mode 100644 index 0000000..90661a3 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0182-Duplicate-Emails.md @@ -0,0 +1,73 @@ +--- +id: duplicate-emails +title: Duplicate Emails +sidebar_label: 0183. Duplicate Emails +tags: +- SQL +- Database +description: "Solution to Leetcode 183. Duplicate Emails" +--- + +## Problem Description + +Given a table `Person`, write a query to find all duplicate emails. + +**Table: Person** + +| Column Name | Type | +| ----------- | ------- | +| id | int | +| email | varchar | +id is the primary key for this table. Each row of this table contains an email. The emails will not contain uppercase letters. + +### Examples + +**Example 1:** + +**Input:** + +**Person table:** + +| id | email | +| --- | ------- | +| 1 | a@b.com | +| 2 | c@d.com | +| 3 | a@b.com | + +**Output:** + +| Email | +| ------- | +| a@b.com | + +### Approach + +1. Group the rows in the `Person` table by the `email` column. +2. Use the `HAVING` clause to filter out the groups that have a count greater than 1, indicating duplicate emails. + +### Solution + +#### SQL + +```sql +-- SQL solution to find duplicate emails + +SELECT email +FROM Person +GROUP BY email +HAVING COUNT(*) > 1; +``` + +### Explanation + +- **GROUP BY email**: Groups the records by the `email` column. +- **HAVING COUNT(*) > 1**: Filters the groups to include only those with more than one occurrence, indicating that the email is duplicated. + +### Complexity Analysis + +- **Time Complexity**: O(n), where n is the number of rows in the `Person` table. +- **Space Complexity**: O(n), where n is the number of rows in the `Person` table. + +### References + +- **LeetCode Problem**: Duplicate Emails \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0184-department-highest-salary.md b/solutions/lc-solutions/0100-0199/0184-department-highest-salary.md new file mode 100644 index 0000000..dd983e0 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0184-department-highest-salary.md @@ -0,0 +1,203 @@ +--- +id: department-highest-salary +title: Department Highest Salary +sidebar_label: 0184. Department Highest Salary +tags: [SQL, Database] +description: Solution to Leetcode 184 Department Highest Salary +sidebar_position: 85 +--- + +## Problem Statement + +### Problem Description + +Given two tables, `Employee` and `Department`, write a query to find the employees who have the highest salary in each department. + +**Table: Employee** + +``` ++--------------+---------+ +| Column Name | Type | ++--------------+---------+ +| id | int | +| name | varchar | +| salary | int | +| departmentId | int | + + +id is the primary key for this table. `departmentId` is a foreign key referencing the `id` column in the `Department` table. + +**Table: Department** + +| Column Name | Type | +|-------------|---------| +| id | int | +| name | varchar | ++-------------+---------+ +``` +id is the primary key (column with unique values) for this table. +departmentId is a foreign key (reference columns) of the ID from the Department table. +Each row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department. + + +Table: Department +``` ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| id | int | +| name | varchar | ++-------------+---------+ +``` + +id is the primary key (column with unique values) for this table. It is guaranteed that department name is not NULL. +Each row of this table indicates the ID of a department and its name. + +Write a solution to find employees who have the highest salary in each of the departments. Return the result table in any order. + +### Examples + +**Example 1:** + +**Input:** + +**Employee table:** + +| id | name | salary | departmentId | +| --- | ----- | ------ | ------------ | +| 1 | Joe | 70000 | 1 | +| 2 | Jim | 90000 | 1 | +| 3 | Henry | 80000 | 2 | +| 4 | Sam | 60000 | 2 | +| 5 | Max | 90000 | 1 | + +**Department table:** + +| id | name | +| --- | ----- | +| 1 | IT | +| 2 | Sales | + +**Output:** + +| Department | Employee | Salary | +|------------|----------|--------| +| IT | Jim | 90000 | +| IT | Max | 90000 | +| Sales | Henry | 80000 | + +### Constraints + +1. Each employee's salary is a positive integer. +2. The number of employees in each department is between 1 and 1000. +3. The number of departments is between 1 and 500. + +## Solution of Given Problem + +### Intuition and Approach + +1. Perform a `JOIN` between the `Employee` table and the `Department` table on the `departmentId` column. +2. Use a subquery to find the maximum salary for each department. +3. Filter the employees who have the highest salary in their respective departments. + +### Complexity Analysis + +- **Time Complexity**: O(n * m), where n is the number of rows in the `Employee` table and m is the number of rows in the `Department` table. +- **Space Complexity**: O(n), where n is the number of rows in the `Employee` table. + +#### Codes in Different Languages + + + + + ```sql + SELECT d.name AS Department, e.name AS Employee, e.salary AS Salary + FROM Employee e + JOIN Department d ON e.departmentId = d.id + WHERE e.salary = ( + SELECT MAX(salary) + FROM Employee + WHERE departmentId = e.departmentId + ); + ``` + + + + + ```python + import sqlite3 + + conn = sqlite3.connect(':memory:') + cursor = conn.cursor() + + cursor.execute(''' + CREATE TABLE Employee ( + id INTEGER PRIMARY KEY, + name TEXT, + salary INTEGER, + departmentId INTEGER + ) + ''') + + cursor.execute(''' + CREATE TABLE Department ( + id INTEGER PRIMARY KEY, + name TEXT + ) + ''') + + employees = [ + (1, 'Joe', 70000, 1), + (2, 'Jim', 90000, 1), + (3, 'Henry', 80000, 2), + (4, 'Sam', 60000, 2), + (5, 'Max', 90000, 1) + ] + + departments = [ + (1, 'IT'), + (2, 'Sales') + ] + + cursor.executemany('INSERT INTO Employee VALUES (?, ?, ?, ?)', employees) + cursor.executemany('INSERT INTO Department VALUES (?, ?)', departments) + + cursor.execute(''' + SELECT d.name AS Department, e.name AS Employee, e.salary AS Salary + FROM Employee e + JOIN Department d ON e.departmentId = d.id + WHERE e.salary = ( + SELECT MAX(salary) + FROM Employee + WHERE departmentId = e.departmentId + ) + ''') + results = cursor.fetchall() + for row in results: + print(row) + + conn.close() + ``` + + + + +## Video Explanation of Given Problem + + + +--- + +

Authors:

+ +
+{['pallasivasai'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/0185-department-top-three-salaries.md b/solutions/lc-solutions/0100-0199/0185-department-top-three-salaries.md new file mode 100644 index 0000000..205b768 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0185-department-top-three-salaries.md @@ -0,0 +1,127 @@ +--- +id: department-top-three-salaries +title: Department Top Three Salaries(LeetCode) +sidebar_label: 0185-Department Top Three Salaries +tags: + - Database +description: Given two tables named Employee table with four columns named id, name, salary, departmentId and Department table with two columns named id, name we have to to find the employees who are high earners in each of the departments. + + +--- + +## Problem Statement +Table: Employee +``` ++--------------+---------+ +| Column Name | Type | ++--------------+---------+ +| id | int | +| name | varchar | +| salary | int | +| departmentId | int | ++--------------+---------+ +``` +id is the primary key (column with unique values) for this table. +departmentId is a foreign key (reference columns) of the ID from the Department table. +Each row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department. + + +Table: Department +``` ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| id | int | +| name | varchar | ++-------------+---------+ +``` +id is the primary key (column with unique values) for this table. It is guaranteed that department name is not NULL. +Each row of this table indicates the ID of a department and its name. + +A company's executives are interested in seeing who earns the most money in each of the company's departments. A high earner in a department is an employee who has a salary in the top three unique salaries for that department. + +Write a solution to find the employees who are high earners in each of the departments. + +Return the result table in any order. + +### Examples + +**Example 1:** +Input: +```plaintext +Employee table: ++----+-------+--------+--------------+ +| id | name | salary | departmentId | ++----+-------+--------+--------------+ +| 1 | Joe | 85000 | 1 | +| 2 | Henry | 80000 | 2 | +| 3 | Sam | 60000 | 2 | +| 4 | Max | 90000 | 1 | +| 5 | Janet | 69000 | 1 | +| 6 | Randy | 85000 | 1 | +| 7 | Will | 70000 | 1 | ++----+-------+--------+--------------+ +Department table: ++----+-------+ +| id | name | ++----+-------+ +| 1 | IT | +| 2 | Sales | ++----+-------+ +``` +Output: +``` ++------------+----------+--------+ +| Department | Employee | Salary | ++------------+----------+--------+ +| IT | Max | 90000 | +| IT | Joe | 85000 | +| IT | Randy | 85000 | +| IT | Will | 70000 | +| Sales | Henry | 80000 | +| Sales | Sam | 60000 | ++------------+----------+--------+ +``` +Explanation: +In the IT department: +- Max earns the highest unique salary +- Both Randy and Joe earn the second-highest unique salary +- Will earns the third-highest unique salary + +In the Sales department: +- Henry earns the highest salary +- Sam earns the second-highest salary +- There is no third-highest salary as there are only two employees +## Solution + +### Approach +1. We will select three columns for the final output:
+ + * D.Name as Department: The name of the department. + * E.Name as Employee: The name of the employee. + * E.Salary as Salary: The salary of the employee. + +2. Then we will use WHERE clause which has
+ + * D.ID = E.DepartmentId: Ensures that the department ID in the Department table matches the department ID in the Employee table (aliased as E). + * E.DepartmentId = E2.DepartmentId: Ensures that the department ID in the Employee table (aliased as E) matches the department ID in the Employee table (aliased as E2). + * E.Salary <= E2.Salary: Ensures that the salary of E is less than or equal to the salary of E2. This creates a comparison to find the top salaries within each department. +3. Then we will use Group By clause to group the results by department ID and employee name. +4. Then we will use Having clause + * count(distinct E2.Salary) <= 3: Filters the groups to include only those where the distinct count of salaries in E2 is less than or equal to 3. This effectively limits the results to the top 3 salaries per department. +5. Then finally we order the final results by department name in ascending order and employee salary in descending order. +#### Implementation + +```MySQL +SELECT D.Name as Department, E.Name as Employee, E.Salary +FROM Department D, Employee E, Employee E2 +WHERE D.ID = E.DepartmentId and E.DepartmentId = E2.DepartmentId and +E.Salary <= E2.Salary +group by D.ID,E.Name having count(distinct E2.Salary) <= 3 +order by D.Name, E.Salary desc +``` + + +### Conclusion + +This approach efficiently solves the problem by joining the Department table with the Employee table twice (aliased as E and E2). It finds employees who are among the top three highest salaries within their respective departments. The final result lists these employees along with their department names and salaries, sorted by department name and salary in descending order. diff --git a/solutions/lc-solutions/0100-0199/0185-top-three-salaries.md b/solutions/lc-solutions/0100-0199/0185-top-three-salaries.md new file mode 100644 index 0000000..7fe931c --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0185-top-three-salaries.md @@ -0,0 +1,165 @@ +--- +id: top-three-salaries +title: Department top three salaries +sidebar_label: 0185-Deaprtment top three salaries +tags: +- SQL +- Database +description: "Solution to Leetcode 183. Customers Who Never Order" +--- + +## Problem Description + +Table: Employee +``` ++--------------+---------+ +| Column Name | Type | ++--------------+---------+ +| id | int | +| name | varchar | +| salary | int | +| departmentId | int | ++--------------+---------+ +id is the primary key (column with unique values) for this table. +departmentId is a foreign key (reference column) of the ID from the Department table. +Each row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department. +``` +Table: Department +``` ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| id | int | +| name | varchar | ++-------------+---------+ +id is the primary key (column with unique values) for this table. +Each row of this table indicates the ID of a department and its name. + +``` + +A company's executives are interested in seeing who earns the most money in each of the company's departments. A high earner in a department is an employee who has a salary in the top three unique salaries for that department. + +Write a solution to find the employees who are high earners in each of the departments. + +Return the result table in any order. + +The result format is in the following example +### Examples + +**Example 1:** +``` +Input: +Employee table: ++----+-------+--------+--------------+ +| id | name | salary | departmentId | ++----+-------+--------+--------------+ +| 1 | Joe | 85000 | 1 | +| 2 | Henry | 80000 | 2 | +| 3 | Sam | 60000 | 2 | +| 4 | Max | 90000 | 1 | +| 5 | Janet | 69000 | 1 | +| 6 | Randy | 85000 | 1 | +| 7 | Will | 70000 | 1 | ++----+-------+--------+--------------+ +Department table: ++----+-------+ +| id | name | ++----+-------+ +| 1 | IT | +| 2 | Sales | ++----+-------+ +Output: ++------------+----------+--------+ +| Department | Employee | Salary | ++------------+----------+--------+ +| IT | Max | 90000 | +| IT | Joe | 85000 | +| IT | Randy | 85000 | +| IT | Will | 70000 | +| Sales | Henry | 80000 | +| Sales | Sam | 60000 | ++------------+----------+--------+ +Explanation: +In the IT department: +- Max earns the highest unique salary +- Both Randy and Joe earn the second-highest unique salary +- Will earns the third-highest unique salary + +In the Sales department: +- Henry earns the highest salary +- Sam earns the second-highest salary +- There is no third-highest salary as there are only two employees +``` + +### Approach +#### Approach 1: Return the First n Rows Using nlargest() +#### Algorithm +- For this problem, we can either identify the top earners first using DataFrame employee and then join the DataFrame department to get the department name, or join the DataFrame department first to get the department name before identifying the top earners. In this approach, we use the latter logic. + +- In this step, we can also update the column name in the DataFrame department from name to Department as requested by the final output. +```sql +Employee_Department = employee.merge(department, left_on='departmentId', right_on='id').rename(columns = {'name_y': 'Department'}) +``` + +- Since the definition of a high earner is an employee who has a salary in the top three unique salaries for the department, we want to make sure the salary is unique at the department level for later calculation. To do this, we select only the department and salary from the DataFrame created in the last step and drop any duplicated records if existed. +```sql +Employee_Department = Employee_Department[['Department', 'departmentId', 'salary']].drop_duplicates() +``` + +- Now we can identify the top 3 unique salaries for each department. We use the function nlargest() to get this value. The parameter '3' is passed to the function as it defines the number of rows to return. + +```sql +top_salary = Employee_Department.groupby(['Department', 'departmentId']).salary.nlargest(3).reset_index() +``` + +- Now we only need to identify the employees are in these departments and making the same amount of salary. To do this, we can merge the DataFrame top_salary, which contains the top three unique salary for each department, to the DataFrame employee on departmentId and salary, so only the employees that match both criteria will be retained. + + +```sql +df = top_salary.merge(employee, on=['departmentId', 'salary']) +``` + +- Lastly, we clean the DataFrame as per requested by the final output. We keep only the columns needed and rename the columns accordingly. + +```sql +df[['Department', 'name', 'salary']].rename(columns = {'name': 'Employee', 'salary': 'Salary'}) +``` + +### Solution + +#### SQL + +```sql +WITH employee_department AS + ( + SELECT d.id, + d.name AS Department, + salary AS Salary, + e.name AS Employee, + DENSE_RANK()OVER(PARTITION BY d.id ORDER BY salary DESC) AS rnk + FROM Department d + JOIN Employee e + ON d.id = e.departmentId + ) +SELECT Department, Employee, Salary +FROM employee_department +WHERE rnk <= 3 +``` + +#### PYthon +```python +import pandas as pd +​ +def top_three_salaries(employee: pd.DataFrame, department: pd.DataFrame) -> pd.DataFrame: + + Employee_Department = employee.merge(department, left_on='departmentId', right_on='id').rename(columns = {'name_y': 'Department'}) + + Employee_Department = Employee_Department[['Department', 'departmentId', 'salary']].drop_duplicates() + + top_salary = Employee_Department.groupby(['Department', 'departmentId']).salary.nlargest(3).reset_index() + + df = top_salary.merge(employee, on=['departmentId', 'salary']) + + return df[['Department', 'name', 'salary']].rename(columns = {'name': 'Employee', 'salary': 'Salary'}) +``` + diff --git a/solutions/lc-solutions/0100-0199/0186-reverse-word-string-2.md b/solutions/lc-solutions/0100-0199/0186-reverse-word-string-2.md new file mode 100644 index 0000000..d9f88fc --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0186-reverse-word-string-2.md @@ -0,0 +1,130 @@ +--- +id: reverse-words-in-string-II +title: Reverse words in string -II +sidebar_label: 0186-Reverse words in string -II +tags: +- strings +description: "Given an input string , reverse the string word by word. + +" +--- + +## Problem Description +Given a character array s, reverse the order of the words. + +A word is defined as a sequence of non-space characters. The words in s will be separated by a single space. + +Your code must solve the problem in-place, i.e. without allocating extra space. +### Examples + +**Example 1:** +``` +Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] +Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"] + +``` + +***Example:2*** +``` +Input: s = ["a"] +Output: ["a"] +``` + + +#### Constraints +- `1 <= s.length <= 105` +- `s[i] `is an English letter (uppercase or lowercase), digit, or space ' '. +- There is at least one word in s. +- s does not contain leading or trailing spaces. +- All the words in s are guaranteed to be separated by a single space. + + +### Approach + +- Here's a step-by-step explanation of the approach in simple terms: + +#### Helper Function reverse: + +- A helper function reverse is defined to reverse a section of the list in-place. It takes the list s and two indices i and j and swaps elements at these indices moving towards the center until i is no longer less than j. + + +#### Initial Setup: + +- The function starts by initializing three variables: i, j, and n. +- i keeps track of the start of the current word. +- j is used to iterate through the list. +- n is the length of the list. +- Reverse Each Word Individually: + +The function iterates through the list using j. +When a space (' ') is encountered, it means the end of a word has been found. +The reverse function is called to reverse the characters in the word from index i to j-1. +After reversing the word, i is set to j+1 to start tracking the next word. +If the end of the list is reached (j == n-1), the last word is reversed by calling reverse from index i to j. + +#### Reverse the Entire List: + +- After all individual words are reversed, the entire list is reversed by calling the reverse function from index 0 to n-1. +By reversing each word individually and then reversing the entire list, the words end up in the correct reversed order. + + + + +### Solution + +#### Java + +```Java +class Solution { + public void reverseWords(char[] s) { + int n = s.length; + for (int i = 0, j = 0; j < n; ++j) { + if (s[j] == ' ') { + reverse(s, i, j - 1); + i = j + 1; + } else if (j == n - 1) { + reverse(s, i, j); + } + } + reverse(s, 0, n - 1); + } + + private void reverse(char[] s, int i, int j) { + for (; i < j; ++i, --j) { + char t = s[i]; + s[i] = s[j]; + s[j] = t; + } + } +} +``` + +#### PYthon +```python +class Solution: + def reverseWords(self, s: List[str]) -> None: + """ + Do not return anything, modify s in-place instead. + """ + + def reverse(s, i, j): + while i < j: + s[i], s[j] = s[j], s[i] + i += 1 + j -= 1 + + i, j, n = 0, 0, len(s) + while j < n: + if s[j] == ' ': + reverse(s, i, j - 1) + i = j + 1 + elif j == n - 1: + reverse(s, i, j) + j += 1 + reverse(s, 0, n - 1) +``` + + +### Complexity analysis +- Time Complexity: $𝑂(n)$ +- Space Complexity: $O(1)$ diff --git a/solutions/lc-solutions/0100-0199/0187-repeated-dna-sequence.md b/solutions/lc-solutions/0100-0199/0187-repeated-dna-sequence.md new file mode 100644 index 0000000..54a75ca --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0187-repeated-dna-sequence.md @@ -0,0 +1,112 @@ +--- +id: repeated-dna-sequence +title: Repeated DNA Sequences +sidebar_label: 0187-Repeated DNA Sequences +tags: +- strings +description: "leetcode solution of problem 187" +--- + +## Problem Description +The DNA sequence is composed of a series of nucleotides abbreviated as `'A', 'C', 'G', and 'T'`. + +For example, `"ACGAATTCCG"` is a DNA sequence. +When studying DNA, it is useful to identify repeated sequences within the DNA. + +Given a string s that represents a DNA sequence, return all the `10`-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order. + + + +### Examples + +**Example 1:** +``` +Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" +Output: ["AAAAACCCCC","CCCCCAAAAA"] + +``` + +***Example:2*** +``` +Input: s = "AAAAAAAAAAAAA" +Output: ["AAAAAAAAAA"] +``` + + +#### Constraints +- `1 <= s.length <= 105` +- `s[i]` is either `'A', 'C', 'G', or 'T'`. + + +### Approach + +1. **Initialize Sets**: Use two hash setsβ€”`seen` to track all 10-letter-long substrings encountered, and `ans` to store substrings that appear more than once. + +2. **Iterate Through String**: Loop through the string, extracting each 10-letter-long substring. + +3. **Check and Record**: For each substring, check if it is already in `seen`. If it is, add it to `ans`. Regardless, add the substring to `seen`. + +4. **Return Results**: Convert the `ans` set to a vector and return it as the result. + +### Solution + +#### C++ + +```cpp +class Solution { + public: + vector findRepeatedDnaSequences(string s) { + unordered_set ans; + unordered_set seen; + const string_view sv(s); + + for (int i = 0; i + 10 <= s.length(); ++i) { + if (seen.count(sv.substr(i, 10))) + ans.insert(s.substr(i, 10)); + seen.insert(sv.substr(i, 10)); + } + + return {ans.begin(), ans.end()}; + } +}; +``` + +#### PYthon +```python +class Solution: + def findRepeatedDnaSequences(self, s: str) -> List[str]: + ans = set() + seen = set() + + for i in range(len(s) - 9): + seq = s[i:i + 10] + if seq in seen: + ans.add(seq) + seen.add(seq) + + return list(ans) +``` + +#### Java +```Java +class Solution { + public List findRepeatedDnaSequences(String s) { + Set ans = new HashSet<>(); + Set seen = new HashSet<>(); + + for (int i = 0; i + 10 <= s.length(); ++i) { + final String seq = s.substring(i, i + 10); + if (seen.contains(seq)) + ans.add(seq); + seen.add(seq); + } + + return new ArrayList<>(ans); + } +} +``` + + +### Complexity analysis +- Time Complexity: $𝑂(n)$ +- Space Complexity: $O(n)$ diff --git a/solutions/lc-solutions/0100-0199/0188-best-time-to-buy-sell-stock-IV.md b/solutions/lc-solutions/0100-0199/0188-best-time-to-buy-sell-stock-IV.md new file mode 100644 index 0000000..ccef9de --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0188-best-time-to-buy-sell-stock-IV.md @@ -0,0 +1,154 @@ +--- +id: best-time-to-buy-sell-stock-IV +title: Best Time to Buy and Sell Stock IV +sidebar_label: 0188-Best Time to Buy and Sell Stock IV +tags: +- Arrays +- DP +description: "leetcode solution of problem 188" +--- + +## Problem Description +You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k. + +Find the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k times. + +Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). + + +### Examples + +**Example 1:** +``` +Input: k = 2, prices = [2,4,1] +Output: 2 +Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. +``` +***Example 2:*** +``` +Input: k = 2, prices = [3,2,6,5,0,3] +Output: 7 +Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. +``` + +#### Constraints +- `1 <= k <= 100` +- `1 <= prices.length <= 1000` +-` 0 <= prices[i] <= 1000` + + +### Approach +### Approach to Find Maximum Profit with at Most k Transactions + +1. **Edge Case Handling**: + - If `k` is greater than or equal to half the length of `prices`, it means we can perform an unlimited number of transactions. + - In this case, initialize `sell` to 0 (maximum profit with no stock) and `hold` to negative infinity (maximum profit with stock). + - Iterate through `prices` to update `sell` and `hold` based on the maximum possible profit at each price. + - Return the final `sell` value as the result. + +2. **General Case**: + - If `k` is less than half the length of `prices`, initialize two lists: `sell` to store maximum profit after selling a stock, and `hold` to store maximum profit after buying a stock. + - Both lists have a length of `k + 1`, with `sell` initialized to 0 and `hold` initialized to negative infinity. + +3. **Iterate Through Prices**: + - For each price in `prices`, iterate from `k` down to 1 to update `sell` and `hold`. + - Update `sell[i]` to be the maximum of itself or the profit from selling the stock held at the current price. + - Update `hold[i]` to be the maximum of itself or the profit from buying a stock at the current price. + +4. **Return Results**: Return `sell[k]`, which represents the maximum profit with at most `k` transactions. + + +### Solution + +#### C++ + +```cpp +class Solution { + public: + int maxProfit(int k, vector& prices) { + if (k >= prices.size() / 2) { + int sell = 0; + int hold = INT_MIN; + + for (const int price : prices) { + sell = max(sell, hold + price); + hold = max(hold, sell - price); + } + + return sell; + } + + vector sell(k + 1); + vector hold(k + 1, INT_MIN); + + for (const int price : prices) + for (int i = k; i > 0; --i) { + sell[i] = max(sell[i], hold[i] + price); + hold[i] = max(hold[i], sell[i - 1] - price); + } + + return sell[k]; + } +}; +``` + +#### PYthon +```python +class Solution: + def maxProfit(self, k: int, prices: List[int]) -> int: + if k >= len(prices) // 2: + sell = 0 + hold = -math.inf + + for price in prices: + sell = max(sell, hold + price) + hold = max(hold, sell - price) + + return sell + + sell = [0] * (k + 1) + hold = [-math.inf] * (k + 1) + + for price in prices: + for i in range(k, 0, -1): + sell[i] = max(sell[i], hold[i] + price) + hold[i] = max(hold[i], sell[i - 1] - price) + + return sell[k] +``` + +#### Java +```Java +class Solution { + public int maxProfit(int k, int[] prices) { + if (k >= prices.length / 2) { + int sell = 0; + int hold = Integer.MIN_VALUE; + + for (final int price : prices) { + sell = Math.max(sell, hold + price); + hold = Math.max(hold, sell - price); + } + + return sell; + } + + int[] sell = new int[k + 1]; + int[] hold = new int[k + 1]; + Arrays.fill(hold, Integer.MIN_VALUE); + + for (final int price : prices) + for (int i = k; i > 0; --i) { + sell[i] = Math.max(sell[i], hold[i] + price); + hold[i] = Math.max(hold[i], sell[i - 1] - price); + } + + return sell[k]; + } +} +``` + + +### Complexity analysis +- Time Complexity: $𝑂(nk)$ +- Space Complexity: $O(k)$ diff --git a/solutions/lc-solutions/0100-0199/0189-rotate-array.md b/solutions/lc-solutions/0100-0199/0189-rotate-array.md new file mode 100644 index 0000000..d814296 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0189-rotate-array.md @@ -0,0 +1,185 @@ +--- +id: 189-rotate-array +title: Rotate Array (LeetCode) +sidebar_label: 0189 Rotate Array +tags: + - Array + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Rotate Array problem on LeetCode." +--- + +## Problem Description + +Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,3,4,5,6,7], k = 3 +Output: [5,6,7,1,2,3,4] +Explanation: +rotate 1 steps to the right: [7,1,2,3,4,5,6] +rotate 2 steps to the right: [6,7,1,2,3,4,5] +rotate 3 steps to the right: [5,6,7,1,2,3,4] + +``` + +**Example 2:** + +``` +Input: nums = [-1,-100,3,99], k = 2 +Output: [3,99,-1,-100] +Explanation: +rotate 1 steps to the right: [99,-1,-100,3] +rotate 2 steps to the right: [3,99,-1,-100] +``` + +### Constraints + +- $1 <= nums.length <= 105$ +- $-231 <= nums[i] <= 231 - 1$ +- $0 <= k <= 105$ + + +## Solution for Candy Distribution Problem + +### Intuition And Approach + +To rotate an array to the right by k steps, we need to move the last k elements to the front and shift the rest of the elements to the right. A straightforward way to achieve this in-place (without using extra space for another array) is to use the reversal method. + +Here is the step-by-step approach: + +1. Adjust k: + +If k is greater than the length of the array, rotating by k steps is the same as rotating by k % n steps (where n is the length of the array). This is because rotating by the length of the array brings it back to the original position. +Calculate k = k % n. + +2. Reverse the entire array: + +By reversing the entire array, the last k elements (which we want to move to the front) will be at the beginning, but in reverse order. +For example, reversing [1, 2, 3, 4, 5, 6, 7] gives [7, 6, 5, 4, 3, 2, 1]. + +3. Reverse the first k elements: + +The first k elements are now the elements that were originally at the end of the array. Reverse these to restore their original order. +Continuing the example, reversing the first 3 elements of [7, 6, 5, 4, 3, 2, 1] gives [5, 6, 7, 4, 3, 2, 1]. + +4. Reverse the remaining n - k elements: + +Finally, reverse the rest of the array (from the k-th element to the end) to restore their order. +In the example, reversing the elements from index 3 to 6 of [5, 6, 7, 4, 3, 2, 1] gives [5, 6, 7, 1, 2, 3, 4]. + + + +#### Code in Different Languages + + + + + ```java + + class Solution { + public void rotate(int[] nums, int k) { + // Ensure k is within the bounds of the array length + k = k % nums.length; + + // Reverse the entire array + reverse(nums, 0, nums.length - 1); + + // Reverse the first k elements + reverse(nums, 0, k - 1); + + // Reverse the remaining elements + reverse(nums, k, nums.length - 1); + } + + // Helper function to reverse elements in the array from start to end + private void reverse(int[] nums, int start, int end) { + while (start < end) { + int temp = nums[start]; + nums[start] = nums[end]; + nums[end] = temp; + start++; + end--; + } + } + + ``` + + + + ```python + + class Solution(object): + def rotate(self, nums, k): + k = k % len(nums) + + # Reverse the entire array + self.reverse(nums, 0, len(nums) - 1) + + # Reverse the first k elements + self.reverse(nums, 0, k - 1) + + # Reverse the remaining elements + self.reverse(nums, k, len(nums) - 1) + + def reverse(self, nums, start, end): + while start < end: + nums[start], nums[end] = nums[end], nums[start] + start += 1 + end -= 1 + + ``` + + + + + + ```cpp + + #include + using namespace std; + + class Solution { + public: + void rotate(vector& nums, int k) { + // Ensure k is within the bounds of the array length + k = k % nums.size(); + + // Reverse the entire array + reverse(nums, 0, nums.size() - 1); + + // Reverse the first k elements + reverse(nums, 0, k - 1); + + // Reverse the remaining elements + reverse(nums, k, nums.size() - 1); + } + + private: + void reverse(vector& nums, int start, int end) { + while (start < end) { + int temp = nums[start]; + nums[start] = nums[end]; + nums[end] = temp; + start++; + end--; + } + } + }; + ``` + + + + + +## References + +- **LeetCode Problem:** [Rotate Array Problem](https://leetcode.com/problems/rotate-array/) +- **Solution Link:** [Rotate Array Solution on LeetCode](https://leetcode.com/problems/rotate-array/solutions/5273312/rotate-array-solution) +- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) diff --git a/solutions/lc-solutions/0100-0199/0190-Reverse-Bits.md b/solutions/lc-solutions/0100-0199/0190-Reverse-Bits.md new file mode 100644 index 0000000..0861e29 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0190-Reverse-Bits.md @@ -0,0 +1,132 @@ +--- +id: Reverse-Bits +title: Reverse-Bits +sidebar_label: Reverse Bits +tags: + - Bit Manipulation + - Integer Manipulation +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Reverse-Bits](https://leetcode.com/problems/Reverse-Bits/description/) | [Reverse-Bits Solution on LeetCode](https://leetcode.com/problems/Reverse-Bits/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + + +## Problem Description + +Reverse the bits of a given 32-bit unsigned integer. + +### Note + +In some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. + +In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 below, the input represents the signed integer -3 and the output represents the signed integer -1073741825. + +### Examples + +**Example 1:** + +Input: `n = 00000010100101000001111010011100` +Output: `964176192` (Binary: `00111001011110000010100101000000`) +Explanation: The input binary string `00000010100101000001111010011100` represents the unsigned integer `43261596`, so return `964176192` which its binary representation is `00111001011110000010100101000000`. + +**Example 2:** + +Input: `n = 11111111111111111111111111111101` +Output: `3221225471` (Binary: `10111111111111111111111111111111`) +Explanation: The input binary string `11111111111111111111111111111101` represents the unsigned integer `4294967293`, so return `3221225471` which its binary representation is `10111111111111111111111111111111`. + +### Constraints + +- The input must be a binary string of length 32. + +## Approach + +To reverse the bits of a 32-bit unsigned integer, we can use bit manipulation. We will: + +1. Initialize a variable to hold the result. +2. Iterate through each bit of the input number. +3. For each bit, shift the result left by one position and add the current bit. +4. Shift the input number right by one position. +5. Continue until all 32 bits are processed. + +## Solution + +### Step-by-Step Algorithm + +1. Initialize the result to 0. +2. For each of the 32 bits: + 1. Left shift the result by 1 bit. + 2. Add the least significant bit (LSB) of `n` to the result. + 3. Right shift `n` by 1 bit. +3. Return the result. + +### Python + +```python +class Solution: + def reverseBits(self, n: int) -> int: + result = 0 + for i in range(32): + result = (result << 1) | (n & 1) + n >>= 1 + return result +``` + +### Java +```java +public class Solution { + public int reverseBits(int n) { + int result = 0; + for (int i = 0; i < 32; i++) { + result = (result << 1) | (n & 1); + n >>= 1; + } + return result; + } +} +``` + +### C++ +```cpp +class Solution { +public: + uint32_t reverseBits(uint32_t n) { + uint32_t result = 0; + for (int i = 0; i < 32; i++) { + result = (result << 1) | (n & 1); + n >>= 1; + } + return result; + } +}; +``` + +### C +```c +uint32_t reverseBits(uint32_t n) { + uint32_t result = 0; + for (int i = 0; i < 32; i++) { + result = (result << 1) | (n & 1); + n >>= 1; + } + return result; +} +``` + +### JavaScript +```js +var reverseBits = function(n) { + let result = 0; + for (let i = 0; i < 32; i++) { + result = (result << 1) | (n & 1); + n >>= 1; + } + return result >>> 0; +}; +``` + +### Conclusion +The bit manipulation technique efficiently reverses the bits of a 32-bit unsigned integer. The key steps involve shifting and masking bits appropriately within a loop that iterates exactly 32 times. This approach ensures that the solution is both time-efficient and space-efficient, with a time complexity of O(1) and a space complexity of O(1). diff --git a/solutions/lc-solutions/0100-0199/0191-number-of-1-bits.md b/solutions/lc-solutions/0100-0199/0191-number-of-1-bits.md new file mode 100644 index 0000000..a900190 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0191-number-of-1-bits.md @@ -0,0 +1,88 @@ +--- +id: number-of-1-bits +title: Number of 1 Bits(LeetCode) +sidebar_label: 0191-Number of 1 Bits +tags: + - Divide & Conquer + - Bit Manipulation +description: Write a function that takes the binary representation of a positive integer and returns the number of set bits it has (also known as the Hamming weight). +--- + +## Problem Statement + +Write a function that takes the binary representation of a positive integer and returns the number of set bits it has (also known as the Hamming weight). + +### Examples + +**Example 1:** + +```plaintext +Input: n = 11 +Output: 3 +Explanation: +The input binary string 1011 has a total of three set bits. +``` + +**Example 2:** + +```plaintext +Input: n = 128 +Output: 1 +Explanation: +The input binary string 10000000 has a total of one set bit. +``` + +**Example 3:** + +```plaintext +Input: n = 2147483645 +Output: 30 +Explanation: +The input binary string 1111111111111111111111111111101 has a total of thirty set bits. +``` + +### Constraints + +- `1 <= n <= 231 - 1` + +## Solution + +The Hamming weight (or population count) of a binary number is the number of '1' bits in its binary representation. This problem involves calculating the Hamming weight of an integer. The approach uses bitwise operations to efficiently count the number of '1' bits. + +### Approach + +#### Algorithm + +1. Initialization: +* Initialize a variable `ones` to 0. This will keep track of the number of '1' bits encountered. +2. Bitwise AND Operation: +* Perform a bitwise AND operation between the integer `n` and `1` (i.e., n & 1). +* If the result is 1, it means the least significant bit (LSB) of `n` is 1. Add this result to `ones`. +3. Bit Shift: +* Right shift the bits of n using an unsigned right shift operator (>>>) to check the next bit. +4. Loop Until Zero: +* Continue the above steps until n becomes 0. +5. Return Result: +* Return the value of ones which represents the Hamming weight of the integer. + +#### Implementation + +```Java +public static int hammingWeight(int n) { + int ones = 0; + while (n != 0) { + ones = ones + (n & 1); // Check if the LSB is 1 + n = n >>> 1; // Right shift by one bit (unsigned) + } + return ones; +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(1)$ +- **Space complexity**: $O(1)$ + +### Conclusion + +This approach efficiently calculates the Hamming weight of a 32-bit integer using bitwise operations. By using bitwise AND to check each bit and unsigned right shift to move to the next bit, we ensure a time complexity of `O(1)`, making it both fast and space-efficient. This method is particularly useful for low-level bit manipulation tasks and demonstrates a clear understanding of bitwise operations and their application in counting bits. diff --git a/solutions/lc-solutions/0100-0199/0192-word-frequency.md b/solutions/lc-solutions/0100-0199/0192-word-frequency.md new file mode 100644 index 0000000..1e044ea --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0192-word-frequency.md @@ -0,0 +1,76 @@ +--- +id: word-frequency +title: Word Frequency +sidebar_label: 0192 Word Frequency +tags: + - Leetcode + - Bash + +description: "This is a solution to the Word Frequency problem." +--- + +## Problem Description + +Write a bash script to calculate the frequency of each word in a text file words.txt. + +For simplicity sake, you may assume: + +words.txt contains only lowercase characters and space ' ' characters. +Each word must consist of lowercase characters only. +Words are separated by one or more whitespace characters. + +### Examples + +**Example 1:** + +``` +Assume that words.txt has the following content: + +the day is sunny the the +the sunny is is + +Your script should output the following, sorted by descending frequency: + +the 4 +is 3 +sunny 2 +day 1 + +``` + + +### Constraints + +- The input text file `words.txt` contains only lowercase characters and spaces. +- Words are separated by one or more whitespace characters. + +## Solution for Word Frequency Problem + +### Intuition And Approach + +To solve this problem using Unix tools, we can leverage a series of commands piped together to process the text file. The approach includes: + +1. Replacing spaces with newlines to handle word separation. +2. Sorting the words to prepare for counting duplicates. +3. Using `uniq` to count the occurrences of each word. +4. Sorting the counts in descending order. +5. Formatting the output to display word frequency. + +#### Code + + + + + ```bash +tr -s ' ' '\n' < words.txt | sort | uniq -c | sort -nr | awk '{print $2, $1}' + ``` + + + + + +## References + +- **LeetCode Problem:** [Word frequency Problem](https://leetcode.com/problems/word-frequency/) +- **Solution Link:** [Word-Frequency Solution on LeetCode](https://leetcode.com/problems/word-frequency/solutions/5273312/word-frequency-solution) +- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) diff --git a/solutions/lc-solutions/0100-0199/0193-valid-phone-numbers.md b/solutions/lc-solutions/0100-0199/0193-valid-phone-numbers.md new file mode 100644 index 0000000..96efc00 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0193-valid-phone-numbers.md @@ -0,0 +1,66 @@ +--- +id: valid-phone-numbers +title: Valid Phone Numbers +difficulty: Easy +sidebar_label: 0193-Valid-Phone-Numbers +tags: + - Shell + - LeetCode Easy +--- + +## Problem Description +Given a text file `file.txt` that contains a list of phone numbers (one per line), write a one-liner bash script to print all valid phone numbers. + +You may assume that a valid phone number must appear in one of the following two formats: +1. `(xxx) xxx-xxxx` +2. `xxx-xxx-xxxx` + +(Here `x` denotes a digit.) + +You may also assume each line in the text file is a single valid or invalid phone number that follows the above formats (no leading or trailing white spaces). + +### Example +**Example 1:** +```plaintext +Assume that `file.txt` has the following content: +987-123-4567 +123 456 7890 +(123) 456-7890 + +Your script should output the following valid phone numbers: +987-123-4567 +(123) 456-7890 +``` + +### Constraints +- The file `file.txt` will be at most $10^4$ lines. +- The phone numbers in the file are either valid or invalid according to the described formats. + +## Solution Approach + +### Approach Overview +We can use regular expressions with the `grep` command to filter out valid phone numbers from the file. + +### Detailed Steps + +1. **Use `grep` with Regular Expressions**: + - The `grep` command can be used to match lines in the file against the specified patterns. + - We need to use the `-E` option for extended regular expressions. + +2. **Regular Expression for Phone Numbers**: + - Use the pattern `^\(\d{3}\) \d{3}-\d{4}$` to match phone numbers in the format `(xxx) xxx-xxxx`. + - Use the pattern `^\d{3}-\d{3}-\d{4}$` to match phone numbers in the format `xxx-xxx-xxxx`. + +## Code Examples + +### Shell Script +```sh +# Using grep with extended regular expressions to match the two valid formats +grep -E '^\(\d{3}\) \d{3}-\d{4}$|^\d{3}-\d{3}-\d{4}$' file.txt +``` + +## Complexity + +- **Time Complexity**: $O(n)$, where $n$ is the number of lines in the file. The `grep` command processes each line in the file once. + +- **Space Complexity**: $O(1)$, as the space used by `grep` is constant and does not depend on the input size. diff --git a/solutions/lc-solutions/0100-0199/0194-transpose-file.md b/solutions/lc-solutions/0100-0199/0194-transpose-file.md new file mode 100644 index 0000000..5c5f158 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0194-transpose-file.md @@ -0,0 +1,73 @@ +--- +id: transpose-file +title: Transpose File +difficulty: Medium +sidebar_label: 0194-Transpose-File +tags: + - Shell + - LeetCode Medium +--- + +## Problem Description +Given a text file `file.txt`, transpose its content. + +You may assume that each row has the same number of columns and each field is separated by the `' '` character. + +### Example +**Example 1:** +```plaintext +Assume that `file.txt` has the following content: +name age +alice 21 +ryan 30 + +Your script should output the following transposed content: +name alice ryan +age 21 30 +``` + +### Constraints +- The file `file.txt` will be at most 10^3 lines. +- Each line in the file will have at most 10^3 characters. +- Each field in the file is separated by a single space character. + +## Solution Approach + +### Approach Overview +We can use a combination of `awk`, `paste`, and `cut` commands in a bash script to transpose the content of the file. + +### Detailed Steps + +1. **Read Each Line and Store Columns**: + - Use `awk` to read each line and store columns in arrays. + +2. **Print Transposed Content**: + - Loop through the columns and print them as rows. + +## Code Examples + +### Shell Script +```sh +awk ' +{ + for (i = 1; i <= NF; i++) { + if (NR == 1) { + s[i] = $i; + } else { + s[i] = s[i] " " $i; + } + } +} +END { + for (i = 1; i <= NF; i++) { + print s[i]; + } +} +' file.txt +``` + +## Complexity + +- **Time Complexity**: `O(n * m)`, where `n` is the number of rows and `m` is the number of columns. Each element is processed once. + +- **Space Complexity**: `O(n * m)`, as we store each element in memory to perform the transposition. diff --git a/solutions/lc-solutions/0100-0199/0195-tenth-line.md b/solutions/lc-solutions/0100-0199/0195-tenth-line.md new file mode 100644 index 0000000..b931f4f --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0195-tenth-line.md @@ -0,0 +1,89 @@ +--- +id: tenth-line +title: Tenth Line +difficulty: Easy +sidebar_label: 0195-Tenth-Line +tags: + - Shell + - LeetCode Easy +--- + +## Problem Description +Given a text file `file.txt`, print just the 10th line of the file. + +If the file has less than 10 lines, what should you output? There's no need to output anything (an empty output). + +### Example +**Example 1:** +```plaintext +Assume that `file.txt` has the following content: +Line 1 +Line 2 +Line 3 +Line 4 +Line 5 +Line 6 +Line 7 +Line 8 +Line 9 +Line 10 + +Your script should output the following: +Line 10 +``` + +**Example 2:** +```plaintext +Assume that `file.txt` has the following content: +Line 1 +Line 2 +Line 3 + +Your script should output nothing since there are less than 10 lines in the file. +``` + +### Constraints +- The file `file.txt` will have at most 10^3 lines. +- Each line in the file will have at most 10^3 characters. + +## Solution Approach + +### Approach Overview +There are multiple ways to achieve this using different shell commands. Here, we demonstrate solutions using `sed`, `awk`, and `tail` with `head`. + +### Detailed Steps + +1. **Using `sed`**: + - The `sed` command can directly print the 10th line. + +2. **Using `awk`**: + - The `awk` command can be used to check the line number and print the 10th line. + +3. **Using `tail` and `head`**: + - The `tail` command can be used to get the last lines starting from the 10th, and then `head` can get the first of those lines. + +## Code Examples + +### Shell Script Using `sed` +```sh +# Using sed to print the 10th line +sed -n '10p' file.txt +``` + +### Shell Script Using `awk` +```sh +# Using awk to print the 10th line +awk 'NR == 10' file.txt +``` + +### Shell Script Using `tail` and `head` +```sh +# Using tail and head to print the 10th line +tail -n +10 file.txt | head -n 1 +``` + +## Complexity + +- **Time Complexity**: `O(n)`, where `n` is the number of lines in the file. Each line is read once until the 10th line. + +- **Space Complexity**: `O(1)`, as no additional space is used beyond the required output. diff --git a/solutions/lc-solutions/0100-0199/0196-delete-duplicate-emails.md b/solutions/lc-solutions/0100-0199/0196-delete-duplicate-emails.md new file mode 100644 index 0000000..27b806a --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0196-delete-duplicate-emails.md @@ -0,0 +1,81 @@ +--- +id: delete-duplicate-emails +title: Delete Duplicate Emails +difficulty: Easy +sidebar_label: 0196-Delete-Duplicate-Emails +tags: + - SQL + - LeetCode Easy +--- + +## Problem Description +Write a SQL query to delete all the duplicate emails, keeping only one unique email with the smallest `id`. + +Assume the table `Person` has the following structure: +```plaintext ++----+------------------+ +| id | email | ++----+------------------+ +| 1 | john@example.com | +| 2 | bob@example.com | +| 3 | john@example.com | ++----+------------------+ +``` + +### Example +**Example 1:** +```plaintext +Assume that the `Person` table has the following content: ++----+------------------+ +| id | email | ++----+------------------+ +| 1 | john@example.com | +| 2 | bob@example.com | +| 3 | john@example.com | ++----+------------------+ + +Your query should delete the duplicate emails and the result table should look like: ++----+------------------+ +| id | email | ++----+------------------+ +| 1 | john@example.com | +| 2 | bob@example.com | ++----+------------------+ +``` + +### Constraints +- The `Person` table will have at most 10^4 rows. +- Each email in the `Person` table will have at most 100 characters. + +## Solution Approach + +### Approach Overview +To delete duplicate emails while keeping the record with the smallest `id`, we can use a subquery to identify the duplicates and then delete them based on their `id`. + +### Detailed Steps + +1. **Identify Duplicates**: + - Use a subquery to find the smallest `id` for each duplicate email. + +2. **Delete Duplicates**: + - Delete from the `Person` table where the `id` is not in the list of smallest `id`s for each email. + +## Code Examples + +### SQL Query +```sql +DELETE p1 FROM Person p1 +JOIN Person p2 +ON p1.email = p2.email +AND p1.id > p2.id; +``` + +### Explanation +- The `JOIN` operation matches each row in the `Person` table with every other row having the same email. +- The `DELETE` statement removes rows from the `Person` table where the `id` is greater than the smallest `id` for each email, effectively keeping only one unique email with the smallest `id`. + +## Complexity + +- **Time Complexity**: `O(n^2)` in the worst case, where `n` is the number of rows in the `Person` table, due to the `JOIN` operation. However, for practical purposes with indexing and optimizations, the performance may be better. + +- **Space Complexity**: `O(1)`, as no additional space is required beyond the query execution. diff --git a/solutions/lc-solutions/0100-0199/0197-rising-temperature.md b/solutions/lc-solutions/0100-0199/0197-rising-temperature.md new file mode 100644 index 0000000..31d4946 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0197-rising-temperature.md @@ -0,0 +1,83 @@ +--- +id: rising-temperature +title: Rising Temperature +difficulty: Easy +sidebar_label: 0197-Rising-Temperature +tags: + - SQL + - LeetCode Easy +--- + +## Problem Description +Given a `Weather` table, write a SQL query to find all dates' `Id` with higher temperatures compared to its previous dates (yesterday). + +Assume the table `Weather` has the following structure: +```plaintext ++---------+------------+------------------+ +| Id(INT) | RecordDate(DATE) | Temperature(INT) | ++---------+------------+------------------+ +| 1 | 2015-01-01 | 10 | +| 2 | 2015-01-02 | 25 | +| 3 | 2015-01-03 | 20 | +| 4 | 2015-01-04 | 30 | ++---------+------------+------------------+ +``` + +### Example +**Example 1:** +```plaintext +Assume that the `Weather` table has the following content: ++---------+------------+------------------+ +| Id(INT) | RecordDate(DATE) | Temperature(INT) | ++---------+------------+------------------+ +| 1 | 2015-01-01 | 10 | +| 2 | 2015-01-02 | 25 | +| 3 | 2015-01-03 | 20 | +| 4 | 2015-01-04 | 30 | ++---------+------------+------------------+ + +For the `Weather` table above, your query should return: ++----+ +| Id | ++----+ +| 2 | +| 4 | ++----+ +``` +### Constraints +- The `Weather` table will have at most 10^4 rows. +- The `RecordDate` values are unique. + +## Solution Approach + +### Approach Overview +To find all dates' `Id` with higher temperatures compared to its previous dates, we need to compare each row with the row corresponding to the previous date. + +### Detailed Steps + +1. **Join the Table with Itself**: + - Use a `JOIN` operation to join the `Weather` table with itself, where the `RecordDate` of the first instance is one day after the `RecordDate` of the second instance. + +2. **Filter Rows with Higher Temperature**: + - In the `WHERE` clause, compare the `Temperature` of the joined rows to ensure we only select rows where the current day's temperature is higher than the previous day's temperature. + +## Code Examples + +### SQL Query +```sql +SELECT w1.Id +FROM Weather w1 +JOIN Weather w2 +ON DATEDIFF(w1.RecordDate, w2.RecordDate) = 1 +WHERE w1.Temperature > w2.Temperature; +``` + +### Explanation +- `JOIN Weather w2 ON DATEDIFF(w1.RecordDate, w2.RecordDate) = 1`: This joins each row in the `Weather` table with the row from the previous day. +- `WHERE w1.Temperature > w2.Temperature`: This filters the rows to only include those where the temperature is higher than the previous day's temperature. + +## Complexity + +- **Time Complexity**: `O(n log n)` if indexed properly. The `JOIN` operation on dates can be efficient with indexing on `RecordDate`. + +- **Space Complexity**: `O(n)`, as we might need additional space for the result set depending on the number of rows that satisfy the condition. diff --git a/solutions/lc-solutions/0100-0199/0198-house-robber.md b/solutions/lc-solutions/0100-0199/0198-house-robber.md new file mode 100644 index 0000000..ba5347c --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0198-house-robber.md @@ -0,0 +1,176 @@ +--- +id: rotate-array +title: Rotate Array +sidebar_label: 0189 Rotate Array +tags: + - Array + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Rotate Array problem on LeetCode." +--- + +## Problem Description + +Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,3,4,5,6,7], k = 3 +Output: [5,6,7,1,2,3,4] +Explanation: +rotate 1 steps to the right: [7,1,2,3,4,5,6] +rotate 2 steps to the right: [6,7,1,2,3,4,5] +rotate 3 steps to the right: [5,6,7,1,2,3,4] + +``` + +**Example 2:** + +``` +Input: nums = [-1,-100,3,99], k = 2 +Output: [3,99,-1,-100] +Explanation: +rotate 1 steps to the right: [99,-1,-100,3] +rotate 2 steps to the right: [3,99,-1,-100] +``` + +### Constraints + +- $1 <= nums.length <= 105$ +- $-231 <= nums[i] <= 231 - 1$ +- $0 <= k <= 105$ + + +## Solution for Candy Distribution Problem + +### Intuition And Approach + +To rotate an array to the right by k steps, we need to move the last k elements to the front and shift the rest of the elements to the right. A straightforward way to achieve this in-place (without using extra space for another array) is to use the reversal method. + +Here is the step-by-step approach: + +## Adjust k: + +If k is greater than the length of the array, rotating by k steps is the same as rotating by k % n steps (where n is the length of the array). This is because rotating by the length of the array brings it back to the original position. +Calculate k = k % n. + +## Reverse the entire array: + +By reversing the entire array, the last k elements (which we want to move to the front) will be at the beginning, but in reverse order. +For example, reversing [1, 2, 3, 4, 5, 6, 7] gives [7, 6, 5, 4, 3, 2, 1]. + +## Reverse the first k elements: + +The first k elements are now the elements that were originally at the end of the array. Reverse these to restore their original order. +Continuing the example, reversing the first 3 elements of [7, 6, 5, 4, 3, 2, 1] gives [5, 6, 7, 4, 3, 2, 1]. + +## Reverse the remaining n - k elements: + +Finally, reverse the rest of the array (from the k-th element to the end) to restore their order. +In the example, reversing the elements from index 3 to 6 of [5, 6, 7, 4, 3, 2, 1] gives [5, 6, 7, 1, 2, 3, 4]. + + + +#### Code in Different Languages + + + + + ```java + + class Solution { + public void rotate(int[] nums, int k) { + // Ensure k is within the bounds of the array length + k = k % nums.length; + + // Reverse the entire array + reverse(nums, 0, nums.length - 1); + + // Reverse the first k elements + reverse(nums, 0, k - 1); + + // Reverse the remaining elements + reverse(nums, k, nums.length - 1); + } + + // Helper function to reverse elements in the array from start to end + private void reverse(int[] nums, int start, int end) { + while (start < end) { + int temp = nums[start]; + nums[start] = nums[end]; + nums[end] = temp; + start++; + end--; + } + } + + ``` + + + + ```python + + class Solution(object): + def rotate(self, nums, k): + k = k % len(nums) + self.reverse(nums, 0, len(nums) - 1) + self.reverse(nums, 0, k - 1) + self.reverse(nums, k, len(nums) - 1) + def reverse(self, nums, start, end): + while start < end: + nums[start], nums[end] = nums[end], nums[start] + start += 1 + end -= 1 + ``` + + + + + ```cpp + + #include + using namespace std; + + class Solution { + public: + void rotate(vector& nums, int k) { + // Ensure k is within the bounds of the array length + k = k % nums.size(); + + // Reverse the entire array + reverse(nums, 0, nums.size() - 1); + + // Reverse the first k elements + reverse(nums, 0, k - 1); + + // Reverse the remaining elements + reverse(nums, k, nums.size() - 1); + } + + private: + void reverse(vector& nums, int start, int end) { + while (start < end) { + int temp = nums[start]; + nums[start] = nums[end]; + nums[end] = temp; + start++; + end--; + } + } +}; + ``` + + + + + +## References + +- **LeetCode Problem:** [House robber Problem](https://leetcode.com/problems/house-robber/) +- **Solution Link:** [House Robber Solution on LeetCode](https://leetcode.com/problems/house-robber/solutions/5273312/house-robber-solution) +- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) diff --git a/solutions/lc-solutions/0100-0199/0199-Binary-Tree-Right-Side-View.md b/solutions/lc-solutions/0100-0199/0199-Binary-Tree-Right-Side-View.md new file mode 100644 index 0000000..28bd35d --- /dev/null +++ b/solutions/lc-solutions/0100-0199/0199-Binary-Tree-Right-Side-View.md @@ -0,0 +1,187 @@ +--- +id: binary-tree-right-side-view +title: Binary Tree Right Side View Solution +sidebar_label: 0199 Binary Tree Right Side View +tags: + - Binary Tree + - Depth-First Search + - Breadth-First Search + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Binary Tree Right Side View problem on LeetCode." +--- + +## Problem Description + +Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. + +### Examples + +**Example 1:** + +``` +Input: root = [1,2,3,null,5,null,4] +Output: [1,3,4] +``` + +**Example 2:** + +``` +Input: root = [1,null,3] +Output: [1,3] +``` + +**Example 3:** + +``` +Input: root = [] +Output: [] +``` + + +### Constraints + +- The number of nodes in the tree is in the range `[0, 100]`. +- $-100 <=$ Node.val $<= 100$ + +## Solution for Binary Tree Right Side View Problem + +### Intuition + +The intuition behind the solution is to perform a level-order traversal (BFS) of the binary tree and record the value of the last node at each level, which represents the view from the right side. + +### Approach + +1. Initialize an empty result list to store the right side view of the tree. +2. Perform a level-order traversal (BFS) of the tree. +3. At each level, record the value of the last node in the result list. +4. Return the result list. + +#### Code in Different Languages + + + + + ```python + + from collections import deque + class TreeNode(object): + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + class Solution(object): + def rightSideView(self, root): + result = [] + if not root: + return result + + queue = deque([root]) + + while queue: + level_length = len(queue) + for i in range(level_length): + node = queue.popleft() + if i == level_length - 1: + result.append(node.val) + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + + return result + ``` + + + + ```java + + import java.util.*; + + class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode() {} + TreeNode(int val) { this.val = val; } + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } + } + + class Solution { + public List rightSideView(TreeNode root) { + List result = new ArrayList<>(); + if (root == null) return result; + + Queue queue = new LinkedList<>(); + queue.add(root); + + while (!queue.isEmpty()) { + int size = queue.size(); + for (int i = 0; i < size; i++) { + TreeNode node = queue.poll(); + if (i == size - 1) result.add(node.val); + if (node.left != null) queue.add(node.left); + if (node.right != null) queue.add(node.right); + } + } + + return result; + + }} + ``` + + + + ```cpp + + #include + #include + #include + + using namespace std; + + class Solution { + public: + vector rightSideView(TreeNode* root) { + vector result; + if (!root) return result; + + queue q; + q.push(root); + + while (!q.empty()) { + int size = q.size(); + for (int i = 0; i < size; ++i) { + TreeNode* node = q.front(); + q.pop(); + if (i == size - 1) result.push_back(node->val); + if (node->left) q.push(node->left); + if (node->right) q.push(node->right); + } + } + + return result; + } + }; + ``` + + + + +### Complexity Analysis + +- **Time complexity**: The time complexity of the solution is $O(N)$, where N is the number of nodes in the binary tree. This is because we visit each node exactly once during the level-order traversal. +- **Space complexity**: The space complexity of the solution is $O(N)$, where N is the number of nodes in the binary tree. This is because the space used by the queue for level-order traversal can be at most N in the worst case. + +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/binary-tree-right-side-view/) +- **Solution Link:** [Binary Tree Right Side View Solution on LeetCode](https://leetcode.com/problems/binary-tree-right-side-view/solutions/) +- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) diff --git a/solutions/lc-solutions/0100-0199/183-Customers-Who-Never-Order.md b/solutions/lc-solutions/0100-0199/183-Customers-Who-Never-Order.md new file mode 100644 index 0000000..7f8ed7f --- /dev/null +++ b/solutions/lc-solutions/0100-0199/183-Customers-Who-Never-Order.md @@ -0,0 +1,96 @@ +--- +id: customers-who-never-order +title: Customers Who Never Order +sidebar_label: 0183. Customers Who Never Order +tags: +- SQL +- Database +description: "Solution to Leetcode 183. Customers Who Never Order" +--- + +## Problem Description + +Given two tables, `Customers` and `Orders`, write a query to find all customers who never ordered anything. + +**Table: Customers** + +| Column Name | Type | +| ----------- | ------- | +| id | int | +| name | varchar | +id is the primary key for this table. + +**Table: Orders** + +| Column Name | Type | +| ----------- | ---- | +| id | int | +| customerId | int | +id is the primary key for this table. `customerId` is a foreign key referencing the `id` column in the `Customers` table. + +### Examples + +**Example 1:** + +**Input:** + +**Customers table:** + +| id | name | +| --- | ----- | +| 1 | Joe | +| 2 | Henry | +| 3 | Sam | +| 4 | Max | + +**Orders table:** + +| id | customerId | +| --- | ---------- | +| 1 | 3 | +| 2 | 1 | + +**Output:** + +| Customers | +| --------- | +| Henry | +| Max | + +### Approach + +1. Perform a `LEFT JOIN` between the `Customers` table and the `Orders` table on the `id` and `customerId` columns. +2. Use the `WHERE` clause to filter out the customers who have `NULL` in the `Orders` table, which indicates that they never placed an order. + +### Solution + +#### SQL + +```sql +-- SQL solution to find customers who never order anything + +SELECT + name AS Customers +FROM + Customers +LEFT JOIN + Orders +ON + Customers.id = Orders.customerId +WHERE + Orders.customerId IS NULL; +``` + +### Explanation + +- **LEFT JOIN**: Joins the `Customers` table with the `Orders` table. This join includes all customers, even those who have not placed any orders. +- **WHERE Orders.customerId IS NULL**: Filters the result to include only those customers who do not have a corresponding entry in the `Orders` table. + +### Complexity Analysis + +- **Time Complexity**: O(n), where n is the number of rows in the `Customers` table. +- **Space Complexity**: O(n), where n is the number of rows in the `Customers` table. + +### References + +- **LeetCode Problem**: Customers Who Never Order \ No newline at end of file diff --git a/solutions/lc-solutions/0100-0199/_category_.json b/solutions/lc-solutions/0100-0199/_category_.json new file mode 100644 index 0000000..9c2ccc3 --- /dev/null +++ b/solutions/lc-solutions/0100-0199/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "0100-0199", + "position": 3, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (0100 - 0199)" + } +} diff --git a/solutions/lc-solutions/0200-0299/0200-number-of-islands.md b/solutions/lc-solutions/0200-0299/0200-number-of-islands.md new file mode 100644 index 0000000..c6baa27 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0200-number-of-islands.md @@ -0,0 +1,407 @@ +--- +id: number-of-islands +title: Number of Islands +sidebar_label: 0200 - Number of Islands +tags: + - Graph + - Depth-First-Search + - Breadth-First-Search + - C++ + - Java + - Python +description: "This is a solution to the Number of Island problem on LeetCode." +--- + +In this page, we will solve the Number of Islands problem using Two different approaches: Breadth First Search (BFS) and Depth First Search (DFS) technique. We will provide the implementation of the solution in C++, Python, Java. + +## Problem Description + +Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. + +An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. + +### Examples + +**Example 1:** + +```plaintext +Input: grid = [ + ["1","1","1","1","0"], + ["1","1","0","1","0"], + ["1","1","0","0","0"], + ["0","0","0","0","0"] +] +Output: 1 +``` + +**Example 2:** + +```plaintext +Input: grid = [ + ["1","1","0","0","0"], + ["1","1","0","0","0"], + ["0","0","1","0","0"], + ["0","0","0","1","1"] +] +Output: 3 +``` + +### Constraints + +- `m == grid.length` +- `n == grid[i].length` +- `1 <= m, n <= 300` +- `grid[i][j] is '0' or '1'.` + +--- + +## Solution for Number of Islands Problem + +### Intuition and Approach + +This solution employs a Breadth-First Search (BFS) and Depth First Search (DFS) approach to traverse the grid, identifying islands by exploring contiguous land cells Eight Directionally. It marks visited cells to avoid redundant exploration and counts the number of separate island formations encountered. + + + + +### Approach 1: Breadth First Search (BFS) + +The breadth-first search (BFS) algorithm to traverse through the grid and identify connected components, a count variable to keep track of the number of islands found after that we initializes a 2D vector called vis to mark visited cells in the grid. +For each unvisited cell (grid[row][col] == '1' and vis[row][col] == 0), it increments the count and invokes the bfs function to explore the island further. +Inside bfs, it marks the current cell as visited and pushes it onto a queue. It then enters a while loop where it queues cells from the queue and explores their neighboring cells. For each neighboring cell that meets the criteria of being within bounds, containing '1', and not visited yet, it marks it as visited and enqueues it for further exploration.The loop continues until the queue is empty, indicating that the entire island has been explored. +After exploring all cells in the grid, we returns the count of islands found. + +#### Codes in Different Languages + + + + + ```cpp + + class Solution { + public: + void bfs(int row, int col,int m, int n, vector>& grid,vector>& vis){ + + vis[row][col]=1; + + queue> q; + q.push({row,col}); + + while(!q.empty()){ + int row=q.front().first; + int col=q.front().second; + q.pop(); + + for(int deltarow=-1;deltarow<=1;deltarow++){ + for(int deltacol=-1;deltacol<=1;deltacol++){ + int nrow=row+deltarow; //neighbour_row + int ncol=col+deltacol; //neighbour_col + + if((abs(deltarow-deltacol)==1) && nrow>=0 && nrow=0 && ncol>& grid) { + int n=grid.size(); + int m=grid[0].size(); + int count=0; + + vector> vis(n,vector(m,0)); + + for(int row=0;row + + + ```python + + from collections import deque + + class Solution: + def bfs(self, row, col, m, n, grid, vis): + vis[row][col] = 1 + + q = deque([(row, col)]) + + while q: + row, col = q.popleft() + + for deltarow in range(-1, 2): + for deltacol in range(-1, 2): + nrow = row + deltarow # neighbour_row + ncol = col + deltacol # neighbour_col + + if (abs(deltarow - deltacol) == 1 and 0 <= nrow < n and 0 <= ncol < m and + grid[nrow][ncol] == '1' and vis[nrow][ncol] == 0): + vis[nrow][ncol] = 1 + q.append((nrow, ncol)) + + def numIslands(self, grid): + n = len(grid) + m = len(grid[0]) + count = 0 + + vis = [[0] * m for _ in range(n)] + + for row in range(n): + for col in range(m): + if not vis[row][col] and grid[row][col] == '1': + count += 1 + self.bfs(row, col, m, n, grid, vis) + + return count + ``` + + + + + ```java + + class pair + { + int row; + int col; + pair(int row,int col) + { + this.row=row; + this.col=col; + } + } + class Solution { + public boolean isValid(int i,int j,int m,int n) + { + return i>=0 && i=0 && j q=new LinkedList<>(); + int m=grid.length,n=grid[0].length; + q.offer(new pair(r,c)); + while(!q.isEmpty()) + { + pair top=q.poll(); + int row=top.row; + int col=top.col; + if(isValid(row-1,col,m,n)) + { + if(grid[row-1][col]=='1' &&!visited[row-1][col]) + { + visited[row-1][col]=true; + q.offer(new pair(row-1,col)); + } + } + if(isValid(row+1,col,m,n)) + { + if(grid[row+1][col]=='1' &&!visited[row+1][col]) + { + visited[row+1][col]=true; + q.offer(new pair(row+1,col)); + } + } + if(isValid(row,col-1,m,n)) + { + if(grid[row][col-1]=='1' &&!visited[row][col-1]) + { + visited[row][col-1]=true; + q.offer(new pair(row,col-1)); + } + } + if(isValid(row,col+1,m,n)) + { + if(grid[row][col+1]=='1' &&!visited[row][col+1]) + { + visited[row][col+1]=true; + q.offer(new pair(row,col+1)); + } + } + } + } + public int numIslands(char[][] grid) { + int i,j,m=grid.length,n=grid[0].length; + boolean visited[][]=new boolean[m][n]; + int count=0; + for(i=0;i + + +#### Complexity Analysis + +- Time Complexity: $$O(M*N)$$ +- Space Complexity: $$O(M*N)$$ +- Where `M` is the row of the grid. +- Where `N` is the col of the grid. + + + + +### Approach 2: Depth First Search (DFS) + +In Depth First Search (DFS) algorithm to find number of islands in a grid by initializes a 2D vector vis to keep track of visited cells. It iterates through each cell of the grid and if it's not visited and contains '1', it starts a dfs function call from that cell. During DFS, it marks visited cells and explores neighboring cells recursively. Each time a new island is found, the count is incremented. Finally, the method returns the count of islands in the grid. + +#### Code in Different Languages + + + + + + ```cpp + class Solution { + public: + void dfs(vector>& grid, vector>& vis, int row, int col, int m, int n){ + vis[row][col] = 1; + + int dr[4] = {+1,0,-1,0}; + int dc[4] = {0,+1,0,-1}; + + for(int i=0 ; i<4 ; i++){ + int nrow = row + dr[i]; + int ncol = col + dc[i]; + if(nrow>=0 && nrow=0 && ncol>& grid) { + + int m = grid.size(); + int n = grid[0].size(); + int cnt = 0; + vector> vis(m,vector(n,0)); + + for(int row=0 ; row + + + ```python + class Solution(object): + def dfs(self, grid, vis, row, col, m, n): + vis[row][col] = 1 + + dr = [+1, 0, -1, 0] + dc = [0, +1, 0, -1] + + for i in range(4): + nrow = row + dr[i] + ncol = col + dc[i] + if 0 <= nrow < m and 0 <= ncol < n and not vis[nrow][ncol] and grid[nrow][ncol] == '1': + self.dfs(grid, vis, nrow, ncol, m, n) + def numIslands(self, grid): + m = len(grid) + n = len(grid[0]) + cnt = 0 + vis = [[0] * n for _ in range(m)] + + for row in range(m): + for col in range(n): + if not vis[row][col] and grid[row][col] == '1': + self.dfs(grid, vis, row, col, m, n) + cnt += 1 + + return cnt + ``` + + + + + ```java + class Solution { + public void dfs(char[][] grid, int[][] vis, int row, int col, int m, int n) { + vis[row][col] = 1; + + int[] dr = {+1, 0, -1, 0}; + int[] dc = {0, +1, 0, -1}; + + for (int i = 0; i < 4; i++) { + int nrow = row + dr[i]; + int ncol = col + dc[i]; + if (nrow >= 0 && nrow < m && ncol >= 0 && ncol < n && vis[nrow][ncol] == 0 && grid[nrow][ncol] == '1') { + dfs(grid, vis, nrow, ncol, m, n); + } + } + } + + public int numIslands(char[][] grid) { + int m = grid.length; + int n = grid[0].length; + int cnt = 0; + int[][] vis = new int[m][n]; + + for (int row = 0; row < m; row++) { + for (int col = 0; col < n; col++) { + if (vis[row][col] == 0 && grid[row][col] == '1') { + dfs(grid, vis, row, col, m, n); + cnt++; + } + } + } + + return cnt; + } + } + ``` + + + + + + +#### Complexity Analysis + +- Time Complexity: $$O(M*N)$$ +- Space Complexity: $$O(M*N)$$ +- Where `M` is the row of the grid. +- Where `N` is the col of the grid. + + + + +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/number-of-islands/) +- **Solution Link:** [Number of Islands Solution on LeetCode](https://leetcode.com/problems/number-of-islands/submissions/1236284776/) diff --git a/solutions/lc-solutions/0200-0299/0201-bitwise-and-of-numbers-range.md b/solutions/lc-solutions/0200-0299/0201-bitwise-and-of-numbers-range.md new file mode 100644 index 0000000..605ffe6 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0201-bitwise-and-of-numbers-range.md @@ -0,0 +1,157 @@ +--- +id: bitwise-and-of-numbers-range +title: Bitwise AND of Numbers Range +sidebar_label: 201 Bitwise AND of Numbers Range +tags: +- Bit Manipulation +- C++ +- Python +- Java +description: "This document provides a solution where we return the bitwise AND of all numbers in a given range." +--- + +## Problem + +Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive. + +### Examples + +**Example 1:** + +``` +Input: left = 5, right = 7 + +Output: 4 + +``` +**Example 2:** +``` +Input: left = 0, right = 0 + +Output: 0 + +``` +**Example 3:** +``` +Input: left = 1, right = 2147483647 + +Output: 0 + +``` + +### Constraints + +- `0 <= left <= right <= 2^31 - 1` + +--- + +### Intuition +The problem is asking to find the bitwise AND of all numbers in a range. The first thing that comes to mind is that the bitwise AND of a number with a larger number will always be less than or equal to the number. This is because the AND operation can only unset bits, not set them. Therefore, the result will be the common prefix of the binary representations of the left and right numbers, with the rest of the bits set to zero. + +## Approach + +**Simple Bit Manipulation:** + +The approach is to right shift both the left and right numbers until they become equal. This is equivalent to finding the common prefix of their binary representations. The number of times we need to right shift is the number of trailing zeros in the result. Then we left shift the common prefix by this count to get the result. + +- Let's understand this with a simple example. Suppose we have `left =` 5 and `right = 7`. If we write these numbers in binary (the language computers understand), we get `101` for `5` and `111` for `7`. + +- Now, we need to find the bitwise AND of all numbers from `5` to `7`. In binary, that's like saying `101 AND 110 AND 111`. The result of this operation is `100`. + +- Our approach is to keep shifting both `5` and `7` to the right until they become the same number. This is like finding the common part of their binary representations. In our case, we shift `5` and `7` to the right once, and we get `2` and `3` respectively. They're not the same, so we shift again. Now we get `1` and `1`. They're the same, so we stop. We've shifted twice. + +- The number of times we shift is the number of zeros at the end of our result. In our case, the result `100` has two zeros at the end, which is the same as the number of times we shifted. + +- Finally, we shift our common number (`1`) to the left the same number of times we shifted right before. In our case, we shift `1` to the left twice and get `100`, which is our result. + + +#### Code in Java + + ```java +class Solution { + public int rangeBitwiseAnd(int left, int right) { + int cnt = 0; + while (left != right) { + left >>= 1; + right >>= 1; + cnt++; + } + return (left << cnt); + } +} + + public static void main(String[] args) { + Solution solution = new Solution(); + int left = 5; + int right = 7; + System.out.println("Bitwise AND of range [" + left + ", " + right + "] is " + solution.rangeBitwiseAnd(left, right)); + } +} + +``` + +#### Code in C++ + + ```cpp +#include +using namespace std; + +class Solution { +public: + int rangeBitwiseAnd(int left, int right) { + int count = 0; + + while (left != right) { + left >>= 1; + right >>= 1; + count++; + } + + return (left << count); + } +}; + +int main() { + Solution solution; + int left = 5; + int right = 7; + cout << "Bitwise AND of range [" << left << ", " << right << "] is " << solution.rangeBitwiseAnd(left, right) << endl; + return 0; +} +``` + +#### Code in Python + + ```py +class Solution: + def rangeBitwiseAnd(self, left: int, right: int) -> int: + cnt = 0 + while left != right: + left >>= 1 + right >>= 1 + cnt += 1 + return left << cnt + +if __name__ == "__main__": + solution = Solution() + left = 5 + right = 7 + print(f"Bitwise AND of range [{left}, {right}] is {solution.rangeBitwiseAnd(left, right)}") +``` + +### Complexity Analysis + +#### Time Complexity: $O(log n)$ + +> **Reason**: This is because in each iteration of the while loop, the numbers `left` and `right` are divided by `2` (right-shifted by 1 bit), which is equivalent to halving the numbers. Thus, the number of iterations required to make `left` equal to `right` is proportional to the number of bits in the binary representation of n, which is +$O(log n)$. + +#### Space Complexity: $O(1)$ + +> **Reason**: The space complexity is $O(1)$, because we only use a constant amount of extra space regardless of the input size. + +# References + +- **LeetCode Problem:** [Number of Digit One](https://leetcode.com/problems/bitwise-and-of-numbers-range/description/) +- **Solution Link:** [Number of Digit One Solution on LeetCode](https://leetcode.com/problems/bitwise-and-of-numbers-range/solutions/) +- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/sidkul712/) diff --git a/solutions/lc-solutions/0200-0299/0202-happy-number.md b/solutions/lc-solutions/0200-0299/0202-happy-number.md new file mode 100644 index 0000000..4c418fb --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0202-happy-number.md @@ -0,0 +1,337 @@ +--- +id: happy-number +title: Happy Number +sidebar_label: 202 Happy Number +tags: +- Hash Table +- Two Pointers +- C++ +- Python +- Java +description: "This document provides a solution for Happy Number problem on LeetCode." +--- + +## Problem + +Write an algorithm to determine if a number n is happy. + +A happy number is a number defined by the following process: + +- Starting with any positive integer, replace the number by the sum of the squares of its digits. +- Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. +- Those numbers for which this process ends in 1 are happy. + +Return true if n is a happy number, and false if not. + +### Examples + +**Example 1:** + +``` +Input: n = 19 + +Output: true + +``` +**Example 2:** +``` +Input: n = 2 + +Output: false + +``` + +### Constraints + +- `1 <= n <= 2^31 - 1` + +--- + +### Intuition +A happy number is defined as a number that, when repeatedly replaced by the sum of the squares of its digits, eventually reaches 1. If the process never reaches 1 and enters into a cycle, then the number is not a happy number. + +## Approach + +**1. Hash Map:** + +This approach uses a hash map to keep track of numbers encountered during the process of computing the "next" number. If a number is encountered again, it indicates a cycle, and the function returns false. If the number 1 is encountered, the function returns true. + +- Define a function next(num) to compute the next number based on the rules specified in the problem. + +- Start with the given number n and repeatedly compute the next number until either 1 is encountered (indicating happiness) or a cycle is detected. + +- Use a hash map to keep track of encountered numbers to detect cycles. + + +#### Code in Java + + ```java +import java.util.HashSet; +import java.util.Scanner; + +class Solution { + private int next(int num) { + int n = 0; + while (num > 0) { + int r = num % 10; + n += (r * r); + num /= 10; + } + return n; + } + + public boolean isHappy(int n) { + HashSet set = new HashSet<>(); + while (n != 1 && !set.contains(n)) { + set.add(n); + n = next(n); + } + return n == 1; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + Scanner scanner = new Scanner(System.in); + System.out.print("Enter a number: "); + int n = scanner.nextInt(); + if (solution.isHappy(n)) { + System.out.println(n + " is a happy number."); + } else { + System.out.println(n + " is not a happy number."); + } + scanner.close(); + } +} + +``` + +#### Code in C++ + + ```cpp +#include +#include + +class Solution { +private: + int next(int num){ + int n = 0; + while(num){ + int r = num % 10; + n += (r * r); + num /= 10; + } + return n; + } +public: + bool isHappy(int n) { + int num = n; + std::unordered_map mp; + do { + num = next(num); + if(num == 1) return true; + if(mp.find(num) != mp.end()) return false; + else mp[num] = 1; + } while(num != n); + return false; + } +}; + +int main() { + Solution solution; + int n; + std::cout << "Enter a number: "; + std::cin >> n; + if(solution.isHappy(n)) { + std::cout << n << " is a happy number." << std::endl; + } else { + std::cout << n << " is not a happy number." << std::endl; + } + return 0; +} + +``` + +#### Code in Python + + ```py +class Solution: + def next(self, num): + n = 0 + while num > 0: + r = num % 10 + n += (r * r) + num //= 10 + return n + + def isHappy(self, n: int) -> bool: + visited = set() + while n != 1 and n not in visited: + visited.add(n) + n = self.next(n) + return n == 1 + +if __name__ == "__main__": + solution = Solution() + n = int(input("Enter a number: ")) + if solution.isHappy(n): + print(f"{n} is a happy number.") + else: + print(f"{n} is not a happy number.") + +``` + +### Complexity Analysis + +#### Time Complexity: $O(log n)$ + +> **Reason**: The primary operation is the sum of the squares of the digits of the number, which involves iterating over the digits. The number of digits in `n` is proportional to log base 10 of `n` i.e., $O(log n)$. Typically, the process of finding whether a number is happy converges quickly to either 1 (happy) or a cycle (not happy).. + +#### Space Complexity: $O(log n)$ + +> **Reason**: The main space requirement is for storing previously seen numbers to detect cycles. The number of unique sums that can be encountered before either converging to 1 or entering a cycle is limited, and in practice, it's bound by a constant. However, in the worst case, the storage grows logarithmically with the size of `n`. + +**2. Two Pointers:** + +This approach uses Floyd's cycle detection algorithm, also known as the "tortoise and hare" algorithm. It employs two pointers, one slow and one fast, to detect cycles in the sequence of numbers. + +- Define a function next(num) to compute the next number based on the rules specified in the problem. +- Use two pointers, slow and fast, initialized to the given number n. +- Advance slow by one step and fast by two steps at each iteration. + - If a cycle is detected (i.e., slow equals fast), exit the loop. + - If slow eventually reaches 1, return true; otherwise, return false. + + +#### Code in Java + + ```java + +import java.util.Scanner; + +class Solution { + private int next(int num) { + int n = 0; + while (num > 0) { + int r = num % 10; + n += (r * r); + num /= 10; + } + return n; + } + + public boolean isHappy(int n) { + int slow = n, fast = n; + do { + slow = next(slow); + fast = next(next(fast)); + } while (slow != fast); + return slow == 1; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + Scanner scanner = new Scanner(System.in); + System.out.print("Enter a number: "); + int n = scanner.nextInt(); + if (solution.isHappy(n)) { + System.out.println(n + " is a happy number."); + } else { + System.out.println(n + " is not a happy number."); + } + scanner.close(); + } +} + + +``` + +#### Code in C++ + + ```cpp +#include + +class Solution { +private: + int next(int num) { + int n = 0; + while (num) { + int r = num % 10; + n += (r * r); + num /= 10; + } + return n; + } +public: + bool isHappy(int n) { + int slow = n, fast = n; + do { + slow = next(slow); + fast = next(next(fast)); + } while (slow != fast); + return slow == 1; + } +}; + +int main() { + Solution solution; + int n; + std::cout << "Enter a number: "; + std::cin >> n; + if (solution.isHappy(n)) { + std::cout << n << " is a happy number." << std::endl; + } else { + std::cout << n << " is not a happy number." << std::endl; + } + return 0; +} + +``` + +#### Code in Python + + ```py +class Solution: + def next(self, num): + n = 0 + while num > 0: + r = num % 10 + n += (r * r) + num //= 10 + return n + + def isHappy(self, n: int) -> bool: + slow = n + fast = n + while True: + slow = self.next(slow) + fast = self.next(self.next(fast)) + if slow == fast: + break + return slow == 1 + +if __name__ == "__main__": + solution = Solution() + n = int(input("Enter a number: ")) + if solution.isHappy(n): + print(f"{n} is a happy number.") + else: + print(f"{n} is not a happy number.") + + +``` + +### Complexity Analysis + +#### Time Complexity: $O(log n)$ + +> **Reason**: The algorithm uses Floyd's cycle detection (tortoise and hare) which typically converges or detects a cycle quickly, resulting in O(log n) overall time complexity. + +#### Space Complexity: $O(1)$ + +> **Reason**: The space complexity is constant, $O(1)$, since the algorithm only uses a few integer variables (slow, fast) for cycle detection and does not require any additional data structures like a hash set or hash map to store intermediate results. + + +# References + +- **LeetCode Problem:** [Number of Digit One](https://leetcode.com/problems/happy-number/description/) +- **Solution Link:** [Number of Digit One Solution on LeetCode](https://leetcode.com/problems/happy-number/solutions/) +- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/sidkul712/) diff --git a/solutions/lc-solutions/0200-0299/0203-Remove-Linked-List-Elements.md b/solutions/lc-solutions/0200-0299/0203-Remove-Linked-List-Elements.md new file mode 100644 index 0000000..65697bf --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0203-Remove-Linked-List-Elements.md @@ -0,0 +1,176 @@ +--- +id: remove-linked-list-elements +title: Remove Linked List Elements +sidebar_label: 203-Remove-Linked-List-Elements +tags: +- Linked List +- Java +- C++ +- Python +- Data Structures +description: "This document provides solutions for removing all nodes from a linked list that have a specific value." +--- + +## Problem + +Given the head of a linked list and an integer `val`, remove all the nodes of the linked list that have `Node.val == val`, and return the new head. + +### Examples + +**Example 1:** + +**Input:** head = [1,2,6,3,4,5,6], val = 6 + +**Output:** [1,2,3,4,5] + +**Example 2:** + +**Input:** head = [], val = 1 + +**Output:** [] + +**Example 3:** + +**Input:** head = [7,7,7,7], val = 7 + +**Output:** [] + +### Constraints + +- The number of nodes in the list is in the range `[0, 10^4]`. +- `1 <= Node.val <= 50` +- `0 <= val <= 50` + +--- + +## Approach + +The approach involves iterating through the linked list and removing nodes that have the specified value. This can be achieved using a dummy node to handle edge cases where the head itself needs to be removed. + +### Steps: + +1. **Dummy Node:** + - Create a dummy node that points to the head of the list. This helps to easily handle the case where the head node itself needs to be removed. + +2. **Iterate and Remove:** + - Use a pointer to iterate through the list, checking each node's value. + - If a node's value equals `val`, adjust the pointers to bypass this node. + +3. **Return New Head:** + - Return the next node of the dummy node as the new head of the list. + +## Solution for Remove Linked List Elements + +### Java Solution + +```java +class ListNode { + int val; + ListNode next; + ListNode() {} + ListNode(int val) { this.val = val; } + ListNode(int val, ListNode next) { this.val = val; this.next = next; } +} + +class Solution { + public ListNode removeElements(ListNode head, int val) { + // Create a dummy node to handle edge cases + ListNode dummy = new ListNode(0); + dummy.next = head; + + // Use a pointer to iterate through the list + ListNode current = dummy; + + while (current.next != null) { + if (current.next.val == val) { + // Bypass the node with the value equal to val + current.next = current.next.next; + } else { + // Move to the next node + current = current.next; + } + } + + // Return the new head + return dummy.next; + } +} +``` +### C++ solution + +```cpp +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* removeElements(ListNode* head, int val) { + // Create a dummy node to handle edge cases + ListNode* dummy = new ListNode(0); + dummy->next = head; + + // Use a pointer to iterate through the list + ListNode* current = dummy; + + while (current->next != nullptr) { + if (current->next->val == val) { + // Bypass the node with the value equal to val + current->next = current->next->next; + } else { + // Move to the next node + current = current->next; + } + } + + // Return the new head + return dummy->next; + } +}; +``` +### Python Solution + +```python +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +class Solution: + def removeElements(self, head: ListNode, val: int) -> ListNode: + # Create a dummy node to handle edge cases + dummy = ListNode(0) + dummy.next = head + + # Use a pointer to iterate through the list + current = dummy + + while current.next is not None: + if current.next.val == val: + # Bypass the node with the value equal to val + current.next = current.next.next + else: + # Move to the next node + current = current.next + + # Return the new head + return dummy.next +``` +### Complexity Analysis +**Time Complexity:** O(n) + +>Reason: The algorithm involves a single pass through the linked list, resulting in a time complexity of $O(n)$, where $n$ is the number of nodes in the list. + +**Space Complexity:** O(1) +>Reason: The space complexity is $O(1)$ because the algorithm uses a constant amount of extra space. + +### References +**LeetCode Problem:** Remove Linked List Elements + +**Solution Link:** Remove Linked List Elements Solution on LeetCode + + diff --git a/solutions/lc-solutions/0200-0299/0204-count-primes.md b/solutions/lc-solutions/0200-0299/0204-count-primes.md new file mode 100644 index 0000000..d93954d --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0204-count-primes.md @@ -0,0 +1,284 @@ +--- +id: count-primes +title: Count Primes +sidebar_label: 0204 - Count Primes +tags: +- Array +- Math +- Enumeration +- Number Theory + +description: "This is a solution to the Count Primes problem on LeetCode." +--- + +## Problem Description +Given an integer n, return the number of prime numbers that are strictly less than n. + +### Examples + +**Example 1:** +``` +Input: n = 10 +Output: 4 +Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. + +``` +**Example 2:** +``` +Input: n = 0 +Output: 0 +``` +**Example 3:** +``` +Input: n = 1 +Output: 0 +``` + +### Constraints +- `0 <= n <= 5 * 10^6` + +## Solution for Count Primes Problem + +### Brute Force +- Iterate through all numbers from 2 up to n-1 (since we need to find primes less than n). +- For each number, check if it is a prime by counting its divisors. + + + + +#### Implementation + +```jsx live +function primeCounter(n) { + function isPrime(n) { + let count = 0; + if (n === 1) { + return false; + } + for (let i = 1; i < n; i++) { + if (n % i === 0) { + count++; + } + } + if (count > 1) { + return false; + } + return true; + } + + function countPrimes(n) { + let count = 0; + for (let i = 2; i < n; i++) { + if (isPrime(i)) { + count++; + } + } + return count; + } + + const input = 10 + const output = countPrimes(input) + return ( +
+

+ Input: { JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); +} +``` +#### Complexity Analysis + +- Time Complexity: $ O(n^2) $ is the time complexity, because two nested loops are used , one is from 2 to n and second is used to check whether a number is prime or not which also takes $ O(n)$ complexity +- Space Complexity: $ O(1) $ + + +### Optimized Approach - Sieve of Eratosthenes Algorithm +#### Intuition +The Sieve of Eratosthenes is an efficient algorithm to find all prime numbers up to a given limit n. The basic idea is to iteratively mark the multiples of each prime starting from 2. By the end of the algorithm, the numbers that remain unmarked are prime. + +#### Steps +- Create a list of boolean values: Initialize an array is_prime of size n with all values set to true. is_prime[i] will be true if i is a prime number, false otherwise. +- Mark non-primes: Starting from the first prime number (2), mark all its multiples as non-prime. Move to the next number and repeat until you've processed numbers up to the square root of n. +- Count primes: The numbers which remain marked as true in the is_prime array are primes. + +#### Code in Different Languages + + + + + ```javascript + function countPrimes(n) { + if (n <= 2) return 0; + + // Step 1: Initialize the array with true values + let is_prime = new Array(n).fill(true); + is_prime[0] = is_prime[1] = false; // 0 and 1 are not primes + + // Step 2: Mark non-primes + for (let i = 2; i * i < n; i++) { + if (is_prime[i]) { + for (let j = i * i; j < n; j += i) { + is_prime[j] = false; + } + } + } + + // Step 3: Count primes + let count = 0; + for (let i = 2; i < n; i++) { + if (is_prime[i]) { + count++; + } + } + return count; + } + + + ``` + + + + + ```typescript + function countPrimes(n: number): number { + if (n <= 2) return 0; + + // Step 1: Initialize the array with true values + const isPrime: boolean[] = new Array(n).fill(true); + isPrime[0] = isPrime[1] = false; // 0 and 1 are not primes + + // Step 2: Mark non-primes + for (let i = 2; i * i < n; ++i) { + if (isPrime[i]) { + for (let j = i * i; j < n; j += i) { + isPrime[j] = false; + } + } + } + + // Step 3: Count primes + let count = 0; + for (let i = 2; i < n; ++i) { + if (isPrime[i]) { + ++count; + } + } + return count; +} + ``` + + + + + ```python + def count_primes(n: int) -> int: + if n <= 2: + return 0 + + # Step 1: Initialize the array with True values + is_prime = [True] * n + is_prime[0] = is_prime[1] = False # 0 and 1 are not primes + + # Step 2: Mark non-primes + for i in range(2, int(n ** 0.5) + 1): + if is_prime[i]: + for j in range(i * i, n, i): + is_prime[j] = False + + # Step 3: Count primes + count = sum(is_prime[2:]) + return count + + ``` + + + + +``` +public class Solution { + public int countPrimes(int n) { + if (n <= 2) return 0; + + // Step 1: Initialize the array with true values + boolean[] isPrime = new boolean[n]; + for (int i = 2; i < n; i++) { + isPrime[i] = true; + } + + // Step 2: Mark non-primes + for (int i = 2; i * i < n; i++) { + if (isPrime[i]) { + for (int j = i * i; j < n; j += i) { + isPrime[j] = false; + } + } + } + + // Step 3: Count primes + int count = 0; + for (int i = 2; i < n; i++) { + if (isPrime[i]) { + count++; + } + } + return count; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.countPrimes(10)); // Output: 4 (primes are 2, 3, 5, 7) + } +} + +``` + + + + + ```cpp + int countPrimes(int n) { + if (n <= 2) return 0; + + // Step 1: Initialize the array with true values + vector is_prime(n, true); + is_prime[0] = is_prime[1] = false; // 0 and 1 are not primes + + // Step 2: Mark non-primes + for (int i = 2; i * i < n; ++i) { + if (is_prime[i]) { + for (int j = i * i; j < n; j += i) { + is_prime[j] = false; + } + } + } + + // Step 3: Count primes + int count = 0; + for (int i = 2; i < n; ++i) { + if (is_prime[i]) { + ++count; + } + } + return count; + } + ``` + + + + +#### Complexity Analysis +- Time Complexity: $ O(N*log(logn))$ + - Space Complexity: $ O(N)$ +
+
+ +## References + +- **LeetCode Problem**: [Count Primes](https://leetcode.com/problems/count-primes/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/count-primes/solutions) + diff --git a/solutions/lc-solutions/0200-0299/0205-isomorphic-strings.md b/solutions/lc-solutions/0200-0299/0205-isomorphic-strings.md new file mode 100644 index 0000000..491f127 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0205-isomorphic-strings.md @@ -0,0 +1,174 @@ +--- +id: isomorphic-strings +title: Isomorphic Strings +sidebar_label: 205-Isomorphic-Strings +tags: +- Hash Table +- String +- Java +- C++ +- Python +description: "This document provides solutions for determining if two strings are isomorphic." +--- + +## Problem + +Given two strings `s` and `t`, determine if they are isomorphic. + +Two strings `s` and `t` are isomorphic if the characters in `s` can be replaced to get `t`. + +All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. + +### Examples + +**Example 1:** + +**Input:** s = "egg", t = "add" + +**Output:** true + +**Example 2:** + +**Input:** s = "foo", t = "bar" + +**Output:** false + +**Example 3:** + +**Input:** s = "paper", t = "title" + +**Output:** true + +### Constraints + +- `1 <= s.length <= 5 * 10^4` +- `t.length == s.length` +- `s` and `t` consist of any valid ASCII characters. + +--- + +## Approach + +The problem can be solved by using two hash maps to track the mappings from characters in `s` to `t` and vice versa. If the mappings are consistent throughout the strings, then the strings are isomorphic. + +### Steps: + +1. **Initialization:** + - Create two hash maps to store the character mappings from `s` to `t` and from `t` to `s`. + +2. **Iterate and Map:** + - Iterate through the characters of both strings simultaneously. + - For each character pair, check if the current mapping exists and is consistent with the previous mappings. + - If any inconsistency is found, return false. + +3. **Return Result:** + - If the iteration completes without finding any inconsistency, return true. + +## Solution for Isomorphic Strings + +### Java Solution + +```java +import java.util.HashMap; +import java.util.Map; + +class Solution { + public boolean isIsomorphic(String s, String t) { + if (s.length() != t.length()) return false; + + Map mapS = new HashMap<>(); + Map mapT = new HashMap<>(); + + for (int i = 0; i < s.length(); i++) { + char c1 = s.charAt(i); + char c2 = t.charAt(i); + + if (mapS.containsKey(c1)) { + if (mapS.get(c1) != c2) return false; + } else { + mapS.put(c1, c2); + } + + if (mapT.containsKey(c2)) { + if (mapT.get(c2) != c1) return false; + } else { + mapT.put(c2, c1); + } + } + + return true; + } +} +``` +### C++ Solution + +```cpp +#include +#include + +class Solution { +public: + bool isIsomorphic(std::string s, std::string t) { + if (s.length() != t.length()) return false; + + std::unordered_map mapS; + std::unordered_map mapT; + + for (int i = 0; i < s.length(); i++) { + char c1 = s[i]; + char c2 = t[i]; + + if (mapS.count(c1)) { + if (mapS[c1] != c2) return false; + } else { + mapS[c1] = c2; + } + + if (mapT.count(c2)) { + if (mapT[c2] != c1) return false; + } else { + mapT[c2] = c1; + } + } + + return true; + } +}; +``` +### Python Solution + +```python +class Solution: + def isIsomorphic(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + + mapS = {} + mapT = {} + + for c1, c2 in zip(s, t): + if c1 in mapS: + if mapS[c1] != c2: + return False + else: + mapS[c1] = c2 + + if c2 in mapT: + if mapT[c2] != c1: + return False + else: + mapT[c2] = c1 + + return True +``` +### Complexity Analysis +**Time Complexity:** O(n) +> Reason: The algorithm involves a single pass through both strings, resulting in a time complexity of $O(n)$, where $n$ is the length of the strings. + +**Space Complexity:** O(n) +>Reason: The space complexity is $O(n)$ due to the additional hash maps used to store the character mappings. + +### References +**LeetCode Problem:** Isomorphic Strings + +**Solution Link:** Isomorphic Strings Solution on LeetCode \ No newline at end of file diff --git a/solutions/lc-solutions/0200-0299/0206-Reverse-Linkedlist.md b/solutions/lc-solutions/0200-0299/0206-Reverse-Linkedlist.md new file mode 100644 index 0000000..944446a --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0206-Reverse-Linkedlist.md @@ -0,0 +1,302 @@ +--- +id: Reverse-LinkedList +title: Reverse LinkedList +sidebar_label: 206-Reverse-LinkedList +tags: + - Linkedlist + - Recursion + - Java + - C++ + - Python +description: "This document provides solutions for determining the Reverse Linkedlist." +--- + +## Problem Statement + +Given the head of a singly linked list, reverse the list, and return the reversed list. + +Example 1: + + ![alt text](image.png) + + Input: head = [1,2,3,4,5] + Output: [5,4,3,2,1] + +Example 2: + + ![alt text](image-1.png) + + Input: head = [1,2] + Output: [2,1] + +Example 3: +Input: head = [] +Output: [] + +### Solutions + +#### Intuition : + +The problem is asking to reverse a singly-linked list. One common approach to reverse a linked list is to use recursion. The idea is to reverse the rest of the list and then move the current node to the end. The base case of the recursion is when the current node is null, in which case the head of the reversed list is set to the previous node. + +#### Approach : + +1. The solve function is a recursive function that reverses the linked list. It takes three parameters: head (a reference to the head of the reversed list), prev (the previous node in the reversed list), and curr (the current node in the original list). + +2. If curr is null, it means we have reached the end of the original list. In this case, we set the head to prev, effectively updating the head of the reversed list, and return. + +3. Otherwise, we store the next node in a variable (nextNode) to prevent losing the reference to the rest of the list. + +4. We make a recursive call to solve with updated parameters: head remains the same, curr becomes the next node (nextNode), and prev becomes the current node (curr). + +5. After the recursive call, we update the next pointer of the current node (curr->next) to point to the previous node (prev), effectively reversing the link. + +6. The reverseList function is a wrapper function that checks if the list is empty or has only one element. If so, it returns the head unchanged. Otherwise, it calls the solve function to reverse the list and returns the updated head. + + + + + ```cpp + #include + + // Definition for singly-linked list. + struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} + }; + + class Solution { + public: + void solve(ListNode* &head, ListNode* prev, ListNode* curr) { + if (curr == nullptr) { + head = prev; + return; + } + ListNode* nextNode = curr->next; + solve(head, curr, nextNode); + curr->next = prev; + } + + ListNode* reverseList(ListNode* head) { + if (head == nullptr || head->next == nullptr) { + return head; + } + solve(head, nullptr, head); + return head; + } + }; + + // Helper function to print the linked list + void printList(ListNode* node) { + while (node != nullptr) { + std::cout << node->val << " "; + node = node->next; + } + } + + // Driver code + int main() { + Solution solution; + ListNode* head = new ListNode(1); + head->next = new ListNode(2); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(4); + head->next->next->next->next = new ListNode(5); + + std::cout << "Original list: "; + printList(head); + + head = solution.reverseList(head); + + std::cout << "\nReversed list: "; + printList(head); + + return 0; + } + ``` + + + + ```java + // Definition for singly-linked list. + class ListNode { + int val; + ListNode next; + ListNode() {} + ListNode(int val) { this.val = val; } + ListNode(int val, ListNode next) { this.val = val; this.next = next; } + } + + public class Solution { + public void solve(ListNode head, ListNode prev, ListNode curr) { + if (curr == null) { + head = prev; + return; + } + ListNode nextNode = curr.next; + solve(head, curr, nextNode); + curr.next = prev; + } + + public ListNode reverseList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + solve(head, null, head); + return head; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + ListNode head = new ListNode(1); + head.next = new ListNode(2); + head.next.next = new ListNode(3); + head.next.next.next = new ListNode(4); + head.next.next.next.next = new ListNode(5); + + System.out.print("Original list: "); + printList(head); + + head = solution.reverseList(head); + + System.out.print("\nReversed list: "); + printList(head); + } + + // Helper function to print the linked list + public static void printList(ListNode node) { + while (node != null) { + System.out.print(node.val + " "); + node = node.next; + } + } + } + ``` + + + + ```python + # Definition for singly-linked list. + class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + class Solution: + def solve(self, head: 'ListNode', prev: 'ListNode', curr: 'ListNode') -> None: + if curr is None: + head[0] = prev + return + nextNode = curr.next + self.solve(head, curr, nextNode) + curr.next = prev + + def reverseList(self, head: 'ListNode') -> 'ListNode': + if head is None or head.next is None: + return head + head_ref = [head] + self.solve(head_ref, None, head) + return head_ref[0] + + # Helper function to print the linked list + def printList(node): + while node: + print(node.val, end=" ") + node = node.next + + # Driver code + if __name__ == "__main__": + solution = Solution() + head = ListNode(1) + head.next = ListNode(2) + head.next.next = ListNode(3) + head.next.next.next = ListNode(4) + head.next.next.next.next = ListNode(5) + + print("Original list: ", end="") + printList(head) + + head = solution.reverseList(head) + + print("\nReversed list: ", end="") + printList(head) + ``` + + + + ```c + #include + #include + + // Definition for singly-linked list. + struct ListNode { + int val; + struct ListNode *next; + }; + + void solve(struct ListNode** head, struct ListNode* prev, struct ListNode* curr) { + if (curr == NULL) { + *head = prev; + return; + } + struct ListNode* nextNode = curr->next; + solve(head, curr, nextNode); + curr->next = prev; + } + + struct ListNode* reverseList(struct ListNode* head) { + if (head == NULL || head->next == NULL) { + return head; + } + solve(&head, NULL, head); + return head; + } + + // Helper function to print the linked list + void printList(struct ListNode* node) { + while (node != NULL) { + printf("%d ", node->val); + node = node->next; + } + } + + // Driver code + int main() { + struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode)); + head->val = 1; + head->next = (struct ListNode*)malloc(sizeof(struct ListNode)); + head->next->val = 2; + head->next->next = (struct ListNode*)malloc(sizeof(struct ListNode)); + head->next->next->val = 3; + head->next->next->next = (struct ListNode*)malloc(sizeof(struct ListNode)); + head->next->next->next->val = 4; + head->next->next->next->next = (struct ListNode*)malloc(sizeof(struct ListNode)); + head->next->next->next->next->val = 5; + head->next->next->next->next->next = NULL; + + printf("Original list: "); + printList(head); + + head = reverseList(head); + + printf("\nReversed list: "); + printList(head); + + return 0; + } + ``` + + + + +## Video lecture + + diff --git a/solutions/lc-solutions/0200-0299/0207-course-schedule.md b/solutions/lc-solutions/0200-0299/0207-course-schedule.md new file mode 100644 index 0000000..1f86e12 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0207-course-schedule.md @@ -0,0 +1,224 @@ +--- +id: course-schedule +title: Course Schedule +sidebar_label: 0207 Course Schedule +tags: +- Depth-First Search +- Topological Sort +- Graph +- Breadth-First Search +- Recursion +description: "This document provides a solution to the Course Schedule problem." +--- + +## Problem +You are given a total of numCourses courses labeled from 0 to numCourses - 1. You are also given an array prerequisites where $\text{prerequisites[i]} = [ a^i , b^i ]$ indicates that you must take course $b^i$ first if you want to take course $a^i$ . + +For example, the pair [0, 1] indicates that to take course 0 you have to first take course 1. +Return `true` if you can finish all courses. Otherwise, return `false`. + +### Example 1: + +``` +Input: numCourses = 2, prerequisites = [[1,0]] +Output: true +Explanation: There are a total of 2 courses to take. +To take course 1 you should have finished course 0. So it is possible. +``` + +### Example 2: + +``` +Input: numCourses = 2, prerequisites = [[1,0],[0,1]] +Output: false +Explanation: There are a total of 2 courses to take. +To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. +``` + +### Constraints: +- `1 <= numCourses <= 2000` +- `0 <= prerequisites.length <= 5000` +- `prerequisites[i].length == 2` +- `0 <= ai, bi < numCourses ` +- All the pairs prerequisites[i] are **unique**. +## Solution +The code aims to solve the problem of determining whether it is possible to finish all the given courses without any cyclic dependencies. It uses the topological sort algorithm, specifically Kahn's algorithm, to solve this problem. + +1. **Initialization**: + - Create an empty adjacency list to represent the directed graph. Each node in the graph represents a course, and the edges represent the prerequisites. + - Create an array called `indegree` of size `numCourses` and initialize all its elements to 0. The `indegree` array will keep track of the number of incoming edges to each course. + - Create an empty vector `ans` to store the topological order of the courses. + +2. **Building the Graph**: + - Iterate over the `prerequisites` array, which contains pairs of courses indicating the prerequisites. + - For each pair `[a, b]`, add an edge in the adjacency list from `b` to `a`. This indicates that course `b` must be completed before course `a`. + - Increment the indegree of course `a` by 1, as it has one more prerequisite. + +3. **Performing Topological Sort using Kahn's Algorithm**: + - Create an empty queue `q` to store the nodes to visit. + - Iterate over all the courses (0 to `numCourses-1`) and enqueue the courses with an indegree of 0 into the queue. These courses have no prerequisites and can be started immediately. + - While the queue is not empty, do the following: + - Dequeue the front element from the queue and store it in a variable `t`. + - Add `t` to the `ans` vector to keep track of the topological order. + - For each neighbor `x` of `t` in the adjacency list: + - Decrement the indegree of `x` by 1 since we are removing the prerequisite `t`. + - If the indegree of `x` becomes 0, enqueue `x` into the queue. This means that all the prerequisites of course `x` have been completed. + +4. **Checking the Result**: + - After the topological sort is complete, check if the size of the `ans` vector is equal to the total number of courses (`numCourses`). + - If they are equal, it means that all the courses can be finished without any cyclic dependencies. Return `true`. + - If the sizes are different, it implies that there is a cycle in the graph, and it is not possible to complete all the courses. Return `false`. + + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + bool canFinish(int n, vector>& prerequisites) { + vector adj[n]; + vector indegree(n, 0); + vector ans; + + for(auto x: prerequisites){ + adj[x[0]].push_back(x[1]); + indegree[x[1]]++; + } + + queue q; + for(int i = 0; i < n; i++){ + if(indegree[i] == 0){ + q.push(i); + } + } + + while(!q.empty()){ + auto t = q.front(); + ans.push_back(t); + q.pop(); + + for(auto x: adj[t]){ + indegree[x]--; + if(indegree[x] == 0){ + q.push(x); + } + } + } + return ans.size() == n; + } +}; +``` + + + + +```java +class Solution { + public boolean canFinish(int n, int[][] prerequisites) { + List[] adj = new List[n]; + int[] indegree = new int[n]; + List ans = new ArrayList<>(); + + for (int[] pair : prerequisites) { + int course = pair[0]; + int prerequisite = pair[1]; + if (adj[prerequisite] == null) { + adj[prerequisite] = new ArrayList<>(); + } + adj[prerequisite].add(course); + indegree[course]++; + } + + Queue queue = new LinkedList<>(); + for (int i = 0; i < n; i++) { + if (indegree[i] == 0) { + queue.offer(i); + } + } + + while (!queue.isEmpty()) { + int current = queue.poll(); + ans.add(current); + + if (adj[current] != null) { + for (int next : adj[current]) { + indegree[next]--; + if (indegree[next] == 0) { + queue.offer(next); + } + } + } + } + + return ans.size() == n; + } +} +``` + + + + + +```python +class Solution: + def canFinish(self, n: int, prerequisites: List[List[int]]) -> bool: + adj = [[] for _ in range(n)] + indegree = [0] * n + ans = [] + + for pair in prerequisites: + course = pair[0] + prerequisite = pair[1] + adj[prerequisite].append(course) + indegree[course] += 1 + + queue = deque() + for i in range(n): + if indegree[i] == 0: + queue.append(i) + + while queue: + current = queue.popleft() + ans.append(current) + + for next_course in adj[current]: + indegree[next_course] -= 1 + if indegree[next_course] == 0: + queue.append(next_course) + + return len(ans) == n +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N + P)$ + +> **Reason**: Where N is the number of courses and P is the number of prerequisites. + +### Space Complexity: $O(N + P)$ + +:::note +**Reason**: We use an adjacency list to store the graph and an array to store the in-degree of each node. +::: + +## References + +- **LeetCode Problem**: [Course Schedule](https://leetcode.com/problems/course-schedule/description/) + +- **Leetcode Solutions:** [Course Schedule](https://leetcode.com/problems/course-schedule/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/0200-0299/0208-Implement-Trie.md b/solutions/lc-solutions/0200-0299/0208-Implement-Trie.md new file mode 100644 index 0000000..e30abfd --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0208-Implement-Trie.md @@ -0,0 +1,306 @@ +--- +id: Implement-Trie +title: Implement Trie +sidebar_label: 0208 Implement-Trie +tags: + - Trie + - java + - python + - c++ + - Recursion +description: "This document provides a solution to the Implementation of Trie." +--- + +## Problem Statement + +A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. + +Implement the Trie class: + +1. Trie() Initializes the trie object. + +2. void insert(String word) Inserts the string word into the trie. + +3. boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise. + +4. boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise. + +### Example 1: + +Input: +["Trie", "insert", "search", "search", "startsWith", "insert", "search"] +[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] +Output +[null, null, true, false, true, null, true] + +Explanation + +``` + Trie trie = new Trie(); + + trie.insert("apple"); + trie.search("apple"); // return True + trie.search("app"); // return False + trie.startsWith("app"); // return True + trie.insert("app"); + trie.search("app"); // return True +``` + +## Solutions + + A Trie prefix tree is a tree data structure which is used to store the strings. Each node in the Trie represents a character of the string and stores the boolean value to indicate whether it is the end of a word. The Trie tree is used to find all the possible words by traversing all the nodes of the tree. Insertion in the Trie tree is performed by iterating each character of the string and checking if the character is already present in the Trie tree. If it is present, then move to the corresponding node of that character, otherwise create a new node and connect it with the Trie tree. + + + + + ```cpp + #include + #include + + class TrieNode { + public: + TrieNode *child[26]; + bool isWord; + TrieNode() { + isWord = false; + for (auto &a : child) a = nullptr; + } + }; + + class Trie { + TrieNode* root; + public: + Trie() { + root = new TrieNode(); + } + void insert(std::string s) { + TrieNode *p = root; + for (auto &a : s) { + int i = a - 'a'; + if (!p->child[i]) p->child[i] = new TrieNode(); + p = p->child[i]; + } + p->isWord = true; + } + bool search(std::string key, bool prefix=false) { + TrieNode *p = root; + for (auto &a : key) { + int i = a - 'a'; + if (!p->child[i]) return false; + p = p->child[i]; + } + if (prefix == false) return p->isWord; + return true; + } + bool startsWith(std::string prefix) { + return search(prefix, true); + } + }; + + // Driver code + int main() { + Trie trie; + trie.insert("apple"); + std::cout << trie.search("apple") << "\n"; // returns true + std::cout << trie.search("app") << "\n"; // returns false + std::cout << trie.startsWith("app") << "\n"; // returns true + trie.insert("app"); + std::cout << trie.search("app") << "\n"; // returns true + return 0; + } + ``` + + + + ```java + class TrieNode { + TrieNode[] child; + boolean isWord; + + public TrieNode() { + child = new TrieNode[26]; + isWord = false; + for (int i = 0; i < 26; i++) { + child[i] = null; + } + } + } + + class Trie { + TrieNode root; + + public Trie() { + root = new TrieNode(); + } + + public void insert(String s) { + TrieNode p = root; + for (char c : s.toCharArray()) { + int i = c - 'a'; + if (p.child[i] == null) p.child[i] = new TrieNode(); + p = p.child[i]; + } + p.isWord = true; + } + + public boolean search(String key, boolean prefix) { + TrieNode p = root; + for (char c : key.toCharArray()) { + int i = c - 'a'; + if (p.child[i] == null) return false; + p = p.child[i]; + } + if (!prefix) return p.isWord; + return true; + } + + public boolean startsWith(String prefix) { + return search(prefix, true); + } + + public static void main(String[] args) { + Trie trie = new Trie(); + trie.insert("apple"); + System.out.println(trie.search("apple")); // returns true + System.out.println(trie.search("app")); // returns false + System.out.println(trie.startsWith("app")); // returns true + trie.insert("app"); + System.out.println(trie.search("app")); // returns true + } + } + ``` + + + + ```python + class TrieNode: + def __init__(self): + self.child = [None] * 26 + self.isWord = False + + class Trie: + def __init__(self): + self.root = TrieNode() + + def insert(self, s: str) -> None: + p = self.root + for a in s: + i = ord(a) - ord('a') + if not p.child[i]: + p.child[i] = TrieNode() + p = p.child[i] + p.isWord = True + + def search(self, key: str, prefix: bool = False) -> bool: + p = self.root + for a in key: + i = ord(a) - ord('a') + if not p.child[i]: + return False + p = p.child[i] + if not prefix: + return p.isWord + return True + + def startsWith(self, prefix: str) -> bool: + return self.search(prefix, True) + + # Driver code + if __name__ == "__main__": + trie = Trie() + trie.insert("apple") + print(trie.search("apple")) # returns True + print(trie.search("app")) # returns False + print(trie.startsWith("app")) # returns True + trie.insert("app") + print(trie.search("app")) # returns True + ``` + + + + ```c + #include + #include + #include + + // Definition for TrieNode + typedef struct TrieNode { + struct TrieNode* child[26]; + bool isWord; + } TrieNode; + + // Function to create a new TrieNode + TrieNode* createTrieNode() { + TrieNode* node = (TrieNode*)malloc(sizeof(TrieNode)); + node->isWord = false; + for (int i = 0; i < 26; i++) { + node->child[i] = NULL; + } + return node; + } + + typedef struct Trie { + TrieNode* root; + } Trie; + + // Function to create a new Trie + Trie* createTrie() { + Trie* trie = (Trie*)malloc(sizeof(Trie)); + trie->root = createTrieNode(); + return trie; + } + + // Function to insert a word into the Trie + void insert(Trie* trie, char* s) { + TrieNode* p = trie->root; + while (*s) { + int i = *s - 'a'; + if (!p->child[i]) p->child[i] = createTrieNode(); + p = p->child[i]; + s++; + } + p->isWord = true; + } + + // Function to search for a word or prefix in the Trie + bool search(Trie* trie, char* key, bool prefix) { + TrieNode* p = trie->root; + while (*key) { + int i = *key - 'a'; + if (!p->child[i]) return false; + p = p->child[i]; + key++; + } + if (!prefix) return p->isWord; + return true; + } + + // Function to check if a prefix exists in the Trie + bool startsWith(Trie* trie, char* prefix) { + return search(trie, prefix, true); + } + + // Driver code + int main() { + Trie* trie = createTrie(); + insert(trie, "apple"); + printf("%d\n", search(trie, "apple", false)); // returns 1 (true) + printf("%d\n", search(trie, "app", false)); // returns 0 (false) + printf("%d\n", startsWith(trie, "app")); // returns 1 (true) + insert(trie, "app"); + printf("%d\n", search(trie, "app", false)); // returns 1 (true) + return 0; + } + ``` + + + + +## Video Lecture: + + diff --git a/solutions/lc-solutions/0200-0299/0209-minimum-size-subarray-sum.md b/solutions/lc-solutions/0200-0299/0209-minimum-size-subarray-sum.md new file mode 100644 index 0000000..8485d52 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0209-minimum-size-subarray-sum.md @@ -0,0 +1,233 @@ +--- +id: minimum-size-subarray-sum +title: Minimum Size Subarray Sum +sidebar_label: 0209 Minimum Size Subarray Sum +tags: + - Dynamic Programming + - C + - C++ + - Java + - Python +description: "This document provides a solution to the Minimum Size Subarray Sum problem" +--- + +## Problem Statement + +Given an array of positive integers nums and a positive integer target, return the minimal length of a +subarray +whose sum is greater than or equal to target. If there is no such subarray, return 0 instead. + +Example 1: + + Input: target = 7, nums = [2,3,1,2,4,3] + Output: 2 + Explanation: The subarray [4,3] has the minimal length under the problem constraint. + +Example 2: + + Input: target = 4, nums = [1,4,4] + Output: 1 + +Example 3: + + Input: target = 11, nums = [1,1,1,1,1,1,1,1] + Output: 0 + +## Solutions + +### Intuition + + To solve this problem efficiently, we need to avoid checking all possible subarrays one by one since doing so would result in a very slow solution when dealing with a large array. The intuitive insight here is that we can do much better by using a "sliding window" approach. This approach involves maintaining a window that expands and contracts as we iterate through the array to find the smallest window that satisfies the condition. + + Here's the thought process behind the sliding window solution: + + 1. We start with two pointers, both at the beginning of the array. These pointers represent the margins of our current window. + + 2. We move the end pointer to the right, adding numbers to our current window's sum. + + 3. As soon as the window's sum becomes equal to or greater than the target, we attempt to shrink the window from the left to find smaller valid windows that still meet the sum criterion. + + 4. Each successful window gives us a potential answer (its size), we keep track of the minimum size found. + + 5. We continue this process until the end pointer reaches the end of the array, and there are no more subarrays to check. + + 6. If the minimum length of the window is never updated from the initial setting that is larger than the array length, it means no valid subarray has been found, and we should return 0. + + 7. By using this approach, we can ensure that we only traverse the array once, giving us an efficient solution with a time complexity of O(n), where n is the length of the input array. + + Learn more about Binary Search, Prefix Sum and Sliding Window patterns. + +### Solution Approach + + The provided solution uses the Sliding Window pattern to solve the problem efficiently. This approach is useful when you need to find a subarray that meets certain criteria, and the problem can be solved in linear time without the need to check every possible subarray individually. + + Here's how the sliding window algorithm is implemented in the solution: + + 1. Initialize two pointers, j at 0 to represent the start of the window and i which will move through the array. + + 2. Maintain a running sum, s, of the values within the current window which starts at 0. + + 3. Iterate over the array using i and continuously add the value of nums[i] to s. + + 4. Inside the loop, use a while loop to check if the current sum s is greater than or equal to the target. If it is, attempt to shrink the window from the left by: + + 5. Updating the minimum length of the valid window if necessary using ans = min(ans, i - j + 1). + + 6. Subtracting nums[j] from the sum s since the left end of the window is moving to the right. + + 7. Incrementing j to actually move the window's start to the right. + + 8. Once the end of the array is reached and there are no more elements to add to the sum, check if ans was updated or not. If ans is still greater than the length of the array n, it means no valid subarray was found, so we return 0. + + 9. If ans was updated during the process (meaning a valid subarray was found), return the value of ans which holds the length of the smallest subarray with a sum of at least target. + + 10. The use of two pointers to create a window that slides over the array allows this algorithm to run in O(n) time, making it very efficient for this type of problem. + + Please note that the Reference Solution Approach mentions another method which is using PreSum & Binary Search but the provided code doesn't implement this method. The PreSum & Binary Search method involves creating an array of prefix sums and then using binary search to find the smallest valid subarray for each element. This is a bit more complex and generally not as efficient as the Sliding Window method used here which requires only O(n) time and O(1) extra space. + + + + + ```cpp + #include + #include + #include + using namespace std; + + class Solution { + public: + int minSubArrayLen(int target, vector& nums) { + int n = nums.size(); + int left = 0; + int sum = 0; + int minLength = INT_MAX; + + for (int i = 0; i < n; i++) { + sum += nums[i]; + + while (sum >= target) { + minLength = min(minLength, i - left + 1); + sum -= nums[left++]; + } + } + + return minLength == INT_MAX ? 0 : minLength; + } + }; + ``` + + + + ```java + import java.util.*; + + public class Solution { + public int minSubArrayLen(int target, int[] nums) { + int n = nums.length; + int left = 0; + int sum = 0; + int minLength = Integer.MAX_VALUE; + + for (int i = 0; i < n; i++) { + sum += nums[i]; + + while (sum >= target) { + minLength = Math.min(minLength, i - left + 1); + sum -= nums[left++]; + } + } + + return minLength == Integer.MAX_VALUE ? 0 : minLength; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + int[] nums = {2, 3, 1, 2, 4, 3}; + int target = 7; + System.out.println(solution.minSubArrayLen(target, nums)); // Output: 2 + } + } + ``` + + + + ```python + from typing import List + + class Solution: + def minSubArrayLen(self, target: int, nums: List[int]) -> int: + n = len(nums) + left = 0 + sum = 0 + minLength = float('inf') + + for i in range(n): + sum += nums[i] + + while sum >= target: + minLength = min(minLength, i - left + 1) + sum -= nums[left] + left += 1 + + return 0 if minLength == float('inf') else minLength + + # Driver code + if __name__ == "__main__": + solution = Solution() + nums = [2, 3, 1, 2, 4, 3] + target = 7 + print(solution.minSubArrayLen(target, nums)) # Output: 2 + ``` + + + + ```c + #include + #include + + int minSubArrayLen(int target, int* nums, int numsSize) { + int left = 0; + int sum = 0; + int minLength = INT_MAX; + + for (int i = 0; i < numsSize; i++) { + sum += nums[i]; + + while (sum >= target) { + if (i - left + 1 < minLength) { + minLength = i - left + 1; + } + sum -= nums[left++]; + } + } + + return minLength == INT_MAX ? 0 : minLength; + } + + // Driver code + int main() { + int nums[] = {2, 3, 1, 2, 4, 3}; + int target = 7; + int result = minSubArrayLen(target, nums, sizeof(nums) / sizeof(nums[0])); + printf("%d\n", result); // Output: 2 + return 0; + } + ``` + + + + +## Time and Space Complexity + + The time complexity of the code is $O(n)$, where n is the length of the input list nums. This is because there are two pointers i and j, both of which travel across the list at most once. The inner while loop only increases j and decreases the sum s until the sum is less than the target, but j can never be increased more than n times throughout the execution of the algorithm. Therefore, each element is processed at most twice, once when it is added to s and once when it is subtracted, leading to a linear time complexity. + + The space complexity of the code is $O(1)$, which means it requires a constant amount of additional space. This is because the algorithm only uses a fixed number of single-value variables (n, ans, s, j, i, x) and does not utilize any data structures that grow with the size of the input. + +## video lecture + + diff --git a/solutions/lc-solutions/0200-0299/0210-course-schedule-II.md b/solutions/lc-solutions/0200-0299/0210-course-schedule-II.md new file mode 100644 index 0000000..1562ed0 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0210-course-schedule-II.md @@ -0,0 +1,245 @@ +--- +id: course-schedule-II +title: Course Schedule II +sidebar_label: 0210 Course Schedule II +tags: +- Depth-First Search +- Topological Sort +- Graph +- Breadth-First Search +description: "This document provides a solution to the Course Schedule II problem." +--- + +## Problem +There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you must take course `bi` first if you want to take course `ai`. + +For example, the pair `[0, 1]`, indicates that to take course 0 you have to first take course `1`. +Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array. + + +### Example 1: + +``` +Input: numCourses = 2, prerequisites = [[1,0]] +Output: [0,1] +Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. +``` + +### Example 2: + +``` +Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] +Output: [0,2,1,3] +Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. +So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. +``` + +### Example 3: + +``` +Input: numCourses = 1, prerequisites = [] +Output: [0] +``` + +### Constraints: +- `1 <= numCourses <= 2000` +- `0 <= prerequisites.length <= numCourses * (numCourses - 1)` +- `prerequisites[i].length == 2` +- `0 <= ai, bi < numCourses` +- `ai != bi` +- All the pairs `[ai, bi]` are distinct. + +## Solution +The code aims to solve the problem of determining whether it is possible to finish all the given courses without any cyclic dependencies. It uses the topological sort algorithm, specifically Kahn's algorithm, to solve this problem. + +1. **Initialization**: + - Create an empty adjacency list to represent the directed graph. Each node in the graph represents a course, and the edges represent the prerequisites. + - Create an array called `indegree` of size `numCourses` and initialize all its elements to 0. The `indegree` array will keep track of the number of incoming edges to each course. + - Create an empty vector `ans` to store the topological order of the courses. + +2. **Building the Graph**: + - Iterate over the `prerequisites` array, which contains pairs of courses indicating the prerequisites. + - For each pair `[a, b]`, add an edge in the adjacency list from `b` to `a`. This indicates that course `b` must be completed before course `a`. + - Increment the indegree of course `a` by 1, as it has one more prerequisite. + +3. **Performing Topological Sort using Kahn's Algorithm**: + - Create an empty queue `q` to store the nodes to visit. + - Iterate over all the courses (0 to `numCourses-1`) and enqueue the courses with an indegree of 0 into the queue. These courses have no prerequisites and can be started immediately. + - While the queue is not empty, do the following: + - Dequeue the front element from the queue and store it in a variable `t`. + - Add `t` to the `ans` vector to keep track of the topological order. + - For each neighbor `x` of `t` in the adjacency list: + - Decrement the indegree of `x` by 1 since we are removing the prerequisite `t`. + - If the indegree of `x` becomes 0, enqueue `x` into the queue. This means that all the prerequisites of course `x` have been completed. + +4. **Checking the Result**: + - After the topological sort is complete, check if the size of the `ans` vector is equal to the total number of courses (`numCourses`). + - If they are equal, it means that all the courses can be finished without any cyclic dependencies. Return `true`. + - If the sizes are different, it implies that there is a cycle in the graph, and it is not possible to complete all the courses. Return `false`. + + +## Code in Different Languages + + + + +```cpp +class Solution +{ +public: + vector findOrder(int V, int m, vector> prerequisites) + { + vector adj[V]; + for (auto it : prerequisites) { + adj[it[1]].push_back(it[0]); + } + + + + int indegree[V] = {0}; + for (int i = 0; i < V; i++) { + for (auto it : adj[i]) { + indegree[it]++; + } + } + + queue q; + for (int i = 0; i < V; i++) { + if (indegree[i] == 0) { + q.push(i); + } + } + vector topo; + while (!q.empty()) { + int node = q.front(); + q.pop(); + topo.push_back(node); + + for (auto it : adj[node]) { + indegree[it]--; + if (indegree[it] == 0) q.push(it); + } + } + + if (topo.size() == V) return topo; + return {}; + } +}; +``` + + + +```java +class Solution { + static int[] findOrder(int n, int m, ArrayList> prerequisites) { + // Form a graph + ArrayList> adj = new ArrayList<>(); + for (int i = 0; i < n; i++) { + adj.add(new ArrayList<>()); + } + + for (int i = 0; i < m; i++) { + adj.get(prerequisites.get(i).get(1)).add(prerequisites.get(i).get(0)); + } + + + + int indegree[] = new int[n]; + for (int i = 0; i < n; i++) { + for (int it : adj.get(i)) { + indegree[it]++; + } + } + + + Queue q = new LinkedList(); + for (int i = 0; i < n; i++) { + if (indegree[i] == 0) { + q.add(i); + } + } + + + int topo[] = new int[n]; + int ind = 0; + // o(v + e) + while (!q.isEmpty()) { + int node = q.peek(); + + q.remove(); + topo[ind++] = node; + // node is in your topo sort + // so please remove it from the indegree + + for (int it : adj.get(node)) { + indegree[it]--; + if (indegree[it] == 0) q.add(it); + } + } + + + if (ind == n) return topo; + int[] arr = {}; + return arr; + } +} +``` + +```Python +class Solution: + def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: + adjList = [[] for _ in range(numCourses)] + visited = [0] * numCourses # 0: unprocessed, 1: processing, 2: processed + courses = [] + + # build adjacency list + for prereq in prerequisites: + a, b = prereq[0], prereq[1] + adjList[b].append(a) + + # cycle detection with topological sort + def dfs(root: int) -> bool: + if visited[root] == 1: + return False + if visited[root] == 2: + return True + + visited[root] = 1 + + for neighbor in adjList[root]: + if not dfs(neighbor): + return False + + visited[root] = 2 + courses.append(root) + + return True + + # iterate through every unprocessed course + for course in range(numCourses): + if visited[course] == 0 and not dfs(course): + return [] + + # dfs topological sort returns sorting in reversed order + courses = reversed(courses) + + return courses +``` + + + + +## Complexity Analysis + +### Time Complexity: $O(V+E)$ + +> **Reason**: where V = no. of nodes and E = no. of edges. This is a simple BFS algorithm. + +### Space Complexity: $O(N) + O(N) ~ O(2N)$ + + +## References + +- **LeetCode Problem**: [Course Schedule ii](https://leetcode.com/problems/course-schedule-ii/description/) + +- **Leetcode Solutions:** [Course Schedule ii](https://leetcode.com/problems/course-schedule-ii/solutions/) diff --git a/solutions/lc-solutions/0200-0299/0211-design-add-and-search-words-data-structure.md b/solutions/lc-solutions/0200-0299/0211-design-add-and-search-words-data-structure.md new file mode 100644 index 0000000..52a18e2 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0211-design-add-and-search-words-data-structure.md @@ -0,0 +1,215 @@ +--- +id: design-add-and-search-words-data-structure +title: Design Add and Search Words Data Structure +sidebar_label: 0211 - Design Add and Search Words Data Structure +tags: +- Depth-First Search +- String +description: "This document provides a solution to the leetcode 211" +--- + +## Problem +Design a data structure that supports adding new words and finding if a string matches any previously added string. + +Implement the `WordDictionary` class: + +`WordDictionary()` Initializes the object. +`void addWord(word)` Adds `word` to the data structure, it can be matched later. +`bool search(word)` Returns `true` if there is any string in the data structure that matches `word` or `false` otherwise. `word` may contain dots `'.'` where dots can be matched with any letter. + + +### Example 1: + +``` +Input: ["WordDictionary","addWord","addWord","addWord","search","search","search","search"] [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]] +Output: [null,null,null,null,false,true,true,true] + +Explanation: WordDictionary wordDictionary = new WordDictionary(); +wordDictionary.addWord("bad"); +wordDictionary.addWord("dad"); +wordDictionary.addWord("mad"); +wordDictionary.search("pad"); // return False +wordDictionary.search("bad"); // return True +wordDictionary.search(".ad"); // return True +wordDictionary.search("b.."); // return True +``` + +### Constraints: +- `1 <= word.length <= 25` +- `word` in `addWord` consists of lowercase English letters +- word in search consist of '.' or lowercase English letters. +- There will be at most 2 dots in word for search queries. +- At most 104 calls will be made to addWord and search. + + +## Solution + +### Data Structure: + +- Trie (Prefix Tree): A tree-like data structure where each node represents a single character of a word. The root node is an entry point for all words. Each node has up to 26 children (one for each letter 'a' to 'z'). + +### Adding a Word: + +- Start at the root node. +- For each character in the word: +- Calculate the index of the character (character - 'a'). +- If the corresponding child node is NULL, create a new TrieNode. +Move to the child node. +- After processing all characters, mark the current node as a leaf node to indicate the end of a word. + +### Searching for a Word: +- Start at the root node. +- Use a recursive helper function searchHelper to handle the search: +- If you reach the end of the word, check if the current node is a leaf node. +- If the current character is '.', check all possible children nodes. +- If the current character is a regular letter, move to the corresponding child node. +- Return true if a matching word is found, otherwise false. + + +## Code in Different Languages + + + + +```cpp +class TrieNode{ + public: + TrieNode *children[26]; + bool isLeaf = false; + + TrieNode(){ + for(int i=0;i<26;i++) children[i] = NULL; + isLeaf = false; + } +}; + +TrieNode *root; + +class WordDictionary { +public: + WordDictionary() { + root = new TrieNode() ; + } + + void addWord(string word) { + TrieNode *curr = root; + for(int i=0;i 'z') return; + int index = word[i] - 'a'; + if(!curr->children[index]) curr->children[index] = new TrieNode(); + curr = curr->children[index]; + } + curr->isLeaf = true; + } + + // bool search(string word) { + // TrieNode *curr = root; + // for(int i=0;i 'z') return false; + // int index = word[i] - 'a'; + // if(!curr->children[index]) return false; + // curr = curr->children[index]; + // } + // return curr->isLeaf; + // } + + bool searchHelper(TrieNode* curr, string word, int index) { + if (index == word.size()) return curr->isLeaf; + if (word[index] == '.') { + for (int i = 0; i < 26; i++) { + if (curr->children[i] && searchHelper(curr->children[i], word, index + 1)) return true; + } + return false; + } else { + int idx = word[index] - 'a'; + if (!curr->children[idx]) return false; + return searchHelper(curr->children[idx], word, index + 1); + } +} + + bool search(string word) { + return searchHelper(root, word, 0); +} + +}; + +``` + + + + +```java +import java.util.*; + +class WordDictionary { + Map> map; + + public WordDictionary() { + map = new HashMap<>(); + } + + public void addWord(String word) { + int index = word.length(); + if (!map.containsKey(index)) { + List list = new ArrayList<>(); + list.add(word); + map.put(index, list); + } else { + map.get(index).add(word); + } + } + + public boolean search(String word) { + int index = word.length(); + if (!map.containsKey(index)) { + return false; + } + + List list = map.get(index); + for (String s : list) { + if (isSame(s, word)) { + return true; + } + } + return false; + } + + private boolean isSame(String s, String word) { + for (int i = 0; i < s.length(); i++) { + if (word.charAt(i) != '.' && s.charAt(i) != word.charAt(i)) { + return false; + } + } + return true; + } +} + +/** + * Your WordDictionary object will be instantiated and called as such: + * WordDictionary obj = new WordDictionary(); + * obj.addWord(word); + * boolean param_2 = obj.search(word); + */ + +``` + + + +## Complexity Analysis + +### Time Complexity: +- Adding a Word: O(m), where m is the length of the word. Each character is processed once. +- Searching for a Word: +- Worst Case: O(m * 26^m), where m is the length of the word and all characters are '.' (wildcards). This is due to the recursive search through all possible children nodes at each level. + + +### Space Complexity: +- TrieNode: O(1) per node. +- WordDictionary: O(n * m), where n is the number of words and m is the average length of the words. + + +## References + +- **LeetCode Problem**: [Design Add and Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure/description/) + +- **Leetcode Solutions:** [Design Add and Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure/solutions/3313923/java-akash2023/) diff --git a/solutions/lc-solutions/0200-0299/0212-word-search-ii.md b/solutions/lc-solutions/0200-0299/0212-word-search-ii.md new file mode 100644 index 0000000..fb6c6a2 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0212-word-search-ii.md @@ -0,0 +1,236 @@ +--- +id: word-search-II +title: Word Search II +sidebar_label: 0212-word-search-ii +tags: + - Array + - String + - Backtracking + - Trie + - Matrix + - C++ + - Java + - Python +description: "This document provides a solution to the Word Search II problem, where we need to return all words on the board, given an mXn board of characters and a list of strings words." +--- + +## Problem + +Given an `m x n` `board` of characters and a list of strings `words`, return all words on the board. + +Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. + +### Examples + +**Example 1:** + +Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"] +Output: ["eat","oath"] + +**Example 2:** + +Input: board = [["a","b"],["c","d"]], words = ["abcb"] +Output: [] + +### Constraints + +- `m == board.length` +- `n == board[i].length` +- `1 <= m, n <= 12` +- `board[i][j]` is a lowercase English letter. +- `1 <= words.length <= 3 * 104` +- `1 <= words[i].length <= 10` +- `words[i]` consists of lowercase English letters. +- All the strings of `words` are unique. + +### Approach + +The approach is very straightforward. After getting familiarized with trie data structure after you watch the above playlist, you will find implementing a trie, a very easy task. Hence let’s discuss the extra logic that comes into the picture here. + +After you insert all the words into the trie, start doing a DFS at each position in the grid, standing at the root of the trie. At each step, check whether there exists a node attached to the alphabet corresponding to the one present in the grid. If yes, proceed to that particular node and in the grid, go to that particular alphabet cell. At each step, check whether the flag of that node is set to true or not. If it is true, then you know that you have reached the end of that particular word of the β€˜words’ array. String β€˜s’ will keep track of this string and it will be inserted into your β€˜ans’ array. Array simply refers to vector, the dynamic array in C++. + +This solution also employs a backtracking technique because you make a cell β€˜*’ once you go to that so that the same character doesn’t repeat in the same word again and this change has to be reverted back once we have checked for that word so that you are not missing out on finding other words that are possibly associated with these changed characters. Also, it is not a good practice to modify the given input array when it’s passed by address. + +### Solution + +#### Code in Different Languages + +### C++ Solution +```cpp +struct TrieNode { + vector> children; + const string* word = nullptr; + TrieNode() : children(26) {} +}; + +class Solution { + public: + vector findWords(vector>& board, vector& words) { + vector ans; + + for (const string& word : words) + insert(word); + + for (int i = 0; i < board.size(); ++i) + for (int j = 0; j < board[0].size(); ++j) + dfs(board, i, j, root, ans); + + return ans; + } + + private: + shared_ptr root = make_shared(); + + void insert(const string& word) { + shared_ptr node = root; + for (const char c : word) { + const int i = c - 'a'; + if (node->children[i] == nullptr) + node->children[i] = make_shared(); + node = node->children[i]; + } + node->word = &word; + } + + void dfs(vector>& board, int i, int j, shared_ptr node, + vector& ans) { + if (i < 0 || i == board.size() || j < 0 || j == board[0].size()) + return; + if (board[i][j] == '*') + return; + + const char c = board[i][j]; + shared_ptr child = node->children[c - 'a']; + if (child == nullptr) + return; + if (child->word != nullptr) { + ans.push_back(*child->word); + child->word = nullptr; + } + + board[i][j] = '*'; + dfs(board, i + 1, j, child, ans); + dfs(board, i - 1, j, child, ans); + dfs(board, i, j + 1, child, ans); + dfs(board, i, j - 1, child, ans); + board[i][j] = c; + } +}; +``` +### Java Solution +```java +class TrieNode { + public TrieNode[] children = new TrieNode[26]; + public String word; +} + +class Solution { + public List findWords(char[][] board, String[] words) { + for (final String word : words) + insert(word); + + List ans = new ArrayList<>(); + + for (int i = 0; i < board.length; ++i) + for (int j = 0; j < board[0].length; ++j) + dfs(board, i, j, root, ans); + + return ans; + } + + private TrieNode root = new TrieNode(); + + private void insert(final String word) { + TrieNode node = root; + for (final char c : word.toCharArray()) { + final int i = c - 'a'; + if (node.children[i] == null) + node.children[i] = new TrieNode(); + node = node.children[i]; + } + node.word = word; + } + + private void dfs(char[][] board, int i, int j, TrieNode node, List ans) { + if (i < 0 || i == board.length || j < 0 || j == board[0].length) + return; + if (board[i][j] == '*') + return; + + final char c = board[i][j]; + TrieNode child = node.children[c - 'a']; + if (child == null) + return; + if (child.word != null) { + ans.add(child.word); + child.word = null; + } + + board[i][j] = '*'; + dfs(board, i + 1, j, child, ans); + dfs(board, i - 1, j, child, ans); + dfs(board, i, j + 1, child, ans); + dfs(board, i, j - 1, child, ans); + board[i][j] = c; + } +} +``` +### Python Solution + +```python +class TrieNode: + def __init__(self): + self.children: Dict[str, TrieNode] = {} + self.word: Optional[str] = None + + +class Solution: + def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: + m = len(board) + n = len(board[0]) + ans = [] + root = TrieNode() + + def insert(word: str) -> None: + node = root + for c in word: + node = node.children.setdefault(c, TrieNode()) + node.word = word + + for word in words: + insert(word) + + def dfs(i: int, j: int, node: TrieNode) -> None: + if i < 0 or i == m or j < 0 or j == n: + return + if board[i][j] == '*': + return + + c = board[i][j] + if c not in node.children: + return + + child = node.children[c] + if child.word: + ans.append(child.word) + child.word = None + + board[i][j] = '*' + dfs(i + 1, j, child) + dfs(i - 1, j, child) + dfs(i, j + 1, child) + dfs(i, j - 1, child) + board[i][j] = c + + for i in range(m): + for j in range(n): + dfs(i, j, root) + + return ans +``` +### Complexity Analysis +**Time Complexity:** O(W * L) + +>Reason: For each word in words, we insert each character into the Trie. If we assume the average length of a word is L and there are W words, this operation is O(W * L). + +**Space Complexity:** O(M * N * M * N) diff --git a/solutions/lc-solutions/0200-0299/0213-house-robber-II.md b/solutions/lc-solutions/0200-0299/0213-house-robber-II.md new file mode 100644 index 0000000..71c276a --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0213-house-robber-II.md @@ -0,0 +1,220 @@ +--- +id: house-robber-II +title: House Robber II +sidebar_label: 0213 House Robber II +tags: +- Dynamic Programming +- Circular Array +- C++ +- Java +- Python +description: "This document provides a solution to the House Robber II problem, where houses are arranged in a circle." +--- + +## Problem + +You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night. + +Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. + +### Examples + +**Example 1:** + +Input: nums = [2,3,2] +Output: 3 +Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. + +**Example 2:** + +Input: nums = [1,2,3,1] +Output: 4 +Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). +Total amount you can rob = 1 + 3 = 4. + +**Example 3:** + +Input: nums = [1,2,3] +Output: 3 + +### Constraints + +- $1 <= nums.length <= 100$ +- $0 <= nums[i] <= 1000$ + +### Approach + +The approach to solving this problem can be summarized as: + +- Make two reduced arrays - arr1(arr-last element) and arr2(arr-first element). + +- Find the maximum of non-adjacent elements as mentioned in article DP5 on arr1 and arr2 separately. Let’s call the answers we got ans1 and ans2 respectively. + +- Return max(ans1, ans2) as our final answer. + +### Solution + +This problem can be solved using dynamic programming. The approach is to make two reduced arrays: one excluding the first element and one excluding the last element. Then, find the maximum sum of non-adjacent elements in both reduced arrays separately. Return the maximum of these two sums as the final answer. + +#### Code in Different Languages + + + + + ```cpp +#include + +using namespace std; + +long long int solve(vector& arr){ + int n = arr.size(); + long long int prev = arr[0]; + long long int prev2 =0; + + for(int i=1; i1) + pick += prev2; + long long int nonPick = 0 + prev; + + long long int cur_i = max(pick, nonPick); + prev2 = prev; + prev= cur_i; + } + return prev; +} + +long long int robStreet(int n, vector &arr){ + vector arr1; + vector arr2; + + if(n==1) + return arr[0]; + + for(int i=0; i arr{1,5,1,2,6}; + int n=arr.size(); + cout< + + + +```java +import java.util.*; + +public class HouseRobberII { + public static long solve(List arr) { + int n = arr.size(); + long prev = arr.get(0); + long prev2 = 0; + + for (int i = 1; i < n; i++) { + long pick = arr.get(i); + if (i > 1) + pick += prev2; + long nonPick = 0 + prev; + + long cur_i = Math.max(pick, nonPick); + prev2 = prev; + prev = cur_i; + } + return prev; + } + + public static long robStreet(int n, List arr) { + List arr1 = new ArrayList<>(); + List arr2 = new ArrayList<>(); + + if (n == 1) + return arr.get(0); + + for (int i = 0; i < n; i++) { + if (i != 0) + arr1.add(arr.get(i)); + if (i != n - 1) + arr2.add(arr.get(i)); + } + + long ans1 = solve(arr1); + long ans2 = solve(arr2); + + return Math.max(ans1, ans2); + } + + public static void main(String[] args) { + List arr = Arrays.asList(1, 5, 1, 2, 6); + int n = arr.size(); + System.out.println(robStreet(n, arr)); + } +} +``` + + + + + +```python +def solve(arr): + n = len(arr) + prev = arr[0] + prev2 = 0 + + for i in range(1, n): + pick = arr[i] + if i > 1: + pick += prev2 + non_pick = 0 + prev + + cur_i = max(pick, non_pick) + prev2 = prev + prev = cur_i + + return prev + +def rob_street(n, arr): + arr1 = arr[1:] # Excluding the first element + arr2 = arr[:-1] # Excluding the last element + + ans1 = solve(arr1) + ans2 = solve(arr2) + + return max(ans1, ans2) + +arr = [1, 5, 1, 2, 6] +print(rob_street(len(arr), arr)) +``` + + + + +### Complexity Analysis + +#### Time Complexity: O(N) + +> **Reason**: We are running a simple iterative loop, two times. Therefore total time complexity will be O(N) + O(N) β‰ˆ O(N) + +#### Space Complexity: O(1) + +> **Reason**: We are not using extra space. + +This solution efficiently handles the circular nature of the problem, ensuring that adjacent houses are not robbed in the same night. The time complexity of this solution is O(N), where N is the number of elements in the input array. + +### References + +- **LeetCode Problem**: [House Robber II](https://leetcode.com/problems/house-robber-ii/) + +- **Authors GeeksforGeeks Profile:** [Vipul lakum](https://leetcode.com/u/vipul_lakum_02/) diff --git a/solutions/lc-solutions/0200-0299/0214-Shortest-Palindrome.md b/solutions/lc-solutions/0200-0299/0214-Shortest-Palindrome.md new file mode 100644 index 0000000..b25ad4e --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0214-Shortest-Palindrome.md @@ -0,0 +1,163 @@ +--- +id: shortest-palindrome +title: Shortest Palindrome +sidebar_label: 0214 Shortest Palindrome +tags: +- String +- KMP Algorithm +- C++ +- Java +- Python +description: "This document provides a solution to finding the shortest palindrome by adding characters in front of the given string." +--- + +## Problem +Given a string `s`, you can convert it to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation. + +### Example 1: +Input: s = "aacecaaa" +Output: "aaacecaaa" + +### Example 2: +Input: s = "abcd" +Output: "dcbabcd" + +### Constraints: +- $0 \leq \text{s.length} \leq 5 \times 10^4$ +- s consists of lowercase English letters only. + +## Solution +To solve this problem efficiently, we can leverage the KMP (Knuth-Morris-Pratt) algorithm to find the longest prefix of the reversed string that matches the suffix of the original string. This allows us to determine the shortest palindrome. + +### Steps: +1. Reverse the string `s` to get `rev_s`. +2. Construct a new string `new_s = s + "#" + rev_s`. +3. Compute the KMP table (prefix function) for `new_s` to find the longest prefix which is also a suffix. +4. The length of this longest prefix gives us the length of characters from `rev_s` that we need to prepend to `s` to form the shortest palindrome. + +#### Code in Different Languages + + + + + ```python + + class Solution(object): + def shortestPalindrome(self, s): + """ + :type s: str + :rtype: str + """ + if not s: + return "" + + # Step 1: Reverse the string + rev_s = s[::-1] + + # Step 2: Combine s and rev_s with a separator + new_s = s + "#" + rev_s + + # Step 3: Compute KMP table (prefix function) for new_s + n = len(new_s) + kmp = [0] * n + + for i in range(1, n): + j = kmp[i - 1] + while j > 0 and new_s[i] != new_s[j]: + j = kmp[j - 1] + if new_s[i] == new_s[j]: + j += 1 + kmp[i] = j + + # Step 4: Calculate the overlap length + overlap = kmp[-1] + + # Step 5: Form the result palindrome + return rev_s[:len(s) - overlap] + s + + ``` + + + + ```java + + class Solution { + public String shortestPalindrome(String s) { + String rev_s = new StringBuilder(s).reverse().toString(); + + // Form the new string to check + String new_s = s + "#" + rev_s; + int n = new_s.length(); + + // Compute the KMP table (prefix function) + int[] kmp = new int[n]; + for (int i = 1, j = 0; i < n; ++i) { + while (j > 0 && new_s.charAt(i) != new_s.charAt(j)) { + j = kmp[j - 1]; + } + if (new_s.charAt(i) == new_s.charAt(j)) { + ++j; + } + kmp[i] = j; + } + + // The length of the longest prefix which is also suffix + int overlap = kmp[n - 1]; + + // Construct the result + return rev_s.substring(0, rev_s.length() - overlap) + s; + } + } + + ``` + + + + ```cpp + + #include + #include + + using namespace std; + + class Solution { + public: + string shortestPalindrome(string s) { + string rev_s = s; + reverse(rev_s.begin(), rev_s.end()); + + // Form the new string to check + string new_s = s + "#" + rev_s; + int n = new_s.size(); + + // Compute the KMP table (prefix function) + vector kmp(n, 0); + for (int i = 1, j = 0; i < n; ++i) { + while (j > 0 && new_s[i] != new_s[j]) { + j = kmp[j - 1]; + } + if (new_s[i] == new_s[j]) { + ++j; + } + kmp[i] = j; + } + + // The length of the longest prefix which is also suffix + int overlap = kmp[n - 1]; + + // Construct the result + return rev_s.substr(0, rev_s.size() - overlap) + s; + } + }; + + ``` + + + + + +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/shortest-palindrome/) +- **Solution Link:** [Shortest Palindrome Solution on LeetCode](https://leetcode.com/problems/shortest-palindrome/solutions/) +- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) diff --git a/solutions/lc-solutions/0200-0299/0215-kth-largest-element-in-an-array.md b/solutions/lc-solutions/0200-0299/0215-kth-largest-element-in-an-array.md new file mode 100644 index 0000000..4f6b3dc --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0215-kth-largest-element-in-an-array.md @@ -0,0 +1,111 @@ +--- +id: kth-largest-element-in-an-array +title: Kth Largest Element in an Array (LeetCode) +sidebar_label: 0215-KthLargestElementInAnArray +description: Find the kth largest element in an unsorted array. Note that it is the kth largest element in sorted order, not the kth distinct element. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [Kth Largest Element in an Array Solution on LeetCode](https://leetcode.com/problems/kth-largest-element-in-an-array/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +Given an integer array `nums` and an integer `k`, return the `k`th largest element in the array. + +Note that it is the `k`th largest element in sorted order, not the `k`th distinct element. + +### Examples + +#### Example 1 + +- **Input:** `nums = [3,2,1,5,6,4]`, `k = 2` +- **Output:** `5` +- **Explanation:** The second largest element is 5. + +#### Example 2 + +- **Input:** `nums = [3,2,3,1,2,4,5,5,6]`, `k = 4` +- **Output:** `4` +- **Explanation:** The fourth largest element is 4. + +### Constraints + +- `1 <= k <= nums.length <= 10^4` +- $-10^4 <= nums[i] <= 10^4$ + +### Approach + +To find the `k`th largest element in an unsorted array, we can use various methods such as sorting, using a min-heap, or using Quickselect algorithm. Here are the approaches: + +1. **Sorting**: + - Sort the array and return the element at index `len(nums) - k`. + +2. **Min-Heap**: + - Maintain a min-heap of size `k`. + - Iterate through the array and maintain the heap with the largest `k` elements. + - The root of the heap will be the `k`th largest element. + +3. **Quickselect**: + - Use a partition-based method to find the `k`th largest element in `O(n)` average time complexity. + +### Solution Code + +#### Python + +```python +import heapq + +class Solution: + def findKthLargest(self, nums, k): + return heapq.nlargest(k, nums)[-1] +``` + +#### Java + +```java +import java.util.PriorityQueue; + +class Solution { + public int findKthLargest(int[] nums, int k) { + PriorityQueue minHeap = new PriorityQueue<>(); + for (int num : nums) { + minHeap.offer(num); + if (minHeap.size() > k) { + minHeap.poll(); + } + } + return minHeap.peek(); + } +} +``` + +#### C++ + +```c++ +#include +#include + +class Solution { +public: + int findKthLargest(vector& nums, int k) { + priority_queue, greater> minHeap; + for (int num : nums) { + minHeap.push(num); + if (minHeap.size() > k) { + minHeap.pop(); + } + } + return minHeap.top(); + } +}; +``` + +### Conclusion +The above solutions effectively find the kth largest element in an array using different methods. +The min-heap approach provides an efficient solution with a time complexity of O(n log k), making it +suitable for larger inputs while ensuring the correct element is found. Each implementation handles +edge cases and constraints effectively, providing robust solutions across various programming +languages. \ No newline at end of file diff --git a/solutions/lc-solutions/0200-0299/0216-Combination-sum-III.md b/solutions/lc-solutions/0200-0299/0216-Combination-sum-III.md new file mode 100644 index 0000000..afacfa3 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0216-Combination-sum-III.md @@ -0,0 +1,345 @@ +--- +id: combination-sum-III +title: Combination Sum III +sidebar_label: 0216-combination-sum-III +tags: + - Dynamic Programming + - Array + - C++ + - Java + - Python +description: "This document provides a solution to the combination sum III problem," +--- + +## Problem Statement + +Find all valid combinations of k numbers that sum up to n such that the following conditions are true: + +1. Only numbers 1 through 9 are used. +2. Each number is used at most once. + +Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order. + +Example 1: + +Input: k = 3, n = 7 +Output: [[1,2,4]] +Explanation: + +``` +1 + 2 + 4 = 7 +There are no other valid combinations. +``` + +Example 2: + +Input: k = 3, n = 9 +Output: [[1,2,6],[1,3,5],[2,3,4]] +Explanation: + +``` +1 + 2 + 6 = 9 +1 + 3 + 5 = 9 +2 + 3 + 4 = 9 +There are no other valid combinations. +``` + +Example 3: + +Input: k = 4, n = 1 +Output: [] +Explanation: There are no valid combinations. + +``` +Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination. +``` + +## Solutions + +### Intuition + + To find the solution, we can utilize a Depth First Search (DFS) algorithm. DFS will help us explore all possible combinations of numbers recursively while adhering to the constraints. Here's the intuition behind using DFS for this problem: + + 1. We begin by considering numbers from 1 to 9 and use each of them as a starting point of a combination. + + 2. To build a combination, we add a number to the current combination (t in the given code) and recursively call the DFS function to add the next number. + + 3. While adding the new number, we have three conditions to check: + a. We must not exceed the target sum n. + b. We should not use more than k numbers. + c. We cannot use numbers greater than 9. + + 4. If the sum of numbers in the current combination equals n and we have used exactly k numbers, then we found a valid combination which we add to the answer list (ans). + + 5. After exploring a number's inclusion, we backtrack by removing the number from the current combination and exploring the possibility of not including that number. + + 6. Through this process of including and excluding each number, and backtracking after exploring each possibility, we ensure that all valid combinations are found. + + 7. Each combination is built up incrementally from the smaller numbers towards the larger ones to avoid repeated combinations and maintain uniqueness. + +The beauty of DFS in this situation is that it inherently avoids duplicates and handles the "each number used at most once" constraint by the recursive nature of its implementation. DFS explores each branch fully (one specific number added vs. not added) before backtracking, which helps cover all potential unique combinations without repetition. + +## Solution Approach + +The provided solution uses a Depth First Search (DFS) algorithm to explore all possible unique combinations of numbers that add up to n using at most k numbers. Here is a step-by-step breakdown of the approach, referring to specific parts of the implementation: + +1. DFS Function: The function dfs(i: int, s: int) is a recursive function where i represents the current number that we are considering adding to the combination, and s is the remaining sum that we need to achieve. The solution initializes the function by calling dfs(1, n). + +2. Base Conditions: + + a. The first base condition checks whether the remaining sum s is 0. If s is 0 and we have exactly k numbers in our temporary combination t, then we have found a valid combination. We then append a a copy of t (using t[:] to create a copy) to our answers list ans. + + b. The second base condition checks whether the current number i is greater than 9 or i is greater than the remaining sum s or we have already selected k numbers. In any of these cases, the function returns without making further recursive calls since no valid combination can be completed under these conditions. + +3. Choosing the Current Number: + + We add the current number i to our temporary combination t. This is the "exploring the possibility of including the number" part of the DFS. + +4. Recursive Call for Next Number: + + After including the current number, we make a recursive call to dfs(i + 1, s - i). This call will explore combinations where the current number i is part of the solution. By passing i + 1, we are ensuring that the same number is not used more than once. By passing s - i, we are reducing the sum by the value of the number we've included. + +5. Backtracking: + + After the recursive call, we backtrack by removing the last number that we added β€” t.pop(). This is where we explore the possibility of excluding the current number. + +6. Recursive Call without the Current Number: + + Another recursive call dfs(i + 1, s) is then made. This call will explore combinations that exclude the current number i. + +7. Initialization: + + The function maintains a list ans to collect all valid combinations found by the DFS. + A list t is used to build a temporary combination that is being explored. + +8. Return Result: + + Once the initial call to dfs(1, n) has completed, all possible combinations have been explored, and the ans list contains all valid combinations as required by the problem. This list is returned as the final result. + +Through the combination of recursive DFS, building combinations incrementally, making sure that each number is used at most once, and backtracking after exploring each possibility, the solution efficiently finds all the valid combinations that sum up to n. The use of a temporary list t for tracking the current combination and the answer list ans are examples of data structures used in this problem to store intermediate and final results, respectively. + + + + + ```cpp + #include + #include + using namespace std; + + class Solution { + public: + vector> combinationSum3(int k, int n) { + vector> output; + vector currentSeq; + vector nums(9); + iota(nums.begin(), nums.end(), 1); + + combination(nums, 0, n, k, currentSeq, output); + + return output; + } + + private: + bool combination(vector& nums, int pos, int target, int length, vector& currentSeq, vector>& output) { + if (currentSeq.size() > length) { + return false; + } + if (target == 0 && currentSeq.size() == length) { + output.push_back(currentSeq); + return true; + } + else if (target < 0) { + return false; + } + + for (int i = pos; i < nums.size(); ++i) { + currentSeq.push_back(nums[i]); + + auto result = combination(nums, i + 1, target - nums[i], length, currentSeq, output); + + currentSeq.pop_back(); + + if (!result) { + return true; + } + } + return true; + } + }; + ``` + + + + ```java + import java.util.*; + + public class Solution { + public List> combinationSum3(int k, int n) { + List> output = new ArrayList<>(); + List currentSeq = new ArrayList<>(); + List nums = new ArrayList<>(); + for (int i = 1; i <= 9; i++) { + nums.add(i); + } + + combination(nums, 0, n, k, currentSeq, output); + + return output; + } + + private boolean combination(List nums, int pos, int target, int length, List currentSeq, List> output) { + if (currentSeq.size() > length) { + return false; + } + if (target == 0 && currentSeq.size() == length) { + output.add(new ArrayList<>(currentSeq)); + return true; + } else if (target < 0) { + return false; + } + + for (int i = pos; i < nums.size(); ++i) { + currentSeq.add(nums.get(i)); + + boolean result = combination(nums, i + 1, target - nums.get(i), length, currentSeq, output); + + currentSeq.remove(currentSeq.size() - 1); + + if (!result) { + return true; + } + } + return true; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.combinationSum3(3, 7)); // Output: [[1, 2, 4]] + System.out.println(solution.combinationSum3(3, 9)); // Output: [[1, 2, 6], [1, 3, 5], [2, 3, 4]] + } + } + ``` + + + + ```python + from typing import List + + class Solution: + def combinationSum3(self, k: int, n: int) -> List[List[int]]: + def combination(nums, pos, target, length, currentSeq, output): + if len(currentSeq) > length: + return False + if target == 0 and len(currentSeq) == length: + output.append(list(currentSeq)) + return True + elif target < 0: + return False + + for i in range(pos, len(nums)): + currentSeq.append(nums[i]) + + result = combination(nums, i + 1, target - nums[i], length, currentSeq, output) + + currentSeq.pop() + + if not result: + return True + return True + + output = [] + currentSeq = [] + nums = list(range(1, 10)) + + combination(nums, 0, n, k, currentSeq, output) + + return output + ``` + + + + ```c + #include + #include + #include + + void combination(int* nums, int pos, int target, int length, int* currentSeq, int currentLen, int*** output, int* outputSize, int** columnSizes) { + if (currentLen > length) { + return; + } + if (target == 0 && currentLen == length) { + (*outputSize)++; + *output = realloc(*output, (*outputSize) * sizeof(int*)); + (*output)[*outputSize - 1] = malloc(currentLen * sizeof(int)); + (*columnSizes) = realloc(*columnSizes, (*outputSize) * sizeof(int)); + for (int i = 0; i < currentLen; i++) { + (*output)[*outputSize - 1][i] = currentSeq[i]; + } + (*columnSizes)[*outputSize - 1] = currentLen; + return; + } else if (target < 0) { + return; + } + + for (int i = pos; i < 9; i++) { + currentSeq[currentLen] = nums[i]; + combination(nums, i + 1, target - nums[i], length, currentSeq, currentLen + 1, output, outputSize, columnSizes); + } + } + + int** combinationSum3(int k, int n, int* returnSize, int** returnColumnSizes) { + int* nums = malloc(9 * sizeof(int)); + for (int i = 0; i < 9; i++) { + nums[i] = i + 1; + } + + int* currentSeq = malloc(k * sizeof(int)); + int** output = NULL; + int* columnSizes = NULL; + int outputSize = 0; + + combination(nums, 0, n, k, currentSeq, 0, &output, &outputSize, &columnSizes); + + *returnSize = outputSize; + *returnColumnSizes = columnSizes; + + free(nums); + free(currentSeq); + + return output; + } + ``` + + + + +## Time and Space Complexity + + The given Python code defines a method combinationSum3 that finds all possible combinations of k different numbers that add up to a number n, where each number is from 1 to 9 (inclusive) and each combination is unique. + +### Time Complexity + + The time complexity of this function can be analyzed by looking at the recursive dfs calls. Each call to dfs potentially makes two further calls, corresponding to including the current number i or excluding it. We can view this as a binary tree of decisions, where at each step, we decide whether to include a number in our current combination (t.append(i)) or not (dfs(i + 1, s)). + + Each number between 1 and 9 is considered exactly once in the context of a particular combination, and there are 9 choices at the first call, 8 at the second, and so forth. However, the depth of our recursion is limited by k (the size of each combination) and the fact that we do not consider subsequent numbers once we reach a sum greater than n or a combination length equal to k. + + Therefore, the time complexity is O(9! / (9 - k)!) in the worst case (when n is large enough to allow all combinations of k numbers). Note that since k < 9, this time complexity remains within a polynomial bound with respect to 9 (the number of different numbers we can pick). + +### Space Complexity + + The space complexity is determined by the space needed for the recursive call stack and the space used to store the combinations. In the worst case, the recursion can go as deep as k, as we stop further recursion when the length of the temporary list t reaches k. Therefore the recursion call stack will contribute $O(k)$. + + The space for storing all the combinations also needs to be considered. We have a list of lists to store the valid combinations, and, at most, each combination contains k elements. In the worst case, the number of combinations stored will also be bounded by the total number of combinations of k numbers out of 9, which is $O(9! / (k!(9 - k)!))$ (this is the binomial coefficient representing the number of ways to choose k distinct integers from a set of 9). + + However, because these combinations are part of the output, we often do not count this as extra space in terms of space complexity analysis (since the space is required to represent the output). Thus the space complexity is usually considered to be $O(k)$, which accounts only for the recursion depth and not the output storage. + + Combining both the recursion call stack and the output storage, and if we were to include the output as part of the space complexity, our total space complexity would be $O(9! / (k!(9 - k)!) + k)$. + +## Video Lecture + + diff --git a/solutions/lc-solutions/0200-0299/0217-contains-duplicate.md b/solutions/lc-solutions/0200-0299/0217-contains-duplicate.md new file mode 100644 index 0000000..efaf45c --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0217-contains-duplicate.md @@ -0,0 +1,182 @@ +--- +id: contains-duplicate +title: Contains Duplicate(LeetCode) +sidebar_label: 0217-Contains Duplicate +tags: + - Array + - Hash Table + - Sorting +description: Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. +--- + +## Problem Statement + +Given an integer array `nums`, return `true` if any value appears at least twice in the array, and return `false` if every element is distinct. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [1,2,3,1] +Output: true +``` + +**Example 2:** + +```plaintext +Input: nums = [1,2,3,4] +Output: false +``` + +**Example 3:** + +```plaintext +Input: nums = [1,1,1,3,3,4,3,2,4,2] +Output: true +``` + +### Constraints + +- `1 <= nums.length <= 105` +- `-109 <= nums[i] <= 109` + +## Solution + +When tasked with checking for duplicates in an array, there are several approaches to consider. Below, we detail four different methods, from the simplest brute force solution to more optimized approaches using sorting and hash-based structures. + +### Approach 1: Brute Force + +#### Algorithm + +1. Iterate through the array with an outer loop. +2. For each element in the outer loop, iterate through the array with an inner loop starting from the next element. +3. Compare the current element of the outer loop with the current element of the inner loop. +4. If a match is found, return true. +5. If no duplicates are found after all iterations, return false. + +#### Implementation + +```C++ +class Solution { +public: + bool containsDuplicate(vector& nums) { + int n = nums.size(); + for (int i = 0; i < n - 1; i++) { + for (int j = i + 1; j < n; j++) { + if (nums[i] == nums[j]) + return true; + } + } + return false; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: $O(N^2)$ +- **Space complexity**: $O(1)$ + +### Approach 2: Sorting + +#### Algorithm + +1. Sort the array in ascending order. +2. Iterate through the sorted array. +3. Compare each element with its next element. +4. If a match is found, return true. +5. If no duplicates are found after all comparisons, return false. + +#### Implementation + +```C++ +class Solution { +public: + bool containsDuplicate(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + for (int i = 1; i < n; i++) { + if (nums[i] == nums[i - 1]) + return true; + } + return false; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: $O(NlogN)$ +- **Space complexity**: $O(1)$ + +### Approach 3: Hash Set + +#### Algorithm + +1. Create an empty hash set. +2. Iterate through the array. +3. For each element, check if it exists in the hash set. +4. If it exists, return true. +5. If it does not exist, add the element to the hash set. +6. If no duplicates are found after all iterations, return false. + +#### Implementation + +```C++ +class Solution { +public: + bool containsDuplicate(vector& nums) { + unordered_set seen; + for (int num : nums) { + if (seen.count(num) > 0) + return true; + seen.insert(num); + } + return false; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: $O(N)$ +- **Space complexity**: $O(N)$ + +### Approach 4: Hash Map + +#### Algorithm + +1. Create an empty hash map. +2. Iterate through the array. +3. For each element, check if it exists in the hash map with a count greater than or equal to 1. +4. If it exists, return true. +5.If it does not exist, add the element to the hash map and set its count to 1. +6. If no duplicates are found after all iterations, return false. + +#### Implementation + +```C++ +class Solution { +public: + bool containsDuplicate(vector& nums) { + unordered_map seen; + for (int num : nums) { + if (seen[num] >= 1) + return true; + seen[num]++; + } + return false; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: $O(N)$ +- **Space complexity**: $O(N)$ + + +### Conclusion + +For checking duplicates in an array, the most efficient approaches are those utilizing hash-based data structures, such as hash sets or hash maps. These methods provide linear time complexity and are suitable for large datasets. While the brute force and sorting approaches are simpler, they are less efficient and may not be practical for larger arrays. diff --git a/solutions/lc-solutions/0200-0299/0218-the-skyline-problem.md b/solutions/lc-solutions/0200-0299/0218-the-skyline-problem.md new file mode 100644 index 0000000..1190737 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0218-the-skyline-problem.md @@ -0,0 +1,234 @@ +--- + +id: the-skyline-problem +title: The Skyline Problem +difficulty: Hard +sidebar_label: 0218-The-Skyline-Problem +tags: + - Divide and Conquer + - Heap (Priority Queue) + - Binary Indexed Tree + - Segment Tree + - Line Sweep + - LeetCode Hard +--- + +## Problem Description +A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively. + +The buildings are represented by a list of triplets `[left, right, height]`, where: +- `left` is the x coordinate of the left edge of the building. +- `right` is the x coordinate of the right edge of the building. +- `height` is the height of the building. + +The output is a list of "key points" (coordinates) that uniquely define a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is not included. + +### Example +**Example 1:** +```plaintext +Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]] +Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]] +``` + +**Example 2:** +```plaintext +Input: buildings = [[0,2,3],[2,5,3]] +Output: [[0,3],[5,0]] +``` + +### Constraints +- `1 <= buildings.length <= 10^4` +- `0 <= left_i < right_i <= 2^31 - 1` +- `1 <= height_i <= 2^31 - 1` +- `buildings` is sorted by `left` in non-decreasing order. + +## Approach + +### Approach Overview +To solve the skyline problem, we can use a combination of a line sweep algorithm and a max-heap to track the current heights of buildings as we move from left to right across the x-axis. + +### Detailed Steps + +1. **Extract Key Events**: + - For each building, extract two events: one for the start (`left`) of the building with its height as positive, and one for the end (`right`) of the building with its height as negative. + +2. **Sort Events**: + - Sort the events primarily by the x-coordinate. If two events have the same x-coordinate, process the event with the taller height first. + +3. **Process Events Using a Max-Heap**: + - Use a max-heap to keep track of the current building heights as we process each event. + - For each event: + - If it's a start event (height is positive), add the height to the heap. + - If it's an end event (height is negative), remove the height from the heap. + - After processing the event, check the current highest height in the heap. If it has changed from the previous highest height, add a new key point to the result. + +## Code Examples + +### Python +```python +from heapq import heappush, heappop + +class Solution: + def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]: + events = [] + for left, right, height in buildings: + events.append((left, -height, right)) + events.append((right, 0, 0)) + + events.sort() + result, heap = [[0, 0]], [(0, float('inf'))] + + for x, negH, R in events: + while x >= heap[0][1]: + heappop(heap) + if negH: + heappush(heap, (negH, R)) + if result[-1][1] != -heap[0][0]: + result.append([x, -heap[0][0]]) + + return result[1:] +``` + +### C++ +```cpp +class Solution { +public: + vector> getSkyline(vector>& buildings) { + vector> events; + for (const auto& building : buildings) { + events.emplace_back(building[0], -building[2]); + events.emplace_back(building[1], building[2]); + } + sort(events.begin(), events.end()); + + vector> result; + multiset heights = {0}; + int prevMaxHeight = 0; + + for (const auto& event : events) { + int x = event.first; + int h = event.second; + if (h < 0) { + heights.insert(-h); + } else { + heights.erase(heights.find(h)); + } + int currentMaxHeight = *heights.rbegin(); + if (currentMaxHeight != prevMaxHeight) { + result.push_back({x, currentMaxHeight}); + prevMaxHeight = currentMaxHeight; + } + } + + return result; + } +}; +``` + +### Java +```java +class Solution { + public List> getSkyline(int[][] buildings) { + List events = new ArrayList<>(); + for (int[] building : buildings) { + events.add(new int[]{building[0], -building[2]}); + events.add(new int[]{building[1], building[2]}); + } + Collections.sort(events, (a, b) -> { + if (a[0] != b[0]) return Integer.compare(a[0], b[0]); + return Integer.compare(a[1], b[1]); + }); + + List> result = new ArrayList<>(); + PriorityQueue heights = new PriorityQueue<>(Collections.reverseOrder()); + heights.add(0); + int prevMaxHeight = 0; + + for (int[] event : events) { + if (event[1] < 0) { + heights.add(-event[1]); + } else { + heights.remove(event[1]); + } + int currentMaxHeight = heights.peek(); + if (currentMaxHeight != prevMaxHeight) { + result.add(Arrays.asList(event[0], currentMaxHeight)); + prevMaxHeight = currentMaxHeight; + } + } + + return result; + } +} +``` + +### C +```c +#include + +typedef struct { + int x, h; +} Event; + +int cmp(const void *a, const void *b) { + Event *ea = (Event *)a; + Event *eb = (Event *)b; + if (ea->x != eb->x) return ea->x - eb->x; + return ea->h - eb->h; +} + +int* getSkyline(int** buildings, int buildingsSize, int* buildingsColSize, int* returnSize) { + int eventCount = 2 * buildingsSize; + Event *events = (Event *)malloc(eventCount * sizeof(Event)); + int *heights = (int *)malloc(eventCount * sizeof(int)); + int *result = (int *)malloc(eventCount * 2 * sizeof(int)); + int heightsSize = 0, resultSize = 0, maxHeight = 0; + + for (int i = 0; i < buildingsSize; ++i) { + events[2 * i].x = buildings[i][0]; + events[2 * i].h = -buildings[i][2]; + events[2 * i + 1].x = buildings[i][1]; + events[2 * i + 1].h = buildings[i][2]; + } + + qsort(events, eventCount, sizeof(Event), cmp); + + heights[heightsSize++] = 0; + for (int i = 0; i < eventCount; ++i) { + Event event = events[i]; + if (event.h < 0) { + heights[heightsSize++] = -event.h; + } else { + for (int j = 0; j < heightsSize; ++j) { + if (heights[j] == event.h) { + for (int k = j; k < heightsSize - 1; ++k) { + heights[k] = heights[k + 1]; + } + --heightsSize; + break; + } + } + } + int currentMaxHeight = 0; + for (int j = 0; j < heightsSize; ++j) { + if (heights[j] > currentMaxHeight) currentMaxHeight = heights[j]; + } + if (currentMaxHeight != maxHeight) { + result[resultSize++] = event.x; + result[resultSize++] = currentMaxHeight; + maxHeight = currentMaxHeight; + } + } + + *returnSize = resultSize; + free(events); + free(heights); + return result; +} +``` + +## Complexity + +- **Time Complexity**: `O(n log n)`, where `n` is the number of buildings. Sorting the events takes `O(n log n)` time, and processing each event takes `O(log n)` time due to heap operations. +- **Space Complexity**: `O(n)`, due to the storage of events and the heap structure. + diff --git a/solutions/lc-solutions/0200-0299/0219-contains-duplicate-II.md b/solutions/lc-solutions/0200-0299/0219-contains-duplicate-II.md new file mode 100644 index 0000000..ba93593 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0219-contains-duplicate-II.md @@ -0,0 +1,182 @@ +--- +id: contains-duplicate-II +title: Contains Duplicate II(LeetCode) +sidebar_label: 0219-Contains Duplicate II +tags: + - Array + - Hash Table + - Sliding Window +description: Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k. +--- + +## Problem Statement + +Given an integer array `nums` and an integer `k`, return `true` if there are two distinct indices `i` and `j` in the array such that `nums[i] == nums[j]` and `abs(i - j) <= k`. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [1,2,3,1], k = 3 +Output: true +``` + +**Example 2:** + +```plaintext +Input: nums = [1,0,1,1], k = 1 +Output: true +``` + +**Example 3:** + +```plaintext +Input: nums = [1,2,3,1,2,3], k = 2 +Output: false +``` + +### Constraints + +- `1 <= nums.length <= 105` +- `109 <= nums[i] <= 109` +- `0 <= k <= 105` + +## Solution + +We can solve this problem using a HashSet or a HashMap to keep track of the elements within the sliding window of size k. Here, we discuss Java, C++, Python, and JavaScript solutions for this problem. + +### Approach 1: Java Solution Using HashSet + +#### Algorithm + +1. Initialize an empty HashSet. +2. Traverse the array with a loop. +3. For each element: +* If it is already in the HashSet, return 'true'. +* Add the element to the HashSet. +* If the HashSet size exceeds 'k', remove the oldest element. +4. If no duplicate is found within the given range, return 'false'. + +#### Implementation + +```Java +class Solution { + public boolean containsNearbyDuplicate(int[] nums, int k) { + if (nums == null || nums.length < 2 || k == 0) return false; + HashSet hset = new HashSet(); + for (int j = 0; j < nums.length; j++) { + if (!hset.add(nums[j])) return true; + if (hset.size() >= k + 1) { + hset.remove(nums[j - k]); + } + } + return false; + } +} +``` + +### Complexity Analysis + +- **Time complexity**: O(N) +- **Space complexity**: O(k) + +### Approach 2: C++ Solution Using Unordered Set + +#### Algorithm + +1. Initialize an unordered set. +2. Traverse the array with a loop. +3. For each element: +* Check if it is in the set. If yes, return 'true'. +* Insert the element into the set. +* If the set size exceeds 'k', remove the oldest element. +4. If no duplicate is found, return 'false'. + +#### Implementation + +```C++ +class Solution { +public: + bool containsNearbyDuplicate(vector& nums, int k) { + unordered_set hset; + for (int idx = 0; idx < nums.size(); idx++) { + if (hset.count(nums[idx])) return true; + hset.insert(nums[idx]); + if (hset.size() > k) { + hset.erase(nums[idx - k]); + } + } + return false; + } +}; +``` + +### Approach 3: Python Solution Using Dictionary + +#### Algorithm + +1. Initialize an empty dictionary. +2. Traverse the array with a loop. +3. For each element: +* Check if the element exists in the dictionary and the difference between the current index and the stored index + is less than or equal to 'k'. If yes, return 'true'. +* Update the dictionary with the current element and its index. +4. If no duplicate is found, return 'false'. + +#### Implementation + +```Python +class Solution: + def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: + hset = {} + for idx in range(len(nums)): + if nums[idx] in hset and abs(idx - hset[nums[idx]]) <= k: + return True + hset[nums[idx]] = idx + return False +``` + +### Complexity Analysis + +- **Time complexity**: O(N) +- **Space complexity**: O(k) + +### Approach 4: JavaScript Solution Using HashMap + +#### Algorithm + +1. Initialize an empty Map. +2. Traverse the array with a loop. +3. For each element: +* Check if it exists in the map and the difference between indices is less than or equal to 'k'. If yes, return + 'true'. +* Update the map with the current element and its index. +4. If no duplicate is found, return 'false'. + +#### Implementation + +```Javascript +var containsNearbyDuplicate = function(nums, k) { + const hasmap = new Map(); + for (let idx = 0; idx < nums.length; idx++) { + if (hasmap.has(nums[idx]) && idx - hasmap.get(nums[idx]) <= k) { + return true; + } + hasmap.set(nums[idx], idx); + } + return false; +}; +``` + +### Complexity Analysis + +- **Time complexity**: O(N) +- **Space complexity**: O(k) + + +### Conclusion + +All four solutions utilize a similar strategy of keeping track of the elements within a sliding window of size 'k'. +This ensures that we can efficiently determine if any two indices have the same value and are within 'k' distance of +each other. Each solution is optimal with a time complexity of O(n) and a space complexity of O(k). diff --git a/solutions/lc-solutions/0200-0299/0220-contains-dublicate-lll.md b/solutions/lc-solutions/0200-0299/0220-contains-dublicate-lll.md new file mode 100644 index 0000000..026b253 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0220-contains-dublicate-lll.md @@ -0,0 +1,116 @@ +--- +id: contains-duplicate-III +title: Contains Dublicate -III +sidebar_label: 0220- Contains Dublicate III +tags: + - Array + - Sorting + - Bucket sort + - Sliding Window +description: This is the solution of question H-Index II on leetcode +sidebar_position: 0220 +--- + +## Problem Description + +You are given an integer array nums and two integers indexDiff and valueDiff. + +Find a pair of indices` (i, j) `such that: + +`i != j`, +`abs(i - j) <= indexDiff.` +`abs(nums[i] - nums[j]) <= valueDiff`, and +Return `true` if such pair exists or `false` otherwise. + +### Example 1 + +``` +Input: nums = [1,2,3,1], indexDiff = 3, valueDiff = 0 +Output: true + +Explanation: We can choose (i, j) = (0, 3). +We satisfy the three conditions: +i != j --> 0 != 3 +abs(i - j) <= indexDiff --> abs(0 - 3) <= 3 +abs(nums[i] - nums[j]) <= valueDiff --> abs(1 - 1) <= 0 +``` + +### Example 2 + +``` +Input: nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3 +Output: false + +Explanation: After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false. +``` + +### Constraints + +- `2 <= nums.length <= 105` +- `109 <= nums[i] <= 109` +- `1 <= indexDiff <= nums.length` +- `0 <= valueDiff <= 109` + +## Approach +1. **Initialize a Set:** + - Use a `set` to maintain a sliding window of size \( k \). + +2. **Iterate through Array:** + - For each element in `nums`: + - If index \( i \) exceeds \( k \), remove the element `nums[i - k - 1]` from the set to maintain the window size. + - Use `window.lower_bound(nums[i] - z)` to find the smallest number in the set greater than or equal to `nums[i] - z`. + - Check if this number is within the range \([nums[i] - z, nums[i] + z]\). If so, return `true`. + - Insert the current number `nums[i]` into the set. + +3. **Return False if No Pair Found:** + - If the loop completes without finding such a pair, return `false`. + + + + +### Solution Code + +#### C++ + +```c++ +class Solution { +public: + bool containsNearbyAlmostDuplicate(vector& nums, int k, int z) { + set window; + for (int i = 0; i < nums.size(); i++) { + if (i > k) window.erase(nums[i-k-1]); + auto it = window.lower_bound( nums[i] - z); + if (it != window.end() && *it <= ( nums[i] + z)) + return true; + window.insert(nums[i]); + } + return false; + } +}; +``` + +#### Python +```python +from sortedcontainers import SortedList + +class Solution: + def containsNearbyAlmostDuplicate(self, nums, k, t): + SList = SortedList() + for i in range(len(nums)): + if i > k: SList.remove(nums[i-k-1]) + pos1 = SortedList.bisect_left(SList, nums[i] - t) + pos2 = SortedList.bisect_right(SList, nums[i] + t) + + if pos1 != pos2 and pos1 != len(SList): return True + + SList.add(nums[i]) + + return False +``` + +#### Conclusion +### Time Complexity: +- O(n log k), where \( n \) is the number of elements in `nums` and \( k \) is the sliding window size. + +### Space Complexity: +- O(k) for the `set` containing at most \( k \) elements. diff --git a/solutions/lc-solutions/0200-0299/0221 - Maximal Square.md b/solutions/lc-solutions/0200-0299/0221 - Maximal Square.md new file mode 100644 index 0000000..22a2cdf --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0221 - Maximal Square.md @@ -0,0 +1,130 @@ +--- +id: maximal-square +title: Maximal Square +sidebar_label: 221 Maximal Square +tags: +- Dynamic Programming +- Java +- Matrix +- Array +description: "This document provides a solution where we find the largest square containing only 1's and return its area." +--- + +## Problem + +You are given an m x n binary $matrix$ filled with 0's and 1's, find the largest square containing only 1's and return its area. + +### Examples + +**Example 1:** + +![image](https://github.com/vivekvardhan2810/codeharborhub.github.io/assets/91594529/4816deda-e3ba-47d4-b6d8-b38dd4fe67e2) + +**Input:** matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] + +**Output:** 4 + +**Example 2:** + +![image](https://github.com/vivekvardhan2810/codeharborhub.github.io/assets/91594529/43f9556f-bdde-4d5c-b8ab-a5807c51cb3c) + +**Input:** matrix = [["0","1"],["1","0"]] + +**Output:** 1 + +**Example 3:** + +**Input:** matrix = [["0"]] + +**Output:** 0 + +### Constraints + +- $m == matrix.length$ +- $n == matrix[i].length$ +- $1 <= m, n <= 300$ +- $matrix[i][j]$ is $0$ or $1$ + +--- +## Approach +There are four approaches discussed that helps to obtain the solution: + +1. **Dynamic Programming Table**: + - Use a 2D DP array **'dp'** where **'dp[i][j]'** represents the side length of the largest square whose bottom-right corner is at position **'(i, j)'**. + + - The value of **'dp[i][j]'** is determined by the values of **'dp[i-1][j]'**, **'dp[i][j-1]'**, and **'dp[i-1][j-1]'**. + +2. **Transition**: + + - If **'matrix[i][j]'** is $1$: + - If **'i'** or **'j'** is $0$ (first row or first column), **'dp[i][j]'** is $1$ because the largest square ending there can only be of $size1$. + + - Otherwise, **'dp[i][j]'** is the minimum of **'dp[i-1][j]'**, **'dp[i][j-1]'**, and **'dp[i-1][j-1]'** plus $1$. This is because we can form a larger square only if all three adjacent squares can also form squares of $1's$. + +3. **Max Side Length**: + + - Track the maximum side length of squares found during the iteration. + +4. **Result**: + + - The area of the largest square is the square of the maximum side length found. + +## Solution for Maximal Square + +This problem can be solved using dynamic programming. The problem requires to Utilize a DP table where each entry represents the side length of the largest square ending at that position. + +#### Code in Java + + ```java +class Solution { + public int maximalSquare(char[][] matrix) { + if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { + return 0; + } + + int rows = matrix.length; + int cols = matrix[0].length; + int maxSide = 0; + + // Create a DP array to store the size of the largest square ending at each position + int[][] dp = new int[rows][cols]; + + // Fill the DP array + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + if (matrix[i][j] == '1') { + if (i == 0 || j == 0) { + // If we're at the first row or first column, the largest square ending here is just 1 + dp[i][j] = 1; + } else { + // Otherwise, calculate the size of the square based on the surrounding squares + dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1; + } + // Update the maximum side length found + maxSide = Math.max(maxSide, dp[i][j]); + } + } + } + + // The area of the largest square is side length squared + return maxSide * maxSide; + } +} + +``` + +### Complexity Analysis + +#### Time Complexity: O($m$ x $n$) + +> **Reason**: The algorithm involves iterating through each cell of the matrix once, leading to a time complexity of $𝑂(π‘š Γ— 𝑛)$, where $π‘š$ is the number of rows and $𝑛$ is the number of columns. + +#### Space Complexity: O($m$ Γ— $n$) + +> **Reason**: The space complexity is $𝑂(π‘š Γ— 𝑛)$ due to the additional DP array used. This could be optimized to $O(n)$ by reusing a single row of DP values, but in the given solution, we use a full 2D DP array. + +# References + +- **LeetCode Problem:** [Maximal Square](https://leetcode.com/problems/maximal-square/description/) +- **Solution Link:** [Maximal Square Solution on LeetCode](https://leetcode.com/problems/maximal-square/solutions/) +- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/vivekvardhan43862/) diff --git a/solutions/lc-solutions/0200-0299/0222-count-complete-tree-node.md b/solutions/lc-solutions/0200-0299/0222-count-complete-tree-node.md new file mode 100644 index 0000000..5c8ce3f --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0222-count-complete-tree-node.md @@ -0,0 +1,166 @@ +--- +id: count-complete-tree-nodes +title: Count Complete tree nodes +sidebar_label: 0222 Count complete tree nodes +tags: + - tree + - Binary search +description: "This is a solution to the Count Complete tree nodes" +--- + +## Problem Description + +Given the `root` of a complete binary tree, return the number of the nodes in the tree. + +According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. + +Design an algorithm that runs in less than `O(n)` time complexity. + + +### Examples +**Example 1:** + +``` + +Input:root = [1,2,3,4,5,6] +Output: 6 +``` + +**Example 2:** + +``` +Input: root = [] +Output: 0 +``` + +**Example 3** +``` +Input: root = [1] +Output: 1 +``` + +### Constraints + +- The number of nodes in the tree is in the range` [0, 5 * 104]`. +- `0 <= Node.val <= 5 * 104` +- The tree is guaranteed to be complete. + +### Approach + +- Get the 'left depth' of both left and right subtrees +- If they are the same, then count the left subtree with simple math, and recursively call it on the right subtree +- Otherwise, count the right subtree with simple math, and recursively call it on the left subtree. + + +#### Code in C++ + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int findDepthLeft(TreeNode* root){ + if (root == NULL) return 0; + return 1 + findDepthLeft(root->left); + } + + + int countNodes(TreeNode* root) { + if (root == NULL) return 0; + int depth_L = findDepthLeft(root->left); + int depth_R = findDepthLeft(root->right); + + // Either left tree is full (largest in row continues to left) + // Or right tree is full (full row, largest ended in next row on left) + // Counting each level gives us: 1 + 2 + 4 ... + 2^(depth_R - 1) + // = 2^depth_R - 1. Since we also need to include this node, it is 2^depth_R + int counted = pow(2, depth_R); + + if (depth_L == depth_R){ + // 1 + count(depth_L == depth_R) + rest + return counted + countNodes(root->right); + + } else{ + // 1 + count(depth_R) + rest + return counted + countNodes(root->left); + } + + } +}; +``` +#### Code in java +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ + class Solution { + public int countNodes(TreeNode root) { + if (root == null) + return 0; + return countNodes(root.left) + countNodes(root.right) + 1; + } + } + +``` + +#### Code in python +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def countNodes(self, root: Optional[TreeNode]) -> int: + if root is None: + return 0 + if root.left is None and root.right is None: + return 1 + elif root.right is None: + return 2 + left_level = self.level(root.left) + right_level = self.level(root.right) + if left_level == right_level: + return 2 ** left_level + self.countNodes(root.right) + else: + return self.countNodes(root.left) + 2 ** right_level + + def level(self, root): + i = 0 + while root: + i += 1 + root = root.left + return i +``` + + + +### Complexity analysis +#### Time complexity: +- `O(logn)`. At every step, you are disregarding half the tree. Think about it like this: You never wasted time visiting the nodes in the tree you found to be full, except on the left-most path (negligible). Since you shrink the input by half every time, it is logn. +- Technically, the (negligible) portion would make this algorithm (logn)^2, but practically it makes little difference as it operates similarly to log. You can also optimize this by skipping the branch you already computed and adding the depth, but it would make the solution less readable. + +#### Space complexity: +- `O(logn)`, as that is the maximum recursion depth, which is our space usage. diff --git a/solutions/lc-solutions/0200-0299/0223-rectangle-area.md b/solutions/lc-solutions/0200-0299/0223-rectangle-area.md new file mode 100644 index 0000000..42a19db --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0223-rectangle-area.md @@ -0,0 +1,93 @@ +--- +id: rectangle-area +title: Rectangle Area +sidebar_label: 0223 Rectangle Area +tags: +- Geometry +- Math +description: "This gives solution to the problem rectangle area" +--- + +## Problem + +Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles. + +The first rectangle is defined by its bottom-left corner `(ax1, ay1)` and its top-right corner `(ax2, ay2).` + +The second rectangle is defined by its bottom-left corner `(bx1, by1)` and its top-right corner `(bx2, by2).` + +### Examples + +**Example 1:** + +**Input:** `rax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2` +**Output:** `45` + +**Example 2:** + +**Input:** ` ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2` +**Output:** `16` + +### Constraints + +- `104 <= ax1 <= ax2 <= 104` +- `104 <= ay1 <= ay2 <= 104` +- `104 <= bx1 <= bx2 <= 104` +- `104 <= by1 <= by2 <= 104` + +--- + +## Approach +Find area of both rectangle and subtract the common region. + +### Solution + +#### Java + +```java +class Solution { + public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { + int areaA = Math.abs(ax1 - ax2) * Math.abs(ay1 - ay2); + int areaB = Math.abs(bx1 - bx2) * Math.abs(by1 - by2); + + int intersectionWidth = Math.max(0, Math.min(ax2, bx2) - Math.max(ax1, bx1)); + int intersectionHeight = Math.max(0, Math.min(ay2, by2) - Math.max(ay1, by1)); + int intersectionArea = intersectionWidth * intersectionHeight; + + return areaA + areaB - intersectionArea; + } +} +``` +### C++ +```cpp +class Solution { +public: + int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { + int ans=(ax2-ax1)*(ay2-ay1)+(bx2-bx1)*(by2-by1); + int rem=(min(ax2,bx2)-max(ax1,bx1))*(min(ay2,by2)-max(ay1,by1)); + if(bx1>=ax2||by1>=ay2||bx2<=ax1||by2<=ay1)rem=0; + if(rem<0)rem=0; + return ans-rem; + } +}; +``` +### Python +```python +class Solution: + def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int: + a1=(ax2-ax1)*(ay2-ay1) + a2=(bx2-bx1)*(by2-by1) + x1=max(ax1,bx1) + x2=min(ax2,bx2) + y1=max(ay1,by1) + y2=min(ay2,by2) + if x2-x1<0 or y2-y1<0: #No intersection will occur if one of the side is negative + return a1+a2 + a3=(x2-x1)*(y2-y1) + return a1+a2-a3 +``` +### Complexity Analysis + +#### Time Complexity: O(1) +### Space Complexity: O(1) + diff --git a/solutions/lc-solutions/0200-0299/0224-Basic-Calculator.md b/solutions/lc-solutions/0200-0299/0224-Basic-Calculator.md new file mode 100644 index 0000000..4b911d9 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0224-Basic-Calculator.md @@ -0,0 +1,177 @@ +--- +id: basic-calculator +title: Basic Calculator +sidebar_label: 0224 Basic Calculator +tags: [Math, String, Stack, Recursion] +description: "This gives solution to the problem basic calculator" +--- + +## Problem + +Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. + +**Note:** You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`. + +### Examples + +**Example 1:** + +**Input:** `s = "1 + 1"` +**Output:** `2` + +**Example 2:** + +**Input:** `s = " 2-1 + 2 "` +**Output:** `3` + +**Example 3:** + +**Input:** `s = "(1+(4+5+2)-3)+(6+8)"` +**Output:** `23` + +### Constraints + +- $1 \leq s.length \leq 3 \times 10^5$ +- `s` consists of digits, '+', '-', '(', ')', and ' '. +- `s` represents a valid expression. +- `'+'` is not used as a unary operation (i.e., `"+1"` and `"+(2 + 3)"` are invalid). +- `'-'` could be used as a unary operation (i.e., `"-1"` and `"-(2 + 3)"` are valid). +- There will be no two consecutive operators in the input. +- Every number and running calculation will fit in a signed 32-bit integer. + +--- + +## Approach +The code employs a stack-based approach to parse and evaluate arithmetic expressions. It iterates through each character of the input string, updating the current number and result based on encountered digits, operators, and parentheses. It utilizes a stack to handle nested expressions, pushing and popping intermediate results and signs as needed. Finally, it returns the evaluated result, assuming a valid input expression. + +### Solution + +#### C++ Solution + +```cpp +#include +#include +#include +int calculate(char* s) { + int stack[1000]; + int top = -1; + int num = 0; + int sign = 1; + int result = 0; + while (*s) { + if (isdigit(*s)) { + num = num * 10 + (*s - '0'); + } else if (*s == '+') { + result += sign * num; + num = 0; + sign = 1; + } else if (*s == '-') { + result += sign * num; + num = 0; + sign = -1; + } else if (*s == '(') { + stack[++top] = result; + stack[++top] = sign; + result = 0; + sign = 1; + } else if (*s == ')') { + result += sign * num; + num = 0; + result *= stack[top--]; + result += stack[top--]; + } + s++; + } + return result + sign * num; +} +``` + +#### Java Solution + +```java +public int calculate(String s) { + Stack stack = new Stack(); + int result = 0; + int number = 0; + int sign = 1; + for(int i = 0; i < s.length(); i++){ + char c = s.charAt(i); + if(Character.isDigit(c)){ + number = 10 * number + (int)(c - '0'); + }else if(c == '+'){ + result += sign * number; + number = 0; + sign = 1; + }else if(c == '-'){ + result += sign * number; + number = 0; + sign = -1; + }else if(c == '('){ + stack.push(result); + stack.push(sign); + sign = 1; + result = 0; + }else if(c == ')'){ + result += sign * number; + number = 0; + result *= stack.pop(); + result += stack.pop(); + } + } + if(number != 0) result += sign * number; + return result; +} +``` + +#### Python Solution + +```python +class Solution: + def calculate(self, s: str) -> int: + stack = deque() + current_num = 0 + operator = 1 + n = len(s) + result = 0 + for i, char in enumerate(s): + if char.isdigit(): + current_num = (current_num*10) + int(char) + if char in "+-()" or i==n-1: + if operator == 1: + result+=current_num + elif operator == -1: + result-=current_num + if char == '(': + stack.append(result) + stack.append(operator) + operator = 1 + result=0 + elif char == ')': + sign = stack.pop() + first_arg = stack.pop() + result = first_arg + result * sign + + current_num = 0 + if char == '+': + operator = 1 + elif char == '-': + operator = -1 + + return result +``` + +### Complexity Analysis + +**Time Complexity:** $O(N)$ +:::tip Reason: +We perform a single pass through the string `s`, iterating over each character exactly once, resulting in linear time complexity. +::: + +**Space Complexity:** $O(N)$ +:::tip Reason: +The extra space used is mainly for the stack, which can store at most all the numbers and operators from the string `s` if they are all parentheses, leading to linear space complexity. +::: + +:::note +This solution efficiently calculates the result of the given expression by handling parentheses, addition, and subtraction. The time complexity is linear due to a single pass through the string, and the space complexity is linear due to the use of a stack to handle nested parentheses. +::: diff --git a/solutions/lc-solutions/0200-0299/0225-Implement-Stack-using-Queues.md b/solutions/lc-solutions/0200-0299/0225-Implement-Stack-using-Queues.md new file mode 100644 index 0000000..0e798ef --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0225-Implement-Stack-using-Queues.md @@ -0,0 +1,290 @@ +--- +id: implement-stack-using-queues +title: Implement Stack using Queues +sidebar_label: 0225 Implement Stack using Queues +tags: + - Stack + - Design + - Queue +description: "This is a solution to the Implement Stack using Queues problem on LeetCode." +--- + +## Problem + +Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`). + +Implement the `MyStack` class: + +- `void push(int x)` Pushes element x to the top of the stack. +- `int pop()` Removes the element on the top of the stack and returns it. +- `int top()` Returns the element on the top of the stack. +- `boolean empty()` Returns true if the stack is empty, false otherwise. + +:::note +- You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size, and is empty operations are valid. +- Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. +::: + +### Examples + +**Example 1:** + +Input +``` +["MyStack", "push", "push", "top", "pop", "empty"] +[[], [1], [2], [], [], []] +``` +Output +``` +[null, null, null, 2, 2, false] +``` +Explanation +``` +MyStack myStack = new MyStack(); +myStack.push(1); +myStack.push(2); +myStack.top(); // return 2 +myStack.pop(); // return 2 +myStack.empty(); // return False +``` + +### Constraints + +- $1 \leq x \leq 9$ +- At most 100 calls will be made to `push`, `pop`, `top`, and `empty`. +- All the calls to `pop` and `top` are valid. + +--- + +## Solution + +## Intuition + +For both approaches, the goal is to simulate a stack using queues. + +### Approach 1 (Using 2 queues) + +We maintain two queues, `que1` and `que2`. + +- **Push:** When pushing a new element, we push it onto `que2` and then move all elements from `que1` to `que2`, effectively making the newly pushed element at the front of `que2`. Then, we swap the names of `que1` and `que2`. +- **Pop, Top, and Empty:** Operations are straightforward, as they directly operate on `que1`. + +### Approach 2 (Using 1 queue) + +We maintain a single queue, `que`. + +- **Push:** When pushing a new element, we first push it onto the queue. Then, we rotate the queue by pushing and popping elements until the newly pushed element becomes the front. +- **Pop, Top, and Empty:** Operations are straightforward, as they directly operate on the single queue. + +### Complexity + +- **Time complexity:** + - **Approach 1 (Using 2 queues):** + - Push: $O(n)$ - Moving all elements from one queue to another. + - Pop, Top, Empty: $O(1)$ + - **Approach 2 (Using 1 queue):** + - Push: $O(n)$ - Rotating the queue to bring the newly pushed element to the front. + - Pop, Top, Empty: $O(1)$ + +- **Space complexity:** Both approaches have a space complexity of $O(n)$ to store the elements in the queue(s). + +### Code + +#### Using 2 queues + +```cpp +class MyStack { +public: + queue que1; + queue que2; + + MyStack() {} + + void push(int x) { + que2.push(x); + + while(!que1.empty()){ + que2.push(que1.front()); + que1.pop(); + } + + swap(que1, que2); + } + + int pop() { + int result = que1.front(); + que1.pop(); + + return result; + } + + int top() { + return que1.front(); + } + + bool empty() { + return que1.empty(); + } +}; +``` + +#### Using 1 queue + +```cpp +class MyStack { +public: + queue que; + + MyStack() {} + + void push(int x) { + que.push(x); + int n = que.size(); + + for(int i=0; i que1; + Queue que2; + + public MyStack() { + que1 = new LinkedList<>(); + que2 = new LinkedList<>(); + } + + public void push(int x) { + que2.add(x); + + while (!que1.isEmpty()) { + que2.add(que1.remove()); + } + + Queue temp = que1; + que1 = que2; + que2 = temp; + } + + public int pop() { + return que1.remove(); + } + + public int top() { + return que1.peek(); + } + + public boolean empty() { + return que1.isEmpty(); + } +} +``` + +#### Using 1 queue + +```java +class MyStack { + Queue que; + + public MyStack() { + que = new LinkedList<>(); + } + + public void push(int x) { + que.add(x); + int size = que.size(); + + for (int i = 0; i < size - 1; i++) { + que.add(que.remove()); + } + } + + public int pop() { + return que.remove(); + } + + public int top() { + return que.peek(); + } + + public boolean empty() { + return que.isEmpty(); + } +} +``` + +#### Using 2 queues (Python) + +```python +from queue import Queue + +class MyStack: + def __init__(self): + self.que1 = Queue() + self.que2 = Queue() + + def push(self, x: int) -> None: + self.que2.put(x) + + while not self.que1.empty(): + self.que2.put(self.que1.get()) + + self.que1, self.que2 = self.que2, self.que1 + + def pop(self) -> int: + return self.que1.get() + + def top(self) -> int: + return self.que1.queue[0] + + def empty(self) -> bool: + return self.que1.empty() +``` + +#### Using 1 queue (Python) + +```python +from queue import Queue + +class MyStack: + def __init__(self): + self.que = Queue() + + def push(self, x: int) -> None: + self.que.put(x) + n = self.que.qsize() + + for _ in range(n - 1): + self.que.put(self.que.get()) + + def pop(self) -> int: + return self.que.get() + + def top(self) -> int: + return self.que.queue[0] + + def empty(self) -> bool: + return self.que.empty() +``` diff --git a/solutions/lc-solutions/0200-0299/0226-invert-binary-search-tree.md b/solutions/lc-solutions/0200-0299/0226-invert-binary-search-tree.md new file mode 100644 index 0000000..82d145f --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0226-invert-binary-search-tree.md @@ -0,0 +1,83 @@ +--- +id: invert-binary-search-tree +title: Invert Binary Search Tree +sidebar_label: 0226 Invert Binary Search Tree +tags: + - tree + - recursion + - LeetCode + - C++ +description: "This is a solution to the Invert Binary Search Tree problem on LeetCode." +--- + +## Problem Description + +Given the root of a binary tree, invert the tree, and return its root. + +### Examples + +**Example 1:** + +``` + +Input: root = [4,2,7,1,3,6,9] +Output: [4,7,2,9,6,3,1] +``` + +**Example 2:** + +``` +Input: root = [2,1,3] +Output: [2,3,1] +``` + +``` +Input: root = [] +Output: [] +``` + +### Constraints + +- The number of nodes in the tree is in the range $[0, 100]$. +- $-100 \leq \text{Node.val} \leq 100$ + +### Approach + +To solve this problem(invert BST) we will use recursion(call function repeatedly) and temporary tree node(t) for swapping. + +#### Code in C++ + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + void invert(TreeNode* root){ + if(root==NULL){ + return; + } + TreeNode* t; + t=root->right; + root->right=root->left; + root->left=t; + invert(root->left); + invert(root->right); + } + TreeNode* invertTree(TreeNode* root) { + invert(root); + return root; + + } +}; +``` + + diff --git a/solutions/lc-solutions/0200-0299/0227-Basic-Calculator-II.md b/solutions/lc-solutions/0200-0299/0227-Basic-Calculator-II.md new file mode 100644 index 0000000..70fbc7b --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0227-Basic-Calculator-II.md @@ -0,0 +1,213 @@ +--- +id: basic-calculator-II +title: Basic Calculator II +sidebar_label: 0227 Basic Calculator II +tags: [Math, String, Stack] +description: "This gives solution to the problem basic calculator II" +--- + +## Problem + +Given a string s which represents an expression, evaluate this expression and return its value. + +The integer division should truncate toward zero. + +You may assume that the given expression is always valid. All intermediate results will be in the range of [-2^31, 2^31 - 1]. + +Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval(). + +### Examples + +**Example 1:** + +**Input:** `s = "3+2*2"` +**Output:** `7` + +**Example 2:** + +**Input:** `s = "3/2"` +**Output:** `1` + +**Example 3:** + +**Input:** `s = "3+5 / 2"` +**Output:** `5` + +--- + +### Constraints + +- $1 \leq s.length \leq 3 \times 10^5$ +- `s` consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces. +- `s` represents a valid expression. +- All the integers in the expression are non-negative integers in the range [0, 2^31 - 1]. +- The answer is guaranteed to fit in a 32-bit integer. + +--- + +### Approach + +1. **Iterate through the input string**: The code goes through each character in the input string one by one. + +2. **If char of string is number (`isdigit(c)`)**: When it encounters a digit character, convert `char` (which is initially initialized) to its numeric value. + +3. **Handle operators**: When it encounters an operator (`+`, `-`, `*`, `/`) or reaches the end of a number, it performs the operation based on the last operator seen and the number. + +4. **Use a stack for intermediate results**: The code utilizes a stack data structure to store intermediate results as it processes the expression. This allows it to maintain the correct order of operations. + +5. **Return the final result**: After processing all characters in the string and evaluating the expression, the code returns the final result by summing up all the values stored in the stack. + +--- + +### Solution + +#### C++ Solution + +```cpp +class Solution { +public: + int calculate(string s) { + int num=0; + char opr='+'; + stackst; + + for(int i=0;i **Reason:** The algorithm processes each character of the input string twice. The first pass converts the infix expression to a postfix expression using a stack for operators, and the second pass evaluates the postfix expression. Both passes together result in a linear time complexity relative to the length of the string. + +**Space Complexity:** $O(N)$ +> **Reason:** The algorithm uses additional space for the operator stack during the conversion to postfix notation and the number stack during the evaluation of the postfix expression. Both of these stacks can grow up to the size of the input string, leading to linear space complexity. diff --git a/solutions/lc-solutions/0200-0299/0228-summary-ranges.md b/solutions/lc-solutions/0200-0299/0228-summary-ranges.md new file mode 100644 index 0000000..4681b7e --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0228-summary-ranges.md @@ -0,0 +1,215 @@ +--- +id: summary-ranges +title: Summary Ranges +difficulty: Easy +sidebar_label: 0228-Summary-Ranges +tags: + - Array + - LeetCode Easy +--- + +## Problem Description +You are given a sorted unique integer array `nums`. + +A range `[a,b]` is the smallest interval that covers all the numbers in the array between `a` and `b` (including `a` and `b`). + +Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`. + +### Example +**Example 1:** +```plaintext +Input: nums = [0,1,2,4,5,7] +Output: ["0->2","4->5","7"] +Explanation: The ranges are: +[0,2] --> "0->2" +[4,5] --> "4->5" +[7,7] --> "7" +``` + +**Example 2:** +```plaintext +Input: nums = [0,2,3,4,6,8,9] +Output: ["0","2->4","6","8->9"] +Explanation: The ranges are: +[0,0] --> "0" +[2,4] --> "2->4" +[6,6] --> "6" +[8,9] --> "8->9" +``` + +### Constraints +- `0 <= nums.length <= 20` +- `-2^31 <= nums[i] <= 2^31 - 1` +- All the values of `nums` are unique. +- `nums` is sorted in ascending order. + +## Solution Approach + +### Approach Overview +The problem can be solved by iterating through the array and keeping track of the start and end of each range. Whenever a break in the sequence is found, the current range is added to the result list, and a new range is started. + +### Detailed Steps + +1. **Initialize Variables**: + - Use a list to store the result ranges. + - Use two variables to keep track of the start and end of the current range. + +2. **Iterate through the Array**: + - For each number, check if it continues the current range. + - If it doesn't, add the current range to the result and start a new range. + +3. **Add the Last Range**: + - After the loop, add the final range to the result list. + +4. **Format the Range**: + - Use a specific format for single numbers and ranges (`"a"` for single numbers and `"a->b"` for ranges). + +## Code Examples + +### C++ +```cpp +class Solution { +public: + vector summaryRanges(vector& nums) { + vector result; + if (nums.empty()) return result; + + int start = nums[0], end = nums[0]; + + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] == end + 1) { + end = nums[i]; + } else { + if (start == end) { + result.push_back(to_string(start)); + } else { + result.push_back(to_string(start) + "->" + to_string(end)); + } + start = end = nums[i]; + } + } + + if (start == end) { + result.push_back(to_string(start)); + } else { + result.push_back(to_string(start) + "->" + to_string(end)); + } + + return result; + } +}; +``` + +### Python +```python +class Solution: + def summaryRanges(self, nums: List[int]) -> List[str]: + result = [] + if not nums: + return result + + start = end = nums[0] + + for num in nums[1:]: + if num == end + 1: + end = num + else: + if start == end: + result.append(str(start)) + else: + result.append(f"{start}->{end}") + start = end = num + + if start == end: + result.append(str(start)) + else: + result.append(f"{start}->{end}") + + return result +``` + +### Java +```java +class Solution { + public List summaryRanges(int[] nums) { + List result = new ArrayList<>(); + if (nums.length == 0) return result; + + int start = nums[0], end = nums[0]; + + for (int i = 1; i < nums.length; i++) { + if (nums[i] == end + 1) { + end = nums[i]; + } else { + if (start == end) { + result.add(String.valueOf(start)); + } else { + result.add(start + "->" + end); + } + start = end = nums[i]; + } + } + + if (start == end) { + result.add(String.valueOf(start)); + } else { + result.add(start + "->" + end); + } + + return result; + } +} +``` + +### C +```c +#include +#include + +// Helper function to convert an integer to a string +char* intToStr(int num) { + char* str = (char*)malloc(12 * sizeof(char)); // Max length for an int in C + sprintf(str, "%d", num); + return str; +} + +char ** summaryRanges(int* nums, int numsSize, int* returnSize){ + char **result = (char **)malloc(numsSize * sizeof(char *)); + *returnSize = 0; + + if (numsSize == 0) return result; + + int start = nums[0], end = nums[0]; + + for (int i = 1; i < numsSize; i++) { + if (nums[i] == end + 1) { + end = nums[i]; + } else { + if (start == end) { + result[*returnSize] = intToStr(start); + } else { + result[*returnSize] = (char *)malloc(25 * sizeof(char)); + sprintf(result[*returnSize], "%d->%d", start, end); + } + (*returnSize)++; + start = end = nums[i]; + } + } + + if (start == end) { + result[*returnSize] = intToStr(start); + } else { + result[*returnSize] = (char *)malloc(25 * sizeof(char)); + sprintf(result[*returnSize], "%d->%d", start, end); + } + (*returnSize)++; + + return result; +} +``` + +## Complexity + +- **Time Complexity**: `O(n)`, where `n` is the length of the array. We traverse the array once to identify ranges. + +- **Space Complexity**: `O(1)` (excluding the space required for the result), as no additional space proportional to the input size is used. diff --git a/solutions/lc-solutions/0200-0299/0229-Majority-Element.md b/solutions/lc-solutions/0200-0299/0229-Majority-Element.md new file mode 100644 index 0000000..206e50f --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0229-Majority-Element.md @@ -0,0 +1,215 @@ +--- +id: majority-element-II +title: Majority Element II +sidebar_label: 0229-Majority-Element-II +tags: +- Arrays +- Counting +- C++ +- Java +- Python +description: "This document provides a solution to the Majority Element II problem, where we need to find all elements that appear more than ⌊ n/3 βŒ‹ times." +--- + +## Problem + +Given an integer array of size n, find all elements that appear more than ⌊ n/3 βŒ‹ times. + +### Examples + +**Example 1:** + +Input: nums = [3,2,3] +Output: [3] + +**Example 2:** + +Input: nums = [1] +Output: [1] + +**Example 3:** + +Input: nums = [1,2] +Output: [1,2] + +### Constraints + +- `1 <= nums.length <= 5 * 10^4` +- `-10^9 <= nums[i] <= 10^9` +### Approach + +To solve this problem, we can use the Boyer-Moore Voting Algorithm, which efficiently finds the majority elements in linear time and constant space. The algorithm can be summarized in the following steps: + +1. **First Pass**: + - Use two counters and two candidate variables to identify the potential majority elements. + - Iterate through the array, updating the candidates and their counts accordingly. + +2. **Second Pass**: + - Verify the candidates by counting their occurrences in the array. + +### Solution + +#### Code in Different Languages + +### C++ Solution +```cpp +#include +#include + +using namespace std; + +vector majorityElement(vector& nums) { + int n = nums.size(); + if (n == 0) return {}; + + int candidate1 = 0, candidate2 = 1, count1 = 0, count2 = 0; + + // First pass to find potential candidates + for (int num : nums) { + if (num == candidate1) { + count1++; + } else if (num == candidate2) { + count2++; + } else if (count1 == 0) { + candidate1 = num; + count1 = 1; + } else if (count2 == 0) { + candidate2 = num; + count2 = 1; + } else { + count1--; + count2--; + } + } + + // Second pass to confirm the candidates + count1 = count2 = 0; + for (int num : nums) { + if (num == candidate1) count1++; + if (num == candidate2) count2++; + } + + vector result; + if (count1 > n / 3) result.push_back(candidate1); + if (count2 > n / 3) result.push_back(candidate2); + + return result; +} + +int main() { + vector nums = {3,2,3}; + vector result = majorityElement(nums); + for (int num : result) { + cout << num << " "; + } +} +``` +### Java Solution +```java +import java.util.*; + +public class MajorityElementII { + public static List majorityElement(int[] nums) { + int n = nums.length; + if (n == 0) return Collections.emptyList(); + + int candidate1 = 0, candidate2 = 1, count1 = 0, count2 = 0; + + // First pass to find potential candidates + for (int num : nums) { + if (num == candidate1) { + count1++; + } else if (num == candidate2) { + count2++; + } else if (count1 == 0) { + candidate1 = num; + count1 = 1; + } else if (count2 == 0) { + candidate2 = num; + count2 = 1; + } else { + count1--; + count2--; + } + } + + // Second pass to confirm the candidates + count1 = count2 = 0; + for (int num : nums) { + if (num == candidate1) count1++; + if (num == candidate2) count2++; + } + + List result = new ArrayList<>(); + if (count1 > n / 3) result.add(candidate1); + if (count2 > n / 3) result.add(candidate2); + + return result; + } + + public static void main(String[] args) { + int[] nums = {3, 2, 3}; + List result = majorityElement(nums); + System.out.println(result); + } +} +``` +### Python Solution + +```python +def majorityElement(nums): + n = len(nums) + if n == 0: + return [] + + candidate1, candidate2, count1, count2 = 0, 1, 0, 0 + + # First pass to find potential candidates + for num in nums: + if num == candidate1: + count1 += 1 + elif num == candidate2: + count2 += 1 + elif count1 == 0: + candidate1 = num + count1 = 1 + elif count2 == 0: + candidate2 = num + count2 = 1 + else: + count1 -= 1 + count2 -= 1 + + # Second pass to confirm the candidates + count1, count2 = 0, 0 + for num in nums: + if num == candidate1: + count1 += 1 + elif num == candidate2: + count2 += 1 + + result = [] + if count1 > n / 3: + result.append(candidate1) + if count2 > n / 3: + result.append(candidate2) + + return result + +nums = [3, 2, 3] +print(majorityElement(nums)) +``` + +### Complexity Analysis + +### Time Complexity: O(N) +>Reason: We perform two passes through the array, each requiring linear time. + +**Space Complexity:** O(1) +>Reason: We use a constant amount of extra space for counters and candidates. + +>This solution efficiently finds all elements that appear more than ⌊ n/3 βŒ‹ times using the Boyer-Moore Voting Algorithm. The time complexity is linear, and the space complexity is constant, making it suitable for large input sizes. + +#### References +**LeetCode Problem:** Majority Element II +**Authors GeeksforGeeks Profile:** Vipul lakum diff --git a/solutions/lc-solutions/0200-0299/0230-Kth-smallest-element-in-BST.md b/solutions/lc-solutions/0200-0299/0230-Kth-smallest-element-in-BST.md new file mode 100644 index 0000000..725f40e --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0230-Kth-smallest-element-in-BST.md @@ -0,0 +1,78 @@ +--- +id: kth-smallest-element-in-binary-search-tree +title: Kth Smallest Element in Binary Search Tree +sidebar_label: 0230 Kth Smallest Element in Binary Search Tree +tags: + - tree + - tree traversal + - LeetCode + - C++ +description: "This is a solution to theKth Smallest Element in Binary Search Tree problem on LeetCode." +--- + +## Problem Description + +Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree. + +### Examples + +**Example 1:** + +``` + +Input: root = [3,1,4,null,2], k = 1 +Output: 1 +``` + +**Example 2:** + +``` +Input: root = [5,3,6,2,4,null,null,1], k = 3 +Output: 3 +``` + +### Constraints + +- The number of nodes in the tree is n. +- $1 \leq \text{k} \leq \text{n} \leq 10^4$ +- $1 \leq k \leq n \leq 10^4$ + +### Approach + +To solve this problem(Kth smallest element in BST) we will do the inorder traversal of the tree as we know in a binary search tree the array of elements which we get after inorder traversal they will be in sorted order so the kth smallest element in the given BST will be the kth index(1-indexed) element in inorder traversal of the BST. + +#### Code in C++ + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + // Function for inorder traversal + void inorder(TreeNode* root,vector&a){ + if(root==NULL){ + return; + } + inorder(root->left,a); + a.push_back(root->val); + inorder(root->right,a); + } + // Function to get the kth smallest element + int kthSmallest(TreeNode* root, int k) { + vectora; + inorder(root,a); + return a[k-1]; // as 0-indexed + } +}; +``` + + diff --git a/solutions/lc-solutions/0200-0299/0231-power-of-two.md b/solutions/lc-solutions/0200-0299/0231-power-of-two.md new file mode 100644 index 0000000..b9db897 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0231-power-of-two.md @@ -0,0 +1,121 @@ +--- + +id: power-of-two +title: Power of Two +difficulty: Easy +sidebar_label: 0231-Power-of-Two +tags: + - Math + - Bit Manipulation + - LeetCode Easy +--- + +## Problem Description +Given an integer `n`, return `true` if it is a power of two. Otherwise, return `false`. + +An integer `n` is a power of two if there exists an integer `x` such that `n == 2^x`. + +### Example +**Example 1:** +```plaintext +Input: n = 1 +Output: true +Explanation: 2^0 = 1 +``` + +**Example 2:** +```plaintext +Input: n = 16 +Output: true +Explanation: 2^4 = 16 +``` + +**Example 3:** +```plaintext +Input: n = 3 +Output: false +``` + +**Example 4:** +```plaintext +Input: n = 4 +Output: true +``` + +**Example 5:** +```plaintext +Input: n = 5 +Output: false +``` + +### Constraints +- `-2^31 <= n <= 2^31 - 1` + +## Solution Approach + +### Approach Overview +To determine if a number `n` is a power of two, we can use bit manipulation. A number is a power of two if it has exactly one `1` bit in its binary representation. For example: +- `2` in binary is `10` +- `4` in binary is `100` +- `8` in binary is `1000` + +If `n` is a power of two, `n & (n - 1)` should be `0`. This is because subtracting `1` from a power of two flips all bits after the rightmost `1` (including the rightmost `1` itself). + +### Detailed Steps +1. Check if `n` is greater than `0`. +2. Use the bitwise AND operation `n & (n - 1)`. +3. If the result is `0`, then `n` is a power of two. + +## Code Examples + +### C++ +```cpp +class Solution { +public: + bool isPowerOfTwo(int n) { + // A number n is a power of two if: + // 1. n is greater than 0 + // 2. n & (n - 1) is equal to 0 + return n > 0 && (n & (n - 1)) == 0; + } +}; +``` + +### Python +```python +class Solution: + def isPowerOfTwo(self, n: int) -> bool: + # A number n is a power of two if: + # 1. n is greater than 0 + # 2. n & (n - 1) is equal to 0 + return n > 0 and (n & (n - 1)) == 0 +``` + +### Java +```java +class Solution { + public boolean isPowerOfTwo(int n) { + // A number n is a power of two if: + // 1. n is greater than 0 + // 2. n & (n - 1) is equal to 0 + return n > 0 && (n & (n - 1)) == 0; + } +} +``` + +### C +```c +#include + +bool isPowerOfTwo(int n) { + // A number n is a power of two if: + // 1. n is greater than 0 + // 2. n & (n - 1) is equal to 0 + return n > 0 && (n & (n - 1)) == 0; +} +``` + +## Complexity + +- **Time Complexity**: `O(1)`, because the number of operations is constant and does not depend on the size of the input. +- **Space Complexity**: `O(1)`, because no additional space is used beyond a few integer variables. \ No newline at end of file diff --git a/solutions/lc-solutions/0200-0299/0232-Implement-Queue-using-Stack.md b/solutions/lc-solutions/0200-0299/0232-Implement-Queue-using-Stack.md new file mode 100644 index 0000000..5f4b7c1 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0232-Implement-Queue-using-Stack.md @@ -0,0 +1,227 @@ +--- +id: queue-using-stacks +title: Implement Queue using Stacks +sidebar_label: Implement Queue using Stacks +tags: +- Data Structures +- Stack +- Queue +- Python +- Java +- C++ +description: "This document provides an implementation of a queue using stacks, supporting push, pop, peek, and empty operations." +--- + +### Examples + +**Example 1:** + +``` + +Input +["MyQueue", "push", "push", "peek", "pop", "empty"] +[[], [1], [2], [], [], []] +Output +[null, null, null, 1, 1, false] + +Explanation +MyQueue myQueue = new MyQueue(); +myQueue.push(1); // queue is: [1] +myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) +myQueue.peek(); // return 1 +myQueue.pop(); // return 1, queue is [2] +myQueue.empty(); // return false +``` + +### Constraints + +- $1 <= x <= 9$ +- At most 100 calls will be made to push, pop, peek, and empty. +- All the calls to pop and peek are valid. + +## Problem Statement +Implement a first-in-first-out (FIFO) queue using two stacks. The implemented queue should support the following operations: +- `push(x)`: Pushes element `x` to the back of the queue. +- `pop()`: Removes the element from the front of the queue and returns it. +- `peek()`: Returns the element at the front of the queue without removing it. +- `empty()`: Returns whether the queue is empty. + +## Approach +To achieve FIFO order using stacks, we can use two stacks: +- `stack1`: Used for enqueue operations (`push`). +- `stack2`: Used for dequeue operations (`pop` and `peek`). + +### Operations Details: +1. **Push Operation (`push(x)`)**: + - Simply push the element onto `stack1`. + +2. **Pop Operation (`pop()`)**: + - If `stack2` is empty, transfer all elements from `stack1` to `stack2`. Then, pop the top element from `stack2`. + +3. **Peek Operation (`peek()`)**: + - If `stack2` is empty, transfer all elements from `stack1` to `stack2`. Then, peek at the top element of `stack2`. + +4. **Empty Check (`empty()`)**: + - The queue is considered empty if both `stack1` and `stack2` are empty. + +#### Code in Different Languages + + + + + ```python + + class MyQueue: + + def __init__(self): + self.stack1 = [] # Stack for enqueue operations + self.stack2 = [] # Stack for dequeue operations + + def push(self, x): + """ + Push element x to the back of the queue. + """ + self.stack1.append(x) + + def pop(self): + """ + Removes the element from the front of the queue and returns it. + """ + self.move_elements() + return self.stack2.pop() + + def peek(self): + """ + Returns the element at the front of the queue without removing it. + """ + self.move_elements() + return self.stack2[-1] + + def empty(self): + """ + Returns whether the queue is empty. + """ + return len(self.stack1) == 0 and len(self.stack2) == 0 + + def move_elements(self): + """ + Moves elements from stack1 to stack2 if stack2 is empty. + """ + if not self.stack2: + while self.stack1: + self.stack2.append(self.stack1.pop()) + + ``` + + + + ```java + + import java.util.Stack; + + class MyQueue { + private Stack stack1; + private Stack stack2; + + /** Initialize your data structure here. */ + public MyQueue() { + stack1 = new Stack<>(); + stack2 = new Stack<>(); + } + + /** Push element x to the back of queue. */ + public void push(int x) { + stack1.push(x); + } + + /** Removes the element from in front of queue and returns that element. */ + public int pop() { + moveElements(); + return stack2.pop(); + } + + /** Get the front element. */ + public int peek() { + moveElements(); + return stack2.peek(); + } + + /** Returns whether the queue is empty. */ + public boolean empty() { + return stack1.isEmpty() && stack2.isEmpty(); + } + + private void moveElements() { + if (stack2.isEmpty()) { + while (!stack1.isEmpty()) { + stack2.push(stack1.pop()); + } + } + } + } + + ``` + + + + ```cpp + + #include + + class MyQueue { + private: + std::stack stack1; + std::stack stack2; + + public: + /** Initialize your data structure here. */ + MyQueue() { + + } + + /** Push element x to the back of queue. */ + void push(int x) { + stack1.push(x); + } + + /** Removes the element from in front of queue and returns that element. */ + int pop() { + moveElements(); + int front = stack2.top(); + stack2.pop(); + return front; + } + + /** Get the front element. */ + int peek() { + moveElements(); + return stack2.top(); + } + + /** Returns whether the queue is empty. */ + bool empty() { + return stack1.empty() && stack2.empty(); + } + + private: + void moveElements() { + if (stack2.empty()) { + while (!stack1.empty()) { + stack2.push(stack1.top()); + stack1.pop(); + } + } + } + }; + + ``` + + + + + +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/implement-queue-using-stacks/) +- **Solution Link:** [Implement-Queue-Using-Stacks Solution on LeetCode](https://leetcode.com/problems/implement-queue-using-stacks/solutions/) +- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) diff --git a/solutions/lc-solutions/0200-0299/0233 - Number of Digit One.md b/solutions/lc-solutions/0200-0299/0233 - Number of Digit One.md new file mode 100644 index 0000000..991198e --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0233 - Number of Digit One.md @@ -0,0 +1,126 @@ +--- +id: number-of-digit-one +title: Number of Digit One +sidebar_label: 233 Number of Digit One +tags: +- Dynamic Programming +- Java +- Recursion +- Math +description: "This document provides a solution where we count the total number of digit $1$ appearing in all non-negative integers less than or equal to n." +--- + +## Problem + +Given an integer n, count the total number of $digit$ 1 appearing in all non-negative integers less than or equal to n. + +### Examples + +**Example 1:** + +``` +Input: n = 13 + +Output: 6 + +``` +**Example 2:** +``` +Input: n = 0 + +Output: 0 + +``` +### Constraints + +- `0 <= n <= 10^9` + +--- +## Approach +There are four approaches discussed that helps to obtain the solution: + +1. **Dynamic Programming Table**: + + - Initialize **'count'** to $0$, which will store the total count of $1's$. + + - Use **'factor'** to isolate each digit position, starting from the units place and moving to higher places (tens, hundreds, etc.). + +3. **Iterative Analysis**: + + - Loop through each digit position using **'factor'**, which starts from $1$ and increases by a factor of $10$ in each iteration. + + - For each position defined by **'factor'**, determine: + + - **'lowerNumbers'**: Numbers to the right of the current digit. + + - **'currentDigit'**: The digit at the current position. + + - **'higherNumbers'**: Numbers to the left of the current digit. + +3. **Count Calculation**: + + - If **'currentDigit'** is $0$, then the count of $1's$ contributed by the current digit position comes solely from higher numbers. + + - If **'currentDigit'** is $1$, it includes all $1's$ contributed by higher numbers, plus the $1's$ in the lower numbers up to **'lowerNumbers + 1'**. + + - If **'currentDigit'** is greater than $1$, it includes all $1's$ contributed by higher numbers and the full set of lower numbers for that digit position. + +4. **Result**: + + - Return the accumulated **'count'** after processing all digit positions. + +## Solution for Number of Digit One + +This problem can be solved using dynamic programming. The problem requires to count the total number of digit $1$ appearing in all non-negative integers less than or equal to n. + +#### Code in Java + + ```java +class Solution { + public int countDigitOne(int n) { + if (n <= 0) return 0; + + int count = 0; + for (long factor = 1; factor <= n; factor *= 10) { + long lowerNumbers = n - (n / factor) * factor; + long currentDigit = (n / factor) % 10; + long higherNumbers = n / (factor * 10); + + if (currentDigit == 0) { + count += higherNumbers * factor; + } else if (currentDigit == 1) { + count += higherNumbers * factor + lowerNumbers + 1; + } else { + count += (higherNumbers + 1) * factor; + } + } + + return count; + } + + public static void main(String[] args) { + Solution sol = new Solution(); + + // Test cases + System.out.println(sol.countDigitOne(13)); + System.out.println(sol.countDigitOne(0)); + } +} + +``` + +### Complexity Analysis + +#### Time Complexity: $O(log_{10} n)$ + +> **Reason**: The time complexity is $O(log_{10} n)$, because we are processing each digit position from the least significant to the most significant, and the number of digit positions is logarithmic relative to the input size. + +#### Space Complexity: $O(1)$ + +> **Reason**: The space complexity is $O(1)$, because we only use a constant amount of extra space regardless of the input size. + +# References + +- **LeetCode Problem:** [Number of Digit One](https://leetcode.com/problems/number-of-digit-one/description/) +- **Solution Link:** [Number of Digit One Solution on LeetCode](https://leetcode.com/problems/number-of-digit-one/solutions/) +- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/vivekvardhan43862/) diff --git a/solutions/lc-solutions/0200-0299/0234-palindrome-linked-list.md b/solutions/lc-solutions/0200-0299/0234-palindrome-linked-list.md new file mode 100644 index 0000000..b1b35c0 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0234-palindrome-linked-list.md @@ -0,0 +1,194 @@ +--- +id: palindrome-linked-list +title: Palindrome Linked List(LeetCode) +sidebar_label: 0234-Palindrome Linked List +tags: + - Linked List + - Two Pointer + - Stack + - Recursion +description: Given the head of a singly linked list, return true if it is a palindrome or false otherwise. +--- + +## Problem Statement + +Given the `head` of a singly linked list, return `true` if it is a palindrome or `false` otherwise. + +### Examples + +**Example 1:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/3912ff1d-6425-4b30-aa4c-94955c9ee9bd) + +```plaintext +Input: head = [1,2,2,1] +Output: true +``` + +**Example 2:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/429d0cde-46de-4c2d-af7a-dd69bda5c426) + +```plaintext +Input: head = [1,2] +Output: false +``` + +### Constraints + +- The number of nodes in the list is in the range `[1, 105]`. +- `0 <= Node.val <= 9` + +## Solution + +### Approach + +To check if a linked list is a palindrome using O(1) extra space, we can reverse the second half of the linked list and then compare it to the first half. The key steps involve: + +1. Finding the middle of the linked list. + + ![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/5bfdbfd5-0f6f-4040-a946-9820621e2910) + +2. Reversing the second half of the list. + + ![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/5a2e1fdb-d8ca-4842-8638-23a1f0d3e2d5) + +3. Comparing the two halves for equality. + + ![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/ce99042e-62e4-4bf5-92ec-2fb01db9fc2d) + +(Note: This process works regardless of whether the length of the linked list is odd or even, as the comparison will stop when slow reaches the "dead-end" node.) + + ![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/7f423edf-044a-40f4-bccf-d762d65a66a9) + +#### Algorithm + +1. Find the middle of the linked list: +* Use two pointers, `slow` and `fast`. Move `slow` by one step and `fast` by two steps in each iteration. When `fast` reaches the end, slow will be at the middle. +2. Reverse the second half: +* Starting from the middle node, reverse the direction of the `next` pointers for each node until the end of the list. +3. Compare the first and second halves: +* Initialize two pointers, one at the head and the other at the start of the reversed second half. +* Compare the values of the nodes pointed to by these pointers. If any values differ, the list is not a palindrome. If all values match, the list is a palindrome. + +#### Implementation + +Javascript Code: + +```Javascript +var isPalindrome = function(head) { + let slow = head, fast = head, prev = null, temp; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + prev = slow; + slow = slow.next; + prev.next = null; + while (slow) { + temp = slow.next; + slow.next = prev; + prev = slow; + slow = temp; + } + fast = head; + slow = prev; + while (slow) { + if (fast.val !== slow.val) return false; + fast = fast.next; + slow = slow.next; + } + return true; +}; +``` + +Python Code: + +```Python +class Solution: + def isPalindrome(self, head: ListNode) -> bool: + slow, fast, prev = head, head, None + while fast and fast.next: + slow, fast = slow.next, fast.next.next + prev, slow, prev.next = slow, slow.next, None + while slow: + slow.next, prev, slow = prev, slow, slow.next + fast, slow = head, prev + while slow: + if fast.val != slow.val: + return False + fast, slow = fast.next, slow.next + return True +``` + +Java Code: + +```Java +class Solution { + public boolean isPalindrome(ListNode head) { + ListNode slow = head, fast = head, prev = null, temp; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + prev = slow; + slow = slow.next; + prev.next = null; + while (slow != null) { + temp = slow.next; + slow.next = prev; + prev = slow; + slow = temp; + } + fast = head; + slow = prev; + while (slow != null) { + if (fast.val != slow.val) return false; + fast = fast.next; + slow = slow.next; + } + return true; + } +} +``` + +C++ Code: + +```C++ +class Solution { +public: + bool isPalindrome(ListNode* head) { + ListNode *slow = head, *fast = head, *prev = nullptr, *temp; + while (fast && fast->next) { + slow = slow->next; + fast = fast->next->next; + } + prev = slow; + slow = slow->next; + prev->next = NULL; + while (slow) { + temp = slow->next; + slow->next = prev; + prev = slow; + slow = temp; + } + fast = head; + slow = prev; + while (slow) { + if (fast->val != slow->val) return false; + fast = fast->next; + slow = slow->next; + } + return true; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: O(N) +- **Space complexity**: O(1) + +### Conclusion + +By using two pointers to find the middle, reversing the second half of the linked list, and then comparing the two halves, we can determine if a linked list is a palindrome with a time complexity of O(N) and a space complexity of O(1). This approach ensures we do not use extra space beyond the input list itself, meeting the problem's constraints. diff --git a/solutions/lc-solutions/0200-0299/0235-lowest-common-Ancestor-of-binary-search-tree.md b/solutions/lc-solutions/0200-0299/0235-lowest-common-Ancestor-of-binary-search-tree.md new file mode 100644 index 0000000..a83c287 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0235-lowest-common-Ancestor-of-binary-search-tree.md @@ -0,0 +1,165 @@ +--- +id: lowest-common-ancestor-of-a-binary-search-tree. +title: Lowest Common Ancestor of a Binary Search Tree. +sidebar_label: 235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree +tags: +- Binary Search Tree +- Tree +- Depth-First Search +- Binary Tree +description: "Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST." +--- + +## Problem + +Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST. + +According to the definition of LCA on Wikipedia: β€œThe lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” + +### Examples + +**Example 1:** + +![image](https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png) + +**Input:** `root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8` +**Output:** `6` +**Explanation:** The LCA of nodes 2 and 8 is 6. + +**Example 2:** + +![image](https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png) + +**Input:** `root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4` +**Output:** `2` +**Explanation:** The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. + +**Example 3:** + +**Input:** `root = [2,1], p = 2, q = 1` +**Output:** `2` + +### Constraints + +- The number of nodes in the tree is in the range `[2, 10^5]`. +- `-10^9 <= Node.val <= 10^9` +- All `Node.val` are unique. +- `p != q` +- `p` and `q` will exist in the BST. + +--- + +## Approach + +To find the lowest common ancestor in a Binary Search Tree (BST), we can utilize the properties of the BST. The left subtree of a node contains only nodes with values less than the node's value, and the right subtree contains only nodes with values greater than the node's value. + +### Steps: + +1. **Start from the Root:** Begin the search from the root node of the BST. +2. **Value Comparison:** + - If both `p` and `q` are smaller than the current node's value, move to the left child. + - If both `p` and `q` are greater than the current node's value, move to the right child. + - If `p` and `q` lie on either side of the current node, or one of them is the current node, then the current node is their LCA. + +### Solution + +#### Java + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + while (root != null) { + // If both p and q are lesser than root, LCA must be in the left subtree + if (p.val < root.val && q.val < root.val) { + root = root.left; + } + // If both p and q are greater than root, LCA must be in the right subtree + else if (p.val > root.val && q.val > root.val) { + root = root.right; + } + // If p and q lie on either side of root, or one of them is the root, then root is the LCA + else { + return root; + } + } + return null; + } +} +``` +#### CPP +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + while (root != nullptr) { + // If both p and q are lesser than root, LCA must be in the left subtree + if (p->val < root->val && q->val < root->val) { + root = root->left; + } + // If both p and q are greater than root, LCA must be in the right subtree + else if (p->val > root->val && q->val > root->val) { + root = root->right; + } + // If p and q lie on either side of root, or one of them is the root, then root is the LCA + else { + return root; + } + } + return nullptr; + } +}; +``` +### Python +```python +# Definition for a binary tree node. +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None + +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + while root: + # If both p and q are lesser than root, LCA must be in the left subtree + if p.val < root.val and q.val < root.val: + root = root.left + # If both p and q are greater than root, LCA must be in the right subtree + elif p.val > root.val and q.val > root.val: + root = root.right + # If p and q lie on either side of root, or one of them is the root, then root is the LCA + else: + return root + return None +``` + +### Complexity Analysis +#### Time Complexity: O(h) + +**Reason**: The algorithm may traverse the height h of the tree. In the worst case, this is O(log n) for a balanced BST and O(n) for a skewed BST. +Space Complexity: O(1) + +**Reason**: The algorithm uses constant space. +#### References +**LeetCode Problem** : Lowest Common Ancestor of a Binary Search Tree +**Solution Link**: LCA Solution on LeetCode + +**Wikipedia Definition**: Lowest Common Ancestor diff --git a/solutions/lc-solutions/0200-0299/0236-Lowest-Common-Ancestor-of-a-Binary-Tree.md b/solutions/lc-solutions/0200-0299/0236-Lowest-Common-Ancestor-of-a-Binary-Tree.md new file mode 100644 index 0000000..51280ff --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0236-Lowest-Common-Ancestor-of-a-Binary-Tree.md @@ -0,0 +1,146 @@ +--- +id: lowest-common-ancestor-of-a-binary-tree +title: Lowest Common Ancestor of a Binary Tree +sidebar_label: 0236-Lowest-Common-Ancestor-of-a-Binary-Tree +tags: +- Tree +- Depth-First Search +- Binary Tree +description: "Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree." +--- + +## Problem + +Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. + +According to the definition of LCA on Wikipedia: β€œThe lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” + +### Examples + +**Example 1:** + +**Input:** `root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1` +**Output:** `3` +**Explanation:** The LCA of nodes 5 and 1 is 3. + +**Example 2:** + +**Input:** `root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4` +**Output:** `5` +**Explanation:** The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. + +**Example 3:** + +**Input:** `root = [1,2], p = 1, q = 2` +**Output:** `1` + +### Constraints + +- The number of nodes in the tree is in the range `[2, 10^5]`. +- `-10^9 <= Node.val <= 10^9` +- All `Node.val` are unique. +- `p != q` +- `p` and `q` will exist in the tree. + +--- + +## Approach + +To find the lowest common ancestor in a binary tree, we can use a recursive depth-first search (DFS) approach. The idea is to traverse the tree starting from the root. If we find either of the nodes `p` or `q`, we return that node. If both nodes are found in different subtrees of a node, then that node is their lowest common ancestor. + +### Steps: + +1. **Base Case:** If the current node is `null` or matches `p` or `q`, return the current node. +2. **Recursive Search:** + - Recursively search the left subtree for `p` and `q`. + - Recursively search the right subtree for `p` and `q`. +3. **Determine LCA:** + - If both left and right recursive calls return non-null, the current node is the LCA. + - If only one of the recursive calls returns non-null, that means both nodes are located in the same subtree, so return the non-null result. + +### Solution + +#### Java + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root == null || root == p || root == q) { + return root; + } + TreeNode left = lowestCommonAncestor(root.left, p, q); + TreeNode right = lowestCommonAncestor(root.right, p, q); + if (left != null && right != null) { + return root; + } + return left != null ? left : right; + } +} +``` +### C++ +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (root == nullptr || root == p || root == q) { + return root; + } + TreeNode* left = lowestCommonAncestor(root->left, p, q); + TreeNode* right = lowestCommonAncestor(root->right, p, q); + if (left != nullptr && right != nullptr) { + return root; + } + return left != nullptr ? left : right; + } +}; +``` +### Python +``` +# Definition for a binary tree node. +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None + +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + if not root or root == p or root == q: + return root + left = self.lowestCommonAncestor(root.left, p, q) + right = self.lowestCommonAncestor(root.right, p, q) + if left and right: + return root + return left if left else right +``` +### Complexity Analysis +#### Time Complexity: O(n) + +**Reason:** The algorithm visits each node in the tree once, where n is the number of nodes in the tree. +Space Complexity: O(h) + +**Reason:** The space complexity is determined by the height h of the tree due to the recursion stack. In the worst case, the height of the tree is O(n) for a skewed tree, but O(log n) for a balanced tree. + +### References +**LeetCode Problem:** Lowest Common Ancestor of a Binary Tree + +**Solution Link:** LCA Solution on LeetCode +**Wikipedia Definition:** Lowest Common Ancestor diff --git a/solutions/lc-solutions/0200-0299/0237-Delete-Node-in-a-Linked-List.md b/solutions/lc-solutions/0200-0299/0237-Delete-Node-in-a-Linked-List.md new file mode 100644 index 0000000..1649d9b --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0237-Delete-Node-in-a-Linked-List.md @@ -0,0 +1,170 @@ +--- +id: delete-node-in-a-linked-list +title: Delete Node in a Linked List +sidebar_label: 0237-Delete-Node-in-a-Linked-List +tags: + - Linked List + - C++ + - Java + - Python +description: "This document provides a solution to the Delete Node in a Linked List problem, where we need to delete a given node from a singly linked list." +--- + +## Problem + +Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly. + +It is guaranteed that the node to be deleted is not a tail node in the list. + +All the values of the linked list are unique, and it is guaranteed that the given node node is not the last node in the linked list. + +Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: + +- The value of the given node should not exist in the linked list. +- The number of nodes in the linked list should decrease by one. +- All the values before node should be in the same order. +- All the values after node should be in the same order. + +### Custom testing: + +- For the input, you should provide the entire linked list head and the node to be given node. node should not be the last node of the list and should be an actual node in the list. +- We will build the linked list and pass the node to your function. +- The output will be the entire list after calling your function. + +### Examples + +**Example 1:** + +Input: head = [4,5,1,9], node = 5 +Output: [4,1,9] +Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. + +**Example 2:** + +Input: head = [4,5,1,9], node = 1 +Output: [4,5,9] +Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. + +### Constraints + +- The number of nodes in the list is in the range `[2, 1000]`. +- `-1000 <= Node.val <= 1000` +- The value of each node in the list is unique. +- The `node` to be deleted is in the list and is not a tail node. + +### Approach + +Since we do not have access to the head of the list, we cannot use the standard deletion method. Instead, we can solve the problem by copying the value of the next node to the current node and then deleting the next node. This effectively removes the node from the list. + +### Solution + +#### Code in Different Languages + +### C++ Solution +```cpp +#include + +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +void deleteNode(ListNode* node) { + if (node == nullptr || node->next == nullptr) return; + ListNode* next_node = node->next; + node->val = next_node->val; + node->next = next_node->next; + delete next_node; +} + +int main() { + ListNode* head = new ListNode(4); + head->next = new ListNode(5); + head->next->next = new ListNode(1); + head->next->next->next = new ListNode(9); + + deleteNode(head->next); // Deletes node with value 5 + + ListNode* current = head; + while (current) { + std::cout << current->val << " "; + current = current->next; + } + std::cout << std::endl; +} +``` +### Java Solution + +```java +class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } +} + +public class DeleteNode { + public void deleteNode(ListNode node) { + if (node == null || node.next == null) return; + node.val = node.next.val; + node.next = node.next.next; + } + + public static void main(String[] args) { + ListNode head = new ListNode(4); + head.next = new ListNode(5); + head.next.next = new ListNode(1); + head.next.next.next = new ListNode(9); + + new DeleteNode().deleteNode(head.next); // Deletes node with value 5 + + ListNode current = head; + while (current != null) { + System.out.print(current.val + " "); + current = current.next; + } + System.out.println(); + } +} +``` +### Python Solution + +```python +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +def deleteNode(node): + if not node or not node.next: + return + node.val = node.next.val + node.next = node.next.next + +# Test +head = ListNode(4) +head.next = ListNode(5) +head.next.next = ListNode(1) +head.next.next.next = ListNode(9) + +deleteNode(head.next) # Deletes node with value 5 + +current = head +while current: + print(current.val, end=" ") + current = current.next +print() +``` +### Complexity Analysis +**Time Complexity:** O(1) + +>Reason: The operation involves copying the value and changing pointers, which are constant time operations. + +**Space Complexity:** O(1) + +>Reason: We use a constant amount of extra space. + +This solution deletes a node in a singly-linked list by copying the value of the next node to the current node and adjusting the pointers accordingly, achieving the desired result with constant time and space complexity. + +### References +**LeetCode Problem:** Delete Node in a Linked List \ No newline at end of file diff --git a/solutions/lc-solutions/0200-0299/0238-product-of-array-except-self.md b/solutions/lc-solutions/0200-0299/0238-product-of-array-except-self.md new file mode 100644 index 0000000..da6667d --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0238-product-of-array-except-self.md @@ -0,0 +1,180 @@ +--- +id: product-of-array-except-self +title: Product of Array Except Self(LeetCode) +sidebar_label: 0238-Product of Array Except Self +tags: + - Array + - Prefix Sum +description: Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. +--- + +## Problem Statement + +Given an integer array `nums`, return an array `answer` such that `answer[i]` is equal to the product of all the elements of `nums` except `nums[i]`. + +The product of any prefix or suffix of `nums` is guaranteed to fit in a 32-bit integer. + +You must write an algorithm that runs in `O(n)` time and without using the division operation. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [1,2,3,4] +Output: [24,12,8,6] +``` + +**Example 2:** + +```plaintext +Input: nums = [-1,1,0,-3,3] +Output: [0,0,9,0,0] +``` + +### Constraints + +- `2 <= nums.length <= 105` +- `30 <= nums[i] <= 30` +- The product of any prefix or suffix of `nums` is guaranteed to fit in a 32-bit integer. + +## Solution + +We can solve this problem using multiple approaches. Here, I have explained all the possible solutions: + +1. Brute Force Approach: Using nested loops to calculate the product of elements except for the current index. +2. Dynamic Programming (Tabulation): Using two arrays to store the left and right products. +3. Dynamic Programming (Space Optimization): Optimizing space usage by combining the two product arrays into a single array. + +### Approach Brute Force (Two Nested Loops) + +### Algorithm +1. Initialize an empty vector `output`. +2. Iterate through each element `i` in the array `nums`: +* Set `product` to 1. +* Iterate through each element `j` in the array `nums`: + * If `i` equals `j`, skip this iteration. + * Multiply `product` by `nums[j]`. +* Append `product` to the `output` vector. +3. Return the `output` vector. + +#### Implementation + +```C++ +class Solution { +public: + vector productExceptSelf(vector& nums) { + int n = nums.size(); + vector output; + for(int i = 0; i < n; i++) { + int product = 1; + for(int j = 0; j < n; j++) { + if(i == j) continue; + product *= nums[j]; + } + output.push_back(product); + } + return output; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: O(N^2) - Two nested loops create a quadratic time complexity. +- **Space complexity**: O(1) - No extra space except for the output array (which doesn't count towards space complexity). + +### Approach 2: Dynamic Programming (Tabulation) + +#### Algorithm + +1. Initialize vectors `left_Product` and `right_Product` of size `n` with all elements set to 1. +2. Calculate `left_Product`: +* Set `left_Product[0]` to 1. +* For each element `i` from 1 to `n-1`, set `left_Product[i]` to `left_Product[i-1]` multiplied by `nums[i-1]`. +3. Calculate `right_Product`: +* Set `right_Product[n-1]` to 1. +* For each element `i` from `n-2` to 0, set `right_Product[i]` to `right_Product[i+1]` multiplied by `nums[i+1]`. +4. Initialize vector `ans` of size `n`. +5. For each element `i` from 0 to `n-1`, set `ans[i]` to `left_Product[i]` multiplied by `right_Product[i]`. +6. Return the `ans` vector. + +#### Implementation + +```C++ +class Solution { +public: + vector productExceptSelf(vector& nums) { + int n = nums.size(); + vector ans(n); + vector left_Product(n); + vector right_Product(n); + + left_Product[0] = 1; + for(int i = 1; i < n; i++) { + left_Product[i] = left_Product[i-1] * nums[i-1]; + } + + right_Product[n-1] = 1; + for(int i = n-2; i >= 0; i--) { + right_Product[i] = right_Product[i+1] * nums[i+1]; + } + + for(int i = 0; i < n; i++) { + ans[i] = left_Product[i] * right_Product[i]; + } + return ans; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: O(N) - We iterate through the array three times. +- **Space complexity**: O(N) - Two additional arrays (left_Product and right_Product) are used. + +### Approach 3: Dynamic Programming (Space Optimization) + +#### Algorithm + +1. Initialize a vector `output` of size `n` with all elements set to 1. +2. Calculate the left product: +* Set `output[0]` to 1. +* For each element `i` from 1 to `n-1`, set `output[i]` to `output[i-1]` multiplied by `nums[i-1]`. +3. Calculate the right product: +* Initialize `right` to 1. +* For each element `i` from `n-1` to 0, set `output[i]` to `output[i]` multiplied by right, then set `right` to `right` multiplied by `nums[i]`. +4. Return the `output` vector. + +#### Implementation + +```C++ +class Solution { +public: + vector productExceptSelf(vector& nums) { + int n = nums.size(); + vector output(n); + + output[0] = 1; + for(int i = 1; i < n; i++) { + output[i] = output[i-1] * nums[i-1]; + } + + int right = 1; + for(int i = n-1; i >= 0; i--) { + output[i] *= right; + right *= nums[i]; + } + return output; + } +}; +``` + +### Complexity Analysis + +- **Time complexity**: O(N) - We iterate through the array twice. +- **Space complexity**: O(1) - Constant space is used, except for the output array. + +### Conclusion + +By exploring various approaches to solve this problem, we can see that the brute force method, while simple, is inefficient with a time complexity of O(N^2). The dynamic programming approach with tabulation optimizes the time complexity to O(N) but uses extra space. The most optimized approach uses space-efficient dynamic programming, maintaining O(N) time complexity while reducing space complexity to O(1). This final approach is the best in terms of both time and space efficiency. diff --git a/solutions/lc-solutions/0200-0299/0239-sliding-window-maximum.md b/solutions/lc-solutions/0200-0299/0239-sliding-window-maximum.md new file mode 100644 index 0000000..90f39fb --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0239-sliding-window-maximum.md @@ -0,0 +1,322 @@ +--- +id: sliding-window-maximum +title: Sliding Window Maximum +sidebar_label: 239 -Sliding Window Maximum +tags: +- Array +- Queue +- Sliding Window +- Heap (Priority Queue) +- Monotonic Queue + +description: "This is a solution to the Sliding Window Maximum problem on LeetCode." +--- + +## Problem Description +You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. + +Return the max sliding window. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 +Output: [3,3,5,5,6,7] +Explanation: +Window position Max +--------------- ----- +[1 3 -1] -3 5 3 6 7 3 + 1 [3 -1 -3] 5 3 6 7 3 + 1 3 [-1 -3 5] 3 6 7 5 + 1 3 -1 [-3 5 3] 6 7 5 + 1 3 -1 -3 [5 3 6] 7 6 + 1 3 -1 -3 5 [3 6 7] 7 +``` + +**Example 2:** +``` +Input: nums = [1], k = 1 +Output: [1] +``` + +### Constraints +- `1 <= nums.length <= 10^5` +- `10^4 <= nums[i] <= 10^4` +- `1 <= k <= nums.length` + +## Solution for Sliding Window Maximum Problem +### Approach +##### Sliding Window Approach: +- The sliding window technique involves maintaining a window of fixed size (k) as it slides from the beginning to the end of the array. +This allows us to efficiently compute the desired result for each window without redundant computations. +##### HashMap Usage: +- A hashmap (or hash table) is utilized to keep track of elements within the current window and their frequencies (or counts). +The hashmap helps in quickly determining the maximum element within the current window without having to scan the entire window repeatedly. +##### Initialization: +-Initialize two pointers, left and right, to define the current window. Initially, set both pointers to the beginning of the array. +##### Building the Initial Window: +- Extend the right pointer to expand the window until its size reaches k. During this expansion: +Update the hashmap to include the frequency of each element in the current window. +##### Maintaining the Hashmap: +- As you slide the window (right pointer moves one step to the right), update the hashmap: +- Increment the count of the element pointed by right. +- Adjust the hashmap to ensure it reflects the elements and their counts within the current window. +##### Finding the Maximum: + +- Once the window size equals k, retrieve the maximum value from the hashmap. Depending on the requirement (maximum or minimum), this can be determined efficiently: +- For maximum: Iterate through the hashmap (or use additional data structures like max heap) to find the maximum element. +- For minimum: Similarly, find the minimum element within the hashmap. +##### Adjusting the Window: + +- Slide the window to the right (left pointer moves one step to the right): +- Decrement the count of the element pointed by left. +- Remove elements from the hashmap if their count drops to zero to maintain accuracy in the calculation. +##### Output the Result: +- Store or directly process the result for each window (e.g., store the maximum value found for each window). + +- Repeat Until Completion: +- Continue this process until the right pointer has traversed the entire array. + + + + #### Implementation + ```jsx live + function Solution(arr) { + var maxSlidingWindow = function(nums, k) { + let maxQueue = []; + let result = []; + + for (let i = 0; i < nums.length; i++) { + // Remove elements from maxQueue that are out of the current window + while (maxQueue.length > 0 && maxQueue[maxQueue.length - 1] < nums[i]) { + maxQueue.pop(); + } + + // Add current element to maxQueue + maxQueue.push(nums[i]); + + // Remove elements from maxQueue that are out of the current window range + if (i >= k - 1) { + result.push(maxQueue[0]); + if (nums[i - k + 1] === maxQueue[0]) { + maxQueue.shift(); + } + } + } + + return result; +}; + + const input = [1,3,-1,-3,5,3,6,7] + const k = 3 + const output =maxSlidingWindow(input , k) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(n) $ because of traversing + - Space Complexity: $ O(n) $ because of hashmap + + ## Code in Different Languages + + + + ```javascript + var maxSlidingWindow = function(nums, k) { + let maxQueue = []; + let result = []; + + for (let i = 0; i < nums.length; i++) { + // Remove elements from maxQueue that are out of the current window + while (maxQueue.length > 0 && maxQueue[maxQueue.length - 1] < nums[i]) { + maxQueue.pop(); + } + + // Add current element to maxQueue + maxQueue.push(nums[i]); + + // Remove elements from maxQueue that are out of the current window range + if (i >= k - 1) { + result.push(maxQueue[0]); + if (nums[i - k + 1] === maxQueue[0]) { + maxQueue.shift(); + } + } + } + + return result; +}; + + ``` + + + + + ```typescript + function maxSlidingWindow(nums: number[], k: number): number[] { + let maxQueue: number[] = []; + let result: number[] = []; + + for (let i = 0; i < nums.length; i++) { + // Remove elements from maxQueue that are out of the current window + while (maxQueue.length > 0 && maxQueue[maxQueue.length - 1] < nums[i]) { + maxQueue.pop(); + } + + // Add current element to maxQueue + maxQueue.push(nums[i]); + + // Remove elements from maxQueue that are out of the current window range + if (i >= k - 1) { + result.push(maxQueue[0]); + if (nums[i - k + 1] === maxQueue[0]) { + maxQueue.shift(); + } + } + } + + return result; +} + ``` + + + + ```python + function maxSlidingWindow(nums: number[], k: number): number[] { + let maxQueue: number[] = []; + let result: number[] = []; + + for (let i = 0; i < nums.length; i++) { + // Remove elements from maxQueue that are out of the current window + while (maxQueue.length > 0 && maxQueue[maxQueue.length - 1] < nums[i]) { + maxQueue.pop(); + } + + // Add current element to maxQueue + maxQueue.push(nums[i]); + + // Remove elements from maxQueue that are out of the current window range + if (i >= k - 1) { + result.push(maxQueue[0]); + if (nums[i - k + 1] === maxQueue[0]) { + maxQueue.shift(); + } + } + } + + return result; +} + + ``` + + + + + ```java + import java.util.*; + +class Solution { + public int[] maxSlidingWindow(int[] nums, int k) { + Deque maxQueue = new LinkedList<>(); + List result = new ArrayList<>(); + + for (int i = 0; i < nums.length; i++) { + // Remove elements from maxQueue that are out of the current window + while (!maxQueue.isEmpty() && nums[maxQueue.peekLast()] < nums[i]) { + maxQueue.pollLast(); + } + + // Add current element to maxQueue + maxQueue.offer(i); + + // Remove elements from maxQueue that are out of the current window range + if (i >= k - 1) { + result.add(nums[maxQueue.peekFirst()]); + if (maxQueue.peekFirst() == i - k + 1) { + maxQueue.pollFirst(); + } + } + } + + // Convert List to int[] + return result.stream().mapToInt(Integer::intValue).toArray(); + } +} + + ``` + + + + + ```cpp + class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + mapmp; + + int i=0; + int j=0; + vectorans; + while(jfirst); + j++; + } + else if(j-i+1>k) + { + while(j-i+1>k) + { + mp[nums[i]]--; + + if(mp[nums[i]]==0)mp.erase(nums[i]); + + i++; + } + + if(j-i+1==k) + { + auto it =mp.rbegin(); + ans.push_back(it->first); + } + + j++; + + } + } + + return ans; + } +}; + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Sliding Window Problem](https://leetcode.com/problems/sliding-window-maximum/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/sliding-window-maximum/solutions) + diff --git a/solutions/lc-solutions/0200-0299/0240-search-a-2d-matrix-II.md b/solutions/lc-solutions/0200-0299/0240-search-a-2d-matrix-II.md new file mode 100644 index 0000000..bdd389c --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0240-search-a-2d-matrix-II.md @@ -0,0 +1,332 @@ +--- +id: search-a-2d-matrix-ii +title: Search a 2D Matrix II Solution +sidebar_label: 0240 - Search a 2D Matrix II +tags: + - Search a 2D Matrix II + - Array + - Binary Search + - Divide and Conquer + - Matrix + - LeetCode + - JavaScript + - TypeScript +description: "This is a solution to the Search a 2D Matrix II problem on LeetCode." +sidebar_position: 240 +--- + +In this tutorial, we will solve the Search a 2D Matrix II problem using efficient search techniques. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, and C++. + +## Problem Description + +Write an efficient algorithm that searches for a value in an `m x n` matrix. This matrix has the following properties: + +- Integers in each row are sorted in ascending order from left to right. +- Integers in each column are sorted in ascending order from top to bottom. + +### Examples + +**Example 1:** + +```plaintext +Input: matrix = [ + [1, 4, 7, 11, 15], + [2, 5, 8, 12, 19], + [3, 6, 9, 16, 22], + [10, 13, 14, 17, 24], + [18, 21, 23, 26, 30] +], target = 5 +Output: true +``` + +**Example 2:** + +```plaintext +Input: matrix = [ + [1, 4, 7, 11, 15], + [2, 5, 8, 12, 19], + [3, 6, 9, 16, 22], + [10, 13, 14, 17, 24], + [18, 21, 23, 26, 30] +], target = 20 +Output: false +``` + +### Constraints + +- `m == matrix.length` +- `n == matrix[i].length` +- $1 \leq n, m \leq 300$ +- $-10^9 \leq \text{matrix[i][j]} \leq 10^9$ +- All the integers in each row are sorted in ascending order. +- All the integers in each column are sorted in ascending order. +- $-10^9 \leq target \leq 10^9$ + +--- + +## Solution for Search a 2D Matrix II + +### Intuition and Approach + +To search for a value in this matrix efficiently, we can utilize the properties of the matrix. Since the matrix is sorted both row-wise and column-wise, we can start our search from the top-right corner of the matrix. From here, we have two options: + +1. If the target is greater than the current value, move downwards. +2. If the target is less than the current value, move leftwards. + +This approach ensures that we eliminate one row or one column in each step, leading to an efficient search. + + + + +### Approach: Greedy Search + +By leveraging the sorted properties of the matrix, we can search for the target value efficiently using a greedy approach. This involves starting from the top-right corner and adjusting our search direction based on the current value. + +#### Implementation + +```jsx live +function searchMatrix(matrix, target) { + if (!matrix || matrix.length === 0 || matrix[0].length === 0) return false; + let rows = matrix.length; + let cols = matrix[0].length; + let row = 0; + let col = cols - 1; + + while (row < rows && col >= 0) { + if (matrix[row][col] === target) { + return true; + } else if (matrix[row][col] > target) { + col--; + } else { + row++; + } + } + return false; +} + +const matrix = [ + [1, 4, 7, 11, 15], + [2, 5, 8, 12, 19], + [3, 6, 9, 16, 22], + [10, 13, 14, 17, 24], + [18, 21, 23, 26, 30], +]; +const target = 5; +const result = searchMatrix(matrix, target); + +return ( +
+

+ Input: matrix = [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, + 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ], target = 5 +

+

+ Output: {result ? "true" : "false"} +

+
+); +``` + +#### Codes in Different Languages + + + + + ```javascript + function searchMatrix(matrix, target) { + if (!matrix || matrix.length === 0 || matrix[0].length === 0) return false; + let rows = matrix.length; + let cols = matrix[0].length; + let row = 0; + let col = cols - 1; + + while (row < rows && col >= 0) { + if (matrix[row][col] === target) { + return true; + } else if (matrix[row][col] > target) { + col--; + } else { + row++; + } + } + return false; + } + ``` + + + + + ```typescript + function searchMatrix(matrix: number[][], target: number): boolean { + if (!matrix || matrix.length === 0 || matrix[0].length === 0) return false; + let rows = matrix.length; + let cols = matrix[0].length; + let row = 0; + let col = cols - 1; + + while (row < rows && col >= 0) { + if (matrix[row][col] === target) { + return true; + } else if (matrix[row][col] > target) { + col--; + } else { + row++; + } + } + return false; + } + ``` + + + + + ```python + def searchMatrix(matrix: List[List[int]], target: int) -> bool: + if not matrix or not matrix[0]: + return False + rows = len(matrix) + cols = len(matrix[0]) + row = 0 + col = cols - 1 + + while row < rows and col >= 0: + if matrix[row][col] == target: + return True + elif matrix[row][col] > target: + col -= 1 + else: + row += 1 + + return False + ``` + + + + + ```java + class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { + return false; + } + int rows = matrix.length; + int cols = matrix[0].length; + int row = 0; + int col = cols - 1; + + while (row < rows && col >= 0) { + if (matrix[row][col] == target) { + return true; + } else if (matrix[row][col] > target) { + col--; + } else { + row++; + } + } + return false; + } + } + ``` + + + + + ```cpp + class Solution { + public: + bool searchMatrix(vector>& matrix, int target) { + if (matrix.empty() || matrix[0].empty()) return false; + int rows = matrix.size(); + int cols = matrix[0].size(); + int row = 0; + int col = cols - 1; + + while (row < rows && col >= 0) { + if (matrix[row][col] == target) { + return true; + } else if (matrix[row][col] > target) { + col--; + } else { + row++; + } + } + return false; + } + }; + ``` + + + + +#### Complexity Analysis + +- **Time Complexity:** $O(m + n)$, where `m` is the number of rows and `n` is the number of columns. +- **Space Complexity:** $O(1)$, as we are not using any additional space. + +- The time complexity is linear in terms of the dimensions of the matrix. Each step eliminates either a row or a + +column, leading to a linear time complexity of $O(m + n)$. + +- The space complexity is constant because we only use a few extra variables regardless of the matrix size. + +
+
+ +:::tip Note +This solution leverages the matrix's properties to reduce the search space efficiently, making it suitable for large matrices. +::: + +--- + +## Video Explanation of Search a 2D Matrix II + + + + + +--- + + + + + + + + + + + + + + + + + + + + + diff --git a/solutions/lc-solutions/0200-0299/0241-different-ways-to-add-parentheses.md b/solutions/lc-solutions/0200-0299/0241-different-ways-to-add-parentheses.md new file mode 100644 index 0000000..43af954 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0241-different-ways-to-add-parentheses.md @@ -0,0 +1,217 @@ +--- +id: different-ways-to-add-parentheses +title: Different Ways to Add Parentheses +sidebar_label: 0241-Different Ways to Add Parentheses +tags: + - DP + - Leet code +description: "Solution to leetocde 241" +--- + +## Intuition +When evaluating an expression, we encounter the same problem on the left and right substrings of an operator. Recursion can be used to calculate all possible ways to evaluate the expression. + +## Recursion +We define a recursive function `getDiffWays` where `getDiffWays(i, j)` returns the number of ways to evaluate the expression from index `i` to `j`. Therefore, our answer will be `getDiffWays(0, n - 1)`, where `n` is the length of the expression. + +```cpp +class Solution { + bool isOperator(char ch) { + return (ch == '+' || ch == '-' || ch == '*'); + } + + vector getDiffWays(int i, int j, string& expression) { + + // Base case: if the length of the substring is 1 or 2, return the number found + int len = j - i + 1; + if(len <= 2) { + return { stoi(expression.substr(i, len)) }; + } + + // If it is not a number, it is an expression + // Evaluate every operator present in the expression + vector res; + for(int ind = i; ind <= j; ind++) { + if(isOperator(expression[ind])) { + char op = expression[ind]; + + // Get all results for the left and right substrings using recursion + vector left = getDiffWays(i, ind - 1, expression); + vector right = getDiffWays(ind + 1, j, expression); + + // Try all options for left and right operands and push all results to the answer + for(int l : left) { + for(int r : right) { + if(op == '+') { + res.push_back(l + r); + } + else if(op == '-') { + res.push_back(l - r); + } + else if(op == '*') { + res.push_back(l * r); + } + } + } + } + } + return res; + } + +public: + vector diffWaysToCompute(string expression) { + int n = expression.size(); + return getDiffWays(0, n - 1, expression); + } +}; +``` + +## Complexity +Time complexity: Exponential. It's hard to derive the exact time complexity, but it will be definitely exponential in nature. + +Space complexity: O(n * x) for the recursion stack, where x is the number of ways to calculate the expression (operators!). + +## Memoization +If we observe the overlapping subproblems that get calculated again and again, we can avoid this by introducing a 3D DP array or cache to store the calculated results. + +```cpp +class Solution { + bool isOperator(char ch) { + return (ch == '+' || ch == '-' || ch == '*'); + } + + vector getDiffWays(int i, int j, vector>>& dp, string& expression) { + + // Return cached result if already calculated + if(!dp[i][j].empty()) { + return dp[i][j]; + } + + // Base case: if the length of the substring is 1 or 2, return the number found + int len = j - i + 1; + if(len <= 2) { + return dp[i][j] = { stoi(expression.substr(i, len)) }; + } + + // If it is not a number, it is an expression + // Evaluate every operator present in the expression + vector res; + for(int ind = i; ind <= j; ind++) { + if(isOperator(expression[ind])) { + char op = expression[ind]; + + // Get all results for the left and right substrings using recursion + vector left = getDiffWays(i, ind - 1, dp, expression); + vector right = getDiffWays(ind + 1, j, dp, expression); + + // Try all options for left and right operands and push all results to the answer + for(int l : left) { + for(int r : right) { + if(op == '+') { + res.push_back(l + r); + } + else if(op == '-') { + res.push_back(l - r); + } + else if(op == '*') { + res.push_back(l * r); + } + } + } + } + } + return dp[i][j] = res; + } + +public: + vector diffWaysToCompute(string expression) { + int n = expression.size(); + vector>> dp(n, vector>(n)); + return getDiffWays(0, n - 1, dp, expression); + } +}; +``` + +## Complexity +Time complexity: O(n^2 * (n * x^2)), as there are approximately n^2 states and calculating these states takes O(n * x^2) time. + +Space complexity: O(n * x) + O(n^2 * x) for the recursion stack and dp array, where x is the number of ways to calculate the expression (operators!). + +## Tabulation +We can eliminate the recursion stack space used in the memoization solution by calculating the result for every valid expression substring in a bottom-up manner, known as tabulation. + +In tabulation, we need to check if a given substring is a valid arithmetic expression or not. + +```cpp +class Solution { + bool isOperator(char ch) { + return (ch == '+' || ch == '-' || ch == '*'); + } + +public: + vector diffWaysToCompute(string expression) { + int n = expression.size(); + vector>> dp(n, vector>(n)); + + // Function to check if a given substring of expression is a valid expression + auto isValidExpression = [&](int i, int j) -> bool { + return (i == 0 || isOperator(expression[i - 1])) && (j == n - 1 || isOperator(expression[j + 1])); + }; + + // Get the answer for all single-digit numbers + for(int i = 0; i < n; i++) { + if(isValidExpression(i, i)) { + dp[i][i] = { stoi(expression.substr(i, 1)) }; + } + } + + // Get the answer for all 2-digit numbers + for(int i = 0, j = 1; j < n; i++, j++) { + if(isValidExpression(i, j)) { + dp[i][j] = { stoi(expression.substr(i, 2)) }; + } + } + + // Get the answer for all valid expression substrings in a bottom-up manner + for(int len = 3; len <= n; len++) { + for(int i = 0, j = i + len - 1; j < n; i++, j++) { + if(!isValidExpression(i, j)) + continue; + + // Try to evaluate every operator + for(int ind = i; ind <= j; ind++) { + if(isOperator(expression[ind])) { + char op = expression[ind]; + + // Get all results for the left and right substrings + vector left = dp[i][ind - 1]; + vector right = dp[ind + 1][j]; + + // Try all options for left and right operands and push all results to the answer + for(int l : left) { + for(int r : right) { + if(op == '+') { + dp[i][j].push_back(l + r); + } + else if(op == '-') { + dp[i][j].push_back(l - r); + } + else if(op == '*') { + dp[i][j].push_back(l * r); + } + } + } + } + } + } + } + + return dp[0][n - 1]; + } +}; +``` + +## Complexity +Time complexity: O(n^3 * x^2), same as the memoization solution. + +Space complexity: O(n^2 * x) for the dp array, where x is the number of ways to calculate the expression (operators!). diff --git a/solutions/lc-solutions/0200-0299/0242-valid-anagram.md b/solutions/lc-solutions/0200-0299/0242-valid-anagram.md new file mode 100644 index 0000000..0d8b5b3 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0242-valid-anagram.md @@ -0,0 +1,156 @@ +--- +id: valid-anagram +title: Valid Anagram +sidebar_label: 0242 Valid Anagram +tags: + - String + - Hash Table + - Sorting + - LeetCode + - Python + - Java + - C++ +description: "This is a solution to the Valid Anagram problem on LeetCode." +--- + +## Problem Description + +Given two strings `s` and `t`, return true if `t` is an anagram of `s`, and false otherwise. + +An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + +### Examples + +**Example 1:** + +``` +Input: s = "anagram", t = "nagaram" +Output: true +``` + +**Example 2:** + +``` +Input: s = "rat", t = "car" +Output: false +``` + +### Constraints + +- $1 <= s.length, t.length <= 5 * 10^4$ +- s and t consist of lowercase English letters. + +## Solution for Valid Anagram Problem + +### Approach + +To determine if two strings `s` and `t` are anagrams, we can use the following approach: + +1. **Character Counting**: Count the occurrences of each character in both strings using arrays of size 26 (since there are 26 lowercase letters). +2. **Comparison**: Compare the two arrays. If they are identical, then `t` is an anagram of `s`. + +### Code in Different Languages + + + + + ```python + + class Solution: + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + + # Initialize arrays to count occurrences of each character + count_s = [0] * 26 + count_t = [0] * 26 + + # Count occurrences of each character in s + for char in s: + count_s[ord(char) - ord('a')] += 1 + + # Count occurrences of each character in t + for char in t: + count_t[ord(char) - ord('a')] += 1 + + # Compare the two arrays + return count_s == count_t + ``` + + + + ```java + + class Solution { + public boolean isAnagram(String s, String t) { + if (s.length() != t.length()) { + return false; + } + + // Initialize arrays to count occurrences of each character + int[] count_s = new int[26]; + int[] count_t = new int[26]; + + // Count occurrences of each character in s + for (char ch : s.toCharArray()) { + count_s[ch - 'a']++; + } + + // Count occurrences of each character in t + for (char ch : t.toCharArray()) { + count_t[ch - 'a']++; + } + + // Compare the two arrays + return Arrays.equals(count_s, count_t); + } + } + ``` + + + + ```cpp + + #include + using namespace std; + + class Solution { + public: + bool isAnagram(string s, string t) { + if (s.length() != t.length()) { + return false; + } + + // Initialize arrays to count occurrences of each character + vector count_s(26, 0); + vector count_t(26, 0); + + // Count occurrences of each character in s + for (char ch : s) { + count_s[ch - 'a']++; + } + + // Count occurrences of each character in t + for (char ch : t) { + count_t[ch - 'a']++; + } + + // Compare the two arrays + return count_s == count_t; + } + }; + ``` + + + + +### Complexity Analysis + +- **Time complexity**: O(n), where n is the length of the strings `s` and `t`. We iterate through both strings once to count characters and compare counts, which are both O(n). +- **Space complexity**: O(1) for the fixed-size arrays in Python and O(26) = O(1) for arrays in Java and C++, since there are only 26 lowercase letters. + +## References + +- **LeetCode Problem:** [Valid Anagram](https://leetcode.com/problems/valid-anagram/) +- **Solution Link:** [Valid Anagram Solution on LeetCode](https://leetcode.com/problems/valid-anagram/solution/) +- **Author's GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) diff --git a/solutions/lc-solutions/0200-0299/0243-shortest-word-distanc.md b/solutions/lc-solutions/0200-0299/0243-shortest-word-distanc.md new file mode 100644 index 0000000..5126280 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0243-shortest-word-distanc.md @@ -0,0 +1,144 @@ +--- +id: shortest-word-distance +title: Shortest Word Distance Solution +sidebar_label: 0243 Shortest Word Distance +tags: + - Array + - Two Pointers + - LeetCode + - Python + - Java + - C++ +description: "This is a solution to the Shortest Word Distance problem on LeetCode." +--- + +## Problem Description + +Given a list of words `words` and two words `word1` and `word2`, return the shortest distance between these two words in the list. + +### Examples + +**Example 1:** +``` +Input: words = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice" +Output: 3 +``` + +### Constraints + +- You may assume that `words` contains at least two words. +- All the words in `words` are guaranteed to be unique. +- `word1` and `word2` are two distinct words in the list. + +## Solution for Shortest Word Distance Problem + +### Approach + +To find the shortest distance between two words `word1` and `word2` in a list of words `words`, we can use the following approach: + +1. **Two Pointers**: Use two pointers to track the most recent indices of `word1` and `word2` as we iterate through the list. +2. **Update Distance**: For each occurrence of `word1` or `word2`, update the minimum distance found so far if possible. + +### Code in Different Languages + + + + + ```python + + class Solution: + def shortestDistance(self, words: List[str], word1: str, word2: str) -> int: + index1 = -1 + index2 = -1 + min_distance = float('inf') + + for i in range(len(words)): + if words[i] == word1: + index1 = i + elif words[i] == word2: + index2 = i + + if index1 != -1 and index2 != -1: + min_distance = min(min_distance, abs(index1 - index2)) + + return min_distance + ``` + + + + ```java + + import java.util.*; + + class Solution { + public int shortestDistance(String[] words, String word1, String word2) { + int index1 = -1; + int index2 = -1; + int minDistance = Integer.MAX_VALUE; + + for (int i = 0; i < words.length; i++) { + if (words[i].equals(word1)) { + index1 = i; + } else if (words[i].equals(word2)) { + index2 = i; + } + + if (index1 != -1 && index2 != -1) { + minDistance = Math.min(minDistance, Math.abs(index1 - index2)); + } + } + + return minDistance; + } + } + ``` + + + + ```cpp + + #include + #include + #include + #include + using namespace std; + + class Solution { + public: + int shortestDistance(vector& words, string word1, string word2) { + int index1 = -1; + int index2 = -1; + int minDistance = INT_MAX; + + for (int i = 0; i < words.size(); i++) { + if (words[i] == word1) { + index1 = i; + } else if (words[i] == word2) { + index2 = i; + } + + if (index1 != -1 && index2 != -1) { + minDistance = min(minDistance, abs(index1 - index2)); + } + } + + return minDistance; + } + }; + ``` + + + + +### Complexity Analysis + +- **Time complexity**: O(n), where n is the number of elements in the `words` array. We iterate through the array once. +- **Space complexity**: O(1) in additional space, as we use only a few extra variables regardless of the input size. + +## References + +- **LeetCode Problem:** [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/) +- **Solution Link:** [Shortest Word Distance Solution on LeetCode](https://leetcode.com/problems/shortest-word-distance/solution/) +- **Author's GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) + + diff --git a/solutions/lc-solutions/0200-0299/0244-shortest-distance-between-words-II.md b/solutions/lc-solutions/0200-0299/0244-shortest-distance-between-words-II.md new file mode 100644 index 0000000..f99d32f --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0244-shortest-distance-between-words-II.md @@ -0,0 +1,381 @@ +--- +id: shortest-distance-between-words-II +title: Shortest Distance Between Words +sidebar_label: 0244-Shortest Distance Between Words - II +tags: [Hash Map, Two Pointers] +description: Solution to finding the shortest distance between two words in an array of strings. +--- + +## Problem Statement + +### Problem Description + +Design a data structure that can compute the shortest distance between any two distinct strings within an array of strings. Initialize the data structure with an array of strings, `wordsDict`. Once initialized, it should return the smallest possible index difference between two different strings in `wordsDict` when queried. + +### Examples + +**Example 1:** + +``` +Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"] +Query: word1 = "coding", word2 = "practice" +Output: 3 +``` + +**Example 2:** + +``` +Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"] +Query: word1 = "makes", word2 = "coding" +Output: 1 +``` + +### Constraints + +- The number of words in `wordsDict` is in the range [1, 10^5]. +- `wordsDict[i]` consists of lowercase English letters. +- `word1` and `word2` are distinct and will always be in `wordsDict`. + +## Solution of Given Problem + +### Intuition and Approach + +To efficiently find the shortest distance between two words in the dictionary, a preprocessing step is required during initialization. We traverse the `wordsDict` array once and create a hash map where keys are the distinct words from the array, and values are lists of indices where each key word is located in the original array. This preprocessing step allows for a quick lookup of the positions of any word, facilitating the computation of the distances between any two words. + +Once the positions are mapped, to find the shortest distance between `word1` and `word2`, we get their list of indices from our hash map. We need to find the minimum difference between any two indices from these lists. The lists are already sorted because the indices were appended in the order they were encountered during initialization. + +A two-pointer approach efficiently solves the problem of finding the minimum difference. Start with the first index of each list, and at each step, move the pointer that points to the smaller index to the next index in its list. This approach will traverse the two lists simultaneously and will always give the smallest possible difference in indices (thus the shortest distance) between `word1` and `word2`. The process repeats until we have fully traversed one of the lists, ensuring that no potential shorter distance is missed. + +### Approaches + +#### Codes in Different Languages + + + + + ```javascript + class WordDistance { + constructor(wordsDict) { + this.word_positions = {}; + for (let index = 0; index < wordsDict.length; index++) { + const word = wordsDict[index]; + if (!this.word_positions[word]) { + this.word_positions[word] = []; + } + this.word_positions[word].push(index); + } + } + + shortest(word1, word2) { + const positions1 = this.word_positions[word1]; + const positions2 = this.word_positions[word2]; + let i = 0, j = 0, min_distance = Infinity; + + while (i < positions1.length && j < positions2.length) { + const index1 = positions1[i], index2 = positions2[j]; + min_distance = Math.min(min_distance, Math.abs(index1 - index2)); + if (index1 < index2) { + i++; + } else { + j++; + } + } + + return min_distance; + } + } + + // Example Usage + const wordsDict = ["practice", "makes", "perfect", "coding", "makes"]; + const wordDistance = new WordDistance(wordsDict); + console.log(wordDistance.shortest("coding", "practice")); // Output: 3 + console.log(wordDistance.shortest("makes", "coding")); // Output: 1 + ``` + + + + + ```typescript + class WordDistance { + private word_positions: { [key: string]: number[] } = {}; + + constructor(wordsDict: string[]) { + for (let index = 0; index < wordsDict.length; index++) { + const word = wordsDict[index]; + if (!this.word_positions[word]) { + this.word_positions[word] = []; + } + this.word_positions[word].push(index); + } + } + + shortest(word1: string, word2: string): number { + const positions1 = this.word_positions[word1]; + const positions2 = this.word_positions[word2]; + let i = 0, j = 0, min_distance = Infinity; + + while (i < positions1.length && j < positions2.length) { + const index1 = positions1[i], index2 = positions2[j]; + min_distance = Math.min(min_distance, Math.abs(index1 - index2)); + if (index1 < index2) { + i++; + } else { + j++; + } + } + + return min_distance; + } + } + + // Example Usage + const wordsDict = ["practice", "makes", "perfect", "coding", "makes"]; + const wordDistance = new WordDistance(wordsDict); + console.log(wordDistance.shortest("coding", "practice")); // Output: 3 + console.log(wordDistance.shortest("makes", "coding")); // Output: 1 + ``` + + + + + ```python + class WordDistance: + def __init__(self, wordsDict: list[str]): + self.word_positions = {} + for index, word in enumerate(wordsDict): + if word not in self.word_positions: + self.word_positions[word] = [] + self.word_positions[word].append(index) + + def shortest(self, word1: str, word2: str) -> int: + positions1 = self.word_positions[word1] + positions2 = self.word_positions[word2] + i, j = 0, 0 + min_distance = float('inf') + + while i < len(positions1) and j < len(positions2): + index1, index2 = positions1[i], positions2[j] + min_distance = min(min_distance, abs(index1 - index2)) + if index1 < index2: + i += 1 + else: + j += 1 + + return min_distance + + # Example Usage + wordsDict = ["practice", "makes", "perfect", "coding", "makes"] + word_distance = WordDistance(wordsDict) + print(word_distance.shortest("coding", "practice")) # Output: 3 + print(word_distance.shortest("makes", "coding")) # Output: 1 + ``` + + + + + ```java + import java.util.*; + + class WordDistance { + private Map> wordPositions; + + public WordDistance(String[] wordsDict) { + wordPositions = new HashMap<>(); + for (int index = 0; index < wordsDict.length; index++) { + String word = wordsDict[index]; + if (!wordPositions.containsKey(word)) { + wordPositions.put(word, new ArrayList<>()); + } + wordPositions.get(word).add(index); + } + } + + public int shortest(String word1, String word2) { + List positions1 = wordPositions.get(word1); + List positions2 = wordPositions.get(word2); + int i = 0, j = 0, minDistance = Integer.MAX_VALUE; + + while (i < positions1.size() && j < positions2.size()) { + int index1 = positions1.get(i), index2 = positions2.get(j); + minDistance = Math.min(minDistance, Math.abs(index1 - index2)); + if (index1 < index2) { + i++; + } else { + j++; + } + } + + return minDistance; + } + + public static void main(String[] args) { + String[] wordsDict = {"practice", "makes", "perfect", "coding", "makes"}; + WordDistance wordDistance = new WordDistance(wordsDict); + System.out.println(wordDistance.shortest("coding", "practice")); // Output: 3 + System.out.println(wordDistance.shortest("makes", "coding")); // Output: 1 + } + } + ``` + + + + ```cpp + #include + #include + #include + #include + #include + #include + + class WordDistance { + public: + WordDistance(std::vector& wordsDict) { + for (int i = 0; i < wordsDict.size(); ++i) { + word_positions[wordsDict[i]].push_back(i); + } + } + + int shortest(const std::string& word1, const std::string& word2) { + const std::vector& positions1 = word_positions[word1]; + const std::vector& positions2 = word_positions[word2]; + int i = 0, j = 0; + int min_distance = INT_MAX; + + while (i < positions1.size() && j < positions2.size()) { + min_distance = std::min(min_distance, std::abs(positions1[i] - positions2[j])); + if (positions1[i] < positions2[j]) { + ++i; + } else { + ++j; + } + } + + return min_distance; + } + + private: + std::unordered_map> word_positions; + }; + + int main() { + std::vector wordsDict = {"practice", "makes", "perfect", "coding", "makes"}; + WordDistance wordDistance(wordsDict); + + std::cout << wordDistance.shortest("coding", "practice") << std::endl; // Output: 3 + std::cout << wordDistance.shortest("makes", "coding") << std::endl; // Output: 1 + + return 0; + } + ``` + + + + +### Explanation + + + + +1. **Initialization (Constructor)**: + - We iterate through the `wordsDict` array and populate the `wordPositions` map with arrays of indices for each word. This allows for quick lookups of the positions of any word in the list. + +2. **Shortest Distance (`shortest` method)**: + - Retrieve the arrays of indices for `word1` and `word2` from the map. + - Use two pointers (`i` and `j`) to traverse the arrays and compute the minimum distance. This two-pointer technique efficiently finds the minimum index difference by advancing the pointer that points to the smaller index. + + + + +1. **Initialization (Constructor)**: + - We iterate through the `wordsDict` array and populate the `wordPositions` map with arrays of indices for each word. This allows for quick lookups of the positions of any word in the list. + +2. **Shortest Distance (`shortest` method)**: + - Retrieve the arrays of indices for `word1` and `word2` from the map. + - Use two pointers (`i` and `j`) to traverse the arrays and compute the minimum distance. This two-pointer technique efficiently finds the minimum index difference by advancing the pointer that points to the smaller index. + + + + + +1. **Initialization (`__init__` method)**: + - We iterate through `wordsDict` and populate the `word_positions` dictionary with lists of indices for each word. + +2. **Shortest Distance (`shortest` method)**: + - Retrieve the lists of indices for `word1` and `word2`. + - Use two pointers (`i` and `j`) to traverse the lists and compute the minimum distance. This two-pointer technique ensures that we efficiently find the minimum index difference by advancing the pointer that points to the smaller index. + + + + + +- **Initialization**: + - `wordIndices` is a `Map` where each key is a word and each value is a list of indices where the word occurs in `wordsDict`. + +- **shortest Method**: + - Uses two lists of indices for the given words and applies a two-pointer approach to find the smallest index difference. + - The pointers traverse through the lists, adjusting to find the minimum distance efficiently. + + + + +1. **Initialization (Constructor)**: + - We iterate through the `wordsDict` and populate the `word_positions` unordered map with vectors of indices for each word. + +2. **Shortest Distance (`shortest` method)**: + - Retrieve the vectors of indices for `word1` and `word2` from the map. + - Use two pointers (`i` and `j`) to traverse the vectors and compute the minimum distance. This two-pointer technique efficiently finds the minimum index difference by advancing the pointer that points to the smaller index. + + + +### Complexity + + + +- **Initialization**: O(n), where `n` is the number of words in `wordsDict`. +- **Querying**: O(m + k), where `m` and `k` are the lengths of the arrays of indices for `word1` and `word2` respectively. This ensures that the queries are processed efficiently after the initial setup. + + + + +- **Initialization**: O(n), where `n` is the number of words in `wordsDict`. +- **Querying**: O(m + k), where `m` and `k` are the lengths of the arrays of indices for `word1` and `word2` respectively. This ensures that the queries are processed efficiently after the initial setup. + + + + +- **Initialization**: O(n), where `n` is the number of words in `wordsDict`. +- **Querying**: O(m + k), where `m` and `k` are the lengths of the lists of indices for `word1` and `word2` respectively. This is efficient for typical use cases and allows quick queries after the initial setup. + + + + +- **Data Structure Design**: Use a Map `>` to store the indices of each word in the `wordsDict`. This allows us to quickly access the positions of any word in the array. + +- **Initialization**: Traverse the `wordsDict` and populate the map with the indices of each word. + +- **Query Processing**: For each query, use the map to get the list of indices for the two words.Use a two-pointer technique to find the minimum distance between the indices of the two words. + + + + +- **Initialization**: O(n), where `n` is the number of words in `wordsDict`. +- **Querying**: O(m + k), where `m` and `k` are the lengths of the vectors of indices for `word1` and `word2` respectively. This ensures that the queries are processed efficiently after the initial setup. + + + +## References + +- **LeetCode Problem:** [Shortest Word Distance-II](https://leetcode.com/problems/shortest-word-distance-ii/) + +

Authors:

+ +
+{['sivaprasath2004','pallasivasai'].map(username => ( + +))} +
+ + + + + \ No newline at end of file diff --git a/solutions/lc-solutions/0200-0299/0244-shortest-word-distance-II.md b/solutions/lc-solutions/0200-0299/0244-shortest-word-distance-II.md new file mode 100644 index 0000000..f168ff5 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0244-shortest-word-distance-II.md @@ -0,0 +1,358 @@ +--- +id: shortest-word-distance-ii +title: Shortest Word Distance II Solution +sidebar_label: 0244 - Shortest Word Distance II +tags: + - Shortest Word Distance II + - Array + - Hash Table + - Design + - LeetCode + - JavaScript + - TypeScript +description: "This is a solution to the Shortest Word Distance II problem on LeetCode." +sidebar_position: 244 +--- + +In this tutorial, we will solve the Shortest Word Distance II problem using a design approach with a hash table. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, and C++. + +## Problem Description + +Design a class which receives a list of words in the constructor, and implements a method that takes two words `word1` and `word2` and return the shortest distance between these two words in the list. + +### Examples + +**Example 1:** + +```plaintext +Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice" +Output: 3 +``` + +**Example 2:** + +```plaintext +Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding" +Output: 1 +``` + +### Constraints + +- $1 \leq \text{wordsDict.length} \leq 3 \times 10^4$ +- $1 \leq \text{wordsDict[i].length} \leq 10$ +- `wordsDict[i]` consists of lowercase English letters. +- `word1` and `word2` are both in `wordsDict`. +- `word1` != `word2`. + +--- + +## Solution for Shortest Word Distance II + +### Intuition and Approach + +We can solve this problem efficiently by pre-processing the words dictionary and storing the indices of each word in a hash table. This allows us to quickly find the shortest distance between any two given words by comparing their indices. + + + + +### Approach: Using Hash Table + +The hash table approach involves pre-processing the `wordsDict` to store the indices of each word. When we need to find the shortest distance between two words, we retrieve their indices from the hash table and calculate the minimum distance. + +#### Implementation + +```jsx live +function shortestWordDistanceII() { + class WordDistance { + constructor(wordsDict) { + this.wordMap = new Map(); + for (let i = 0; i < wordsDict.length; i++) { + if (!this.wordMap.has(wordsDict[i])) { + this.wordMap.set(wordsDict[i], []); + } + this.wordMap.get(wordsDict[i]).push(i); + } + } + + shortest(word1, word2) { + const indices1 = this.wordMap.get(word1); + const indices2 = this.wordMap.get(word2); + let i = 0; + let j = 0; + let minDistance = Infinity; + + while (i < indices1.length && j < indices2.length) { + minDistance = Math.min(minDistance, Math.abs(indices1[i] - indices2[j])); + if (indices1[i] < indices2[j]) { + i++; + } else { + j++; + } + } + + return minDistance; + } + } + + const wordsDict = ["practice", "makes", "perfect", "coding", "makes"]; + const wordDistance = new WordDistance(wordsDict); + const result = wordDistance.shortest("coding", "practice"); + + return ( +
+

+ Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice" +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + class WordDistance { + constructor(wordsDict) { + this.wordMap = new Map(); + for (let i = 0; i < wordsDict.length; i++) { + if (!this.wordMap.has(wordsDict[i])) { + this.wordMap.set(wordsDict[i], []); + } + this.wordMap.get(wordsDict[i]).push(i); + } + } + + shortest(word1, word2) { + const indices1 = this.wordMap.get(word1); + const indices2 = this.wordMap.get(word2); + let i = 0; + let j = 0; + let minDistance = Infinity; + + while (i < indices1.length && j < indices2.length) { + minDistance = Math.min(minDistance, Math.abs(indices1[i] - indices2[j])); + if (indices1[i] < indices2[j]) { + i++; + } else { + j++; + } + } + + return minDistance; + } + } + ``` + + + + + ```typescript + class WordDistance { + private wordMap: Map; + + constructor(wordsDict: string[]) { + this.wordMap = new Map(); + for (let i = 0; i < wordsDict.length; i++) { + if (!this.wordMap.has(wordsDict[i])) { + this.wordMap.set(wordsDict[i], []); + } + this.wordMap.get(wordsDict[i])!.push(i); + } + } + + shortest(word1: string, word2: string): number { + const indices1 = this.wordMap.get(word1)!; + const indices2 = this.wordMap.get(word2)!; + let i = 0; + let j = 0; + let minDistance = Infinity; + + while (i < indices1.length && j < indices2.length) { + minDistance = Math.min(minDistance, Math.abs(indices1[i] - indices2[j])); + if (indices1[i] < indices2[j]) { + i++; + } else { + j++; + } + } + + return minDistance; + } + } + ``` + + + + + ```python + class WordDistance: + def __init__(self, wordsDict: List[str]): + self.word_map = {} + for i, word in enumerate(wordsDict): + if word not in self.word_map: + self.word_map[word] = [] + self.word_map[word].append(i) + + def shortest(self, word1: str, word2: str) -> int: + indices1 = self.word_map[word1] + indices2 = self.word_map[word2] + i, j = 0, 0 + min_distance = float('inf') + + while i < len(indices1) and j < len(indices2): + min_distance = min(min_distance, abs(indices1[i] - indices2[j])) + if indices1[i] < indices2[j]: + i += 1 + else: + j += 1 + + return min_distance + ``` + + + + + ```java + class WordDistance { + private Map> wordMap; + + public WordDistance(String[] wordsDict) { + wordMap = new HashMap<>(); + for (int i = 0; i < wordsDict.length; i++) { + wordMap.putIfAbsent(wordsDict[i], new ArrayList<>()); + wordMap.get(wordsDict[i]).add(i); + } + } + + public int shortest(String word1, String word2) { + List indices1 = wordMap.get(word1); + List indices2 = wordMap.get(word2); + int i = 0, j = 0, minDistance = Integer.MAX_VALUE; + + while (i < indices1.size() && j < indices2.size()) { + minDistance = Math.min(minDistance, Math.abs(indices1.get(i) - indices2.get(j))); + if (indices1.get(i) < indices2.get(j)) { + i++; + } else { + j++; + } + } + + return minDistance; + } + } + ``` + + + + + ```cpp + class WordDistance { + public: + unordered_map> wordMap; + + WordDistance(vector& wordsDict) { + for (int i = 0; i < wordsDict.size(); ++i) { + wordMap[wordsDict[i]].push_back(i); + } + } + + int shortest(string word1, string word2) { + const vector& indices1 = wordMap[word1]; + const vector& indices2 = wordMap[word2]; + int i = 0, j = 0, minDistance = INT_MAX; + + while (i < indices1.size() && j < indices2.size()) { + minDistance = min(minDistance, abs(indices1[i] - indices2[j])); + if (indices1[i] < indices2[j]) { + ++i; + + + } else { + ++j; + } + } + + return minDistance; + } + }; + ``` + + + + +#### Complexity Analysis + +- **Time Complexity:** $O(n + k)$, where `n` is the number of words in `wordsDict` and `k` is the number of queries. +- **Space Complexity:** $O(n)$, where `n` is the number of words in `wordsDict`. +- The time complexity for preprocessing is $O(n)$ because we iterate through all the words once. +- The space complexity is $O(n)$ because we store the indices of each word in a hash table. +- The time complexity for each query is $O(k)$, where `k` is the length of the indices list for the words. + +
+
+ +:::tip Note +The hash table approach is efficient and recommended for this problem due to its linear preprocessing time complexity and efficient query handling. +::: + +--- + +## Video Explanation of Shortest Word Distance II + + + + + + --- + + + + + + + + + + + + + + + + + + + + + diff --git a/solutions/lc-solutions/0200-0299/0245-Shortest-Word-Distance-III.md b/solutions/lc-solutions/0200-0299/0245-Shortest-Word-Distance-III.md new file mode 100644 index 0000000..aa0fdca --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0245-Shortest-Word-Distance-III.md @@ -0,0 +1,358 @@ +--- +id: shortest-distance-between-words-III +title: Shortest Distance Between Words -III +sidebar_label: 0245-Shortest Distance Between Words - III +tags: [Hash Map, Two Pointers] +description: Solution to finding the shortest distance between two words in an array of strings. +--- + +## Problem Statement + +- Given an array of strings wordsDict and two strings that already exist in the array word1 and word2, return the shortest distance between the occurrence of these two words in the list. + +- Note: that `word1` and `word2` may be the same. It is guaranteed that they represent two individual words in the list. + +#### Example 1: +```bash + Input: wordsDict = [β€œpractice”, β€œmakes”, β€œperfect”, β€œcoding”, β€œmakes”], word1 = β€œmakes”, word2 = β€œcoding” + Output: 1 +``` + +#### Example 2: + +```bash + Input: wordsDict = [β€œpractice”, β€œmakes”, β€œperfect”, β€œcoding”, β€œmakes”], word1 = β€œmakes”, word2 = β€œmakes” +Output: 3 +``` + + ### Solution + +#### Approach + +1. **Initialization**: + - Initialize two variables to store the most recent positions of `word1` and `word2`. + - Initialize a variable to store the minimum distance, set it to a large value initially. + +2. **Single Pass through the List**: + - Iterate through the list, and for each word: + - If the word is `word1`, update the most recent position of `word1`. + - If the word is `word2`, update the most recent position of `word2`. + - If both words are the same, ensure you handle the same word case properly. + - Calculate the distance between the most recent positions of `word1` and `word2` and update the minimum distance if the calculated distance is smaller. + +3. **Output**: + - After iterating through the list, the minimum distance variable will hold the shortest distance between the two words. + + +#### Codes in Different Languages + + + + +```javascript +function shortestDistance(wordsDict, word1, word2) { + let pos1 = -1; + let pos2 = -1; + let minDistance = Infinity; + + for (let i = 0; i < wordsDict.length; i++) { + if (wordsDict[i] === word1) { + pos1 = i; + if (word1 === word2) { + pos2 = pos1; + } + if (pos2 !== -1) { + minDistance = Math.min(minDistance, Math.abs(pos1 - pos2)); + } + } else if (wordsDict[i] === word2) { + pos2 = i; + if (pos1 !== -1) { + minDistance = Math.min(minDistance, Math.abs(pos1 - pos2)); + } + } + } + + return minDistance; +} + +// Example usage: +const wordsDict1 = ["practice", "makes", "perfect", "coding", "makes"]; +const word1 = "makes"; +const word2 = "coding"; +console.log(shortestDistance(wordsDict1, word1, word2)); // Output: 1 + +const wordsDict2 = ["practice", "makes", "perfect", "coding", "makes"]; +const word1Same = "makes"; +const word2Same = "makes"; +console.log(shortestDistance(wordsDict2, word1Same, word2Same)); // Output: 3 +``` + + + + +```typescript +function shortestDistance(wordsDict: string[], word1: string, word2: string): number { + let pos1: number = -1; + let pos2: number = -1; + let minDistance: number = Infinity; + + for (let i = 0; i < wordsDict.length; i++) { + if (wordsDict[i] === word1) { + pos1 = i; + if (word1 === word2) { + pos2 = pos1; + } + if (pos2 !== -1) { + minDistance = Math.min(minDistance, Math.abs(pos1 - pos2)); + } + } else if (wordsDict[i] === word2) { + pos2 = i; + if (pos1 !== -1) { + minDistance = Math.min(minDistance, Math.abs(pos1 - pos2)); + } + } + } + + return minDistance; +} + +// Example usage: +const wordsDict1: string[] = ["practice", "makes", "perfect", "coding", "makes"]; +const word1: string = "makes"; +const word2: string = "coding"; +console.log(shortestDistance(wordsDict1, word1, word2)); // Output: 1 + +const wordsDict2: string[] = ["practice", "makes", "perfect", "coding", "makes"]; +const word1Same: string = "makes"; +const word2Same: string = "makes"; +console.log(shortestDistance(wordsDict2, word1Same, word2Same)); // Output: 3 +``` + + + +```java +public class ShortestWordDistance { + public int shortestDistance(String[] wordsDict, String word1, String word2) { + int pos1 = -1; + int pos2 = -1; + int minDistance = Integer.MAX_VALUE; + + for (int i = 0; i < wordsDict.length; i++) { + if (wordsDict[i].equals(word1)) { + pos1 = i; + if (word1.equals(word2)) { + pos2 = pos1; + } + if (pos2 != -1) { + minDistance = Math.min(minDistance, Math.abs(pos1 - pos2)); + } + } else if (wordsDict[i].equals(word2)) { + pos2 = i; + if (pos1 != -1) { + minDistance = Math.min(minDistance, Math.abs(pos1 - pos2)); + } + } + } + + return minDistance; + } + + public static void main(String[] args) { + ShortestWordDistance solution = new ShortestWordDistance(); + + String[] wordsDict1 = {"practice", "makes", "perfect", "coding", "makes"}; + String word1 = "makes"; + String word2 = "coding"; + System.out.println(solution.shortestDistance(wordsDict1, word1, word2)); // Output: 1 + + String[] wordsDict2 = {"practice", "makes", "perfect", "coding", "makes"}; + String word1Same = "makes"; + String word2Same = "makes"; + System.out.println(solution.shortestDistance(wordsDict2, word1Same, word2Same)); // Output: 3 + } +} +``` + + + + ```python + def shortestDistance(wordsDict, word1, word2): + pos1, pos2 = -1, -1 + min_distance = float('inf') + + for i, word in enumerate(wordsDict): + if word == word1: + pos1 = i + if word1 == word2: + pos2 = pos1 + if pos2 != -1: + min_distance = min(min_distance, abs(pos1 - pos2)) + + elif word == word2: + pos2 = i + if pos1 != -1: + min_distance = min(min_distance, abs(pos1 - pos2)) + + return min_distance + wordsDict = ["practice", "makes", "perfect", "coding", "makes"] + word1 = "makes" + word2 = "coding" + print(shortestDistance(wordsDict, word1, word2)) # Output: 1 + + wordsDict = ["practice", "makes", "perfect", "coding", "makes"] + word1 = "makes" + word2 = "makes" + print(shortestDistance(wordsDict, word1, word2)) # Output: 3 +``` + + + +```cpp +#include +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + int shortestDistance(vector& wordsDict, string word1, string word2) { + int pos1 = -1; + int pos2 = -1; + int minDistance = INT_MAX; + + for (int i = 0; i < wordsDict.size(); ++i) { + if (wordsDict[i] == word1) { + pos1 = i; + if (word1 == word2) { + pos2 = pos1; + } + if (pos2 != -1) { + minDistance = min(minDistance, abs(pos1 - pos2)); + } + } else if (wordsDict[i] == word2) { + pos2 = i; + if (pos1 != -1) { + minDistance = min(minDistance, abs(pos1 - pos2)); + } + } + } + + return minDistance; + } +}; + +int main() { + Solution solution; + + vector wordsDict1 = {"practice", "makes", "perfect", "coding", "makes"}; + string word1 = "makes"; + string word2 = "coding"; + cout << solution.shortestDistance(wordsDict1, word1, word2) << endl; // Output: 1 + + vector wordsDict2 = {"practice", "makes", "perfect", "coding", "makes"}; + string word1Same = "makes"; + string word2Same = "makes"; + cout << solution.shortestDistance(wordsDict2, word1Same, word2Same) << endl; // Output: 3 + + return 0; +} +``` + + + +### Explanation: + + + +- **Initialization**: `pos1` and `pos2` are initialized to `-1` to indicate that the positions of `word1` and `word2` have not been found yet. `minDistance` is set to `Infinity` to ensure any found distance will be smaller. +- **Single Pass**: We iterate through the list, and for each occurrence of `word1` or `word2`, we update the respective positions. +- **Distance Calculation**: If both positions have been updated at least once, we calculate the distance and update `minDistance` if the new distance is smaller. +- **Handling Same Words**: If `word1` is the same as `word2`, we set `pos2` to `pos1` whenever `word1` is found to ensure we calculate the distance correctly between different occurrences of the same word. + + + + +- **Initialization**: `pos1` and `pos2` are initialized to `-1` to indicate that the positions of `word1` and `word2` have not been found yet. `minDistance` is set to `Infinity` to ensure any found distance will be smaller. +- **Single Pass**: We iterate through the list, and for each occurrence of `word1` or `word2`, we update the respective positions. +- **Distance Calculation**: If both positions have been updated at least once, we calculate the distance and update `minDistance` if the new distance is smaller. +- **Handling Same Words**: If `word1` is the same as `word2`, we set `pos2` to `pos1` whenever `word1` is found to ensure we calculate the distance correctly between different occurrences of the same word. + + +- **Initialization**: `pos1` and `pos2` are initialized to `-1` to indicate that the positions of `word1` and `word2` have not been found yet. `minDistance` is set to `Integer.MAX_VALUE` to ensure any found distance will be smaller. +- **Single Pass**: We iterate through the list, and for each occurrence of `word1` or `word2`, we update the respective positions. +- **Distance Calculation**: If both positions have been updated at least once, we calculate the distance and update `minDistance` if the new distance is smaller. +- **Handling Same Words**: If `word1` is the same as `word2`, we set `pos2` to `pos1` whenever `word1` is found to ensure we calculate the distance correctly between different occurrences of the same word. + + + +- **Initialization**: `pos1` and `pos2` are initialized to `-1` to indicate that the positions of `word1` and `word2` have not been found yet. `min_distance` is set to infinity to ensure any found distance will be smaller. +- **Single Pass**: We iterate through the list, and for each occurrence of `word1` or `word2`, we update the respective positions. +- **Distance Calculation**: If both positions have been updated at least once, we calculate the distance and update `min_distance` if the new distance is smaller. +- **Handling Same Words**: If `word1` is the same as `word2`, we set `pos2` to `pos1` whenever `word1` is found to ensure we calculate the distance correctly between different occurrences of the same word. + + + +- **Initialization**: `pos1` and `pos2` are initialized to `-1` to indicate that the positions of `word1` and `word2` have not been found yet. `minDistance` is set to `INT_MAX` to ensure any found distance will be smaller. +- **Single Pass**: We iterate through the list, and for each occurrence of `word1` or `word2`, we update the respective positions. +- **Distance Calculation**: If both positions have been updated at least once, we calculate the distance and update `minDistance` if the new distance is smaller. +- **Handling Same Words**: If `word1` is the same as `word2`, we set `pos2` to `pos1` whenever `word1` is found to ensure we calculate the distance correctly between different occurrences of the same word. + + + + + +### Complexity + + + +- **O(n)**: The solution involves a single pass through the list `wordsDict`, where `n` is the length of the list. During this pass, each element is checked and possibly used to update positions and compute distances, which are all O(1) operations. + +- **O(1)**: The solution uses a constant amount of extra space, regardless of the input size. It only maintains a few integer variables (`pos1`, `pos2`, `minDistance`) to store indices and distances. There are no data structures whose size grows with the input. + + + + +- **Time Complexity**: `O(n)` + - We iterate through the array `wordsDict` once, where `n` is the length of the array. Each element is processed in constant time. + +- **Space Complexity**: `O(1)` + - We use a constant amount of extra space for variables `pos1`, `pos2`, and `minDistance`. No additional data structures are used that grow with the size of the input. + + + +- **Time Complexity**: `O(n)` + - We iterate through the array `wordsDict` once, where `n` is the length of the array. Each element is processed in constant time. + +- **Space Complexity**: `O(1)` + - We use a constant amount of extra space for variables `pos1`, `pos2`, and `minDistance`. No additional data structures are used that grow with the size of the input. + + +- **O(n)**: The solution involves a single pass through the list `wordsDict`, where `n` is the length of the list. In this pass, each element is checked and possibly used to update positions and compute distances, which are all O(1) operations. + +- **O(1)**: The solution uses a constant amount of extra space, regardless of the input size. It only maintains a few integer variables (`pos1`, `pos2`, `min_distance`) to store indices and distances. There are no data structures whose size grows with the input. + + + +- **Time Complexity**: `O(n)` + - We iterate through the array `wordsDict` once, where `n` is the length of the array. Each element is processed in constant time. + +- **Space Complexity**: `O(1)` + - We use a constant amount of extra space for variables `pos1`, `pos2`, and `minDistance`. No additional data structures are used that grow with the size of the input. + + + + +## References + +- **LeetCode Problem:** [Shortest Word Distance-III](https://leetcode.com/problems/shortest-word-distance-iii/) + +

Author:

+ +
+{['sivaprasath2004'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0200-0299/0246-Strobogrammatic-Number.md b/solutions/lc-solutions/0200-0299/0246-Strobogrammatic-Number.md new file mode 100644 index 0000000..ed3b425 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0246-Strobogrammatic-Number.md @@ -0,0 +1,315 @@ +--- +id: strobogrammatic-number +title: Strobogrammatic Number +sidebar_label: 0246-Strobogrammatic Number +tags: [Hash Map, Two Pointers] +description: Solution to finding the Strobogrammatic Number in an array of strings. +--- + +### Description + + +A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). + +Write a function to determine if a number is strobogrammatic. The number is represented as a string. + +### Example: + + +**Example 1:** + +```bash +Input: "69" +Output: true +``` + +**Example 2:** +```bash +Input: "88" +Output: true +``` + +**Example 3:** +```bash +Input: "962" +Output: false +``` + +### Solution + +#### Approach + +1. Create a dictionary to map each digit to its strobogrammatic counterpart. +2. Iterate over the number from both ends towards the center. +3. For each pair of digits, check if they are valid strobogrammatic pairs using the dictionary. +4. Return true if all pairs are valid, otherwise return false. + + +#### Codes in Different Languages + + + + + +```javascript +function isStrobogrammatic(num) { + const strobogrammaticMap = { + '0': '0', + '1': '1', + '6': '9', + '8': '8', + '9': '6' + }; + let left = 0, right = num.length - 1; + while (left <= right) { + if (!(num[left] in strobogrammaticMap) || strobogrammaticMap[num[left]] !== num[right]) { + return false; + } + left++; + right--; + } + return true; +} + +// Example usage: +console.log(isStrobogrammatic("69")); // Output: true +console.log(isStrobogrammatic("88")); // Output: true +console.log(isStrobogrammatic("962")); // Output: false +``` + + + + + + +```typescript +function isStrobogrammatic(num: string): boolean { + const strobogrammaticMap: { [key: string]: string } = { + '0': '0', + '1': '1', + '6': '9', + '8': '8', + '9': '6' + }; + let left = 0, right = num.length - 1; + while (left <= right) { + if (!(num[left] in strobogrammaticMap) || strobogrammaticMap[num[left]] !== num[right]) { + return false; + } + left++; + right--; + } + return true; +} + +// Example usage: +console.log(isStrobogrammatic("69")); // Output: true +console.log(isStrobogrammatic("88")); // Output: true +console.log(isStrobogrammatic("962")); // Output: false +``` + + + + + + +```python +def isStrobogrammatic(num): + strobogrammatic_map = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'} + left, right = 0, len(num) - 1 + while left <= right: + if num[left] not in strobogrammatic_map or strobogrammatic_map[num[left]] != num[right]: + return False + left += 1 + right -= 1 + return True + +# Example usage: +print(isStrobogrammatic("69")) # Output: true +print(isStrobogrammatic("88")) # Output: true +print(isStrobogrammatic("962")) # Output: false +``` + + + + + +```java +import java.util.HashMap; +import java.util.Map; + +public class StrobogrammaticNumber { + public static boolean isStrobogrammatic(String num) { + Map strobogrammaticMap = new HashMap<>(); + strobogrammaticMap.put('0', '0'); + strobogrammaticMap.put('1', '1'); + strobogrammaticMap.put('6', '9'); + strobogrammaticMap.put('8', '8'); + strobogrammaticMap.put('9', '6'); + + int left = 0, right = num.length() - 1; + while (left <= right) { + if (!strobogrammaticMap.containsKey(num.charAt(left)) || strobogrammaticMap.get(num.charAt(left)) != num.charAt(right)) { + return false; + } + left++; + right--; + } + return true; + } + + public static void main(String[] args) { + System.out.println(isStrobogrammatic("69")); // Output: true + System.out.println(isStrobogrammatic("88")); // Output: true + System.out.println(isStrobogrammatic("962")); // Output: false + } +} +``` + + + + + +```cpp +#include +#include +#include + +using namespace std; + +bool isStrobogrammatic(string num) { + unordered_map strobogrammaticMap = { + {'0', '0'}, + {'1', '1'}, + {'6', '9'}, + {'8', '8'}, + {'9', '6'} + }; + + int left = 0, right = num.length() - 1; + while (left <= right) { + if (strobogrammaticMap.find(num[left]) == strobogrammaticMap.end() || strobogrammaticMap[num[left]] != num[right]) { + return false; + } + left++; + right--; + } + return true; +} + +int main() { + cout << boolalpha; + cout << isStrobogrammatic("69") << endl; // Output: true + cout << isStrobogrammatic("88") << endl; // Output: true + cout << isStrobogrammatic("962") << endl; // Output: false + return 0; +} +``` + + + + +#### Explanation: + + + + +1. The `strobogrammaticMap` defines the valid strobogrammatic pairs. +2. Two pointers, `left` and `right`, traverse the string from both ends towards the center. +3. For each pair of digits, we check if they exist in the map and match the required strobogrammatic counterpart. +4. If any pair is invalid, return false; if all pairs are valid, return true. + + + + + +1. The `strobogrammaticMap` defines the valid strobogrammatic pairs. +2. Two pointers, `left` and `right`, traverse the string from both ends towards the center. +3. For each pair of digits, we check if they exist in the map and match the required strobogrammatic counterpart. +4. If any pair is invalid, return false; if all pairs are valid, return true. + + + + + +1. The dictionary `strobogrammatic_map` defines the valid strobogrammatic pairs. +2. Two pointers, `left` and `right`, are used to traverse the number from both ends. +3. For each pair of digits, we check if they are in the dictionary and match the required strobogrammatic counterpart. +4. If any pair is invalid, return false; if all pairs are valid, return true. + + + + + +1. The `strobogrammaticMap` defines the valid strobogrammatic pairs. +2. Two pointers, `left` and `right`, traverse the string from both ends towards the center. +3. For each pair of digits, we check if they exist in the map and match the required strobogrammatic counterpart. +4. If any pair is invalid, return false; if all pairs are valid, return true. + + + + + +1. The `strobogrammaticMap` defines the valid strobogrammatic pairs. +2. Two pointers, `left` and `right`, traverse the string from both ends towards the center. +3. For each pair of digits, we check if they exist in the map and match the required strobogrammatic counterpart. +4. If any pair is invalid, return false; if all pairs are valid, return true. + + + + + +#### Complexity: + + + + +1. **Time complexity**: $O(n)$, where $n$ is the length of the input string, as we only iterate through the string once. +2. **Space complexity**: $O(1)$, as we use a fixed amount of extra space for the map and pointers. +3. This makes the approach efficient and suitable for checking strobogrammatic properties in linear time. + + + + + +1. **Time complexity**: $O(n)$, where $n$ is the length of the input string, as we only iterate through the string once. +2. **Space complexity**: $O(1)$, as we use a fixed amount of extra space for the map and pointers. +3. This makes the approach efficient and suitable for checking strobogrammatic properties in linear time. + + + + + +1. Time complexity: $O(n)$, where $n$ is the length of the input string, as we only iterate through the string once. +2. Space complexity: $O(1)$, as we use a fixed amount of extra space for the dictionary and pointers. +3. This makes the approach efficient and suitable for checking strobogrammatic properties in linear time. + + + + + +1. **Time complexity**: $O(n)$, where $n$ is the length of the input string, as we only iterate through the string once. +2. **Space complexity**: $O(1)$, as we use a fixed amount of extra space for the map and pointers. +3. This makes the approach efficient and suitable for checking strobogrammatic properties in linear time. + + + + +1. **Time complexity**: $O(n)$, where $n$ is the length of the input string, as we only iterate through the string once. +2. **Space complexity**: $O(1)$, as we use a fixed amount of extra space for the map and pointers. +3. This makes the approach efficient and suitable for checking strobogrammatic properties in linear time. + + + + +## References + +- **LeetCode Problem:** [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) + +

Author:

+ +
+{['sivaprasath2004'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/0200-0299/0255-Verify-Preorder-Sequence-in-Binary-Search-Tree.md b/solutions/lc-solutions/0200-0299/0255-Verify-Preorder-Sequence-in-Binary-Search-Tree.md new file mode 100644 index 0000000..a533820 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0255-Verify-Preorder-Sequence-in-Binary-Search-Tree.md @@ -0,0 +1,367 @@ +--- +id: verify-preorder-sequence-in-binary-search-tree +title: Verify Preorder Sequence in Binary Search Tree +sidebar_label: 0255-Verify Preorder Sequence in Binary Search Tree +tags: [Hash Map, Two Pointers,Binary Search Tree] +description: Solution to finding and Verify Preorder Sequence in Binary Search Tree. +--- + +### Description + +Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree. + +You may assume each number in the sequence is unique. + +Consider the following binary search tree: + +```bash + 5 + / \ + 2 6 + / \ + 1 3 +``` + +### Example: + +**Example 1:** +```bash +Input: [5,2,6,1,3] +Output: false +``` + + +**Example 2:** +```bash +Input: [5,2,1,3,6] +Output: true +``` +### Solution + +#### **Approach** + +- Use a stack to simulate the traversal. +- Maintain a variable `low` which represents the lowest value that the next node can take. Initially, set `low` to negative infinity. +- Iterate through the array: + - If we encounter a value less than `low`, it means the sequence is invalid. + - If the current value is greater than the top of the stack, keep popping from the stack and update `low` to the value of the last popped element. This ensures that we are correctly moving to the right subtree. + - Push the current value onto the stack. + + + + + + +```javascript +function verifyPreorder(preorder) { + let stack = []; + let low = -Infinity; + + for (let value of preorder) { + if (value < low) { + return false; + } + while (stack.length > 0 && value > stack[stack.length - 1]) { + low = stack.pop(); + } + stack.push(value); + } + return true; +} + +// Example usage: +const preorder1 = [5, 2, 6, 1, 3]; +console.log(verifyPreorder(preorder1)); // Output: false + +const preorder2 = [5, 2, 1, 3, 6]; +console.log(verifyPreorder(preorder2)); // Output: true +``` + + + + + + +```typescript +function verifyPreorder(preorder: number[]): boolean { + let stack: number[] = []; + let low: number = -Infinity; + + for (let value of preorder) { + if (value < low) { + return false; + } + while (stack.length > 0 && value > stack[stack.length - 1]) { + low = stack.pop()!; + } + stack.push(value); + } + return true; +} + +// Example usage: +const preorder1: number[] = [5, 2, 6, 1, 3]; +console.log(verifyPreorder(preorder1)); // Output: false + +const preorder2: number[] = [5, 2, 1, 3, 6]; +console.log(verifyPreorder(preorder2)); // Output: true +``` + + + + + + +```python +def verifyPreorder(preorder): + stack = [] + low = float('-inf') + + for value in preorder: + if value < low: + return False + while stack and value > stack[-1]: + low = stack.pop() + stack.append(value) + + return True + +# Example usage: +preorder1 = [5, 2, 6, 1, 3] +print(verifyPreorder(preorder1)) # Output: False + +preorder2 = [5, 2, 1, 3, 6] +print(verifyPreorder(preorder2)) # Output: True +``` + + + + + +```java +import java.util.Stack; + +public class Solution { + public boolean verifyPreorder(int[] preorder) { + Stack stack = new Stack<>(); + int low = Integer.MIN_VALUE; + + for (int value : preorder) { + if (value < low) { + return false; + } + while (!stack.isEmpty() && value > stack.peek()) { + low = stack.pop(); + } + stack.push(value); + } + return true; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + int[] preorder1 = {5, 2, 6, 1, 3}; + System.out.println(solution.verifyPreorder(preorder1)); // Output: false + + int[] preorder2 = {5, 2, 1, 3, 6}; + System.out.println(solution.verifyPreorder(preorder2)); // Output: true + } +} +``` + + + + +```cpp +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + bool verifyPreorder(vector& preorder) { + stack stk; + int low = INT_MIN; + + for (int value : preorder) { + if (value < low) { + return false; + } + while (!stk.empty() && value > stk.top()) { + low = stk.top(); + stk.pop(); + } + stk.push(value); + } + + return true; + } +}; + +int main() { + Solution solution; + + vector preorder1 = {5, 2, 6, 1, 3}; + cout << (solution.verifyPreorder(preorder1) ? "true" : "false") << endl; // Output: false + + vector preorder2 = {5, 2, 1, 3, 6}; + cout << (solution.verifyPreorder(preorder2) ? "true" : "false") << endl; // Output: true + + return 0; +} +``` + + + + + +### Explanation: + + + + + + +1. **Initialization**: + - A stack is used to keep track of the nodes. + - `low` is initialized to `-Infinity` to represent the smallest possible value initially. + +2. **Iteration**: + - For each value in the `preorder` array: + - If the value is less than `low`, it means we are visiting a node in the right subtree that violates the BST property, hence return `false`. + - If the current value is greater than the top of the stack, it means we are transitioning from the left subtree to the right subtree. We keep popping the stack and update `low` to ensure that subsequent nodes in the right subtree are greater than this value. + - Push the current value onto the stack. + +3. **Return**: + - If we successfully iterate through the entire array without finding any violations, return `true`. + + + + + + +1. **Initialization**: + - A stack is used to keep track of the nodes. + - `low` is initialized to `-Infinity` to represent the smallest possible value initially. + +2. **Iteration**: + - For each value in the `preorder` array: + - If the value is less than `low`, it means we are visiting a node in the right subtree that violates the BST property, hence return `false`. + - If the current value is greater than the top of the stack, it means we are transitioning from the left subtree to the right subtree. We keep popping the stack and update `low` to ensure that subsequent nodes in the right subtree are greater than this value. + - Push the current value onto the stack. + +3. **Return**: + - If we successfully iterate through the entire array without finding any violations, return `true`. + + + + + +1. **Initialization**: + - A stack is used to keep track of the nodes. + - `low` is initialized to negative infinity to represent the smallest possible value initially. + +2. **Iteration**: + - For each value in the `preorder` array: + - If the value is less than `low`, it means we are visiting a node in the right subtree that violates the BST property, hence return `False`. + - If the current value is greater than the top of the stack, it means we are transitioning from the left subtree to the right subtree. We keep popping the stack and update `low` to ensure that subsequent nodes in the right subtree are greater than this value. + - Push the current value onto the stack. + +3. **Return**: + - If we successfully iterate through the entire array without finding any violations, return `True`. + + + + + +1. **Initialization**: + - A stack is used to keep track of the nodes. + - `low` is initialized to `Integer.MIN_VALUE` to represent the smallest possible value initially. + +2. **Iteration**: + - For each value in the `preorder` array: + - If the value is less than `low`, it means we are visiting a node in the right subtree that violates the BST property, hence return `false`. + - If the current value is greater than the top of the stack, it means we are transitioning from the left subtree to the right subtree. We keep popping the stack and update `low` to ensure that subsequent nodes in the right subtree are greater than this value. + - Push the current value onto the stack. + +3. **Return**: + - If we successfully iterate through the entire array without finding any violations, return `true`. + + + + + +1. **Initialization**: + - A stack is used to keep track of the nodes. + - `low` is initialized to `INT_MIN` to represent the smallest possible value initially. + +2. **Iteration**: + - For each value in the `preorder` array: + - If the value is less than `low`, it means we are visiting a node in the right subtree that violates the BST property, hence return `false`. + - If the current value is greater than the top of the stack, it means we are transitioning from the left subtree to the right subtree. We keep popping the stack and update `low` to ensure that subsequent nodes in the right subtree are greater than this value. + - Push the current value onto the stack. + +3. **Return**: + - If we successfully iterate through the entire array without finding any violations, return `true`. + + + + + +### Complexity: + + + + + + +- **Time Complexity**: `O(n)`, where `n` is the length of the preorder array. Each element is pushed and popped from the stack at most once. +- **Space Complexity**: `O(n)`, where `n` is the length of the preorder array, which is the worst-case space complexity for the stack. + + + + + +- **Time Complexity**: `O(n)`, where `n` is the length of the preorder array. Each element is pushed and popped from the stack at most once. +- **Space Complexity**: `O(n)`, where `n` is the length of the preorder array, which is the worst-case space complexity for the stack. + + + + + + +- **Time Complexity**: `O(n)`, where `n` is the length of the preorder array. Each element is pushed and popped from the stack at most once. +- **Space Complexity**: `O(n)`, where `n` is the length of the preorder array, which is the worst-case space complexity for the stack. + + + + + +- **Time Complexity**: `O(n)`, where `n` is the length of the preorder array. Each element is pushed and popped from the stack at most once. +- **Space Complexity**: `O(n)`, where `n` is the length of the preorder array, which is the worst-case space complexity for the stack. + + + +- **Time Complexity**: `O(n)`, where `n` is the length of the preorder array. Each element is pushed and popped from the stack at most once. +- **Space Complexity**: `O(n)`, where `n` is the length of the preorder array, which is the worst-case space complexity for the stack. + + + + + + +## References + +- **LeetCode Problem:** [Binary Search Tree](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/) + +

Author:

+ +
+{['sivaprasath2004'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/0200-0299/0256-paint-house.md b/solutions/lc-solutions/0200-0299/0256-paint-house.md new file mode 100644 index 0000000..cbaa62f --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0256-paint-house.md @@ -0,0 +1,375 @@ +--- +id: paint-house +title: Paint House +sidebar_label: 0256. Paint House +tags: [Hash Map, Two Pointers] +description: Solution to finding the paint House. +--- + +## Description +- There is a row of n houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. + +- The cost of painting each house with a certain color is represented by an n x 3 cost matrix costs. + +- For example, costs[0][0] is the cost of painting house 0 with the color red; costs[1][2] is the cost of painting house 1 with color green, and so on... +Return the minimum cost to paint all houses. + +## Example: + +**Example 1:** +```bash +Input: costs = [[17,2,17],[16,16,5],[14,3,19]] +Output: 10 +Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. +Minimum cost: 2 + 5 + 3 = 10. +``` + +**Example 2:** +```bash +Input: costs = [[7,6,2]] +Output: 2 + ``` + +## Constraints: +```bash +costs.length == n +costs[i].length == 3 +1 <= n <= 100 +1 <= costs[i][j] <= 20 +``` + +## Solution + +#### Approach + +To solve the "Paint House" problem efficiently, we can use dynamic programming to keep track of the minimum cost to paint each house while ensuring no two adjacent houses have the same color. Here's the step-by-step approach to implement this solution: + +### Approach: + +1. **Initialization**: + - Use the given cost matrix to keep track of the costs. Initialize variables to store the costs of painting the previous house red, blue, or green. + +2. **Dynamic Programming**: + - Iterate through each house starting from the second one, updating the minimum cost to paint the current house with each color based on the previous house's costs. + - For each house, calculate the cost to paint it red, blue, or green as the current cost plus the minimum of the other two costs from the previous house. + +3. **Result**: + - The answer will be the minimum cost to paint the last house with any of the three colors. + + + + + + +```javascript +function minCost(costs) { + if (costs.length === 0) return 0; + + let n = costs.length; + + // Initial cost for the first house + let previousRed = costs[0][0]; + let previousBlue = costs[0][1]; + let previousGreen = costs[0][2]; + + for (let i = 1; i < n; i++) { + let currentRed = costs[i][0] + Math.min(previousBlue, previousGreen); + let currentBlue = costs[i][1] + Math.min(previousRed, previousGreen); + let currentGreen = costs[i][2] + Math.min(previousRed, previousBlue); + + // Update previous costs to current costs for the next iteration + previousRed = currentRed; + previousBlue = currentBlue; + previousGreen = currentGreen; + } + + // The minimum cost of the last house can be any color + return Math.min(previousRed, previousBlue, previousGreen); +} + +// Example usage: +const costs1 = [[17, 2, 17], [16, 16, 5], [14, 3, 19]]; +console.log(minCost(costs1)); // Output: 10 + +const costs2 = [[7, 6, 2]]; +console.log(minCost(costs2)); // Output: 2 +``` + + + + +```typescript +function minCost(costs: number[][]): number { + if (costs.length === 0) return 0; + + let n = costs.length; + + // Initial cost for the first house + let previousRed = costs[0][0]; + let previousBlue = costs[0][1]; + let previousGreen = costs[0][2]; + + for (let i = 1; i < n; i++) { + let currentRed = costs[i][0] + Math.min(previousBlue, previousGreen); + let currentBlue = costs[i][1] + Math.min(previousRed, previousGreen); + let currentGreen = costs[i][2] + Math.min(previousRed, previousBlue); + + // Update previous costs to current costs for the next iteration + previousRed = currentRed; + previousBlue = currentBlue; + previousGreen = currentGreen; + } + + // The minimum cost of the last house can be any color + return Math.min(previousRed, previousBlue, previousGreen); +} + +// Example usage: +const costs1: number[][] = [[17, 2, 17], [16, 16, 5], [14, 3, 19]]; +console.log(minCost(costs1)); // Output: 10 + +const costs2: number[][] = [[7, 6, 2]]; +console.log(minCost(costs2)); // Output: 2 +``` + + + + + +```python +def minCost(costs): + if not costs: + return 0 + + n = len(costs) + + # Initial cost for the first house + previousRed = costs[0][0] + previousBlue = costs[0][1] + previousGreen = costs[0][2] + + for i in range(1, n): + currentRed = costs[i][0] + min(previousBlue, previousGreen) + currentBlue = costs[i][1] + min(previousRed, previousGreen) + currentGreen = costs[i][2] + min(previousRed, previousBlue) + + # Update previous costs to current costs for the next iteration + previousRed = currentRed + previousBlue = currentBlue + previousGreen = currentGreen + + # The minimum cost of the last house can be any color + return min(previousRed, previousBlue, previousGreen) + +# Example usage: +costs1 = [[17, 2, 17], [16, 16, 5], [14, 3, 19]] +print(minCost(costs1)) # Output: 10 + +costs2 = [[7, 6, 2]] +print(minCost(costs2)) # Output: 2 +``` + + + + + + + +```java +public class Solution { + public int minCost(int[][] costs) { + if (costs == null || costs.length == 0) { + return 0; + } + + int n = costs.length; + + // Initial cost for the first house + int previousRed = costs[0][0]; + int previousBlue = costs[0][1]; + int previousGreen = costs[0][2]; + + for (int i = 1; i < n; i++) { + int currentRed = costs[i][0] + Math.min(previousBlue, previousGreen); + int currentBlue = costs[i][1] + Math.min(previousRed, previousGreen); + int currentGreen = costs[i][2] + Math.min(previousRed, previousBlue); + + // Update previous costs to current costs for the next iteration + previousRed = currentRed; + previousBlue = currentBlue; + previousGreen = currentGreen; + } + + // The minimum cost of the last house can be any color + return Math.min(previousRed, Math.min(previousBlue, previousGreen)); + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + int[][] costs1 = {{17, 2, 17}, {16, 16, 5}, {14, 3, 19}}; + System.out.println(solution.minCost(costs1)); // Output: 10 + + int[][] costs2 = {{7, 6, 2}}; + System.out.println(solution.minCost(costs2)); // Output: 2 + } +} +``` + + + + + +```cpp +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + int minCost(vector>& costs) { + if (costs.empty()) return 0; + + int n = costs.size(); + + // Initial cost for the first house + int previousRed = costs[0][0]; + int previousBlue = costs[0][1]; + int previousGreen = costs[0][2]; + + for (int i = 1; i < n; ++i) { + int currentRed = costs[i][0] + min(previousBlue, previousGreen); + int currentBlue = costs[i][1] + min(previousRed, previousGreen); + int currentGreen = costs[i][2] + min(previousRed, previousBlue); + + // Update previous costs to current costs for the next iteration + previousRed = currentRed; + previousBlue = currentBlue; + previousGreen = currentGreen; + } + + // The minimum cost of the last house can be any color + return min({previousRed, previousBlue, previousGreen}); + } +}; + +int main() { + Solution solution; + + vector> costs1 = {{17, 2, 17}, {16, 16, 5}, {14, 3, 19}}; + cout << solution.minCost(costs1) << endl; // Output: 10 + + vector> costs2 = {{7, 6, 2}}; + cout << solution.minCost(costs2) << endl; // Output: 2 + + return 0; +} +``` + + + +### Explanation: + + + +- **Initialization**: We start by assigning the costs of painting the first house to `previousRed`, `previousBlue`, and `previousGreen`. +- **Dynamic Programming**: For each subsequent house, we calculate the cost of painting it each color based on the minimum cost of painting the previous house a different color. + - `currentRed = costs[i][0] + Math.min(previousBlue, previousGreen)` + - `currentBlue = costs[i][1] + Math.min(previousRed, previousGreen)` + - `currentGreen = costs[i][2] + Math.min(previousRed, previousBlue)` +- **Result**: After processing all the houses, the minimum cost of painting the last house can be either red, blue, or green. The final result is the minimum of these three values. + + +- **Initialization**: We start by assigning the costs of painting the first house to `previousRed`, `previousBlue`, and `previousGreen`. +- **Dynamic Programming**: For each subsequent house, we calculate the cost of painting it each color based on the minimum cost of painting the previous house a different color. + - `currentRed = costs[i][0] + Math.min(previousBlue, previousGreen)` + - `currentBlue = costs[i][1] + Math.min(previousRed, previousGreen)` + - `currentGreen = costs[i][2] + Math.min(previousRed, previousBlue)` +- **Result**: After processing all the houses, the minimum cost of painting the last house can be either red, blue, or green. The final result is the minimum of these three values. + + + +1. **Initialization**: + - Initialize the costs for painting the first house (`previousRed`, `previousBlue`, `previousGreen`) using the first row of the input `costs` matrix. + +2. **Dynamic Programming**: + - Iterate through each house starting from the second one (index 1). For each house, calculate the minimum cost to paint it red, blue, or green based on the costs of painting the previous house a different color. + - Update the variables to store the minimum costs for the current house to be used in the next iteration. + +3. **Result**: + - After processing all the houses, the result is the minimum cost of painting the last house, which can be either red, blue, or green. + + +1. **Initialization**: + - Initialize the costs for painting the first house (`previousRed`, `previousBlue`, `previousGreen`) using the first row of the input `costs` matrix. + +2. **Dynamic Programming**: + - Iterate through each house starting from the second one (index 1). For each house, calculate the minimum cost to paint it red, blue, or green based on the costs of painting the previous house a different color. + - Update the variables to store the minimum costs for the current house to be used in the next iteration. + +3. **Result**: + - After processing all the houses, the result is the minimum cost of painting the last house, which can be either red, blue, or green. + + + +1. **Initialization**: + - Initialize the costs for painting the first house (`previousRed`, `previousBlue`, `previousGreen`) using the first row of the input `costs` matrix. + +2. **Dynamic Programming**: + - Iterate through each house starting from the second one (index 1). For each house, calculate the minimum cost to paint it red, blue, or green based on the costs of painting the previous house a different color. + - Update the variables to store the minimum costs for the current house to be used in the next iteration. + +3. **Result**: + - After processing all the houses, the result is the minimum cost of painting the last house, which can be either red, blue, or green. + + + +### Complexity: + + + + +- **Time Complexity**: `O(n)`, where `n` is the number of houses. We only make a single pass through the houses. +- **Space Complexity**: `O(1)`, as we use a constant amount of additional space regardless of the number of houses. + + + +- **Time Complexity**: `O(n)`, where `n` is the number of houses. We only make a single pass through the houses. +- **Space Complexity**: `O(1)`, as we use a constant amount of additional space regardless of the number of houses. + + + +- **Time Complexity**: `O(n)`, where `n` is the number of houses. The solution involves a single pass through the list of houses. +- **Space Complexity**: `O(1)`, as we use a constant amount of extra space for storing the costs of painting the houses. + + + + + +- **Time Complexity**: `O(n)`, where `n` is the number of houses. The solution involves a single pass through the list of houses. +- **Space Complexity**: `O(1)`, as we use a constant amount of extra space for storing the costs of painting the houses. + + + + + +- **Time Complexity**: `O(n)`, where `n` is the number of houses. The solution involves a single pass through the list of houses. +- **Space Complexity**: `O(1)`, as we use a constant amount of extra space for storing the costs of painting the houses. + + + + +## References + +- **LeetCode Problem:** [paint house](https://leetcode.com/problems/paint-house/) + +

Author:

+ +
+{['sivaprasath2004'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/0200-0299/0257-Binary-Tree-Paths.md b/solutions/lc-solutions/0200-0299/0257-Binary-Tree-Paths.md new file mode 100644 index 0000000..c459ae7 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0257-Binary-Tree-Paths.md @@ -0,0 +1,195 @@ +--- +id: binary-tree-paths +title: Binary Tree Paths +sidebar_label: 0257. Binary Tree Paths +tags: +- Tree +- Depth-First Search +description: "Solution to Leetcode 257. Binary Tree Paths" +--- + +## Problem Description + +Given the root of a binary tree, return all root-to-leaf paths in any order. + +A leaf is a node with no children. + +### Examples + +**Example 1:** + +``` +Input: root = [1,2,3,null,5] +Output: ["1->2->5","1->3"] +``` + +**Example 2:** + +``` +Input: root = [1] +Output: ["1"] +``` + +### Constraints +- The number of nodes in the tree is in the range [1, 100]. +- $-100 \leq \text{Node.val} \leq 100$ + +### Approach +1. Define a `TreeNode` class to represent the nodes in the binary tree. +2. Create a `Solution` class with a method `binaryTreePaths` to find all root-to-leaf paths. +3. Use a helper function `construct_paths` to perform depth-first search (DFS) to construct paths from the root to leaf nodes. +4. If a node is a leaf, add the path to the result list. Otherwise, extend the current path and recursively call the helper function for the left and right children. +5. Return the list of paths. + +### Complexity + +Time complexity: $O(n)$, where n is the number of nodes in the tree, since we need to visit each node. + +Space complexity: $O(n)$, since the maximum depth of the recursion tree can go up to n. + +### Solution + +#### Code in Different Languages + +#### Python + +```python +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def binaryTreePaths(self, root: TreeNode) -> list[str]: + def construct_paths(node, path): + if node: + path += str(node.val) + if not node.left and not node.right: # if reach a leaf + paths.append(path) # update paths + else: + path += '->' # extend the current path + construct_paths(node.left, path) + construct_paths(node.right, path) + + paths = [] + construct_paths(root, '') + return paths + +# Example Usage +# Constructing the tree [1, 2, 3, null, 5] +root = TreeNode(1) +root.left = TreeNode(2) +root.right = TreeNode(3) +root.left.right = TreeNode(5) + +solution = Solution() +print(solution.binaryTreePaths(root)) # Output: ["1->2->5", "1->3"] +``` + +#### C++ + +```cpp +#include +#include + +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector binaryTreePaths(TreeNode* root) { + vector paths; + construct_paths(root, "", paths); + return paths; + } + + void construct_paths(TreeNode* node, string path, vector& paths) { + if (node) { + path += to_string(node->val); + if (!node->left && !node->right) { // if reach a leaf + paths.push_back(path); // update paths + } else { + path += "->"; // extend the current path + construct_paths(node->left, path, paths); + construct_paths(node->right, path, paths); + } + } + } +}; + +// Example Usage +// Constructing the tree [1, 2, 3, null, 5] +TreeNode* root = new TreeNode(1); +root->left = new TreeNode(2); +root->right = new TreeNode(3); +root->left->right = new TreeNode(5); + +Solution solution; +vector result = solution.binaryTreePaths(root); // Output: ["1->2->5", "1->3"] +``` + +#### Java + +```java +import java.util.ArrayList; +import java.util.List; + +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +class Solution { + public List binaryTreePaths(TreeNode root) { + List paths = new ArrayList<>(); + construct_paths(root, "", paths); + return paths; + } + + private void construct_paths(TreeNode node, String path, List paths) { + if (node != null) { + path += Integer.toString(node.val); + if (node.left == null && node.right == null) { // if reach a leaf + paths.add(path); // update paths + } else { + path += "->"; // extend the current path + construct_paths(node.left, path, paths); + construct_paths(node.right, path, paths); + } + } + } + + public static void main(String[] args) { + // Example Usage + // Constructing the tree [1, 2, 3, null, 5] + TreeNode root = new TreeNode(1); + root.left = new TreeNode(2); + root.right = new TreeNode(3); + root.left.right = new TreeNode(5); + + Solution solution = new Solution(); + List result = solution.binaryTreePaths(root); // Output: ["1->2->5", "1->3"] + System.out.println(result); + } +} +``` + +### Complexity Analysis + +- Time Complexity: $O(n)$ +- Space Complexity: $O(n)$ + +### References + +- **LeetCode Problem**: Binary Tree Paths diff --git a/solutions/lc-solutions/0200-0299/0258-Add-digits.md b/solutions/lc-solutions/0200-0299/0258-Add-digits.md new file mode 100644 index 0000000..308e380 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0258-Add-digits.md @@ -0,0 +1,95 @@ +--- +id: add-digits +title: Add Digits +sidebar_label: 0258-Add-digits +tags: ['Math', 'Simulation', 'NumberTheory' ] +description: "Given an integer num, repeatedly add all its digits until the result has only one digit, and return it." +--- + +## Problem + +Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it.. + +### Examples + +**Example 1:** +``` +Input: num = 38 +Output: 2 +Explanation: The process is +38 --> 3 + 8 --> 11 +11 --> 1 + 1 --> 2 +Since 2 has only one digit, return it. +``` +**Example 2:** +``` +Input: num = 0 +Output: 0 +``` +### Constraints + +- `0 <= num <= 2^31 - 1` + +### Approach + +Any number where it's digits add to `9` is always divisible by `9`. `(18, 27, 36, 45, 54, 63, 72, 81, 90, etc.)` Therefore the 'digital root' for any number divisible by `9` is always `9`. You can see this even in larger numbers like 99 because `9 + 9 = 18`, and then `1 + 8 = 9` still, so the root always becomes `9` for any numbers divisible by `9`. + +Additionally, 0 always has a digital root of 0 obviously. + +The only other cases you need to worry about to find the digital root are when it isn't 0 or 9. + +So for any number that isn't 0 and isn't divisible by 9, the root will always `n % 9` for a given number n. (AKA the difference between given number n and the nearest number that is divisible by `9`, since numbers divisible by `9` always have a digital root of `9`). +For examples: `100 % 9 = 1 (one greater than 99, which is divisible by 9)`. +`101 % 9 = 2` +`102 % 9 = 3` and so on. + +This explanation/algorithm skips the whole "add digits until there is only 1 remaining", so the description of this problem seems pretty misleading to me since it makes you think the solution will be something unrelated to the optimal one. I guess the point of Leetcode is to learn all of these tricks though. + + + +### Solution + +#### Code in Different Languages + +### C++ Solution +```cpp +class Solution { +public: + int addDigits(int num) { + if(num == 0) return 0; + else if(num % 9 == 0) return 9; + else return num % 9; + } +}; +``` +### Java Solution +```java +class Solution { + public int addDigits(int num) { + if(num == 0) return 0; + else if(num % 9 == 0) return 9; + else return num % 9; + } +} +``` +### Python Solution + +```python +class Solution: + def addDigits(self, num: int) -> int: + if num == 0 : return 0 + if num % 9 == 0 : return 9 + else : return (num % 9) +``` +### Complexity Analysis +**Time Complexity:** $O(1)$ + + +**Space Complexity:** $O(1)$ + + +This solution efficiently add the digits of a number in $o(1)$ space complexity and $o(1)$ time complexity + +### References +**LeetCode Problem:** Add-digits + diff --git a/solutions/lc-solutions/0200-0299/0260-Single-Number-III.md b/solutions/lc-solutions/0200-0299/0260-Single-Number-III.md new file mode 100644 index 0000000..34bdf89 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0260-Single-Number-III.md @@ -0,0 +1,136 @@ +--- +id: single-number-III +title: Single Number III +sidebar_label: 0260-Single-Number-III +tags: + - Array + - Bit Manipulation + - C++ + - Java + - Python +description: "Given an integer array `nums`, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order." +--- + +## Problem + +Given an integer array `nums`, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order. + +You must write an algorithm that runs in linear runtime complexity and uses only constant extra space. + +### Examples + +**Example 1:** +``` +Input: nums = [1,2,1,3,2,5] +Output: [3,5] +Explanation: [5, 3] is also a valid answer. +``` +**Example 2:** + +Input: nums = [-1,0] +Output: [-1,0] + +**Example 3:** + +Input: nums = [0,1] +Output: [1,0] + + +### Constraints + +- `2 <= nums.length <= 3 * 10^4` +- `-2^31 <= nums[i] <= 2^31 - 1` +- Each integer in `nums` will appear twice, only two integers will appear once. + +### Approach + +Once again, we need to use XOR to solve this problem. But this time, we need to do it in two passes: + +- In the first pass, we XOR all elements in the array, and get the XOR of the two numbers we need to find. Note that since the two numbers are distinct, so there must be a set bit (that is, `the bit with value '1'`) in the XOR result. Find +out an arbitrary set bit (for example, the rightmost set bit). + +- In the second pass, we divide all numbers into two groups, one with the aforementioned bit set, another with the aforementinoed bit unset. Two different numbers we need to find must fall into thte two distrinct groups. XOR numbers in each group, we can find a number in either group. + +### Solution + +#### Code in Different Languages + +### C++ Solution +```cpp +class Solution +{ +public: + vector singleNumber(vector& nums) + { + // Pass 1 : + // Get the XOR of the two numbers we need to find + int diff = accumulate(nums.begin(), nums.end(), 0, bit_xor()); + // Get its last set bit + diff &= -diff; + + // Pass 2 : + vector rets = {0, 0}; // this vector stores the two numbers we will return + for (int num : nums) + { + if ((num & diff) == 0) // the bit is not set + { + rets[0] ^= num; + } + else // the bit is set + { + rets[1] ^= num; + } + } + return rets; + } +}; +``` +### Java Solution + +```java +public class Solution { + public int[] singleNumber(int[] nums) { + // Pass 1 : + // Get the XOR of the two numbers we need to find + int diff = 0; + for (int num : nums) { + diff ^= num; + } + // Get its last set bit + diff &= -diff; + + // Pass 2 : + int[] rets = {0, 0}; // this array stores the two numbers we will return + for (int num : nums) + { + if ((num & diff) == 0) // the bit is not set + { + rets[0] ^= num; + } + else // the bit is set + { + rets[1] ^= num; + } + } + return rets; + } +} +``` +### Python Solution + +```python +class Solution: + def singleNumber(self, nums): + s = reduce(xor, nums) + nz = s & (s-1) ^ s + num1 = reduce(xor, filter(lambda n: n & nz, nums)) + return(num1, s ^ num1) + +``` +### Complexity Analysis +**Time Complexity:** O(N) + +**Space Complexity:** O(1) + +### References +**LeetCode Problem:** Single Number III diff --git a/solutions/lc-solutions/0200-0299/0263-Ugly-Number.md b/solutions/lc-solutions/0200-0299/0263-Ugly-Number.md new file mode 100644 index 0000000..1e00868 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0263-Ugly-Number.md @@ -0,0 +1,122 @@ +--- +id: ugly-number +title: Ugly Number +sidebar_label: 0263-Ugly-Number +tags: + - Math + - Number Theory + - C++ + - Java + - Python +description: "This document provides a solution to the Ugly Number problem, where we need to determine if a number is an ugly number." +--- + +## Problem + +An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer `n`, return `true` if `n` is an ugly number. + +### Examples + +**Example 1:** + +Input: n = 6 +Output: true +Explanation: 6 = 2 Γ— 3 + +**Example 2:** + +Input: n = 8 +Output: true +Explanation: 8 = 2 Γ— 2 Γ— 2 + +**Example 3:** + +Input: n = 14 +Output: false +Explanation: 14 is not an ugly number since it includes the prime factor 7. + +**Example 4:** + +Input: n = 1 +Output: true +Explanation: 1 is typically treated as an ugly number. + +### Constraints + +- `-2^31 <= n <= 2^31 - 1` + +### Approach + +To determine if a number is an ugly number, we can follow these steps: + +1. If `n` is less than or equal to 0, return `false` since ugly numbers are positive. +2. Divide `n` by 2, 3, and 5 as long as it is divisible by these numbers. +3. After performing the above division, if the resulting number is 1, then `n` is an ugly number. Otherwise, it is not. + +### Solution + +#### Code in Different Languages + +### C++ Solution +```cpp +#include + +using namespace std; + +bool isUgly(int n) { + if (n <= 0) return false; + while (n % 2 == 0) n /= 2; + while (n % 3 == 0) n /= 3; + while (n % 5 == 0) n /= 5; + return n == 1; +} + +int main() { + int n = 6; + cout << (isUgly(n) ? "true" : "false") << endl; +} +``` +### Java Solution + +```java +public class UglyNumber { + public static boolean isUgly(int n) { + if (n <= 0) return false; + while (n % 2 == 0) n /= 2; + while (n % 3 == 0) n /= 3; + while (n % 5 == 0) n /= 5; + return n == 1; + } + + public static void main(String[] args) { + int n = 6; + System.out.println(isUgly(n) ? "true" : "false"); + } +} +``` +### Python Solution + +```python +def isUgly(n): + if n <= 0: + return False + for i in [2, 3, 5]: + while n % i == 0: + n //= i + return n == 1 + +n = 6 +print(isUgly(n)) +``` +### Complexity Analysis +**Time Complexity:** O(logN) +>Reason: The division operations will run in logarithmic time relative to the input value n. + +**Space Complexity:** O(1) + +>Reason: We use a constant amount of extra space. + +This solution checks whether a number is an ugly number by continually dividing the number by 2, 3, and 5. If the result is 1, the number is an ugly number. The time complexity is logarithmic, and the space complexity is constant, making it efficient for large input values. + +### References +**LeetCode Problem:** Ugly Number diff --git a/solutions/lc-solutions/0200-0299/0264-Ugly-Number-II.md b/solutions/lc-solutions/0200-0299/0264-Ugly-Number-II.md new file mode 100644 index 0000000..a8c4bc8 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0264-Ugly-Number-II.md @@ -0,0 +1,175 @@ +--- +id: ugly-number-II +title: Ugly Number II +sidebar_label: 0264-Ugly-Number-II +tags: + - Math + - Number Theory + - Dynamic Programming + - Heap + - C++ + - Java + - Python +description: "This document provides a solution to the Ugly Number II problem, where we need to find the nth ugly number." +--- + +## Problem + +An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer `n`, return the `n`-th ugly number. + +### Examples + +**Example 1:** + +Input: n = 10 +Output: 12 +Explanation: The sequence of ugly numbers is [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ...], and the 10th ugly number is 12. + +**Example 2:** + +Input: n = 1 +Output: 1 +Explanation: 1 is typically treated as an ugly number. + +### Constraints + +- `1 <= n <= 1690` + +### Approach + +To solve this problem, we can use a dynamic programming approach to generate ugly numbers in sequence: + +1. Initialize an array `ugly_numbers` to store the first `n` ugly numbers. +2. Use three pointers (i2, i3, i5) to track the indices for multiples of 2, 3, and 5 respectively. +3. Start with the first ugly number `1` and iteratively compute the next ugly number by taking the minimum of the next multiples of 2, 3, and 5. +4. Update the corresponding pointer and move to the next position in the `ugly_numbers` array. +5. Repeat until we have generated `n` ugly numbers. + +### Solution + +#### Code in Different Languages + +### C++ Solution +```cpp +#include +#include + +using namespace std; + +int nthUglyNumber(int n) { + vector ugly_numbers(n); + ugly_numbers[0] = 1; + int i2 = 0, i3 = 0, i5 = 0; + int next_multiple_of_2 = 2; + int next_multiple_of_3 = 3; + int next_multiple_of_5 = 5; + + for (int i = 1; i < n; i++) { + int next_ugly = min(next_multiple_of_2, min(next_multiple_of_3, next_multiple_of_5)); + ugly_numbers[i] = next_ugly; + + if (next_ugly == next_multiple_of_2) { + i2++; + next_multiple_of_2 = ugly_numbers[i2] * 2; + } + if (next_ugly == next_multiple_of_3) { + i3++; + next_multiple_of_3 = ugly_numbers[i3] * 3; + } + if (next_ugly == next_multiple_of_5) { + i5++; + next_multiple_of_5 = ugly_numbers[i5] * 5; + } + } + + return ugly_numbers[n - 1]; +} + +int main() { + int n = 10; + cout << nthUglyNumber(n) << endl; // Output: 12 +} +``` +### Java Solution +```java +public class UglyNumberII { + public static int nthUglyNumber(int n) { + int[] ugly_numbers = new int[n]; + ugly_numbers[0] = 1; + int i2 = 0, i3 = 0, i5 = 0; + int next_multiple_of_2 = 2; + int next_multiple_of_3 = 3; + int next_multiple_of_5 = 5; + + for (int i = 1; i < n; i++) { + int next_ugly = Math.min(next_multiple_of_2, Math.min(next_multiple_of_3, next_multiple_of_5)); + ugly_numbers[i] = next_ugly; + + if (next_ugly == next_multiple_of_2) { + i2++; + next_multiple_of_2 = ugly_numbers[i2] * 2; + } + if (next_ugly == next_multiple_of_3) { + i3++; + next_multiple_of_3 = ugly_numbers[i3] * 3; + } + if (next_ugly == next_multiple_of_5) { + i5++; + next_multiple_of_5 = ugly_numbers[i5] * 5; + } + } + + return ugly_numbers[n - 1]; + } + + public static void main(String[] args) { + int n = 10; + System.out.println(nthUglyNumber(n)); // Output: 12 + } +} +``` +### Python Solution + +```python +def nthUglyNumber(n): + ugly_numbers = [0] * n + ugly_numbers[0] = 1 + i2 = i3 = i5 = 0 + next_multiple_of_2 = 2 + next_multiple_of_3 = 3 + next_multiple_of_5 = 5 + + for i in range(1, n): + next_ugly = min(next_multiple_of_2, next_multiple_of_3, next_multiple_of_5) + ugly_numbers[i] = next_ugly + + if next_ugly == next_multiple_of_2: + i2 += 1 + next_multiple_of_2 = ugly_numbers[i2] * 2 + if next_ugly == next_multiple_of_3: + i3 += 1 + next_multiple_of_3 = ugly_numbers[i3] * 3 + if next_ugly == next_multiple_of_5: + i5 += 1 + next_multiple_of_5 = ugly_numbers[i5] * 5 + + return ugly_numbers[n - 1] + +n = 10 +print(nthUglyNumber(n)) # Output: 12 +``` +### Complexity Analysis +**Time Complexity:** O(n) + +>Reason: We iterate through the sequence of ugly numbers up to n. + +**Space Complexity:** O(n) + +>Reason: We use an array to store the first n ugly numbers. + +This solution efficiently finds the n-th ugly number by generating the sequence of ugly numbers using a dynamic programming approach with three pointers for multiples of 2, 3, and 5. + +### References +**LeetCode Problem:** Ugly Number II + + diff --git a/solutions/lc-solutions/0200-0299/0268-Missing-Number.md b/solutions/lc-solutions/0200-0299/0268-Missing-Number.md new file mode 100644 index 0000000..e76bac9 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0268-Missing-Number.md @@ -0,0 +1,67 @@ +--- +id: missing-number +title: Missing Number +sidebar_label: 268-Missing-Number +tags: + - Array + - Hash Table + - Math + - Binary search + - Bit Manupulation + - Sorting + +--- + +## Problem Description + +Given an array `nums` containing `n` distinct numbers in the range `[0, n]`, return the only number in the range that is missing from the array. + + +### Example + +**Example 1:** + +``` +Input: nums = [3,0,1] +Output: 2 +Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. +``` + +**Example 2:** +``` +Input: nums = [0,1] +Output: 2 +Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. +``` + +### Constraints + +- `1 <= n <= 104` + +## Solution Approach + +### Intuition: + +To efficiently determine the missing number in the array + + +## Solution Implementation + +### Code (C++): + +```cpp +class Solution { +public: + int missingNumber(vector& nums) { + int n = nums.size(); + int sum = (n*(n+1))/2; + int s1=0; + for(int i=0; i$0 \leq \text{num} \leq 2^31 - 1$ + +--- + +## Solution for Two Sum Problem + +### Intuition and Approach + +Understanding the structure and pattern of English numbers is essential to translating numbers into their representation in language. By taking into account the following, we may divide the issue into manageable chunks: + +1. We build a list for the unique names of numbers 1 through 19, which do not follow any particular pattern (lt20). +2. We list the tens from 20 to 90 because they have unique names as well. +3. Generally speaking, complex numbers are sums of smaller numbers. For instance, 345 can be interpreted as "Three Hundred Forty-Five," which is the result of adding the smaller number "Forty-Five" to the word "Three Hundred". +4. The way that numbers higher than 99 are named in English is by adding a scale word, such as "Thousand," "Million," or "Billion," and then saying the name of the next number that comes after. + +In light of this, we tackle the issue by developing a recursive function transfer that is capable of handling values smaller than a thousand. Subsequently, we employ an iterative process to apply this function to segments of the input number, gradually decreasing from billions to units, attaching suitable scale terms, and concatenating these segments to generate the complete representation of English words. + +We keep an array thousands, which is made up of scale words divided by a factor of ten, and an adjusted counter to work on fractions of the number, in order to track units of thousand. The number can be divided into segments that can be handled by transfer before the matching scale term (if any) is attached by using division and modulo operations. + +The method begins with the largest unit that can be used, billions, then gradually removes portions of the number until the whole amount has been converted. After that, we combine the created segments and eliminate any remaining spaces to obtain the final representation of the English words. + +#### Code in Different Languages + + + + +```javascript +const map = new Map(); +map.set(1, "One"); +map.set(2, "Two"); +map.set(3, "Three"); +map.set(4, "Four"); +map.set(5, "Five"); +map.set(6, "Six"); +map.set(7, "Seven"); +map.set(8, "Eight"); +map.set(9, "Nine"); +map.set(10, "Ten"); +map.set(11, "Eleven"); +map.set(12, "Twelve"); +map.set(13, "Thirteen"); +map.set(14, "Fourteen"); +map.set(15, "Fifteen"); +map.set(16, "Sixteen"); +map.set(17, "Seventeen"); +map.set(18, "Eighteen"); +map.set(19, "Nineteen"); +map.set(20, "Twenty"); +map.set(30, "Thirty"); +map.set(40, "Forty"); +map.set(50, "Fifty"); +map.set(60, "Sixty"); +map.set(70, "Seventy"); +map.set(80, "Eighty"); +map.set(90, "Ninety"); +map.set(100, "Hundred"); +map.set(1000, "Thousand"); +map.set(1000000, "Million"); +map.set(1000000000, "Billion"); + +function numberToWords(num) { + if (num === 0) { + return "Zero"; + } + let result = ""; + for (let i = 1000000000; i >= 1000; i /= 1000) { + if (num >= i) { + result += get3Digits(Math.floor(num / i)) + " " + map.get(i) + " "; + num %= i; + } + } + if (num > 0) { + result += get3Digits(num); + } + return result.trim(); +} + +function get3Digits(num) { + let result = ""; + if (num >= 100) { + result += " " + map.get(Math.floor(num / 100)) + " " + map.get(100); + num %= 100; + } + if (num > 0) { + if (num < 20 || num % 10 === 0) { + result += " " + map.get(num); + } else { + result += + " " + map.get(Math.floor(num / 10) * 10) + " " + map.get(num % 10); + } + } + return result.trim(); +} +``` + + + + +```typescript +const map: Map = new Map([ + [1, "One"], + [2, "Two"], + [3, "Three"], + [4, "Four"], + [5, "Five"], + [6, "Six"], + [7, "Seven"], + [8, "Eight"], + [9, "Nine"], + [10, "Ten"], + [11, "Eleven"], + [12, "Twelve"], + [13, "Thirteen"], + [14, "Fourteen"], + [15, "Fifteen"], + [16, "Sixteen"], + [17, "Seventeen"], + [18, "Eighteen"], + [19, "Nineteen"], + [20, "Twenty"], + [30, "Thirty"], + [40, "Forty"], + [50, "Fifty"], + [60, "Sixty"], + [70, "Seventy"], + [80, "Eighty"], + [90, "Ninety"], + [100, "Hundred"], + [1000, "Thousand"], + [1000000, "Million"], + [1000000000, "Billion"], +]); +function numberToWords(num: number): string { + if (num === 0) { + return "Zero"; + } + + const sb: string[] = []; + for (let i = 1000000000; i >= 1000; i /= 1000) { + if (num >= i) { + sb.push(get3Digits(Math.floor(num / i))); + sb.push(map.get(i) as string); + num %= i; + } + } + + if (num > 0) { + sb.push(get3Digits(num)); + } + + return sb.join(" ").trim(); +} + +function get3Digits(num: number): string { + const sb: string[] = []; + if (num >= 100) { + sb.push(map.get(Math.floor(num / 100)) as string); + sb.push(map.get(100) as string); + num %= 100; + } + + if (num > 0) { + if (num < 20 || num % 10 === 0) { + sb.push(map.get(num) as string); + } else { + sb.push(map.get(Math.floor(num / 10) * 10) as string); + sb.push(map.get(num % 10) as string); + } + } + + return sb.join(" "); +} +``` + + + + +```python + class Solution: + def numberToWords(self, num: int) -> str: + + if num == 0: + return 'Zero' + + + less_than_20 = [ + '', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', + 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', + 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen' + ] + + + tens = [ + '', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety' + ] + + + thousands = ['Billion', 'Million', 'Thousand', ''] + + + def translate(num): + if num == 0: + return '' + elif num < 20: + return less_than_20[num] + ' ' + elif num < 100: + return tens[num // 10] + ' ' + translate(num % 10) + else: + return less_than_20[num // 100] + ' Hundred ' + translate(num % 100) + + result = [] + i, j = 1000000000, 0 + + + while i > 0: + if num // i != 0: + result.append(translate(num // i)) + result.append(thousands[j]) + result.append(' ') + num %= i + j += 1 + i //= 1000 + + return ''.join(result).strip() +``` + + + + +```java +import java.util.HashMap; +import java.util.Map; + +public class Solution { + + private static final Map NUMBER_TO_WORDS_MAP; + + + static { + NUMBER_TO_WORDS_MAP = new HashMap<>(); + + NUMBER_TO_WORDS_MAP.put(1, "One"); + NUMBER_TO_WORDS_MAP.put(2, "Two"); + NUMBER_TO_WORDS_MAP.put(3, "Three"); + NUMBER_TO_WORDS_MAP.put(4, "Four"); + NUMBER_TO_WORDS_MAP.put(5, "Five"); + NUMBER_TO_WORDS_MAP.put(6, "Six"); + NUMBER_TO_WORDS_MAP.put(7, "Seven"); + NUMBER_TO_WORDS_MAP.put(8, "Eight"); + NUMBER_TO_WORDS_MAP.put(9, "Nine"); + + NUMBER_TO_WORDS_MAP.put(10, "Ten"); + NUMBER_TO_WORDS_MAP.put(11, "Eleven"); + NUMBER_TO_WORDS_MAP.put(12, "Twelve"); + NUMBER_TO_WORDS_MAP.put(13, "Thirteen"); + NUMBER_TO_WORDS_MAP.put(14, "Fourteen"); + NUMBER_TO_WORDS_MAP.put(15, "Fifteen"); + NUMBER_TO_WORDS_MAP.put(16, "Sixteen"); + NUMBER_TO_WORDS_MAP.put(17, "Seventeen"); + NUMBER_TO_WORDS_MAP.put(18, "Eighteen"); + NUMBER_TO_WORDS_MAP.put(19, "Nineteen"); + + NUMBER_TO_WORDS_MAP.put(20, "Twenty"); + NUMBER_TO_WORDS_MAP.put(30, "Thirty"); + NUMBER_TO_WORDS_MAP.put(40, "Forty"); + NUMBER_TO_WORDS_MAP.put(50, "Fifty"); + NUMBER_TO_WORDS_MAP.put(60, "Sixty"); + NUMBER_TO_WORDS_MAP.put(70, "Seventy"); + NUMBER_TO_WORDS_MAP.put(80, "Eighty"); + NUMBER_TO_WORDS_MAP.put(90, "Ninety"); + + NUMBER_TO_WORDS_MAP.put(100, "Hundred"); + NUMBER_TO_WORDS_MAP.put(1000, "Thousand"); + NUMBER_TO_WORDS_MAP.put(1000000, "Million"); + NUMBER_TO_WORDS_MAP.put(1000000000, "Billion"); + } + + + public String numberToWords(int num) { + + if (num == 0) { + return "Zero"; + } + + StringBuilder wordsBuilder = new StringBuilder(); + + + for (int i = 1000000000; i >= 1000; i /= 1000) { + if (num >= i) { + wordsBuilder.append(processThreeDigits(num / i)).append(" ").append(NUMBER_TO_WORDS_MAP.get(i)); + num %= i; + } + } + + + if (num > 0) { + wordsBuilder.append(processThreeDigits(num)); + } + + + return wordsBuilder.substring(1); + } + + + private String processThreeDigits(int num) { + StringBuilder threeDigitsBuilder = new StringBuilder(); + + if (num >= 100) { + threeDigitsBuilder.append(" ") + .append(NUMBER_TO_WORDS_MAP.get(num / 100)) + .append(" ") + .append(NUMBER_TO_WORDS_MAP.get(100)); + num %= 100; + } + if (num > 0) { + + if (num < 20 || num % 10 == 0) { + threeDigitsBuilder.append(" ").append(NUMBER_TO_WORDS_MAP.get(num)); + } else { + + threeDigitsBuilder.append(" ") + .append(NUMBER_TO_WORDS_MAP.get(num / 10 * 10)) + .append(" ") + .append(NUMBER_TO_WORDS_MAP.get(num % 10)); + } + } + return threeDigitsBuilder.toString(); + } +} +``` + + + + +```cpp + #include +#include +#include + +using std::string; +using std::unordered_map; + +class Solution { +public: + + + string numberToWords(int num) { + unordered_map number_to_words_map = {{1, "One"}, + {2, "Two"}, + {3, "Three"}, + {4, "Four"}, + {5, "Five"}, + {6, "Six"}, + {7, "Seven"}, + {8, "Eight"}, + {9, "Nine"}, + {10, "Ten"}, + {11, "Eleven"}, + {12, "Twelve"}, + {13, "Thirteen"}, + {14, "Fourteen"}, + {15, "Fifteen"}, + {16, "Sixteen"}, + {17, "Seventeen"}, + {18, "Eighteen"}, + {19, "Nineteen"}, + {20, "Twenty"}, + {30, "Thirty"}, + {40, "Forty"}, + {50, "Fifty"}, + {60, "Sixty"}, + {70, "Seventy"}, + {80, "Eighty"}, + {90, "Ninety"}, + {100, "Hundred"}, + {1000, "Thousand"}, + {1000000, "Million"}, + {1000000000, "Billion"}}; + if (num == 0) { + return "Zero"; + } + + string words = ""; + + for (int i = 1000000000; i >= 1000; i /= 1000) { + if (num >= i) { + words += + processThreeDigits(num / i, number_to_words_map) + " " + number_to_words_map[i]; + num %= i; + } + } + + if (num > 0) { + words += processThreeDigits(num, number_to_words_map); + } + + if (!words.empty() && words.front() == ' ') { + words = words.substr(1); + } + return words; + } + +private: + string processThreeDigits(int num, unordered_map number_to_words_map) { + string result = ""; + + if (num >= 100) { + result += " " + number_to_words_map[num / 100] + " " + + number_to_words_map[100]; + num %= 100; + } + if (num > 0) { + + if (num < 20 || num % 10 == 0) { + result += " " + number_to_words_map[num]; + } else { + + result += " " + number_to_words_map[num / 10 * 10] + " " + + number_to_words_map[num % 10]; + } + } + return result; + } +}; +``` + + + + +#### Complexity Analysis + +- **Time Complexity:** $O(n)$ +- **Space Complexity:** $O(n)$ +- The time complexity is $O(n)$ where `n` is the number of digits in the input number since each digit or group of digits is processed once +- The space complexity is $O(n)$ due to the storage required for the word representation of the number + +--- + +

Authors:

+ +
+{['Avdhut-Pailwan'].map(username => ( + +))} +
+```` diff --git a/solutions/lc-solutions/0200-0299/0274-H-index.md b/solutions/lc-solutions/0200-0299/0274-H-index.md new file mode 100644 index 0000000..7227f35 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0274-H-index.md @@ -0,0 +1,122 @@ +--- +id: h-index +title: H-Index (LeetCode) +sidebar_label: 0274-H-Index +tags: + - Array + - Sorting + - Counting Sort +description: Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return the researcher's h-index. +sidebar_position: 0274 +--- + +## Problem Description + +Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return the researcher's h-index.According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times. + +### Example 1 + +- **Input:** ` citations = [3,0,6,1,5]` +- **Output:** `3` +- **Explanation:**[3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. +Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. + +### Example 2 + +- **Input:** `citations = [1,3,1] ` +- **Output:** `1` + +### Constraints + +- `n == citations.length` +- `1 <= n <= 5000` +- `0 <= citations[i] <= 1000` + +## Approach +Create a function hasLeastCitations with a parameter h to check if there are at least h papers with >= h citations. When hasLeastCitations(x) is true, hasLeastCitations(x-1) is also true. This means that hasLeastCitations is a monotonic function, so we can binary search for the highest h for which it return true. This h is our h-index. + +### Solution Code + +#### C++ + +```c++ +class Solution { +public: + bool hasLeastCitations(int h, vector& citations) { + int count = 0; + for (int cite_count : citations) { + if (cite_count >= h) + count++; + } + return count >= h; + } + int hIndex(vector& citations) { + int low = 0, high = citations.size(); + while (low <= high) { + int mid = (low + high) / 2; + if (hasLeastCitations(mid, citations)) + low = mid + 1; + else + high = mid - 1; + } + return high; + } +}; +``` + +#### Java +```java +class Solution { + static boolean hasLeastCitations(int h, int[] citations) { + int count = 0; + for (int cite_count : citations) { + if (cite_count >= h) + count++; + } + return count >= h; + } + public int hIndex(int[] citations) { + int low = 0, high = citations.length; + while (low <= high) { + int mid = (low + high) / 2; + if (hasLeastCitations(mid, citations)) + low = mid + 1; + else + high = mid - 1; + } + return high; + } +} +``` + +#### Python +```python +class Solution: + def hIndex(self, citations: List[int]) -> int: + + def hasLeastCitations(h, citations): + return sum(cite_count >= h for cite_count in citations) >= h + + low = 0 + high = len(citations) + while low <= high: + mid = (low + high) // 2 + if hasLeastCitations(mid, citations): + low = mid + 1 + else: + high = mid - 1 + return high + +``` + +#### Conclusion +- Time Complexity + + - 1. Sorting is O(nlogn) + + - 2. Looping is O(n) + + - The total time complexity as O(n log n). + +- Space Complexity +The only memory we allocate is the integer h, so the space complexity is O(1). \ No newline at end of file diff --git a/solutions/lc-solutions/0200-0299/0275-H-Index-II.md b/solutions/lc-solutions/0200-0299/0275-H-Index-II.md new file mode 100644 index 0000000..cfda3dd --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0275-H-Index-II.md @@ -0,0 +1,114 @@ +--- +id: h-Index II +title: H-Index II (LeetCode) +sidebar_label: 0275-H-Index II +tags: + - Array + - Binary Search +description: This is the solution of question H-Index II on leetcode +sidebar_position: 0275 +--- + +## Problem Description + +Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations is sorted in ascending order, return the researcher's h-index. +According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times. + +You must write an algorithm that runs in logarithmic time. + +### Example 1 + +``` +Input: citations = [0,1,3,5,6] +Output: 3 +Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. +Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. +``` + +### Example 2 + +``` +Input: citations = [1,2,100] +Output: 2 +``` + +### Constraints + +- `n == citations.length` +- `1 <= n <= 10^5` +- `0 <= citations[i] <= 1000` + +## Approach +Just binary search, each time check `citations[mid]` +1. `citations[mid] == len-mid`, then it means there are citations[mid] papers that have at least + citations[mid] citations. +2. `citations[mid] > len-mid`, then it means there are `citations[mid]` papers that have moret than + citations[mid] citations, so we should continue searching in the left half +3. `citations[mid] < len-mid`, we should continue searching in the right side + After iteration, it is guaranteed that right+1 is the one we need to find `(i.e. len-(right+1) papars have at least len-(righ+1) citations)` + +### Solution Code + +#### C++ + +```c++ +class Solution { +public: + int hIndex(vector& citations) { + int left=0, len = citations.size(), right= len-1, mid; + while(left<=right) + { + mid=left+ (right-left)/2; + if(citations[mid] >= (len-mid)) right = mid - 1; + else left = mid + 1; + } + return len - left; + } +}; +``` + +#### Java +```java +public int hIndex(int[] citations) { + int len = citations.length; + int lo = 0, hi = len - 1; + while (lo <= hi) { + int med = (hi + lo) / 2; + if (citations[med] == len - med) { + return len - med; + } else if (citations[med] < len - med) { + lo = med + 1; + } else { + //(citations[med] > len-med), med qualified as a hIndex, + // but we have to continue to search for a higher one. + hi = med - 1; + } + } + return len - lo; +} +``` + +#### Python +```python +class Solution: + def hIndex(self, citations): + if not citations: return 0 + n = len(citations) + beg, end = 0, n - 1 + while beg <= end: + mid = (beg + end)//2 + if mid + citations[mid] >= n: + end = mid - 1 + else: + beg = mid + 1 + return n - beg + + +``` + +#### Conclusion +- Time Complexity + - The total time complexity as $O(log n)$. + +- Space Complexity + - The only memory we allocate is the integer h, so the space complexity is O(1). \ No newline at end of file diff --git a/solutions/lc-solutions/0200-0299/0283-move-zeroes.md b/solutions/lc-solutions/0200-0299/0283-move-zeroes.md new file mode 100644 index 0000000..77b0d48 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0283-move-zeroes.md @@ -0,0 +1,85 @@ +--- +id: move-zeroes +title: Move Zeroes(LeetCode) +sidebar_label: 0283-Move Zeroes +tags: + - Array + - Two Pointers +description: Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. +--- + +## Problem Statement + +Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. + +Note that you must do this in-place without making a copy of the array. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [0,1,0,3,12] +Output: [1,3,12,0,0] +``` + +**Example 2:** + +```plaintext +Input: nums = [0] +Output: [0] +``` + +### Constraints + +- `1 <= nums.length <= 104` +- `231 <= nums[i] <= 231 - 1` + +## Solution + +### Explanation +The algorithm employs a two-pointer approach with a `slow` pointer and a `fast` pointer to achieve this task efficiently. + +1. Initialization: +* Initialize the `slow` pointer to 0. The `slow` pointer will track the position to place the next non-zero element. +* The `fast` pointer will traverse the entire array. +2. Traversal: +* Iterate through the array using the `fast` pointer. +* For each element: + * If `nums[fast]` is not zero and `nums[slow]` is zero, swap the elements at the `slow` and `fast` pointers. + * Increment the `slow` pointer if it points to a non-zero element. +3. Swapping: +* This swapping ensures that all non-zero elements are moved to the front of the array, and the zeros are moved to the back. + +### Algorithm + +1. Initialize the `slow` pointer to 0. +2. Iterate through the array with the `fast` pointer from index 0 to the end of the array: +* If `nums[fast]` is not zero and `nums[slow]` is zero: + * Swap `nums[slow]` and `nums[fast]`. +* If `nums[slow]` is not zero, increment the `slow` pointer. + +### Implementation + +```Python +class Solution: + def moveZeroes(self, nums: list) -> None: + slow = 0 + for fast in range(len(nums)): + if nums[fast] != 0 and nums[slow] == 0: + nums[slow], nums[fast] = nums[fast], nums[slow] + + # wait while we find a non-zero element to + # swap with you + if nums[slow] != 0: + slow += 1 +``` + +### Complexity Analysis + +- **Time complexity**: O(n), where n is the number of elements in the array. Each element is processed once by the `fast` pointer. +- **Space complexity**: O(1), as the operations are performed in-place without using extra space. + +### Conclusion + +This approach ensures that all the zeros in the array are moved to the end while maintaining the order of the non-zero elements. The in-place operations guarantee an O(1) space complexity, and each element is processed only once, resulting in an O(n) time complexity. This solution is optimal and efficient for the given problem. diff --git a/solutions/lc-solutions/0200-0299/0283-movezeroes.md b/solutions/lc-solutions/0200-0299/0283-movezeroes.md new file mode 100644 index 0000000..88740af --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0283-movezeroes.md @@ -0,0 +1,116 @@ +--- +id: movezeroes +title: Move Zeroes +sidebar_label: 0283-Move Zeroes +tags: + - Array + - Two Pointers + +description: "This is a solution to the move zeroes in leetcode" +--- + +## Problem Description + +Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. + +Note that you must do this in-place without making a copy of the array. + + + + +### Examples + +**Example 1:** + +``` +Input: nums = [0,1,0,3,12] +Output: [1,3,12,0,0] + +``` +**Example 2:** +``` +Input: nums = [0] +Output: [0] + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(n)$ + +*** Space Complexity:** $O(1)$ + +### Constraints + +- `1 <= nums.length <= 104` +- `-231 <= nums[i] <= 231 - 1` + + + +### Solution +## Approach +The approach to solving the "Move Zeroes" problem involves iterating through the list while maintaining a pointer to track the position for non-zero elements. Initialize a pointer l to zero, which represents the index where the next non-zero element should be placed. As you traverse the list with another pointer r, check each element. If an element is non-zero, swap it with the element at index l and then increment l. This effectively moves non-zero elements to the front while shifting zeros towards the end. The result is that all non-zero elements are moved to the beginning of the list in their original order, followed by all zeros. This method ensures in-place modification of the list with a linear time complexity of O(n) and constant space complexity O(1). +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + void moveZeroes(vector& nums) { + int l = 0; + for (int r = 0; r < nums.size(); ++r) { + if (nums[r] != 0) { + swap(nums[l], nums[r]); + l++; + } + } + } +}; +``` + + + + +```java +class Solution { + public void moveZeroes(List nums) { + int l = 0; + for (int r = 0; r < nums.size(); r++) { + if (nums.get(r) != 0) { + + int temp = nums.get(l); + nums.set(l, nums.get(r)); + nums.set(r, temp); + l++; + } + } +} +} + +``` + + + + +```python +class Solution: + def moveZeroes(self, nums: List[int]) -> None: + + l=0 + for r in range(len(nums)): + if nums[r]!=0: + nums[l],nums[r]=nums[r],nums[l] + l=l+1 + return nums + +``` + + + +## References + +- **LeetCode Problem**: [Move Zeroes](https://leetcode.com/problems/move-zeroes/description/) + +- **Solution Link**: [Move Zeroes](https://leetcode.com/problems/move-zeroes/post-solution/?submissionId=1193763087) diff --git a/solutions/lc-solutions/0200-0299/0287-find-the-duplicate-number.md b/solutions/lc-solutions/0200-0299/0287-find-the-duplicate-number.md new file mode 100644 index 0000000..e3c8dbe --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0287-find-the-duplicate-number.md @@ -0,0 +1,123 @@ +--- +id: find-the-duplicate-number +title: Find the Duplicate Number +sidebar_label: 0287-Find the Duplicate Number +tags: + - Array + - Two Pointers + - Binary Search + - Bit Manipulation +description: Given an array of N + 1 size, where each element is between 1 and N. Assuming there is only one duplicate number, your task is to find the duplicate number. +--- + +## Problem Description + +Given an array of integers `nums` of `n + 1` size, where each element is in the range `[1, n]` inclusive. Assuming there is only one duplicate number, your task is to find the duplicate number. + +Note You must solve the problem **without modifying** the array `nums` and uses only constant extra space + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [1,3,4,2,2] +Output: 2 +``` + +**Example 2:** + +```plaintext +Input: nums = nums = [3,1,3,4,2] +Output: 3 +``` + +**Example 3:** + +```plaintext +Input: nums = nums = [3,3,3,3,3] +Output: 3 +``` + +### Constraints + +- `1 <= n <= 105` +- `nums.length == n + 1` +- `1 <= nums[i] <= n` +- All the integers in `nums` appear only **once** except for **precisely one integer** which appears **two or more times**. + +## Solution + +The algorithm implemented in the code to find the duplicate number in an array follows the Floyd's Tortoise and Hare (Cycle Detection) method. Here's a concise explanation: + +## Approach + +### 1. Cycle Detection (Finding Intersection Point): + +- Use two pointers, slow and fast. +- Both pointers start at the first element of the array. +- Move the slow pointer by one step (slow = nums[slow]). +- Move the fast pointer by two steps (fast = nums[nums[fast]]). +- Continue this process until the two pointers meet. This meeting point is guaranteed due to the presence of a cycle (the duplicate number causes the cycle). + +### 2. Finding the Entrance to the Cycle (Duplicate Number): + +- Once the intersection point is found, reset the fast pointer to the start of the array. +- Move both pointers one step at a time (slow = nums[slow] and fast = nums[fast]) until they meet again. +- The meeting point is the start of the cycle and is the duplicate number. + +### Why it Works + +- The array can be visualized as a linked list where each element points to the next element indicated by the value at its index. +- The presence of a duplicate means that there is a cycle in this "linked list". +- Floyd's Tortoise and Hare algorithm is used to detect this cycle and find the entry point of the cycle, which corresponds to the duplicate number. + +### Implementation + +### C++ + +```C++ +class Solution { + int findDuplicate(vector < int > & nums) { + int slow = nums[0]; + int fast = nums[0]; + do { + slow = nums[slow]; + fast = nums[nums[fast]]; + } while (slow != fast); + fast = nums[0]; + while (slow != fast) { + slow = nums[slow]; + fast = nums[fast]; + } + return slow; + } +} +``` + +### Java + +```Java +class Solution { + public int findDuplicate(int[] nums) { + int slow = nums[0]; + int fast = nums[0]; + do { + slow = nums[slow]; + fast = nums[nums[fast]]; + } while (slow != fast); + + fast = nums[0]; + while (slow != fast) { + slow = nums[slow]; + fast = nums[fast]; + } + return slow; + } +} +``` + +### Complexity Analysis + +- **Time complexity**: O(N), Since we traversed through the array only once. +- **Space complexity**: O(1), as the operations are performed in-place without using extra space. diff --git a/solutions/lc-solutions/0200-0299/0295-find-median-from-data-stream.md b/solutions/lc-solutions/0200-0299/0295-find-median-from-data-stream.md new file mode 100644 index 0000000..58d3a67 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/0295-find-median-from-data-stream.md @@ -0,0 +1,180 @@ +--- +id: median-finder +title: Median Finder +sidebar_label: Median Finder +tags: +- Heap +- Data Structure +- C++ +- Java +- Python +description: "This document provides a solution to the Median Finder problem, where you need to efficiently find the median of a stream of numbers." +--- + +## Problem +The MedianFinder class is designed to efficiently find the median of a stream of numbers. You can add numbers to the stream using the `addNum` method and retrieve the median using the `findMedian` method. + +## Solution +The approach uses two heaps: +- A max heap to store the smaller half of the numbers +- A min heap to store the larger half of the numbers + +The median can be found in constant time by looking at the tops of the heaps. + +### Step-by-Step Explanation + +1. **Initialize two heaps**: + - `maxHeap` for the lower half of the data (inverted to act like a max heap using negative values). + - `minHeap` for the upper half of the data. + +2. **Add number**: + - If the number is less than or equal to the maximum of `maxHeap`, push it to `maxHeap`. + - Otherwise, push it to `minHeap`. + - Balance the heaps if necessary to ensure `maxHeap` always has equal or one more element than `minHeap`. + +3. **Find median**: + - If the heaps have equal sizes, the median is the average of the roots of both heaps. + - Otherwise, the median is the root of `maxHeap`. + +## Code in Different Languages + + + + + +## C++ +```cpp +#include +#include + +class MedianFinder { + public: + void addNum(int num) { + if (maxHeap.empty() || num <= maxHeap.top()) + maxHeap.push(num); + else + minHeap.push(num); + + // Balance the two heaps so that + // |maxHeap| >= |minHeap| and |maxHeap| - |minHeap| <= 1. + if (maxHeap.size() < minHeap.size()) + maxHeap.push(minHeap.top()), minHeap.pop(); + else if (maxHeap.size() - minHeap.size() > 1) + minHeap.push(maxHeap.top()), maxHeap.pop(); + } + + double findMedian() { + if (maxHeap.size() == minHeap.size()) + return (maxHeap.top() + minHeap.top()) / 2.0; + return maxHeap.top(); + } + + private: + std::priority_queue maxHeap; + std::priority_queue, std::greater> minHeap; +}; + +int main() { + MedianFinder mf; + mf.addNum(1); + mf.addNum(2); + std::cout << mf.findMedian() << std::endl; // Output: 1.5 + mf.addNum(3); + std::cout << mf.findMedian() << std::endl; // Output: 2 +} +``` + + + + +## Java +```java +import java.util.Collections; +import java.util.PriorityQueue; +import java.util.Queue; + +public class MedianFinder { + private Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + private Queue minHeap = new PriorityQueue<>(); + + public void addNum(int num) { + if (maxHeap.isEmpty() || num <= maxHeap.peek()) + maxHeap.offer(num); + else + minHeap.offer(num); + + // Balance the two heaps so that + // |maxHeap| >= |minHeap| and |maxHeap| - |minHeap| <= 1. + if (maxHeap.size() < minHeap.size()) + maxHeap.offer(minHeap.poll()); + else if (maxHeap.size() - minHeap.size() > 1) + minHeap.offer(maxHeap.poll()); + } + + public double findMedian() { + if (maxHeap.size() == minHeap.size()) + return (double) (maxHeap.peek() + minHeap.peek()) / 2.0; + return (double) maxHeap.peek(); + } + + public static void main(String[] args) { + MedianFinder mf = new MedianFinder(); + mf.addNum(1); + mf.addNum(2); + System.out.println(mf.findMedian()); // Output: 1.5 + mf.addNum(3); + System.out.println(mf.findMedian()); // Output: 2 + } +} +``` + + + + + +## Python +```python +import heapq + +class MedianFinder: + def __init__(self): + self.maxHeap = [] + self.minHeap = [] + + def addNum(self, num: int) -> None: + if not self.maxHeap or num <= -self.maxHeap[0]: + heapq.heappush(self.maxHeap, -num) + else: + heapq.heappush(self.minHeap, num) + + # Balance the two heaps so that + # |maxHeap| >= |minHeap| and |maxHeap| - |minHeap| <= 1. + if len(self.maxHeap) < len(self.minHeap): + heapq.heappush(self.maxHeap, -heapq.heappop(self.minHeap)) + elif len(self.maxHeap) - len(self.minHeap) > 1: + heapq.heappush(self.minHeap, -heapq.heappop(self.maxHeap)) + + def findMedian(self) -> float: + if len(self.maxHeap) == len(self.minHeap): + return (-self.maxHeap[0] + self.minHeap[0]) / 2.0 + return -self.maxHeap[0] + +# Example usage +mf = MedianFinder() +mf.addNum(1) +mf.addNum(2) +print(mf.findMedian()) # Output: 1.5 +mf.addNum(3) +print(mf.findMedian()) # Output: 2 +``` + + + +# Complexity Analysis +## Time Complexity: $O(log N)$ for addNum, $O(1)$ for findMedian +### Reason: +Adding a number involves heap insertion which takes $O(log N)$ time. Finding the median involves looking at the top elements of the heaps, which takes $O(1)$ time. + +## Space Complexity: $O(N)$ +### Reason: +We are storing all the numbers in the two heaps. diff --git a/solutions/lc-solutions/0200-0299/_category_.json b/solutions/lc-solutions/0200-0299/_category_.json new file mode 100644 index 0000000..db1c089 --- /dev/null +++ b/solutions/lc-solutions/0200-0299/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "0200-0299", + "position": 4, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (0200 - 0299)" + } +} diff --git a/solutions/lc-solutions/0200-0299/image-1.png b/solutions/lc-solutions/0200-0299/image-1.png new file mode 100644 index 0000000..ccf7ac2 Binary files /dev/null and b/solutions/lc-solutions/0200-0299/image-1.png differ diff --git a/solutions/lc-solutions/0200-0299/image.png b/solutions/lc-solutions/0200-0299/image.png new file mode 100644 index 0000000..a8b0b86 Binary files /dev/null and b/solutions/lc-solutions/0200-0299/image.png differ diff --git a/solutions/lc-solutions/0300-0399/0300-longest-increasing-subsequence.md b/solutions/lc-solutions/0300-0399/0300-longest-increasing-subsequence.md new file mode 100644 index 0000000..4c4a611 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0300-longest-increasing-subsequence.md @@ -0,0 +1,119 @@ +--- +id: longest-increasing-subsequence +title: Longest Increasing Subsequence (LeetCode) +sidebar_label: 0300-LongestIncreasingSubsequence +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/longest-increasing-subsequence/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/longest-increasing-subsequence/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +## Problem Description + +Given an integer array nums, return the length of the longest strictly increasing subsequence. + +### Examples + +#### Example 1: + +- **Input:** nums = [10,9,2,5,3,7,101,18] +- **Output:** 4 +- **Explanation:** The longest increasing subsequence is [2,3,7,101], therefore the length is 4. + +#### Example 2: + +- **Input:** nums = [0,1,0,3,2,3] +- **Output:** 4 + +#### Example 3: + +- **Input:** nums = [7,7,7,7,7,7,7] +- **Output:** 1 + +### Constraints: + +- $1 <= nums.length <= 2500$ +- $-10^4 <= nums[i] <= 10^4$ + +## Approach + +We can solve this problem using dynamic programming or binary search. Here, we will discuss the binary search approach which achieves $O(n log(n))$ time complexity. + +1. Initialize an empty list tails to keep track of the smallest ending element for all increasing subsequences. +2. Iterate through each element num in the input nums. +3. If num is greater than the last element in tails, append num to tails. +4. Otherwise, perform a binary search on tails to find the smallest element greater than or equal to num and update that element with num. +5. After iterating through all elements in nums, return the length of tails. + +## Solution Code + +#### Python + +```py +class Solution: + def lengthOfLIS(self, nums): + tails = [] + for num in nums: + left, right = 0, len(tails) - 1 + while left <= right: + mid = (left + right) // 2 + if tails[mid] < num: + left = mid + 1 + else: + right = mid - 1 + if left < len(tails): + tails[left] = num + else: + tails.append(num) + return len(tails) +``` + +#### C++ + +```cpp +class Solution { +public: + int lengthOfLIS(vector& nums) { + vector tails; + for (int num : nums) { + auto it = lower_bound(tails.begin(), tails.end(), num); + if (it == tails.end()) + tails.push_back(num); + else + *it = num; + } + return tails.size(); + } +}; +``` + +#### Java + +```java +class Solution { + public int lengthOfLIS(int[] nums) { + List tails = new ArrayList<>(); + for (int num : nums) { + int left = 0, right = tails.size() - 1; + while (left <= right) { + int mid = left + (right - left) / 2; + if (tails.get(mid) < num) + left = mid + 1; + else + right = mid - 1; + } + if (left < tails.size()) + tails.set(left, num); + else + tails.add(num); + } + return tails.size(); + } +} +``` + +## Conclusion + +The "Longest Increasing Subsequence" problem can be efficiently solved using the binary search approach, achieving $O(n log(n))$ time complexity. The provided solution code implements this approach in Python, C++, and Java, providing an optimal solution to the problem. diff --git a/solutions/lc-solutions/0300-0399/0301-Remove-Invalid-Parentheses.md b/solutions/lc-solutions/0300-0399/0301-Remove-Invalid-Parentheses.md new file mode 100644 index 0000000..957cd59 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0301-Remove-Invalid-Parentheses.md @@ -0,0 +1,213 @@ +--- +id: remove-invalid-parentheses +title: remove-invalid-parentheses +sidebar_label: 0301 Remove Invalid Parentheses +tags: +- String +- Backtracking +- BFS +- C++ +- Java +- Python +description: "This document provides a solution to the Remove Invalid Parentheses " +--- + +## Problem + +Given a string `s` that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid. + +Return a list of unique strings that are valid with the minimum number of removals. You may return the answer in any order. + + + +### Examples + +**Example 1:** + +``` +Input: s = "()())()" +Output: ["(())()","()()()"] +``` + +**Example 2:** + +``` +Input: s = "(a)())()" +Output: ["(a())()","(a)()()"] + +``` + + + +### Constraints + +- `1 <= s.length <= 25` +- `s consists of lowercase English letters and parentheses '(' and ')'` +- `There will be at most 20 parentheses in s` + +### Approach +The idea is straightforward, with the input string s, we generate all possible states by removing one `(` or `)`, check if they are valid, if found valid ones on the current level, put them to the final result list and we are done, otherwise, add them to a queue and carry on to the next level. + +The good thing of using BFS is that we can guarantee the number of parentheses that need to be removed is minimal, also no recursion call is needed in BFS. + +Thanks to @peisi, we don't need stack to check valid parentheses. + +Time complexity: + +In BFS we handle the states level by level, in the worst case, we need to handle all the levels, we can analyze the time complexity level by level and add them up to get the final complexity. + +On the first level, there's only one string which is the input string s, let's say the length of it is `n`, to check whether it's valid, we need `O(n)` time. On the second level, we remove one `(` or `)` from the first level, so there are `C(n, n-1)` new strings, each of them has `n-1` characters, and for each string, we need to check whether it's valid or not, thus the total time complexity on this level is `(n-1) x C(n, n-1)`. Come to the third level, total time complexity is `(n-2) x C(n, n-2)`, so on and so forth... + +Finally we have this formula: + +`T(n) = n x C(n, n) + (n-1) x C(n, n-1) + ... + 1 x C(n, 1) = n x 2^(n-1)`. +### Solution + +#### Code in Different Languages + + + ```cpp + class Solution { +public: + vector removeInvalidParentheses(string s) { + unordered_set result; + int left_removed = 0; + int right_removed = 0; + for(auto c : s) { + if(c == '(') { + ++left_removed; + } + if(c == ')') { + if(left_removed != 0) { + --left_removed; + } + else { + ++right_removed; + } + } + } + helper(s, 0, left_removed, right_removed, 0, "", result); + return vector(result.begin(), result.end()); + } +private: + void helper(string s, int index, int left_removed, int right_removed, int pair, string path, unordered_set& result) { + if(index == s.size()) { + if(left_removed == 0 && right_removed == 0 && pair == 0) { + result.insert(path); + } + return; + } + if(s[index] != '(' && s[index] != ')') { + helper(s, index + 1, left_removed, right_removed, pair, path + s[index], result); + } + else { + if(s[index] == '(') { + if(left_removed > 0) { + helper(s, index + 1, left_removed - 1, right_removed, pair, path, result); + } + helper(s, index + 1, left_removed, right_removed, pair + 1, path + s[index], result); + } + if(s[index] == ')') { + if(right_removed > 0) { + helper(s, index + 1, left_removed, right_removed - 1, pair, path, result); + } + if(pair > 0) { + helper(s, index + 1, left_removed, right_removed, pair - 1, path + s[index], result); + } + } + } + } +}; + ``` + + + +```java +public class Solution { + public List removeInvalidParentheses(String s) { + List res = new ArrayList<>(); + + // sanity check + if (s == null) return res; + + Set visited = new HashSet<>(); + Queue queue = new LinkedList<>(); + + // initialize + queue.add(s); + visited.add(s); + + boolean found = false; + + while (!queue.isEmpty()) { + s = queue.poll(); + + if (isValid(s)) { + // found an answer, add to the result + res.add(s); + found = true; + } + + if (found) continue; + + // generate all possible states + for (int i = 0; i < s.length(); i++) { + // we only try to remove left or right paren + if (s.charAt(i) != '(' && s.charAt(i) != ')') continue; + + String t = s.substring(0, i) + s.substring(i + 1); + + if (!visited.contains(t)) { + // for each state, if it's not visited, add it to the queue + queue.add(t); + visited.add(t); + } + } + } + + return res; + } + + // helper function checks if string s contains valid parantheses + boolean isValid(String s) { + int count = 0; + + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '(') count++; + if (c == ')' && count-- == 0) return false; + } + + return count == 0; + } +} +``` + + +```python +def removeInvalidParentheses(self, s): + level = {s} + while True: + valid = [] + for s in level: + try: + eval('0,' + filter('()'.count, s).replace(')', '),')) + valid.append(s) + except: + pass + if valid: + return valid + level = {s[:i] + s[i+1:] for s in level for i in range(len(s))} +``` + + + +### Complexity Analysis + +- Time Complexity: $O(N)$ + +- Space Complexity: $O(N)$ + +### References + +- **LeetCode Problem**: Remove Invalid Parentheses \ No newline at end of file diff --git a/solutions/lc-solutions/0300-0399/0302-smallest-rectangle-enclosing-black-pixels.md b/solutions/lc-solutions/0300-0399/0302-smallest-rectangle-enclosing-black-pixels.md new file mode 100644 index 0000000..101a3a4 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0302-smallest-rectangle-enclosing-black-pixels.md @@ -0,0 +1,179 @@ +--- +id: smallest-rectangle-enclosing-black-pixels +title: Smallest Rectangle Enclosing Black Pixels +sidebar_label: 0302-Smallest-Rectangle-Enclosing-Black-Pixels +tags: [Binary Search, Matrix, Array, Hard] +description: Given an image represented by a binary matrix where 0 is a white pixel and 1 is a black pixel, return the area of the smallest rectangle that encloses all black pixels. The black pixels are connected, and the rectangle must be axis-aligned. + +--- + +## Problem Statement + +You are given an `m x n` binary matrix `image` where `0` represents a white pixel and `1` represents a black pixel. The black pixels are connected, i.e., there is only one black region. Pixels are connected horizontally and vertically. + +Given the location `(x, y)` of one of the black pixels, return the area of the smallest (axis-aligned) rectangle that encloses all black pixels. + +**You must write an algorithm with less than O(mn) runtime complexity.** + +### Examples + +**Example 1:** + +```plaintext +Input: image = [["0","0","1","0"],["0","1","1","0"],["0","1","0","0"]], x = 0, y = 2 +Output: 6 +``` + +**Example 2:** + +```plaintext +Input: image = [["1"]], x = 0, y = 0 +Output: 1 +``` +### Constraints +- m == image.length +- n == image[i].length +- 1 <= m, n <= 100 +- image[i][j] is either '0' or '1'. +- 0 <= x < m +- 0 <= y < n +- image[x][y] == '1' +- The black pixels in the image only form one component. +- At most 10^4 calls will be made to `add` and `find`. + + +## Solution + +### Approach + +We use binary search to find the left, right, top, and bottom edges of the rectangle that encloses all the black pixels. + +#### Algorithm + +`Binary Search` to hold remainder. + +- Horizontal Search: Find the top and bottom boundaries of the rectangle by searching for rows that contain black pixels. +- Vertical Search: Find the left and right boundaries of the rectangle by searching for columns that contain black pixels. + +#### Implementation + +## (Java) + +```Java +public class Smallest_Rectangle_Enclosing_Black_Pixels { + + public class Solution_BinarySearch { + public int minArea(char[][] image, int x, int y) { + if (image == null || image.length == 0) { + return 0; + } + + int m = image.length; + int n = image[0].length; + + int up = binarySearch(image, true, 0, x, 0, n, true); + int down = binarySearch(image, true, x + 1, m, 0, n, false); + int left = binarySearch(image, false, 0, y, up, down, true); + int right = binarySearch(image, false, y + 1, n, up, down, false); + + return (right - left) * (down - up); + } + + int binarySearch(char[][] image, boolean isHorizontal, int i, int j, int low, int high, boolean opt) { + while (i < j) { + int k = low; + int mid = (i + j) / 2; + + while (k < high && (isHorizontal ? image[mid][k] : image[k][mid]) == '0') { + ++k; + } + + if (k < high == opt) { + j = mid; + } else { + i = mid + 1; + } + } + + return i; + } + } + + class Solution_BruteForce { + public int minArea(char[][] image, int x, int y) { + int rows = image.length, columns = image[0].length; + int top = x, bottom = x, left = y, right = y; + int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; + image[x][y] = '2'; + Queue queue = new LinkedList<>(); + queue.offer(new int[]{x, y}); + while (!queue.isEmpty()) { + int[] cell = queue.poll(); + int row = cell[0], column = cell[1]; + for (int[] direction : directions) { + int newRow = row + direction[0], newColumn = column + direction[1]; + if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && image[newRow][newColumn] == '1') { + image[newRow][newColumn] = '2'; + top = Math.min(top, newRow); + bottom = Math.max(bottom, newRow); + left = Math.min(left, newColumn); + right = Math.max(right, newColumn); + queue.offer(new int[]{newRow, newColumn}); + } + } + } + return (bottom - top + 1) * (right - left + 1); + } + } +} + +``` + +## (C++) +``` C++ +C++ +class TwoSum { + Map map; + List list; + int low = Integer.MAX_VALUE; + int high = Integer.MIN_VALUE; + /** Initialize your data structure here. */ + public TwoSum() { + map = new HashMap<>(); + list = new LinkedList<>(); + } + + /** Add the number to an internal data structure..*/ + public void add(int number) { + if(map.containsKey(number)){ + map.put(number,true); + }else{ + map.put(number,false); + list.add(number); + low = Math.min(low,number); + high = Math.max(high,number); + } + } + + /** Find if there exists any pair of numbers which sum is equal + * to the value. */ + public boolean find(int value) { + if(value < 2* low || value > 2*high) return false; + for(int num : list){ + int target = value - num; + if(map.containsKey(target)){ + if(num != target) return true; + else if(map.get(target)) return true; + } + } + return false; + } +} + +``` + +### Complexity Analysis + +- **Time Complexity**: $O(\log m \cdot n + \log n \cdot m)$, where $m$ is the number of rows and $n$ is the number of columns. + +- **Space complexity**: $O(1)$, as we are using a constant amount of extra space for variables and no additional data structures. diff --git a/solutions/lc-solutions/0300-0399/0303-range-sum-query-immutable.md b/solutions/lc-solutions/0300-0399/0303-range-sum-query-immutable.md new file mode 100644 index 0000000..2284ebc --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0303-range-sum-query-immutable.md @@ -0,0 +1,121 @@ +--- +id: range-sum-query-immutable +title: Range Sum Query - Immutable (LeetCode) +sidebar_label: 0303-RangeSumQueryImmutable +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/range-sum-query-immutable/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/range-sum-query-immutable/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +## Problem Description + +Given an integer array nums, handle multiple queries of the following type: + +Calculate the sum of the elements of nums between indices left and right inclusive where $left <= right$. + +Implement the NumArray class: + +- `NumArray(int[] nums)`: Initializes the object with the integer array nums. +- `int sumRange(int left, int right)`: Returns the sum of the elements of nums between indices left and right inclusive (i.e., nums[left] + nums[left + 1] + ... + nums[right]). + +### Example + +#### Example 1: + +**Input:** +["NumArray", "sumRange", "sumRange", "sumRange"] +[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] + +**Output:** +[null, 1, -1, -3] + +**Explanation:** + +NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); +numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 +numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 +numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 + + +### Constraints + +- $1 <= \text{nums.length} <= 10^4$ +- $-10^5 <= \text{nums[i]} <= 10^5$ +- $0 <= \text{left} <= \text{right} < \text{nums.length}$ +- At most $10^4$ calls will be made to sumRange. + +## Approach + +To efficiently handle multiple queries of summing elements within a range, we can precompute the cumulative sum array (prefix sum array). The cumulative sum array cumSum stores the sum of elements up to index i from the beginning of the input array. Then, to calculate the sum between any two indices left and right, we simply return cumSum[right] - cumSum[left-1], handling the edge case when left is 0. + +### Implementation Steps: + +1. Initialize an array cumSum of the same length as the input nums. +2. Initialize cumSum[0] as nums[0]. +3. Iterate from index 1 to the end of nums: + - Update cumSum[i] = cumSum[i-1] + nums[i]. +4. To calculate the sum between `left` and right, return cumSum[right] - cumSum[left-1] (if left > 0) or cumSum[right] (if left = 0). + +## Solution Code + +#### Python + +```py +class NumArray: + def __init__(self, nums): + self.prefix_sum = [0] * (len(nums) + 1) + for i in range(len(nums)): + self.prefix_sum[i + 1] = self.prefix_sum[i] + nums[i] + + def sumRange(self, left, right): + return self.prefix_sum[right + 1] - self.prefix_sum[left] +``` + +#### Java + +```java +class NumArray { + int[] cumSum; + + public NumArray(int[] nums) { + cumSum = new int[nums.length]; + cumSum[0] = nums[0]; + for (int i = 1; i < nums.length; i++) { + cumSum[i] = cumSum[i - 1] + nums[i]; + } + } + + public int sumRange(int left, int right) { + return cumSum[right] - (left > 0 ? cumSum[left - 1] : 0); + } +} +``` + +#### C++ + +```cpp +class NumArray { +private: + vector cumSum; + +public: + NumArray(vector& nums) { + cumSum.resize(nums.size()); + cumSum[0] = nums[0]; + for (int i = 1; i < nums.size(); i++) { + cumSum[i] = cumSum[i - 1] + nums[i]; + } + } + + int sumRange(int left, int right) { + return cumSum[right] - (left > 0 ? cumSum[left - 1] : 0); + } +}; +``` + +## Conclusion + +The "Range Sum Query - Immutable" problem can be efficiently solved using a cumulative sum array. By precomputing the cumulative sum of elements up to each index, we can handle multiple queries of summing elements within a range with constant time complexity. The provided solution code implements this approach in Python, Java, and C++, providing an optimal solution to the problem. diff --git a/solutions/lc-solutions/0300-0399/0304-range-sum-query-2d-immutable.md b/solutions/lc-solutions/0300-0399/0304-range-sum-query-2d-immutable.md new file mode 100644 index 0000000..227377a --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0304-range-sum-query-2d-immutable.md @@ -0,0 +1,170 @@ +--- +id: range-sum-query-2d-immutable +title: Range Sum Query 2D - Immutable (LeetCode) +sidebar_label: 0304-RangeSumQuery2DImmutable +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/range-sum-query-2d-immutable/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/range-sum-query-2d-immutable/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +## Problem Description + +Given a 2D matrix matrix, handle multiple queries of the following type: + +Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). + +Implement the NumMatrix class: + +- NumMatrix(int[][] matrix): Initializes the object with the integer matrix matrix. +- int sumRegion(int row1, int col1, int row2, int col2): Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). + +You must design an algorithm where sumRegion works in $O(1)$ time complexity. + +### Example + +#### Example 1: + +**Input:** +["NumMatrix", "sumRegion", "sumRegion", "sumRegion"] +[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1,5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]] + +**Output:** +[null, 8, 11, 12] + +**Explanation:** +NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]); +numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) +numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) +numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) + +### Constraints + +- $m == \text{matrix.length}$ +- $n == \text{matrix[i].length}$ +- $1 <= m, n <= 200$ +- $-10^4 <= \text{matrix[i][j]} <= 10^4$ +- $0 <= \text{row1} <= \text{row2} < m$ +- $0 <= \text{col1} <= \text{col2} < n$ +- At most $10^4$ calls will be made to sumRegion. + +## Approach + +To achieve $O(1)$ time complexity for sumRegion, we can precompute the cumulative sum matrix. The cumulative sum matrix cumSum stores the sum of elements from (0, 0) to (i, j) in the original matrix. + +### Implementation Steps: + +1. Initialize a 2D array cumSum of the same dimensions as the input matrix. +2. Initialize the first row and column of cumSum: + - cumSum[0][0] = matrix[0][0] + - For the first row, cumSum[0][j] = cumSum[0][j-1] + matrix[0][j] + - For the first column, cumSum[i][0] = cumSum[i-1][0] + matrix[i][0] +3. Populate the rest of cumSum using the formula: + - cumSum[i][j] = cumSum[i-1][j] + cumSum[i][j-1] - cumSum[i-1][j-1] + matrix[i][j] +4. To calculate the sum between (row1, col1) and (row2, col2): + - Get the sums from cumSum at (row2, col2), (row1-1, col2), (row2, col1-1), and (row1-1, col1-1). + - Subtract the sum at (row1-1, col2) and (row2, col1-1), and add the sum at (row1-1, col1-1) to get the sum of the required region. + +## Solution Code + +#### Python + +```py +class NumMatrix: + def __init__(self, matrix): + if not matrix or not matrix[0]: + self.dp = None + return + + m, n = len(matrix), len(matrix[0]) + self.dp = [[0] * (n + 1) for _ in range(m + 1)] + + # Calculate cumulative sums + for i in range(1, m + 1): + for j in range(1, n + 1): + self.dp[i][j] = matrix[i - 1][j - 1] + self.dp[i - 1][j] + self.dp[i][j - 1] - self.dp[i - 1][j - 1] + + def sumRegion(self, row1, col1, row2, col2): + if not self.dp: + return 0 + + return self.dp[row2 + 1][col2 + 1] - self.dp[row1][col2 + 1] - self.dp[row2 + 1][col1] + self.dp[row1][col1] +``` + +#### Java + +```java +class NumMatrix { + int[][] cumulativeSum; + + public NumMatrix(int[][] matrix) { + if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { + cumulativeSum = new int[1][1]; + return; + } + int m = matrix.length; + int n = matrix[0].length; + cumulativeSum = new int[m + 1][n + 1]; + + // Calculate cumulative sums + for (int i = 1; i <= m; i++) { + for (int j = 1; j <= n; j++) { + cumulativeSum[i][j] = matrix[i - 1][j - 1] + + cumulativeSum[i - 1][j] + + cumulativeSum[i][j - 1] - + cumulativeSum[i - 1][j - 1]; + } + } + } + public int sumRegion(int row1, int col1, int row2, int col2) { + return cumulativeSum[row2 + 1][col2 + 1] - + cumulativeSum[row1][col2 + 1] - + cumulativeSum[row2 + 1][col1] + + cumulativeSum[row1][col1]; + } +} + +``` + +#### C++ + +```cpp +#include + +class NumMatrix { +private: + std::vector> cumulativeSum; + +public: + NumMatrix(std::vector>& matrix) { + if (matrix.empty() || matrix[0].empty()) { + cumulativeSum = {{0}}; + return; + } + int m = matrix.size(); + int n = matrix[0].size(); + cumulativeSum = std::vector>(m + 1, std::vector(n + 1, 0)); + // Calculate cumulative sums + for (int i = 1; i <= m; i++) { + for (int j = 1; j <= n; j++) { + cumulativeSum[i][j] = matrix[i - 1][j - 1] + + cumulativeSum[i - 1][j] + + cumulativeSum[i][j - 1] - + cumulativeSum[i - 1][j - 1]; + } + } + } + int sumRegion(int row1, int col1, int row2, int col2) { + return cumulativeSum[row2 + 1][col2 + 1] - + cumulativeSum[row1][col2 + 1] - + cumulativeSum[row2 + 1][col1] + + cumulativeSum[row1][col1]; + } +}; +``` + +## Conclusion + +The "Range Sum Query 2D - Immutable" problem can be efficiently solved using a precomputed cumulative sum matrix. By computing the cumulative sum of elements up to each index in the matrix, we can handle multiple queries of summing elements inside a rectangular region in $O(1)$ time complexity. The provided solution code implements this approach in Python, Java, and C++, providing an optimal solution to the problem. \ No newline at end of file diff --git a/solutions/lc-solutions/0300-0399/0305-number-of-islands-ii.md b/solutions/lc-solutions/0300-0399/0305-number-of-islands-ii.md new file mode 100644 index 0000000..d434588 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0305-number-of-islands-ii.md @@ -0,0 +1,341 @@ +--- +id: number-of-islands-ii +title: Number of Islands II +sidebar_label: 0305-Number-of-Islands-II +tags: [Union-Find, Matrix, Hard] +description: Given a 2D grid map of `m` rows and `n` columns initially filled with water, perform `addLand` operations that turn the water at specific positions into land. Return the number of islands after each operation. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. + +--- + +## Problem Statement + +You are given an empty 2D binary grid `grid` of size `m x n`. The grid represents a map where `0`s represent water and `1`s represent land. Initially, all the cells of `grid` are water cells (i.e., all the cells are `0`s). + +We may perform an `addLand` operation which turns the water at position `(ri, ci)` into land. You are given an array `positions` where `positions[i] = [ri, ci]` is the position `(ri, ci)` at which we should operate the `i`-th operation. + +Return an array of integers `answer` where `answer[i]` is the number of islands after turning the cell `(ri, ci)` into a land. + +An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. + +### Examples + +**Example 1:** + +```plaintext +Input: m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]] +Output: [1,1,2,3] +Explanation: +Initially, the 2D grid is filled with water. +- Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. We have 1 island. +- Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. We still have 1 island. +- Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. We have 2 islands. +- Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. We have 3 islands. +``` + +**Example 2:** + +```plaintext +Input: m = 1, n = 1, positions = [[0,0]] +Output: [1] +``` + +### Constraints +- 1 <= m, n, positions.length <= 10^4 +- 1 <= m * n <= 10^4 +- positions[i].length == 2 +- 0 <= ri < m +- 0 <= ci < n + +### Follow up +Could you solve it in time complexity $O(k log(mn))$, where k == positions.length? + +## Solution + +### Approach + +We use Union-Find to keep track of connected components (islands) and perform operations efficiently. + +#### Algorithm +- Union-Find Data Structure: Used to manage and merge different islands. +- Add Land Operation: Convert the water at a given position into land and update the number of islands by checking adjacent cells and merging islands as needed. + +#### Python + +```py +class Solution: + def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]: + def check(i, j): + return 0 <= i < m and 0 <= j < n and grid[i][j] == 1 + + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + p = list(range(m * n)) + grid = [[0] * n for _ in range(m)] + res = [] + cur = 0 # current island count + for i, j in positions: + if grid[i][j] == 1: # already counted, same as previous island count + res.append(cur) + continue + grid[i][j] = 1 + cur += 1 + for x, y in [(-1, 0), (1, 0), (0, -1), (0, 1)]: + if check(i + x, j + y) and find(i * n + j) != find((i + x) * n + j + y): + p[find(i * n + j)] = find((i + x) * n + j + y) + cur -= 1 + # 1 0 1 + # 0 1 0 + # for above, if setting 1st-row 2nd-col 0-to-1 + # cur will -1 for 3 times + # but cur += 1 after grid[i][j] = 1 so cur final result is 1 + res.append(cur) + return res + +############ + +class UnionFind(object): + def __init__(self, m, n): + self.dad = [i for i in range(m * n)] + self.rank = [0 for _ in range(m * n)] + + def find(self, x): + if self.dad[x] != x: + self.dad[x] = self.find(self.dad[x]) + return self.dad[x] + + def union(self, xy): # xy is a tuple (x,y), with x and y value inside + x, y = map(self.find, xy) + if x == y: + return False + if self.rank[x] > self.rank[y]: + self.dad[y] = x + elif self.rank[x] < self.rank[y]: + self.dad[x] = y + else: + self.dad[y] = x # search to the left, to find parent + self.rank[x] += 1 # now x a parent, so +1 its rank + return True + + +class Solution(object): + def numIslands2(self, m, n, positions): + """ + :type m: int + :type n: int + :type positions: List[List[int]] + :rtype: List[int] + """ + uf = UnionFind(m, n) + ans = 0 + ret = [] + dirs = [(0, -1), (0, 1), (1, 0), (-1, 0)] + grid = set() + for i, j in positions: + ans += 1 + grid |= {(i, j)} + for di, dj in dirs: + ni, nj = i + di, j + dj + if 0 <= ni < m and 0 <= nj < n and (ni, nj) in grid: + if uf.union((ni * n + nj, i * n + j)): + ans -= 1 + ret.append(ans) + return ret + + +################ + + +class UnionFind: + def __init__(self, n: int): + self.p = list(range(n)) + self.size = [1] * n + + def find(self, x: int): + if self.p[x] != x: + self.p[x] = self.find(self.p[x]) + return self.p[x] + + def union(self, a: int, b: int) -> bool: + pa, pb = self.find(a - 1), self.find(b - 1) + if pa == pb: + return False + if self.size[pa] > self.size[pb]: + self.p[pb] = pa + self.size[pa] += self.size[pb] + else: + self.p[pa] = pb + self.size[pb] += self.size[pa] + return True + + +class Solution: + def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]: + uf = UnionFind(m * n) + grid = [[0] * n for _ in range(m)] + ans = [] + dirs = (-1, 0, 1, 0, -1) + cnt = 0 + for i, j in positions: + if grid[i][j]: + ans.append(cnt) + continue + grid[i][j] = 1 + cnt += 1 + for a, b in pairwise(dirs): + x, y = i + a, j + b + if ( + 0 <= x < m + and 0 <= y < n + and grid[x][y] + and uf.union(i * n + j, x * n + y) + ): + cnt -= 1 + ans.append(cnt) + return ans + +``` + +#### Java + +```java +class UnionFind { + private final int[] p; + private final int[] size; + + public UnionFind(int n) { + p = new int[n]; + size = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + size[i] = 1; + } + } + + public int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + + public boolean union(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return false; + } + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + return true; + } +} + +class Solution { + public List numIslands2(int m, int n, int[][] positions) { + int[][] grid = new int[m][n]; + UnionFind uf = new UnionFind(m * n); + int[] dirs = {-1, 0, 1, 0, -1}; + int cnt = 0; + List ans = new ArrayList<>(); + for (var p : positions) { + int i = p[0], j = p[1]; + if (grid[i][j] == 1) { + ans.add(cnt); + continue; + } + grid[i][j] = 1; + ++cnt; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 + && uf.union(i * n + j, x * n + y)) { + --cnt; + } + } + ans.add(cnt); + } + return ans; + } +} + +``` + +#### C++ + +```cpp +class UnionFind { +public: + UnionFind(int n) { + p = vector(n); + size = vector(n, 1); + iota(p.begin(), p.end(), 0); + } + + bool unite(int a, int b) { + int pa = find(a), pb = find(b); + if (pa == pb) { + return false; + } + if (size[pa] > size[pb]) { + p[pb] = pa; + size[pa] += size[pb]; + } else { + p[pa] = pb; + size[pb] += size[pa]; + } + return true; + } + + int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } + +private: + vector p, size; +}; + +class Solution { +public: + vector numIslands2(int m, int n, vector>& positions) { + int grid[m][n]; + memset(grid, 0, sizeof(grid)); + UnionFind uf(m * n); + int dirs[5] = {-1, 0, 1, 0, -1}; + int cnt = 0; + vector ans; + for (auto& p : positions) { + int i = p[0], j = p[1]; + if (grid[i][j]) { + ans.push_back(cnt); + continue; + } + grid[i][j] = 1; + ++cnt; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] && uf.union(i * n + j, x * n + y)) { + --cnt; + } + } + ans.push_back(cnt); + } + return ans; + } +}; +``` + +### Complexity Analysis + +- **Time Complexity**: $O(k \cdot \log(m \cdot n))$, where $k$ is the length of the `positions` array, and $m$ and $n$ are the dimensions of the grid. This is due to the Union-Find operations with path compression and union by size. + +- **Space Complexity**: $O(m \cdot n)$, as we need space for the grid and the Union-Find data structure to manage the connectivity of the cells. diff --git a/solutions/lc-solutions/0300-0399/0306-additive-number.md b/solutions/lc-solutions/0300-0399/0306-additive-number.md new file mode 100644 index 0000000..8acbdc7 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0306-additive-number.md @@ -0,0 +1,138 @@ +--- +id: additive-number +title: Additive Number (LeetCode) +sidebar_label: 0306-AdditiveNumber +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Merge Two Sorted Lists](https://leetcode.com/problems/additive-number/) | [Merge Two Sorted Lists Solution on LeetCode](https://leetcode.com/problems/additive-number/solutions/) | [VijayShankerSharma](https://leetcode.com/u/darkknight648/) | + +## Problem Description + +Given a string containing only digits, determine if it forms an additive sequence. An additive sequence is a sequence of numbers where each term (excluding the first two) is the sum of the preceding two. + +### Example + +#### Example 1: + +- **Input:** "112358" +- **Output:** true +- **Explanation:** The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8. + +#### Example 2: + +- **Input:** "199100199" +- **Output:** true +- **Explanation:** The additive sequence is: 1, 99, 100, 199. 1 + 99 = 100, 99 + 100 = 199. + +### Constraints: + +- $1 \leq \text{num.length} \leq 35$ +- $\text{num}$ consists only of digits. + +## Approach + +We can use a backtracking approach to check all possible combinations of additive sequences. Starting with the first two numbers, we can recursively check if the sum of the current two numbers matches the next number in the sequence. If it does, we continue checking the rest of the string. If the entire string is consumed and all sums match, we return true, otherwise false. + +To handle overflow for very large input integers, we can use a data type capable of storing large numbers, such as BigInteger in Java. + +## Solution Code + +#### Python + +```py +class Solution: + def isAdditiveNumber(self, num): + n = len(num) + def backtrack(idx, num1, num2): + if idx == n: + return True + for i in range(idx, n): + if num[idx] == '0' and i > idx: + break + next_num = int(num[idx:i + 1]) + if next_num == num1 + num2: + if backtrack(i + 1, num2, next_num): + return True + + elif next_num > num1 + num2: + break + return False + for i in range(1, n): + for j in range(i): + num1 = int(num[:j + 1]) + num2 = int(num[j + 1:i + 1]) + if backtrack(i + 1, num1, num2): + return True + + return False +``` + +#### Java + +```java +public class Solution { + public boolean isAdditiveNumber(String num) { + int n = num.length(); + return backtrack(num, 0, n, null, null); + } + private boolean backtrack(String num, int idx, int n, Long num1, Long num2) { + if (idx == n) { + return true; + } + for (int i = idx; i < n; i++) { + if (num.charAt(idx) == '0' && i > idx) { + break; + } + long nextNum = Long.parseLong(num.substring(idx, i + 1)); + if (num1 == null || num2 == null || nextNum == num1 + num2) { + if (backtrack(num, i + 1, n, num2, nextNum)) { + return true; + } + } else if (nextNum > num1 + num2) { + break; + } + } + return false; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + bool isAdditiveNumber(std::string num) { + int n = num.size(); + return backtrack(num, 0, n, nullptr, nullptr); + } +private: + bool backtrack(const std::string& num, int idx, int n, long long* num1, long long* num2) { + if (idx == n) { + return true; + } + for (int i = idx; i < n; i++) { + if (num[idx] == '0' && i > idx) { + break; + } + long long nextNum = stoll(num.substr(idx, i - idx + 1)); + if (num1 == nullptr || num2 == nullptr || nextNum == *num1 + *num2) { + if (backtrack(num, i + 1, n, num2, &nextNum)) { + return true; + } + } else if (nextNum > *num1 + *num2) { + break; + } + } + return false; + } +}; +``` + +## Conclusion + +The "Additive Number" problem can be efficiently solved using a backtracking approach, checking all possible combinations of additive sequences. By recursively checking if the sum of the current two numbers matches the next number in the sequence, we can determine if the given string forms an additive sequence. The provided solution code implements this approach in Python, Java, and C++, providing an optimal solution to the problem. diff --git a/solutions/lc-solutions/0300-0399/0307-Range-Sum-Query-Mutable.md b/solutions/lc-solutions/0300-0399/0307-Range-Sum-Query-Mutable.md new file mode 100644 index 0000000..8e13884 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0307-Range-Sum-Query-Mutable.md @@ -0,0 +1,189 @@ +--- +id: range-sum-query-mutable +title: Range Sum Query - Mutable (LeetCode) +sidebar_label: 0307-Range Sum Query - Mutable +tags: + - Array + - Design + - Binary Indexed Tree + - Segment Tree +description: This is the solution of question Range Sum query - Mutable on leetcode +sidebar_position: 0307 +--- + +## Problem Description + +Given an integer array nums, handle multiple queries of the following types: + +1. Update the value of an element in nums. +2.Calculate the sum of the elements of nums between indices left and right inclusive where `left <= right`. +3. Implement the NumArray class: + +`NumArray(int[] nums)` Initializes the object with the integer array nums. +`void update(int index, int val) Updates the value of nums[index] to be val`. +`int sumRange(int left, int right)` Returns the sum of the elements of nums between indices left and right inclusive `(i.e. nums[left] + nums[left + 1] + ... + nums[right])`. + +### Example 1 +``` +Input +["NumArray", "sumRange", "update", "sumRange"] +[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]] +Output +[null, 9, null, 8] + +Explanation +NumArray numArray = new NumArray([1, 3, 5]); +numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9 +numArray.update(1, 2); // nums = [1, 2, 5] +numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8 + +``` + +### Constraints + +- `1 <= nums.length <= 3 * 10^4` +- `-100 <= nums[i] <= 100` +- `0 <= index < nums.length` +- `-100 <= val <= 100` +- `0 <= left <= right < nums.length` +- `At most 3 * 104 calls will be made to update and sumRange` + +## Approach + +- This is a classic Dynamic Range Sum Query problem, to query sum in range efficiently where + elements can be updated dynamically. +- This problem can be solved in various approaches such as: Segment Tree, BIT, Sqrt Decomposition... + In this post, I use Binary Indexed Tree (BIT) structure because it's easy to implement and it has high performance. +- In BIT structure, there are 2 basic operations: + `addValue(idx, value)`: Add an amount of value into element at index idx `(1-based indexing)`, `time: O(logN)` +`getSum(idx): Get sum in range [0..idx] (1-based indexing), time: O(logN)` + +### Solution Code + +#### C++ + +```c++ +class BIT { // One-based indexing + vector bit; +public: + BIT(int size=0) { + bit.assign(size + 1, 0); + } + int getSum(int idx) { // Get sum in range [1..idx] + int sum = 0; + for (; idx > 0; idx -= idx & (-idx)) + sum += bit[idx]; + return sum; + } + void addValue(int idx, int val) { + for (; idx < bit.size(); idx += idx & (-idx)) + bit[idx] += val; + } +}; +class NumArray { + BIT bit; + vector nums; +public: + NumArray(vector& nums) { + this->bit = BIT(nums.size()); + this->nums = nums; + for (int i = 0; i < nums.size(); ++i) + bit.addValue(i+1, nums[i]); + } + void update(int index, int val) { + int diff = val - nums[index]; // get diff amount of `val` compared to current value + bit.addValue(index + 1, diff); // add this `diff` amount at index `index+1` of BIT, plus 1 because in BIT it's 1-based indexing + nums[index] = val; // update latest value of `nums[index]` + } + int sumRange(int left, int right) { + return bit.getSum(right+1) - bit.getSum(left); + } +}; +``` + +#### Java +```java +class BIT { // one-based indexing + int[] bit; + BIT(int size) { + bit = new int[size + 1]; + } + int getSum(int idx) { // Get sum in range [1..idx] + int sum = 0; + for (; idx > 0; idx -= idx & (-idx)) + sum += bit[idx]; + return sum; + } + int getSumRange(int left, int right) { // left, right inclusive + return getSum(right) - getSum(left - 1); + } + void addValue(int idx, int val) { + for (; idx < bit.length; idx += idx & (-idx)) + bit[idx] += val; + } +} +class NumArray { + BIT bit; + int[] nums; + public NumArray(int[] nums) { + this.nums = nums; + bit = new BIT(nums.length); + for (int i = 0; i < nums.length; ++i) + bit.addValue(i+1, nums[i]); + } + public void update(int index, int val) { + int diff = val - nums[index]; // get diff amount of `val` compared to current value + bit.addValue(index + 1, diff); // add this `diff` amount at index `index+1` of BIT, plus 1 because in BIT it's 1-based indexing + nums[index] = val; // update latest value of `nums[index]` + } + public int sumRange(int left, int right) { + return bit.getSum(right+1) - bit.getSum(left); + } +} +``` + +#### Python +```python +class BIT: + def __init__(self, size): + self.bit = [0] * (size + 1) + + def getSum(self, idx): # Get sum in range [1..idx], 1-based indexing + s = 0 + while idx > 0: + s += self.bit[idx] + idx -= idx & (-idx) + return s + + def getSumRange(self, left, right): # left, right inclusive, 1-based indexing + return self.getSum(right) - self.getSum(left - 1) + + def addValue(self, idx, val): # 1-based indexing + while idx < len(self.bit): + self.bit[idx] += val + idx += idx & (-idx) + +class NumArray: + + def __init__(self, nums: List[int]): + self.nums = nums + self.bit = BIT(len(nums)) + for i, v in enumerate(nums): + self.bit.addValue(i+1, v) + + def update(self, index: int, val: int) -> None: + diff = val - self.nums[index] # get diff amount of `val` compared to current value + self.bit.addValue(index+1, diff) # add this `diff` amount at index `index+1` of BIT, plus 1 because in BIT it's 1-based indexing + self.nums[index] = val # update latest value of `nums[index]` + + def sumRange(self, left: int, right: int) -> int: + return self.bit.getSumRange(left+1, right+1) +``` + +#### Conclusion +- Time Complexity + - Constructor: $O(NlogN)$, where N is length of nums array + - update, sumRange: $O(logN)$ + +- Space Complexity +The space complexity is $O(1)$. \ No newline at end of file diff --git a/solutions/lc-solutions/0300-0399/0308-range-sum-query-2d-mutable.md b/solutions/lc-solutions/0300-0399/0308-range-sum-query-2d-mutable.md new file mode 100644 index 0000000..73204e1 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0308-range-sum-query-2d-mutable.md @@ -0,0 +1,333 @@ +--- +id: range-sum-query-2d-mutable +title: Range Sum Query 2D - Mutable +sidebar_label: 0308-Range-Sum-Query-2D-Mutable +tags: [Segment Tree, 2D Matrix, Hard] +description: Given a 2D matrix, handle multiple queries of the following types - updating the value of a cell and calculating the sum of elements inside a rectangle defined by its upper left and lower right corners. + +--- + + +## Problem Statement + +Given a 2D matrix `matrix`, handle multiple queries of the following types: + +1. **Update** the value of a cell in `matrix`. +2. **Calculate** the sum of the elements inside a rectangle defined by its upper left corner `(row1, col1)` and lower right corner `(row2, col2)`. + +Implement the `NumMatrix` class: + +- **NumMatrix(int[][] matrix)**: Initializes the object with the integer matrix `matrix`. +- **void update(int row, int col, int val)**: Updates the value of `matrix[row][col]` to be `val`. +- **int sumRegion(int row1, int col1, int row2, int col2)**: Returns the sum of the elements of `matrix` inside the rectangle defined by its upper left corner `(row1, col1)` and lower right corner `(row2, col2)`. + +### Examples + +**Example 1:** + +```plaintext +Input: +["NumMatrix", "sumRegion", "update", "sumRegion"] +[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [3, 2, 2], [2, 1, 4, 3]] +Output: +[null, 8, null, 10] +``` + +**Example 2:** + +```plaintext +Input: m = 1, n = 1, positions = [[0,0]] +Output: [1] +``` + +### Constraints +- m == matrix.length +- n == matrix[i].length +- 1 <= m, n <= 200 +- -1000 <= matrix[i][j] <= 1000 +- 0 <= row < m +- 0 <= col < n +- -1000 <= val <= 1000 +- 0 <= row1 <= row2 < m +- 0 <= col1 <= col2 < n +- At most 5000 calls will be made to sumRegion and update. + +### Follow up +Implement a solution with Binary Indexed Tree or Segment Tree. + +## Solution + +### Approach + +We use Binary Indexed Tree (BIT) to handle the update and sum queries efficiently. + +#### Algorithm +- Binary Indexed Tree: Maintain a BIT to manage and update the sums of elements efficiently. +- Update Operation: Update the value in the BIT when a cell value changes. +- Query Operation: Calculate the sum for a given rectangle using the BIT. + +#### Python + +```py +# segment tree +class Node: + def __init__(self): + self.l = 0 + self.r = 0 + self.v = 0 + +class SegmentTree: + def __init__(self, nums): + n = len(nums) + self.nums = nums + self.tr = [Node() for _ in range(4 * n)] + self.build(1, 1, n) + + def build(self, u, l, r): + self.tr[u].l = l + self.tr[u].r = r + if l == r: + self.tr[u].v = self.nums[l - 1] + return + mid = (l + r) >> 1 + self.build(u << 1, l, mid) + self.build(u << 1 | 1, mid + 1, r) + self.pushup(u) + + def modify(self, u, x, v): + if self.tr[u].l == x and self.tr[u].r == x: + self.tr[u].v = v + return + mid = (self.tr[u].l + self.tr[u].r) >> 1 + if x <= mid: + self.modify(u << 1, x, v) + else: + self.modify(u << 1 | 1, x, v) + self.pushup(u) + + def query(self, u, l, r): + if self.tr[u].l >= l and self.tr[u].r <= r: + return self.tr[u].v + mid = (self.tr[u].l + self.tr[u].r) >> 1 + v = 0 + if l <= mid: + v += self.query(u << 1, l, r) + if r > mid: + v += self.query(u << 1 | 1, l, r) + return v + + def pushup(self, u): + self.tr[u].v = self.tr[u << 1].v + self.tr[u << 1 | 1].v + +class NumMatrix: + + def __init__(self, matrix: List[List[int]]): + self.trees = [SegmentTree(row) for row in matrix] + + def update(self, row: int, col: int, val: int) -> None: + tree = self.trees[row] + tree.modify(1, col + 1, val) + + def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: + return sum(self.trees[row].query(1, col1 + 1, col2 + 1) for row in range(row1, row2 + 1)) + + +# Your NumMatrix object will be instantiated and called as such: +# obj = NumMatrix(matrix) +# obj.update(row,col,val) +# param_2 = obj.sumRegion(row1,col1,row2,col2) + +############ +''' +It uses a binary indexed tree (BIT) or Fenwick tree to efficiently update and query sums of submatrices. +The NumMatrix class constructor initializes the BIT and matrix data structure. +The update method updates the matrix and BIT with the difference in values. +The sumRegion method computes the sum of a submatrix using prefix sums computed with the BIT. +The sum method computes a prefix sum in the BIT. + + +"Fenwick tree" vs "Segment tree" +https://stackoverflow.com/questions/64190332/fenwick-tree-vs-segment-tree + +''' + +class NumMatrix: + def __init__(self, matrix: List[List[int]]): + if not matrix or not matrix[0]: + self.m, self.n = 0, 0 + return + + self.m, self.n = len(matrix), len(matrix[0]) + self.bit = [[0] * (self.n + 1) for _ in range(self.m + 1)] + self.matrix = [[0] * self.n for _ in range(self.m)] + + for i in range(self.m): + for j in range(self.n): + self.update(i, j, matrix[i][j]) + + def update(self, row: int, col: int, val: int) -> None: + diff = val - self.matrix[row][col] + self.matrix[row][col] = val + i = row + 1 + while i <= self.m: + j = col + 1 + while j <= self.n: + self.bit[i][j] += diff + j += j & -j + i += i & -i + + def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: + return self.sum(row2 + 1, col2 + 1) - self.sum(row2 + 1, col1) - self.sum(row1, col2 + 1) + self.sum(row1, col1) + + def sum(self, row: int, col: int) -> int: + res = 0 + i = row + while i > 0: + j = col + while j > 0: + res += self.bit[i][j] + j -= j & -j + i -= i & -i + return res + +``` + +#### Java + +```java +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + public static int lowbit(int x) { + return x & -x; + } +} + +class NumMatrix { + private BinaryIndexedTree[] trees; + + public NumMatrix(int[][] matrix) { + int m = matrix.length; + int n = matrix[0].length; + trees = new BinaryIndexedTree[m]; + for (int i = 0; i < m; ++i) { + BinaryIndexedTree tree = new BinaryIndexedTree(n); + for (int j = 0; j < n; ++j) { + tree.update(j + 1, matrix[i][j]); + } + trees[i] = tree; + } + } + + public void update(int row, int col, int val) { + BinaryIndexedTree tree = trees[row]; + int prev = tree.query(col + 1) - tree.query(col); + tree.update(col + 1, val - prev); + } + + public int sumRegion(int row1, int col1, int row2, int col2) { + int s = 0; + for (int i = row1; i <= row2; ++i) { + BinaryIndexedTree tree = trees[i]; + s += tree.query(col2 + 1) - tree.query(col1); + } + return s; + } +} + +``` + +#### C++ + +```cpp +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + int lowbit(int x) { + return x & -x; + } +}; + +class NumMatrix { +public: + vector trees; + + NumMatrix(vector>& matrix) { + int m = matrix.size(); + int n = matrix[0].size(); + trees.resize(m); + for (int i = 0; i < m; ++i) { + BinaryIndexedTree* tree = new BinaryIndexedTree(n); + for (int j = 0; j < n; ++j) { + tree->update(j + 1, matrix[i][j]); + } + trees[i] = tree; + } + } + + void update(int row, int col, int val) { + BinaryIndexedTree* tree = trees[row]; + int prev = tree->query(col + 1) - tree->query(col); + tree->update(col + 1, val - prev); + } + + int sumRegion(int row1, int col1, int row2, int col2) { + int s = 0; + for (int i = row1; i <= row2; ++i) { + BinaryIndexedTree* tree = trees[i]; + s += tree->query(col2 + 1) - tree->query(col1); + } + return s; + } +}; + +``` + +### Complexity Analysis + +- **Time Complexity**: $O(\log m \cdot \log n)$ for both update and sumRegion operations, where $m$ and $n$ are the dimensions of the matrix. +- **Space Complexity**: $O(m \cdot n)$ for storing the BITs and matrix. diff --git a/solutions/lc-solutions/0300-0399/0309-best-time-to-buy-and-sell-stocks.md b/solutions/lc-solutions/0300-0399/0309-best-time-to-buy-and-sell-stocks.md new file mode 100644 index 0000000..64c765e --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0309-best-time-to-buy-and-sell-stocks.md @@ -0,0 +1,168 @@ +--- +id: best-time-to-buy-and-sell-stock +title: Best Time to Buy and Sell Stock +sidebar_label: Best Time to Buy and Sell Stock +tags: +- Array +- Dynamic Programming + +description: "This article provides a solution to the Best Time to Buy and Sell Stock problem, which finds the maximum profit that can be obtained by buying and selling a stock at most once." +--- + +## Problem Description + +You are given an array `prices` where `prices[i]` is the price of a given stock on the ith day. + +Find the maximum profit you can achieve by buying and selling a stock at most once. + +### Examples + +**Example 1:** +``` +Input: prices = [7, 1, 5, 3, 6, 4] + +Output: 5 + +Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6 - 1 = 5. +``` +**Example 2:** +``` +Input: prices = [7, 6, 4, 3, 1] + +Output: 0 + +Explanation: In this case, no transaction is done, so the max profit = 0. +``` + +### Constraints + +- $1 <= prices.length <= 10^5$ +- $0 <= prices[i] <= 10^4$ + +## Solution Approach + +To solve this problem, we can use a simple approach involving iterating through the array and keeping track of the minimum price seen so far and the maximum profit that can be achieved. + +### Algorithm + +1. Initialize `min_price` to infinity and `max_profit` to 0. +2. Iterate through each price in the `prices` array: + - Update `min_price` to be the minimum of `min_price` and the current price. + - Update `max_profit` to be the maximum of `max_profit` and the difference between the current price and `min_price`. +3. Return `max_profit`. + + + +#### Code in Different Languages + + + + + ```python + + class Solution(object): + def maxProfit(self, prices): + if not prices: + return 0 + + n = len(prices) + + # Initialize arrays to store states + hold = [0] * n # Maximum profit if holding a stock on day i + sold = [0] * n # Maximum profit if sold a stock on day i + rest = [0] * n # Maximum profit if in cooldown or did nothing on day i + + # Base cases + hold[0] = -prices[0] # Buying the stock on day 0 + sold[0] = 0 # Cannot sell on day 0 + rest[0] = 0 # No activity on day 0 + + # Fill arrays based on relations + for i in range(1, n): + hold[i] = max(hold[i-1], rest[i-1] - prices[i]) + sold[i] = hold[i-1] + prices[i] + rest[i] = max(rest[i-1], sold[i-1]) + return max(sold[n-1], rest[n-1]) + + + + + +```java + public class Solution { + public int maxProfit(int[] prices) { + if (prices.length == 0) return 0; + + int n = prices.length; + + int[] hold = new int[n]; + int[] sold = new int[n]; + int[] rest = new int[n]; + + hold[0] = -prices[0]; + sold[0] = 0; + rest[0] = 0; + + for (int i = 1; i < n; i++) { + hold[i] = Math.max(hold[i-1], rest[i-1] - prices[i]); + sold[i] = hold[i-1] + prices[i]; + rest[i] = Math.max(rest[i-1], sold[i-1]); + } + + return Math.max(sold[n-1], rest[n-1]); + } + } + + +``` + + + + + ``` + + #include + #include + + class Solution { + public: + int maxProfit(std::vector& prices) { + if (prices.empty()) return 0; + + int n = prices.size(); + + std::vector hold(n); + std::vector sold(n); + std::vector rest(n); + + hold[0] = -prices[0]; + sold[0] = 0; + rest[0] = 0; + + for (int i = 1; i < n; i++) { + hold[i] = std::max(hold[i-1], rest[i-1] - prices[i]); + sold[i] = hold[i-1] + prices[i]; + rest[i] = std::max(rest[i-1], sold[i-1]); + } + + return std::max(sold[n-1], rest[n-1]); + } + + // Example usage: + int main() { + Solution solution; + std::vector prices = {1, 2, 3, 0, 2}; + std::cout << solution.maxProfit(prices) << std::endl; // Output: 3 + return 0; + } + }; + ``` + + + + +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) +- **Solution Link:** [best-time-to-buy-and-sell-stock-with-cooldown Solution on LeetCode](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/solutions/) +- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) diff --git a/solutions/lc-solutions/0300-0399/0312-Burst-ballons.md b/solutions/lc-solutions/0300-0399/0312-Burst-ballons.md new file mode 100644 index 0000000..646b41e --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0312-Burst-ballons.md @@ -0,0 +1,337 @@ +--- +id: burst-ballons +title: Burst-Ballons +sidebar_label: 0312 - Burst Ballons +tags: +- Array +- Dynamic Programming + +description: "This is a solution to the Burst Ballons problem on LeetCode." +--- + +## Problem Description + +You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons. + +If you burst the ith balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it. + +Return the maximum coins you can collect by bursting the balloons wisely. + +### Examples + +**Example 1:** + +``` +Input: nums = [3,1,5,8] +Output: 167 +Explanation: +nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] +coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 + +``` + +**Example 2:** + +``` +Input: nums = [1,5] +Output: 10 + +``` + +### Constraints + +- `n == nums.length` +- `1 <= n <= 300` +- `0 <= nums[i] <= 100` + +## Solution for Burst Ballons Problem + + +### Brute Force - Recursion + +#### Intuition +When I first get this problem, it is far from dynamic programming to me. I started with the most naive idea the backtracking. + +We have n balloons to burst, which mean we have n steps in the game. In the i th step we have `n-i` balloons to burst, `i = 0~n-1`. Therefore we are looking at an algorithm of $O(n!)$. Well, it is slow, probably works for `n < 12` only. + +Of course this is not the point to implement it. We need to identify the redundant works we did in it and try to optimize. + +Well, we can find that for any balloons left the maxCoins does not depends on the balloons already bursted. This indicate that we can use memorization (top down) or dynamic programming (bottom up) for all the cases from small numbers of balloon until n balloons. How many cases are there? For k balloons there are `C(n, k)` cases and for each case it need to scan the k balloons to compare. The sum is quite big still. It is better than $O(n!)$ but worse than $O(2^n)$. + + +#### Solution Using Recursion + + + +#### Implementation + +```jsx live +function coinChangeWrapper(arr) { + class Solution { + int solve(vectornums){ + if(nums.size()==0){ + return 0; + } + int maxi=-1e9; + for(int i=0;i=0){ + product=product*nums[i-1]; + } + if(i+1& nums) { + return solve(nums); + } +}; + + + const input = [3,1,5,8] + const sum = 167 + const output = maxCoins(input) + return ( +
+

+ Input: { JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```python + class Solution: + def solve(self, nums): + if len(nums) == 0: + return 0 + + maxi = -1e9 + for i in range(len(nums)): + product = nums[i] + k = nums[i] + if i - 1 >= 0: + product *= nums[i - 1] + if i + 1 < len(nums): + product *= nums[i + 1] + nums.pop(i) + maxi = max(maxi, product + self.solve(nums)) + nums.insert(i, k) + return maxi + + def maxCoins(self, nums): + return self.solve(nums) + +``` + + + + + +``` +import java.util.ArrayList; +import java.util.List; + +class Solution { + private int solve(List nums) { + if (nums.size() == 0) { + return 0; + } + + int maxi = Integer.MIN_VALUE; + for (int i = 0; i < nums.size(); i++) { + int product = nums.get(i); + int k = nums.get(i); + + if (i - 1 >= 0) { + product *= nums.get(i - 1); + } + if (i + 1 < nums.size()) { + product *= nums.get(i + 1); + } + + nums.remove(i); + maxi = Math.max(maxi, product + solve(new ArrayList<>(nums))); + nums.add(i, k); + } + return maxi; + } + + public int maxCoins(int[] nums) { + List numList = new ArrayList<>(); + for (int num : nums) { + numList.add(num); + } + return solve(numList); + } +} + + +``` + + + + + ```cpp + + class Solution { + int solve(vectornums){ + if(nums.size()==0){ + return 0; + } + int maxi=-1e9; + for(int i=0;i=0){ + product=product*nums[i-1]; + } + if(i+1& nums) { + return solve(nums); + } +}; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $ O(2^n) $ is the time complexity, where n is the number of coins , because it has Overlapping subproblems +- Space Complexity: This approach doesn't need any auxilary space, but it maintains a recusion stack internally. +If we consider the recursion tree, there is a repetition of a few sub-trees. + +### Optimized Approach - Memoization +#### Intuition + We then think can we apply the divide and conquer technique? After all there seems to be many self similar sub problems from the previous analysis. + +Well, the nature way to divide the problem is burst one balloon and separate the balloons into `2` sub sections one on the left and one one the right. However, in this problem the left and right become adjacent and have effects on the maxCoins in the future. + +Then another interesting idea come up. Which is quite often seen in dp problem analysis. That is reverse thinking. Like I said the coins you get for a balloon does not depend on the balloons already burst. Therefore +instead of divide the problem by the first balloon to burst, we divide the problem by the last balloon to burst. + +Why is that? Because only the first and last balloons we are sure of their adjacent balloons before hand! + +For the first we have `nums[i-1]*nums[i]*nums[i+1]` for the last we have `nums[-1]*nums[i]*nums[n]`. + +OK. Think about n balloons if i is the last one to burst, what now? + +We can see that the balloons is again separated into 2 sections. But this time since the balloon i is the last balloon of all to burst, the left and right section now has well defined boundary and do not affect each other! Therefore we can do either recursive method with memoization or dp. + + + + + + ```cpp + int solve(vector&nums,int low,int high,vector>&dp){ + if(low>high){ + return 0; + } + if(dp[low][high]!=-1){ + return dp[low][high]; + } + int maxi=INT_MIN; + for(int i=low;i<=high;i++){ + int cost=nums[i]*nums[low-1]*nums[high+1]+solve(nums,low,i-1,dp)+solve(nums,i+1,high,dp); + maxi=max(maxi,cost); + } + return dp[low][high]=maxi; + } +public: + int maxCoins(vector& nums) { + int n=nums.size(); + nums.insert(nums.begin(),1); + nums.push_back(1); + vector>dp(n+2,vector(n+2,0)); + // return solve(nums,1,n,dp); + for(int i=n;i>=1;i--){ + for(int j=1;j<=n;j++){ + if(i>j){ + continue; + } + int maxi=INT_MIN; + for(int ind=i;ind<=j;ind++){ + int cost=nums[ind]*nums[i-1]*nums[j+1]+dp[ind+1][j]+dp[i][ind-1]; + maxi=max(cost,maxi); + } + dp[i][j]=maxi; + } + } + return dp[1][n]; + } +}; + ``` + + + + +#### Complexity Analysis +- Time Complexity: $ O(N^3)$ + - Reason: There are N*A states therefore at max β€˜N*A’ new problems will be solved. A is amount. +- Space Complexity: $O(N*N)$ + - Reason: We are using a recursion stack space(O(N)) and a 2D array ( O(N*A)). + +### Using Tabulation Method +#### Intuition + Here comes the final solutions. Note that we put 2 balloons with 1 as boundaries and also burst all the zero balloons in the first round since they won't give any coins. +The algorithm runs in $O(n^3)$ which can be easily seen from the 3 loops in dp solution. + + + + + ```cpp + int maxCoinsDP(vector &iNums) { + int nums[iNums.size() + 2]; + int n = 1; + for (int x : iNums) if (x > 0) nums[n++] = x; + nums[0] = nums[n++] = 1; + + + int dp[n][n] = {}; + for (int k = 2; k < n; ++k) { + for (int left = 0; left < n - k; ++left) + int right = left + k; + for (int i = left + 1; i < right; ++i) + dp[left][right] = max(dp[left][right], + nums[left] * nums[i] * nums[right] + dp[left][i] + dp[i][right]); + } + + return dp[0][n - 1]; +} + ``` + - Here Time and Space Complexity are same as memoized approach. + + +
+
+ +## References + +- **LeetCode Problem**: [Coin Change](https://leetcode.com/problems/burst-balloons/description/) + diff --git a/solutions/lc-solutions/0300-0399/0313-Super-Ugly-Number.md b/solutions/lc-solutions/0300-0399/0313-Super-Ugly-Number.md new file mode 100644 index 0000000..6b571c5 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0313-Super-Ugly-Number.md @@ -0,0 +1,161 @@ +--- +id: super-ugly-number +title: Super Ugly Number (LeetCode) +sidebar_label: 0313-Super Ugly Number +tags: + - Array + - Math + - Dynammic Programming +description: This is the solution of question Super Ugly Number on leetcode +sidebar_position: 0313 +--- + +## Problem Description + +A super ugly number is a positive integer whose prime factors are in the array primes. + +Given an integer `n` and an array of integers primes, return the `nth` super ugly number. + +The `nth` super ugly number is guaranteed to fit in a 32-bit signed integer. + +### Example 1 + +``` +Input: n = 12, primes = [2,7,13,19] +Output: 32 +Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19]. + +``` + +### Example 2 + +``` +Input: n = 1, primes = [2,3,5] +Output: 1 +Explanation: 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5]. + +``` + +### Constraints + +- `1 <= n <= 10^5` +- `1 <= primes.length <= 100` +- `2 <= primes[i] <= 1000` +- `primes[i] is guaranteed to be a prime number.` +- `All the values of primes are unique and sorted in ascending order.` + + +## Approach +To solve the problem of finding the nth super ugly number given a list of prime numbers, here's the approach I would take: +1. Initialize a list or array to store the super ugly numbers. +2. Since the first super ugly number is always 1, add it to the list. +3. Create a separate list to keep track of the indices for each prime number in the given list. Initialize all indices to 0. +4. Iterate from `1` to `n` (exclusive) to find the remaining super ugly numbers. +For each iteration: +a. Find the minimum value among the products of each prime number with its corresponding super ugly number at the respective index. +b. Add the minimum value to the list of super ugly numbers. +c. Update the indices for the prime numbers that contributed to the minimum value by incrementing them. +d. Repeat steps a-c until all n super ugly numbers are found. +Return the nth super ugly number from the list. +This approach takes advantage of the fact that each super ugly number can be obtained by multiplying a prime number with a previously generated super ugly number. By keeping track of the indices for each prime number, we can efficiently generate the super ugly numbers in ascending order. + +### Solution Code + +#### Python + +```python +class Solution(object): + def nthSuperUglyNumber(self, n, primes): + size = len(primes) + ugly, dp, index, ugly_nums = 1, [1], [0] * size, [1] * size + for i in range(1, n): + # compute possibly ugly numbers and update index + for j in range(0, size): + if ugly_nums[j] == ugly: + ugly_nums[j] = dp[index[j]] * primes[j] + index[j] += 1 + # get the minimum + ugly = min(ugly_nums) + dp.append(ugly) + return dp[-1] + +``` + +#### C++ +```c++ +// Finds the nth super ugly number given a list of prime numbers. + +class Solution { +public: + int nthSuperUglyNumber(int n, vector& primes) { + if (n == 1) + return 1; + + int numPrimes = primes.size(); // Number of prime numbers + vector primeIndices(numPrimes, 0); // Indices to track prime number multiples + + int superUgly[n]; // Array to store super ugly numbers + // memset(superUgly, 0, sizeof(superUgly)); // Initialize the array (commented out since it's unnecessary) + superUgly[0] = 1; // First super ugly number is always 1 + + for (int i = 1; i < n; i++) { + long minVal = INT_MAX; // Minimum value among the prime number multiples + + // Find the minimum value among the prime number multiples + for (int j = 0; j < numPrimes; j++) { + minVal = min(minVal, (long)primes[j] * superUgly[primeIndices[j]]); + } + + superUgly[i] = (int)minVal; // Store the minimum value as the next super ugly number + + // Increment the indices for prime number multiples that contribute to the minimum value + for (int j = 0; j < numPrimes; j++) { + if (minVal == (long)primes[j] * superUgly[primeIndices[j]]) { + primeIndices[j]++; + } + } + + // cout< int: + return int(sqrt(n)) + +``` + +#### Conclusion +- Time Complexity +The total time complexity as O(1). + +- Space Complexity +The space complexity is O(1). diff --git a/solutions/lc-solutions/0300-0399/0322-coin-change.md b/solutions/lc-solutions/0300-0399/0322-coin-change.md new file mode 100644 index 0000000..a2f2f1c --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0322-coin-change.md @@ -0,0 +1,414 @@ +--- +id: coin-change +title: Coin Change +sidebar_label: 0322 - Coin Change +tags: +- Array +- Dynamic Programming + +description: "This is a solution to the Coin Change problem on LeetCode." +--- + +## Problem Description + +You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. +Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. +You may assume that you have an infinite number of each kind of coin. + +### Examples + +**Example 1:** + +``` +Input: coins = [1,2,5], amount = 11 +Output: 3 +Explanation: 11 = 5 + 5 + 1 + +``` + +**Example 2:** + +``` +Input: coins = [2], amount = 3 +Output: -1 + +``` +**Example 3:** +``` +Input: coins = [1], amount = 0 +Output: 0 +``` + +### Constraints + +- `1 <= coins.length <= 12` +- `1 <= coins[i] <= 231 - 1` +- `0 <= amount <= 104` + +## Solution for Coin Change Problem + + +### Brute Force - Recursion + +#### Intuition +Now, take a look at what the coin change problem is all about. + +You are given a sequence of coins of various denominations as part of the coin change problem. For example, consider the following array a collection of coins, with each element representing a different denomination. + +##### Example + `{ 2, 3, 5, 10, 20, 30, 50 }` + +Our goal is to use these coins to accumulate a certain amount of money while using the fewest (or optimal) coins. Furthermore, you can assume that a given denomination has an infinite number of coins. To put it another way, you can use a specific denomination as many times as you want. + +For example, if you want to reach 78 using the above denominations, you will need the four coins listed below. + + `{ 3, 5, 20, 50 }` + + +#### Solution Using Recursion + You have two options for each coin: include it or exclude it. + +coins[] = `{1, 2, 3}` +sum = 4 + +When you include a coin, you add its value to the current sum solution(sol+coins[i], I, and if it is not equal, you move to the next coin, i.e., the next recursive call solution(sol, i++). + +Total solutions are 2. + +The diagram below depicts the recursive calls made during program execution. +![image](https://www.simplilearn.com/ice9/free_resources_article_thumb/Coin%20Change%20Problem%20-%20soni/recursive-solution-of-coin-change-problem.png) + + + + +#### Implementation + +```jsx live +function coinChangeWrapper(arr) { + function solve(coins, index, sum) { + if (sum === 0) return 0; + + if (index < 0 || sum < 0) return Number.MAX_SAFE_INTEGER; + + // Not take the current coin + let notTake = solve(coins, index - 1, sum); + + // Take the current coin + let take = Number.MAX_SAFE_INTEGER; + if (sum >= coins[index]) { + let result = solve(coins, index, sum - coins[index]); + if (result !== Number.MAX_SAFE_INTEGER) { + take = 1 + result; + } + } + + return Math.min(take, notTake); + } + + function coinChange(coins, amount) { + let ans = solve(coins, coins.length - 1, amount); + if (ans === Number.MAX_SAFE_INTEGER) return -1; + return ans; + } + + + const input = [1,2,3] + const sum = 4 + const output = coinChange(input ,sum) + return ( +
+

+ Input: { JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function solve(coins, index, sum) { + if (sum === 0) return 0; + + if (index < 0 || sum < 0) return Number.MAX_SAFE_INTEGER; + + // Not take the current coin + let notTake = solve(coins, index - 1, sum); + + // Take the current coin + let take = Number.MAX_SAFE_INTEGER; + if (sum >= coins[index]) { + let result = solve(coins, index, sum - coins[index]); + if (result !== Number.MAX_SAFE_INTEGER) { + take = 1 + result; + } + } + + return Math.min(take, notTake); + } + + function coinChange(coins, amount) { + let ans = solve(coins, coins.length - 1, amount); + if (ans === Number.MAX_SAFE_INTEGER) return -1; + return ans; + } + + ``` + + + + + ```typescript + function solve(coins: number[], index: number, sum: number): number { + if (sum === 0) return 0; + + if (index < 0 || sum < 0) return Number.MAX_SAFE_INTEGER; + + // Take the current coin + let take = Number.MAX_SAFE_INTEGER; + if (sum >= coins[index]) { + let result = solve(coins, index, sum - coins[index]); + if (result !== Number.MAX_SAFE_INTEGER) { + take = 1 + result; + } + } + + // Not take the current coin + let notTake = solve(coins, index - 1, sum); + + return Math.min(take, notTake); + } + + function coinChange(coins: number[], amount: number): number { + let ans = solve(coins, coins.length - 1, amount); + if (ans === Number.MAX_SAFE_INTEGER) return -1; + return ans; + } + + ``` + + + + + ```python + def coin_change(coins, amount): + def solve(coins, index, sum): + if sum == 0: + return 0 + if index < 0 or sum < 0: + return float('inf') + + # Take the current coin + take = float('inf') + if sum >= coins[index]: + result = solve(coins, index, sum - coins[index]) + if result != float('inf'): + take = 1 + result + + # Not take the current coin + not_take = solve(coins, index - 1, sum) + + return min(take, not_take) + + ans = solve(coins, len(coins) - 1, amount) + return -1 if ans == float('inf') else ans + + ``` + + + + + +``` +public class CoinChange { + public static int solve(int[] coins, int index, int sum) { + if (sum == 0) return 0; + if (index < 0 || sum < 0) return Integer.MAX_VALUE; + + // Take the current coin + int take = Integer.MAX_VALUE; + if (sum >= coins[index]) { + int result = solve(coins, index, sum - coins[index]); + if (result != Integer.MAX_VALUE) { + take = 1 + result; + } + } + + // Not take the current coin + int notTake = solve(coins, index - 1, sum); + + return Math.min(take, notTake); + } + + public static int coinChange(int[] coins, int amount) { + int ans = solve(coins, coins.length - 1, amount); + if (ans == Integer.MAX_VALUE) return -1; + return ans; + } + + public static void main(String[] args) { + int[] coins = {1, 2, 5}; + int amount = 11; + System.out.println(coinChange(coins, amount)); // Output: 3 + } +} + +``` + + + + + ```cpp + int solve(vector& coins, int index, int sum) { + if (sum == 0) return 0; + if (index < 0 || sum < 0) return INT_MAX; + + // Take the current coin + int take = INT_MAX; + if (sum >= coins[index]) { + int result = solve(coins, index, sum - coins[index]); + if (result != INT_MAX) { + take = 1 + result; + } + } + + // Not take the current coin + int notTake = solve(coins, index - 1, sum); + + return min(take, notTake); +} + +int coinChange(vector& coins, int amount) { + int ans = solve(coins, coins.size() - 1, amount); + if (ans == INT_MAX) return -1; + return ans; +} + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $ O(2^n) $ is the time complexity, where n is the number of coins , because it has Overlapping subproblems +- Space Complexity: This approach doesn't need any auxilary space, but it maintains a recusion stack internally. +If we consider the recursion tree, there is a repetition of a few sub-trees. + + +### Optimized Approach - Memoization +#### Intuition + Can we recursive calls which are repeating ? +The dynamic approach to solving the coin change problem is similar to the dynamic method used to solve the 0/1 Knapsack problem. +To store the solution to the subproblem, you must use a 2D array (i.e. table). Then, take a look at the image below. +![image](https://www.simplilearn.com/ice9/free_resources_article_thumb/Coin%20Change%20Problem%20-%20soni/dynamic-programming-solution-using-coin-change-problem.png) + + + + + + ```cpp + int solve(vector& coins, int index, int amount, vector>& dp) { + if (amount == 0) return 0; + if (amount < 0 || index < 0) return INT_MAX; + + if (dp[index][amount] != -1) return dp[index][amount]; + + // Take the current coin + int take = INT_MAX; + if (amount >= coins[index]) { + int result = solve(coins, index, amount - coins[index], dp); + if (result != INT_MAX) { + take = 1 + result; + } + } + + // Not take the current coin + int notTake = solve(coins, index - 1, amount, dp); + + // Memoize the result + dp[index][amount] = min(take, notTake); + + return dp[index][amount]; +} + +int coinChange(vector& coins, int amount) { + int n = coins.size(); + vector> dp(n, vector(amount + 1, -1)); + int ans = solve(coins, n - 1, amount, dp); + return ans == INT_MAX ? -1 : ans; +} + ``` + + + + +#### Complexity Analysis +- Time Complexity: $ O(N*A)$ + - Reason: There are N*A states therefore at max β€˜N*A’ new problems will be solved. A is amount. +- Space Complexity: $ O(N*A) + O(N)$ + - Reason: We are using a recursion stack space(O(N)) and a 2D array ( O(N*A)). + +### Using Tabulation Method +#### Intuition + - In the tabulation approach, we'll create a table (or array) to store solutions for all possible subproblems. + - We'll fill up this table iteratively, starting from the smallest subproblems and gradually moving towards the main problem. + - At each step, we'll use the solutions of already solved subproblems to find solutions for larger subproblems. + - Finally, the solution to the main problem will be found at the last entry of the table. +#### Iterative Process + - We'll iterate through each amount of money starting from 0 up to the target amount. + - For each amount, we'll iterate through each coin denomination and calculate the minimum number of coins required to make that amount using the current coin denomination. + - We'll fill up the table progressively until we reach the target amount. + + + + + ```cpp + int coinChange(vector& coins, int amount) { + int dp[coins.size() + 1][amount + 1]; + for (int i = 0; i < coins.size() + 1; i++) { + for (int j = 0; j < amount + 1; j++) { + + if (i == 0) { + dp[i][j] = INT_MAX - 1; + } + if (j == 0) { + dp[i][j] = 0; + } + } + } + for (int i = 1; i < coins.size() + 1; i++) { + for (int j = 1; j < amount + 1; j++) { + if (coins[i - 1] <= j) { + dp[i][j] = min(dp[i][j - coins[i - 1]] + 1, dp[i - 1][j]); + } else { + dp[i][j] = dp[i - 1][j]; + } + } + } + + if (dp[coins.size()][amount] == INT_MAX - 1) { + return -1; + } + + return dp[coins.size()][amount]; + } + ``` + - Here Time and Space Complexity are same as memoized approach. + + +
+
+ +## References + +- **LeetCode Problem**: [Coin Change](https://leetcode.com/problems/coin-change/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/coin-change/solutions) + diff --git a/solutions/lc-solutions/0300-0399/0324-wiggle-sort-ii.md b/solutions/lc-solutions/0300-0399/0324-wiggle-sort-ii.md new file mode 100644 index 0000000..43e3bd8 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0324-wiggle-sort-ii.md @@ -0,0 +1,237 @@ +--- +id: wiggle-sort-ii +title: Wiggle Sort II +sidebar_label: 0324 - Wiggle Sort II +tags: +- Array +- Divide and Conquer +- Greedy +- Sorting +- Quickselect + +description: "This is a solution to the Wiggle Sort II problem on LeetCode." +--- + +## Problem Description +Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... +You may assume the input array always has a valid answer. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,5,1,1,6,4] +Output: [1,6,1,5,1,4] +Explanation: [1,4,1,5,1,6] is also accepted. + +``` + +**Example 2:** +``` +Input: nums = [1,3,2,2,3,1] +Output: [2,3,1,3,1,2] +``` + +### Constraints + +- `1 <= nums.length <= 5 * 10^4` +- `0 <= nums[i] <= 5000` +- It is guaranteed that there will be an answer for the given input nums. + +## Solution for Wiggle Sort II Problem +### Approach +#### Sorting the Array: +- The first step is to sort the input array nums. This ensures that the elements are in non-decreasing order. +- Sorting helps to easily pick the smallest and largest remaining elements in subsequent steps. +#### Creating a Temporary Array: +- A temporary array temp of the same size as nums is created to store the elements in a "wiggle" pattern. +- An index variable j is initialized to point to the last element of the sorted nums array. This will help in filling the temporary array from the largest to the smallest element. +#### Filling Odd Indices: +- A loop runs from the index 1 to the end of the array with a step of 2 (i.e., 1, 3, 5, ...). This loop fills the odd indices of the temp array. +- The largest remaining elements from nums are placed at these odd indices. The index j is decremented after placing each element. +#### Filling Even Indices: +- Another loop runs from the index 0 to the end of the array with a step of 2 (i.e., 0, 2, 4, ...). This loop fills the even indices of the temp array. +- The largest remaining elements from nums are placed at these even indices. The index j is decremented after placing each element. +- Copying Back to Original Array: +- The temp array, now containing the elements in the desired "wiggle" order, is copied back to the original nums array. + + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function wiggleSort(nums) { + nums.sort((a, b) => a - b); + const temp = new Array(nums.length); + let j = nums.length - 1; + for (let i = 1; i < nums.length; i += 2) { + temp[i] = nums[j--]; + } + for (let i = 0; i < nums.length; i += 2) { + temp[i] = nums[j--]; + } + return temp; + } + const input = [1, 5, 1, 1, 6, 4]; + const output = wiggleSort(input); + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(nlogn) $ is the time complexity, where n is the size of array + - Space Complexity: $ O(n) $ , because of the Temp array we have taken. + + ## Code in Different Languages + + + + ```javascript + function wiggleSort(nums) { + nums.sort((a, b) => a - b); + const temp = new Array(nums.length); + let j = nums.length - 1; + for (let i = 1; i < nums.length; i += 2) { + temp[i] = nums[j--]; + } + for (let i = 0; i < nums.length; i += 2) { + temp[i] = nums[j--]; + } + for (let i = 0; i < nums.length; i++) { + nums[i] = temp[i]; + } + } + ``` + + + + + ```typescript + function wiggleSort(nums: number[]): void { + nums.sort((a, b) => a - b); + const temp: number[] = new Array(nums.length); + let j = nums.length - 1; + + for (let i = 1; i < nums.length; i += 2) { + temp[i] = nums[j--]; + } + for (let i = 0; i < nums.length; i += 2) { + temp[i] = nums[j--]; + } + + for (let i = 0; i < nums.length; i++) { + nums[i] = temp[i]; + } +} + +// Example usage + const input: number[] = [1, 5, 1, 1, 6, 4]; + wiggleSort(input); + console.log(input); // Output might be [1, 6, 1, 5, 1, 4] + ``` + + + + + ```python + def wiggle_sort(nums): + nums.sort() + temp = [0] * len(nums) + j = len(nums) - 1 + + for i in range(1, len(nums), 2): + temp[i] = nums[j] + j -= 1 + for i in range(0, len(nums), 2): + temp[i] = nums[j] + j -= 1 + + for i in range(len(nums)): + nums[i] = temp[i] + +# Example usage +input = [1, 5, 1, 1, 6, 4] +wiggle_sort(input) +print(input) # Output might be [1, 6, 1, 5, 1, 4] + + ``` + + + + + ```java + import java.util.Arrays; + +public class WiggleSort { + public static void wiggleSort(int[] nums) { + Arrays.sort(nums); + int[] temp = new int[nums.length]; + int j = nums.length - 1; + + for (int i = 1; i < nums.length; i += 2) { + temp[i] = nums[j--]; + } + for (int i = 0; i < nums.length; i += 2) { + temp[i] = nums[j--]; + } + + System.arraycopy(temp, 0, nums, 0, nums.length); + } + + public static void main(String[] args) { + int[] input = {1, 5, 1, 1, 6, 4}; + wiggleSort(input); + System.out.println(Arrays.toString(input)); // Output might be [1, 6, 1, 5, 1, 4] + } +} + + ``` + + + + + ```cpp + class Solution { +public: + void wiggleSort(vector& nums) { + sort(nums.begin() , nums.end()); + vectortemp(nums.size()); + int j=nums.size()-1; + for(int i=1;i + + +
+
+ +## References + +- **LeetCode Problem**: [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/wiggle-sort-ii/solution) + diff --git a/solutions/lc-solutions/0300-0399/0326-power-of-three.md b/solutions/lc-solutions/0300-0399/0326-power-of-three.md new file mode 100644 index 0000000..ac14ad3 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0326-power-of-three.md @@ -0,0 +1,121 @@ +--- +id: power-of-three +title: Power of Three (LeetCode) +sidebar_label: 0326-PowerOfThree +--- + +## Problem Description + +| Problem Statement | Solution Link | +| :---------------- | :------------ | +| [Power of Three](https://leetcode.com/problems/power-of-three/) | [Power of Three Solution on LeetCode](https://leetcode.com/problems/power-of-three/solutions/) | + +## Problem Description + +Given an integer `n`, return `true` if it is a power of three. Otherwise, return `false`. + +An integer `n` is a power of three if there exists an integer `x` such that `n == 3^x`. + +### Examples + +#### Example 1: + +- **Input:** n = 27 +- **Output:** true + +#### Example 2: + +- **Input:** n = 0 +- **Output:** false + +#### Example 3: + +- **Input:** n = 9 +- **Output:** true + +#### Example 4: + +- **Input:** n = 45 +- **Output:** false + +### Constraints: + +- $-2^{31} <= n <= 2^{31} - 1$ + +## Approach + +We can solve this problem by iterating and multiplying a variable starting from 3 until it exceeds or equals `n`. If at any point it equals `n`, we return `true`. If we exceed `n` without finding an exact match, we return `false`. + +## Solution Code + +#### C++ + +```cpp +class Solution { +public: + bool isPowerOfThree(int n) { + if(n == 1) { + return true; + } + for(long long i = 3; i <= n; i *= 3) { + if(i == n) { + return true; + } + } + return false; + } +}; +``` + +#### Python + +```python +class Solution: + def isPowerOfThree(self, n: int) -> bool: + if n == 1: + return True + i = 3 + while i <= n: + if i == n: + return True + i *= 3 + return False +``` + +#### Java + +```java +class Solution { + public boolean isPowerOfThree(int n) { + if (n == 1) { + return true; + } + for (long i = 3; i <= n; i *= 3) { + if (i == n) { + return true; + } + } + return false; + } +} +``` + +#### JavaScript + +```javascript +var isPowerOfThree = function(n) { + if (n === 1) { + return true; + } + for (let i = 3; i <= n; i *= 3) { + if (i === n) { + return true; + } + } + return false; +}; +``` + +## Conclusion + +The "Power of Three" problem can be solved by iteratively checking powers of three. The provided solutions in C++, Python, Java, and JavaScript efficiently implement this approach, ensuring correct results within the given constraints. diff --git a/solutions/lc-solutions/0300-0399/0327-Count-of-Range-Sum.md b/solutions/lc-solutions/0300-0399/0327-Count-of-Range-Sum.md new file mode 100644 index 0000000..c7368d0 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0327-Count-of-Range-Sum.md @@ -0,0 +1,176 @@ +--- +id: count-of-range-sum +title: Count of Range Sum (LeetCode) +sidebar_label: 0327-Count of Range Sum +tags: + - Array + - Binary Search + - Divide and Conqueor + - Binary Indexed Tree + - Segment Tree + - Merge Sort + - Ordered Set +description: "This is a solution to the Count of Range Sum problem on LeetCode" +sidebar_position: 0327 +--- + +## Problem Description + +Given an integer array `nums` and two integers `lower` and `upper`, return the number of range sums that lie in `[lower, upper]` inclusive. + +Range `sum S(i, j)` is defined as the sum of the elements in nums between indices i and j inclusive, where `i <= j`. + +### Example 1 + +``` +Input: nums = [-2,5,-1], lower = -2, upper = 2 +Output: 3 +Explanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2. + +``` + +### Example 2 + +``` +Input: nums = [0], lower = 0, upper = 0 +Output: 1 + +``` + + +### Constraints + +- `1 <= nums.length <= 10^5` +- `-2^31 <= nums[i] <= 2^31 - 1` +- `-10^5 <= lower <= upper <= 10^5` + +## Approach + +To start, we already know there is a straightforward solution by computing each range sum and checking whether it lies in [lower, upper] or not. If the number of elements is `n`, we have `n*(n+1)/2` such range sums so the naive solution will end up with $O(n^2)$ time complexity. Now we are asked to do better than that. So what are the targeted time complexities in your mind? When I first looked at the problem, my instinct is that $O(n)$ solution is too ambitious, so I will target at linearithmic-like $(O(n*(logn)^b))$ solutions. To get the logarithmic part, it's natural to think of breaking down the original array, and that's where the divide-and-conquer idea comes from. + +For this problem, we need some array to apply our divide and conquer algorithm. Without much thinking, we can do that directly with the input array (nums) itself. Since our problem also involves range sums and I believe you have the experience of computing range sums from prefix array of the input array, we might as well apply divide and conquer ideas on the prefix array. So I will give both the input-array based and prefix-array based divide&conquer solutions. + +Let's first look at input-array based divide&conquer solution. Our original problem is like this: given an input array nums with length n and a range `[lower, upper]`, find the total number of range sums that lie in the given range. Note the range [lower, upper] and the input array are both fixed. Therefore each range sum can be characterized by two indices i1 and i2 `(i1 <= i2)`, such that range sum `S(i1, i2)` is the summation of input elements with indices going from i1 up to i2 (both inclusive). Then our problem can be redefined in terms of the value ranges of `i1` and `i2`. For example our original problem can be restated as finding the total number of range sums lying in the given range with `0 <= i1 <= i2 <= n - 1`, or in a symbolic way `T(0, n-1)`. + +Now if we break our original input array into two subarrays, `[0, m]` and `[m+1, n-1]` with `m = (n-1)/2`, our original problem can be divided into three parts, depending on the values of i1 and i2. If i1 and i2 are both from the first subarray `[0, m]`, we have a subproblem `T(0, m)`; if i1 and i2 are both from the second subarray, we have a subproblem `T(m+1, n-1)`; if i1 is from the first subarray and i2 from the second (note we assume `i1 <= i2`, therefore we don't have the other case with i2 from first subarray and i1 from second), then we have a new problem which I define as C. In summary we should have: + +`T(0, n-1) = T(0, m) + T(m+1, n-1) + C` + +Now from the master theorem, the time complexity of the new problem C should be better than $O(n^2)$, otherwise we make no improvement by applying this divide&conquer idea. So again, I will aim at linearithmic-like solutions for the new problem C: find the total number of range sums lying in the given range with each range sum starting from the first subarray and ending at the second subarray. + +First let's try to compute all such range sums. The way I did it was first computing the prefix array of the second subarray and the suffix array (or "backward" prefix array if you like) of the first subarray. Then I can naively add each element in the suffix array to all elements in the prefix array to obtain all the possible range sums. Of course you end up with $O(n^2)$ solution, as expected. So how can we approach it with better time complexity? + +Here are the facts I observed: for each element e in the suffix array, we need to add it to all elements in the prefix array. But the order in which we add it doesn't matter. This implies that we can sort our prefix array. This can be done in $O(nlogn)$ time. Now we have a sorted prefix array, do we still need to add the element e to all elements in the prefix array? The answer is no. Because our final goal is to compare the resulted range sums with the given range bounds lower and upper. It is equivalent to modifying the range bounds so we have new bounds `(lower - e)` and `(upper - e)` and leave the prefix array unchanged. Now we can compare these new bounds with the sorted prefix array, and I'm sure you can write your own binary search algorithm to do that. So for each element e in the suffix array, we can compute the modified range bounds and get the number of range sums in this new range in logn time. Therefore the total time will be $O(nlogn)$. So in summary, our new problem C can be solved in $O(nlogn)$ time and according to the master theorem, our original problem can be solved in $O(n(logn)^2)$ time. The following is the complete java program: + +### Solution Code + +#### C++ + +```c++ +class Solution { +public: + int mergeSort(vector& sum, int lower, int upper, int low, int high) + { + if(high-low <= 1) return 0; + int mid = (low+high)/2, m = mid, n = mid, count =0; + count =mergeSort(sum,lower,upper,low,mid) +mergeSort(sum,lower,upper,mid,high); + for(int i =low; i< mid; i++) + { + while(m < high && sum[m] - sum[i] < lower) m++; + while(n < high && sum[n] - sum[i] <= upper) n++; + count += n - m; + } + inplace_merge(sum.begin()+low, sum.begin()+mid, sum.begin()+high); + return count; + } + + int countRangeSum(vector& nums, int lower, int upper) { + int len = nums.size(); + vector sum(len + 1, 0); + for(int i =0; i< len; i++) sum[i+1] = sum[i]+nums[i]; + return mergeSort(sum, lower, upper, 0, len+1); + } +}; +``` + +#### Java +```java +public int countRangeSum(int[] nums, int lower, int upper) { + if (nums == null || nums.length == 0 || lower > upper) return 0; + return countRangeSumSub(nums, 0, nums.length - 1, lower, upper); +} + +private int countRangeSumSub(int[] nums, int l, int r, int lower, int upper) { + if (l == r) return nums[l] >= lower && nums[r] <= upper ? 1 : 0; // base case + + int m = l + (r - l) / 2; + long[] arr = new long[r - m]; // prefix array for the second subarray + long sum = 0; + int count = 0; + + for (int i = m + 1; i <= r; i++) { + sum += nums[i]; + arr[i - (m + 1)] = sum; // compute the prefix array + } + + Arrays.sort(arr); // sort the prefix array + + // Here we can compute the suffix array element by element. + // For each element in the suffix array, we compute the corresponding + // "insertion" indices of the modified bounds in the sorted prefix array + // then the number of valid ranges sums will be given by the indices difference. + // I modified the bounds to be "double" to avoid duplicate elements. + sum = 0; + for (int i = m; i >= l; i--) { + sum += nums[i]; + count += findIndex(arr, upper - sum + 0.5) - findIndex(arr, lower - sum - 0.5); + } + + return countRangeSumSub(nums, l, m, lower, upper) + countRangeSumSub(nums, m + 1, r, lower, upper) + count; +} + +// binary search function +private int findIndex(long[] arr, double val) { + int l = 0, r = arr.length - 1, m = 0; + + while (l <= r) { + m = l + (r - l) / 2; + + if (arr[m] <= val) { + l = m + 1; + } else { + r = m - 1; + } + } + + return l; +} +``` + +#### Python +```python +def countRangeSum(self, nums, lower, upper): + first = [0] + for num in nums: + first.append(first[-1] + num) + def sort(lo, hi): + mid = (lo + hi) / 2 + if mid == lo: + return 0 + count = sort(lo, mid) + sort(mid, hi) + i = j = mid + for left in first[lo:mid]: + while i < hi and first[i] - left < lower: i += 1 + while j < hi and first[j] - left <= upper: j += 1 + count += j - i + first[lo:hi] = sorted(first[lo:hi]) + return count + return sort(0, len(first)) +``` + +#### Conclusion +Time Complexity + - The Total Time Complexity is $O(nlog(n))$ + +Space Complexity + - The Space Complexity is $O(n)$. diff --git a/solutions/lc-solutions/0300-0399/0328-odd-even-linked-list.md b/solutions/lc-solutions/0300-0399/0328-odd-even-linked-list.md new file mode 100644 index 0000000..b145654 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0328-odd-even-linked-list.md @@ -0,0 +1,123 @@ +--- +id: odd-even-linked-list +title: Odd Even Linked List +sidebar_label: 0328 Odd Even Linked List +tags: +- Linked List +- C++ +- Java +- Python +description: "This document provides a solution to group all the nodes with odd indices together followed by the nodes with even indices given the head of a singly linked list." +--- + +## Problem +Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. + +The first node is considered odd, and the second node is even, and so on. + +Note that the relative order inside both the even and odd groups should remain as it was in the input. + +You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. + +### Example 1: +Input: head = [1,2,3,4,5] +Output: [1,3,5,2,4] + +### Example 2: +Input: head = [2,1,3,5,6,4,7] +Output: [2,3,6,7,1,5,4] + +### Constraints: +- The number of nodes in the linked list is in the range `[0, 10^4]`. +- `-10^6 <= Node.val <= 10^6` + +## Solution +To reorder the given linked list based on odd and even indices, we can follow a simple approach. We'll divide the linked list into two separate groups: one for nodes with odd indices and one for nodes with even indices. Then, we'll merge these two groups to obtain the final reordered list while maintaining the relative order of nodes within each group. We'll start by initializing two pointers: one for odd nodes and one for even nodes. Initially, the odd pointer will point to the head of the linked list, and the even pointer will point to the next node. We'll also keep track of the head of the even list to connect it later. Next, we'll iterate through the linked list, advancing the odd pointer by two steps and the even pointer by two steps in each iteration. This will separate the nodes into odd and even group while keeping their original order. + +Finally, we'll merge the even list after the odd list by linking the last node of the odd group to the head of the even group. This will connect the two groups and give us the desired reordered list. + +#### Code in Different Languages + +#### Python + +```py +class Solution: + def oddEvenList(self, head: ListNode) -> ListNode: + oddHead = ListNode(0) + evenHead = ListNode(0) + odd = oddHead + even = evenHead + isOdd = True + + while head: + if isOdd: + odd.next = head + odd = head + else: + even.next = head + even = head + head = head.next + isOdd = not isOdd + + even.next = None + odd.next = evenHead.next + return oddHead.next +``` + +#### Java + +```java +class Solution { + public ListNode oddEvenList(ListNode head) { + ListNode oddHead = new ListNode(0); + ListNode evenHead = new ListNode(0); + ListNode odd = oddHead; + ListNode even = evenHead; + + for (boolean isOdd = true; head != null; head = head.next, isOdd = !isOdd) + if (isOdd) { + odd.next = head; + odd = odd.next; + } else { + even.next = head; + even = even.next; + } + + odd.next = evenHead.next; + even.next = null; + return oddHead.next; + } +} +``` + +#### C++ + +```cpp +class Solution { + public: + ListNode* oddEvenList(ListNode* head) { + ListNode oddHead(0); + ListNode evenHead(0); + ListNode* odd = &oddHead; + ListNode* even = &evenHead; + + for (int isOdd = 0; head; head = head->next) + if (isOdd ^= 1) { + odd->next = head; + odd = odd->next; + } else { + even->next = head; + even = even->next; + } + + odd->next = evenHead.next; + even->next = nullptr; + return oddHead.next; + } +}; +``` + +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/odd-even-linked-list/) +- **Solution Link:** [Shortest Palindrome Solution on LeetCode](https://leetcode.com/problems/odd-even-linked-list/solutions/) diff --git a/solutions/lc-solutions/0300-0399/0329-longest-increasing-path-in-a-matrix.md b/solutions/lc-solutions/0300-0399/0329-longest-increasing-path-in-a-matrix.md new file mode 100644 index 0000000..e6320f3 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0329-longest-increasing-path-in-a-matrix.md @@ -0,0 +1,471 @@ +--- +id: longest-increasing-path-in-a-matrix +title: Longest Increasing Path in a Matrix +sidebar_label: 0329 - Longest Increasing Path in a Matrix +tags: +- Array +- Dynamic Programming +- Depth-First Search +- Breadth-First Search +- Graph +- Topological Sort +- Memoization +- Matrix +description: "This is a solution to the Longest Increasing Path in a Matrix problem on LeetCode." +--- + +## Problem Description + +Given an m x n integers matrix, return the length of the longest increasing path in matrix. +From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed). + +### Examples + +**Example 1:** + +``` +Input: matrix = [[9,9,4],[6,6,8],[2,1,1]] +Output: 4 +Explanation: The longest increasing path is [1, 2, 6, 9]. + +``` + +**Example 2:** + +```Input: matrix = [[3,4,5],[3,2,6],[2,2,1]] +Output: 4 +Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed. + +``` +**Example 3:** +``` +Input: matrix = [[1]] +Output: 1 +``` + +### Constraints + +- `m == matrix.length` +- `n == matrix[i].length` +- `1 <= m, n <= 200 ` +- `0 <= matrix[i][j] <= 2^31 - 1` + +## Solution for Longest Increasing Path in a Matrix Problem + + +### Approach 1: Brute Force + +#### Intuition +The brute force approach for solving the longest increasing path in a matrix involves exploring every possible path starting from each cell in the matrix without using any form of memoization or dynamic programming to cache intermediate results. This means the algorithm will re-compute the length of paths multiple times for overlapping subproblems, leading to increased time complexity. + + + +#### Implementation + +```jsx live +function longestIncreasingPathWrapper(arr) { + function isValid(row, col, i, j) { + return i < row && i >= 0 && j < col && j >= 0; + } + + function solve(arr, i, j, dp, delRow, delCol) { + if (dp[i][j] !== -1) { + return dp[i][j]; + } + let ans = 1; + for (let k = 0; k < 4; k++) { + const newRow = delRow[k] + i; + const newCol = delCol[k] + j; + + if (isValid(arr.length, arr[0].length, newRow, newCol) && arr[newRow][newCol] > arr[i][j]) { + ans = Math.max(ans, 1 + solve(arr, newRow, newCol, dp, delRow, delCol)); + } + } + + dp[i][j] = ans; + return ans; + } + + function calculateLongestIncreasingPath(arr) { + const rows = arr.length; + const cols = arr[0].length; + const dp = Array.from({ length: rows }, () => Array(cols).fill(-1)); + const delRow = [0, 1, 0, -1]; + const delCol = [1, 0, -1, 0]; + + let ans = 0; + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + ans = Math.max(ans, solve(arr, i, j, dp, delRow, delCol)); + } + } + + return ans; + } + + const input = [[9,9,4],[6,6,8],[2,1,1]] + const output = calculateLongestIncreasingPath(input) + return ( +
+

+ Input: { JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript +const delRow = [0, 1, 0, -1]; +const delCol = [1, 0, -1, 0]; + +const isValid = (row, col, i, j) => { + return i < row && i >= 0 && j < col && j >= 0; +}; + +const solve = (arr, i, j, prev) => { + let ans = 1; // Initial path length is 1 (the cell itself) + for (let k = 0; k < 4; k++) { + const newRow = delRow[k] + i; + const newCol = delCol[k] + j; + + // Check if the new cell is within bounds and its value is greater than the current cell value + if (isValid(arr.length, arr[0].length, newRow, newCol) && arr[newRow][newCol] > prev) { + // Recursively compute the path length from the new cell + ans = Math.max(ans, 1 + solve(arr, newRow, newCol, arr[newRow][newCol])); + } + } + return ans; +}; + +const longestIncreasingPath = (arr) => { + let ans = 0; + // Iterate over all cells in the matrix + for (let i = 0; i < arr.length; i++) { + for (let j = 0; j < arr[0].length; j++) { + // Compute the longest increasing path starting from cell (i, j) + ans = Math.max(ans, solve(arr, i, j, arr[i][j] - 1)); + } + } + return ans; +}; + ``` + + + + + ```typescript +const delRow: number[] = [0, 1, 0, -1]; +const delCol: number[] = [1, 0, -1, 0]; + +const isValid = (row: number, col: number, i: number, j: number): boolean => { + return i < row && i >= 0 && j < col && j >= 0; +}; + +const solve = (arr: number[][], i: number, j: number, prev: number): number => { + let ans: number = 1; // Initial path length is 1 (the cell itself) + for (let k = 0; k < 4; k++) { + const newRow: number = delRow[k] + i; + const newCol: number = delCol[k] + j; + + // Check if the new cell is within bounds and its value is greater than the current cell value + if (isValid(arr.length, arr[0].length, newRow, newCol) && arr[newRow][newCol] > prev) { + // Recursively compute the path length from the new cell + ans = Math.max(ans, 1 + solve(arr, newRow, newCol, arr[newRow][newCol])); + } + } + return ans; +}; + +const longestIncreasingPath = (arr: number[][]): number => { + let ans: number = 0; + // Iterate over all cells in the matrix + for (let i = 0; i < arr.length; i++) { + for (let j = 0; j < arr[0].length; j++) { + // Compute the longest increasing path starting from cell (i, j) + ans = Math.max(ans, solve(arr, i, j, arr[i][j] - 1)); + } + } + return ans; +}; + + ``` + + + + + ```python + def is_valid(row, col, i, j): + return i < row and i >= 0 and j < col and j >= 0 + +def solve(arr, i, j, prev): + del_row = [0, 1, 0, -1] + del_col = [1, 0, -1, 0] + ans = 1 # Initial path length is 1 (the cell itself) + for k in range(4): + new_row = del_row[k] + i + new_col = del_col[k] + j + + # Check if the new cell is within bounds and its value is greater than the current cell value + if is_valid(len(arr), len(arr[0]), new_row, new_col) and arr[new_row][new_col] > prev: + # Recursively compute the path length from the new cell + ans = max(ans, 1 + solve(arr, new_row, new_col, arr[new_row][new_col])) + return ans + +def longest_increasing_path(arr): + ans = 0 + # Iterate over all cells in the matrix + for i in range(len(arr)): + for j in range(len(arr[0])): + # Compute the longest increasing path starting from cell (i, j) + ans = max(ans, solve(arr, i, j, arr[i][j] - 1)) + return ans + + + ``` + + + + + ```java + import java.util.Arrays; + +class Solution { + private static final int[] delRow = {0, 1, 0, -1}; + private static final int[] delCol = {1, 0, -1, 0}; + + private boolean isValid(int row, int col, int i, int j) { + return i < row && i >= 0 && j < col && j >= 0; + } + + private int solve(int[][] arr, int i, int j, int prev) { + int ans = 1; // Initial path length is 1 (the cell itself) + for (int k = 0; k < 4; k++) { + int newRow = delRow[k] + i; + int newCol = delCol[k] + j; + + // Check if the new cell is within bounds and its value is greater than the current cell value + if (isValid(arr.length, arr[0].length, newRow, newCol) && arr[newRow][newCol] > prev) { + // Recursively compute the path length from the new cell + ans = Math.max(ans, 1 + solve(arr, newRow, newCol, arr[newRow][newCol])); + } + } + return ans; + } + + public int longestIncreasingPath(int[][] arr) { + int ans = 0; + // Iterate over all cells in the matrix + for (int i = 0; i < arr.length; i++) { + for (int j = 0; j < arr[0].length; j++) { + // Compute the longest increasing path starting from cell (i, j) + ans = Math.max(ans, solve(arr, i, j, arr[i][j] - 1)); + } + } + return ans; + } +} + ``` + + + + + ```cpp + class Solution { +public: + int delRow[4] = {0, 1, 0, -1}; + int delCol[4] = {1, 0, -1, 0}; + + bool isValid(int row, int col, int i, int j) { + return i < row && i >= 0 && j < col && j >= 0; + } + + int solve(vector>& arr, int i, int j, int prev) { + int ans = 1; // Initial path length is 1 (the cell itself) + for (int k = 0; k < 4; k++) { + int newRow = delRow[k] + i; + int newCol = delCol[k] + j; + + // Check if the new cell is within bounds and its value is greater than the current cell value + if (isValid(arr.size(), arr[0].size(), newRow, newCol) && + arr[newRow][newCol] > prev) { + // Recursively compute the path length from the new cell + ans = max(ans, 1 + solve(arr, newRow, newCol, arr[newRow][newCol])); + } + } + return ans; + } + + int longestIncreasingPath(vector>& arr) { + int ans = 0; + // Iterate over all cells in the matrix + for (int i = 0; i < arr.size(); i++) { + for (int j = 0; j < arr[0].size(); j++) { + // Compute the longest increasing path starting from cell (i, j) + ans = max(ans, solve(arr, i, j, arr[i][j] - 1)); + } + } + return ans; + } +}; + + ``` + + + + +#### Complexity Analysis + +- Time Complexity: the time complexity is ( M x N ) ^ 2 for brute force because from each M X N points we traverse M X N cells +- Space Complexity: O(1) + + +### Optimized Approach - Memoization +#### Intuition + - Instead of recursively exploring all possible paths from each cell in the matrix, we can store and reuse intermediate results using dynamic programming. + + - By caching the lengths of the longest increasing paths starting from each cell, we can avoid redundant computations and dramatically reduce the time complexity. + + + + + ```cpp + class Solution { +public: + int delRow[4] = {0, 1, 0, -1}; + int delCol[4] = {1, 0, -1, 0}; + + bool isValid(int row, int col, int i, int j) { + return i < row && i >= 0 && j < col && j >= 0; + } + + int solve(vector>& arr, int i, int j, vector>& dp) { + if (dp[i][j] != -1) { + return dp[i][j]; + } + int ans = 1; + for (int k = 0; k < 4; k++) { + int newRow = delRow[k] + i; + int newCol = delCol[k] + j; + + if (isValid(arr.size(), arr[0].size(), newRow, newCol) && arr[newRow][newCol] > arr[i][j]) { + ans = max(ans, 1 + solve(arr, newRow, newCol, dp)); + } + } + + dp[i][j] = ans; + return ans; + } + + int longestIncreasingPath(vector>& arr) { + int rows = arr.size(); + int cols = arr[0].size(); + vector> dp(rows, vector(cols, -1)); + + int ans = 0; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + ans = max(ans, solve(arr, i, j, dp)); + } + } + + return ans; + } +}; + ``` + + + + +#### Complexity Analysis +- Time Complexity: the time complexity is ( M x N ) for dp solution because from each M X N points because we are storing the the solution for particular cell in the dp array. +- Space Complexity: O(M x N) + +### Using Topological Sort +#### Intuition + - We regard a cell in the matrix as a node,a directed edge from node x to node y if x and y are adjacent and x's value < y's value + Then a graph is formed. + No cycles can exist in the graph, i.e. a DAG is formed. + The problem becomes to get the longest path in the DAG. + Topological sort can iterate the vertices of a DAG in the linear ordering. + Using Kahn's algorithm(BFS) to implement topological sort while counting the levels can give us the longest chain of nodes in the DAG. + + + + + + ```cpp + class Solution { + vector> directions = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; + int rows, cols, longest = 0; +public: + int longestIncreasingPath(vector>& matrix) { + rows = matrix.size(); + // Empty + if(!rows) return 0; + cols = matrix[0].size(); + // Matrix corresponding to Indegree count + vector> Indegree(rows, vector(cols)); + // Source nodes of increasing paths + queue> q; + + for(int i = 0; i < rows; i++){ + for(int j = 0; j < cols; j++){ + for(auto &d: directions){ + int x = i + d[0]; + int y = j + d[1]; + // OUT OF BOUNDS CHECK + if(x >= 0 && x < rows && y >= 0 && y < cols){ + // Increasing Path (end) + if(matrix[x][y] < matrix[i][j]) Indegree[i][j]++; + } + } + // Increasing Path (start) + if(!Indegree[i][j]) q.push({i, j}); + } + } + // BFS + while(!q.empty()){ + int size = q.size(); + while(size--){ + pair current = q.front(); // Current matrix cell + q.pop(); + // Explore neigbhors + for(auto &d: directions){ + int x = current.first + d[0]; + int y = current.second + d[1]; + // OUT OF BOUNDS CHECK + if(x >= 0 && x < rows && y >= 0 && y < cols){ + // "Erase" current cell and move onto next level + if(matrix[x][y] > matrix[current.first][current.second] && --Indegree[x][y] == 0) + q.push({x,y}); + } + } + } + longest++; + } + return longest; + } +}; + ``` + + + + +
+
+ +## References + +- **LeetCode Problem**: [Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/solution) + diff --git a/solutions/lc-solutions/0300-0399/0330-patching-array.md b/solutions/lc-solutions/0300-0399/0330-patching-array.md new file mode 100644 index 0000000..567ff55 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0330-patching-array.md @@ -0,0 +1,125 @@ +--- +id: patching-array +title: Patching Array +level: hard +sidebar_label: Patching Array +tags: + - Greedy + - Array + - Binary Search + - Java +description: "This document provides solutions for the Patching Array problem." +--- + +## Problem Statement + +Given a sorted integer array `nums` and an integer `n`, add/patch elements to the array such that any number in the range `[1, n]` inclusive can be formed by the sum of some elements in the array. + +Return the minimum number of patches required. + +**Example:** + +Example 1: + +Input: `nums = [1,3]`, `n = 6` + +Output: `1` + +Explanation: + +Combinations of nums are `[1]`, `[3]`, `[1,3]`, which form possible sums of: `1, 3, 4`. +Now if we add/patch `2` to nums, the combinations are: `[1]`, `[2]`, `[3]`, `[1,3]`, `[2,3]`, `[1,2,3]`. +Possible sums are `1, 2, 3, 4, 5, 6`, which now covers the range `[1, 6]`. +So we only need `1` patch. + +Example 2: + +Input: `nums = [1,5,10]`, `n = 20` + +Output: `2` + +Explanation: + +The two patches can be `[2, 4]`. + +Example 3: + +Input: `nums = [1,2,2]`, `n = 5` + +Output: `0` + +Explanation: + +In this case, the array `nums` already covers all sums up to `5`, so no patches are needed. + +**Constraints:** + +- `1 <= nums.length <= 1000` +- `1 <= nums[i] <= 10^4` +- `nums` is sorted in ascending order. +- `1 <= n <= 2 * 10^9 - 1` + +## Solutions + +### Approach + +The problem can be efficiently solved using a greedy approach: + +1. **Initialization:** + - Initialize `miss` to `1`, which represents the smallest number that cannot be formed with the current elements in `nums`. + - Initialize `result` to `0` to count the number of patches needed. + - Initialize `i` to `0` to iterate through `nums`. + +2. **Iterate Until Covering `n`:** + - While `miss` is less than or equal to `n`, check if the current number `miss` can be formed by adding elements from `nums`. + - If `nums[i]` is less than or equal to `miss`, add `nums[i]` to `miss` and move to the next element (`i++`). + - If `nums[i]` is greater than `miss` or `i` exceeds the length of `nums`, it means `miss` cannot be formed with the current elements. Therefore, add `miss` itself to `nums` to extend the range of possible sums and increment `result`. + +3. **Return Result:** + - Once the loop ends and `miss` is greater than `n`, return `result`, which is the minimum number of patches required to cover all sums up to `n`. + +### Java + +```java +class Solution { + public int minPatches(int[] nums, int n) { + long miss = 1; + int result = 0; + int i = 0; + + while (miss <= n) { + if (i < nums.length && nums[i] <= miss) { + miss += nums[i]; + i++; + } else { + miss += miss; + result++; + } + } + + return result; + } +``` +### Python + +```Python +from typing import List + +class Solution: + def minPatches(self, nums: List[int], n: int) -> int: + miss = 1 + result = 0 + i = 0 + + while miss <= n: + if i < len(nums) and nums[i] <= miss: + miss += nums[i] + i += 1 + else: + miss += miss + result += 1 + + return result +``` + + diff --git a/solutions/lc-solutions/0300-0399/0334-increasing-triplet-subsequence.md b/solutions/lc-solutions/0300-0399/0334-increasing-triplet-subsequence.md new file mode 100644 index 0000000..8707fbe --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0334-increasing-triplet-subsequence.md @@ -0,0 +1,143 @@ +--- +id: increasing-triplet-subsequence +title: Increasing Triplet Subsequence +sidebar_label: 334-Increasing Triplet Subsequence +tags: + - Arrays + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Increasing Triplet Subsequence problem on LeetCode." +sidebar_position: 4 +--- + +## Problem Description + +Given an integer array `nums`, return `true` if there exists a triple of indices (i, j, k) such that `i < j < k` and `nums[i] < nums[j] < nums[k]`. If no such indices exist, return `false`. + +### Examples + +**Example 1:** + +``` +Input: nums = [1, 2, 3, 4, 5] +Output: true +Explanation: Any triplet where i < j < k is valid. +``` + +**Example 2:** + +``` +Input: nums = [5, 4, 3, 2, 1] +Output: false +Explanation: No triplet exists. +``` + +**Example 3:** + +``` +Input: nums = [2, 1, 5, 0, 4, 6] +Output: true +Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6. +``` + +### Constraints + +- `1 <= nums.length <= 5 * 10^5` +- `-2^31 <= nums[i] <= 2^31 - 1` + +### Follow-up + +Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity? + +--- + +## Solution for Increasing Triplet Subsequence Problem + +### Approach + +To solve this problem, we can maintain two variables first and second to represent the smallest and second smallest numbers encountered so far. The algorithm iterates through the array and updates these two variables. If we find a number that is larger than second, we have found an increasing triplet. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + bool increasingTriplet(vector& nums) { + int first = INT_MAX, second = INT_MAX; + for (int num : nums) { + if (num <= first) { + first = num; + } else if (num <= second) { + second = num; + } else { + return true; + } + } + return false; + } +}; +``` + + + + + +```java +class Solution { + public boolean increasingTriplet(int[] nums) { + int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE; + for (int num : nums) { + if (num <= first) { + first = num; + } else if (num <= second) { + second = num; + } else { + return true; + } + } + return false; + } +} +``` + + + + + +```python +class Solution: + def increasingTriplet(self, nums: List[int]) -> bool: + first = second = float('inf') + for num in nums: + if num <= first: + first = num + elif num <= second: + second = num + else: + return True + return False +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(n)$, where $n$ is the length of the array. We iterate through the array once. +- **Space Complexity**: $O(1)$. We use a constant amount of extra space for the variables `first` and `second`. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0300-0399/0336-Palindrome-Pairs.md b/solutions/lc-solutions/0300-0399/0336-Palindrome-Pairs.md new file mode 100644 index 0000000..f3e1c84 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0336-Palindrome-Pairs.md @@ -0,0 +1,221 @@ +--- +id: palindrome-pairs +title: Palindrome Pairs Solution +sidebar_label: 0102 Palindrome Pairs +tags: + - String + - Trie + - Hash Table + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Palindrome Pairs problem on LeetCode." +--- + +## Problem Description + +Given a list of unique words, find all pairs of distinct indices (i, j) in the list such that the concatenation of `words[i] + words[j]` forms a palindrome. + +### Examples + +**Example 1:** + +``` +Input: words = ["abcd","dcba","lls","s","sssll"] +Output: [[0,1],[1,0],[3,2],[2,4]] +Explanation: The palindromes are ["abcddcba","dcbaabcd","slls","llssssll"] +``` + +**Example 2:** + +``` +Input: words = ["bat","tab","cat"] +Output: [[0,1],[1,0]] +Explanation: The palindromes are ["battab","tabbat"] +``` + +### Constraints + +- $1 <= words.length <= 5000$ +- $0 <= words[i].length <= 300$ +- words[i] consists of lowercase English letters. + +--- + +## Solution for Palindrome Pairs Problem + +### Intuition And Approach + +To efficiently find all palindrome pairs in the list of words, we can leverage a HashMap (or Trie for optimization) to store the reverse of each word along with its index. Then, for each word, we check its substrings to find potential pairs that form palindromes. + +#### Code in Different Languages + + + + + ```java + + import java.util.*; + + class Solution { + public List> palindromePairs(String[] words) { + Map wordMap = new HashMap<>(); + List> result = new ArrayList<>(); + + // Build the word map + for (int i = 0; i < words.length; i++) { + wordMap.put(words[i], i); + } + + // Iterate through each word + for (int i = 0; i < words.length; i++) { + String word = words[i]; + int n = word.length(); + + // Check each possible split of the word into left and right parts + for (int j = 0; j <= n; j++) { + String left = word.substring(0, j); + String right = word.substring(j); + String revLeft = new StringBuilder(left).reverse().toString(); + String revRight = new StringBuilder(right).reverse().toString(); + + // Check if left + right forms a palindrome + if (isPalindrome(left) && wordMap.containsKey(revRight) && wordMap.get(revRight) != i) { + result.add(Arrays.asList(wordMap.get(revRight), i)); + } + + // Check if right + left forms a palindrome (to avoid duplicates) + if (j < n && isPalindrome(right) && wordMap.containsKey(revLeft) && wordMap.get(revLeft) != i) { + result.add(Arrays.asList(i, wordMap.get(revLeft))); + } + } + } + + return result; + } + + private boolean isPalindrome(String s) { + int left = 0, right = s.length() - 1; + while (left < right) { + if (s.charAt(left) != s.charAt(right)) { + return false; + } + left++; + right--; + } + return true; + } + } + + ``` + + + + + ```python + + from collections import defaultdict + + class Solution: + def palindromePairs(self, words): + def is_palindrome(word): + return word == word[::-1] + + word_map = {word: i for i, word in enumerate(words)} + result = [] + + for i, word in enumerate(words): + n = len(word) + for j in range(n + 1): + left, right = word[:j], word[j:] + rev_left, rev_right = left[::-1], right[::-1] + + if is_palindrome(left) and rev_right in word_map and word_map[rev_right] != i: + result.append([word_map[rev_right], i]) + + if j < n and is_palindrome(right) and rev_left in word_map and word_map[rev_left] != i: + result.append([i, word_map[rev_left]]) + + return result + + ``` + + + + + ```cpp + + #include + #include + #include + #include + + using namespace std; + + class Solution { + public: + vector> palindromePairs(vector& words) { + unordered_map wordMap; + vector> result; + + // Build the word map + for (int i = 0; i < words.size(); ++i) { + wordMap[words[i]] = i; + } + + // Iterate through each word + for (int i = 0; i < words.size(); ++i) { + const string& word = words[i]; + int n = word.size(); + + // Check each possible split of the word into left and right parts + for (int j = 0; j <= n; ++j) { + string left = word.substr(0, j); + string right = word.substr(j); + string revLeft = left; + string revRight = right; + reverse(revLeft.begin(), revLeft.end()); + reverse(revRight.begin(), revRight.end()); + + // Check if left + right forms a palindrome + if (isPalindrome(left) && wordMap.find(revRight) != wordMap.end() && wordMap[revRight] != i) { + result.push_back({wordMap[revRight], i}); + } + + // Check if right + left forms a palindrome (to avoid duplicates) + if (j < n && isPalindrome(right) && wordMap.find(revLeft) != wordMap.end() && wordMap[revLeft] != i) { + result.push_back({i, wordMap[revLeft]}); + } + } + } + + return result; + } + + bool isPalindrome(const string& s) { + int left = 0, right = s.size() - 1; + while (left < right) { + if (s[left] != s[right]) { + return false; + } + ++left; + --right; + } + return true; + } + }; + + ``` + + + + + +## References + +- **LeetCode Problem:** [Palindrome Pairs Problem](https://leetcode.com/problems/palindrome-pairs/) +- **Solution Link:** [Palindrome Pairs Solution on LeetCode](https://leetcode.com/problems/palindrome-pairs/solutions/5016750/palindrome-pairs/) +- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) + +--- diff --git a/solutions/lc-solutions/0300-0399/0342-Power-Of-Four b/solutions/lc-solutions/0300-0399/0342-Power-Of-Four new file mode 100644 index 0000000..66833f4 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0342-Power-Of-Four @@ -0,0 +1,58 @@ +--- +id: power-of-four +title: Power Of Four +sidebar_label: 342-Power-Of-Four +tags: + - Math + - Bit Manupulation + - Recursion +--- + +## Problem Description +Given an integer `n`, return `true` if it is a power of four. Otherwise, return `false`. + +An integer `n` is a power of four, if there exists an integer x such that `n == 4x`. + + +### Example + +**Example 1:** + +``` +Input: n = 16 +Output: true +``` + +**Example 2:** +``` +Input: n = 5 +Output: false +``` + +### Constraints + +- `-231 <= n <= 231 - 1` + +## Solution Approach + +### Intuition: + +To efficiently determine the power of four of the number + + +## Solution Implementation + +### Code (C++): + +```cpp +class Solution { +public: + bool isPowerOfFour(int n) { + if(n==0) return false; + else if(n==1) return true; + return n%4==0 && isPowerOfFour(n/4); + + } +}; + +``` diff --git a/solutions/lc-solutions/0300-0399/0342-powerof-four.md b/solutions/lc-solutions/0300-0399/0342-powerof-four.md new file mode 100644 index 0000000..f399b32 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0342-powerof-four.md @@ -0,0 +1,177 @@ +--- +id: powerof-four +title: Power of Four +sidebar_label: 342-Power of Four +tags: + - Math + - Bit Manipulation + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Power of Four problem on LeetCode." +sidebar_position: 6 +--- + +## Problem Description + +Given an integer `n`, return `true` if it is a power of four. Otherwise, return `false`. + +An integer `n` is a power of four if there exists an integer `x` such that `n == 4^x`. + +### Examples + +**Example 1:** + +``` +Input: n = 16 +Output: true +``` + +**Example 2:** + +``` +Input: n = 5 +Output: false +``` + +**Example 3:** + +``` +Input: n = 1 +Output: true +``` + +### Constraints + +- `-2^31 <= n <= 2^31 - 1` + + + +--- + +## Solution for Power of Four Problem + +### Approach 1: Brute Force (Loop/Recursion) + +The brute force approach involves repeatedly dividing the number by `4` and checking if it becomes `1`. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + bool isPowerOfFour(int n) { + if (n < 1) return false; + while (n % 4 == 0) { + n /= 4; + } + return n == 1; + } +}; +``` + + + + + +```java +class Solution { + public boolean isPowerOfFour(int n) { + if (n < 1) return false; + while (n % 4 == 0) { + n /= 4; + } + return n == 1; + } +} +``` + + + + + +```python +class Solution: + def isPowerOfFour(self, n: int) -> bool: + if n < 1: + return False + while n % 4 == 0: + n //= 4 + return n == 1 +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(\log n)$, as we keep dividing `n` by `4`. +- **Space Complexity**: $O(1)$, constant space usage. + +### Approach 2: Optimized (Bit Manipulation) + +The optimized approach checks if `n` is a power of four without loops or recursion. We can use bit manipulation: + +1. `n > 0`: Ensure `n` is positive. +2. `n & (n - 1) == 0`: Ensure `n` is a power of two (only one bit set). +3. `(n - 1) % 3 == 0`: Ensure `n` is a power of four (using properties of powers of four). + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + bool isPowerOfFour(int n) { + return n > 0 && (n & (n - 1)) == 0 && (n - 1) % 3 == 0; + } +}; +``` + + + + + +```java +class Solution { + public boolean isPowerOfFour(int n) { + return n > 0 && (n & (n - 1)) == 0 && (n - 1) % 3 == 0; + } +} +``` + + + + + +```python +class Solution: + def isPowerOfFour(self, n: int) -> bool: + return n > 0 and (n & (n - 1)) == 0 and (n - 1) % 3 == 0 +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(1)$, constant time operations. +- **Space Complexity**: $O(1)$, constant space usage. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0300-0399/0344-reverse-string.md b/solutions/lc-solutions/0300-0399/0344-reverse-string.md new file mode 100644 index 0000000..39a6c00 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0344-reverse-string.md @@ -0,0 +1,250 @@ +--- +id: reverse-string +title: Reverse String +sidebar_label: 344. Reverse String + +tags: +- Strings +- C++ +- Reverse String + +description: "This is a solution to the Reverse String problem on LeetCode." +--- + +## Problem Description +Write a function that reverses a string. The input string is given as an array of characters `s`. +You must do this by modifying the input array *in-place* with `O(1)` extra memory. + +### Examples + +**Example 1:** +``` +Input: s = ["h","e","l","l","o"] +Output: ["o","l","l","e","h"] +``` + +**Example 2:** +``` +Input: s = ["H","a","n","n","a","h"] +Output: ["h","a","n","n","a","H"] +``` + + +### Constraints +- `1 <= s.length <= 105` +- `s[i]` is a printable ascii character. + + +## Solution for Reverse String +### Approach +#### Brute Force +- Create a new array `reversed` of the same length as `s`. +- Iterate over the input array `s` from the end to the beginning and copy each character to the `reversed` array. +- Copy the contents of the `reversed` array back to `s`. + +**Implementation:** +```javascript +var reverseStringBruteForce = function(s) { + const n = s.length; + const reversed = new Array(n); + + for (let i = 0; i < n; i++) { + reversed[i] = s[n - 1 - i]; + } + + for (let i = 0; i < n; i++) { + s[i] = reversed[i]; + } +}; +``` + +**Complexity:** +- Time Complexity: `O(n)`, where n is the length of the array `s`, as we need to iterate through the array twice. +- Space Complexity: `O(n)` as we use an additional array of the same length as `s`. + +**Corner Cases:** +- An empty array: `[]`. +- An array with one character: `['a']` +- An array with repeated characters: `['a', 'a', 'a']` + +#### Optimized Approach +- **Two-pointer Technique**: Use two pointers: one starting from the beginning `(left)` and one from the end `(right)` of the array. +- **Swapping**: Swap the characters at these two pointers. +- **Continue Until Pointers Meet**: Move the pointers towards the center until they meet. + +**Implementation:** + +```javascript +var reverseStringOptimized = function(s) { + let left = 0; + let right = s.length - 1; + + while (left < right) { + [s[left], s[right]] = [s[right], s[left]]; // Swap characters + left++; + right--; + } +}; +``` + +**Complexity:** +- Time Complexity: `O(n)` where n is the length of the array `s`, as we only iterate through half of the array. +- Space Complexity: `O(1)` as we do not use any extra space apart from the input array. + +**Corner Cases:** +- An empty array: `[]`. +- An array with one character: `['a']` +- An array with repeated characters: `['a', 'a', 'a']` + + + + + +#### Implementation + + ```jsx live + function Solution(arr) { + var reversedString = function(s) { + let left = 0 + let right = s.length - 1 + + while(left < right){ + // Swap characters + [s[left], s[right]] = [s[right], s[left]] + left++ + right-- + } + }; + + const input = ['h', 'e', 'l', 'l', 'o'] + const originalInput = [...input] + reversedString(input) + return ( +
+

+ Input: + {JSON.stringify(originalInput)} +

+

+ Output: {JSON.stringify(input)} +

+
+ ); + } + ``` + +#### Complexity Analysis + + - Time Complexity: $O(n)$ + - Space Complexity: $O(1)$ + + ## Code in Different Languages + + + + + + + ```javascript + var reverseString = function(s) { + let left = 0; + let right = s.length - 1; + + while (left < right) { + [s[left], s[right]] = [s[right], s[left]]; // Swap characters + left++; + right--; + } + }; + ``` + + + + + + + ```typescript + function reverseString(s: string[]): void { + let left = 0; + let right = s.length - 1; + + while (left < right) { + [s[left], s[right]] = [s[right], s[left]]; // Swap characters + left++; + right--; + } + }; + ``` + + + + + + + ```python + class Solution: + def reverseString(self, s: List[str]) -> None: + """ + Do not return anything, modify s in-place instead. + """ + left, right = 0, len(s) - 1 + + while left < right: + s[left], s[right] = s[right], s[left] # Swap characters + left += 1 + right -= 1 + ``` + + + + + + + ```java + class Solution { + public void reverseString(char[] s) { + int left = 0, right = s.length - 1; + + while (left < right) { + char temp = s[left]; + s[left] = s[right]; + s[right] = temp; + left++; + right--; + } + } + } + ``` + + + + + + + ```cpp + class Solution { + public: + void reverseString(vector& s) { + int left = 0, right = s.size() - 1; + + while (left < right) { + swap(s[left], s[right]); // Swap characters + left++; + right--; + } + } + }; + + ``` + + + + +
+
+ +## References + +- **LeetCode Problem**: [Reverse String](https://leetcode.com/problems/reverse-string/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/reverse-string/solutions/) \ No newline at end of file diff --git a/solutions/lc-solutions/0300-0399/0345-reverse-vowels-of-a-string.md b/solutions/lc-solutions/0300-0399/0345-reverse-vowels-of-a-string.md new file mode 100644 index 0000000..223cb5c --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0345-reverse-vowels-of-a-string.md @@ -0,0 +1,313 @@ +--- +id: reverse-vowels-of-a-string +title: Reverse Vowels of a String Solution +sidebar_label: 0345 - Reverse Vowels of a String +tags: + - Reverse Vowels of a String + - String + - Two Pointers + - LeetCode + - JavaScript + - TypeScript +description: "This is a solution to the Reverse Vowels of a String problem on LeetCode." +sidebar_position: 345 +--- + +In this tutorial, we will solve the Reverse Vowels of a String problem using efficient string manipulation techniques. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, and C++. + +## Problem Description + +Given a string `s`, reverse only all the vowels in the string and return it. + +The vowels are `'a', 'e', 'i', 'o', 'u'`, and they can appear in both lower and upper cases, more than once. + +### Examples + +**Example 1:** + +```plaintext +Input: s = "hello" +Output: "holle" +``` + +**Example 2:** + +```plaintext +Input: s = "leetcode" +Output: "leotcede" +``` + +### Constraints + +- `1 <= s.length <= 3 * 10^5` +- `s` consists of printable ASCII characters. + +--- + +## Solution for Reverse Vowels of a String + +### Intuition and Approach + +To solve this problem, we can use a two-pointer approach to efficiently reverse the vowels in the string. We will place one pointer at the beginning (`left`) and another at the end (`right`) of the string. We will move these pointers towards each other, swapping vowels when both pointers point to a vowel. + + + + +### Approach: Two Pointers + +We can use two pointers to efficiently reverse the vowels in the string. This involves traversing the string from both ends and swapping vowels when encountered. + +#### Implementation + +```jsx live +function reverseVowels(s) { + const vowels = new Set('aeiouAEIOU'); + const arr = s.split(''); + let left = 0; + let right = arr.length - 1; + + while (left < right) { + if (!vowels.has(arr[left])) { + left++; + continue; + } + if (!vowels.has(arr[right])) { + right--; + continue; + } + [arr[left], arr[right]] = [arr[right], arr[left]]; + left++; + right--; + } + + return arr.join(''); +} + +const input = "hello"; +const result = reverseVowels(input); + +return ( +
+

+ Input: {input} +

+

+ Output: {result} +

+
+); +``` + +#### Codes in Different Languages + + + + + ```javascript + function reverseVowels(s) { + const vowels = new Set('aeiouAEIOU'); + const arr = s.split(''); + let left = 0; + let right = arr.length - 1; + + while (left < right) { + if (!vowels.has(arr[left])) { + left++; + continue; + } + if (!vowels.has(arr[right])) { + right--; + continue; + } + [arr[left], arr[right]] = [arr[right], arr[left]]; + left++; + right--; + } + + return arr.join(''); + } + ``` + + + + + ```typescript + function reverseVowels(s: string): string { + const vowels = new Set('aeiouAEIOU'); + const arr = s.split(''); + let left = 0; + let right = arr.length - 1; + + while (left < right) { + if (!vowels.has(arr[left])) { + left++; + continue; + } + if (!vowels.has(arr[right])) { + right--; + continue; + } + [arr[left], arr[right]] = [arr[right], arr[left]]; + left++; + right--; + } + + return arr.join(''); + } + ``` + + + + + ```python + def reverseVowels(s: str) -> str: + vowels = set('aeiouAEIOU') + s = list(s) + left, right = 0, len(s) - 1 + + while left < right: + if s[left] not in vowels: + left += 1 + continue + if s[right] not in vowels: + right -= 1 + continue + s[left], s[right] = s[right], s[left] + left += 1 + right -= 1 + + return ''.join(s) + ``` + + + + + ```java + class Solution { + public String reverseVowels(String s) { + Set vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')); + char[] arr = s.toCharArray(); + int left = 0, right = arr.length - 1; + + while (left < right) { + if (!vowels.contains(arr[left])) { + left++; + continue; + } + if (!vowels.contains(arr[right])) { + right--; + continue; + } + char temp = arr[left]; + arr[left] = arr[right]; + arr[right] = temp; + left++; + right--; + } + + return new String(arr); + } + } + ``` + + + + + ```cpp + class Solution { + public: + string reverseVowels(string s) { + unordered_set vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; + int left = 0, right = s.size() - 1; + + while (left < right) { + if (vowels.find(s[left]) == vowels.end()) { + left++; + continue; + } + if (vowels.find(s[right]) == vowels.end()) { + right--; + continue; + } + swap(s[left], s[right]); + left++; + right--; + } + + return s; + } + }; + ``` + + + + +#### Complexity Analysis + +- **Time Complexity:** $O(n)$, where `n` is the length of the string. +- **Space Complexity:** $O(1)$, as we are not using any additional space. + +- The time complexity is linear in terms of the length of the string. Each character is checked and potentially swapped once, leading to a time complexity of $O(n)$. +- The space complexity is constant because we only use a few extra variables regardless of the string size. + +
+
+ +:::tip Note +This solution efficiently reverses the vowels in the string while maintaining the order of non-vowel characters. +::: + +--- + +## Video Explanation of Reverse Vowels of a String + + + + + + --- + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/solutions/lc-solutions/0300-0399/0346-moving-average-from-data-stream.md b/solutions/lc-solutions/0300-0399/0346-moving-average-from-data-stream.md new file mode 100644 index 0000000..8b4ade2 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0346-moving-average-from-data-stream.md @@ -0,0 +1,295 @@ +--- +id: moving-average-from-data-stream +title: Moving Average from Data Stream Solution +sidebar_label: 0346 - Moving Average from Data Stream +tags: + - Moving Average from Data Stream + - Data Stream + - Queue + - Sliding Window + - LeetCode + - JavaScript + - TypeScript +description: "This is a solution to the Moving Average from Data Stream problem on LeetCode." +sidebar_position: 346 +--- + +In this tutorial, we will solve the Moving Average from Data Stream problem using an efficient queue-based approach. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, and C++. + +## Problem Description + +Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. + +### Examples + +**Example 1:** + +```plaintext +MovingAverage m = new MovingAverage(3); +m.next(1); // return 1.0 +m.next(10); // return 5.5 +m.next(3); // return 4.66667 +m.next(5); // return 6.0 +``` + +### Constraints + +- `1 <= size <= 1000` +- `-10^5 <= val <= 10^5` +- At most `10^4` calls will be made to `next`. + +--- + +## Solution for Moving Average from Data Stream + +### Intuition and Approach + +To solve this problem, we can use a queue to store the elements of the sliding window and maintain the sum of the elements in the current window. When a new element is added, we add it to the queue and update the sum. If the queue size exceeds the window size, we remove the oldest element from the queue and update the sum accordingly. + + + + +### Approach: Queue + +We will use a queue to maintain the elements of the sliding window and a variable to keep track of the sum of the elements. + +#### Implementation + +```jsx live +class MovingAverage { + constructor(size) { + this.size = size; + this.queue = []; + this.sum = 0; + } + + next(val) { + this.queue.push(val); + this.sum += val; + if (this.queue.length > this.size) { + this.sum -= this.queue.shift(); + } + return this.sum / this.queue.length; + } +} + +const movingAverage = new MovingAverage(3); +const results = [ + movingAverage.next(1), // 1.0 + movingAverage.next(10), // 5.5 + movingAverage.next(3), // 4.66667 + movingAverage.next(5) // 6.0 +]; + +return ( +
+

Moving Average after adding 1: {results[0]}

+

Moving Average after adding 10: {results[1]}

+

Moving Average after adding 3: {results[2]}

+

Moving Average after adding 5: {results[3]}

+
+); +``` + +#### Codes in Different Languages + + + + + ```javascript + class MovingAverage { + constructor(size) { + this.size = size; + this.queue = []; + this.sum = 0; + } + + next(val) { + this.queue.push(val); + this.sum += val; + if (this.queue.length > this.size) { + this.sum -= this.queue.shift(); + } + return this.sum / this.queue.length; + } + } + ``` + + + + + ```typescript + class MovingAverage { + private size: number; + private queue: number[]; + private sum: number; + + constructor(size: number) { + this.size = size; + this.queue = []; + this.sum = 0; + } + + next(val: number): number { + this.queue.push(val); + this.sum += val; + if (this.queue.length > this.size) { + this.sum -= this.queue.shift()!; + } + return this.sum / this.queue.length; + } + } + ``` + + + + + ```python + from collections import deque + + class MovingAverage: + + def __init__(self, size: int): + self.size = size + self.queue = deque() + self.sum = 0 + + def next(self, val: int) -> float: + self.queue.append(val) + self.sum += val + if len(self.queue) > self.size: + self.sum -= self.queue.popleft() + return self.sum / len(self.queue) + ``` + + + + + ```java + import java.util.LinkedList; + import java.util.Queue; + + class MovingAverage { + private int size; + private Queue queue; + private int sum; + + public MovingAverage(int size) { + this.size = size; + this.queue = new LinkedList<>(); + this.sum = 0; + } + + public double next(int val) { + queue.offer(val); + sum += val; + if (queue.size() > size) { + sum -= queue.poll(); + } + return (double) sum / queue.size(); + } + } + ``` + + + + + ```cpp + #include + + class MovingAverage { + public: + MovingAverage(int size) { + this->size = size; + this->sum = 0; + } + + double next(int val) { + q.push(val); + sum += val; + if (q.size() > size) { + sum -= q.front(); + q.pop(); + } + return (double) sum / q.size(); + } + + private: + int size; + int sum; + std::queue q; + }; + ``` + + + + +#### Complexity Analysis + +- **Time Complexity:** $O(1)$ for each call to `next`, as we are simply adding and removing elements from the queue and updating the sum. +- **Space Complexity:** $O(N)$, where `N` is the size of the window, to store the elements in the queue. + +- The time complexity is constant for each `next` operation because we perform a fixed number of operations regardless of the number of elements in the queue. +- The space complexity is linear in terms of the size of the window because we store up to `N` elements in the queue. + +
+
+ +:::tip Note +This solution efficiently calculates the moving average of the elements in the stream using a sliding window. +::: + +--- + +## Video Explanation of Moving Average from Data Stream + + + + + + --- + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/solutions/lc-solutions/0300-0399/0349-Intersection-of-Two-Arrays.md b/solutions/lc-solutions/0300-0399/0349-Intersection-of-Two-Arrays.md new file mode 100644 index 0000000..7e93ac3 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0349-Intersection-of-Two-Arrays.md @@ -0,0 +1,184 @@ +--- +id: intersection-of-two-arrays +title: Intersection of Two Arrays +sidebar_label: 0349 Intersection of Two Arrays +tags: +- Array +- Hash Table +- Two Pointers +- Binary Search +- Sorting +description: "Solution to Leetcode 349. Intersection of Two Arrays " +--- + +## Problem Description + +Given two integer arrays nums1 and nums2, return an array of their +intersection. Each element in the result must be unique and you may return the result in any order. + + + +### Examples + +**Example 1:** + +``` +Input: nums1 = [1,2,2,1], nums2 = [2,2] +Output: [2] +``` + +**Example 2:** + +``` +Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] +Output: [9,4] +Explanation: [4,9] is also accepted. + +``` + + + +### Constraints +- `1 <= nums1.length, nums2.length <= 1000` +- `0 <= nums1[i], nums2[i] <= 1000` + +### Approach +1. If nums1 and nums2 are sorted, we can use a two pointers approach to find elements that appear in both arrays. Initialize one pointer for each array that starts at the smallest element. + +2. If the numbers at both pointers are the same, add the number to a set that stores integers that appear in both arrays. Then, increase both pointers by 1, since this element is already processed. + +3. Otherwise, if the numbers at both pointers are not equal, the smaller of the two values cannot appear in the other array because both arrays are sorted. Therefore, we can increase the pointer of the smaller value. + +### Complexity + +Time complexity: $O(nlogn+mlogm)$, where n and m are the arrays lengths. This dominating term comes from the need to sort both input arrays at the beginning of the solution. + +Space complexity: $O(m+n)$ in the worst case when all elements in the arrays are different. This space is necessary to store and create the set intersection. The space used to store the result is not counted in the space complexity. + + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp +class Solution { +public: + std::vector intersection(std::vector& nums1, std::vector& nums2) { + sort(nums1.begin(), nums1.end()); + sort(nums2.begin(), nums2.end()); + + int N = nums1.size(); + int M = nums2.size(); + int p1 = 0; + int p2 = 0; + unordered_set intersection; + while (p1 < N && p2 < M) { + if (nums1[p1] == nums2[p2]) { + intersection.insert(nums1[p1]); + p1++; + p2++; + } + else if (nums1[p1] < nums2[p2]) { + p1++; + } + else { + p2++; + } + } + vector result(intersection.begin(), intersection.end()); + return result; + } +}; + + ``` + +#### JAVA + +```java +class Solution { + public int[] intersection(int[] nums1, int[] nums2) { + Arrays.sort(nums1); + Arrays.sort(nums2); + + int N = nums1.length; + int M = nums2.length; + int p1 = 0; + int p2 = 0; + + Set intersection = new HashSet<>(); + + while (p1 < N && p2 < M) { + if (nums1[p1] == nums2[p2]) { + intersection.add(nums1[p1]); + p1++; + p2++; + } + else if (nums1[p1] < nums2[p2]) { + p1++; + } + else { + p2++; + } + } + + int K = intersection.size(); + int[] result = new int[K]; + int curr = 0; + for (int x: intersection) { + result[curr++] = x; + } + return result; + } +} +``` + +#### PYTHON + +```python +class Solution(object): + def intersection(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: List[int] + """ + nums1.sort() + nums2.sort() + + N = len(nums1) + M = len(nums2) + p1 = 0 + p2 = 0 + + intersection = set() + + while p1 < N and p2 < M: + if nums1[p1] == nums2[p2]: + intersection.add(nums1[p1]) + p1 += 1 + p2 += 1 + elif nums1[p1] < nums2[p2]: + p1 += 1 + else: + p2 += 1 + result = [] + for x in intersection: + result.append(x) + return result + + +``` + + + +### Complexity Analysis + +- Time Complexity: $O(nlogn+mlogm)$ + +- Space Complexity: $O(n+m)$ + +### References + +- **LeetCode Problem**: Intersection of Two Arrays \ No newline at end of file diff --git a/solutions/lc-solutions/0300-0399/0350-Intersection-of-Two-Arrays-II.md b/solutions/lc-solutions/0300-0399/0350-Intersection-of-Two-Arrays-II.md new file mode 100644 index 0000000..ca2e6c5 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0350-Intersection-of-Two-Arrays-II.md @@ -0,0 +1,163 @@ +--- +id: intersection-of-two-arrays-II +title: Intersection of Two Arrays II +sidebar_label: 0350 Intersection of Two Arrays II +tags: +- Array +- Hash Table +- Two Pointers +- Binary Search +- Sorting +description: "Solution to Leetcode 350. Intersection of Two Arrays II " +--- + +## Problem Description + +Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order. + + + +### Examples + +**Example 1:** + +``` +Input: nums1 = [1,2,2,1], nums2 = [2,2] +Output: [2,2] +``` + +**Example 2:** + +``` +Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] +Output: [4,9] +Explanation: [9,4] is also accepted. + +``` + + + +### Constraints +- `1 <= nums1.length, nums2.length <= 1000` +- `0 <= nums1[i], nums2[i] <= 1000` + +### Approach +1. Sort Both Arrays: Sorting helps in comparing elements of both arrays efficiently. By sorting both arrays, we can then use a two-pointer approach to find common elements. + +2. Initialize Pointers: Use two pointers i and j to traverse through nums1 and nums2 respectively. Also, use a pointer k to keep track of the position in nums1 where we store the result. + +3. Traverse Both Arrays: + +- Compare the elements at the current positions of both pointers. +- If the element in nums1 is less than the element in nums2, increment pointer i. +- If the element in nums1 is greater than the element in nums2, increment pointer j. +- If the elements are equal, it means we have found a common element. Store this element in nums1[k], increment i, j, and k. +- Return the Result: The result is stored in the first k positions of nums1. Use Arrays.copyOfRange to return this part of the array. + +### Complexity + +Time Complexity: Sorting both arrays takes $O(n log n + m log m)$, where $n$ is the length of nums1 and $m$ is the length of nums2. The two-pointer traversal takes $O(n + m)$. Thus, the overall time complexity is $O(n log n + m log m + n + m) = O(n log n + m log m)$. + +Space Complexity: The space complexity is $O(1)$ if we ignore the space used for sorting, as we are not using any extra space apart from the input arrays. + + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp +class Solution { +public: + vector intersect(vector& nums1, vector& nums2) { + sort(nums1.begin(), nums1.end()); + sort(nums2.begin(), nums2.end()); + + int i = 0, j = 0; + vector result; + + while (i < nums1.size() && j < nums2.size()) { + if (nums1[i] < nums2[j]) { + i++; + } else if (nums1[i] > nums2[j]) { + j++; + } else { + result.push_back(nums1[i]); + i++; + j++; + } + } + + return result; + } +}; + ``` + +#### JAVA + +```java +class Solution { + public int[] intersect(int[] nums1, int[] nums2) { + int l1 = nums1.length; + int l2 = nums2.length; + int i = 0, j = 0, k = 0; + Arrays.sort(nums1); + Arrays.sort(nums2); + while( i < l1 && j < l2) + { + if(nums1[i] < nums2[j]) + { + i++; + } + else if(nums1[i] > nums2[j]) + { + j++; + } + else + { + nums1[k++] = nums1[i++]; + j++; + } + } + return Arrays.copyOfRange(nums1,0,k); + } +} +``` + +#### PYTHON + +```python +class Solution(object): + def intersect(self, nums1, nums2): + nums1.sort() + nums2.sort() + + i, j = 0, 0 + result = [] + + while i < len(nums1) and j < len(nums2): + if nums1[i] < nums2[j]: + i += 1 + elif nums1[i] > nums2[j]: + j += 1 + else: + result.append(nums1[i]) + i += 1 + j += 1 + + return result + +``` + + + +### Complexity Analysis + +- Time Complexity: $O(n log n + m log m)$ + +- Space Complexity: $O(1)$ + +### References + +- **LeetCode Problem**: Intersection of Two Arrays II \ No newline at end of file diff --git a/solutions/lc-solutions/0300-0399/0352-Data-Stream-as-Disjoint-Intervals.md b/solutions/lc-solutions/0300-0399/0352-Data-Stream-as-Disjoint-Intervals.md new file mode 100644 index 0000000..2f19413 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0352-Data-Stream-as-Disjoint-Intervals.md @@ -0,0 +1,237 @@ +--- +id: data-stream-as-disjoint-intervals +title: Data Stream as Disjoint Intervals +sidebar_label: 0352 Data Stream as Disjoint Intervals +tags: + - Binary Search + - Design + - Ordered Set + - Java + - Python + - C++ +description: "This is a solution to the Data Stream as Disjoint Intervals problem on LeetCode." +--- + +## Problem Description + +Given a data stream input of non-negative integers a1, a2, ..., an, summarize the numbers seen so far as a list of disjoint intervals. + +Implement the SummaryRanges class: + +- `SummaryRanges()` Initializes the object with an empty stream. +- void `addNum(int value)` Adds the integer value to the stream. +- `int[][] getIntervals()` Returns a summary of the integers in the stream currently as a list of disjoint intervals `[starti, endi]`. The answer should be sorted by starting. + +### Examples + +**Example 1:** + +``` +Input +["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"] +[[], [1], [], [3], [], [7], [], [2], [], [6], []] +Output +[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]] + +Explanation +SummaryRanges summaryRanges = new SummaryRanges(); +summaryRanges.addNum(1); // arr = [1] +summaryRanges.getIntervals(); // return [[1, 1]] +summaryRanges.addNum(3); // arr = [1, 3] +summaryRanges.getIntervals(); // return [[1, 1], [3, 3]] +summaryRanges.addNum(7); // arr = [1, 3, 7] +summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]] +summaryRanges.addNum(2); // arr = [1, 2, 3, 7] +summaryRanges.getIntervals(); // return [[1, 3], [7, 7]] +summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7] +summaryRanges.getIntervals(); // return [[1, 3], [6, 7]] + +``` + + +### Constraints + +- `0 <= value <= 10^4` +- `At most 3 * 10^4 calls will be made to addNum and getIntervals.` +- `At most 10^2 calls will be made to getIntervals` + +--- + +## Solution for Data Stream as Disjoint Intervals + +### Intuition + +The intuition behind this implementation is to use a data structure that allows for easy ordering and searching, as well as efficient insertion and deletion of intervals. In this case, a std::map is used to store the disjoint intervals. The key is the start value of the interval and the value is the end value. +By using a data structure like map which implements a balanced binary search tree, we can easily find the correct position of new value and merge it with the existing intervals if necessary, which will help us to maintain the disjoint property of the intervals. + +### Approach +The approach used in this implementation is to use a data structure, in this case a std::map, to store the disjoint intervals. Each interval is stored as a key-value pair in the map, where the key is the start value of the interval and the value is the end value. + +When a new value is added to the stream, the `lower_bound()` function is used to find the correct position of the new value in the map, and then the implementation checks if the new value can be added to an existing interval or if it needs to create a new one. It also checks if the new value can merge with the interval before or after it, and merges them if necessary. + +The `getIntervals()` function iterates through the map and stores the intervals in a vector of vectors, which is returned. + +By using the map's properties of ordering and searching, the implementation can easily find the correct position of the new value in the stream and merge it with the existing intervals if necessary. + +This approach is efficient in terms of space and time complexity because it allows for easy ordering and searching, as well as efficient insertion and deletion of intervals, which is important for maintaining the disjoint property of the intervals. + +#### Code in Different Languages + + + + + ```java + public class SummaryRanges { + TreeMap tree; + + public SummaryRanges() { + tree = new TreeMap<>(); + } + + public void addNum(int val) { + if(tree.containsKey(val)) return; + Integer l = tree.lowerKey(val); + Integer h = tree.higherKey(val); + if(l != null && h != null && tree.get(l).end + 1 == val && h == val + 1) { + tree.get(l).end = tree.get(h).end; + tree.remove(h); + } else if(l != null && tree.get(l).end + 1 >= val) { + tree.get(l).end = Math.max(tree.get(l).end, val); + } else if(h != null && h == val + 1) { + tree.put(val, new Interval(val, tree.get(h).end)); + tree.remove(h); + } else { + tree.put(val, new Interval(val, val)); + } + } + + public List getIntervals() { + return new ArrayList<>(tree.values()); + } +} + + ``` + + + + + ```python + class DSU: + def __init__(self): + self.p = {} + self.intervals = {} + + def exists(self, x): return x in self.p + + def make_set(self, x): + self.p[x] = x + self.intervals[x] = [x,x] + + def find(self, x): + if not self.exists(x): return None + + if self.p[x] != x: + self.p[x] = self.find(self.p[x]) + + return self.p[x] + + def union(self, x, y): + xr = self.find(x) + yr = self.find(y) + + if xr is None or yr is None: return + + self.p[xr] = yr + + ## interval adjusting logic + x_interval = self.intervals[xr] + del self.intervals[xr] + + self.intervals[yr] = [min(self.intervals[yr][0], x_interval[0]), max(self.intervals[yr][1], x_interval[1])] + +class SummaryRanges: + def __init__(self): + self.dsu = DSU() + + def addNum(self, val: int) -> None: + if self.dsu.exists(val): return + + self.dsu.make_set(val) + + self.dsu.union(val, val-1) + self.dsu.union(val, val+1) + + def getIntervals(self) -> List[List[int]]: + return sorted(self.dsu.intervals.values()) + + ``` + + + + + ```cpp + + class SummaryRanges { +public: + SummaryRanges() { + + } + + void addNum(int value) { + auto it = _map.lower_bound(value); + bool merged = false; + if(it != _map.begin()) { + auto prev = it; + --prev; + if(prev->second + 1 >= value) { + merged = true; + prev->second = max(prev->second, value); + } + } + + if(it != _map.end()) { + if(it->first - 1 <= value) { + if(merged) { + auto prev = it; + --prev; + if(prev->second >= it->first - 1) { + prev->second = max(prev->second, it->second); + _map.erase(it); + } + } else { + merged = true; + if(it->first != value) { + pair p = *it; + p.first = min(p.first, value); + it = _map.insert(it, p); + ++it; + if(it != _map.end()) + _map.erase(it); + } + } + } + } + if(!merged) + _map.insert(it, {value, value}); + } + + vector> getIntervals() { + vector> intervals; + for(auto const & p : _map) + intervals.push_back({p.first, p.second}); + return intervals; + } + + map _map; +}; + + ``` + + + + + +## References + +- **LeetCode Problem:** [Palindrome Pairs Problem](https://leetcode.com/problems/data-stream-as-disjoint-intervals/description/) +--- diff --git a/solutions/lc-solutions/0300-0399/0355-design-twitter.md b/solutions/lc-solutions/0300-0399/0355-design-twitter.md new file mode 100644 index 0000000..3aee7bd --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0355-design-twitter.md @@ -0,0 +1,276 @@ +--- +id: twitter-design +title: Design Twitter +sidebar_label: Design Twitter +tags: + - Design + - OOP + - System Design + - Data Structures +description: Design a simplified version of Twitter with basic functionalities using OOP principles. +--- + +## Problem Description + +Design a simplified version of Twitter where users can post tweets, follow/unfollow other users, and see the 10 most recent tweets in their news feed. + +### Functionality Requirements + +- **postTweet(userId, tweetId)**: Composes a new tweet with ID `tweetId` by the user `userId`. Each tweet ID is unique. + +- **getNewsFeed(userId)**: Retrieves the 10 most recent tweet IDs in the user's news feed. The feed includes tweets posted by users who the current user follows and their own tweets. Tweets should be ordered from most recent to least recent. + +- **follow(followerId, followeeId)**: The user with ID `followerId` starts following the user with ID `followeeId`. + +- **unfollow(followerId, followeeId)**: The user with ID `followerId` stops following the user with ID `followeeId`. + +### Examples + +**Example 1:** + +``` +Input +["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] +[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]] +Output +[null, null, [5], null, null, [6, 5], null, [5]] + +Explanation +Twitter twitter = new Twitter(); +twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). +twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5] +twitter.follow(1, 2); // User 1 follows user 2. +twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). +twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. +twitter.unfollow(1, 2); // User 1 unfollows user 2. +twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2. +``` + +### Constraints + +- $1 <= userId, followerId, followeeId <= 500$ +- $0 <= tweetId <= 10^4$ +- At most 3 * 10^4 calls will be made to postTweet, getNewsFeed, follow, and unfollow. + +## Solution for Twitter Design Problem + +### Design Approach + +To implement the simplified Twitter functionality, we'll use the following classes: + +- **User**: Represents a user with a unique `userId`, manages their tweets and follows. +- **Tweet**: Represents a tweet with a unique `tweetId` and a timestamp. +- **Twitter**: Manages users, tweets, and the operations (post tweet, get news feed, follow, unfollow). + +#### Code in Different Languages + + + + + + + ```python + + from collections import defaultdict, deque + import heapq + + class Twitter: + def __init__(self): + self.user_tweets = defaultdict(deque) # Maps userId to a deque of their tweets + self.user_follows = defaultdict(set) # Maps userId to a set of users they follow + self.time_stamp = 0 # Global timestamp to keep track of the order of tweets + + def postTweet(self, userId, tweetId): + # Add the tweet to the user's deque of tweets + self.user_tweets[userId].appendleft((self.time_stamp, tweetId)) + self.time_stamp += 1 + + def getNewsFeed(self, userId): + # Create a min-heap to keep track of the 10 most recent tweets + min_heap = [] + + # Add user's own tweets + self.addTweetsToHeap(min_heap, userId) + + # Add tweets from the users the given user is following + for followeeId in self.user_follows[userId]: + self.addTweetsToHeap(min_heap, followeeId) + + # Extract tweet IDs from the heap and return them in reverse order (most recent first) + return [tweetId for time_stamp, tweetId in sorted(min_heap, reverse=True)] + + def addTweetsToHeap(self, heap, userId): + # Add up to 10 most recent tweets of a user to the heap + if userId in self.user_tweets: + for tweet in list(self.user_tweets[userId])[:10]: + heapq.heappush(heap, tweet) + if len(heap) > 10: + heapq.heappop(heap) + + def follow(self, followerId, followeeId): + # A user cannot follow themselves + if followerId != followeeId: + self.user_follows[followerId].add(followeeId) + + def unfollow(self, followerId, followeeId): + # Remove the followeeId from the followerId's set of follows + if followerId in self.user_follows and followeeId in self.user_follows[followerId]: + self.user_follows[followerId].remove(followeeId) + ``` + + + + + ```java + + + import java.util.*; + class Twitter { + private static int timeStamp = 0; + private Map userMap; + + private class Tweet { + public int id; + public int time; + public Tweet next; + + public Tweet(int id) { + this.id = id; + this.time = timeStamp++; + this.next = null; + } + } + + public class User { + public int id; + public Set followed; + public Tweet tweetHead; + + public User(int id) { + this.id = id; + followed = new HashSet<>(); + follow(id); // follow itself + tweetHead = null; + } + + public void follow(int id) { + followed.add(id); + } + + public void unfollow(int id) { + followed.remove(id); + } + + public void post(int id) { + Tweet t = new Tweet(id); + t.next = tweetHead; + tweetHead = t; + } + } + + public Twitter() { + userMap = new HashMap<>(); + } + + public void postTweet(int userId, int tweetId) { + if (!userMap.containsKey(userId)) { + userMap.put(userId, new User(userId)); + } + userMap.get(userId).post(tweetId); + } + + public List getNewsFeed(int userId) { + List res = new ArrayList<>(); + if (!userMap.containsKey(userId)) return res; + + Set users = userMap.get(userId).followed; + PriorityQueue pq = new PriorityQueue<>(users.size(), (a, b) -> (b.time - a.time)); + + for (int user : users) { + Tweet t = userMap.get(user).tweetHead; + if (t != null) { + pq.add(t); + } + } + int n = 0; + while (!pq.isEmpty() && n < 10) { + Tweet t = pq.poll(); + res.add(t.id); + n++; + if (t.next != null) { + pq.add(t.next); + } + } + return res; + } + + public void follow(int followerId, int followeeId) { + if (!userMap.containsKey(followerId)) { + userMap.put(followerId, new User(followerId)); + } + if (!userMap.containsKey(followeeId)) { + userMap.put(followeeId, new User(followeeId)); + } + userMap.get(followerId).follow(followeeId); + } + + public void unfollow(int followerId, int followeeId) { + if (!userMap.containsKey(followerId)) return; + if (followerId == followeeId) return; + userMap.get(followerId).unfollow(followeeId); + } + + ``` + + + + ```cpp + + class Twitter { + public: + Twitter() { + + } + + void postTweet(int userId, int tweetId) { + feed.push_back({ userId, tweetId }); + } + + vector getNewsFeed(int userId) { + std::vector ret; + for (int i = feed.size() - 1; i >= 0; --i) { + auto& [user, tweet] = feed[i]; + if (userId == user || (following[userId].contains(user))) { + ret.push_back(tweet); + if (ret.size() == 10) break; + } + } + return ret; + } + + void follow(int followerId, int followeeId) { + following[followerId].insert(followeeId); + } + + void unfollow(int followerId, int followeeId) { + following[followerId].erase(followeeId); + } + + std::unordered_map> following; + std::vector> feed; + }; + ``` + + + + +### Complexity Analysis + +- **Time complexity**: The time complexity of the solution is $O(N)$, where N is the number of nodes in the binary tree. This is because we visit each node exactly once during the level-order traversal. +- **Space complexity**: The space complexity of the solution is $O(N)$, where N is the number of nodes in the binary tree. This is because the space used by the queue for level-order traversal can be at most N in the worst case. + +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/binary-tree-right-side-view/) +- **Solution Link:** [Binary Tree Right Side View Solution on LeetCode](https://leetcode.com/problems/binary-tree-right-side-view/solutions/) +- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/) diff --git a/solutions/lc-solutions/0300-0399/0368-largest-divisible-subset.md b/solutions/lc-solutions/0300-0399/0368-largest-divisible-subset.md new file mode 100644 index 0000000..a6152d1 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0368-largest-divisible-subset.md @@ -0,0 +1,150 @@ +--- +id: largest-divisible-subset +title: Largest Divisible Subset (LeetCode) +sidebar_label: 0368-Largest Divisible Subset +tags: + - Array + - Math + - Sorting + - Dynamic Programming +description: Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) +sidebar_position: 0368 +--- + +## Problem Description + +Given a set of distinct positive integers nums, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies: + +- answer[i] % answer[j] == 0, or +- answer[j] % answer[i] == 0 +If there are multiple solutions, return any of them. + +### Example 1 + +- **Input:** `nums = [1,2,3]` +- **Output:** `[1,2]` + +### Example 2 + +- **Input:** `nums = [1,2,4,8]` +- **Output:** `[1,2,4,8]` + + +### Constraints + +- `1 <= nums.length <= 1000` +- `1 <= nums[i] <= 2 * 10^9` +- `All the integers in nums are unique.` + +## Approach + +- 1. The first insight is that if we sort the list of numbers nums in ascending order, any larger number can only be divisible by a smaller number and not vice versa. This imposes an order on potential divisibility relationships. + +- 2. The second insight is that we can use Dynamic Programming to build up knowledge of the largest divisible subset up to any given index as we iterate through our sorted list. We define an array f[i] to represent the size of the largest divisible subset that includes nums[i] as the largest number in the subset. So for each number nums[i], we look back at all previous numbers nums[j] where j < i and update f[i] if nums[i] % nums[j] == 0. + +- 3. Lastly, knowing the size of the largest subset isn't enough; we want the subset itself. We keep track of the index k at which we attain the maximum size of the subset. Once we finish populating our f array, we can backtrack from nums[k] and construct the actual subset by looking at elements that could be used to reach nums[k]. To construct the result, we traverse in reverse, starting from nums[k] going backward, and add numbers to our subset ans that have the correct divisibility property and help us reach the previously calculated optimum size m at each step until we've constructed the full largest subset. + +### Solution Code + +#### C++ + +```c++ +class Solution { +public: + vector largestDivisibleSubset(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + vector subsetSizes(n, 1); + int maxSubsetIndex = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[i] % nums[j] == 0) { + subsetSizes[i] = max(subsetSizes[i], subsetSizes[j] + 1); + } + } + if (subsetSizes[maxSubsetIndex] < subsetSizes[i]) { + maxSubsetIndex = i; + } + } + int currentSize = subsetSizes[maxSubsetIndex]; + vector largestSubset; + for (int i = maxSubsetIndex; currentSize > 0; --i) { + if (nums[maxSubsetIndex] % nums[i] == 0 && subsetSizes[i] == currentSize) { + largestSubset.push_back(nums[i]); + maxSubsetIndex = i; + --currentSize; + } + } + return largestSubset; + } +}; +``` + +#### Java +```java +class Solution { + public List largestDivisibleSubset(int[] nums) { + Arrays.sort(nums); + int length = nums.length; + int[] dp = new int[length]; + Arrays.fill(dp, 1); + int maxIndex = 0; + for (int i = 0; i < length; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[i] % nums[j] == 0) { + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + if (dp[maxIndex] < dp[i]) { + maxIndex = i; + } + } + int subsetSize = dp[maxIndex]; + List result = new ArrayList<>(); + for (int i = maxIndex; subsetSize > 0; --i) { + if (nums[maxIndex] % nums[i] == 0 && dp[i] == subsetSize) { + result.add(nums[i]); + maxIndex = i; + --subsetSize; + } + } + + return result; + } +} +``` + +#### Python +```python +class Solution: + def largestDivisibleSubset(self, nums: List[int]) -> List[int]: + nums.sort() + n = len(nums) + dp = [1] * n + max_index = 0 + for i in range(n): + for j in range(i): + if nums[i] % nums[j] == 0: + dp[i] = max(dp[i], dp[j] + 1) + if dp[max_index] < dp[i]: + max_index = i + subset_size = dp[max_index] + current_index = max_index + largest_subset = [] + while subset_size: + if nums[max_index] % nums[current_index] == 0 and dp[current_index] == subset_size: + largest_subset.append(nums[current_index]) + max_index, subset_size = current_index, subset_size - 1 + current_index -= 1 + return largest_subset +``` + +#### Conclusion +Time Complexity + - The outer loop runs n times where n is the number of elements in nums. + - The inner loop, for each element of the outer loop, runs a maximum of i times which is less than n. +- The Total Time Complexity is O(n^2) + +Space Complexity + - The f list which is of size n contributes O(n) to the space complexity. +- The Total Space Complexity is O(n) \ No newline at end of file diff --git a/solutions/lc-solutions/0300-0399/0373-find-k-pairs-with-smallest-sums.md b/solutions/lc-solutions/0300-0399/0373-find-k-pairs-with-smallest-sums.md new file mode 100644 index 0000000..685f1cf --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0373-find-k-pairs-with-smallest-sums.md @@ -0,0 +1,199 @@ +--- +id: find-k-pairs-with-smallest-sums +title: Find K Pairs with Smallest Sums +sidebar_label: 0373-Find K Pairs with Smallest Sums +tags: + - priority queue + - Leet code +description: "Solution to leetocde 373" +--- + +## Problem Description + +You are given two integer arrays `nums1` and `nums2` sorted in non-decreasing order and an integer `k`. + +Define a pair `(u, v)` which consists of one element from the first array and one element from the second array. + +Return the `k` pairs `(u1, v1)`, `(u2, v2)`, ..., `(uk, vk)` with the smallest sums. + +### Examples + +### Example 1: + +``` + Input: nums1 = [1, 7, 11], nums2 = [2, 4, 6], k = 3 + Output: [[1, 2], [1, 4], [1, 6]] + Explanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] +``` + +### Example 2: + +``` + Input: nums1 = [1, 1, 2], nums2 = [1, 2, 3], k = 2 + Output: [[1, 1], [1, 1]] + Explanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] +``` + +## Constraints: + +- $1 <= nums1.length, nums2.length <= 10^5$ +- $-10^9 <= nums1[i], nums2[i] <= 10^9$ +- $`nums1` and `nums2` both are sorted in non-decreasing order.$ +- $1 <= k <= 10^4$ +- $k <= nums1.length * nums2.length$ + +Certainly! Here is the algorithm for finding the k smallest pairs with the smallest sums: + +## Algorithm + +1. **Initialize a Max-Heap**: + + - Use a max-heap (priority queue) to keep track of the k smallest pairs by their sums. The max-heap will allow us to efficiently manage the top k smallest pairs. + +2. **Iterate Through Pairs**: + + - Use two nested loops to iterate through all possible pairs formed by taking one element from `nums1` and one from `nums2`. + - For each pair `(nums1[i], nums2[j])`: + - Calculate the sum of the pair: `sum = nums1[i] + nums2[j]`. + +3. **Heap Management**: + + - If the heap has fewer than k elements, push the current pair and its sum into the heap. + - If the heap already contains k elements: + - Compare the current pair's sum with the maximum sum in the heap (the top element). + - If the current pair's sum is smaller, pop the top element from the heap and push the current pair into the heap. + - If the current pair's sum is greater than or equal to the maximum sum in the heap, break the inner loop to avoid unnecessary comparisons. This optimization works because `nums2` is sorted; once a pair's sum exceeds the largest in the heap, subsequent pairs in the inner loop will only get larger. + +4. **Extract Results**: + - After processing all pairs, extract all pairs from the heap. These pairs will be in descending order of their sums because of the max-heap. + - Reverse the result list to get the pairs in ascending order of their sums. + +## C++ Solution + +```cpp +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector> kSmallestPairs(vector& nums1, vector& nums2, int k) { + vector> ans; + priority_queue>> pq; + + for (int i = 0; i < nums1.size(); i++) { + for (int j = 0; j < nums2.size(); j++) { + int sum = nums1[i] + nums2[j]; + + if (pq.size() < k) { + pq.push({sum, {nums1[i], nums2[j]}}); + } else if (sum < pq.top().first) { + pq.pop(); + pq.push({sum, {nums1[i], nums2[j]}}); + } else { + break; + } + } + } + + while (!pq.empty()) { + ans.push_back({pq.top().second.first, pq.top().second.second}); + pq.pop(); + } + + reverse(ans.begin(), ans.end()); // Reverse to get the pairs in ascending order. + return ans; + } +}; +``` + +## Python Solution + +```python +import heapq + +class Solution: + def kSmallestPairs(self, nums1, nums2, k): + pq = [] + for i in range(len(nums1)): + for j in range(len(nums2)): + sum = nums1[i] + nums2[j] + if len(pq) < k: + heapq.heappush(pq, (-sum, nums1[i], nums2[j])) + else: + if sum < -pq[0][0]: + heapq.heappop(pq) + heapq.heappush(pq, (-sum, nums1[i], nums2[j])) + else: + break + ans = [] + while pq: + sum, num1, num2 = heapq.heappop(pq) + ans.append([num1, num2]) + ans.reverse() # Reverse to get the pairs in ascending order + return ans +``` + +## Java Solution + +```java +import java.util.*; + +public class Solution { + public List> kSmallestPairs(int[] nums1, int[] nums2, int k) { + PriorityQueue pq = new PriorityQueue<>((a, b) -> b[0] - a[0]); + for (int i = 0; i < nums1.length; i++) { + for (int j = 0; j < nums2.length; j++) { + int sum = nums1[i] + nums2[j]; + if (pq.size() < k) { + pq.offer(new int[]{sum, nums1[i], nums2[j]}); + } else if (sum < pq.peek()[0]) { + pq.poll(); + pq.offer(new int[]{sum, nums1[i], nums2[j]}); + } else { + break; + } + } + } + List> ans = new ArrayList<>(); + while (!pq.isEmpty()) { + int[] pair = pq.poll(); + ans.add(Arrays.asList(pair[1], pair[2])); + } + Collections.reverse(ans); // Reverse to get the pairs in ascending order + return ans; + } +} +``` + +## JavaScript Solution + +```javascript +class Solution { + kSmallestPairs(nums1, nums2, k) { + let pq = new MaxPriorityQueue({ priority: (x) => x[0] }); + for (let i = 0; i < nums1.length; i++) { + for (let j = 0; j < nums2.length; j++) { + let sum = nums1[i] + nums2[j]; + if (pq.size() < k) { + pq.enqueue([sum, nums1[i], nums2[j]]); + } else if (sum < pq.front().element[0]) { + pq.dequeue(); + pq.enqueue([sum, nums1[i], nums2[j]]); + } else { + break; + } + } + } + let ans = []; + while (!pq.isEmpty()) { + let [sum, num1, num2] = pq.dequeue().element; + ans.push([num1, num2]); + } + ans.reverse(); // Reverse to get the pairs in ascending order + return ans; + } +} +``` diff --git a/solutions/lc-solutions/0300-0399/0374-guess-number-higher-or-lower.md b/solutions/lc-solutions/0300-0399/0374-guess-number-higher-or-lower.md new file mode 100644 index 0000000..11b6bc0 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0374-guess-number-higher-or-lower.md @@ -0,0 +1,169 @@ +--- +id: guess-number-higher-or-lower +title: Guess Number Higher or Lower +sidebar_label: 0374-Guess Number Higher or Lower +tags: + - Binary Search + - Leet code +description: "Solution to leetocde 374" +--- + +### Problem Description + +We are playing the Guess Game. The game is as follows: + +I pick a number from `1` to `n`. You have to guess which number I picked. + +Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. + +You call a pre-defined API int guess(int num), which returns three possible results: + +- `-1`: Your guess is higher than the number I picked $(i.e. num > pick).$ +- `1`: Your guess is lower than the number I picked $(i.e. num < pick).$ +- `0`: your guess is equal to the number I picked $(i.e. num == pick).$ + +Return the number that I picked. + +### Examples + +**Example 1:** + +``` +Input: n = 10, pick = 6 +Output: 6 +``` + +**Example 2:** + +``` +Input: n = 1, pick = 1 +Output: 1 +``` + +**Example 3:** + +``` +Input: n = 2, pick = 1 +Output: 1 +``` + +### Constraints: + +- $1 <= n <= 231 - 1$ +- $1 <= pick <= n$ + +### Algorithm + +1. **Initialization**: + + - Set `l` (low) to `1` and `h` (high) to `n`. These variables represent the current search range. + +2. **Binary Search Loop**: + + - While `l` is less than or equal to `h`, continue searching. + - Compute the middle point `mid` as `(l + h) / 2`. + +3. **Evaluate `guess(mid)`**: + + - Use the `guess` function to determine how to adjust the search range based on the value returned: + - If `guess(mid)` returns `1`, it means `mid` is too low, so adjust `l` to `mid + 1`. + - If `guess(mid)` returns `-1`, it means `mid` is too high, so adjust `h` to `mid - 1`. + - If `guess(mid)` returns `0`, it means `mid` is the target number, so return `mid`. + +4. **Completion**: + - If the loop exits without finding the number (i.e., `l > h`), return `l`. This handles the case where the target number is not exactly in the range but `l` will be the next potential guess. + +### Code Implementation + +### Python + +```python +def guessNumber(n): + l, h = 1, n + + while l <= h: + mid = (l + h) // 2 + + if guess(mid) == 1: + l = mid + 1 + elif guess(mid) == -1: + h = mid - 1 + else: + return mid + + return l +``` + +### C++ + +```cpp +class Solution { +public: + int guessNumber(int n) { + long long l = 1; + long long h = n; + + while (l <= h) { + int mid = (l + h) / 2; + + if (guess(mid) == 1) { + l = mid + 1; + } else if (guess(mid) == -1) { + h = mid - 1; + } else { + return mid; + } + } + + return l; + } +}; +``` + +### Java + +```java +public class Solution { + public int guessNumber(int n) { + long l = 1; + long h = n; + + while (l <= h) { + int mid = (int)((l + h) / 2); + + if (guess(mid) == 1) { + l = mid + 1; + } else if (guess(mid) == -1) { + h = mid - 1; + } else { + return mid; + } + } + + return (int)l; + } +} +``` + +### JavaScript + +```javascript +function guessNumber(n) { + let l = 1; + let h = n; + + while (l <= h) { + let mid = Math.floor((l + h) / 2); + + if (guess(mid) === 1) { + l = mid + 1; + } else if (guess(mid) === -1) { + h = mid - 1; + } else { + return mid; + } + } + + return l; +} +``` diff --git a/solutions/lc-solutions/0300-0399/0375-guess-number-higher-or-lower-II.md b/solutions/lc-solutions/0300-0399/0375-guess-number-higher-or-lower-II.md new file mode 100644 index 0000000..d376f66 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0375-guess-number-higher-or-lower-II.md @@ -0,0 +1,181 @@ +--- +id: guess-number-higher-or-lower-II +title: Guess Number Higher or Lower II +sidebar_label: 0375-Guess Number Higher or Lower II +tags: + - DP + - Leet code +description: "Solution to leetocde 375" +--- + +## Problem Description + +We are playing the Guessing Game. The game will work as follows: + +I pick a number between 1 and n. +You guess a number. +If you guess the right number, you win the game. +If you guess the wrong number, then I will tell you whether the number I picked is higher or lower, and you will continue guessing. +Every time you guess a wrong number x, you will pay x dollars. If you run out of money, you lose the game. +Given a particular n, return the minimum amount of money you need to guarantee a win regardless of what number I pick. + +## Examples: + +**Example 1:** + +``` +Input: n = 10 +Output: 16 +Explanation: The winning strategy is as follows: +- The range is [1,10]. Guess 7. + - If this is my number, your total is $0. Otherwise, you pay $7. + - If my number is higher, the range is [8,10]. Guess 9. + - If this is my number, your total is $7. Otherwise, you pay $9. + - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16. + - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16. + - If my number is lower, the range is [1,6]. Guess 3. + - If this is my number, your total is $7. Otherwise, you pay $3. + - If my number is higher, the range is [4,6]. Guess 5. + - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5. + - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15. + - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15. + - If my number is lower, the range is [1,2]. Guess 1. + - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1. + - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11. +The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win. +``` + +**Example 2:** + +``` +Input: n = 1 +Output: 0 +Explanation: There is only one possible number, so you can guess 1 and not have to pay anything. +``` + +**Example 3:** + +``` +Input: n = 2 +Output: 1 +Explanation: There are two possible numbers, 1 and 2. +- Guess 1. + - If this is my number, your total is $0. Otherwise, you pay $1. + - If my number is higher, it must be 2. Guess 2. Your total is $1. +The worst case is that you pay $1. +``` + +## Constraints: + +- $1 <= n <= 200$ + +### Algorithm Explanation + +1. **Dynamic Programming Table Setup**: + + - We create a 2D DP array `dp` where `dp[start][end]` represents the minimum amount of money required to guarantee a win if the number is between `start` and `end`. + +2. **Base Case**: + + - If `start == end`, no money is needed because we have only one number to guess. So `dp[start][end] = 0`. + +3. **Filling the DP Table**: + + - We fill the table for ranges starting from the largest range down to the smallest. + - For each range `[start, end]`, we consider every possible guess `i` within that range. + - The cost for a guess `i` is `i` plus the maximum of the costs of the two resulting subranges `[start, i-1]` and `[i+1, end]` (since we are guaranteed a win, we must consider the worst-case scenario). + - We choose the guess that minimizes this maximum cost. + +4. **Result**: + - The result is stored in `dp[1][n]` which represents the minimum amount of money needed to guarantee a win when guessing a number between 1 and `n`. + +### C++ Code + +```cpp +class Solution { +public: + int getMoneyAmount(int n) { + vector> dp(n + 2, vector(n + 2, 0)); + + for (int start = n; start >= 1; --start) { + for (int end = start + 1; end <= n; ++end) { + int mini = INT_MAX; + for (int i = start; i <= end; ++i) { + int leftRange = dp[start][i - 1]; + int rightRange = dp[i + 1][end]; + int cost = i + max(leftRange, rightRange); + mini = min(mini, cost); + } + dp[start][end] = mini; + } + } + return dp[1][n]; + } +}; +``` + +### Python Code + +```python +class Solution: + def getMoneyAmount(self, n: int) -> int: + dp = [[0] * (n + 2) for _ in range(n + 2)] + + for start in range(n, 0, -1): + for end in range(start + 1, n + 1): + mini = float('inf') + for i in range(start, end + 1): + leftRange = dp[start][i - 1] + rightRange = dp[i + 1][end] + cost = i + max(leftRange, rightRange) + mini = min(mini, cost) + dp[start][end] = mini + + return dp[1][n] +``` + +### Java Code + +```java +class Solution { + public int getMoneyAmount(int n) { + int[][] dp = new int[n + 2][n + 2]; + + for (int start = n; start >= 1; start--) { + for (int end = start + 1; end <= n; end++) { + int mini = Integer.MAX_VALUE; + for (int i = start; i <= end; i++) { + int leftRange = dp[start][i - 1]; + int rightRange = dp[i + 1][end]; + int cost = i + Math.max(leftRange, rightRange); + mini = Math.min(mini, cost); + } + dp[start][end] = mini; + } + } + return dp[1][n]; + } +} +``` + +### JavaScript Code + +```javascript +var getMoneyAmount = function (n) { + const dp = Array.from({ length: n + 2 }, () => Array(n + 2).fill(0)); + + for (let start = n; start >= 1; start--) { + for (let end = start + 1; end <= n; end++) { + let mini = Infinity; + for (let i = start; i <= end; i++) { + let leftRange = dp[start][i - 1]; + let rightRange = dp[i + 1][end]; + let cost = i + Math.max(leftRange, rightRange); + mini = Math.min(mini, cost); + } + dp[start][end] = mini; + } + } + return dp[1][n]; +}; +``` diff --git a/solutions/lc-solutions/0300-0399/0376-wiggle-subsequence.md b/solutions/lc-solutions/0300-0399/0376-wiggle-subsequence.md new file mode 100644 index 0000000..053c027 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0376-wiggle-subsequence.md @@ -0,0 +1,139 @@ +--- +id: wiggle-subsequence +title: Wiggle Subsequence +sidebar_label: 0376 - Wiggle Subsequence +tags: + - DP + - Leet code +description: "Solution to leetocde 376" +--- + +### Problem Description + +You are given an integer array `nums`. A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. + +For example: + +- `[1, 7, 4, 9, 2, 5]` is a wiggle sequence because the differences `(6, -3, 5, -7, 3)` alternate between positive and negative. +- `[1, 4, 7, 2, 5]` is not a wiggle sequence because its first two differences are positive. +- `[1, 7, 4, 5, 5]` is not a wiggle sequence because its last difference is zero. + +A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. + +Given an integer array `nums`, return the length of the longest wiggle subsequence of `nums`. + +### Example 1: + +- Input: `nums = [1,7,4,9,2,5]` +- Output: `6` +- Explanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3). + +### Example 2: + +- Input: `nums = [1,17,5,10,13,15,10,5,16,8]` +- Output: `7` +- Explanation: One possible subsequence is `[1, 17, 10, 13, 10, 16, 8]` with differences (16, -7, 3, -3, 6, -8). + +### Example 3: + +- Input: `nums = [1,2,3,4,5,6,7,8,9]` +- Output: `2` +- Explanation: The longest wiggle subsequence is `[1, 2]` or `[9, 8]`. + +### Constraints: + +- `1 <= nums.length <= 1000` +- `0 <= nums[i] <= 1000` + +### Algorithm Explanation + +1. **Initialization**: + + - Initialize two variables, `peak` and `valley`, to 1. These will keep track of the lengths of the longest wiggle sequences that end in a peak or a valley, respectively. + +2. **Traversal**: + + - Traverse through the list of numbers starting from the second element. + - If the current number is greater than the previous number, it contributes to a peak. Update `peak` to `valley + 1`. + - If the current number is less than the previous number, it contributes to a valley. Update `valley` to `peak + 1`. + +3. **Result**: + - The maximum value of `peak` and `valley` will give the length of the longest wiggle subsequence. + +### C++ Code + +```cpp +class Solution { +public: + int wiggleMaxLength(vector& nums) { + int size = nums.size(), peak = 1, valley = 1; + for(int i = 1; i < size; ++i) { + if (nums[i] > nums[i - 1]) + peak = valley + 1; + else if (nums[i] < nums[i - 1]) + valley = peak + 1; + } + return max(peak, valley); + } +}; +``` + +### Python Code + +```python +class Solution: + def wiggleMaxLength(self, nums: List[int]) -> int: + size = len(nums) + if size < 2: + return size + + peak = valley = 1 + for i in range(1, size): + if nums[i] > nums[i - 1]: + peak = valley + 1 + elif nums[i] < nums[i - 1]: + valley = peak + 1 + + return max(peak, valley) +``` + +### Java Code + +```java +class Solution { + public int wiggleMaxLength(int[] nums) { + int size = nums.length; + if (size < 2) return size; + + int peak = 1, valley = 1; + for (int i = 1; i < size; i++) { + if (nums[i] > nums[i - 1]) { + peak = valley + 1; + } else if (nums[i] < nums[i - 1]) { + valley = peak + 1; + } + } + return Math.max(peak, valley); + } +} +``` + +### JavaScript Code + +```javascript +var wiggleMaxLength = function (nums) { + let size = nums.length; + if (size < 2) return size; + + let peak = 1, + valley = 1; + for (let i = 1; i < size; i++) { + if (nums[i] > nums[i - 1]) { + peak = valley + 1; + } else if (nums[i] < nums[i - 1]) { + valley = peak + 1; + } + } + return Math.max(peak, valley); +}; +``` diff --git a/solutions/lc-solutions/0300-0399/0380-insert-delete-getrandom-o1.md b/solutions/lc-solutions/0300-0399/0380-insert-delete-getrandom-o1.md new file mode 100644 index 0000000..70d8b7d --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0380-insert-delete-getrandom-o1.md @@ -0,0 +1,126 @@ +--- +id: insert-delete-getrandom-o1 +title: 380. Insert Delete GetRandom O(1) +sidebar_label: 0380-insert-delete-getrandom-o1 +description: "Solution to leetocde 380" +--- + +The most common use cases of Insert Delete GetRandom O(1) are as follows: + +**Caching**: Caching is a way to store frequently accessed data in a temporary location so that it can be accessed quickly. For example, a web browser might cache recently visited websites so that they can load faster the next time you visit them. Insert Delete GetRandom O(1) can be used to implement a cache data structure that allows you to quickly insert, delete, and retrieve cached items. + +**In-memory databases**: In-memory databases are databases that store data in main memory instead of on disk. This makes them much faster than traditional databases, but it also means that they can only store a limited amount of data. Insert Delete GetRandom O(1) can be used to implement an in-memory database that allows you to quickly insert, delete, and retrieve data. + +**Random sampling**: Random sampling is the process of selecting a random subset of a population. This is useful for a variety of tasks, such as getting a representative sample of public opinion or conducting a scientific experiment. Insert Delete GetRandom O(1) can be used to implement a random sampling algorithm that allows you to quickly select a random subset of data. + +**Load balancing**: Load balancing is the process of distributing traffic across multiple servers to improve performance and reliability. Insert Delete GetRandom O(1) can be used to implement a load balancer that assigns incoming requests to servers in a random order. + +**Shuffle**: Shuffling is the process of arranging a set of items in a random order. This is useful for a variety of tasks, such as shuffling a deck of cards or creating a random playlist of songs. Insert Delete GetRandom O(1) can be used to implement a shuffling algorithm that allows you to quickly shuffle a set of items. + +Here are some specific examples of real-world applications that use Insert Delete GetRandom O(1): + +- Google search: Google uses Insert Delete GetRandom O(1) to implement its search index. This allows Google to quickly insert, delete, and retrieve web pages from its index, which is essential for providing fast and accurate search results. +- Facebook newsfeed: Facebook uses Insert Delete GetRandom O(1) to implement its newsfeed. This allows Facebook to quickly show you stories from your friends and family, even if they have a large number of friends. +- Twitter timeline: Twitter uses Insert Delete GetRandom O(1) to implement its timeline. This allows Twitter to quickly show you tweets from the people you follow, even if they tweet frequently. +- Netflix recommendations: Netflix uses Insert Delete GetRandom O(1) to implement its recommendation system. This allows Netflix to quickly recommend movies and TV shows that you are likely to enjoy, based on your viewing history. +- Spotify playlists: Spotify uses Insert Delete GetRandom O(1) to implement its playlists. This allows you to quickly add and remove songs from your playlists, and to shuffle your playlists in a random order. + +Overall, Insert Delete GetRandom O(1) is a versatile data structure that can be used to implement a wide variety of real-world applications. It is especially useful for applications that need to quickly insert, delete, and retrieve data, or that need to generate random samples of data. + +Approach: + +The order of elements is not important in the data structure. If we use an array as the data structure, insertion at the end will be in O(1) time but searching whether the element is already present in the array will take O(N) time. Removal of the element will require searching for the element which will take O(N) time and left shifting the subsequent array elements will also take O(N) time. Getting random element will take O(1) time using the rand() function. So, we need some additional data structure that allows us to locate the array index for removal and also to search whether the element is already present or not. This data structure should do these tasks in average O(1) time. Hashmap fulfils our requirements. + +Algorithm: + +Initialize two data structures: + +a: An array to store elements. +m: A map to associate elements with their indices in the array. +Insertion (insert method): + +Check if the value is already in the map (m). +If it's not in the map: +Add the value to the end of the array. +Store the value's index in the map (m). +Return true to indicate successful insertion. +If it's already in the map, return false. +Removal (remove method): + +Check if the value is in the map (m). +If it's not in the map, return false (the value is not in the data structure). +If it's in the map: +Get the index of the value to be removed. +Replace the value at that index with the last value in the array. +Remove the last element from the array. +Update the index of the last element in the map to the index of the removed element. +Remove the entry for the removed value from the map. +Return true to indicate successful removal. +Get a Random Element (getRandom method): + +Generate a random index within the range of valid indices in the array (from 0 to the size of the array minus 1). +Return the element at the randomly generated index. +The class allows you to insert elements, remove elements, and retrieve a random element, all with an average time complexity of O(1). + +Optimal Solution(C++) + +```cpp +class RandomizedSet { + // Average Time O(1) & Auxiliary Space O(N) +private: + vector a; // array vector + unordered_map m; // Unordered Map does searching, insertion & deletion of element in average O(1) time +public: + /** Initialize your data structure here. */ + RandomizedSet() { + // No need to initialise a & m as they are initialised automatically + // to 0 as and when their container size increases. + } + + /** Inserts a value to the array vector. Returns true if the array did not already contain the specified element. */ + bool insert(int val) { + if(m.find(val)!=m.end()) + // If val is not already present in the map, find() function + // returns an iterator(m.end()) pointing to the successive memory location + // from the last element of the map. Otherwise, find() returns an iterator + // pointing to val which was already present in the map. + return false; + else{ + a.push_back(val); // insert val at the end of the array + m[val]=a.size()-1; // unordered_map[key]=value stores the array element and + // its index as key=array element & value=array element index + return true; + } + } + + /** Removes a value from the array vector. Returns true if the array contained the specified element. */ + bool remove(int val) { + if(m.find(val)==m.end()) // val not present in the array vector + return false; + else{ + // val present in the array vector + // For example: a=[8,4,3,2], m={[8,0],[4,1],[3,2],[2,3]}, val=4, last=2 + // After a[m[val]]=a.back(); a=[8,2,3,2], m={[8,0],[4,1],[3,2],[2,3]} + // After a.pop_back(); a=[8,2,3], m={[8,0],[4,1],[3,2],[2,3]} + // After m[last]=m[val]; a=[8,2,3], m={[8,0],[4,1],[3,2],[2,1]} + // After m.erase(val); a=[8,2,3], m={[8,0],[3,2],[2,1]} + int last=a.back(); // back() fetches last element of the array vector + a[m[val]]=a.back(); // m[val] locates the index of val in the array vector. + // Then we copy array last element value to the val location in the array + a.pop_back(); // Delete the last element of the array + m[last]=m[val]; // In hashmap, assign index of val in array to the index of the last element + m.erase(val); // Delete the val entry from map + return true; + } + } + + /** Get a random element from the array vector */ + int getRandom() { + // rand() function gives random value in the range of 0 to RAND_MAX(whose value is 32767). x%y gives + // remainder when x is divided by y and this remainder is in the range of 0 to y-1. + // rand()%a.size() gives random value in the range of (0 to a.size()-1). + // a[rand()%a.size()] will give random value of array in the range of a[0] to a[a.size()-1]. + return a[rand()%a.size()]; + } +}; +``` diff --git a/solutions/lc-solutions/0300-0399/0382-linked-list-random-node.md b/solutions/lc-solutions/0300-0399/0382-linked-list-random-node.md new file mode 100644 index 0000000..f4ea6e4 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0382-linked-list-random-node.md @@ -0,0 +1,231 @@ +--- +id: linked-list-random-node +title: Linked List Random Node +sidebar_label: 0382-Linked List Random Node +tags: + - Linked List + - Leet code +description: "Solution to leetocde 382" +--- + +### Problem Description + +Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. + +Implement the Solution class: + +Solution(ListNode head) Initializes the object with the head of the singly-linked list head. +int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen. + +### Example 1: + +``` +Input +["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"] +[[[1, 2, 3]], [], [], [], [], []] +Output +[null, 1, 3, 2, 2, 3] +``` + +Explanation: + +``` +Solution solution = new Solution([1, 2, 3]); +solution.getRandom(); // return 1 +solution.getRandom(); // return 3 +solution.getRandom(); // return 2 +solution.getRandom(); // return 2 +solution.getRandom(); // return 3 +// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. +``` + +### Constraints: + +- The number of nodes in the linked list will be in the range $[1, 104].$ +- $-104 <= Node.val <= 104$ +- At most `10^4` calls will be made to getRandom. + +### Follow up: + +- What if the linked list is extremely large and its length is unknown to you? +- Could you solve this efficiently without using extra space? + +### Algorithm + +The `Solution` class is designed to choose a random node's value from a linked list. Here is a high-level overview of the algorithm used in the class: + +1. **Initialization:** + + - Store the head of the linked list. + - Compute the size of the linked list. + +2. **Compute the Length (`len` method):** + + - Traverse the linked list from the head to the end. + - Count the number of nodes. + +3. **Get Random Node Value (`getRandom` method):** + - Generate a random number within the range of the linked list size. + - Traverse the linked list to the node at the position of the generated random number. + - Return the value of that node. + +### C++ Code + +```cpp +#include // for rand() + +// Definition for singly-linked list. +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +private: + ListNode *head; + int size; + + int len(ListNode* head) { + ListNode* mover = head; + int n = 0; + while (mover) { + n++; + mover = mover->next; + } + return n; + } + +public: + Solution(ListNode* head) { + this->head = head; + size = len(head); + } + + int getRandom() { + int move = rand() % size; + ListNode* mover = head; + while (move) { + mover = mover->next; + move--; + } + return mover->val; + } +}; +``` + +### Python Code + +```python +import random + +# Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +class Solution: + def __init__(self, head: ListNode): + self.head = head + self.size = self.len(head) + + def len(self, head: ListNode) -> int: + mover = head + n = 0 + while mover: + n += 1 + mover = mover.next + return n + + def getRandom(self) -> int: + move = random.randint(0, self.size - 1) + mover = self.head + while move: + mover = mover.next + move -= 1 + return mover.val +``` + +### Java Code + +```java +import java.util.Random; + +// Definition for singly-linked list. +class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; next = null; } +} + +class Solution { + private ListNode head; + private int size; + private Random random; + + public Solution(ListNode head) { + this.head = head; + this.size = len(head); + this.random = new Random(); + } + + private int len(ListNode head) { + ListNode mover = head; + int n = 0; + while (mover != null) { + n++; + mover = mover.next; + } + return n; + } + + public int getRandom() { + int move = random.nextInt(size); + ListNode mover = head; + while (move > 0) { + mover = mover.next; + move--; + } + return mover.val; + } +} +``` + +### JavaScript Code + +```javascript +// Definition for singly-linked list. +function ListNode(val) { + this.val = val; + this.next = null; +} + +class Solution { + constructor(head) { + this.head = head; + this.size = this.len(head); + } + + len(head) { + let mover = head; + let n = 0; + while (mover !== null) { + n++; + mover = mover.next; + } + return n; + } + + getRandom() { + const move = Math.floor(Math.random() * this.size); + let mover = this.head; + let steps = move; + while (steps > 0) { + mover = mover.next; + steps--; + } + return mover.val; + } +} +``` diff --git a/solutions/lc-solutions/0300-0399/0383-ransom-note.md b/solutions/lc-solutions/0300-0399/0383-ransom-note.md new file mode 100644 index 0000000..753b7f3 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0383-ransom-note.md @@ -0,0 +1,133 @@ +--- +id: ransome-note +title: Ransom Note +sidebar_label: 0383-Ransom Note +tags: + - Leet code +description: "Solution to leetocde 383" +--- + +### Problem Description + +Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise. + +Each letter in magazine can only be used once in ransomNote. + +### Examples + +Example 1: + +``` +Input: ransomNote = "a", magazine = "b" +Output: false +``` + +Example 2: + +``` +Input: ransomNote = "aa", magazine = "ab" +Output: false +``` + +Example 3: + +``` +Input: ransomNote = "aa", magazine = "aab" +Output: true +``` + +### Constraints: + +- $1 <= ransomNote.length, magazine.length <= 10^5$ +- ransomNote and magazine consist of lowercase English letters. + Alright, here's the breakdown of the code you provided, along with implementations in various languages: + +### Algorithm: + +1. **Initialize a frequency table:** The code creates an array `alpha` of size 26. This array will store the frequency of each letter in the magazine (`a` maps to index 0, `b` to index 1, and so on). +2. **Iterate through ransom note:** For each character `c` in the ransom note: + - Calculate the index `idx` using `ord(c) - ord('a')`. This converts the character `c` to its corresponding numerical position (e.g., 'a' becomes 0, 'b' becomes 1). + - Use `magazine.find(c, alpha[idx])` to find the first occurrence of `c` in the magazine starting from index `alpha[idx]`. This improves efficiency by avoiding redundant searches in the magazine. + - If `i` (the result of `find`) is -1, it means the character `c` is not found in the magazine. In this case, the function returns `False` as the ransom note cannot be formed. + - Update `alpha[idx]` with `i + 1` to track the last position where `c` was found in the magazine. This helps avoid revisiting the same characters in the magazine unnecessarily. +3. **Return True:** After iterating through the entire ransom note, if no characters were missing, the function returns `True`, indicating that the ransom note can be constructed from the magazine. + +**Code Implementations:** + +**Python:** + +```python +from collections import Counter + +class Solution: + def canConstruct(self, ransomNote: str, magazine: str) -> bool: + magazine_counter = Counter(magazine) + ransom_counter = Counter(ransomNote) + for char, count in ransom_counter.items(): + if char not in magazine_counter or magazine_counter[char] < count: + return False + return True +``` + +**C++:** + +```c++ +#include + +class Solution { +public: + bool canConstruct(std::string ransomNote, std::string magazine) { + std::unordered_map magazine_counter; + for (char c : magazine) { + magazine_counter[c]++; + } + for (char c : ransomNote) { + if (magazine_counter.find(c) == magazine_counter.end() || magazine_counter[c] == 0) { + return false; + } + magazine_counter[c]--; + } + return true; + } +}; +``` + +**Java:** + +```java +import java.util.HashMap; + +class Solution { + public boolean canConstruct(String ransomNote, String magazine) { + HashMap magazine_counter = new HashMap<>(); + for (char c : magazine.toCharArray()) { + magazine_counter.put(c, magazine_counter.getOrDefault(c, 0) + 1); + } + for (char c : ransomNote.toCharArray()) { + if (!magazine_counter.containsKey(c) || magazine_counter.get(c) == 0) { + return false; + } + magazine_counter.put(c, magazine_counter.get(c) - 1); + } + return true; + } +} +``` + +**JavaScript:** + +```javascript +function canConstruct(ransomNote, magazine) { + const magazine_counter = {}; + for (const char of magazine) { + magazine_counter[char] = (magazine_counter[char] || 0) + 1; + } + for (const char of ransomNote) { + if (!(char in magazine_counter) || magazine_counter[char] === 0) { + return false; + } + magazine_counter[char]--; + } + return true; +} +``` diff --git a/solutions/lc-solutions/0300-0399/0384-Shuffle-an-Array.md b/solutions/lc-solutions/0300-0399/0384-Shuffle-an-Array.md new file mode 100644 index 0000000..cecd44c --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0384-Shuffle-an-Array.md @@ -0,0 +1,139 @@ +--- +id: shuffle-an-array +title: Shuffle-an-Array +sidebar_label: 0384-Shuffle an Array +tags: + - Leet code +description: "Solution to leetocde 384" +--- + +### Problem Description + +Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling. + +Implement the Solution class: + +- `Solution(int[] nums)` Initializes the object with the integer array nums. +- `int[] reset()` Resets the array to its original configuration and returns it. +- `int[] shuffle()` Returns a random shuffling of the array. + +Example 1: + +``` +Input +["Solution", "shuffle", "reset", "shuffle"] +[[[1, 2, 3]], [], [], []] +Output +[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]] + +Explanation +Solution solution = new Solution([1, 2, 3]); +solution.shuffle(); // Shuffle the array [1,2,3] and return its result. + // Any permutation of [1,2,3] must be equally likely to be returned. + // Example: return [3, 1, 2] +solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] +solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2] +``` + +### Constraints: + +- `1 <= nums.length <= 50` +- `-10^6 <= nums[i] <= 10^6` + +### Motive + +Our motive in this question is to find a random permutation of an array on demand. Now this random permutation should be trully random with a uniform probability distribution. +In other words, for any call to shuffle(), all permutations of the array should have equal probability of being returned. + +Let's try doing it by hand. We take the elements of the array in a bag and shuffle them, then for each position in the shuffled array, we draw one element from the bag, and put that element in that position, and so on, until the bag is empty. +We can simulate this exact process in our code by maintaining a copy of the original array and generating a random index of the array to put at each index. + +But the problem arises in the exclusion of the selected elements from the bag. We could do a normal array delete `(or shift)` and that would cost us `O(n)` in the worst case, making our time complexity $O(n^2)$, but we can do better. + + +### Code Implementation + +**Python:** + +```python +class Solution(object): + def __init__(self, nums): + self.reset = lambda: nums + self.shuffle = lambda: random.sample(nums, len(nums)) +``` + +**C++:** + +```c++ +class Solution { + vector original; + int n; +public: + + Solution(vector& nums) { + original = nums; + n = original.size(); + } + + vector reset() { + return original; + } + + vector shuffle() { + //make a copy of the original + vector shuffled = original; + + int leftSize = n; + for(int i = n-1; i>=0; i--) { + //draw from the bag + int j = rand()%leftSize; + + //put this element at current position + //and put the original element in the bag + swap(shuffled[i], shuffled[j]); + leftSize--; + } + return shuffled; + } + +}; +``` + +**Java:** + +```java +import java.util.Random; + +public class Solution { + private int[] nums; + private Random random; + + public Solution(int[] nums) { + this.nums = nums; + random = new Random(); + } + + /** Resets the array to its original configuration and return it. */ + public int[] reset() { + return nums; + } + + /** Returns a random shuffling of the array. */ + public int[] shuffle() { + if(nums == null) return null; + int[] a = nums.clone(); + for(int j = 1; j < a.length; j++) { + int i = random.nextInt(j + 1); + swap(a, i, j); + } + return a; + } + + private void swap(int[] a, int i, int j) { + int t = a[i]; + a[i] = a[j]; + a[j] = t; + } +} +``` + diff --git a/solutions/lc-solutions/0300-0399/0385-Mini-Parser.md b/solutions/lc-solutions/0300-0399/0385-Mini-Parser.md new file mode 100644 index 0000000..5a0e22c --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0385-Mini-Parser.md @@ -0,0 +1,179 @@ +--- +id: mini-parser +title: Mini Parser +sidebar_label: 0385 - Mini Parser +tags: + - String + - Stack + - Depth First Search +description: "This is a solution to the Mini Parser problem on LeetCode." +--- + +## Problem Description + +Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized `NestedInteger`. + +Each element is either an integer or a list whose elements may also be integers or other lists. + +### Examples + +**Example 1:** + +``` +Input: s = "324" +Output: 324 +Explanation: You should return a NestedInteger object which contains a single integer 324. + +``` +**Example 2:** +``` + +Input: s = "[123,[456,[789]]]" +Output: [123,[456,[789]]] +Explanation: Return a NestedInteger object containing a nested list with 2 elements: +1. An integer containing value 123. +2. A nested list containing two elements: + i. An integer containing value 456. + ii. A nested list with one element: + a. An integer containing value 789 + +``` +### Constraints + +- `1 <= s.length <= 5 * 10^4` +- `s is the serialization of valid NestedInteger` +- `All the values in the input are in the range [-10^6, 10^6]` + +## Solution for Mini Parser + +### Approach + +This solution uses a stack to record the `NestedInteger`'s. +At the very beginning, an empty NestedInteger is placed in the stack. This NestedInteger will be regarded as a list that holds one but only one NestedInteger, which will be returned in the end. +`Logic: When encountering '[', the stack has one more element. When encountering ']', the stack has one less element`. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + NestedInteger deserialize(string s) { + function isnumber = [](char c){ return (c == '-') || isdigit(c); }; + + stack stk; + stk.push(NestedInteger()); + + for (auto it = s.begin(); it != s.end();) { + const char & c = (*it); + if (isnumber(c)) { + auto it2 = find_if_not(it, s.end(), isnumber); + int val = stoi(string(it, it2)); + stk.top().add(NestedInteger(val)); + it = it2; + } + else { + if (c == '[') { + stk.push(NestedInteger()); + } + else if (c == ']') { + NestedInteger ni = stk.top(); + stk.pop(); + stk.top().add(ni); + } + ++it; + } + } + + NestedInteger result = stk.top().getList().front(); + return result; + } +}; +``` + + + + +```java +public NestedInteger deserialize(String s) { + if (s.isEmpty()) + return null; + if (s.charAt(0) != '[') // ERROR: special case + return new NestedInteger(Integer.valueOf(s)); + + Stack stack = new Stack<>(); + NestedInteger curr = null; + int l = 0; // l shall point to the start of a number substring; + // r shall point to the end+1 of a number substring + for (int r = 0; r < s.length(); r++) { + char ch = s.charAt(r); + if (ch == '[') { + if (curr != null) { + stack.push(curr); + } + curr = new NestedInteger(); + l = r+1; + } else if (ch == ']') { + String num = s.substring(l, r); + if (!num.isEmpty()) + curr.add(new NestedInteger(Integer.valueOf(num))); + if (!stack.isEmpty()) { + NestedInteger pop = stack.pop(); + pop.add(curr); + curr = pop; + } + l = r+1; + } else if (ch == ',') { + if (s.charAt(r-1) != ']') { + String num = s.substring(l, r); + curr.add(new NestedInteger(Integer.valueOf(num))); + } + l = r+1; + } + } + + return curr; +} +``` + + + + + +```python +class Solution: + def deserialize(self, s): + stack, num, last = [], "", None + for c in s: + if c.isdigit() or c == "-": num += c + elif c == "," and num: + stack[-1].add(NestedInteger(int(num))) + num = "" + elif c == "[": + elem = NestedInteger() + if stack: stack[-1].add(elem) + stack.append(elem) + elif c == "]": + if num: + stack[-1].add(NestedInteger(int(num))) + num = "" + last = stack.pop() + return last if last else NestedInteger(int(num)) +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +### Space Complexity: $O(N)$ + +## References + +- **LeetCode Problem**: [Kth Largest Element in a Stream](https://leetcode.com/problems/mini-parser/description/) + +- **Solution Link**: [Kth Largest Element in a Stream](https://leetcode.com/problems/mini-parser/solutions/) diff --git a/solutions/lc-solutions/0300-0399/0386-Lexicographical-Numbers.md b/solutions/lc-solutions/0300-0399/0386-Lexicographical-Numbers.md new file mode 100644 index 0000000..020d1c9 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0386-Lexicographical-Numbers.md @@ -0,0 +1,107 @@ +--- +id: lexicographical-numbers +title: Lexicographical-Numbers +sidebar_label: 0389-Lexicographical-Numbers +tags: + - Leet code +description: "Solution to leetocde 386" +--- + +### Problem Description + +Given an integer `n`, return all the numbers in the range `[1, n]` sorted in lexicographical order. + +You must write an algorithm that runs in $O(n)$ time and uses $O(1)$ extra space. + +Example 1: + +``` +Input: n = 13 +Output: [1,10,11,12,13,2,3,4,5,6,7,8,9] + +``` + +Example 2: + +``` +Input: n = 2 +Output: [1,2] + +``` + +### Constraints: + +- `1 <= n <= 5 * 10^4` + +### Algorithm + +The basic idea is to find the next number to add. +Take 45 for example: if the current number is 45, the next one will be `450 (450 == 45 * 10)(if 450 <= n)`, or `46 (46 == 45 + 1) (if 46 <= n)` or `5 (5 == 45 / 10 + 1)`(5 is less than 45 so it is for sure less than n). +We should also consider `n = 600`, and the current number = 499, the next number is `5` because there are all "9"s after "4" in `"499"` so we should divide `499 by 10` until the last digit is not `"9"`. +It is like a tree, and we are easy to get a sibling, a left most child and the parent of any node. + +### Code Implementation + +**Python:** + +```python +def lexicalOrder(self, n): + top = 1 + while top * 10 <= n: + top *= 10 + def mycmp(a, b, top=top): + while a < top: a *= 10 + while b < top: b *= 10 + return -1 if a < b else b < a + return sorted(xrange(1, n+1), mycmp) + +``` + +**C++:** + +```c++ +class Solution { +public: + vector lexicalOrder(int n) { + vector res(n); + int cur = 1; + for (int i = 0; i < n; i++) { + res[i] = cur; + if (cur * 10 <= n) { + cur *= 10; + } else { + if (cur >= n) + cur /= 10; + cur += 1; + while (cur % 10 == 0) + cur /= 10; + } + } + return res; + } +}; +``` + +**Java:** + +```java +public List lexicalOrder(int n) { + List list = new ArrayList<>(n); + int curr = 1; + for (int i = 1; i <= n; i++) { + list.add(curr); + if (curr * 10 <= n) { + curr *= 10; + } else if (curr % 10 != 9 && curr + 1 <= n) { + curr++; + } else { + while ((curr / 10) % 10 == 9) { + curr /= 10; + } + curr = curr / 10 + 1; + } + } + return list; + } +``` + diff --git a/solutions/lc-solutions/0300-0399/0387-first-unique-character-in-a-string.md b/solutions/lc-solutions/0300-0399/0387-first-unique-character-in-a-string.md new file mode 100644 index 0000000..a02b46d --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0387-first-unique-character-in-a-string.md @@ -0,0 +1,132 @@ +--- +id: first unique character in a string +title: First Unique Character in a String +sidebar_label: 0387-First Unique Character in a String +tags: + - HashTable + - String + - Queue + - Counting +description: "This is a solution to the first unique character in a string in leetcode" +--- + +## Problem Description + +Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1. + + + +### Examples + +**Example 1:** + +``` +Input: s = "leetcode" +Output: 0 +``` +**Example 2:** +``` +Input: s = "loveleetcode" +Output: 2 + ``` +## Complexity Analysis + +*** Time Complexity:** $O(n)$ + +*** Space Complexity:** $O(n)$ + +### Constraints + +- `1 <= s.length <= 105` +- `s`consists of only lowercase English letters. + + + +### Solution +## Approach +To solve the problem of finding the first unique character in a string, we need to implement a strategy that efficiently counts character occurrences and identifies the first non-repeating character. The process begins by initializing a data structure to keep track of character counts. This could be a dictionary in Python, an array in Java, or an unordered_map in C++. The first step involves iterating through the string to populate this data structure with the count of each character. For each character encountered, we either increment its count if it already exists in the data structure or add it with an initial count of one. After constructing the character count data structure, we proceed to identify the first unique character. This requires a second iteration through the string, during which we check each character's count in the data structure. The first character with a count of one is our answer, and we return its index. If the entire string is processed without finding a unique character, we return -1 to indicate that no such character exists. This approach ensures that the solution is both efficient and straightforward, utilizing two passes through the stringβ€”one for counting and one for finding the first unique character. + +## Code in Different Languages + + + + + +```cpp +#include +#include + +class Solution { +public: + int firstUniqChar(std::string s) { + std::unordered_map charCount; + + for (char c : s) { + charCount[c]++; + } + + for (int i = 0; i < s.length(); i++) { + if (charCount[s[i]] == 1) { + return i; + } + } + + return -1; + } +}; + + +``` + + + + +```java +class Solution { + public int firstUniqChar(String s) { + + int[] count = new int[26]; + + for (char c : s.toCharArray()) { + count[c - 'a']++; + } + for (int i = 0; i < s.length(); i++) { + if (count[s.charAt(i) - 'a'] == 1) { + return i; + } + } + + return -1; + } +} + + +``` + + + + +```python +class Solution: + def firstUniqChar(self, s: str) -> int: + dic={} + for i in s: + if i in dic: + dic[i]+=1 + else: + dic[i]=1 + for i in range(len(s)): + if dic[s[i]]==1: + return i + return -1 + + +``` + + + +## References + +- **LeetCode Problem**: [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/description/) + +- **Solution Link**: [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/post-solution/?submissionId=1183734593) diff --git a/solutions/lc-solutions/0300-0399/0389-find-the-difference.md b/solutions/lc-solutions/0300-0399/0389-find-the-difference.md new file mode 100644 index 0000000..b805f81 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0389-find-the-difference.md @@ -0,0 +1,111 @@ +--- +id: find-the-difference +title: Find the Difference +sidebar_label: 0389-Find the Difference +tags: + - Leet code +description: "Solution to leetocde 389" +--- + +### Problem Description + +You are given two strings s and t. + +String t is generated by random shuffling string s and then add one more letter at a random position. + +Return the letter that was added to t. + +Example 1: + +``` +Input: s = "abcd", t = "abcde" +Output: "e" +Explanation: 'e' is the letter that was added. +``` + +Example 2: + +``` +Input: s = "", t = "y" +Output: "y" +``` + +### Constraints: + +- $0 <= s.length <= 1000$ +- $t.length == s.length + 1$ +- $s and t consist of lowercase English letters.$ + +### Algorithm + +1. For each character i in t, it checks if the count of i in t is greater than the count of i in s. If this condition is met, it means that i is the extra letter that was added to t, so it returns i and breaks out of the loop. + +### Code Implementation + +**Python:** + +```python +class Solution(object): + def findTheDifference(self, s, t): + for char in t: + if t.count(char) > s.count(char): + return char +``` + +**C++:** + +```c++ +#include + +char findTheDifference(std::string s, std::string t) { + std::unordered_map char_counts; + for (char c : s) { + char_counts[c]++; + } + for (char c : t) { + if (char_counts.find(c) == char_counts.end() || char_counts[c] == 0) { + return c; + } + char_counts[c]--; + } + return '\0'; // Return null character if no difference found +} +``` + +**Java:** + +```java +public class Solution { + public char findTheDifference(String s, String t) { + HashMap char_counts = new HashMap<>(); + for (char c : s.toCharArray()) { + char_counts.put(c, char_counts.getOrDefault(c, 0) + 1); + } + for (char c : t.toCharArray()) { + if (!char_counts.containsKey(c) || char_counts.get(c) == 0) { + return c; + } + char_counts.put(c, char_counts.get(c) - 1); + } + return '\u0000'; // Return null character if no difference found (Unicode representation) + } +} +``` + +**JavaScript:** + +```javascript +function findTheDifference(s, t) { + const char_counts = {}; + for (const char of s) { + char_counts[char] = (char_counts[char] || 0) + 1; + } + for (const char of t) { + if (!(char in char_counts) || char_counts[char] === 0) { + return char; + } + char_counts[char]--; + } + return ""; // Return empty string if no difference found +} +``` diff --git a/solutions/lc-solutions/0300-0399/0392-is-subsequence.md b/solutions/lc-solutions/0300-0399/0392-is-subsequence.md new file mode 100644 index 0000000..0ab1ea1 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0392-is-subsequence.md @@ -0,0 +1,128 @@ +--- +id: is-subsequence +title: Is Subsequence +sidebar_label: 0392-Is Subsequence +tags: + - Two Pointers + - String + - Dynamic Programming +description: "This is a solution to Is Subsequence in leetcode " +--- + +## Problem Description + +Given two strings s and t, return true if s is a subsequence of t, or false otherwise. + +A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not). + + + +### Examples + +**Example 1:** + +``` +Input: s = "abc", t = "ahbgdc" +Output: true + +``` +**Example 2:** +``` +Input: s = "axc", t = "ahbgdc" +Output: false + + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(m+k*nlogm)$ + +*** Space Complexity:** $O(m)$ + +### Constraints + +- `0 <= s.length <= 100` +- `0 <= t.length <= 104` +- `s` and `t` consist only of lowercase English letters. + + +### Solution +## Approach +To check if 's' is a subsequence of 't', use a two-pointer approach where one pointer traverses 's' and the other traverses 't'. If all characters of 's' are found in order within 't', return 'true'; otherwise, return 'false'. For handling many such checks efficiently, preprocess 't' into a mapping of character positions to quickly locate characters and verify subsequences, which speeds up the process for large numbers of queries. + +## Code in Different Languages + + + + + +```cpp +#include + +class Solution { +public: + bool isSubsequence(std::string s, std::string t) { + int i = 0; + int j = 0; + + while (i < s.length() && j < t.length()) { + if (s[i] == t[j]) { + i++; + } + j++; } + + return i == s.length(); + } +}; + + + +``` + + + + +```java +class Solution { + public boolean isSubsequence(String s, String t) { + int i = 0; + int j = 0; + + while (i < s.length() && j < t.length()) { + if (s.charAt(i) == t.charAt(j)) { + i++; + } + j++; + } + + return i == s.length(); + } +} + +``` + + + + +```python +class Solution: + def isSubsequence(self, s: str, t: str) -> bool: + i=0 + j=0 + + while i + + +## References + +- **LeetCode Problem**: [Is Subsequence](https://leetcode.com/problems/is-subsequence/solutions/) + +- **Solution Link**: [Is Subsequence](https://leetcode.com/problems/is-subsequence/post-solution/?submissionId=1203193848) diff --git a/solutions/lc-solutions/0300-0399/0395-longest-substring-with-atleast-k-repeating-characters.md b/solutions/lc-solutions/0300-0399/0395-longest-substring-with-atleast-k-repeating-characters.md new file mode 100644 index 0000000..99bfd0b --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0395-longest-substring-with-atleast-k-repeating-characters.md @@ -0,0 +1,332 @@ +--- +id: longest-substring-with-atleast-k-repeating-characters +title: Longest Substring With Atleast K Repeating Characters +sidebar_label: 0395-Longest Substring With Atleast K Repeating Characters +tags: + - Leet code +description: "Solution to leetocde 395" +--- + +### Problem Description + +Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k. + +if no such substring exists, return 0. + +### Examples + +Example 1: + +``` +Input: s = "aaabb", k = 3 +Output: 3 +Explanation: The longest substring is "aaa", as 'a' is repeated 3 times. +``` + +Example 2: + +``` +Input: s = "ababbc", k = 2 +Output: 5 +Explanation: The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times. +``` + +### Constraints: + +- $1 <= s.length <= 10^4$ +- $s consists of only lowercase English letters.$ +- $1 <= k <= 10^5$ + +### Algorithm + +1. **Initialize:** + + - `ans`: stores the current maximum length of a valid substring + - `freq`: frequency array to store character counts (size 26 for lowercase letters) + - `n`: length of the string `s` + +2. **Count Character Frequencies:** + + - Iterate through `s` and update `freq[i]` for each character `s[i]`. + +3. **Iterate Over Unique Character Counts:** + + - Use a loop for `curr_unique` from 1 to the total number of unique characters (`unique`) found in step 2. + +4. **Reset for Each Unique Character Count:** + + - Reset `freq` array to 0 using `memset` (C/C++) or loop assignment (other languages). + - Initialize `start`, `end`, `cnt` (number of unique characters in the window), and `count_k` (number of characters with at least `k` repetitions) to 0. + +5. **Sliding Window Technique:** + + - Use a `while` loop until `end` reaches the end of the string `s`: + - **Expand Window:** + - If `cnt` is less than `curr_unique`: + - Increment `freq` for the character at `end`. + - If the character is a new unique character (frequency becomes 1), increment `cnt`. + - If the character's frequency becomes `k`, increment `count_k`. + - Increment `end`. + - **Shrink Window:** + - If `cnt` is equal to `curr_unique`: + - Decrement `freq` for the character at `start`. + - If the character's frequency becomes `k-1`, decrement `count_k`. + - If the character's frequency becomes 0, decrement `cnt`. + - Increment `start`. + +6. **Update Maximum Length:** + + - If `cnt` is equal to `curr_unique` and `count_k` is also equal to `curr_unique` (all characters in the window have at least `k` repetitions), update `ans` with the maximum of the current length (`end - start`). + +7. **Return Maximum Length:** + - Return the final value of `ans`, which represents the length of the longest valid substring. + +## Code Implementations: + +**Python:** + +```python +def longestSubstring(s: str, k: int) -> int: + ans = 0 + freq = [0] * 26 + + n = len(s) + + for i in range(n): + freq[ord(s[i]) - ord('a')] += 1 + + unique = sum(1 for count in freq if count > 0) + + for curr_unique in range(1, unique + 1): + memset(freq, 0, sizeof(freq)) # Replace with loop assignment for Python + start = end = cnt = count_k = 0 + + while end < n: + if cnt <= curr_unique: + ind = ord(s[end]) - ord('a') + if freq[ind] == 0: + cnt += 1 + freq[ind] += 1 + if freq[ind] == k: + count_k += 1 + end += 1 + else: + ind = ord(s[start]) - ord('a') + if freq[ind] == k: + count_k -= 1 + freq[ind] -= 1 + if freq[ind] == 0: + cnt -= 1 + start += 1 + + if cnt == curr_unique and count_k == curr_unique: + ans = max(ans, end - start) + + return ans +``` + +**C++:** + +```c++ +#include + +int longestSubstring(std::string s, int k) { + int ans = 0; + std::vector freq(26, 0); + int n = s.size(); + + // Count character frequencies + for (char c : s) { + freq[c - 'a']++; + } + + // Find the number of unique characters + int unique = 0; + for (int count : freq) { + if (count > 0) { + unique++; + } + } + + // Iterate over window sizes (1 to the number of unique characters) + for (int curr_unique = 1; curr_unique <= unique; curr_unique++) { + std::fill(freq.begin(), freq.end(), 0); // Reset frequencies for each window size + + int start = 0, end = 0, cnt = 0, count_k = 0; + + // Use a sliding window approach + while (end < n) { + if (cnt <= curr_unique) { + int ind = s[end] - 'a'; + + // Expand window + if (freq[ind] == 0) { + cnt++; + } + freq[ind]++; + if (freq[ind] == k) { + count_k++; + } + end++; + } else { + int ind = s[start] - 'a'; + + // Shrink window + if (freq[ind] == k) { + count_k--; + } + freq[ind]--; + if (freq[ind] == 0) { + cnt--; + } + start++; + } + + // Check for valid window + if (cnt == curr_unique && count_k == curr_unique) { + ans = max(ans, end - start); + } + } + } + + return ans; +} +``` + +**Java:** + +```java +public class Solution { + public int longestSubstring(String s, int k) { + int ans = 0; + int[] freq = new int[26]; + int n = s.length(); + + // Count character frequencies + for (char c : s.toCharArray()) { + freq[c - 'a']++; + } + + // Find the number of unique characters + int unique = 0; + for (int count : freq) { + if (count > 0) { + unique++; + } + } + + // Iterate over window sizes (1 to the number of unique characters) + for (int curr_unique = 1; curr_unique <= unique; curr_unique++) { + Arrays.fill(freq, 0); // Reset frequencies for each window size + + int start = 0, end = 0, cnt = 0, count_k = 0; + + // Use a sliding window approach + while (end < n) { + if (cnt <= curr_unique) { + int ind = s.charAt(end) - 'a'; + + // Expand window + if (freq[ind] == 0) { + cnt++; + } + freq[ind]++; + if (freq[ind] == k) { + count_k++; + } + end++; + } else { + int ind = s.charAt(start) - 'a'; + + // Shrink window + if (freq[ind] == k) { + count_k--; + } + freq[ind]--; + if (freq[ind] == 0) { + cnt--; + } + start++; + } + + // Check for valid window + if (cnt == curr_unique && count_k == curr_unique) { + ans = Math.max(ans, end - start); + } + } + } + + return ans; + } +} + +``` + +**JavaScript:** + +```javascript +function longestSubstring(s, k) { + let ans = 0; + const freq = new Array(26).fill(0); + const n = s.length; + + // Count character frequencies + for (const char of s) { + freq[char.charCodeAt(0) - "a".charCodeAt(0)]++; + } + + // Find the number of unique characters + let unique = 0; + for (const count of freq) { + if (count > 0) { + unique++; + } + } + + // Iterate over window sizes (1 to the number of unique characters) + for (let curr_unique = 1; curr_unique <= unique; curr_unique++) { + freq.fill(0); // Reset frequencies for each window size + + let start = 0, + end = 0, + cnt = 0, + count_k = 0; + + // Use a sliding window approach + while (end < n) { + if (cnt <= curr_unique) { + const ind = s.charCodeAt(end) - "a".charCodeAt(0); + + // Expand window + if (freq[ind] === 0) { + cnt++; + } + freq[ind]++; + if (freq[ind] === k) { + count_k++; + } + end++; + } else { + const ind = s.charCodeAt(start) - "a".charCodeAt(0); + + // Shrink window + if (freq[ind] === k) { + count_k--; + } + freq[ind]--; + if (freq[ind] === 0) { + cnt--; + } + start++; + } + + // Check for valid window + if (cnt === curr_unique && count_k === curr_unique) { + ans = Math.max(ans, end - start); + } + } + } + + return ans; +} +``` diff --git a/solutions/lc-solutions/0300-0399/0396-rotate-function.md b/solutions/lc-solutions/0300-0399/0396-rotate-function.md new file mode 100644 index 0000000..2d8865f --- /dev/null +++ b/solutions/lc-solutions/0300-0399/0396-rotate-function.md @@ -0,0 +1,149 @@ +--- +id: rotate-function +title: Rotate Function +sidebar_label: 0396 Rotate Function +tags: +- Array +- Math +- Dynamic Programming + +description: "Solution to Leetcode 396. Rotate Function." +--- + +## Problem Description + +You are given an integer array `nums` of length `n`. + +Assume `arrk` to be an array obtained by rotating nums by `k` positions clock-wise. We define the rotation function `F` on nums as follow: + +- `F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].` + +Return the maximum value of `F(0), F(1), ..., F(n-1).` + +The test cases are generated so that the answer fits in a **32-bit** integer. + + +### Examples + +**Example 1:** + +``` +Input: nums = [4,3,2,6] +Output: 26 +Explaination: +F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 +F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 +F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 +F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 +So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. +``` + +**Example 2:** + +``` +Input: nums = [100] +Output: 0 + +``` + +### Constraints +- `n == nums.length` +- `1 <= n <= 105` +- `-100 <= nums[i] <= 100` + +### Approach +First Calculate F(0) than update F(1) and F(2) with below equations and find max of all. + +F(1) - F(0) = S - n * A[n - 1] ---> F(1) = F(0) + S - n * A[n - 1] +F(2) - F(1) = S - n * A[n - 2] ---> F(2) = F(1) + S - n * A[n - 2] +F(3) - F(2) = S - n * A[n - 3] +Keep track of the maximum value of `F` across all rotations. + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp +class Solution { +public: + int maxRotateFunction(vector& nums) { + int F = 0; + int S = 0; + for(int i = 0; i < nums.size(); i++){ + F = F + (nums[i] * i); + S = S + nums[i]; + } + + int max_val = F; // this is F0 + int n = nums.size(); + + for(int i = n - 1; i >= 1 ; i--){ + F = F + S - n * nums[i]; + max_val = max(max_val , F); + } + return max_val; + } +}; + + ``` + +#### JAVA + +```java +class Solution { + public int maxRotateFunction(int[] nums) { + int F = 0; + int S = 0; + for(int i = 0; i < nums.length; i++){ + F = F + (nums[i] * i); + S = S + nums[i]; + } + + int max = F; // this is F0 + int n = nums.length; + + for(int i = n - 1; i >= 1 ; i--){ + F = F + S - n * nums[i]; + max = Math.max(max , F); + } + return max; + } +} +``` + +#### PYTHON + +```python +class Solution: + def maxRotateFunction(self, nums: List[int]) -> int: + F = 0 + S = 0 + for i in range(len(nums)): + F = F + (nums[i] * i) + S = S + nums[i] + + max_val = F # this is F0 + n = len(nums) + + for i in range(n - 1, 0, -1): + F = F + S - n * nums[i] + max_val = max(max_val, F) + + return max_val + +``` + + + +### Complexity Analysis + +- Time Complexity: $O(n)$ +- Reason: `n` is the number of elements in the nums array, due to its linear traversal to compute the initial values and subsequent rotations. + +- Space Complexity: $O(1)$ + +### References + +- **LeetCode Problem**: Rotate Function \ No newline at end of file diff --git a/solutions/lc-solutions/0300-0399/338-counting-bits.md b/solutions/lc-solutions/0300-0399/338-counting-bits.md new file mode 100644 index 0000000..f2c5b37 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/338-counting-bits.md @@ -0,0 +1,185 @@ +--- +id: counting-bits +title: Counting Bits +sidebar_label: 338-Counting Bits +tags: + - Arrays + - Bit Manipulation + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Counting Bits problem on LeetCode." +sidebar_position: 5 +--- + +## Problem Description + +Given an integer `n`, return an array `ans` of length `n + 1` such that for each `i` (0 <= `i` <= `n`), `ans[i]` is the number of `1`s in the binary representation of `i`. + +### Examples + +**Example 1:** + +``` +Input: n = 2 +Output: [0, 1, 1] +Explanation: +0 --> 0 +1 --> 1 +2 --> 10 +``` + +**Example 2:** + +``` +Input: n = 5 +Output: [0, 1, 1, 2, 1, 2] +Explanation: +0 --> 0 +1 --> 1 +2 --> 10 +3 --> 11 +4 --> 100 +5 --> 101 +``` + +### Constraints + +- `0 <= n <= 10^5` + +### Follow-up + +- Can you solve it in linear time `O(n)` and possibly in a single pass? +- Can you solve it without using any built-in function (i.e., like `__builtin_popcount` in C++)? + +--- + +## Solution for Counting Bits Problem + +### Approach 1: Brute Force (Naive) + +The brute force approach involves iterating through each number from `0` to `n`, converting each number to its binary form, and counting the number of `1`s in that binary representation. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector countBits(int n) { + vector ans(n + 1); + for (int i = 0; i <= n; ++i) { + ans[i] = __builtin_popcount(i); + } + return ans; + } +}; +``` + + + + + +```java +class Solution { + public int[] countBits(int n) { + int[] ans = new int[n + 1]; + for (int i = 0; i <= n; ++i) { + ans[i] = Integer.bitCount(i); + } + return ans; + } +} +``` + + + + + +```python +class Solution: + def countBits(self, n: int) -> List[int]: + return [bin(i).count('1') for i in range(n + 1)] +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(nlogn)$, as converting a number to binary and counting bits takes $O(\log n)$ time, and we do this for each number from `0` to `n`. +- **Space Complexity**: $O(n)$, for storing the result array. + +### Approach 2: Optimized Dynamic Programming + +To achieve a linear time solution, we can use a dynamic programming approach. We use the property that the number of `1`s in `i` can be derived from the number of `1`s in `i >> 1` (i.e., `i` divided by `2`) plus `1` if the last bit of `i` is `1`. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector countBits(int n) { + vector ans(n + 1); + for (int i = 1; i <= n; ++i) { + ans[i] = ans[i >> 1] + (i & 1); + } + return ans; + } +}; +``` + + + + + +```java +class Solution { + public int[] countBits(int n) { + int[] ans = new int[n + 1]; + for (int i = 1; i <= n; ++i) { + ans[i] = ans[i >> 1] + (i & 1); + } + return ans; + } +} +``` + + + + + +```python +class Solution: + def countBits(self, n: int) -> List[int]: + ans = [0] * (n + 1) + for i in range(1, n + 1): + ans[i] = ans[i >> 1] + (i & 1) + return ans +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(n)$, as we calculate the number of bits for each number from `0` to `n` in constant time. +- **Space Complexity**: $O(n)$, for storing the result array. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/0300-0399/_category_.json b/solutions/lc-solutions/0300-0399/_category_.json new file mode 100644 index 0000000..f73fef1 --- /dev/null +++ b/solutions/lc-solutions/0300-0399/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "0300-0399", + "position": 5, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (0300 - 0399)" + } +} diff --git a/solutions/lc-solutions/0400-0499/0401-binary-watch.md b/solutions/lc-solutions/0400-0499/0401-binary-watch.md new file mode 100644 index 0000000..4582819 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0401-binary-watch.md @@ -0,0 +1,138 @@ +--- +id: binary-watch +title: Binary Watch +sidebar_label: 401-Binary Watch +tags: + - Backtracking + - Bit Manipulation + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Binary Watch problem on LeetCode." +sidebar_position: 3 +--- + +## Problem Description + +A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. + +Given an integer `turnedOn` which represents the number of LEDs that are currently on (ignoring the PM), return all possible times the watch could represent. You may return the answer in any order. + +The hour must not contain a leading zero. + +For example, "01:00" is not valid. It should be "1:00". +The minute must consist of two digits and may contain a leading zero. + +For example, "10:2" is not valid. It should be "10:02". + +### Examples + +**Example 1:** + +``` +Input: turnedOn = 1 +Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"] +``` + +**Example 2:** + +``` +Input: turnedOn = 9 +Output: [] +``` + +### Constraints + +- `0 <= turnedOn <= 10` + +--- + +## Solution for Binary Watch Problem + +### Approach: Bit Manipulation and Backtracking + +The problem can be solved using bit manipulation and backtracking. We iterate through all possible hour and minute values, count the number of `1`s in their binary representations, and check if it matches the number of LEDs turned on. + +#### Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +public: + std::vector readBinaryWatch(int turnedOn) { + std::vector times; + for (int h = 0; h < 12; ++h) { + for (int m = 0; m < 60; ++m) { + if (std::bitset<10>((h << 6) + m).count() == turnedOn) { + times.push_back(std::to_string(h) + (m < 10 ? ":0" : ":") + std::to_string(m)); + } + } + } + return times; + } +}; +``` + + + + + +```java +import java.util.ArrayList; +import java.util.List; + +class Solution { + public List readBinaryWatch(int turnedOn) { + List times = new ArrayList<>(); + for (int h = 0; h < 12; h++) { + for (int m = 0; m < 60; m++) { + if (Integer.bitCount((h << 6) + m) == turnedOn) { + times.add(String.format("%d:%02d", h, m)); + } + } + } + return times; + } +} +``` + + + + + +```python +class Solution: + def readBinaryWatch(self, turnedOn: int) -> List[str]: + times = [] + for h in range(12): + for m in range(60): + if bin(h).count('1') + bin(m).count('1') == turnedOn: + times.append(f"{h}:{m:02d}") + return times +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(1)$, since the number of possible combinations (12 hours * 60 minutes) is constant. +- **Space Complexity**: $O(1)$, not counting the space required for the output list. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0402-Remove-K-Digits.md b/solutions/lc-solutions/0400-0499/0402-Remove-K-Digits.md new file mode 100644 index 0000000..b88c4db --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0402-Remove-K-Digits.md @@ -0,0 +1,161 @@ +--- +id: remove-k-digits +title: Remove K Digits (LeetCode) +sidebar_label: 0402-RemoveKDigits +description: Find the smallest possible number by removing K digits from the given number. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Remove K Digits](https://leetcode.com/problems/remove-k-digits/) | [Remove K Digits Solution on LeetCode](https://leetcode.com/problems/remove-k-digits/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +Given a string `num` representing a non-negative integer and an integer `k`, return the smallest possible number you can get by removing `k` digits from `num`. + +**Example:** + +#### Example 1 + +- **Input:** `num = "1432219"`, `k = 3` +- **Output:** `"1219"` +- **Explanation:** Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. + +#### Example 2 + +- **Input:** `num = "10200"`, `k = 1` +- **Output:** `"200"` +- **Explanation:** Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. + +#### Example 3 + +- **Input:** `num = "10"`, `k = 2` +- **Output:** `"0"` +- **Explanation:** Remove all the digits from the number and it is left with nothing which is 0. + +### Constraints + +- `1 <= num.length <= 10^5` +- `num` consists of only digits. +- `num` does not have any leading zeros except for the zero itself. +- `1 <= k <= num.length` + +### Approach + +To solve this problem, we need to systematically remove digits to achieve the smallest possible number. Here's a step-by-step approach: + +1. **Initialization**: + - Use a stack to build the smallest possible number. + - Iterate through each digit in `num`. + +2. **Stack Operations**: + - For each digit, while the stack is not empty, and the top of the stack is greater than the current digit, and `k` is greater than 0, pop the stack (remove the top element). + - Push the current digit to the stack. + - Decrement `k` each time a digit is removed. + +3. **Remove Remaining Digits**: + - If there are still digits to remove (`k > 0`), remove them from the end of the stack. + +4. **Build the Result**: + - Convert the stack to a string. + - Remove leading zeros. + - If the result is empty, return "0". + +### Solution Code + +#### Python + +```python +class Solution: + def removeKdigits(self, num: str, k: int) -> str: + stack = [] + for digit in num: + while k > 0 and stack and stack[-1] > digit: + stack.pop() + k -= 1 + stack.append(digit) + + # Remove the remaining digits from the end if k > 0 + stack = stack[:-k] if k else stack + + # Build the result and remove leading zeros + result = ''.join(stack).lstrip('0') + + return result if result else "0" +``` + +#### Java +```java +import java.util.*; + +class Solution { + public String removeKdigits(String num, int k) { + Deque stack = new ArrayDeque<>(); + for (char digit : num.toCharArray()) { + while (k > 0 && !stack.isEmpty() && stack.peekLast() > digit) { + stack.removeLast(); + k--; + } + stack.addLast(digit); + } + + // Remove the remaining digits from the end if k > 0 + for (int i = 0; i < k; ++i) { + stack.removeLast(); + } + + // Build the result and remove leading zeros + StringBuilder result = new StringBuilder(); + boolean leadingZero = true; + for (char digit : stack) { + if (leadingZero && digit == '0') continue; + leadingZero = false; + result.append(digit); + } + + return result.length() == 0 ? "0" : result.toString(); + } +} +``` + +#### C++ +```c++ +#include +#include +using namespace std; + +class Solution { +public: + string removeKdigits(string num, int k) { + deque stack; + for (char digit : num) { + while (k > 0 && !stack.empty() && stack.back() > digit) { + stack.pop_back(); + k--; + } + stack.push_back(digit); + } + + // Remove the remaining digits from the end if k > 0 + for (int i = 0; i < k; ++i) { + stack.pop_back(); + } + + // Build the result and remove leading zeros + string result; + bool leadingZero = true; + for (char digit : stack) { + if (leadingZero && digit == '0') continue; + leadingZero = false; + result += digit; + } + + return result.empty() ? "0" : result; + } +}; +``` + +### Conclusion +The solution efficiently finds the smallest possible number by removing k digits using a stack-based approach. This approach ensures that we maintain the smallest possible number at each step, and handles edge cases like leading zeros and empty results effectively. \ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0404-sum-of-left-leaves.md b/solutions/lc-solutions/0400-0499/0404-sum-of-left-leaves.md new file mode 100644 index 0000000..3308f9c --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0404-sum-of-left-leaves.md @@ -0,0 +1,395 @@ +--- + +id: sum-of-left-leaves +title: Sum of Left Leaves +sidebar_label: 0404-Sum-of-Last-Leaves +tags: + - Simulation + - LeetCode + - Python + - JavaScript + - TypeScript + - Java + - C++ +description: "This is a solution to the Sum of Last Leaves problem on LeetCode." + +--- +In this page, we will solve the Sum of Left Leaves problem using Depth-First Search (DFS). We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +Given the `root` of a binary tree, return the sum of all left leaves. + +A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. + +### Examples + +**Example 1:** + +```plaintext +Input: root = [3,9,20,null,null,15,7] +Output: 24 +Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively. +``` + +**Example 2:** + +```plaintext +Input: root = [1] +Output: 0 +Explanation: There are no left leaves in the binary tree. The tree only has one node, which is the root node itself. Therefore, the sum of left leaves is 0. +``` + + +### Constraints + +- The number of nodes in the tree is in the range `[1, 1000]`. +- `1000 <= Node.val <= 1000` + +--- + +## Solution for Sum of Left Leaves + +### Intuition and Approach + +## Recursive DFS Traversal: + +- Traverse the tree starting from the root. +- For each node, check if it has a left child that is a leaf. If so, add the value of that leaf to the sum. +- Recursively traverse the left and right subtrees. + +## Base Case: + +- If the current node is `null`, return 0. + +## Leaf Check: + +- A node is a leaf if it has no left or right children. + + + + + +#### Implementation + +- Here's the implementation in multiple languages: + +```jsx live +function sumOfLeftLeaves(root) { + let sum = 0; + + function dfs(node) { + if (!node) return; + + if (node.left && !node.left.left && !node.left.right) { + sum += node.left.val; + } + + dfs(node.left); + dfs(node.right); + } + + dfs(root); + return sum; +} + +``` + +#### Code in Different Languages + + + + + ```javascript + function sumOfLeftLeaves(root) { + let sum = 0; + + function dfs(node) { + if (!node) return; + + if (node.left && !node.left.left && !node.left.right) { + sum += node.left.val; + } + + dfs(node.left); + dfs(node.right); + } + + dfs(root); + return sum; +} + + ``` + + + + + ```typescript + function dfs(node: TreeNode | null): void { + if (!node) return; + + if (node.left && !node.left.left && !node.left.right) { + sum += node.left.val; + } + + dfs(node.left); + dfs(node.right); + } + + dfs(root); + return sum; +} + ``` + + + + + ```python + class Solution: + self.sum = 0 + + def dfs(node): + if not node: + return + + if node.left and not node.left.left and not node.left.right: + self.sum += node.left.val + + dfs(node.left) + dfs(node.right) + + dfs(root) + return self.sum + ``` + + + + + ```java + class Solution { + public int sumOfLeftLeaves(TreeNode root) { + return dfs(root); + } + + private int dfs(TreeNode node) { + if (node == null) { + return 0; + } + + int sum = 0; + if (node.left != null && node.left.left == null && node.left.right == null) { + sum += node.left.val; + } + + sum += dfs(node.left); + sum += dfs(node.right); + + return sum; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + int sumOfLeftLeaves(TreeNode* root) { + if (!root) return 0; + int sum = 0; + dfs(root, sum); + return sum; + } + + void dfs(TreeNode* node, int& sum) { + if (!node) return; + + if (node->left && !node->left->left && !node->left->right) { + sum += node->left->val; + } + + dfs(node->left, sum); + dfs(node->right, sum); + } +}; + + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(L + R)$$, where `L` is the length of the `left` array and `R` is the length of the `right` array. +- Space Complexity: $$O(1)$$, as we are only using a few extra variables. + + + + + +### Approach 2: Simulation + +We can simulate the movement of ants on the plank to observe their behavior and determine the last moment before all ants fall off. + +#### Implementation + +```jsx live +function lastMomentBeforeAllAntsFallOut() { + const n = 4; + const left = [4, 3]; + const right = [0, 1]; + + const getLastMoment = function(n, left, right) { + const positions = Array(n + 1).fill(0); + for (let pos of left) positions[pos] = 1; + for (let pos of right) positions[pos] = 2; + + let lastMoment = 0; + for (let i = 0; i <= n; i++) { + if (positions[i] === 1) lastMoment = Math.max(lastMoment, i); + if (positions[i] === 2) lastMoment = Math.max(lastMoment, n - i); + } + return lastMoment; + }; + + const result = getLastMoment(n, left, right); + return ( +
+

+ Input: n = {n}, left = {JSON.stringify(left)}, right = {JSON.stringify(right)} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function get + +LastMoment(n, left, right) { + const positions = Array(n + 1).fill(0); + for (let pos of left) positions[pos] = 1; + for (let pos of right) positions[pos] = 2; + + let lastMoment = 0; + for (let i = 0; i <= n; i++) { + if (positions[i] === 1) lastMoment = Math.max(lastMoment, i); + if (positions[i] === 2) lastMoment = Math.max(lastMoment, n - i); + } + return lastMoment; + } + ``` + + + + + ```typescript + function getLastMoment(n: number, left: number[], right: number[]): number { + const positions = Array(n + 1).fill(0); + for (let pos of left) positions[pos] = 1; + for (let pos of right) positions[pos] = 2; + + let lastMoment = 0; + for (let i = 0; i <= n; i++) { + if (positions[i] === 1) lastMoment = Math.max(lastMoment, i); + if (positions[i] === 2) lastMoment = Math.max(lastMoment, n - i); + } + return lastMoment; + } + ``` + + + + + ```python + class Solution: + def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int: + positions = [0] * (n + 1) + for pos in left: + positions[pos] = 1 + for pos in right: + positions[pos] = 2 + + last_moment = 0 + for i in range(n + 1): + if positions[i] == 1: + last_moment = max(last_moment, i) + if positions[i] == 2: + last_moment = max(last_moment, n - i) + return last_moment + ``` + + + + + ```java + class Solution { + public int getLastMoment(int n, int[] left, int[] right) { + int[] positions = new int[n + 1]; + for (int pos : left) positions[pos] = 1; + for (int pos : right) positions[pos] = 2; + + int lastMoment = 0; + for (int i = 0; i <= n; i++) { + if (positions[i] == 1) lastMoment = Math.max(lastMoment, i); + if (positions[i] == 2) lastMoment = Math.max(lastMoment, n - i); + } + return lastMoment; + } + } + ``` + + + + + ```cpp + class Solution { + public: + int getLastMoment(int n, vector& left, vector& right) { + vector positions(n + 1, 0); + for (int pos : left) positions[pos] = 1; + for (int pos : right) positions[pos] = 2; + + int lastMoment = 0; + for (int i = 0; i <= n; i++) { + if (positions[i] == 1) lastMoment = max(lastMoment, i); + if (positions[i] == 2) lastMoment = max(lastMoment, n - i); + } + return lastMoment; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(L + R)$$, where `L` is the length of the `left` array and `R` is the length of the `right` array. +- Space Complexity: $$O(N)$$, where `N` is the length of the plank. + +
+
+ +:::tip + +By using a simple maximum calculation approach or a simulation approach, we can efficiently solve the Last Moment Before All Ants Fall Out of a Plank problem. The choice of implementation language depends on the specific requirements and constraints of the problem. + +::: + +## References + +- **LeetCode Problem:** [Last Moment Before All Ants Fall Out of a Plank](https://leetcode.com/problems/last-moment-before-all-ants-fall-out-of-a-plank/) +- **Solution Link:** [Last Moment Before All Ants Fall Out of a Plank Solution on LeetCode](https://leetcode.com/problems/last-moment-before-all-ants-fall-out-of-a-plank/solution/) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + diff --git a/solutions/lc-solutions/0400-0499/0405-convert-a-number-to-hexadecimal.md b/solutions/lc-solutions/0400-0499/0405-convert-a-number-to-hexadecimal.md new file mode 100644 index 0000000..8835b4b --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0405-convert-a-number-to-hexadecimal.md @@ -0,0 +1,149 @@ +--- +id: convert-a-number-to-hexadecimal +title: Convert a Number to Hexadecimal +sidebar_label: 405-Convert a Number to Hexadecimal +tags: + - Bit Manipulation + - Brute Force + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Convert a Number to Hexadecimal problem on LeetCode." +sidebar_position: 8 +--- + +## Problem Description + +Given an integer `num`, return a string representing its hexadecimal representation. For negative integers, the two’s complement method is used. + +All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself. + +Note: You are not allowed to use any built-in library method to directly solve this problem. + +### Examples + +**Example 1:** + +``` +Input: num = 26 +Output: "1a" +``` + +**Example 2:** + +``` +Input: num = -1 +Output: "ffffffff" +``` + +### Constraints + +- `-2^31 <= num <= 2^31 - 1` + +--- + +## Solution for Convert Integer to Hexadecimal Problem + +### Approach: Bit Manipulation + +To solve this problem, we convert the integer to its hexadecimal representation by handling one nibble (4 bits) at a time. For negative numbers, the two’s complement is used. + +#### Brute Force Approach + +1. **Convert Positive Numbers:** + - Use a loop to repeatedly divide the number by 16, and record the remainder. + - Use a map to convert the remainder to a hexadecimal character. + - Concatenate the characters in reverse order to get the final hexadecimal string. + +2. **Handle Negative Numbers:** + - Convert the number to its two's complement representation by adding \(2^{32}\) to the negative number. + - Apply the same method as for positive numbers. + +#### Optimized Approach + +- Since we are only dealing with 32 bits, we can use a mask to extract each nibble and convert it to a hexadecimal digit. + +#### Code in Different Languages + + + + + +```cpp +#include + +class Solution { +public: + std::string toHex(int num) { + if (num == 0) return "0"; + unsigned int n = num; + std::string hex_chars = "0123456789abcdef"; + std::string hex = ""; + while (n) { + hex = hex_chars[n & 15] + hex; + n >>= 4; + } + return hex; + } +}; +``` + + + + + +```java +class Solution { + public String toHex(int num) { + if (num == 0) return "0"; + long n = num & 0xFFFFFFFFL; + StringBuilder hex = new StringBuilder(); + String hexChars = "0123456789abcdef"; + while (n != 0) { + hex.insert(0, hexChars.charAt((int)(n & 15))); + n >>>= 4; + } + return hex.toString(); + } +} +``` + + + + + +```python +class Solution: + def toHex(self, num: int) -> str: + if num == 0: + return "0" + + num &= 0xFFFFFFFF # handle negative numbers + hex_chars = "0123456789abcdef" + result = [] + + while num: + result.append(hex_chars[num & 15]) + num >>= 4 + + return ''.join(result[::-1]) +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(1)$ because the maximum number of iterations is fixed (8 for 32-bit integers). +- **Space Complexity**: $O(1)$ as the space required does not depend on the input size. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0409-longest-palindrome.md b/solutions/lc-solutions/0400-0499/0409-longest-palindrome.md new file mode 100644 index 0000000..e69de29 diff --git a/solutions/lc-solutions/0400-0499/0410-split-array-largest-sum.md b/solutions/lc-solutions/0400-0499/0410-split-array-largest-sum.md new file mode 100644 index 0000000..674c961 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0410-split-array-largest-sum.md @@ -0,0 +1,399 @@ +--- +id: split-array-largest-sum +title: Split Array Largest Sum +sidebar_label: 0410. Split Array Largest Sum + +tags: +- Array +- Binary Search +- C++ +- Java +- Javascript +- Python +- TypeScript +- Hard +- Leetcode +- Split Array Largest Sum + +description: "This is a solution to the Split Array Largest Sum problem on LeetCode." +--- + +## Problem Description +Given an integer array `nums` and an integer `k`, split `nums` into `k` non-empty subarrays such that the largest sum of any subarray is **minimized**. +Return *the minimized largest sum of the split.* +A **subarray** is a contiguous part of the array. + +### Examples + +**Example 1:** +``` +Input: nums = [7,2,5,10,8], k = 2 +Output: 18 +Explanation: There are four ways to split nums into two subarrays. +The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18. +``` + +**Example 2:** +``` +Input: nums = [1,2,3,4,5], k = 2 +Output: 9 +Explanation: There are four ways to split nums into two subarrays. +The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9. +``` + + +### Constraints +- `1 <= nums.length <= 1000` +- `0 <= nums[i] <= 106` +- `1 <= k <= min(50, nums.length)` + + +## Solution for Split Array Largest Sum +### Approach +#### Brute Force +- Generate all possible ways to split the array `nums` into `k` subarrays. +- For each split, calculate the largest sum of the subarrays. +- Keep track of the minimum of these largest sums. + + +**Complexity:** +- Time Complexity: `O(C(n-1, k-1) * n)`, where C(n-1, k-1) is the number of ways to choose k-1 split points from n-1 positions, which is exponential. +- Space Complexity: O(k), for storing split indices. +- Impractical for large inputs due to combinatorial explosion. + +**Corner Cases:** +- `nums` with a single element. +- `k` equal to the length of `nums`, resulting in each element being its own subarray. +- `k` equal to 1, meaning the entire array is one subarray. + +#### Optimized Approach (Binary Search + Greedy) +- Use binary search to find the minimum possible largest sum `(low)` and the maximum possible largest sum `(high)`. +- `low` is the maximum element in `nums` (because each subarray must have at least one element). +- `high` is the sum of all elements in `nums` (the entire array as one subarray). +- Use binary search to narrow down the smallest valid `mid` value, where `mid` represents the largest sum allowed for a subarray. +- Use a greedy algorithm to check if it's possible to split `nums` into `k` subarrays with the largest subarray sum being `mid`. + +**Implementation:** + +```javascript +var splitArray = function(nums, k) { + const canSplit = (nums, k, mid) => { + let count = 1; + let currentSum = 0; + + for (let num of nums) { + if (currentSum + num > mid) { + count++; + currentSum = num; + if (count > k) return false; + } else { + currentSum += num; + } + } + return true; + }; + + let left = Math.max(...nums); + let right = nums.reduce((a, b) => a + b, 0); + + while (left < right) { + let mid = Math.floor((left + right) / 2); + if (canSplit(nums, k, mid)) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; +}; +``` + +**Complexity:** +- Time Complexity: `O(n log(sum(nums) - max(nums)))`, where `n` is the length of `nums`. This is due to the binary search over the sum range and the linear scan to validate each mid value. +- Space Complexity: `O(1)`, as we are not using extra space proportional to the input size. + +**Corner Cases:** +- `nums` with a single element: the result is that single element. +- `k` equal to the length of `nums`: the result is the maximum element in `nums`. +- `k` equal to 1: the result is the sum of all elements in `nums`. +- All elements in `nums` are the same: the result should be one of those elements. + + + + + +#### Implementation + + ```jsx live + function Solution(arr) { + var splitArray = function(nums, k) { + const canSplit = (nums, k, mid) => { + let count = 1; + let currentSum = 0; + + for (let num of nums) { + if (currentSum + num > mid) { + count++; + currentSum = num; + if (count > k) return false; + } else { + currentSum += num; + } + } + return true; + }; + + let left = Math.max(...nums); + let right = nums.reduce((a, b) => a + b, 0); + + while (left < right) { + let mid = Math.floor((left + right) / 2); + if (canSplit(nums, k, mid)) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; + }; + + const nums = [7, 2, 5, 10, 8]; + const k = 2; + const result = splitArray(nums, k); + + return ( +
+

+ Input: + {JSON.stringify({ nums, k })} +

+

+ Output: {result} +

+
+ ); + } + ``` + +#### Complexity Analysis + + - Time Complexity: $O(n log(sum(nums) - max(nums)))$ + - Space Complexity: $O(1)$ + + ## Code in Different Languages + + + + + + + ```javascript + var splitArray = function(nums, k) { + const canSplit = (nums, k, mid) => { + let count = 1; + let currentSum = 0; + + for (let num of nums) { + if (currentSum + num > mid) { + count++; + currentSum = num; + if (count > k) return false; + } else { + currentSum += num; + } + } + return true; + }; + + let left = Math.max(...nums); + let right = nums.reduce((a, b) => a + b, 0); + + while (left < right) { + let mid = Math.floor((left + right) / 2); + if (canSplit(nums, k, mid)) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; + }; + ``` + + + + + + + ```typescript + function splitArray(nums: number[], k: number): number { + const canSplit = (nums: number[], k: number, mid: number): boolean => { + let count = 1; + let currentSum = 0; + + for (let num of nums) { + if (currentSum + num > mid) { + count++; + currentSum = num; + if (count > k) return false; + } else { + currentSum += num; + } + } + return true; + }; + + let left = Math.max(...nums); + let right = nums.reduce((a, b) => a + b, 0); + + while (left < right) { + let mid = Math.floor((left + right) / 2); + if (canSplit(nums, k, mid)) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; + }; + ``` + + + + + + + ```python + class Solution: + def splitArray(self, nums: List[int], k: int) -> int: + def canSplit(nums: List[int], k: int, mid: int) -> bool: + count = 1 + current_sum = 0 + + for num in nums: + if current_sum + num > mid: + count += 1 + current_sum = num + if count > k: + return False + else: + current_sum += num + return True + + left, right = max(nums), sum(nums) + + while left < right: + mid = (left + right) // 2 + if canSplit(nums, k, mid): + right = mid + else: + left = mid + 1 + + return left + ``` + + + + + + + ```java + public class Solution { + public int splitArray(int[] nums, int k) { + int left = Arrays.stream(nums).max().getAsInt(); + int right = Arrays.stream(nums).sum(); + + while (left < right) { + int mid = (left + right) / 2; + if (canSplit(nums, k, mid)) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; + } + + private boolean canSplit(int[] nums, int k, int mid) { + int count = 1; + int currentSum = 0; + + for (int num : nums) { + if (currentSum + num > mid) { + count++; + currentSum = num; + if (count > k) { + return false; + } + } else { + currentSum += num; + } + } + + return true; + } + } + ``` + + + + + + + ```cpp + class Solution { + public: + int splitArray(vector& nums, int k) { + int left = *max_element(nums.begin(), nums.end()); + int right = accumulate(nums.begin(), nums.end(), 0); + + while (left < right) { + int mid = left + (right - left) / 2; + if (canSplit(nums, k, mid)) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; + } + + private: + bool canSplit(vector& nums, int k, int mid) { + int count = 1; + int currentSum = 0; + + for (int num : nums) { + if (currentSum + num > mid) { + count++; + currentSum = num; + if (count > k) { + return false; + } + } else { + currentSum += num; + } + } + + return true; + } + }; + ``` + + + + +
+
+ +## References + +- **LeetCode Problem**: [Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/split-array-largest-sum/solutions/) \ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0412-fizz-buzz.md b/solutions/lc-solutions/0400-0499/0412-fizz-buzz.md new file mode 100644 index 0000000..841d8c6 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0412-fizz-buzz.md @@ -0,0 +1,165 @@ +--- +id: fizz-buzz +title: Fizz Buzz(LeetCode) +sidebar_label: 0412-Fizz Buzz +tags: + - Math + - String + - Simulation +description: Given an integer n, return a string array answer (1-indexed) where "FizzBuzz" if i is divisible by 3 and 5, "Fizz" if i is divisible by 3, "Buzz" if i is divisible by 5, i (as a string) if none of the above conditions are true. +--- + +## Problem Statement + +Given an integer `n`, return a string array `answer` (1-indexed) where: + +`answer[i] == "FizzBuzz"` if `i` is divisible by `3` and `5`. +`answer[i] == "Fizz"` if `i` is divisible by `3`. +`answer[i] == "Buzz"` if `i` is divisible by `5`. +`answer[i] == i` (as a string) if none of the above conditions are true. + +### Examples + +**Example 1:** + +```plaintext +Input: n = 3 +Output: ["1","2","Fizz"] +``` + +**Example 2:** + +```plaintext +Input: n = 5 +Output: ["1","2","Fizz","4","Buzz"] +``` + +**Example 3:** + +```plaintext +Input: n = 15 +Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] +``` + +### Constraints + +- `1 <= n <= 104` + +## Solution + +The FizzBuzz problem is a classic programming task often used to teach and test fundamental coding skills. The problem statement is simple: for a given integer `n`, return a list of strings where each string corresponds to the numbers from 1 to `n` with the following rules: + +* For multiples of 3, add "Fizz" instead of the number. +* For multiples of 5, add "Buzz" instead of the number. +* For multiples of both 3 and 5, add "FizzBuzz" instead of the number. +Here, we present three different approaches to solve the FizzBuzz problem in Java. + +### Approach 1: Simple if-else + +#### Algorithm + +1. Create an empty list to store the results. +2. Loop from 1 to `n`. +3. For each number, check if it is divisible by 15, 3, or 5 using the modulus operator. +4. Add the appropriate string ("FizzBuzz", "Fizz", "Buzz", or the number itself) to the list. +5. Return the list. + +#### Implementation + +```Java +class Solution { + public List fizzBuzz(int n) { + List ans = new ArrayList<>(); + for (int i = 1; i <= n; i++) { + if (i % 15 == 0) { + ans.add("FizzBuzz"); + } else if (i % 3 == 0) { + ans.add("Fizz"); + } else if (i % 5 == 0) { + ans.add("Buzz"); + } else { + ans.add(String.valueOf(i)); + } + } + return ans; + } +} +``` + +### Approach 2: No Modulus Operator + +#### Algorithm + +1. Create an empty list to store the results. +2. Use two counters, `fizz` and `buzz`, initialized to 0. +3. Loop from 1 to `n`. +4. Increment `fizz` and `buzz` for each number. +5. Check the values of `fizz` and buzz to decide whether to add "Fizz", "Buzz", "FizzBuzz", or the number itself to the list. +6. Reset `fizz` and/or `buzz` when they reach their respective thresholds (3 and 5). +7. Return the list. + +#### Implementation + +```Java +class Solution { + public List fizzBuzz(int n) { + List res = new ArrayList<>(); + int i = 1, fizz = 0, buzz = 0; + while (i <= n) { + fizz++; buzz++; + if (fizz == 3 && buzz == 5) { + res.add("FizzBuzz"); + fizz = buzz = 0; + } else if (fizz == 3) { + res.add("Fizz"); + fizz = 0; + } else if (buzz == 5) { + res.add("Buzz"); + buzz = 0; + } else { + res.add(String.valueOf(i)); + } + i++; + } + return res; + } +} +``` + +### Approach 3: Ternary Operator + +#### Algorithm + +1. Create an empty list to store the results. +2. Loop from 1 to `n`. +3. For each number, use the ternary operator to check if it is divisible by 15, 5, or 3, and add the appropriate string to the list. +4. Return the list. + +#### Implementation + +```Java +class Solution { + public List fizzBuzz(int n) { + List ans = new ArrayList<>(); + for (int i = 1; i <= n; i++) { + ans.add( + i % 15 == 0 ? "FizzBuzz" : + i % 5 == 0 ? "Buzz" : + i % 3 == 0 ? "Fizz" : + String.valueOf(i) + ); + } + return ans; + } +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(N)$ +- **Space complexity**: $O(N)$ + + +### Conclusion + +The choice of approach can depend on coding style and specific constraints or preferences. The first approach is straightforward and easy to understand. The second approach is a creative way to avoid the modulus operator, while the third approach uses the ternary operator for a concise solution. diff --git a/solutions/lc-solutions/0400-0499/0413-arithmetic-slices.md b/solutions/lc-solutions/0400-0499/0413-arithmetic-slices.md new file mode 100644 index 0000000..ff7462b --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0413-arithmetic-slices.md @@ -0,0 +1,125 @@ +--- +id: arithmetic-slices +title: Arithmetic Slices (LeetCode) +sidebar_label: 0413-Arithmetic Slices +tags: + - Array + - Dynamic Programming +description: Given an integer array nums, return the number of arithmetic subarrays of nums. +sidebar_position: 0413 +--- + +## Problem Description + +An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. +- For example, `[1,3,5,7,9]`, `[7,7,7,7]`, and `[3,-1,-5,-9]` are arithmetic sequences. + +Given an integer array nums, return the number of arithmetic subarrays of nums. + +A subarray is a contiguous subsequence of the array. + +### Example 1 + +- **Input:** `nums = [1,2,3,4]` +- **Output:** `3` +- **Explanation:** We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself. + +### Example 2 + +- **Input:** ` nums = [1]` +- **Output:** `0` + +### Constraints + +- `1 <= nums.length <= 5000` +- `-1000 <= nums[i] <= 1000` + +## Approach +- 1. Initialize Variables: Before looping through the nums, we initialize the ans variable to 0. This variable will accumulate the total count of arithmetic subarrays. We also initialize a cnt variable to 0; it keeps track of consecutive pairs with the same difference. The d variable, which holds the current common difference between pairs, is set to a number outside the valid range (3000) to handle the edge case at the beginning of the array. + +- 2. Loop through pairwise(nums): We iterate over each pair (a, b) in pairwise(nums). Here, a and b represent consecutive elements in nums. + +- 3. Check the Difference and Update Counter: We compare the difference b - a with the current d. If they're equal, increment cnt by 1, because this extends the current arithmetic subarray sequence by one element. If they're different, update d to the new difference b - a and reset cnt to 0, because we're starting to count a new set of arithmetic subarrays. + +- 4. Update the Answer: Add the current cnt to ans in each iteration. By adding cnt, we're accounting for all the new arithmetic subarrays that end at the current element b. The reason adding cnt works is that for each extension of an arithmetic subarray by one element, we introduce exactly cnt new subarrays where cnt is the count of previous consecutive elements that were part of such subarrays. + +- 5. Return Result: After the loop completes, ans represents the total number of arithmetic subarrays in nums, which is then returned as the final answer. + +### Solution Code + +#### Python + +```python +from itertools import pairwise + +class Solution: + def numberOfArithmeticSlices(self, nums: List[int]) -> int: + total_slices = 0 + current_sequence_length = 0 + previous_difference = 3000 + for current_num, next_num in pairwise(nums): + current_difference = next_num - current_num + if current_difference == previous_difference: + current_sequence_length += 1 + else: + previous_difference = current_difference + current_sequence_length = 0 + total_slices += current_sequence_length + return total_slices +``` + +#### C++ +```c++ +class Solution { +public: + int numberOfArithmeticSlices(vector& nums) { + int totalSlices = 0; + int currentStreak = 0; + int previousDifference = 3000; + for (int i = 0; i < nums.size() - 1; ++i) { + int currentDifference = nums[i + 1] - nums[i]; + if (currentDifference == previousDifference) { + ++currentStreak; + } else { + previousDifference = currentDifference; + currentStreak = 0; + } + totalSlices += currentStreak; + } + return totalSlices; + } +}; + +``` + +#### Java +```Java +class Solution { + public int numberOfArithmeticSlices(int[] nums) { + int arithmeticSliceCount = 0; + int currentSliceLength = 0; + int difference = 3000; + for (int i = 0; i < nums.length - 1; ++i) { + if (nums[i + 1] - nums[i] == difference) { + ++currentSliceLength; + } else { + difference = nums[i + 1] - nums[i]; + currentSliceLength = 0; + } + arithmeticSliceCount += currentSliceLength; + } + return arithmeticSliceCount; + } +} + +``` + + + + +#### Conclusion +- Time Complexity +The time complexity is o(n). + +- Space Complexity +The space complexity is O(1). diff --git a/solutions/lc-solutions/0400-0499/0414-third-maximum-number.md b/solutions/lc-solutions/0400-0499/0414-third-maximum-number.md new file mode 100644 index 0000000..9f4b586 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0414-third-maximum-number.md @@ -0,0 +1,75 @@ +--- +id: third-maximum-number +title: Third Maximum Number +sidebar_label: 0414 Third Maximum Number +tags: + - Math + - Vector + - Set + - LeetCode + - C++ +description: "This is a solution to the Third Maximum Number problem on LeetCode." +--- + +## Problem Description + +Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number. + +### Examples + +**Example 1:** + +``` + +Input: nums = [1,2] +Output: 2 +``` + +**Example 2:** + +``` +Input: nums = [2,2,3,1] +Output: 1 +``` + +**Example 2:** + +``` +Input: root = [0] +Output: [0] +``` + +### Constraints + +- $1 \leq \text{nums.length} \leq 10^4$. +- $-2^(31) \leq \text{Node.val} \leq 2^(31)-1$. + +### Approach + +To solve this problem(third maximum element) first we will store the number from the array/vector in set to get all the unique number from the given array then if size of the set is less than 3 we will just return maximum element from the array otherwise we will return the third element from the set. + +#### Code in C++ + +```cpp +class Solution { +public: + int thirdMax(vector& nums) { + setb; + for(int i=0;ip; + for(auto x :b){ + p.push_back(x); + } + + return p.at(n-3); + } +}; +``` + + diff --git a/solutions/lc-solutions/0400-0499/0415-add-strings.md b/solutions/lc-solutions/0400-0499/0415-add-strings.md new file mode 100644 index 0000000..4c9eadd --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0415-add-strings.md @@ -0,0 +1,179 @@ +--- +id: add-strings +title: Add Strings +sidebar_label: 415-Add Strings +tags: + - String Manipulation + - Simulation + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Add Strings problem on LeetCode." +sidebar_position: 10 +--- + +## Problem Description + +Given two non-negative integers, `num1` and `num2`, represented as strings, return the sum of `num1` and `num2` as a string. + +You must solve the problem without using any built-in library for handling large integers (such as `BigInteger`). You must also not convert the inputs to integers directly. + +### Examples + +**Example 1:** + +``` +Input: num1 = "11", num2 = "123" +Output: "134" +``` + +**Example 2:** + +``` +Input: num1 = "456", num2 = "77" +Output: "533" +``` + +**Example 3:** + +``` +Input: num1 = "0", num2 = "0" +Output: "0" +``` + +### Constraints + +- `1 <= num1.length, num2.length <= 10^4` +- `num1` and `num2` consist of only digits. +- `num1` and `num2` don't have any leading zeros except for the zero itself. + +--- + +## Solution for Add Strings Problem + +To solve this problem, we simulate the addition of two numbers digit by digit from right to left, similar to how we perform addition manually. + +### Approach: Simulation of Digit-by-Digit Addition + +1. **Initialize Variables:** + - `i` and `j` to point to the last characters of `num1` and `num2`. + - `carry` to store the carry-over value during addition. + - `result` to store the result in reverse order. + +2. **Add Digits from Right to Left:** + - Loop until all digits from both numbers and the carry are processed. + - For each step, add the corresponding digits from `num1` and `num2` and the `carry`. + - Calculate the new `carry` and the digit to be added to the result. + - Append the result digit to the `result` list. + +3. **Handle Carry:** + - If there's any remaining carry after the loop, append it to the `result`. + +4. **Return Result:** + - Reverse the `result` list and join the digits to form the final string. + +#### Brute Force Approach + +1. Convert each string to an integer. +2. Add the two integers. +3. Convert the sum back to a string. + +This approach, while simple, is not allowed as per the problem constraints. + +#### Optimized Approach + +The optimized approach uses the manual digit-by-digit addition described above. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + string addStrings(string num1, string num2) { + int i = num1.size() - 1, j = num2.size() - 1, carry = 0; + string result = ""; + + while (i >= 0 || j >= 0 || carry) { + int sum = carry; + if (i >= 0) sum += num1[i--] - '0'; + if (j >= 0) sum += num2[j--] - '0'; + carry = sum / 10; + result += (sum % 10) + '0'; + } + + reverse(result.begin(), result.end()); + return result; + } +}; +``` + + + + + +```java +class Solution { + public String addStrings(String num1, String num2) { + StringBuilder result = new StringBuilder(); + int carry = 0, i = num1.length() - 1, j = num2.length() - 1; + + while (i >= 0 || j >= 0 || carry != 0) { + int sum = carry; + if (i >= 0) sum += num1.charAt(i--) - '0'; + if (j >= 0) sum += num2.charAt(j--) - '0'; + result.append(sum % 10); + carry = sum / 10; + } + + return result.reverse().toString(); + } +} +``` + + + + + +```python +class Solution: + def addStrings(self, num1: str, num2: str) -> str: + i, j = len(num1) - 1, len(num2) - 1 + carry = 0 + result = [] + + while i >= 0 or j >= 0 or carry: + sum_val = carry + if i >= 0: + sum_val += ord(num1[i]) - ord('0') + i -= 1 + if j >= 0: + sum_val += ord(num2[j]) - ord('0') + j -= 1 + carry, digit = divmod(sum_val, 10) + result.append(str(digit)) + + return ''.join(result[::-1]) +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(max(n, m))$, where `n` and `m` are the lengths of `num1` and `num2`. +- **Space Complexity**: $O(max(n, m))$ for storing the result. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0416-Partition-equal-subset-sum.md b/solutions/lc-solutions/0400-0499/0416-Partition-equal-subset-sum.md new file mode 100644 index 0000000..7ed704b --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0416-Partition-equal-subset-sum.md @@ -0,0 +1,214 @@ +--- +id: Partition-equal-subset-sum +title: Partition Equal Subset Sum +sidebar_label: 0416 - Partition Equal Subset Sum +tags: + - Dynamic Programming + - C++ + - Java + - Python +description: "This document provides a solution to the Partition Equal Subset Sum problem." +--- + +## Problem + +Given an integer array `nums`, return `true` if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or `false` otherwise. + +### Examples + +**Example 1:** + +Input: nums = [1,5,11,5] +Output: true +Explanation: The array can be partitioned as [1, 5, 5] and [11]. + +**Example 2:** + +Input: nums = [1,2,3,5] +Output: false +Explanation: The array cannot be partitioned into equal sum subsets. + +### Constraints + +- $1 \leq \text{nums.length} \leq 200$ +- $1 \leq \text{nums}[i] \leq 100$ + +### Approach + +The following are the two main steps to solve this problem: + +1. Calculate the sum of the array. If the sum is odd, there cannot be two subsets with an equal sum, so return `false`. +2. If the sum of the array elements is even, calculate `sum / 2` and find a subset of the array with a sum equal to `sum / 2`. + +The first step is simple. The second step is crucial and can be solved either using recursion or Dynamic Programming. + +### Solution + +This problem can be solved using dynamic programming. We need to find whether the sum of some elements of the array make it equal to `sum / 2`; if yes, then we return `true`, otherwise `false`. + +#### Code in Different Languages + +```cpp title="C++" +using namespace std; + +bool isSubsetSum(int arr[], int n, int sum, vector>& dp) { + if (sum == 0) + return true; + if (n == 0 && sum != 0) + return false; + + if (dp[n][sum] != -1) + return dp[n][sum]; + + if (arr[n - 1] > sum) + return isSubsetSum(arr, n - 1, sum, dp); + + return dp[n][sum] = isSubsetSum(arr, n - 1, sum, dp) || isSubsetSum(arr, n - 1, sum - arr[n - 1], dp); +} + +bool findPartition(int arr[], int n) { + int sum = 0; + for (int i = 0; i < n; i++) + sum += arr[i]; + + if (sum % 2 != 0) + return false; + + vector> dp(n + 1, vector(sum + 1, -1)); + return isSubsetSum(arr, n, sum / 2, dp); +} + +int main() { + int arr[] = {3, 1, 5, 9, 12}; + int n = sizeof(arr) / sizeof(arr[0]); + + if (findPartition(arr, n)) + cout << "Can be divided into two subsets of equal sum"; + else + cout << "Cannot be divided into two subsets of equal sum"; + + int arr2[] = {3, 1, 5, 9, 14}; + int n2 = sizeof(arr2) / sizeof(arr2[0]); + + if (findPartition(arr2, n2)) + cout << endl << "Can be divided into two subsets of equal sum"; + else + cout << endl << "Cannot be divided into two subsets of equal sum"; + + return 0; +} +``` + +```java title="Java" +import java.util.Arrays; + +class PartitionEqualSubsetSum { + static int isSubsetSum(int arr[], int n, int sum, int[][] dp) { + if (sum == 0) + return 1; + if (n == 0 && sum != 0) + return 0; + + if (dp[n][sum] != -1) + return dp[n][sum]; + + if (arr[n - 1] > sum) + return isSubsetSum(arr, n - 1, sum, dp); + + if (isSubsetSum(arr, n - 1, sum, dp) != 0 || isSubsetSum(arr, n - 1, sum - arr[n - 1], dp) != 0) + return dp[n][sum] = 1; + return dp[n][sum] = 0; + } + + static int findPartition(int arr[], int n) { + int sum = 0; + for (int i = 0; i < n; i++) + sum += arr[i]; + + if (sum % 2 != 0) + return 0; + + int dp[][] = new int[n + 1][sum + 1]; + for (int[] row : dp) + Arrays.fill(row, -1); + + return isSubsetSum(arr, n, sum / 2, dp); + } + + public static void main(String[] args) { + int arr[] = {3, 1, 5, 9, 12}; + int n = arr.length; + + if (findPartition(arr, n) == 1) + System.out.println("Can be divided into two subsets of equal sum"); + else + System.out.println("Cannot be divided into two subsets of equal sum"); + + int arr2[] = {3, 1, 5, 9, 14}; + int n2 = arr2.length; + + if (findPartition(arr2, n2) == 1) + System.out.println("Can be divided into two subsets of equal sum"); + else + System.out.println("Cannot be divided into two subsets of equal sum"); + } +} +``` + +```python title="Python" +def isSubsetSum(arr, n, sum, dp): + if sum == 0: + return True + if n == 0 and sum != 0: + return False + + if dp[n][sum] != -1: + return dp[n][sum] + + if arr[n - 1] > sum: + return isSubsetSum(arr, n - 1, sum, dp) + + dp[n][sum] = isSubsetSum(arr, n - 1, sum, dp) or isSubsetSum(arr, n - 1, sum - arr[n - 1], dp) + return dp[n][sum] + +def findPartition(arr, n): + sum = 0 + for i in range(n): + sum += arr[i] + + if sum % 2 != 0: + return False + + dp = [[-1] * (sum + 1) for _ in range(n + 1)] + return isSubsetSum(arr, n, sum // 2, dp) + +arr = [3, 1, 5, 9, 12] +n = len(arr) + +if findPartition(arr, n): + print("Can be divided into two subsets of equal sum") +else: + print("Cannot be divided into two subsets of equal sum") + +arr2 = [3, 1, 5, 9, 14] +n2 = len(arr2) + +if findPartition(arr2, n2): + print("Can be divided into two subsets of equal sum") +else: + print("Cannot be divided into two subsets of equal sum") +``` + +### Complexity Analysis + +#### Time Complexity: $O(\text{sum} \times N)$ + +> **Reason**: The maximum iterations possible are sum * N. + +#### Space Complexity: $O(\text{sum} \times N)$ + +> **Reason**: We are using an extra array for `dp`. + +### References + +- **LeetCode Problem**: Partition Equal Subset Sum \ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0419-Battleships-in-a-Board.md b/solutions/lc-solutions/0400-0499/0419-Battleships-in-a-Board.md new file mode 100644 index 0000000..7f049dc --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0419-Battleships-in-a-Board.md @@ -0,0 +1,121 @@ +--- +id: battleships-in-a-board +title: Battleships in a Board +sidebar_label: 0419-Battleships-in-a-Board +tags: +- Array +- Depth-First Search +- Matrix +description: "Given an `m x n` board where each cell is a battleship 'X' or empty '.', count the number of battleships on the board." +--- + +## Problem + +Given an `m x n` board where each cell is a battleship `'X'` or empty `'.'`, return the number of battleships on the board. + +Battleships can only be placed horizontally or vertically on the board. In other words, they can only occupy a contiguous line of cells horizontally or vertically. Each battleship must be separated by at least one empty cell (either horizontally or vertically) from any other battleship. + +### Examples + +**Example 1:** + +**Input:** `board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]` +**Output:** `2` + +**Example 2:** + +**Input:** `board = [["."]]` +**Output:** `0` + +### Constraints + +- `m == board.length` +- `n == board[i].length` +- `1 <= m, n <= 200` +- `board[i][j]` is either `'X'` or `'.'`. + +### Follow-up + +Could you do it in one-pass, using only `O(1)` extra memory and without modifying the value of the board? + +--- + +## Approach + +To count the number of battleships in one pass and without extra memory, we can traverse the board and count only the top-left cell of each battleship. A cell qualifies as the top-left cell if there are no battleship cells above it or to the left of it. + +### Steps: + +1. Initialize a counter to keep track of the number of battleships. +2. Traverse each cell in the board. +3. For each cell, check if it is a battleship (`'X'`): + - If it is, check if there is no battleship cell above it and no battleship cell to the left of it. + - If both conditions are met, increment the battleship counter. +4. Return the counter after the traversal. + +### Solution + +#### Java Solution + +```java +class Solution { + public int countBattleships(char[][] board) { + int count = 0; + for (int i = 0; i < board.length; i++) { + for (int j = 0; j < board[0].length; j++) { + if (board[i][j] == 'X') { + if (i > 0 && board[i - 1][j] == 'X') continue; + if (j > 0 && board[i][j - 1] == 'X') continue; + count++; + } + } + } + return count; + } +} +``` +### C++ Solution + +```cpp +class Solution { +public: + int countBattleships(vector>& board) { + int count = 0; + for (int i = 0; i < board.size(); i++) { + for (int j = 0; j < board[0].size(); j++) { + if (board[i][j] == 'X') { + if (i > 0 && board[i - 1][j] == 'X') continue; + if (j > 0 && board[i][j - 1] == 'X') continue; + count++; + } + } + } + return count; + } +}; +``` +### Python Solution + +```python +class Solution: + def countBattleships(self, board: List[List[str]]) -> int: + count = 0 + for i in range(len(board)): + for j in range(len(board[0])): + if board[i][j] == 'X': + if i > 0 and board[i - 1][j] == 'X': + continue + if j > 0 and board[i][j - 1] == 'X': + continue + count += 1 + return count +``` +### Complexity Analysis +**Time Complexity:** O(m * n) +>Reason: We traverse each cell of the board once. + +**Space Complexity:** O(1) +>Reason: We do not use any extra space that scales with the input size. + +### References +**LeetCode Problem:** Battleships in a Board \ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0420-strong-password-checker.md b/solutions/lc-solutions/0400-0499/0420-strong-password-checker.md new file mode 100644 index 0000000..ccc6511 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0420-strong-password-checker.md @@ -0,0 +1,255 @@ +--- +id: strong-password-checker +title: Strong Password Checker +sidebar_label: 0420 - Strong Password Checker +tags: + - Greedy + - Dynamic Programming + - Heap +description: "This is a solution to the Strong Password Checker problem on LeetCode." +--- + +## Problem Description + +A password is considered strong if the below conditions are all met: + +- It has at least 6 characters and at most 20 characters. +- It contains at least **one lowercase letter**, at least **one uppercase** letter, and at least **one digit**. +- It does not contain three repeating characters in a row (i.e., `"Baaabb0"` is weak, but `"Baaba0"` is strong). + +Given a string password, return the minimum number of steps required to make password strong. if password is already strong, return 0. + +In one step, you can: + +- Insert one character to password, +- Delete one character from password, or +- Replace one character of password with another character. + +### Examples + +**Example 1:** + +``` +Input: password = "a" +Output: 5 +Explanation: The password needs additional characters, an uppercase letter, and a digit to meet the criteria. +``` + +**Example 2:** + +``` +Input: password = "aA1" +Output: 3 +Explanation: The password needs more characters to reach the minimum length of 6. +``` + +### Constraints + +- `1 <= password.length <= 50` +- `password` consists of letters, digits, dot `'.'` or exclamation mark `'!'`. + +## Solution for Strong Password Checker + +### Approach + +- A strong password should contain at least one lowercase letter, one uppercase letter, and one number. +- It should avoid having the same character repeated three times consecutively and be between 6 and 20 characters long. + +The code achieves this by following these steps: + +1. Utilizes a β€œrequirements” checklist to keep track of the first three criteria (initially unchecked). +2. Maintains a record of character repetitions. +3. Examines each character in the text: + - If different from the previous character, checks off requirements if not met. + - If the same as the previous character, counts consecutive repetitions. +4. Sorts the repeated characters list by the number of repetitions. +5. Adjusts the text: + - For text longer than 20 characters, removes one repeated character in sequences of three or more. + - For texts without such sequences, removes one character from the repeated character list. + - Continues until the text is 20 characters or less. +6. Calculates the number of characters needed to make the text at least 6 characters long (if it’s shorter). +7. Totals all the changes made to meet the rules, providing the minimum number of changes required to create a strong password. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + int strongPasswordChecker(string s) { + bitset<3> requirements{111}; + list repeats; + auto it = s.begin(); + auto it2 = s.end(); + while (it != s.end()) { + if (*it != *it2) { + if (requirements.test(0) && islower(*it)) + requirements.reset(0); + if (requirements.test(1) && isupper(*it)) + requirements.reset(1); + if (requirements.test(2) && isdigit(*it)) + requirements.reset(2); + } else { + while (it != s.end() && *it == *it2) + ++it; + if (distance(it2, it) != 2) + repeats.push_back(distance(it2, it)); + if (it != s.end()) + continue; + else + break; + } + it2 = it; + ++it; + } + repeats.sort([](const int &lhs, const int &rhs) { return (lhs % 3) < (rhs % 3); }); + int ans{0}, len{static_cast(s.size())}; + while (len > 20) { + if (!repeats.empty()) { + if (repeats.front() == 3) { + repeats.pop_front(); + } + else { + --repeats.front(); + repeats.sort([](const int &lhs, const int &rhs) { return (lhs % 3) < (rhs % 3); }); + } + ++ans; + --len; + } + else { + ans += len - 20; + len = 20; + } + } + int rep_ins{0}; + while (!repeats.empty()) { + rep_ins += repeats.front() / 3; + repeats.pop_front(); + } + if ((len + rep_ins) < 6) { + rep_ins += 6 - len - rep_ins; + } + ans += max(static_cast(requirements.count()), rep_ins); + return ans; + } +}; +``` + + + + +```java +class Solution { + public int strongPasswordChecker(String s) { + int res = 0, a = 1, A = 1, d = 1; + char[] carr = s.toCharArray(); + int[] arr = new int[carr.length]; + for (int i = 0; i < arr.length;) { + if (Character.isLowerCase(carr[i])) a = 0; + if (Character.isUpperCase(carr[i])) A = 0; + if (Character.isDigit(carr[i])) d = 0; + int j = i; + while (i < carr.length && carr[i] == carr[j]) i++; + arr[j] = i - j; + } + + int total_missing = (a + A + d); + if (arr.length < 6) { + res += total_missing + Math.max(0, 6 - (arr.length + total_missing)); + } else { + int over_len = Math.max(arr.length - 20, 0), left_over = 0; + res += over_len; + for (int k = 1; k < 3; k++) { + for (int i = 0; i < arr.length && over_len > 0; i++) { + if (arr[i] < 3 || arr[i] % 3 != (k - 1)) continue; + arr[i] -= Math.min(over_len, k); + over_len -= k; + } + } + for (int i = 0; i < arr.length; i++) { + if (arr[i] >= 3 && over_len > 0) { + int need = arr[i] - 2; + arr[i] -= over_len; + over_len -= need; + } + if (arr[i] >= 3) left_over += arr[i] / 3; + } + res += Math.max(total_missing, left_over); + } + return res; + } +} +``` + + + + + +```python +class Solution(object): + def strongPasswordChecker(self, s): + missing_type = 3 + if any('a' <= c <= 'z' for c in s): missing_type -= 1 + if any('A' <= c <= 'Z' for c in s): missing_type -= 1 + if any(c.isdigit() for c in s): missing_type -= 1 + + change = 0 + one = 0 + two = 0 + p = 2 + while p < len(s): + if s[p] == s[p-1] == s[p-2]: + length = 2 + while p < len(s) and s[p] == s[p-1]: + length += 1 + p += 1 + change += length // 3 + if length % 3 == 0: one += 1 + elif length % 3 == 1: two += 1 + else: + p += 1 + + if len(s) < 6: + return max(missing_type, 6 - len(s)) + elif len(s) <= 20: + return max(missing_type, change) + else: + delete = len(s) - 20 + change -= min(delete, one) + change -= min(max(delete - one, 0), two * 2) // 2 + change -= max(delete - one - 2 * two, 0) // 3 + return delete + max(missing_type, change) + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: The code iterates through the input string once and performs various operations such as checking character types, counting repeated characters, and maintaining a list of repeats. + +### Space Complexity: $O(N)$ + +> **Reason**: The space complexity is linear because the size of the repeats list is proportional to the length of the input + +## References + +- **LeetCode Problem**: [Strong Password Checker](https://leetcode.com/problems/strong-password-checker/description/) + +- **Solution Link**: [Strong Password Checker](https://leetcode.com/problems/strong-password-checker/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
+ diff --git a/solutions/lc-solutions/0400-0499/0421-maximum-xor-of-two-numbers-in-an-array.md b/solutions/lc-solutions/0400-0499/0421-maximum-xor-of-two-numbers-in-an-array.md new file mode 100644 index 0000000..1ba6ef6 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0421-maximum-xor-of-two-numbers-in-an-array.md @@ -0,0 +1,191 @@ +--- +id: maximum-xor-of-two-numbers-in-an-array +title: Maximum XOR of two numbers in an array +sidebar_label: 0421-maximum-xor-of-two-numbers-in-an-array +tags: + - Array + - Hash Table + - Bit Manipulation + - Trie +description: "This is a solution to the maximum xor of two numbers in an array problem on LeetCode." +--- + +## Problem Description + +Given an integer array `nums`, return the maximum result of `nums[i] XOR nums[j]`, where `0 <= i <= j < n`. + +### Examples + +**Example 1:** + +``` +Input: nums = [3,10,5,25,2,8] +Output: 28 +Explanation: The maximum result is 5 XOR 25 = 28. +``` + +**Example 2:** + +``` +Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70] +Output: 127 +``` + +### Constraints + +- `1 <= nums.length <= 2 * 105` +- `0 <= nums[i] <= 231 - 1` + +## Solution for Strong Password Checker + +### Approach + +XOR, or exclusive OR, is a binary bitwise operation that returns true (1) only when the operands differ. If the bits are the same, the result is 0. If the bits are different, the result is 1. + +The goal is to maximise the XOR result between two numbers This is achieved by ensuring for each bit position, the XOR result is maximum hence we want to maximise the number of opposite bits between the numbers. + +We use a Trie which allows us to iterate through each bit of the numbers in the array and maximise XOR value by selecting the opposite bit when available hence ensuring the highest possible XOR result. + +Step 1:Create a Trie Node Structure. This structure represents a node in the Trie. + +- It contains an array (β€˜links’) to store links to child nodes (0 and 1). +- Provides methods to interact with the child nodes like β€˜containsKey’, β€˜get’ and β€˜put’. + +Step 2: Iterate through the given array and insert its bit values into the Trie from left to right. + +- For each number, check if the current node has a child node with the current bit. If not, create a new child node with the current bit. +- Move to the child node corresponding to the current bit. + +Step 3: Start from the root node. Initialise the maximum XOR values as 0. + +Step 4: Iterate through each bit of the number (from left to right). Check if the complement of the current bit exists in the Trie. If so: + +- Update the maximum XOR value with the current bit. +- Moves to the child node corresponding to the complement of the current bit. + +## Code in Different Languages + + + + + +```cpp +class Solution { + public: + int findMaximumXOR(vector& nums) { + const int maxNum = ranges::max(nums); + if (maxNum == 0) + return 0; + const int maxBit = static_cast(log2(maxNum)); + int ans = 0; + int prefixMask = 0; // Grows like: 10000 -> 11000 -> ... -> 11111. + + // If ans is 11100 when i = 2, it means that before we reach the last two + // bits, 11100 is the maximum XOR we have, and we're going to explore if we + // can get another two 1s and put them into `ans`. + for (int i = maxBit; i >= 0; --i) { + prefixMask |= 1 << i; + unordered_set prefixes; + // We only care about the left parts, + // If i = 2, nums = {1110, 1011, 0111} + // -> prefixes = {1100, 1000, 0100} + for (const int num : nums) + prefixes.insert(num & prefixMask); + // If i = 1 and before this iteration, the ans is 10100, it means that we + // want to grow the ans to 10100 | 1 << 1 = 10110 and we're looking for + // XOR of two prefixes = candidate. + const int candidate = ans | 1 << i; + for (const int prefix : prefixes) + if (prefixes.count(prefix ^ candidate)) { + ans = candidate; + break; + } + } + + return ans; + } +}; +``` + + + + +```java +class Solution { + public int findMaximumXOR(int[] nums) { + final int maxNum = Arrays.stream(nums).max().getAsInt(); + if (maxNum == 0) + return 0; + final int maxBit = (int) (Math.log(maxNum) / Math.log(2)); + int ans = 0; + int prefixMask = 0; // Grows like: 10000 -> 11000 -> ... -> 11111. + + // If ans is 11100 when i = 2, it means that before we reach the last two + // bits, 11100 is the maximum XOR we have, and we're going to explore if we + // can get another two 1s and put them into `ans`. + for (int i = maxBit; i >= 0; --i) { + prefixMask |= 1 << i; + Set prefixes = new HashSet<>(); + // We only care about the left parts, + // If i = 2, nums = {1110, 1011, 0111} + // . prefixes = {1100, 1000, 0100} + for (final int num : nums) + prefixes.add(num & prefixMask); + // If i = 1 and before this iteration, the ans is 10100, it means that we + // want to grow the ans to 10100 | 1 << 1 = 10110 and we're looking for + // XOR of two prefixes = candidate. + final int candidate = ans | 1 << i; + for (final int prefix : prefixes) + if (prefixes.contains(prefix ^ candidate)) { + ans = candidate; + break; + } + } + + return ans; + } +} +``` + + + + + +```python +class Solution: + def findMaximumXOR(self, nums: List[int]) -> int: + maxNum = max(nums) + if maxNum == 0: + return 0 + maxBit = int(math.log2(maxNum)) + ans = 0 + prefixMask = 0 # `prefixMask` grows like: 10000 -> 11000 -> ... -> 11111. + + # If ans is 11100 when i = 2, it means that before we reach the last two + # bits, 11100 is the maximum XOR we have, and we're going to explore if we + # can get another two 1s and put them into `ans`. + for i in range(maxBit, -1, -1): + prefixMask |= 1 << i + # We only care about the left parts, + # If i = 2, nums = [1110, 1011, 0111] + # -> prefixes = [1100, 1000, 0100] + prefixes = set([num & prefixMask for num in nums]) + # If i = 1 and before this iteration, the ans is 10100, it means that we + # want to grow the ans to 10100 | 1 << 1 = 10110 and we're looking for + # XOR of two prefixes = candidate. + candidate = ans | 1 << i + for prefix in prefixes: + if prefix ^ candidate in prefixes: + ans = candidate + break + + return ans +``` + + + +## Complexity Analysis + +### Time Complexity: O(nlog(max(nums))) + +### Space Complexity: O(N) \ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0430-flatten-a-multilevel-doubly-linked-list.md b/solutions/lc-solutions/0400-0499/0430-flatten-a-multilevel-doubly-linked-list.md new file mode 100644 index 0000000..5adce72 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0430-flatten-a-multilevel-doubly-linked-list.md @@ -0,0 +1,311 @@ +--- +id: flatten-a-multilevel-doubly-linked-list +title: Flatten a Multilevel Doubly Linked List +sidebar_label: 0430 - Flatten a Multilevel Doubly Linked List +tags: +- Linked List +- Depth-First Search +- Doubly-Linked List +description: "This is a solution to the Flatten a Multilevel Doubly Linked List problem on LeetCode." +--- + +## Problem Description +You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. + +Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. + +Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null. +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2021/11/09/flatten11.jpg) +``` +Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] +Output: [1,2,3,7,8,11,12,9,10,4,5,6] +Explanation: The multilevel linked list in the input is shown. +``` +###### After flattening the multilevel linked list it becomes: + +![image](https://assets.leetcode.com/uploads/2021/11/09/flatten12.jpg) +**Example 2:** +![image](https://assets.leetcode.com/uploads/2021/11/09/flatten2.1jpg) +``` +Input: head = [1,2,null,3] +Output: [1,3,2] +Explanation: The multilevel linked list in the input is shown. +``` +**Example 3:** +``` +Input: head = [] +Output: [] +Explanation: There could be empty list in the input. +``` + +### Constraints +- The number of Nodes will not exceed 1000. +- `1 <= Node.val <= 10^5` + +## Solution for Flatten a Multilevel Doubly Linked List + +### Approach +- Recursively traverse the original linked list, pushing nodes into a vector in the order they are visited, considering child nodes first. +- Construct a flattened linked list from this vector, ensuring proper connections between nodes. + + + + +#### Implementation + +```jsx live +function Node(val, prev = null, next = null, child = null) { + return { + val: val, + prev: prev, + next: next, + child: child + }; +} + +function flatten(head) { + if (!head) return null; + + let stack = [head]; + let dummy = new Node(0); + let prev = dummy; + + while (stack.length > 0) { + let current = stack.pop(); + + if (current.next) stack.push(current.next); + if (current.child) { + stack.push(current.child); + current.child = null; + } + + prev.next = current; + current.prev = prev; + prev = current; + } + + dummy.next.prev = null; + return dummy.next; +} + +const input = [1, 2, 3, 4, 5, 6, null, null, null, 7, 8, 9, 10, null, null, 11, 12]; + +// Construct the linked list from the input array +let head = new Node(input[0]); +let current = head; +let stack = [head]; +for (let i = 1; i < input.length; i++) { + if (input[i] === null) continue; + let newNode = new Node(input[i]); + current.next = newNode; + newNode.prev = current; + current = newNode; + if (input[i] !== null) { + stack.push(current); + } +} + +// Link child nodes +for (let i = 0; i < input.length; i++) { + if (input[i] === null) { + let parent = stack.pop(); + parent.child = parent.next; + parent.next = null; + if (parent.child) parent.child.prev = null; + } +} + +// Flatten the linked list +let output = flatten(head); + +return ( +
+

+ Input: {JSON.stringify(input)} +

+

+ Output: {output ? output.toString() : 'null'} +

+
+); +``` + +### Code in Different Languages + + + + + ```javascript +var flatten = function(head) { + const arr = []; + const helper = (node) => { + if(!node) return; + arr.push(node); + helper(node.child); + helper(node.next); + }; + helper(head); + for(let i = 0; i < arr.length; i++) { + arr[i].prev = arr[i-1] || null; + arr[i].next = arr[i+1] || null; + arr[i].child = null; + } + return arr[0] || null; +}; + ``` + + + + ```typescript + function flatten(head: Node | null): Node | null { + if (!head) return null; + + let pseudoHead: Node = new Node(0); + + flattenDFS(pseudoHead, head); + + pseudoHead.next.prev = null; + return pseudoHead.next; +}; + +function flattenDFS(prev: Node, curr: Node | null): Node | null { + if (!curr) return prev; + + // Connect nodes + curr.prev = prev; + prev.next = curr; + + let tempNext: Node | null = curr.next; + let tail = flattenDFS(curr, curr.child); + + // Clean child + curr.child = null; + + return flattenDFS(tail, tempNext); +} + ``` + + + + ```python + class Solution: + def flatten(self, head: 'Node') -> 'Node': + def getTail(node): + prev = None + while node: + _next = node.next + if node.child: + # ... <-> node <-> node.child <-> ... + node.next = node.child + node.child = None + node.next.prev = node + # get the end node of the node.child list + prev = getTail(node.next) + if _next: + # ... <-> prev (end node) <-> _next (originally node.next) <-> ... + _next.prev = prev + prev.next = _next + else: + prev = node + node = _next # loop through the list of nodes + return prev # return end node + + getTail(head) + return head + ``` + + + + +``` +class Solution { + + Node prev = null; + + public Node flatten(Node head) { + dfsHelper(head); + return head; + } + + public void dfsHelper(Node current) { + if (current == null) return; + // postorder traversal, going right first or next in this case + dfsHelper(current.next); + dfsHelper(current.child); + // don't forget to set prev.prev pointer + if (prev != null) prev.prev = current; + // see explanation below + current.next = prev; + current.child = null; + prev = current; + } +} +``` + + + + +```cpp +class Node { +public: + int val; + Node* prev; + Node* next; + Node* child; +}; + + void solve(Node *head, vector& ans, Node *curr) { + if (curr == NULL) { + return; + } + ans.push_back(curr); + if (curr->child) { + solve(head, ans, curr->child); + } + if (curr->next) { + solve(head, ans, curr->next); + } + } + + Node* flatten(Node* head) { + if (!head) return nullptr; + vector ans; + Node *curr = head; + solve(head, ans, curr); + + Node *newHead = NULL; + curr = NULL; + + for (int i = 0; i < ans.size(); i++) { + if (curr == NULL) { + curr = ans[i]; + newHead = ans[i]; + } else { + curr->next = ans[i]; + curr->next->prev = curr; + curr->child = NULL; + curr = curr->next; + } + } + return newHead; +} + +``` + + + +#### Complexity Analysis +- Time Complexity: $ O(N)$ + - Space Complexity: $ O(N)$ +
+
+ +## References + +- **LeetCode Problem**: [Count Primes](https://leetcode.com/problems/count-primes/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/count-primes/solutions) + diff --git a/solutions/lc-solutions/0400-0499/0436-find-right-interval.md b/solutions/lc-solutions/0400-0499/0436-find-right-interval.md new file mode 100644 index 0000000..d68237c --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0436-find-right-interval.md @@ -0,0 +1,236 @@ +--- +id: find-right-interval +title: Find Right Interval +sidebar_label: 0436 - Find Right Interval +tags: +- Binary Search +- Binary Tree +- Sorting +description: "This is a solution to the Find Right Interval problem on LeetCode." +--- + +## Problem Description + +You are given an array of intervals, where intervals[i] = [$\text{start}_i$, $\text{end}_i$] and each $\text{start}_i$ is **unique**. + +The **right interval** for an interval i is an interval j such that $\text{start}_j$ >= $\text{end}_j$ and $\text{start}_j$ is **minimized**. Note that i may equal j. + +Return an array of **right interval** indices for each interval i. If no **right interval** exists for interval i, then put -1 at index i. + +### Examples + +**Example 1:** + +``` +Input: intervals = [[1,2]] +Output: [-1] +Explanation: There is only one interval in the collection, so it outputs -1. +``` + +**Example 2:** + +``` +Input: intervals = [[1,4],[2,3],[3,4]] +Output: [-1,2,-1] +Explanation: There is no right interval for [1,4] and [3,4]. +The right interval for [2,3] is [3,4] since start2 = 3 is the smallest start that is >= end1 = 3. +``` + +### Constraints + +- `1 <= intervals.length <= 2 * 104` +- `intervals[i].length == 2` +- $-10^6 \leq \text{start}_i \leq \text{end}_i \leq 10^6$ +- The start point of each interval is **unique**. + +## Solution for Find Right Interval + +### Intuition + +The problem at hand requires finding the "right interval" for each interval in a list. A right interval for an interval i is defined as the smallest interval j such that the start of j is greater than or equal to the end of i. If no such interval exists, the result should be -1. + +### Approach + +1. **Data Transformation:** Start by transforming the given intervals into a new array where each element keeps track of the original start and end points as well as the original index. This helps in maintaining the reference to the original indices after sorting. + +2. **Sorting:** Sort the transformed array based on the start points. Sorting helps in efficiently searching for the right interval using binary search. + +3. **Binary Search:** For each interval in the sorted array, use binary search to find the smallest interval whose start is greater than or equal to the end of the current interval. The binary search operates over the sorted start points. + +4. **Mapping Results:** The result of the binary search for each interval gives the index of the right interval in the sorted array. This index is then mapped back to the original index using the stored original index in the transformed array. + +5. **Output Formation:** Construct the output array where each position corresponds to the original interval's right interval index. + +## Code in Different Languages + + + + + +```cpp +#include +#include + +class Solution { +public: + std::vector findRightInterval(std::vector>& intv) { + int n = intv.size(); + std::vector> arr(n, std::vector(3)); + + for (int i = 0; i < n; ++i) { + arr[i][0] = intv[i][0]; + arr[i][1] = intv[i][1]; + arr[i][2] = i; + } + + std::sort(arr.begin(), arr.end(), [](const std::vector& a, const std::vector& b) { + return a[0] < b[0]; + }); + + std::vector ans(n); + for (int i = 0; i < n; ++i) { + ans[arr[i][2]] = binarySearch(arr, i, n - 1, arr[i][1]); + } + + return ans; + } + +private: + int binarySearch(const std::vector>& arr, int low, int high, int target) { + int result = -1; + + while (low <= high) { + int mid = low + (high - low) / 2; + + if (arr[mid][0] >= target) { + result = arr[mid][2]; + high = mid - 1; + } else { + low = mid + 1; + } + } + return result; + } +}; + +``` + + + + +```java +class Solution { + public int[] findRightInterval(int[][] intv) { + int n=intv.length; + int [][] arr=new int[n][3]; + + for(int i=0;ia[0]-b[0]); + +int ans[]=new int[n]; + for(int i=0;i= target) { + result = arr[mid][2]; + high = mid - 1; + } else { + low = mid + 1; + } + } + return result; + + + } +} +``` + + + + + +```python +from typing import List + +class Solution: + def findRightInterval(self, intv: List[List[int]]) -> List[int]: + n = len(intv) + arr = [[0, 0, 0] for _ in range(n)] + + for i in range(n): + arr[i][0] = intv[i][0] + arr[i][1] = intv[i][1] + arr[i][2] = i + + arr.sort(key=lambda x: x[0]) + + ans = [0] * n + for i in range(n): + ans[arr[i][2]] = self.binary_search(arr, i, n - 1, arr[i][1]) + + return ans + + def binary_search(self, arr: List[List[int]], low: int, high: int, target: int) -> int: + result = -1 + + while low <= high: + mid = low + (high - low) // 2 + + if arr[mid][0] >= target: + result = arr[mid][2] + high = mid - 1 + else: + low = mid + 1 + + return result + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(Nlog(N))$ + +> **Reason**: The time complexity of the algorithm is O(Nlog(N)), where N is the number of intervals. Sorting the array takes O(Nlog(N)), and for each interval, a binary search takes O(log(N)), leading to O(Nlog(N)) overall due to the N binary searches. + +### Space Complexity: $O(N)$ + +> **Reason**: This space is used for the transformed array and the output array. + +## References + +- **LeetCode Problem**: [Find Right Interval](https://leetcode.com/problems/find-right-interval/description/) + +- **Solution Link**: [Find Right Interval](https://leetcode.com/problems/find-right-interval/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/0400-0499/0437-path-sum-iii.md b/solutions/lc-solutions/0400-0499/0437-path-sum-iii.md new file mode 100644 index 0000000..c281cb1 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0437-path-sum-iii.md @@ -0,0 +1,374 @@ +--- +id: path-sum-iii +title: Path Sum III +sidebar_label: 0437 - Path Sum III +tags: +- Tree +- Depth-First Search +- Binary Tree +description: "This is a solution to the Path Sum III problem on LeetCode." +--- + +## Problem Description +Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum. +The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2021/04/09/pathsum3-1-tree.jpg) +``` +Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 +Output: 3 +Explanation: The paths that sum to 8 are shown. +``` + +**Example 2:** +``` +Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 +Output: 3 +``` + +### Constraints +- The number of nodes in the tree is in the range [0, 1000]. +- `-10^9 <= Node.val <= 10^9` +- `-1000 <= targetSum <= 1000` + +## Solution for Path Sum III + +### Approach +#### Tree Traversal: + +- The main idea is to traverse the binary tree. This is achieved using a recursive function solve that explores all nodes starting from the root. +- The traversal is done using Depth First Search (DFS), ensuring all possible paths from the root to the leaves are explored. +#### Path Tracking: +- During traversal, we maintain a path vector that keeps track of the nodes' values along the current path from the root to the current node. +- As we visit each node, its value is added to the path. +#### Path Sum Calculation: +- After adding a node’s value to the path, we check all sub-paths ending at the current node to see if any of them sum to the targetSum. +- We iterate backwards through the path vector, accumulating the sum and checking if it matches the targetSum. +- If a sub-path's sum matches targetSum, we increment the count. +#### Backtracking: +- After checking the sub-paths for the current node, we backtrack by removing the current node's value from the path. +- This ensures that the path vector only contains nodes along the current path in the DFS traversal. + + + + +#### Implementation + +```jsx live +function pathSum3() { + function TreeNode(val = 0, left = null, right = null) { + this.val = val; + this.left = left; + this.right = right; +} + +function constructTreeFromArray(array) { + if (!array.length) return null; + + let root = new TreeNode(array[0]); + let queue = [root]; + let i = 1; + + while (i < array.length) { + let currentNode = queue.shift(); + + if (array[i] !== null) { + currentNode.left = new TreeNode(array[i]); + queue.push(currentNode.left); + } + i++; + + if (i < array.length && array[i] !== null) { + currentNode.right = new TreeNode(array[i]); + queue.push(currentNode.right); + } + i++; + } + return root; +} +function pathSum(root, targetSum) { + // Map to keep the cumulative sum and its frequency. + const prefixSumCount = new Map(); + + // Helper function to perform DFS on the tree and calculate paths. + function dfs(node, currentSum) { + if (!node) { + return 0; + } + // Update the current sum by adding the node's value. + currentSum += node.val; + + // Get the number of times we have seen the currentSum - targetSum. + let pathCount = prefixSumCount.get(currentSum - targetSum) || 0; + + // Update the count of the current sum in the map. + prefixSumCount.set(currentSum, (prefixSumCount.get(currentSum) || 0) + 1); + + // Explore left and right subtrees. + pathCount += dfs(node.left, currentSum); + pathCount += dfs(node.right, currentSum); + + // After returning from the recursion, decrement the frequency of the current sum. + prefixSumCount.set(currentSum, (prefixSumCount.get(currentSum) || 0) - 1); + + // Return the total count of paths found. + return pathCount; + } + + // Initialize the map with base case before the recursion. + prefixSumCount.set(0, 1); + + // Start DFS from the root node with an initial sum of 0. + return dfs(root, 0); +} + +const array =[10, 5, -3, 3, 2, null, 11, 3, -2, null, 1]; +const root = constructTreeFromArray(array) +const input = root +const targetSum = 8; +const output = pathSum(input ,targetSum) + return ( +
+

+ Input: {JSON.stringify(array)} +

+

+ Output: {output.toString()} +

+
+ ); +} +``` + +### Code in Different Languages + + + + + ```javascript + function TreeNode(val, left = null, right = null) { + return { + val: val, + left: left, + right: right + }; +} + +function pathSum3(root, targetSum) { + function solve(node, targetSum, count, path) { + if (!node) { + return; + } + path.push(node.val); + pathSumHelper(node, targetSum, count, path); + solve(node.left, targetSum, count, path.slice()); + solve(node.right, targetSum, count, path.slice()); + } + + function pathSumHelper(node, targetSum, count, path) { + let sum = 0; + for (let i = path.length - 1; i >= 0; i--) { + sum += path[i]; + if (sum === targetSum) { + count[0]++; + } + } + } + + const path = []; + const count = [0]; + solve(root, targetSum, count, path); + return count[0]; +} +``` + + + + ```typescript + interface TreeNode { + val: number; + left?: TreeNode | null; + right?: TreeNode | null; +} + +function solve(root: TreeNode | null, targetSum: number, count: number[], path: number[]): void { + if (!root) { + return; + } + path.push(root.val); + pathSumHelper(root, targetSum, count, path); + solve(root.left, targetSum, count, path.slice()); + solve(root.right, targetSum, count, path.slice()); +} + +function pathSumHelper(node: TreeNode, targetSum: number, count: number[], path: number[]): void { + let sum = 0; + for (let i = path.length - 1; i >= 0; i--) { + sum += path[i]; + if (sum === targetSum) { + count[0]++; + } + } +} + +function pathSum(root: TreeNode | null, targetSum: number): number { + const path: number[] = []; + const count: number[] = [0]; + solve(root, targetSum, count, path); + return count[0]; +} + ``` + + + + ```python + class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def solve(self, root, targetSum, count, path): + if not root: + return + path.append(root.val) + self.path_sum_helper(root, targetSum, count, path) + self.solve(root.left, targetSum, count, path[:]) + self.solve(root.right, targetSum, count, path[:]) + + def path_sum_helper(self, node, targetSum, count, path): + _sum = 0 + for val in reversed(path): + _sum += val + if _sum == targetSum: + count[0] += 1 + + def pathSum(self, root, targetSum): + path = [] + count = [0] + self.solve(root, targetSum, count, path) + return count[0] + + ``` + + + + +``` +import java.util.ArrayList; +import java.util.List; + +class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode() {} + + TreeNode(int val) { + this.val = val; + } + + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } +} + +public class Solution { + public void solve(TreeNode root, int targetSum, int[] count, List path) { + if (root == null) { + return; + } + path.add(root.val); + pathSumHelper(root, targetSum, count, path); + solve(root.left, targetSum, count, new ArrayList<>(path)); + solve(root.right, targetSum, count, new ArrayList<>(path)); + } + + public void pathSumHelper(TreeNode node, int targetSum, int[] count, List path) { + int sum = 0; + for (int i = path.size() - 1; i >= 0; i--) { + sum += path.get(i); + if (sum == targetSum) { + count[0]++; + } + } + } + + public int pathSum(TreeNode root, int targetSum) { + List path = new ArrayList<>(); + int[] count = new int[1]; + solve(root, targetSum, count, path); + return count[0]; + } +} + +``` + + + + +```cpp + struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + }; + void solve(TreeNode * root,int targetSum,int &count,vectorpath) + { + if(root==NULL) + { + return; + } + path.push_back(root->val); + solve(root->left,targetSum,count,path); + solve(root->right,targetSum,count,path); + + int size=path.size(); + long long sum=0; + for(int i=size-1;i>=0;i--) + { + sum+=path[i]; + if(sum==targetSum) + count++; + } + path.pop_back(); + } + int pathSum(TreeNode* root, int targetSum) { + vectorpath; + int count=0; + solve(root,targetSum,count,path); + return count; + } +``` + + + +#### Complexity Analysis + ##### Time Complexity: +- Tree Traversal (DFS): +We visit each node exactly once during the Depth First Search (DFS). For a binary tree with n nodes, this traversal takes $O(n)$ time. + +- Sub-Path Sum Calculation: +At each node, we check all sub-paths ending at that node. The maximum number of sub-paths to check is equal to the depth of the tree, which in the worst case (a skewed tree) is +$O(n)$.Thus, for each node, the sum checking operation takes $O(n)$ in the worst case. +Combining these two parts, the total time complexity is +$O(n)$Γ—$O(n)$=$O(n^2)$ in the worst case. + ##### Space Complexity: $O(N)$ +
+
+ +## References + +- **LeetCode Problem**: [Path Sum III](https://leetcode.com/problems/path-sum-iii/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/path-sum-iii/solutions) + diff --git a/solutions/lc-solutions/0400-0499/0440-k-th-smallest-in-lexicographical-order.md b/solutions/lc-solutions/0400-0499/0440-k-th-smallest-in-lexicographical-order.md new file mode 100644 index 0000000..8e64fa1 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0440-k-th-smallest-in-lexicographical-order.md @@ -0,0 +1,164 @@ +--- +id: k-th-smallest-in-lexicographical-order +title: K-th Smallest in Lexicographical Order +sidebar_label: 0440 - k-th-smallest-in-lexicographical-order +tags: + - Trie +description: "Return the kth lexicographically smallest integer." +--- + +## Problem Description + +Given two integers `n` and `k`, return the kth lexicographically smallest integer in the range `[1, n]`. + +### Examples + +**Example 1:** + +``` +Input: n = 13, k = 2 +Output: 10 +Explanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. +``` + +**Example 2:** + +``` +Input: n = 1, k = 1 +Output: 1 + +``` + +### Constraints + +- `1 <= k <= n <= 10^9` + + +## Solution for K-th Smallest in Lexicographical Order. + +### Approach +Iterating through potential prefixes (result, result*10, etc.), counting numbers within each prefix range that fall within [1, n], and adjusting the prefix based on whether the count meets or exceeds k, ensuring the retrieval of the k-th lexicographical number efficiently. + +#### Intuition +Lexicographical order means dictionary order. For any number result, numbers prefixed by result are essentially the numbers starting from result up to the next increment of `result`. + +#### Algorithm + +1. Calculate the number of numbers that prefix with result. +Numbers prefixed by result are the union of the following intervals: +[result, result+1) +[result*10, (result+1)*10 ) +[result*100, (result+1)*100 ) +... +But they also shall belong to [1, n] +Therefore, we can easily calculate the number of elements prefixed by result. + +2. Search the next prefix, or search more detailedly. + If the number of numbers that prefixed by result is smaller than the remaining k, we do not need to consider the numbers prefixed by result any more, and march to the next prefix: result+1; + Otherwise, we need to search more detailedly, by appending another digit to the prefix. Such search shall start with result*10. + + +## Code in Different Languages + +### C++ + +```cpp +class Solution { +public: + int findKthNumber(int n, int k) + { + int result = 1; + for(--k; k > 0; ) + { + // calculate #|{result, result*, result**, result***, ...}| + int count = 0; + for (long long first = static_cast(result), last = first + 1; + first <= n; // the interval is not empty + first *= 10, last *= 10) // increase a digit + { + // valid interval = [first, last) union [first, n] + count += static_cast((min(n + 1LL, last) - first)); // add the length of interval + } + + if (k >= count) + { // skip {result, result*, result**, result***, ...} + // increase the current prefix + ++result; + k -= count; + } + else + { // not able to skip all of {result, result*, result**, result***, ...} + // search more detailedly + result *= 10; + --k; + } + } + return result; + } +}; + + +``` +### JAVA +```java + public class Solution { + public int findKthNumber(int n, int k) { + int result = 1; + k--; // adjust k to be zero-indexed + while (k > 0) { + int count = 0; + long first = result; + long last = first + 1; + while (first <= n) { + count += Math.min(n + 1, last) - first; // add the length of interval + first *= 10; + last *= 10; + } + if (k >= count) { + // Skip all numbers starting with 'result' + result++; + k -= count; + } else { + // Move to the next level of prefix + result *= 10; + k--; + } + } + return result; + } +} +``` + +### PYTHON +```python +class Solution(object): + def findKthNumber(self, n, k): + result = 1; + k -= 1 + while k > 0: + count = 0 + interval = [result, result+1] + while interval[0] <= n: + count += (min(n+1, interval[1]) - interval[0]) + interval = [10*interval[0], 10*interval[1]] + + if k >= count: + result += 1 + k -= count + else: + result *= 10 + k -= 1 + return result +``` + +## Complexity Analysis + +### Time Complexity: $O((logn)^2)$ + +> **Reason**: Here, logn is the number of digits in n, and it is also the number of replications of appending zero to search detailedly. Each such appending introduces the increasement of prefix at most 10 times, and each increasement may require O(logn) time to calculate the number of numbers that prefixed by the `result`. + +### Space Complexity: $O(1)$ + +## References + +- **LeetCode Problem**: [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/description/) diff --git a/solutions/lc-solutions/0400-0499/0442-Find-All-Duplicates-in-an-Array.md b/solutions/lc-solutions/0400-0499/0442-Find-All-Duplicates-in-an-Array.md new file mode 100644 index 0000000..a4e2604 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0442-Find-All-Duplicates-in-an-Array.md @@ -0,0 +1,159 @@ +--- +id: find-all-duplicates-in-an-array +title: find-all-duplicates-in-an-array +sidebar_label: 0442 find-all-duplicates-in-an-array +tags: + - hashmap + - LeetCode + - Java + - Python + - C++ +description: This is a solution to the. Find All Duplicates in an Array problem on LeetCode +--- + +## Problem Description + +Given an integer array nums of length n where all the integers of nums are in the range `[1, n]` and each integer appears once or twice, return an array of all the integers that appears twice. + +You must write an algorithm that runs in $O(n)$ time and uses only constant extra space. + +### Examples + +**Example 1:** + +``` + +Input: nums = [4,3,2,7,8,2,3,1] +Output: [2,3] + +``` + +**Example 2:** + + +``` +Input: nums = [1,1,2] +Output: [1] +``` + +**Example 3:** + + +``` +Input: nums = [1] +Output: [] +``` + + +### Constraints + +- $1 \leq \text{nums.length} \leq 105$ +- Each element in nums appears once or twice. + + +--- + +## Solution for Find All Duplicates in an Array + +### Intuition + + - Since each element in the array represents a valid index `(1 to n)`, we can leverage this information. + - We might be able to sort the array and then compare adjacent elements to find duplicates efficiently. + + + +### Approach + + - Utilize existing order: We know that each element should appear at most twice and all values are in the range `[1, n]`. This suggests some inherent order in the array. + - Leverage sorting: By sorting the array, we can group duplicate elements together, making them easier to identify. + - Iterate and compare: After sorting, iterating through the array, we can compare adjacent elements. If two consecutive elements are identical, that element is a duplicate. + + + + + +#### Code in Different Languages + + + + + + ```python +//python + +class Solution: + def findDuplicates(self, nums: List[int]) -> List[int]: + ans =[] + n=len(nums) + for x in nums: + x = abs(x) + if nums[x-1]<0: + ans.append(x) + nums[x-1] *= -1 + return ans + +``` + + + + + ```java +//java + + +class Solution { + public List findDuplicates(int[] nums) { + List ans = new ArrayList<>(); + int n = nums.length; + for (int i = 0; i < n; i++) { + int x = Math.abs(nums[i]); + if (nums[x - 1] < 0) { + ans.add(x); + } + nums[x - 1] *= -1; + } + return ans; + } +} + + +``` + + + + + ```cpp +//cpp + +class Solution { +public: + vector findDuplicates(vector& nums) { + vectorans; + int n=size(nums); + for(int i=0;i + + + + + + +## References + +- **LeetCode Problem:** [Continuous Subarray Sum](https://leetcode.com/problems/find-all-duplicates-in-an-array/) +- **Solution Link:** [Continuous Subarray Sum](https://leetcode.com/problems/find-all-duplicates-in-an-array/submissions/) +- **Authors GeeksforGeeks Profile:** [parikhit kurmi](https://www.geeksforgeeks.org/user/sololeveler673/) +- **Authors Leetcode:** [parikhit kurmi](https://leetcode.com/u/parikhitkurmi14/) \ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0443-string-compression.md b/solutions/lc-solutions/0400-0499/0443-string-compression.md new file mode 100644 index 0000000..d2e424b --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0443-string-compression.md @@ -0,0 +1,177 @@ +--- +id: string-compression +title: String Compression +sidebar_label: 0443 - String Compression +tags: + - Two Pointers + - Array + - Sliding Window +description: "This is a solution to the String Compression problem on LeetCode." +--- + +## Problem Description + +Given an array of characters `chars`, compress it using the following algorithm: + +Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`: + +If the group's length is `1`, append the character to `s`. +Otherwise, append the character followed by the group's length. +The compressed string s **should not be returned separately**, but instead, be stored **in the input character array** `chars`. Note that group lengths that are `10` or longer will be split into multiple characters in `chars`. + +After you are done **modifying the input array**, return the new length of the array. + +You must write an algorithm that uses only constant extra space. + +### Examples + +**Example 1:** + +``` +Input: chars = ["a","a","b","b","c","c","c"] +Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] +Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3". +``` + +**Example 2:** + +``` +Input: chars = ["a"] +Output: Return 1, and the first character of the input array should be: ["a"] +Explanation: The only group is "a", which remains uncompressed since it's a single character. +``` + +### Constraints + +- `1 <= chars.length <= 2000` +- `chars[i]` is a lowercase English letter, uppercase English letter, digit, or symbol. + +## Solution for String Compression + +### Approach + +#### Intuition + +First, we make the following observation. Consider a group `t` of consecutive repeating characters. The length of compressed `t` is less than or equal to the length of `t`. For example, `d` tranforms into `d`, `cc` into `c2`, `aaaa` into `a4`, `bbbbbbbbbbbb` into `b12`. + +This observation allows processing groups in the array `chars` from left to right. + +#### Algorithm + +1. Declare the variables i – the first index of the current group, and res – the length of the answer (of the compressed string). Initialize i = 0, res = 0. + +2. While i is less than the length of chars: + - Find the length of the current group of consecutive repeating characters groupLength. + - Add chars[i] to the answer (chars[res++] = chars[i]). + - If groupLength > 1, add the string representation of groupLength to the answer and increase res accordingly. + - Increase i by groupLength and proceed to the next group. + +3. Return res. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + int compress(vector& chars) { + int i = 0, res = 0; + while (i < chars.size()) { + int groupLength = 1; + while (i + groupLength < chars.size() && chars[i + groupLength] == chars[i]) { + groupLength++; + } + chars[res++] = chars[i]; + if (groupLength > 1) { + for (char c : to_string(groupLength)) { + chars[res++] = c; + } + } + i += groupLength; + } + return res; + } +}; + + +``` + + + + +```java +class Solution { + public int compress(char[] chars) { + int i = 0, res = 0; + while (i < chars.length) { + int groupLength = 1; + while (i + groupLength < chars.length && chars[i + groupLength] == chars[i]) { + groupLength++; + } + chars[res++] = chars[i]; + if (groupLength > 1) { + for (char c : Integer.toString(groupLength).toCharArray()) { + chars[res++] = c; + } + } + i += groupLength; + } + return res; + } +} +``` + + + + + +```python +class Solution: + def compress(self, chars: List[str]) -> int: + i = 0 + res = 0 + while i < len(chars): + group_length = 1 + while (i + group_length < len(chars) + and chars[i + group_length] == chars[i]): + group_length += 1 + chars[res] = chars[i] + res += 1 + if group_length > 1: + str_repr = str(group_length) + chars[res:res+len(str_repr)] = list(str_repr) + res += len(str_repr) + i += group_length + return res +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: All cells are initially white. We will repaint each white cell blue, and we may repaint some blue cells green. Thus each cell will be repainted at most twice. Since there are n cells, the total number of repaintings is O(n). + +### Space Complexity: $O(1)$ + +> **Reason**: We store only a few integer variables and the string representation of groupLength which takes up O(1) space. + +## References + +- **LeetCode Problem**: [String Compression](https://leetcode.com/problems/string-compression/description/) + +- **Solution Link**: [String Compression](https://leetcode.com/problems/string-compression/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0445-add-two-numberii.md b/solutions/lc-solutions/0400-0499/0445-add-two-numberii.md new file mode 100644 index 0000000..e916e4c --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0445-add-two-numberii.md @@ -0,0 +1,416 @@ +--- +id: add-two-numbers-ii +title: Add Two Numbers II +sidebar_label: 0445 - Add Two Numbers II +tags: +- Linked List +- Stack +- Recursion +description: "This is a solution to the Add Two Numbers II problem on LeetCode." +--- + +## Problem Description + +You are given two `non-empty` linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. + +You may assume the two numbers do not contain any leading zero, except the number 0 itself. + +### Examples + +**Example 1:** + +![image](https://assets.leetcode.com/uploads/2021/04/09/sumii-linked-list.jpg) +``` +Input: l1 = [7,2,4,3], l2 = [5,6,4] +Output: [7,8,0,7] +``` + +**Example 2:** + +``` +Input: l1 = [2,4,3], l2 = [5,6,4] +Output: [8,0,7] +``` + +### Constraints + +- The number of nodes in each linked list is in the range `[1, 100]`. +- `0 <= Node.val <= 9` +- It is guaranteed that the list represents a number that does not have leading zeros. + +## Solution for Add Two Numbers II + +### Approach 1: Reverse Given Linked Lists + +#### Intuition + +We are told that the most significant digit comes first, and that each of their nodes includes a single digit. To do a basic addition of two numbers using a sum of two digits and a carry, we must start with the least significant digits (the lowest place) and work our way up to the most significant digits. + +To get the order of digits from the least significant digits to the the most significant digits, we can reverse the given lists so the least significant digits come first. + +We can then iterate over the reversed lists to perform the addition of digits at corresponding places similar to the first approach. + +Let's understand how to reverse a linked list. + +To reverse a linked list, we need three pointers. The first pointer `head` points to the current node under consideration, `temp` points to the next node, and `prev` points to the previous node. This is because while traversing the list, we change the current node's (`head`) next pointer to point to its previous element (`prev`). Since a node does not have reference to its previous node, we must store its previous element beforehand. We also need another pointer to store the next node (`temp`) before changing the reference so we don't lose it after changing `head.next`. + +We start with initializing `prev` to `null`. We then loop until `head` is null, i.e., until we iterate over all the elements. We store `head.next` in `temp` to store the next node we will go to. After storing the next node, we reverse `next` of `head` to the previous element, i.e., `head.next = prev`. We then move `prev` to `head` as this becomes the previous node for the next node and also move `head` to `temp` as this becomes the new node under consideration. + +#### Algorithm + +1. Create two linked lists `r1` and `r2` to store the reverse of the linked lists `l1` and `l2` respectively. +2. Create two integers `totalSum` and `carry` to store the sum and carry of current digits. +3. Create a new `ListNode`, `ans` that will store the sum of current digits. +4. We will add the two numbers using the reverse list by adding the digits one by one. We continue until we cover all the nodes in `r1` and `r2`: + - If `r1` is not null, we add `r1.val` to `totalSum`. + - If `r2` is not null, we add `r2.val` to `totalSum`. + - Set `ans.val = totalSum % 10. + - Store the `carry` as `totalSum / 10`. + - Create a new `ListNode`, `newNode` that will have `val` as `carry`. Set `next` of `newNode` to `ans`. Update `ans = newNode` to use the same variable `ans` for the next iteration. + - Update `totalSum = carry`. +5. If `carry == 0`, it means the newNode that we created in the final iteration of while loop has `val = 0`. Because we perform `ans = newNode` at the end of each while loop iteration while loop, to avoid returning a linked list with a head of `0` (leading zero), we return the next element, i.e., we return `ans.next`. Otherwise, if `carry` is not equal to `0`, the value of `ans` is non-zero. Hence, we just return `ans`. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + ListNode* reverseList(ListNode* head) { + ListNode* prev = nullptr; + ListNode* temp; + while (head) { + // Keep the next node. + temp = head->next; + // reverse the link + head->next = prev; + // Update the previous node and the current node. + prev = head; + head = temp; + } + return prev; + } + + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode* r1 = reverseList(l1); + ListNode* r2 = reverseList(l2); + + int totalSum = 0; + int carry = 0; + ListNode* ans = new ListNode(); + while (r1 || r2) { + if (r1) { + totalSum += r1->val; + r1 = r1->next; + } + if (r2) { + totalSum += r2->val; + r2 = r2->next; + } + + ans->val = totalSum % 10; + carry = totalSum / 10; + ListNode* head = new ListNode(carry); + head->next = ans; + ans = head; + totalSum = carry; + } + + return carry == 0 ? ans->next : ans; + } +}; +``` + + + + +```java +public class Solution { + public ListNode reverseList(ListNode head) { + ListNode prev = null, temp; + while (head != null) { + // Keep the next node + temp = head.next; + // Reverse the link + head.next = prev; + // Update the previous node and the current node. + prev = head; + head = temp; + } + return prev; + } + + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + ListNode r1 = reverseList(l1); + ListNode r2 = reverseList(l2); + + int totalSum = 0, carry = 0; + ListNode ans = new ListNode(); + while (r1 != null || r2 != null) { + if (r1 != null) { + totalSum += r1.val; + r1 = r1.next; + } + if (r2 != null) { + totalSum += r2.val; + r2 = r2.next; + } + + ans.val = totalSum % 10; + carry = totalSum / 10; + ListNode head = new ListNode(carry); + head.next = ans; + ans = head; + totalSum = carry; + } + + return carry == 0 ? ans.next: ans; + } +} +``` + + + + + +```python +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + prev = None + temp = None + while head: + # Keep the next node + temp = head.next + # Reverse the link + head.next = prev + # Update the previous node and the current node. + prev = head + head = temp + return prev + + def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: + r1 = self.reverseList(l1) + r2 = self.reverseList(l2) + + total_sum = 0 + carry = 0 + ans = ListNode() + while r1 or r2: + if r1: + total_sum += r1.val + r1 = r1.next + if r2: + total_sum += r2.val + r2 = r2.next + + ans.val = total_sum % 10 + carry = total_sum // 10 + head = ListNode(carry) + head.next = ans + ans = head + total_sum = carry + + return ans.next if carry == 0 else ans +``` + + + +## Complexity Analysis + +### Time Complexity: $O(M+N)$ + +> **Reason**: +> - Reversing the list l1 and l2 take O(m) and O(n) time respectively. +> - We then iterate over digits of the both lists. We iterate until both the lists are fully traversed. We iterate in the while loop max(m, n) times. We compute totalSum, carry and create a new node in each iteration which takes O(1) time. Hence, the complexity of all the while loop can be written as O(m+n) time. + +### Space Complexity: $O(M+N)$ + +> **Reason**: As we have reversed the input linked lists, we will count the space consumed by the reversed lists. The r1 linked list takes O(m) space and r2 takes O(n) space. + +### Approach 2: Stack + +#### Intuition + +Our task is to do a basic addition of two numbers starting with the least significant digits and working our way up to the most significant digits. In the previous approach, we reversed the linked lists to access the least significant digits first. We can also use **stacks** to access the least significant digits first. + +The advantage of using a stack is that when we loop over a given linked list from the first node to the last and push all the digits in the stack, the top of the stack will have the least significant digit and the bottom will contain the most significant digit. + +We can add the digits at corresponding places of the linked lists using the two stacks moving from the least to the most significant digits using the stack's `pop` method. + +Here's a brief visual representation explaining the approach: + +![image](https://assets.leetcode.com/static_assets/media/original_images/445/445-stack.png) + +### Algorithm + +1. Create two integer stacks `s1` and `s2` to store the integers of the linked lists `l1` and `l2` respectively. +2. Push all the integers of `l1` in `s1` starting from the integer at the first node. The most significant comes first in the list, so it will be stored at the bottom of the stack and the least significant digit will stored at the top. +3. Similarly, push all the integers of `l2` in `s2`. +4. Create two integers `totalSum` and `carry` to store the sum and carry of current digits. +5. Create a new `ListNode`, `ans` that will store the answer. +6. We will add the two numbers present in the linked list now by adding the digits one by one. We continue until both `s1` and `s2` are empty: + - If `s1` is not empty, pop the first element from the stack and add it to `totalSum`. + - If `s2` is not empty, pop the first element from the stack and add it to `totalSum`. + - Set `ans.val = totalSum % 10`. + - Store the `carry` as `totalSum / 10`. + - Create a new `ListNode`, `newNode` that will have `val` as `carry`. Set `next` of `newNode` to `ans`. Update `ans = newNode` to use the same variable `ans` for the next iteration. + - Update `totalSum = carry`. +7. If `carry == 0`, it means the `newNode` that we created in the final iteration of while loop has `val = 0`. Because we perform `ans = newNode` at the end of each while loop, to avoid returning a linked list with a head of `0` (leading zero), we return the next element, i.e., we return `ans.next`. Otherwise, if `carry` is not equal to `0`, the value of `ans` is non-zero. Hence, we just return `ans`. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + stack s1, s2; + + while (l1 != nullptr) { + s1.push(l1->val); + l1 = l1->next; + } + + while (l2 != nullptr) { + s2.push(l2->val); + l2 = l2->next; + } + + int totalSum = 0, carry = 0; + ListNode* ans = new ListNode(); + while (!s1.empty() || !s2.empty()) { + if (!s1.empty()) { + totalSum += s1.top(); + s1.pop(); + } + if (!s2.empty()) { + totalSum += s2.top(); + s2.pop(); + } + + ans->val = totalSum % 10; + carry = totalSum / 10; + ListNode* newNode = new ListNode(carry); + newNode->next = ans; + ans = newNode; + totalSum = carry; + } + + return carry == 0 ? ans->next : ans; + } +}; + +``` + + + + +```java +public class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + Stack s1 = new Stack(); + Stack s2 = new Stack(); + + while(l1 != null) { + s1.push(l1.val); + l1 = l1.next; + }; + while(l2 != null) { + s2.push(l2.val); + l2 = l2.next; + } + + int totalSum = 0, carry = 0; + ListNode ans = new ListNode(); + while (!s1.empty() || !s2.empty()) { + if (!s1.empty()) { + totalSum += s1.pop(); + } + if (!s2.empty()) { + totalSum += s2.pop(); + } + + ans.val = totalSum % 10; + carry = totalSum / 10; + ListNode head = new ListNode(carry); + head.next = ans; + ans = head; + totalSum = carry; + } + + return carry == 0 ? ans.next: ans; + } +} +``` + + + + + +```python +class Solution: + def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: + s1 = [] + s2 = [] + + while l1: + s1.append(l1.val) + l1 = l1.next + while l2: + s2.append(l2.val) + l2 = l2.next + + total_sum = 0 + carry = 0 + ans = ListNode() + while s1 or s2: + if s1: + total_sum += s1.pop() + if s2: + total_sum += s2.pop() + + ans.val = total_sum % 10 + carry = total_sum // 10 + head = ListNode(carry) + head.next = ans + ans = head + total_sum = carry + + return ans.next if carry == 0 else ans +``` + + + +## Complexity Analysis + +### Time Complexity: $O(M+N)$ + +> **Reason**: +> - Iterating over both the lists and pushing all the values in the respective stacks take O(m+n) time. +> - We then iterate over digits of the both lists. We iterate until both the stacks are empty. We iterate in the while loop max(m, n) times. We compute sum, carry and create a new node in each iteration which takes O(1) time. Hence, the complexity of all the while loop can be written as O(m+n) time. + +### Space Complexity: $O(M+N)$ + +> **Reason**: The s1 stack takes O(m) space and the s2 stack takes O(n) space. + +## References + +- **LeetCode Problem**: [Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/description/) + +- **Solution Link**: [Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/0400-0499/0448-Find-All-Numbers_disappeared-In -An -Array.md b/solutions/lc-solutions/0400-0499/0448-Find-All-Numbers_disappeared-In -An -Array.md new file mode 100644 index 0000000..226cfff --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0448-Find-All-Numbers_disappeared-In -An -Array.md @@ -0,0 +1,71 @@ +--- +id: find-all-numbers-disapperared-in-an-array +title: Find All Numbers Disappeared In An Array +sidebar_label: 448-Find-All-Numbers-Disappeared-In-An-Array +tags: + - Array + - Hash Table + +--- + +## Problem Description + +Given an array nums of `n` integers where `nums[i]` is in the range `[1, n]`, return an array of all the integers in the range `[1, n]` that do not appear in `nums`. + + +### Example + +**Example 1:** + +``` +Input: nums = [4,3,2,7,8,2,3,1] +Output: [5,6] +``` + +**Example 2:** +``` +Input: nums = [1,1] +Output: [2] +``` + +### Constraints + +- `1 <= n <= 105` + +## Solution Approach + +### Intuition: + +To efficiently determine the disappeared numbers in the array + + +## Solution Implementation + +### Code (C++): + +```cpp +class Solution { +public: + vector findDisappearedNumbers(vector& nums) { + int n = nums.size(); + // Mark the presence + for (int i = 0; i < n; i++) { + int index = abs(nums[i]) - 1; // Get index from value + if (nums[index] > 0) { + nums[index] = -nums[index]; // Mark as visited + } + } + + // Collect the missing numbers + vector ans; + for (int i = 0; i < n; i++) { + if (nums[i] > 0) { + ans.push_back(i + 1); // The missing number + } + } + + return ans; + } +}; + +``` \ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0451-sort-characters-by-frequency.md b/solutions/lc-solutions/0400-0499/0451-sort-characters-by-frequency.md new file mode 100644 index 0000000..22757cc --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0451-sort-characters-by-frequency.md @@ -0,0 +1,123 @@ +--- +id: sort-characters-by-frequency +title: Sort Characters By Frequency (LeetCode) +sidebar_label: 0451-Sort Characters By Frequency +tags: + - Hash Table + - String + - Sorting + - Heap(Priority Queue) + - Bucket Sort + - Counting +description: Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. +sidebar_position: 0451 +--- + +## Problem Description + +Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. + +Return the sorted string. If there are multiple answers, return any of them. + +Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. + +### Example 1 + +- **Input:** ` s = "tree" ` +- **Output:** `"eert"` +- **Explanation:** 'e' appears twice while 'r' and 't' both appear once.So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. + +### Example 2 + +- **Input:** ` s = "cccaaa" ` +- **Output:** `"aaaccc"` +- **Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.Note that "cacaca" is incorrect, as the same characters must be together. + +### Example 3 + +- **Input:** ` s = "Aabb" ` +- **Output:** `"bbAa"` +- **Explanation:** "bbaA" is also a valid answer, but "Aabb" is incorrect.Note that 'A' and 'a' are treated as two different characters. + + + +### Constraints + +- `1 <= s.length <= 5 * 105` +- `s consists of uppercase and lowercase English letters and digits.` + +## Approach + + - 1. Count the occurrences: We need to go through the string and count the occurrences of each character. This can be done efficiently by using a hash table or a counter data structure where each character is a key, and its count is the value. + + - 2. Sort based on counts: Once we have the counts, the next step is to sort the characters by these counts in descending order. We want the characters with higher counts to come first. + + - 3. With these counts, we can construct a new string. + + + +### Solution Code + +#### C++ + +```c++ +class Solution { +public: + string frequencySort(string s) { + unordered_map frequencyMap; + for (char ch : s) { + ++frequencyMap[ch]; + } + vector uniqueChars; + for (auto& keyValue : frequencyMap) { + uniqueChars.push_back(keyValue.first); + } + sort(uniqueChars.begin(), uniqueChars.end(), [&](char a, char b) { + return frequencyMap[a] > frequencyMap[b]; + }); + string result; + for (char ch : uniqueChars) { + result += string(frequencyMap[ch], ch); + } + return result; + } +}; + +``` + +#### java +```java +class Solution { + public String frequencySort(String s) { + Map frequencyMap = new HashMap<>(52); + for (int i = 0; i < s.length(); ++i) { + frequencyMap.merge(s.charAt(i), 1, Integer::sum); + } + List characters = new ArrayList<>(frequencyMap.keySet()); + characters.sort((a, b) -> frequencyMap.get(b) - frequencyMap.get(a)); + StringBuilder sortedString = new StringBuilder(); + for (char c : characters) { + for (int frequency = frequencyMap.get(c); frequency > 0; --frequency) { + sortedString.append(c); + } + } + return sortedString.toString(); + } +} + +``` + +#### Python +```python +class Solution: + def frequencySort(self, s: str) -> str: + char_frequency = Counter(s) + sorted_characters = sorted(char_frequency.items(), key=lambda item: -item[1]) + frequency_sorted_string = ''.join(character * frequency for character, frequency in sorted_characters) + return frequency_sorted_string +``` + +#### Conclusion +The above solutions use two-pointers approach to reverse the string. + - 1. Time complexity: O(n logn) + - 2. Space complexity: O(n) diff --git a/solutions/lc-solutions/0400-0499/0454-4Sum-II.md b/solutions/lc-solutions/0400-0499/0454-4Sum-II.md new file mode 100644 index 0000000..3e95bc2 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0454-4Sum-II.md @@ -0,0 +1,132 @@ +--- +id: 4Sum-II +title: 4Sum II (LeetCode) +sidebar_label: 0454-4Sum-II +tags: + - Hash Table + - Arrays +description: "Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string." +sidebar_position: 0451 +--- +## Problem Description + +Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that: + +`0 <= i`, `j`, `k`, `l < n` +nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0 + +## Examples + +Example 1: + +Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] +Output: 2 +Explanation: +The two tuples are: +1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0 +2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0 + +Example 2: + +Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] +Output: 1 + +## Constraints + +- n == nums1.length +- n == nums2.length +- n == nums3.length +- n == nums4.length +- `1 <= n <= 200` +- `-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228` + +## Approach + +Create an empty map called "mp" to store integer keys and their corresponding counts. + +Iterate over each element "k" in the "nuns3" vector. + +For each "k", iterate over each element "l" in the "nums4" vector. + +Add the sum of "k" and "l" as a key in the map "mp" and increment its count by 1. + +Initialize a variable "count" to 0. + +Iterate over each element "i" in the "nums1" vector. + +For each "i", iterate over each element "j" in the "nums2" vector. + +Find the value associated with the key -(i + j) in the map "mp" and add it to the "count". + +Return the value of "count" as the result. + +### Solution Code + +#### C++ + +```c++ +class Solution { +public: + int fourSumCount(vector& nums1, vector& nums2, vector& nums3, vector& nums4) { + + unordered_map mp; + + + for(int k : nums3) + for(int l : nums4) + mp[k + l]++; + + + int count = 0; + for(int i : nums1) + for(int j : nums2) + count += mp[-(i + j)]; + + return count; + } +}; +``` + +#### java +```java + +class Solution { + public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { + Map map = new HashMap<>(); + for (int n1 : nums1) { + for (int n2 : nums2) { + map.put(n1 + n2, map.getOrDefault(n1 + n2, 0) + 1); + } + } + + int count = 0; + for (int n3 : nums3) { + for (int n4 : nums4) { + count += map.getOrDefault(-(n3 + n4), 0); + } + } + return count; + } +} + +``` +#### Python +```Python +class Solution: + def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int: + dc1=defaultdict(lambda:0) + for a in nums1: + for b in nums2: + dc1[a+b]+=1 + ans=0 + for c in nums3: + for d in nums4: + ans+=dc1[-c-d] + return ans + +``` + +## Conclusion + +- 1. Time complexity:O(n^2) +- 2. Space complexity:O(n^2) diff --git a/solutions/lc-solutions/0400-0499/0455-assign-cookies.md b/solutions/lc-solutions/0400-0499/0455-assign-cookies.md new file mode 100644 index 0000000..cec43f1 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0455-assign-cookies.md @@ -0,0 +1,192 @@ +--- +id: assign-cookies +title: Assign Cookies +sidebar_label: 0455 - Assign Cookies +tags: + - Sorting + - Greedy + - Two Pointers +description: "This is a solution to the Assign Cookies problem on LeetCode." +--- + +## Problem Description + +Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. + +Each child i has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number. + +### Examples + +**Example 1:** + +``` +Input: g = [1,2,3], s = [1,1] +Output: 1 +Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. +And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. +You need to output 1. +``` + +**Example 2:** + +``` +Input: g = [1,2], s = [1,2,3] +Output: 2 +Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. +You have 3 cookies and their sizes are big enough to gratify all of the children, +You need to output 2. +``` + +### Constraints + +- $1 <= g.length <= 3 * 10^4$ +- $0 <= s.length <= 3 * 10^4$ +- $1 <= g[i], s[j] <= 2^{31} - 1$ + +## Solution for Assign Cookies + +### Overview + +Our objective is to determine the maximum number of content children given cookie sizes and greed factors. + +Each index `i` in `g` represents a child whose minimum cookie size is `g[i]`. +Each index `j` in `s` represents a cookie with the size `s[j]`. + +A child will be content if their cookie's size `s[j]` meets or exceeds their greed `g[i]`, represented as cookie size `s[j] >= g[i]` + +Each child should receive at most one cookie. We must note that we could have many small cookies, but that will not satisfy a greedy child, because they want 1 large cookie. If there are lots of small cookies but no children with small greed, we can't use those cookies. + +### Approach: Greedy, Two-Pointer +#### Intuition + +Given the test case 2 `g = [1, 2]` and `s = [1, 2, 3]`, we could attempt a naive approach, iterating through both arrays and assigning cookies to the children in order. + +Would this approach work for all cases? With the test case `g = [2, 1]` and `s = [1, 2]` we realize we cannot assign cookies in order because the first cookie isn't large enough for the first child, and if we allocate the second cookie to the second child, we satisfy only one child when we could satisfy two. + +We need to be able to ensure that each child receives the smallest cookie that meets their greed so that larger cookies can be saved for children with more greed. We also want to make sure there are no leftover cookies that could have satisfied children. + +The optimal solution will satisfy these conditions: + + - Every child that receives a cookie receives the smallest cookie that meets their greed so no larger cookies are wasted on children with smaller greed + - After cookies are assigned, no cookies are remaining that could satisfy the available children's greed + +How do we ensure that we don't waste larger cookies on children with smaller greed? We notice that in the first example, both arrays are sorted in ascending order. We need to sort the cookies and children in ascending order so that we can guarantee that for each child, we always try the currently smallest available cookie. + +To solve the problem, we will start by sorting both arrays. That way we can ensure the children with the smallest greed and the smallest cookies are at the beginning, and the children with the largest greed and the largest cookies are at the end. + +Next, we will use a while loop to iterate through our array of cookies, attempting to assign cookies to children. We will continue while we have more cookies and children. We will create a variable `cookieIndex` that keeps track of which cookies we have assigned or passed. We will store the number of satisfied children in `contentChildren`. If the next cookie meets the current child's greed, we increment `contentChildren` and `cookieIndex` as that cookie is assigned to a child. If the next cookie doesn't meet the current child's greed, we iterate `cookieIndex` to move on to the next cookie, until we find a cookie large enough for the child or we run out of cookies. Finally, we return `contentChildren`. + +How can we be sure this provides the optimal solution? + +With this approach, each child is offered the smallest available cookie first. Since the cookies are offered in order of ascending size, this ensures every child receives the smallest cookie that meets their greed. While assigning cookies to children, the children are sorted in increasing order of greed, which means that when we offer a cookie that doesn't meet the current child's greed, we also know there are no children less greedy than the current child. This means that any leftover cookies will not satisfy any available children. The approach provides an optimal solution. + +This is a greedy approach because the current child always receives the cookie, even if the cookie could have satisfied the next child. This is the locally optimal choice. + +#### Algorithm + +1. Sort arrays `g` and `s` in ascending order. +2. Initialize variable `contentChildren = 0` to represent the number of children who receive cookies that meet their greed. +3. Initialize variable `cookieIndex = 0` to represent the number of cookies that have been assigned or skipped. +4. while `cookieIndex` is less than the size of `s` and `contentChildren` is less than the size of `g`: + - If the current cookie's size is greater than or equal to the current child's greed: + - Increment `contentChildren` to allocate the cookie. + - Increment `cookieIndex` to move on to the next cookie. +5. Return `contentChildren`. + + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + int findContentChildren(std::vector& g, std::vector& s) { + std::sort(g.begin(), g.end()); + std::sort(s.begin(), s.end()); + int contentChildren = 0; + int cookieIndex = 0; + while (cookieIndex < s.size() && contentChildren < g.size()) { + if (s[cookieIndex] >= g[contentChildren]) { + contentChildren++; + } + cookieIndex++; + } + return contentChildren; + } +}; +``` + + + + +```java +class Solution { + public int findContentChildren(int[] g, int[] s) { + Arrays.sort(g); + Arrays.sort(s); + int contentChildren = 0; + int cookieIndex = 0; + while (cookieIndex < s.length && contentChildren < g.length) { + if (s[cookieIndex] >= g[contentChildren]) { + contentChildren++; + } + cookieIndex++; + } + return contentChildren; + } + +} +``` + + + + + +```python +class Solution: + def findContentChildren(self, g: List[int], s: List[int]) -> int: + g.sort() + s.sort() + content_children = 0 + cookie_index = 0 + while cookie_index < len(s) and content_children < len(g): + if s[cookie_index] >= g[content_children]: + content_children += 1 + cookie_index += 1 + return content_children +``` + + + +## Complexity Analysis + +### Time Complexity: $O(Nβ‹…logN+Mβ‹…logM)$ + +> **Reason**: Sorting an array of length k takes O(kβ‹…log⁑k), we need to sort two given arrays. The while loop iterates over each cookie and child once, taking O(M+N). To sum up, the overall time complexity is O(Nβ‹…log⁑N+Mβ‹…log⁑M). + +### Space Complexity: $O(M+N)$ or $O(logN+logM)$ + +> **Reason**: +> Some extra space is used when we sort `s` and `g` in place. The space complexity of the sorting algorithm depends on the programming language. +> - In Python, the `sort` method sorts a list using the Timesort algorithm which is a combination of Merge Sort and Insertion Sort and has `O(N+M)` additional space. +> - In C++, the sort() function is implemented as a hybrid of Quick Sort, Heap Sort, and Insertion Sort, with a worse-case space complexity of `O(log⁑N+log⁑M)`. +> - In Java, Arrays.sort() is implemented using a variant of the Quick Sort algorithm which has a space complexity of `O(log⁑N+log⁑M)` for sorting two arrays. + +## References + +- **LeetCode Problem**: [Assign Cookies](https://leetcode.com/problems/assign-cookies/description/) + +- **Solution Link**: [Assign Cookies](https://leetcode.com/problems/assign-cookies/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0460-lfu-cache.md b/solutions/lc-solutions/0400-0499/0460-lfu-cache.md new file mode 100644 index 0000000..4a98e4b --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0460-lfu-cache.md @@ -0,0 +1,370 @@ +--- +id: lfu-cache +title: LFU Cache +sidebar_label: 0460 - LFU Cache +tags: +- Hash Table +- Linked List +- Ordered Set +description: "This is a solution to the LFU Cache problem on LeetCode." +--- + +## Problem Description +Design and implement a data structure for a Least Frequently Used (LFU) cache. + +Implement the `LFUCache` class: + +- `LFUCache(int capacity)` Initializes the object with the `capacity` of the data structure. +- `int get(int key)` Gets the value of the `key` if the key exists in the cache. Otherwise, returns -1. +- `void put(int key, int value)` Update the value of the key if present, or inserts the `key` if not already present. When the cache reaches its `capacity`, it should invalidate and remove the **least frequently used** key before inserting a new item. For this problem, when there is a **tie** (i.e., two or more keys with the same frequency), **the least recently used** `key` would be invalidated. + +To determine the least frequently used key, a **use counter** is maintained for each key in the cache. The key with the smallest **use counter** is the least frequently used key. + +When a key is first inserted into the cache, its **use counter** is set to `1` (due to the `put` operation). The **use counter** for a key in the cache is incremented either a `get` or `put` operation is called on it. + +The functions `get` and `put` must each run in O(1) average time complexity. + + +### Examples + +**Example 1:** + +``` +Input-["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"] +[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]] +Output-[null, null, null, 1, null, -1, 3, null, -1, 3, 4] +Explanation: +// cnt(x) = the use counter for key x +// cache=[] will show the last used order for tiebreakers (leftmost element is most recent) +LFUCache lfu = new LFUCache(2); +lfu.put(1, 1); // cache=[1,_], cnt(1)=1 +lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1 +lfu.get(1); // return 1 + // cache=[1,2], cnt(2)=1, cnt(1)=2 +lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2. + // cache=[3,1], cnt(3)=1, cnt(1)=2 +lfu.get(2); // return -1 (not found) +lfu.get(3); // return 3 + // cache=[3,1], cnt(3)=2, cnt(1)=2 +lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1. + // cache=[4,3], cnt(4)=1, cnt(3)=2 +lfu.get(1); // return -1 (not found) +lfu.get(3); // return 3 + // cache=[3,4], cnt(4)=1, cnt(3)=3 +lfu.get(4); // return 4 + // cache=[4,3], cnt(4)=2, cnt(3)=3 +``` + + +### Constraints +- `1 <= capacity <= 104` +- `0 <= key <= 105` +- `0 <= value <= 109` +- At most `2 * 105` calls will be made to `get` and `put`. + +## Solution for LFU Cache + +### Approach +#### HashMap and LinkedHashSet: +##### Intuition +We need to maintain all the keys, values and frequencies. Without invalidation (removing from the data structure when it reaches capacity), they can be maintained by a HashMap `>`, keyed by the original `key` and valued by the `frequency`-`value` pair. + +With the invalidation, we need to maintain the current minimum frequency and delete particular keys. Hence, we can group the keys with the same frequency together and maintain another HashMap``, keyed by the frequency and valued by the set of `keys` that have the same frequency. This way, if we know the minimum frequency, we can access the potential keys to be deleted. + +Also note that in the case of a tie, we're required to find the least recently used key and invalidate it, hence we need to keep the frequencies ordered in the Set. Instead of using a TreeSet which adds an extra O(log(N)) time complexity, we can maintain the keys using a LinkedList so that it supports finding both an arbitrary key and the least recently used key in constant time. Fortunately, LinkedHashSet can do the job. Once a key is inserted/updated, we put it to the end of the LinkedHashSet so that we can invalidate the first key in the LinkedHashSet corresponding to the minimum frequency. + +The original operations can be transformed into operations on the 2 HashMaps, keeping them in sync and maintaining the minimum frequency. + +Since C++ lacks LinkedHashSet, we have to use a workaround like maintaining a list of key and value pairs instead of the LinkedHashSet and keeping the iterator with the frequency in another unordered_map to keep this connection. The idea is similar but a little bit complicated. Another workaround would be to implement your own LRU cache with a doubly linked list. + +##### Algorithm +To make things simpler, assume we have 4 member variables: + +1. HashMap`>` cache, keyed by the original key and valued by the frequency-value pair. +2. HashMap`>` frequencies, keyed by frequency and valued by the set of keys that have the same frequency. +3. `int minf`, which is the minimum frequency at any given time. +4. `int capacity`, which is the `capacity` given in the input. + +It's also convenient to have a private utility function insert to insert a key-value pair with a given frequency. + +##### void insert(int key, int frequency, int value) + +1. Insert frequency-value pair into cache with the given key. +2. Get the LinkedHashSet corresponding to the given frequency (default to empty Set) and insert the given key. + +##### int get(int key) + +1. If the given key is not in the cache, return -1, otherwise go to step 2. +2. Get the frequency and value from the cache. +3. Get the LinkedHashSet associated with frequency from frequencies and remove the given key from it, since the usage of the current key is increased by this function call. +4. If minf == frequency and the above LinkedHashSet is empty, that means there are no more elements used minf times, so increase minf by 1. To save some space, we can also delete the entry frequency from the frequencies hash map. +5. Call insert(key, frequency + 1, value), since the current key's usage has increased from this function call. +6. Return value + +##### void put(int key, int value) +1. If capacity < = 0, exit. +2. If the given key exists in cache, update the value in the original frequency-value (don't call insert here), and then increment the frequency by using get(key). Exit the function. +3. If cache.size() == capacity, get the first (least recently used) value in the LinkedHashSet corresponding to minf in frequencies, and remove it from cache and the LinkedHashSet. +4. If we didn't exit the function in step 2, it means that this element is a new one, so the minimum frequency cannot possibly be greater than one. Set minf to 1. +5. Call insert(key, 1, value) + + +## Code in Different Languages + + + + + +```cpp +class LFUCache { + // key: frequency, value: list of original key-value pairs that have the same frequency. + unordered_map>> frequencies; + // key: original key, value: pair of frequency and the iterator corresponding key int the + // frequencies map's list. + unordered_map>::iterator>> cache; + int capacity; + int minf; + + void insert(int key, int frequency, int value) { + frequencies[frequency].push_back({key, value}); + cache[key] = {frequency, --frequencies[frequency].end()}; + } + +public: + LFUCache(int capacity) : capacity(capacity), minf(0) {} + + int get(int key) { + const auto it = cache.find(key); + if (it == cache.end()) { + return -1; + } + const int f = it->second.first; + const auto iter = it->second.second; + const pair kv = *iter; + frequencies[f].erase(iter); + if (frequencies[f].empty()){ + frequencies.erase(f); + + if(minf == f) { + ++minf; + } + } + + insert(key, f + 1, kv.second); + return kv.second; + } + + void put(int key, int value) { + if (capacity <= 0) { + return; + } + const auto it = cache.find(key); + if (it != cache.end()) { + it->second.second->second = value; + get(key); + return; + } + if (capacity == cache.size()) { + cache.erase(frequencies[minf].front().first); + frequencies[minf].pop_front(); + + if(frequencies[minf].empty()) { + frequencies.erase(minf); + } + } + + minf = 1; + insert(key, 1, value); + } +}; +``` + + + + +```java +class LFUCache { + // key: original key, value: frequency and original value. + private Map> cache; + // key: frequency, value: All keys that have the same frequency. + private Map> frequencies; + private int minf; + private int capacity; + + private void insert(int key, int frequency, int value) { + cache.put(key, new Pair<>(frequency, value)); + frequencies.putIfAbsent(frequency, new LinkedHashSet<>()); + frequencies.get(frequency).add(key); + } + + public LFUCache(int capacity) { + cache = new HashMap<>(); + frequencies = new HashMap<>(); + minf = 0; + this.capacity = capacity; + } + + public int get(int key) { + Pair frequencyAndValue = cache.get(key); + if (frequencyAndValue == null) { + return -1; + } + final int frequency = frequencyAndValue.getKey(); + final Set keys = frequencies.get(frequency); + keys.remove(key); + if (keys.isEmpty()) { + frequencies.remove(frequency); + + if (minf == frequency) { + ++minf; + } + } + final int value = frequencyAndValue.getValue(); + insert(key, frequency + 1, value); + return value; + } + + public void put(int key, int value) { + if (capacity <= 0) { + return; + } + Pair frequencyAndValue = cache.get(key); + if (frequencyAndValue != null) { + cache.put(key, new Pair<>(frequencyAndValue.getKey(), value)); + get(key); + return; + } + if (capacity == cache.size()) { + final Set keys = frequencies.get(minf); + final int keyToDelete = keys.iterator().next(); + cache.remove(keyToDelete); + keys.remove(keyToDelete); + if (keys.isEmpty()) { + frequencies.remove(minf); + } + } + minf = 1; + insert(key, 1, value); + } +} +``` + + + + + +```python +import collections + +class Node: + def __init__(self, key, val): + self.key = key + self.val = val + self.freq = 1 + self.prev = self.next = None + +class DLinkedList: + + def __init__(self): + self._sentinel = Node(None, None) # dummy node + self._sentinel.next = self._sentinel.prev = self._sentinel + self._size = 0 + + def __len__(self): + return self._size + + def append(self, node): + node.next = self._sentinel.next + node.prev = self._sentinel + node.next.prev = node + self._sentinel.next = node + self._size += 1 + + def pop(self, node=None): + if self._size == 0: + return + + if not node: + node = self._sentinel.prev + + node.prev.next = node.next + node.next.prev = node.prev + self._size -= 1 + + return node + +class LFUCache: + def __init__(self, capacity): + self._size = 0 + self._capacity = capacity + + self._node = dict() # key: Node + self._freq = collections.defaultdict(DLinkedList) + self._minfreq = 0 + + + def _update(self, node): + + freq = node.freq + + self._freq[freq].pop(node) + if self._minfreq == freq and not self._freq[freq]: + self._minfreq += 1 + + node.freq += 1 + freq = node.freq + self._freq[freq].append(node) + + def get(self, key): + if key not in self._node: + return -1 + + node = self._node[key] + self._update(node) + return node.val + + def put(self, key, value): + + if self._capacity == 0: + return + + if key in self._node: + node = self._node[key] + self._update(node) + node.val = value + else: + if self._size == self._capacity: + node = self._freq[self._minfreq].pop() + del self._node[node.key] + self._size -= 1 + + node = Node(key, value) + self._node[key] = node + self._freq[1].append(node) + self._minfreq = 1 + self._size += 1 +``` + + + +## Complexity Analysis + ### Time Complexity: $O(1)$ + > **Reason:** We only have basic HashMap/(Linked)HashSet operations + ### Space Complexity: $O(N)$ + > **Reason:** We save all the key-value pairs as well as all the keys with frequencies in the 2 HashMaps (plus a LinkedHashSet), so there are at most $min(N, capacity) keys and values at any given time. + +## References + +- **LeetCode Problem**: [LFU Cache](https://leetcode.com/problems/lfu-cache/description/) + +- **Solution Link**: [LFU Cache](https://leetcode.com/problems/lfu-cache/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/0400-0499/0463-island-perimeter.md b/solutions/lc-solutions/0400-0499/0463-island-perimeter.md new file mode 100644 index 0000000..08b316e --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0463-island-perimeter.md @@ -0,0 +1,155 @@ +--- +id: island-perimeter +title: Island Perimeter +sidebar_label: 0463-island-perimeter +tags: +- Array +- Depth first search +- Breadth first search +- Matrix +description: "This is a solution to the Island Perimeter problem on LeetCode." +--- + +## Problem Description + +You are given `row x col` `grid` representing a map where `grid[i][j] = 1` represents land and `grid[i][j] = 0` represents water. + +Grid cells are connected horizontally/vertically (not diagonally). The `grid` is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). + +The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. + +### Examples + +**Example 1:** + +``` +Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]] +Output: 16 +Explanation: The perimeter is the 16 yellow stripes in the image above. +``` + +**Example 2:** + +``` +Input: grid = [[1]] +Output: 4 +``` + +### Constraints + +- `row == grid.length` +- `col == grid[i].length` +- `1 <= row, col <= 100` +- `grid[i][j]` is `0` or `1`. +- There is exactly one island in `grid`. + + +### Approach + +#### Intuition + +To solve this problem, we need to calculate the total perimeter contributed by each land cell in the grid. Since we're working with a grid that has connected cells horizontally and vertically, each land cell that does not touch another land cell contributes 4 units to the perimeter (as it has four sides). + +Here's the intuitive step-by-step approach: + +1. Initialize a perimeter count to 0. +2. Iterate through each cell in the grid. +3. If a cell is land (1), increment the perimeter count by 4 (all possible sides of a single cell). +4. Then, check the adjacent cells: +- If there is a land cell to the right (horizontally adjacent), the shared edge does not contribute to the perimeter, so we subtract 2 from the perimeter count (as it removes one edge from each of the two adjacent land cells). +- Similarly, if there is a land cell below (vertically adjacent), subtract 2 for the shared edge. +5. Continue this process for all land cells in the grid. +6. Return the total perimeter count. + +This approach works because it dynamically adjusts the perimeter count based on the land cell's adjacency with other land cells, ensuring that shared edges are only counted once. + +## Code in Different Languages + + + + + +```cpp +class Solution { + public: + int islandPerimeter(vector>& grid) { + int islands = 0; + int neighbors = 0; + + for (int i = 0; i < grid.size(); ++i) + for (int j = 0; j < grid[0].size(); ++j) + if (grid[i][j]) { + ++islands; + if (i - 1 >= 0 && grid[i - 1][j]) + ++neighbors; + if (j - 1 >= 0 && grid[i][j - 1]) + ++neighbors; + } + + return islands * 4 - neighbors * 2; + } +}; +``` + + + + +```java +class Solution { + public int islandPerimeter(int[][] grid) { + int islands = 0; + int neighbors = 0; + + for (int i = 0; i < grid.length; ++i) + for (int j = 0; j < grid[0].length; ++j) + if (grid[i][j] == 1) { + ++islands; + if (i - 1 >= 0 && grid[i - 1][j] == 1) + ++neighbors; + if (j - 1 >= 0 && grid[i][j - 1] == 1) + ++neighbors; + } + + return islands * 4 - neighbors * 2; + } +} +``` + + + + + +```python +class Solution: + def islandPerimeter(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + + islands = 0 + neighbors = 0 + + for i in range(m): + for j in range(n): + if grid[i][j] == 1: + islands += 1 + if i + 1 < m and grid[i + 1][j] == 1: + neighbors += 1 + if j + 1 < n and grid[i][j + 1] == 1: + neighbors += 1 + + return islands * 4 - neighbors * 2 +``` + + + +## Complexity Analysis + +### Time Complexity: O(mn) + +### Space Complexity: O(1) + +## References + +- **LeetCode Problem**: [Island Perimeter](https://leetcode.com/problems/island-perimeter/description/) + +- **Solution Link**: [Island Perimeter](https://leetcode.com/problems/island-perimeter/solutions/) diff --git a/solutions/lc-solutions/0400-0499/0472-concatenated-words.md b/solutions/lc-solutions/0400-0499/0472-concatenated-words.md new file mode 100644 index 0000000..2b2889f --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0472-concatenated-words.md @@ -0,0 +1,404 @@ +--- +id: concatenated-words +title: Concatenated Words +sidebar_label: 0472 - Concatenated Words Hello +tags: +- Array +- String +- Dynamic Programming +- Depth-First Search +- Trie +description: "This is a solution to the Concatenated Words problem on LeetCode." +--- + +## Problem Description +Given an array of strings words (without duplicates), return all the concatenated words in the given list of words. +A concatenated word is defined as a string that is comprised entirely of at least two shorter words (not necessarily distinct) in the given array. + +### Examples + +**Example 1:** +``` +Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"] +Output: ["catsdogcats","dogcatsdog","ratcatdogcat"] +Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; +"dogcatsdog" can be concatenated by "dog", "cats" and "dog"; +"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat". +``` + +**Example 2:** +``` +Input: words = ["cat","dog","catdog"] +Output: ["catdog"] +``` + +### Constraints +- `1 <= words.length <= 10^4` +- `1 <= words[i].length <= 30` +- words[i] consists of only lowercase English letters. +- All the strings of words are unique. +- `1 <= sum(words[i].length) <= 10^5` + +## Solution for Concatenated Words + +### Intuition +- The main intuition behind this solution is to use dynamic programming to check if a word can be split into smaller words that are all present in the dictionary. By recursively checking each substring and memoizing the results, we can efficiently determine if a word is a concatenated word. + +### Approach +- Dictionary Setup: Store all words from the input words vector into a set mp for quick lookup. This set will help in O(1) average time complexity for checking if a substring is a valid word. + +#### Recursive Function (solve): + +- Parameters: The function solve takes the word (op), the current index (idx), the count of words found so far (cnt), and a memoization vector (memo). +- Base Case: If idx reaches the end of the word (op.size()), it checks if the count of words (cnt) is at least 2. This ensures that the word is formed by concatenating at least two smaller words. +- Memoization Check: If the result for the current index is already computed (memo[idx] != -1), return the stored result to avoid redundant calculations. +- Substring Generation: Iterate from the current index to the end of the word, generating substrings (temp). For each substring, check if it exists in the set mp. +- Recursive Check: If a valid substring is found, recursively call solve on the remaining part of the word (i + 1). If this recursive call returns true, store the result in memo[idx] and return true. + +#### Main Function (findAllConcatenatedWordsInADict): + +- Initialization: Initialize an empty vector ans to store the result and populate the set mp with all words from the input. +- Processing Each Word: For each word in the input: +- Initialize a memoization vector memo with -1 indicating that no computations have been done for those indices. +- Call the solve function starting from index 0 and count 0. +- If solve returns true, add the word to the result vector ans. + + +- Return Result: After processing all words, return the result vector ans containing all concatenated words. + + + + + +#### Implementation + +```jsx live +function Solution() { +const findAllConcatenatedWordsInADict = (words) => { + const st = new Set(words); + + const solve = (op, idx, cnt, memo) => { + if (idx === op.length) { + return cnt >= 2; + } + + if (memo[idx] !== -1) { + return memo[idx] === 1; + } + + let temp = ""; + for (let i = idx; i < op.length; i++) { + temp += op[i]; + if (st.has(temp)) { + if (solve(op, i + 1, cnt + 1, memo)) { + memo[idx] = 1; + return true; + } + } + } + memo[idx] = 0; + return false; + }; + + const ans = []; + for (const word of words) { + const memo = new Array(word.length).fill(-1); + if (solve(word, 0, 0, memo)) { + ans.push(word); + } + } + return ans; +}; + +const input = ["cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat"]; +const output = findAllConcatenatedWordsInADict(input); + return ( +
+

+ Input: {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); +} +``` + +### Code in Different Languages + + + + + ```javascript + const findAllConcatenatedWordsInADict = (words) => { + const st = new Set(words); + + const solve = (op, idx, cnt, memo) => { + if (idx === op.length) { + return cnt >= 2; + } + + if (memo[idx] !== -1) { + return memo[idx] === 1; + } + + let temp = ""; + for (let i = idx; i < op.length; i++) { + temp += op[i]; + if (st.has(temp)) { + if (solve(op, i + 1, cnt + 1, memo)) { + memo[idx] = 1; + return true; + } + } + } + memo[idx] = 0; + return false; + }; + + const ans = []; + for (const word of words) { + const memo = new Array(word.length).fill(-1); + if (solve(word, 0, 0, memo)) { + ans.push(word); + } + } + return ans; +}; + +``` + + + + ```typescript + class Solution { + private st: Set; + + constructor() { + this.st = new Set(); + } + + private solve(op: string, idx: number, cnt: number, memo: number[]): boolean { + if (idx === op.length) { + return cnt >= 2; + } + + if (memo[idx] !== -1) { + return memo[idx] === 1; + } + + let temp = ""; + for (let i = idx; i < op.length; i++) { + temp += op[i]; + if (this.st.has(temp)) { + if (this.solve(op, i + 1, cnt + 1, memo)) { + memo[idx] = 1; + return true; + } + } + } + memo[idx] = 0; + return false; + } + + public findAllConcatenatedWordsInADict(words: string[]): string[] { + const ans: string[] = []; + this.st = new Set(words); + + for (const word of words) { + const memo = new Array(word.length).fill(-1); + if (this.solve(word, 0, 0, memo)) { + ans.push(word); + } + } + + return ans; + } +} + +// Example usage: +const solution = new Solution(); +const words = ["cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat"]; +const result = solution.findAllConcatenatedWordsInADict(words); +console.log(result); + + ``` + + + + ```python + class Solution: + def __init__(self): + self.st = set() + + def solve(self, op, idx, cnt, memo): + if idx == len(op): + return cnt >= 2 + + if memo[idx] != -1: + return memo[idx] + + temp = "" + for i in range(idx, len(op)): + temp += op[i] + if temp in self.st: + if self.solve(op, i + 1, cnt + 1, memo): + memo[idx] = True + return True + + memo[idx] = False + return False + + def findAllConcatenatedWordsInADict(self, words): + ans = [] + self.st = set(words) + + for word in words: + memo = [-1] * len(word) + if self.solve(word, 0, 0, memo): + ans.append(word) + + return ans + +# Example usage: +solution = Solution() +words = ["cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat"] +result = solution.findAllConcatenatedWordsInADict(words) +print(result) + ``` + + + +```java +import java.util.*; + +class Solution { + private Set st; + + public Solution() { + this.st = new HashSet<>(); + } + + private boolean solve(String op, int idx, int cnt, int[] memo) { + if (idx == op.length()) { + return cnt >= 2; + } + + if (memo[idx] != -1) { + return memo[idx] == 1; + } + + StringBuilder temp = new StringBuilder(); + for (int i = idx; i < op.length(); i++) { + temp.append(op.charAt(i)); + if (st.contains(temp.toString())) { + if (solve(op, i + 1, cnt + 1, memo)) { + memo[idx] = 1; + return true; + } + } + } + memo[idx] = 0; + return false; + } + + public List findAllConcatenatedWordsInADict(String[] words) { + List ans = new ArrayList<>(); + Collections.addAll(st, words); + for (String word : words) { + int[] memo = new int[word.length()]; + Arrays.fill(memo, -1); + if (solve(word, 0, 0, memo)) { + ans.add(word); + } + } + return ans; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + String[] words = {"cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat"}; + List result = solution.findAllConcatenatedWordsInADict(words); + System.out.println(result); + } +} +``` + + + + +```cpp +class Solution { +public: + set st; + bool solve(string& op, int idx, int cnt, vector& memo) { + if (idx == op.size()) { + return cnt >= 2; + } + + if (memo[idx] != -1) { + return memo[idx]; + } + + string temp = ""; + for (int i = idx; i < op.size(); i++) { + temp += op[i]; + if (st.find(temp) != st.end()) { + if (solve(op, i + 1, cnt + 1, memo)) { + return memo[idx] = 1; + } + } + } + return memo[idx] = 0; + } + + vector findAllConcatenatedWordsInADict(vector& words) { + vector ans; + for (const auto& word : words) { + st.insert(word); + } + for (auto& word : words) { + vector memo(word.size(), -1); + if (solve(word, 0, 0, memo)) { + ans.push_back(word); + } + } + return ans; + } +}; +``` + + + +#### Complexity Analysis + ##### Time Complexity: + ##### Initialization: + - Inserting all words into the set st takes $O(Nβ‹…L)$ time, where N is the number of words and L is the average length of the words. This is because each word of length +L takes $O(L)$ time to insert into the set. + ##### Main Loop: +- For each word, we call the solve function which performs a recursive check. There are N words, and for each word of length L, the solve function is called. +##### Recursive Function (solve): +- In the worst case, the solve function examines each possible substring of the word. This can involve $(L^2)$ + substrings in the worst case (considering all possible start and end points of substrings).For each substring, we check if it exists in the set st, which takes + $O(1)$ time on average. +- The memoization array ensures that each index is only computed once, so each index computation takes $O(L)$ time. + + ##### Space Complexity: + ##### Set (st): +- Storing all words in the set takes $O(Nβ‹…L)$ space. +##### Memoization Array: +- For each word of length L, the memoization array takes $O(L)$ space.In the worst case, all N words are of length L, so the total space required for memoization is $O(Nβ‹…L)$. +##### Recursive Call Stack: +- The depth of the recursion is at most L (the length of the longest word), so the space used by the call stack is $O(L)$. +##### Combining these: +- The total space complexity is $O(Nβ‹…L)$ due to the set and memoization array. +
+
+ +## References + +- **LeetCode Problem**: [Concatenated Words](https://leetcode.com/problems/concatenated-words/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/concatenated-words/solutions) + diff --git a/solutions/lc-solutions/0400-0499/0473-matchsticks-to-square.md b/solutions/lc-solutions/0400-0499/0473-matchsticks-to-square.md new file mode 100644 index 0000000..21860d6 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0473-matchsticks-to-square.md @@ -0,0 +1,673 @@ +--- +id: matchsticks-to-square +title: Matchsticks to Square +sidebar_label: 0473 - Matchsticks to Square +tags: +- Recursion +- Backtracking +- Dynamic Programming +description: "This is a solution to the Matchsticks to Square problem on LeetCode." +--- + +## Problem Description + +You are given an integer array `matchsticks` where `matchsticks[i]` is the length of the `ith` matchstick. You want to use **all the matchsticks** to make one square. You **should not break** any stick, but you can link them up, and each matchstick must be used **exactly one time**. + +Return `true` if you can make this square and `false` otherwise. + +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2021/04/09/matchsticks1-grid.jpg) +``` +Input: matchsticks = [1,1,2,2,2] +Output: true +Explanation: You can form a square with length 2, one side of the square came two sticks with length 1. +``` + +**Example 2:** + +``` +Input: matchsticks = [3,3,3,3,4] +Output: false +Explanation: You cannot find a way to form a square with all the matchsticks. +``` + +### Constraints + +- $1 \leq matchsticks.length \leq 15$ +- $1 \leq matchsticks[i] \leq 10^8$ + +## Solution for Matchsticks to Square + +### Overview + +Suppose we have `1,1,1,1,2,2,2,2,3,3,3,3` as our set of matchsticks. In this case a square of side 6 can be formed and we have 4 matchsticks each of 1, 2 and 3 and so we can have each square side formed by `3 + 2 + 1 = 6`. + +![image](https://assets.leetcode.com/static_assets/media/original_images/473/473_Matchsticks-In-Square-Diag-1.png) + +We can clearly see in the diagram above that the 3 matchsticks of sizes `1`, `2` and `3` combine to give one side of our resulting square. + +This problem boils down to splitting an array of integers into 4 subsets where all of these subsets are: +- mutually exclusive i.e. no specific element of the array is shared by any two of these subsets, and +- have the same sum which is equal to the side of our square. + +We know that we will have 4 different subsets. The sum of elements of these subsets would be $$\frac{1}{4} \sum \text{arr}$$. If the sum if not divisible by 4, that implies that 4 subsets of equal value are not possible and we don't need to do any further processing on this. + +The only question that remains now for us to solve is: +> what subset a particular element belongs to? + +If we are able to figure that out, then there's nothing else left to do. But, since we can't say which of the 4 subsets would contain a particular element, we try out all the options. + +### Approach 1: Depth First Search + +#### Intuition +It is possible that a matchstick **can** be a part of any of the 4 sides of the resulting square, but which one of these choices leads to an actual square is something we don't know. + +This means that for every matchstick in our given array, we have 4 different options each representing the side of the square or subset that this matchstick can be a part of. + +We try out all of them and keep on doing this recursively until we exhaust all of the possibilities or until we find an arrangement of our matchsticks such that they form the square. + +**Algorithm** +1. As discussed previously, we will follow a recursive, depth first approach to solve this problem. So, we have a function that takes the current matchstick index we are to process and also the number of sides of the square that are completely formed till now. + +2. If all of the matchsticks have been used up and 4 sides have been completely formed, that implies our square is completely formed. This is the base case for the recursion. + +3. For the current matchstick we have 4 different options. This matchstick at index can be a part of any of the sides of the square. We try out the 4 options by recursing on them. + + - If any of these recursive calls returns True, then we return from there, else we return False + +## Code in Different Languages + + + + + +```cpp +#include +#include + +class Solution { +public: + std::vector nums; + int sums[4] = {0}; + int possibleSquareSide; + + // Depth First Search function. + bool dfs(int index) { + // If we have exhausted all our matchsticks, check if all sides of the square are of equal length + if (index == nums.size()) { + return sums[0] == sums[1] && sums[1] == sums[2] && sums[2] == sums[3]; + } + + // Get current matchstick. + int element = nums[index]; + + // Try adding it to each of the 4 sides (if possible) + for (int i = 0; i < 4; i++) { + if (sums[i] + element <= possibleSquareSide) { + sums[i] += element; + if (dfs(index + 1)) { + return true; + } + sums[i] -= element; + } + } + + return false; + } + + bool makesquare(std::vector& nums) { + // Empty matchsticks. + if (nums.empty()) { + return false; + } + + // Find the perimeter of the square (if at all possible) + int L = nums.size(); + int perimeter = 0; + for (int i = 0; i < L; i++) { + perimeter += nums[i]; + } + + possibleSquareSide = perimeter / 4; + if (possibleSquareSide * 4 != perimeter) { + return false; + } + + // Sort the matchsticks in descending order + std::sort(nums.begin(), nums.end(), std::greater()); + this->nums = nums; + return dfs(0); + } +}; + + +``` + + + + +```java +import java.util.HashMap; +import java.util.Collections; + +class Solution { + public List nums; + public int[] sums; + public int possibleSquareSide; + + public Solution() { + this.sums = new int[4]; + } + + // Depth First Search function. + public boolean dfs(int index) { + + // If we have exhausted all our matchsticks, check if all sides of the square are of equal length + if (index == this.nums.size()) { + return sums[0] == sums[1] && sums[1] == sums[2] && sums[2] == sums[3]; + } + + // Get current matchstick. + int element = this.nums.get(index); + + // Try adding it to each of the 4 sides (if possible) + for(int i = 0; i < 4; i++) { + if (this.sums[i] + element <= this.possibleSquareSide) { + this.sums[i] += element; + if (this.dfs(index + 1)) { + return true; + } + this.sums[i] -= element; + } + } + + return false; + } + + public boolean makesquare(int[] nums) { + // Empty matchsticks. + if (nums == null || nums.length == 0) { + return false; + } + + // Find the perimeter of the square (if at all possible) + int L = nums.length; + int perimeter = 0; + for(int i = 0; i < L; i++) { + perimeter += nums[i]; + } + + this.possibleSquareSide = perimeter / 4; + if (this.possibleSquareSide * 4 != perimeter) { + return false; + } + + // Convert the array of primitive int to ArrayList (for sorting). + this.nums = Arrays.stream(nums).boxed().collect(Collectors.toList()); + Collections.sort(this.nums, Collections.reverseOrder()); + return this.dfs(0); + } +} +``` + + + + + +```python +def makesquare(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + + # If there are no matchsticks, then we can't form any square + if not nums: + return False + + # Number of matchsticks we have + L = len(nums) + + # Perimeter of our square (if one can be formed) + perimeter = sum(nums) + + # Possible side of our square. + possible_side = perimeter // 4 + + # If the perimeter can be equally split into 4 parts (and hence 4 sides, then we move on). + if possible_side * 4 != perimeter: + return False + + # Reverse sort the matchsticks because we want to consider the biggest one first. + nums.sort(reverse=True) + + # This array represents the 4 sides and their current lengths + sums = [0 for _ in range(4)] + + # Our recursive dfs function. + def dfs(index): + + # If we reach the end of matchsticks array, we check if the square was formed or not + if index == L: + # If 3 equal sides were formed, 4th will be the same as these three and answer should be True in that case. + return sums[0] == sums[1] == sums[2] == possible_side + + # The current matchstick can belong to any of the 4 sides (provided their remaining lenghts are >= the size of the current matchstick) + for i in range(4): + # If this matchstick can fir in the space left for the current side + if sums[i] + nums[index] <= possible_side: + # Recurse + sums[i] += nums[index] + if dfs(index + 1): + return True + # Revert the effects of recursion because we no longer need them for other recursions. + sums[i] -= nums[index] + return False + return dfs(0) +``` + + + +This solution is very slow as is. However, we can speed it up considerably by a small trick and that is to `sort our matchsticks sizes in reverse order before processing them recursively`. +The reason for this is that if there is no solution, trying a longer matchstick first will get to negative conclusion earlier. + +e.g. [8,4,4,4]. In this case we can have a square of size 5 but the largest side 8 doesn't fit in anywhere i.e. cannot be a part of any of the sides (because we can't break matchsticks according to the question) and hence we can simply return Falsewithout even considering the remaining matchsticks. +## Complexity Analysis + +### Time Complexity: $O(4^N)$ + +> **Reason**: because we have a total of N sticks and for each one of those matchsticks, we have 4 different possibilities for the subsets they might belong to or the side of the square they might be a part of. + +### Space Complexity: $O(N)$ + +> **Reason**: For recursive solutions, the space complexity is the stack space occupied by all the recursive calls. The deepest recursive call here would be of size N and hence the space complexity is O(N). There is no additional space other than the recursion stack in this solution. + +### Approach 2: Dynamic Programming + +#### Intuition + +In any dynamic programming problem, what's important is that our problem must be breakable into smaller subproblems and also, these subproblems show some sort of overlap which we can save upon by caching or memoization. +Suppose we have `3,3,4,4,5,5` as our matchsticks that have been used already to construct some of the sides of our square (**Note:** not all the sides may be completely constructed at all times.) +If the square side is 8, then there are many possibilities for how the sides can be constructed using the matchsticks above. We can have +``` +(4, 4), (3, 5), (3, 5) -----------> 3 sides fully constructed. +(3, 4), (3, 5), (4), (5) ---------> 0 sides completely constructed. +(3, 3), (4, 4), (5), (5) ---------> 1 side completely constructed. +``` +As we can see above, there are multiple ways to use the same set of matchsticks and land up in completely different recursion states. + +This means that if we just keep track of what all matchsticks have been used and which all are remaining, it won't properly define the state of recursion we are in or what subproblem we are solving. + +A single set of used matchsticks can represent multiple different unrelated subproblems and that is just not right. + +We also need to keep track of number of sides of the square that have been **completely** formed till now. +Also, an important thing to note in the example we just considered was that if the matchsticks being used are [3,3,4,4,5,5] and the side of the square is 8, then we will always consider that arrangement that forms the most number of complete sides over that arrangement that leads to incomplete sides. Hence, the optimal arrangement here is (4,4),(3,5),(3,5) with 3 complete sides of the square. + +Let us take a look at the following recursion tree to see if in-fact we can get overlapping subproblems. +![image](https://assets.leetcode.com/static_assets/media/original_images/473/473_Matchsticks-In-Square-Diag-2.png) + +**Note:** Not all subproblems have been shown in this figure. The thing we wanted to point out was overlapping subproblems. + +We know that the overall sum of these matchsticks can be split equally into 4 halves. The only thing we don't know is if 4 **equal** halves can be carved out of the given set of matchsticks. For that also we need to keep track of the number of sides completely formed at any point in time. **If we end up forming 4 equal sides successfully then naturally we would have used up all of the matchsticks each being used exactly once and we would have formed a square.** + +### Algorithm + +Let us first look at the pseudo-code for this problem before looking at the exact implementation details for the same. +``` +let square_side = sum(matchsticks) / 4 +func recurse(matchsticks_used, sides_formed) { + if sides_formed == 4, then { + Square Formed!! + } + for match in matchsticks available, do { + add match to matchsticks_used + let result = recurse(matchsticks_used, sides_formed) + if result == True, then { + return True + } + remove match from matchsticks_used + } + return False +} +``` +This is the overall structure of our dynamic programming solution. Of course, a lot of implementation details are missing here that we will address now. + +It is very clear from the pseudo-code above that the state of a recursion is defined by two variables `matchsticks_used` and `sides_formed`. Hence, these are the two variables that will be used to **memoize** or cache the results for that specific subproblem. + +The question however is how do we actually store all the matchsticks that have been used? We want a memory efficient solution for this. + +If we look at the question's constraints, we find that the max number of matchsticks we can have are 15. That's a pretty small number and we can make use of this constraint. + +All we need to store is which of the matchsticks from the original list have been used. `We can use a Bit-Map for this` + +We will use N number of bits, one for each of the matchsticks (N is at max 15 according to the question's constraints). Initially we will start with a bit mask of `all 1s` and then as we keep on using the matchsticks, we will keep on setting their corresponding bits to `0`. + +This way, we just have to hash an integer value which represents our bit-map and the max value for this mask would be $2^{15}$. + +**Do we really need to see if all 4 sides have been completely formed ?** + +Another implementation trick that helps optimize this solution is that we don't really need to see if 4 sides have been completely formed. + +This is because, we already know that the sum of all the matchsticks is divisible by 4. So, if 3 equal sides have been formed by using some of the matchsticks, then the remaining matchsticks would definitely form the remaining side of our square. + +Hence, we only need to check if 3 sides of our square can be formed or not. + + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include +#include // For std::accumulate +#include // For std::sort + +// Custom hash function for std::pair +struct pair_hash { + template + std::size_t operator()(const std::pair& p) const { + auto hash1 = std::hash{}(p.first); + auto hash2 = std::hash{}(p.second); + return hash1 ^ hash2; + } +}; + +class Solution { +public: + // The memoization cache to be used during recursion. + std::unordered_map, bool, pair_hash> memo; + + // Array containing our matchsticks. + std::vector nums; + + // Possible side of our square depending on the total sum of all the matchsticks. + int possibleSquareSide; + + // Default constructor to initialize our memo cache. + Solution() : possibleSquareSide(0) {} + + // Main DP function. + bool recurse(int mask, int sidesDone) { + int total = 0; + int L = nums.size(); + + // The memo key for this recursion + std::pair memoKey = std::make_pair(mask, sidesDone); + + // Find out the sum of matchsticks used till now. + for (int i = L - 1; i >= 0; i--) { + if ((mask & (1 << i)) == 0) { + total += nums[L - 1 - i]; + } + } + + // If the sum is divisible by our square's side, then we increment our number of complete sides formed variable. + if (total > 0 && total % possibleSquareSide == 0) { + sidesDone++; + } + + // Base case. + if (sidesDone == 3) { + return true; + } + + // Return precomputed results + if (memo.find(memoKey) != memo.end()) { + return memo[memoKey]; + } + + bool ans = false; + int c = total / possibleSquareSide; + + // Remaining length in the current partially formed side. + int rem = possibleSquareSide * (c + 1) - total; + + // Try out all remaining options (that are valid) + for (int i = L - 1; i >= 0; i--) { + if (nums[L - 1 - i] <= rem && (mask & (1 << i)) > 0) { + if (recurse(mask ^ (1 << i), sidesDone)) { + ans = true; + break; + } + } + } + + // Cache the computed results. + memo[memoKey] = ans; + return ans; + } + + bool makesquare(std::vector& matchsticks) { + // Empty matchsticks. + if (matchsticks.empty()) { + return false; + } + + // Find the perimeter of the square (if at all possible) + int L = matchsticks.size(); + int perimeter = std::accumulate(matchsticks.begin(), matchsticks.end(), 0); + + possibleSquareSide = perimeter / 4; + if (possibleSquareSide * 4 != perimeter) { + return false; + } + + nums = matchsticks; + std::sort(nums.rbegin(), nums.rend()); // Sort in descending order + + return recurse((1 << L) - 1, 0); + } +}; + +``` + + + + +```java +import java.util.HashMap; + +class Solution { + + // The memoization cache to be used during recursion. + public HashMap, Boolean> memo; + + // Array containing our matchsticks. + public int[] nums; + + // Possible side of our square depending on the total sum of all the matchsticks.Β  + public int possibleSquareSide; + + // Default constructor to initialise our memo cache. + public Solution() { + this.memo = new HashMap, Boolean>(); + } + + // Main DP function. + public boolean recurse(Integer mask, Integer sidesDone) { + int total = 0; + int L = this.nums.length; + + // The memo key for this recursion + Pair memoKey = new Pair(mask, sidesDone); + + // Find out the sum of matchsticks used till now. + for(int i = L - 1; i >= 0; i--) { + if ((mask&(1 << i)) == 0) { + total += this.nums[L - 1 - i]; + } + } + + // If the sum if divisible by our square's side, then we increment our number of complete sides formed variable. + if (total > 0 && total % this.possibleSquareSide == 0) { + sidesDone++; + } + + // Base case. + if (sidesDone == 3) { + return true; + } + + + // Return precomputed results + if (this.memo.containsKey(memoKey)) { + return this.memo.get(memoKey); + } + + boolean ans = false; + int c = total / this.possibleSquareSide; + + // Remaining vlength in the current partially formed side. + int rem = this.possibleSquareSide * (c + 1) - total; + + // Try out all remaining options (that are valid) + for(int i = L - 1; i >= 0; i--) { + if (this.nums[L - 1 - i] <= rem && (mask&(1 << i)) > 0) { + if (this.recurse(mask ^ (1 << i), sidesDone)) { + ans = true; + break; + } + } + } + + // Cache the computed results. + this.memo.put(memoKey, ans); + return ans; + } + + public boolean makesquare(int[] nums) { + + // Empty matchsticks. + if (nums == null || nums.length == 0) { + return false; + } + + // Find the perimeter of the square (if at all possible) + int L = nums.length; + int perimeter = 0; + for(int i = 0; i < L; i++) { + perimeter += nums[i]; + } + + int possibleSquareSide = perimeter / 4; + if (possibleSquareSide * 4 != perimeter) { + return false; + } + + this.nums = nums; + this.possibleSquareSide = possibleSquareSide; + return this.recurse((1 << L) - 1, 0); + } +} +``` + + + + + +```python +def makesquare(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + + # If there are no matchsticks, then we can't form any square. + if not nums: + return False + + # Number of matchsticks + L = len(nums) + + # Possible perimeter of our square + perimeter = sum(nums) + + # Possible side of our square from the given matchsticks + possible_side = perimeter // 4 + + # If the perimeter isn't equally divisible among 4 sides, return False. + if possible_side * 4 != perimeter: + return False + + # Memoization cache for the dynamic programming solution. + memo = {} + + # mask and the sides_done define the state of our recursion. + def recurse(mask, sides_done): + + # This will calculate the total sum of matchsticks used till now using the bits of the mask. + total = 0 + for i in range(L - 1, -1, -1): + if not (mask & (1 << i)): + total += nums[L - 1 - i] + + # If some of the matchsticks have been used and the sum is divisible by our square's side, then we increment the number of sides completed. + if total > 0 and total % possible_side == 0: + sides_done += 1 + + # If we were successfully able to form 3 sides, return True + if sides_done == 3: + return True + + # If this recursion state has already been calculated, just return the stored value. + if (mask, sides_done) in memo: + return memo[(mask, sides_done)] + + # Common variable to store answer from all possible further recursions from this step. + ans = False + + # rem stores available space in the current side (incomplete). + c = int(total / possible_side) + rem = possible_side * (c + 1) - total + + # Iterate over all the matchsticks + for i in range(L - 1, -1, -1): + + # If the current one can fit in the remaining space of the side and it hasn't already been taken, then try it out + if nums[L - 1 - i] <= rem and mask&(1 << i): + + # If the recursion after considering this matchstick gives a True result, just break. No need to look any further. + # mask ^ (1 << i) makes the i^th from the right, 0 making it unavailable in future recursions. + if recurse(mask ^ (1 << i), sides_done): + ans = True + break + # cache the result for the current recursion state. + memo[(mask, sides_done)] = ans + return ans + + # recurse with the initial mask with all matchsticks available. + return recurse((1 << L) - 1, 0) +``` + + + +## Complexity Analysis + +### Time Complexity: $O(NΓ—2^N)$ + +> **Reason**: At max $2^N$ unique bit masks are possible and during every recursive call, we iterate our original matchsticks array to sum up the values of matchsticks used to update the `sides_formed` variable. +### Space Complexity: $O(N+2^N)$ + +> **Reason**: because N is the stack space taken up by recursion and $4Γ—2^N= O(2^N)$ is the max possible size of our cache for memoization. + +## References + +- **LeetCode Problem**: [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/description/) + +- **Solution Link**: [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0475-heaters.md b/solutions/lc-solutions/0400-0499/0475-heaters.md new file mode 100644 index 0000000..9b03ffa --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0475-heaters.md @@ -0,0 +1,122 @@ +--- +id: heaters +title: Heaters +sidebar_label: 0475-heaters +tags: + - Array + - Binary Search + - Two Pointers + - Sorting +description: "This is a solution to the heaters problem on LeetCode." +--- + +## Problem Description + +Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. + +Every house can be warmed, as long as the house is within the heater's warm radius range. + +Given the positions of `houses` and `heaters` on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses. + +Notice that all the `heaters` follow your radius standard, and the warm radius will the same. + +### Examples + +**Example 1:** + +``` +Input: houses = [1,2,3,4], heaters = [1,4] +Output: 1 +Explanation: The two heaters were placed at positions 1 and 4. We need to use a radius 1 standard, then all the houses can be warmed. +``` + +**Example 2:** + +``` +Input: houses = [1,5], heaters = [2] +Output: 3 +``` + +### Constraints + +- `1 <= houses.length, heaters.length <= 3 * 104` +- `1 <= houses[i], heaters[i] <= 109` + +### Approach: + +1. Sort and Binary Search +- Sort Heaters array and perform binary search on the house +- If the returned index is greater or equal to zero, ,that means the house is located right on heater, we can ignore it +- If the returned index is smaller than 0, we can have find the left and right heater for this house and get the radius (left will be i -1th and right will be ith position) +- The min of the radii will compare with the res, and the max of them is our temporary res + +2. Sort and Two Pointers +- If we sort both arrays, we just need to find the first heater that is closest to the house +- Then the result is simply the max of distance between the house-heater and the previous res +- To find the closest heater, we use while loop until we get the heater that is closer than previous heater + + +## Code in Different Languages + + + + + +```cpp +class Solution { + public: + int findRadius(vector& houses, vector& heaters) { + ranges::sort(houses); + ranges::sort(heaters); + + int ans = 0; + int i = 0; // heaters' index (currently used) + + for (const int house : houses) { + while (i + 1 < heaters.size() && + house - heaters[i] > heaters[i + 1] - house) + ++i; // The next heater is better. + ans = max(ans, abs(heaters[i] - house)); + } + + return ans; + } +}; +``` + + + + +```java +class Solution { + public int findRadius(int[] houses, int[] heaters) { + Arrays.sort(houses); + Arrays.sort(heaters); + + int ans = 0; + int i = 0; // heaters' index (currently used) + + for (final int house : houses) { + while (i + 1 < heaters.length && house - heaters[i] > heaters[i + 1] - house) + ++i; // The next heater is better. + ans = Math.max(ans, Math.abs(heaters[i] - house)); + } + + return ans; + } +} +``` + + + +## Complexity Analysis + +### Time Complexity: max(O(mlogm),O(nlogn)), where π‘š = ∣houses| and n = |heaters| + +### Space Complexity: O(1) + +## References + +- **LeetCode Problem**: [Heaters](https://leetcode.com/problems/heaters/description/) + +- **Solution Link**: [Heaters](https://leetcode.com/problems/heaters/solutions/) diff --git a/solutions/lc-solutions/0400-0499/0476-number-complement.md b/solutions/lc-solutions/0400-0499/0476-number-complement.md new file mode 100644 index 0000000..2d0946d --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0476-number-complement.md @@ -0,0 +1,89 @@ +--- +id: number-complement +title: Number Complement +tags: +- Bit Manipulation +description: "This is a solution to the number complement problem on LeetCode." +--- + +## Problem Description + +The complement of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation. + +For example, The integer `5` is `"101"` in binary and its complement is `"010"` which is the integer `2`. +Given an integer `num`, return its complement. + +### Examples + +**Example 1:** +``` +Input: num = 5 +Output: 2 +Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. +``` + +**Example 2:** + +``` +Input: num = 1 +Output: 0 +Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. +``` + +### Constraints + +- `1 <= num < 231` + +#### Intuition +The key to solving this problem lies in understanding bitwise operations. In particular, the XOR operation becomes very useful. XOR, or exclusive or, gives us a 1 bit whenever the bits in the same position of the two numbers are different, and a 0 bit when they are the same. + +So, if we XOR the given number with a number that has all bits set to 1, and is of the same length, we will effectively switch all bits of the original number - 0s will become 1s, and 1s will become 0s. This is exactly the complement. + +To get a number with all bits set to 1 and of the same length as num, we can use the fact that a power of two, when decreased by 1, will give us a number with all bits set to 1 that is one less in size. For instance, 2^3 is 1000 in binary, and 2^3 - 1 is 0111. + +Therefore, we calculate 2 raised to the power of the length of the binary representation of num minus 1. To find the length of the binary representation, we convert num to binary using bin(num), slice off the '0b' prefix with [2:], and then take the len of it. Once we have this number, we can XOR it with num to get the desired complement. + + + +## Code in Different Languages + + + + +```cpp +class Solution { + public: + int findComplement(long num) { + for (long i = 1; i <= num; i <<= 1) + num ^= i; + return num; + } +}; + +``` + + + +```java +class Solution { + public int findComplement(int num) { + for (long i = 1; i <= num; i <<= 1) + num ^= i; + return num; + } +} +``` + + + +## Complexity Analysis + +### Time Complexity: O(32)=O(1) + +### Space Complexity: O(1) + +## References + +- **LeetCode Problem**: [Matchsticks to Square](https://leetcode.com/problems/number-complement/) + +- **Solution Link**: [Matchsticks to Square](https://leetcode.com/problems/number-complement/solutions/) diff --git a/solutions/lc-solutions/0400-0499/0477-total-hamming-distance.md b/solutions/lc-solutions/0400-0499/0477-total-hamming-distance.md new file mode 100644 index 0000000..ac641b0 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0477-total-hamming-distance.md @@ -0,0 +1,132 @@ +--- +id: total-hamming-distance +title: Total Hamming Distance +sidebar_label: 0477-total-hamming-distance +tags: +- Array +- Math +- Bit Manipulation +description: "This is a solution to the total hamming distance problem on LeetCode." +--- + +## Problem Description + +The Hamming distance between two integers is the number of positions at which the corresponding bits are different. + +Given an integer array `nums`, return the sum of Hamming distances between all the pairs of the integers in `nums`. + +### Examples + +**Example 1:** + +``` +Input: nums = [4,14,2] +Output: 6 +Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just +showing the four bits relevant in this case). +The answer will be: +HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. + +``` + +**Example 2:** + +``` +Input: nums = [4,14,4] +Output: 4 +``` + +### Constraints + +- `1 <= nums.length <= 104` +- `0 <= nums[i] <= 109` +- The answer for the given input will fit in a 32-bit integer. + +## Solution for Matchsticks to Square + +1. Initialize ans to 0. This variable will hold the sum of Hamming distances. +2. Use a loop to iterate over each bit position. In this case, we loop from 0 to 30, inclusive, because an integer is 32 bits in size and we assume we're dealing with positive numbers only (no need for the sign bit). +3. Inside this loop, initialize two counters a and b to 0. Counter a will keep track of the number of 1's and b of the number of 0's for the current bit position across all numbers in nums. +4. Inner loop through each number v in nums: +- Shift v right by i bits and perform a bitwise AND with 1 ((v >> i) & 1) to isolate the bit at the current bit position. +- If the result is 1, increment counter a (since this number contributes a 1 to the current bit position). +- If the result is 0, increment counter b (since this number contributes a 0 to the current bit position). +5. Outside the inner loop but still inside the first loop, multiply a and b and add the result to ans. This is based on the observation that each pair of numbers contributes 1 to the Hamming distance sum for this bit position if one of them has a 1 and the other has a 0. The total contribution from this bit position is therefore the product of the numbers of 1's and 0's. +6. After completing the loops, ans contains the sum of the Hamming distances, and we return this value. + +## Code in Different Languages + + + + +```cpp +class Solution { + public: + int totalHammingDistance(vector& nums) { + constexpr int kMaxMask = 1 << 30; + int ans = 0; + + for (int mask = 1; mask < kMaxMask; mask <<= 1) { + const int ones = + ranges::count_if(nums, [mask](int num) { return num & mask; }); + const int zeros = nums.size() - ones; + ans += ones * zeros; + } + + return ans; + } +}; + + +``` + + + +```java +class Solution { + public int totalHammingDistance(int[] nums) { + final int kMaxBit = 30; + int ans = 0; + + for (int i = 0; i < kMaxBit; ++i) { + final int mask = 1 << i; + final int ones = (int) Arrays.stream(nums).filter(num -> (num & mask) > 0).count(); + final int zeros = nums.length - ones; + ans += ones * zeros; + } + + return ans; + } +} +``` + + + + +```python +class Solution: + def totalHammingDistance(self, nums: List[int]) -> int: + kMaxBit = 30 + ans = 0 + + for i in range(kMaxBit): + ones = sum(num & (1 << i) > 0 for num in nums) + zeros = len(nums) - ones + ans += ones * zeros + + return ans +``` + + + +## Complexity Analysis + +### Time Complexity: O(30n)=O(n) + +### Space Complexity: O(1) + +## References + +- **LeetCode Problem**: [Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/description/) + +- **Solution Link**: [Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/solutions/) diff --git a/solutions/lc-solutions/0400-0499/0485-Max-Consecutive-Ones.md b/solutions/lc-solutions/0400-0499/0485-Max-Consecutive-Ones.md new file mode 100644 index 0000000..a917060 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0485-Max-Consecutive-Ones.md @@ -0,0 +1,145 @@ +--- +id: Max-Consecutive-Ones +title: Max Consecutive Ones +sidebar_label: 0485-Max-Consecutive-Ones +tags: + - Array +description: "Given a binary array nums, return the maximum number of consecutive 1's in the array." + +--- + + + +## Problem Statement + +Given a binary array nums, return the maximum number of consecutive 1's in the array. + + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [1,1,0,1,1,1] +Output: 3 +Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. +``` + +**Example 2:** + +```plaintext +Input: nums = [1,0,1,1,0,1] +Output: 2 +``` + +### Constraints + +- `1 <= nums.length <= 105` +- nums[i] is either 0 or 1. + + +## Solution + +We maintain a variable count that keeps a track of the number of consecutive 1’s while traversing the array. +The other variable max_count maintains the maximum number of 1’s, in other words, it maintains the answer. + +### Approach + +#### Algorithm +We start traversing from the beginning of the array. Since we can encounter either a 1 or 0 there can be two situations:- + - If the value at the current index is equal to 1 we increase the value of count by one. + After updating the count variable if it becomes more than the max_count, update the max_count. + - If the value at the current index is equal to zero we make the variable count as 0 since there are no more consecutive ones. + +#### Solution + +### Java Solution + +```Java +import java.util.*; +public class Main { + static int findMaxConsecutiveOnes(int nums[]) { + int cnt = 0; + int maxi = 0; + for (int i = 0; i < nums.length; i++) { + if (nums[i] == 1) { + cnt++; + } else { + cnt = 0; + } + + maxi = Math.max(maxi, cnt); + } + return maxi; + } + public static void main(String args[]) { + int nums[] = { 1, 1, 0, 1, 1, 1 }; + int ans = findMaxConsecutiveOnes(nums); + System.out.println("The maximum consecutive 1's are " + ans); + } +} + +``` + +### C++ Solution + +```cpp +#include + +using namespace std; +class Solution { + public: + int findMaxConsecutiveOnes(vector < int > & nums) { + int cnt = 0; + int maxi = 0; + for (int i = 0; i < nums.size(); i++) { + if (nums[i] == 1) { + cnt++; + } else { + cnt = 0; + } + + maxi = max(maxi, cnt); + } + return maxi; + } +}; + +int main() { + vector < int > nums = { 1, 1, 0, 1, 1, 1 }; + Solution obj; + int ans = obj.findMaxConsecutiveOnes(nums); + cout << "The maximum consecutive 1's are " << ans; + return 0; +} +``` + +### Python Solution + +```python + +from typing import List +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + cnt = 0 + maxi = 0 + for i in range(len(nums)): + if nums[i] == 1: + cnt += 1 + else: + cnt = 0 + maxi = max(maxi, cnt) + return maxi + + +if __name__ == "__main__": + nums = [1, 1, 0, 1, 1, 1] + obj = Solution() + ans = obj.findMaxConsecutiveOnes(nums) + print("The maximum consecutive 1's are", ans) +``` + +### Complexity Analysis + +- **Time complexity**: $O(N)$, since the solution involves only a single pass. +- **Space complexity**: $O(1)$, because no extra space is used. diff --git a/solutions/lc-solutions/0400-0499/0486-predict-the-winner.md b/solutions/lc-solutions/0400-0499/0486-predict-the-winner.md new file mode 100644 index 0000000..9a76b30 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0486-predict-the-winner.md @@ -0,0 +1,166 @@ +--- +id: predict-the-winner +title: Predict the Winner +sidebar_label: 0486 - Predict the Winner +tags: + - Leetcode + - Dynamic Programming +--- + +## Problem Statement + +You are given an integer array `nums`. Two players, player 1 and player 2, are playing a game with this array. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` or `nums[nums.length - 1]`), which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array. + +Return `true` if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return `true`. You may assume that both players are playing optimally. + +## Examples + +### Example 1 + +- Input: `nums = [1,5,2]` +- Output: `false` +- Explanation: Initially, player 1 can choose between 1 and 2. + If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). + So, the final score of player 1 is 1 + 2 = 3, and player 2 is 5. + Hence, player 1 will never be the winner and you need to return `false`. + +### Example 2 + +- Input: `nums = [1,5,233,7]` +- Output: `true` +- Explanation: Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 chooses, player 1 can choose 233. + Finally, player 1 has a higher score (234) than player 2 (12), so you need to return `true`, representing player 1 can win. + +## Constraints + +- $1 <= nums.length <= 20$ +- $0 <= nums[i] <= 107$ + +## Algorithm + +1. Use a recursive approach with memoization to solve the problem. +2. Define a function `game(start, end)` that returns the maximum score the current player can achieve from the subarray `nums[start:end+1]`. +3. If `start` is greater than `end`, return 0. +4. If `start` equals `end`, return `nums[start]`. +5. Calculate the score for taking the start or end element and return the maximum of these two options. +6. Use a memoization table to store the results of the recursive calls to avoid recomputation. +7. Compare the score of player 1 with the total score and return true if player 1's score is greater than or equal to half the total score. + +## Code + +### Python + +```python +class Solution: + def predictTheWinner(self, nums: List[int]) -> bool: + n = len(nums) + memo = {} + + def game(start, end): + if start > end: + return 0 + if (start, end) in memo: + return memo[(start, end)] + if start == end: + return nums[start] + take_start = nums[start] + min(game(start + 2, end), game(start + 1, end - 1)) + take_end = nums[end] + min(game(start + 1, end - 1), game(start, end - 2)) + memo[(start, end)] = max(take_start, take_end) + return memo[(start, end)] + + total_score = sum(nums) + player_1 = game(0, n - 1) + player_2 = total_score - player_1 + return player_1 >= player_2 +``` + +### C++ + +```cpp +#include +#include +#include +using namespace std; + +class Solution { +public: + unordered_map memo; + + int game(int start, int end, vector& nums) { + if (start > end) return 0; + string key = to_string(start) + "," + to_string(end); + if (memo.find(key) != memo.end()) return memo[key]; + if (start == end) return nums[start]; + int take_start = nums[start] + min(game(start + 2, end, nums), game(start + 1, end - 1, nums)); + int take_end = nums[end] + min(game(start + 1, end - 1, nums), game(start, end - 2, nums)); + memo[key] = max(take_start, take_end); + return memo[key]; + } + + bool predictTheWinner(vector& nums) { + int n = nums.size(); + int total_score = accumulate(nums.begin(), nums.end(), 0); + int player_1 = game(0, n - 1, nums); + int player_2 = total_score - player_1; + return (player_1 >= player_2); + } +}; +``` + +### Java + +```java +import java.util.HashMap; +import java.util.Map; + +class Solution { + private Map memo = new HashMap<>(); + + public int game(int start, int end, int[] nums) { + if (start > end) return 0; + String key = start + "," + end; + if (memo.containsKey(key)) return memo.get(key); + if (start == end) return nums[start]; + int takeStart = nums[start] + Math.min(game(start + 2, end, nums), game(start + 1, end - 1, nums)); + int takeEnd = nums[end] + Math.min(game(start + 1, end - 1, nums), game(start, end - 2, nums)); + memo.put(key, Math.max(takeStart, takeEnd)); + return memo.get(key); + } + + public boolean predictTheWinner(int[] nums) { + int n = nums.length; + int totalScore = 0; + for (int num : nums) totalScore += num; + int player1 = game(0, n - 1, nums); + int player2 = totalScore - player1; + return player1 >= player2; + } +} +``` + +### JavaScript + +```javascript +var PredictTheWinner = function (nums) { + const memo = new Map(); + + const game = (start, end) => { + if (start > end) return 0; + const key = start + "," + end; + if (memo.has(key)) return memo.get(key); + if (start === end) return nums[start]; + const takeStart = + nums[start] + Math.min(game(start + 2, end), game(start + 1, end - 1)); + const takeEnd = + nums[end] + Math.min(game(start + 1, end - 1), game(start, end - 2)); + const result = Math.max(takeStart, takeEnd); + memo.set(key, result); + return result; + }; + + const totalScore = nums.reduce((a, b) => a + b, 0); + const player1 = game(0, nums.length - 1); + const player2 = totalScore - player1; + return player1 >= player2; +}; +``` diff --git a/solutions/lc-solutions/0400-0499/0491-non-decreasing-subsequences.md b/solutions/lc-solutions/0400-0499/0491-non-decreasing-subsequences.md new file mode 100644 index 0000000..7a3592f --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0491-non-decreasing-subsequences.md @@ -0,0 +1,143 @@ +--- +id: non-decreasing-subsequences +title: Non-Decreasing Subsequences +sidebar_label: 0491 - Non-Decreasing Subsequences +tags: + - Leetcode + - Back-Tracking +--- + +## Problem Statement + +Given an integer array `nums`, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order. + +## Examples + +### Example 1 + +- Input: `nums = [4,6,7,7]` +- Output: `[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]` + +### Example 2 + +- Input: `nums = [4,4,3,2,1]` +- Output: `[[4,4]]` + +## Constraints + +- $1 <= nums.length <= 15$ +- $-100 <= nums[i] <= 100$ + +## Algorithm + +1. Use depth-first search (DFS) to explore all subsequences. +2. Start from the beginning of the array and for each element, either include it in the current subsequence if it maintains non-decreasing order or skip it. +3. Use a set to ensure that each element is used only once at each level of recursion to avoid duplicates. +4. Add the current subsequence to the result if it has at least two elements. + +## Code + +### Python + +```python +class Solution: + def findSubsequences(self, nums: List[int]) -> List[List[int]]: + def dfs(start, path): + if len(path) > 1: + res.append(path) + used = set() + for i in range(start, len(nums)): + if nums[i] not in used and (not path or nums[i] >= path[-1]): + used.add(nums[i]) + dfs(i + 1, path + [nums[i]]) + + res = [] + dfs(0, []) + return res +``` + +### C++ + +```cpp +class Solution { +public: + vector> ans; + + void dfs(vector& nums, vector& temp, int index) { + if (temp.size() > 1) ans.push_back(temp); + + unordered_set used; + for (int i = index; i < nums.size(); i++) { + if ((temp.empty() || temp.back() <= nums[i]) && used.find(nums[i]) == used.end()) { + temp.push_back(nums[i]); + dfs(nums, temp, i + 1); + temp.pop_back(); + used.insert(nums[i]); + } + } + } + + vector> findSubsequences(vector& nums) { + vector temp; + dfs(nums, temp, 0); + return ans; + } +}; +``` + +### Java + +```java +import java.util.*; + +class Solution { + List> ans = new ArrayList<>(); + + public void dfs(int[] nums, List temp, int index) { + if (temp.size() > 1) ans.add(new ArrayList<>(temp)); + + Set used = new HashSet<>(); + for (int i = index; i < nums.length; i++) { + if ((temp.isEmpty() || temp.get(temp.size() - 1) <= nums[i]) && used.add(nums[i])) { + temp.add(nums[i]); + dfs(nums, temp, i + 1); + temp.remove(temp.size() - 1); + } + } + } + + public List> findSubsequences(int[] nums) { + dfs(nums, new ArrayList<>(), 0); + return ans; + } +} +``` + +### JavaScript + +```javascript +var findSubsequences = function (nums) { + const res = []; + + const dfs = (start, path) => { + if (path.length > 1) { + res.push([...path]); + } + const used = new Set(); + for (let i = start; i < nums.length; i++) { + if ( + !used.has(nums[i]) && + (path.length === 0 || nums[i] >= path[path.length - 1]) + ) { + used.add(nums[i]); + path.push(nums[i]); + dfs(i + 1, path); + path.pop(); + } + } + }; + + dfs(0, []); + return res; +}; +``` diff --git a/solutions/lc-solutions/0400-0499/0492-construct-the-rectangle.md b/solutions/lc-solutions/0400-0499/0492-construct-the-rectangle.md new file mode 100644 index 0000000..255015f --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0492-construct-the-rectangle.md @@ -0,0 +1,106 @@ +--- +id: construct-the-rectangle +title: Construct The Rectangle +sidebar_label: 0492 - Construct The Rectangle +tags: + - Leetcode +--- + +## Problem Statement + +A web developer needs to know how to design a web page's size. Given a specific rectangular web page’s area, your task is to design a rectangular web page with length `L` and width `W` that satisfy the following requirements: + +1. The area of the rectangular web page must equal the given target area. +2. The width `W` should not be larger than the length `L`, which means `L >= W`. +3. The difference between length `L` and width `W` should be as small as possible. + +Return an array `[L, W]` where `L` and `W` are the length and width of the web page you designed in sequence. + +## Examples + +### Example 1 + +- Input: `area = 4` +- Output: `[2,2]` +- Explanation: The target area is 4, and all the possible ways to construct it are `[1,4]`, `[2,2]`, `[4,1]`. But according to requirement 2, `[1,4]` is illegal; according to requirement 3, `[4,1]` is not optimal compared to `[2,2]`. So the length `L` is 2, and the width `W` is 2. + +### Example 2 + +- Input: `area = 37` +- Output: `[37,1]` + +### Example 3 + +- Input: `area = 122122` +- Output: `[427,286]` + +## Constraints + +- $1 <= area <= 107$ + +## Algorithm + +1. Start by initializing the width W as the integer square root of the given area. +2. Decrement the width W until you find a divisor of the area. +3. The corresponding length L is the quotient of the area divided by the width. +4. Return [L, W]. + +## Code + +### Python + +```python +import math + +class Solution: + def constructRectangle(self, area: int) -> List[int]: + width = int(math.sqrt(area)) + while area % width != 0: + width -= 1 + length = area // width + return [length, width] +``` + +### C++ + +```cpp +class Solution { +public: + vector constructRectangle(int area) { + int width = sqrt(area); + while (area % width != 0) { + width--; + } + int length = area / width; + return {length, width}; + } +}; +``` + +### Java + +```java +class Solution { + public int[] constructRectangle(int area) { + int width = (int) Math.sqrt(area); + while (area % width != 0) { + width--; + } + int length = area / width; + return new int[]{length, width}; + } +} +``` + +### JavaScript + +```javascript +var constructRectangle = function (area) { + let width = Math.floor(Math.sqrt(area)); + while (area % width !== 0) { + width--; + } + let length = Math.floor(area / width); + return [length, width]; +}; +``` diff --git a/solutions/lc-solutions/0400-0499/0493-reverse-pairs.md b/solutions/lc-solutions/0400-0499/0493-reverse-pairs.md new file mode 100644 index 0000000..0eba99b --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0493-reverse-pairs.md @@ -0,0 +1,323 @@ +--- +id: reverse-pairs +title: Reverse Pairs +sidebar_label: 493-Reverse-Pairs +tags: + - Array + - Binary Search + - Divide and conquer + - Binary Indexed Tree + - Segment Tree + - Merge Sort + - Ordered Set +description: The problem is to reverse the pairs. +sidebar_position: 2667 +--- + +## Problem Statement + +### Problem Description + +Given an integer array `nums`, return the number of reverse pairs in the array. + +A reverse pair is a pair `(i, j)` where: + +`0 <= i < j < nums.length` and +`nums[i] > 2 * nums[j]`. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,3,2,3,1] +Output: 2 +Explanation: The reverse pairs are: +(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1 +(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1 +``` + +**Example 2:** + +``` +Input: nums = [2,4,3,5,1] +Output: 3 +Explanation: The reverse pairs are: +(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1 +(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1 +(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1 +``` + +### Constraints + +- `1 <= nums.length <= 5 * 10^4` + +## Solution of Given Problem + +### Intuition and Approach + +The intuition behind this solution is to use a modified Merge Sort algorithm to count the number of reverse pairs in the array. + + +### Approaches + +- Divide the array into smaller subarrays until each subarray has only one element. +- Merge the subarrays back together, counting the number of reverse pairs between each pair of subarrays. +- The merge step is done in a way that ensures the count of reverse pairs is accurate. + + +#### Codes in Different Languages + + + + + ```javascript + function mergeSortedArrays(nums, left, mid, right, temp) { + let i = left, j = mid + 1, k = 0; + while (i <= mid && j <= right) { + if (nums[i] <= nums[j]) temp[k++] = nums[i++]; + else temp[k++] = nums[j++]; + } + while (i <= mid) temp[k++] = nums[i++]; + while (j <= right) temp[k++] = nums[j++]; +} + +function merge(nums, left, mid, right) { + let count = 0; + let j = mid + 1; + for (let i = left; i <= mid; i++) { + while (j <= right && nums[i] > 2 * nums[j]) j++; + count += j - mid - 1; + } + let temp = new Array(right - left + 1); + mergeSortedArrays(nums, left, mid, right, temp); + for (let i = left; i <= right; i++) nums[i] = temp[i - left]; + return count; +} +function mergeSort(nums, left, right) { + if (left >= right) return 0; + let mid = left + (right - left) / 2; + let count = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right); + count += merge(nums, left, mid, right); + return count; +} + +class Solution { + reversePairs(nums) { + return mergeSort(nums, 0, nums.length - 1); + } +} + + + ``` + + + + + ```typescript + function mergeSortedArrays(nums: number[], left: number, mid: number, right: number, temp: number[]) { + let i = left, j = mid + 1, k = 0; + while (i <= mid && j <= right) { + if (nums[i] <= nums[j]) temp[k++] = nums[i++]; + else temp[k++] = nums[j++]; + } + while (i <= mid) temp[k++] = nums[i++]; + while (j <= right) temp[k++] = nums[j++]; +} + +function merge(nums: number[], left: number, mid: number, right: number) { + let count = 0; + let j = mid + 1; + for (let i = left; i <= mid; i++) { + while (j <= right && nums[i] > 2 * nums[j]) j++; + count += j - mid - 1; + } + let temp = new Array(right - left + 1); + mergeSortedArrays(nums, left, mid, right, temp); + for (let i = left; i <= right; i++) nums[i] = temp[i - left]; + return count; +} +function mergeSort(nums: number[], left: number, right: number) { + if (left >= right) return 0; + let mid = left + (right - left) / 2; + let count = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right); + count += merge(nums, left, mid, right); + return count; +} + +class Solution { + reversePairs(nums: number[]) { + return mergeSort(nums, 0, nums.length - 1); + } +} + + ``` + + + + + ```python + def merge_sorted_arrays(nums, left, mid, right, temp): + i, j, k = left, mid + 1, 0 + while i <= mid and j <= right: + if nums[i] <= nums[j]: + temp[k] = nums[i] + i += 1 + else: + temp[k] = nums[j] + j += 1 + k += 1 + while i <= mid: + temp[k] = nums[i] + i += 1 + k += 1 + while j <= right: + temp[k] = nums[j] + j += 1 + k += 1 + +def merge(nums, left, mid, right): + count = 0 + j = mid + 1 + for i in range(left, mid + 1): + while j <= right and nums[i] > 2 * nums[j]: + j += 1 + count += j - mid - 1 + temp = [0] * (right - left + 1) + merge_sorted_arrays(nums, left, mid, right, temp) + for i in range(left, right + 1): + nums[i] = temp[i - left] + return count + +def merge_sort(nums, left, right): + if left >= right: + return 0 + mid = left + (right - left) // 2 + count = merge_sort(nums, left, mid) + merge_sort(nums, mid + 1, right) + count += merge(nums, left, mid, right) + return count + +class Solution: + def reversePairs(self, nums): + return merge_sort(nums, 0, len(nums) - 1) + + ``` + + + + + ```java + public class Solution { + public int reversePairs(int[] nums) { + return mergeSort(nums, 0, nums.length - 1); + } + + public int mergeSort(int[] nums, int left, int right) { + if (left >= right) { + return 0; + } + int mid = left + (right - left) / 2; + int count = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right); + count += merge(nums, left, mid, right); + return count; + } + public int merge(int[] nums, int left, int mid, int right) { + int count = 0; + int j = mid + 1; + for (int i = left; i <= mid; i++) { + while (j <= right && nums[i] > 2 * nums[j]) { + j++; + } + count += j - mid - 1; + } + int[] temp = new int[right - left + 1]; + mergeSortedArrays(nums, left, mid, right, temp); + for (int i = left; i <= right; i++) { + nums[i] = temp[i - left]; + } + return count; + } + + public void + mergeSortedArrays(int[] nums, int left, int mid, int right, int[] temp) { + int i = left, j = mid + 1, k = 0; + while (i <= mid && j <= right) { + if (nums[i] <= nums[j]) { + temp[k++] = nums[i++]; + } else { + temp[k++] = nums[j++]; + } + } + while (i <= mid) { + temp[k++] = nums[i++]; + } + while (j <= right) { + temp[k++] = nums[j++]; + } + } +} + + ``` + + + + ```cpp + void mergeSortedArrays(vector& nums, int left, int mid, int right, vector& temp) { + int i = left, j = mid + 1, k = 0; + while (i <= mid && j <= right) { + if (nums[i] <= nums[j]) temp[k++] = nums[i++]; + else temp[k++] = nums[j++]; + } + while (i <= mid) temp[k++] = nums[i++]; + while (j <= right) temp[k++] = nums[j++]; +} +int merge(vector& nums, int left, int mid, int right) { + int count = 0; + int j = mid + 1; + for (int i = left; i <= mid; i++) { + while (j <= right && nums[i] > 2 * nums[j]) j++; + count += j - mid - 1; + } + vector temp(right - left + 1); + mergeSortedArrays(nums, left, mid, right, temp); + for (int i = left; i <= right; i++) nums[i] = temp[i - left]; + return count; +} +int mergeSort(vector& nums, int left, int right) { + if (left >= right) return 0; + int mid = left + (right - left) / 2; + int count = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right); + count += merge(nums, left, mid, right); + return count; +} + + +class Solution { +public: + int reversePairs(vector& nums) { + return mergeSort(nums, 0, nums.size() - 1); + + + } +}; + ``` + + + +### Complexity Analysis + +- **Time Complexity**: $$O(n*log(n))$$, where n is the length of the input array. This is because the solution uses a modified Merge Sort algorithm, which has a time complexity of O(n log n). + + +- **Space Complexity**: $$O(n)$$, where n is the length of the input array. This is because the solution uses a temporary array to store the merged sorted arrays. + + + +--- + +

Authors:

+ +
+{['Ishitamukherjee2004'].map(username => ( + +))}
\ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0494-target-sum.md b/solutions/lc-solutions/0400-0499/0494-target-sum.md new file mode 100644 index 0000000..c5a408d --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0494-target-sum.md @@ -0,0 +1,510 @@ +--- +id: target-sum +title: Target Sum +sidebar_label: 0494 - Target Sum +tags: + - Dynamic Programming + - Recursion + - Memoization +description: "This is a solution to the Target Sum problem on LeetCode." +--- + +## Problem Description + +You are given an integer array `nums` and an integer `target`. + +You want to build an **expression** out of nums by adding one of the symbols `'+'` and `'-'` before each integer in nums and then concatenate all the integers. + +For example, if `nums = [2, 1]`, you can add a `'+'` before `2` and a `'-'` before `1` and concatenate them to build the expression `"+2-1"`. +Return the number of different **expressions** that you can build, which evaluates to target. + +### Examples + +**Example 1:** +``` +Input: nums = [1,1,1,1,1], target = 3 +Output: 5 +Explanation: There are 5 ways to assign symbols to make the sum of nums be target 3. +-1 + 1 + 1 + 1 + 1 = 3 ++1 - 1 + 1 + 1 + 1 = 3 ++1 + 1 - 1 + 1 + 1 = 3 ++1 + 1 + 1 - 1 + 1 = 3 ++1 + 1 + 1 + 1 - 1 = 3 +``` + +**Example 2:** + +``` +Input: nums = [1], target = 1 +Output: 1 +``` + +### Constraints + +- `1 <= nums.length <= 20` +- `0 <= nums[i] <= 1000` +- `0 <= sum(nums[i]) <= 1000` +- `-1000 <= target <= 1000` + +## Solution for Target Sum + +### Approach 1: Brute Force +#### Algorithm + +The brute force approach is based on recursion. We need to try to put both the `+` and `-` symbols at every location in the given nums array and find out the assignments which lead to the required result S. + +For this, we make use of a recursive function `calculate(nums, i, sum, S)`, which returns the assignments leading to the sum S, starting from the $i^{th}$ index onwards, provided the sum of elements up to the $i^{th}$ element is sum. This function appends a `+` sign and a `-` sign both to the element at the current index and calls itself with the updated sum as sum + nums[i] and sum - nums[i] respectively along with the updated current index as i+1. Whenever we reach the end of the array, we compare the sum obtained with S. If they are equal, we increment the count value to be returned. + +Thus, the function call `calculate(nums, 0, 0, S)` returns the required number of assignments. + +## Code in Different Languages + + + + + +```cpp +#include + +class Solution { +public: + int count = 0; + + int findTargetSumWays(std::vector& nums, int S) { + calculate(nums, 0, 0, S); + return count; + } + + void calculate(std::vector& nums, int i, int sum, int S) { + if (i == nums.size()) { + if (sum == S) { + count++; + } + } else { + calculate(nums, i + 1, sum + nums[i], S); + calculate(nums, i + 1, sum - nums[i], S); + } + } +}; + + +``` + + + + +```java +public class Solution { + int count = 0; + + public int findTargetSumWays(int[] nums, int S) { + calculate(nums, 0, 0, S); + return count; + } + + public void calculate(int[] nums, int i, int sum, int S) { + if (i == nums.length) { + if (sum == S) { + count++; + } + } else { + calculate(nums, i + 1, sum + nums[i], S); + calculate(nums, i + 1, sum - nums[i], S); + } + } +} +``` + + + + + +```python +from typing import List + +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + self.count = 0 # Initialize the count + + def calculate(nums: List[int], i: int, current_sum: int, target: int): + if i == len(nums): + if current_sum == target: + self.count += 1 + else: + calculate(nums, i + 1, current_sum + nums[i], target) + calculate(nums, i + 1, current_sum - nums[i], target) + + calculate(nums, 0, 0, target) + return self.count + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(2^N)$ + +> **Reason**: Size of recursion tree will be $2^N$. N refers to the size of nums array. + +### Space Complexity: $O(N)$ + +> **Reason**: The depth of the recursion tree can go up to N. + +### Approach 2: Recursion with Memoization + +#### Algorithm + +In the last approach, we can observe that a lot of redundant function calls were made with the same value of i as the current index and the same value of sum as the current sum, since the same values could be obtained through multiple paths in the recursion tree. In order to remove this redundancy, we make use of memoization as well to store the results which have been calculated earlier. + +Thus, for every call to `calculate(nums, i, sum, S)`, we store the result obtained in memo[i][sum + total], where total stands for the sum of all the elements from the input array. The factor of total has been added as an offset to the sum value to map all the sum possible to positive integer range. By making use of memoization, we can get the result of each redundant function call in constant time. + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include +#include + +class Solution { +public: + int total; + + int findTargetSumWays(std::vector& nums, int S) { + total = std::accumulate(nums.begin(), nums.end(), 0); + + std::vector> memo(nums.size(), std::vector(2 * total + 1, INT_MIN)); + return calculate(nums, 0, 0, S, memo); + } + + int calculate(std::vector& nums, int i, int sum, int S, std::vector>& memo) { + if (i == nums.size()) { + return sum == S ? 1 : 0; + } else { + if (memo[i][sum + total] != INT_MIN) { + return memo[i][sum + total]; + } + int add = calculate(nums, i + 1, sum + nums[i], S, memo); + int subtract = calculate(nums, i + 1, sum - nums[i], S, memo); + memo[i][sum + total] = add + subtract; + return memo[i][sum + total]; + } + } +}; + +``` + + + + +```java +public class Solution { + int total; + + public int findTargetSumWays(int[] nums, int S) { + total = Arrays.stream(nums).sum(); + + int[][] memo = new int[nums.length][2 * total + 1]; + for (int[] row : memo) { + Arrays.fill(row, Integer.MIN_VALUE); + } + return calculate(nums, 0, 0, S, memo); + } + + public int calculate(int[] nums, int i, int sum, int S, int[][] memo) { + if (i == nums.length) { + if (sum == S) { + return 1; + } else { + return 0; + } + } else { + if (memo[i][sum + total] != Integer.MIN_VALUE) { + return memo[i][sum + total]; + } + int add = calculate(nums, i + 1, sum + nums[i], S, memo); + int subtract = calculate(nums, i + 1, sum - nums[i], S, memo); + memo[i][sum + total] = add + subtract; + return memo[i][sum + total]; + } + } +} +``` + + + + + +```python +from typing import List + +class Solution: + def findTargetSumWays(self, nums: List[int], S: int) -> int: + self.total = sum(nums) + + memo = [[float('-inf')] * (2 * self.total + 1) for _ in range(len(nums))] + return self.calculate(nums, 0, 0, S, memo) + + def calculate(self, nums: List[int], i: int, current_sum: int, target: int, memo: List[List[int]]) -> int: + if i == len(nums): + return 1 if current_sum == target else 0 + else: + if memo[i][current_sum + self.total] != float('-inf'): + return memo[i][current_sum + self.total] + add = self.calculate(nums, i + 1, current_sum + nums[i], target, memo) + subtract = self.calculate(nums, i + 1, current_sum - nums[i], target, memo) + memo[i][current_sum + self.total] = add + subtract + return memo[i][current_sum + self.total] + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(Tβ‹…N)$ + +> **Reason**: The memo array of size O(Tβ‹…N) has been filled just once. Here, T refers to the sum of the nums array and N refers to the length of the nums array. + +### Space Complexity: $O(T.N)$ + +> **Reason**: The depth of recursion tree can go up to N.The `memo` array contains T.N elements. + +### Approach 3: 2D Dynamic Programming +#### Algorithm +The idea behind this approach is as follows. Suppose we can find out the number of times a particular sum, say $$sum_i$$ is possible up to a particular index, say i, in the given nums array, which is given by say $$count_i$$. Now, we can find out the number of times the sum $$sum_i + nums[i]$$ can occur easily as $$count_i$$. Similarly, the number of times the sum $$sum_i - nums[i]$$ occurs is also given by $$count_i$$. + +Thus, if we know all the sums $$sum_j$$'s which are possible up to the jth index by using various assignments, along with the corresponding count of assignments, $$count_j$$, leading to the same sum, we can determine all the sums possible up to the $(j+1)^{th}$ index along with the corresponding count of assignments leading to the new sums. + +Based on this idea, we make use of a dp to determine the number of assignments which can lead to the given sum. dp[i][j] refers to the number of assignments which can lead to a sum of j up to the $i^{th}$ index. To determine the number of assignments which can lead to a sum of $sum + nums[i]$ up to the $(i+1)^{th}$ index, we can use $$dp[i][sum + nums[i]] = dp[i][sum + nums[i]] + dp[i-1][sum]$$. Similarly, $$dp[i][sum - nums[i]] = dp[i][sum - nums[i]] + dp[i-1][sum]$$. We iterate over the dp array in a row-wise fashion, i.e., firstly, we obtain all the sums which are possible up to a particular index along with the corresponding count of assignments and then proceed for the next element (index) in the nums array. + +But, since the sum can range from `-total` to `total`, where `total` equals the sum of the `nums` array, we need to add an offset of total to the sum indices (column number) to map all the sums obtained to positive range only. + +At the end, the value of $dp[n-1][S+total]$ gives us the required number of assignments. Here, n refers to the number of elements in the `nums` array. + + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +public: + int findTargetSumWays(std::vector& nums, int S) { + int total = std::accumulate(nums.begin(), nums.end(), 0); + int n = nums.size(); + std::vector> dp(n, std::vector(2 * total + 1, 0)); + + dp[0][nums[0] + total] = 1; + dp[0][-nums[0] + total] += 1; + + for (int i = 1; i < n; i++) { + for (int sum = -total; sum <= total; sum++) { + if (dp[i - 1][sum + total] > 0) { + dp[i][sum + nums[i] + total] += dp[i - 1][sum + total]; + dp[i][sum - nums[i] + total] += dp[i - 1][sum + total]; + } + } + } + + return std::abs(S) > total ? 0 : dp[n - 1][S + total]; + } +}; + +``` + + + + +```java +public class Solution { + public int findTargetSumWays(int[] nums, int S) { + int total = Arrays.stream(nums).sum(); + int[][] dp = new int[nums.length][2 * total + 1]; + dp[0][nums[0] + total] = 1; + dp[0][-nums[0] + total] += 1; + + for (int i = 1; i < nums.length; i++) { + for (int sum = -total; sum <= total; sum++) { + if (dp[i - 1][sum + total] > 0) { + dp[i][sum + nums[i] + total] += dp[i - 1][sum + total]; + dp[i][sum - nums[i] + total] += dp[i - 1][sum + total]; + } + } + } + + return Math.abs(S) > total ? 0 : dp[nums.length - 1][S + total]; + } +} +``` + + + + + +```python +from typing import List + +class Solution: + def findTargetSumWays(self, nums, S): + total = sum(nums) + n = len(nums) + dp = [[0] * (2 * total + 1) for _ in range(n)] + + dp[0][nums[0] + total] = 1 + dp[0][-nums[0] + total] += 1 + + for i in range(1, n): + for s in range(-total, total + 1): + if dp[i - 1][s + total] > 0: + dp[i][s + nums[i] + total] += dp[i - 1][s + total] + dp[i][s - nums[i] + total] += dp[i - 1][s + total] + + return 0 if abs(S) > total else dp[n - 1][S + total] +``` + + + +## Complexity Analysis + +### Time Complexity: $O(Tβ‹…N)$ + +> **Reason**: The dp array of size O(Tβ‹…N) has been filled just once. Here, T refers to the sum of the nums array and N refers to the length of the nums array. + +### Space Complexity: $O(T.N)$ + +> **Reason**: dp array of size Tβ‹…N is used. + +### Approach 4: 1D Dynamic Programming +#### Algorithm +If we look closely at the last solution, we can observe that to evaluate the current row of dp, only the values of the last row of dp are needed. Thus, we can save some space by using a 1D DP array instead of a 2D DP array. The only change we need to make is that we have to create an array next of the same size as dp so that we can update it while scanning through dp since it is not safe to mutate dp when the iteration is in progress. After the iteration is completed, we set dp equal to next and create a new empty array next before the next iteration starts, and so on. + + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +public: + int findTargetSumWays(std::vector& nums, int S) { + int total = std::accumulate(nums.begin(), nums.end(), 0); + int n = nums.size(); + std::vector dp(2 * total + 1, 0); + + dp[nums[0] + total] = 1; + dp[-nums[0] + total] += 1; + + for (int i = 1; i < n; i++) { + std::vector next(2 * total + 1, 0); + for (int sum = -total; sum <= total; sum++) { + if (dp[sum + total] > 0) { + next[sum + nums[i] + total] += dp[sum + total]; + next[sum - nums[i] + total] += dp[sum + total]; + } + } + dp = next; + } + + return std::abs(S) > total ? 0 : dp[S + total]; + } +}; +``` + + + + +```java +public class Solution { + public int findTargetSumWays(int[] nums, int S) { + int total = Arrays.stream(nums).sum(); + int[] dp = new int[2 * total + 1]; + dp[nums[0] + total] = 1; + dp[-nums[0] + total] += 1; + + for (int i = 1; i < nums.length; i++) { + int[] next = new int[2 * total + 1]; + for (int sum = -total; sum <= total; sum++) { + if (dp[sum + total] > 0) { + next[sum + nums[i] + total] += dp[sum + total]; + next[sum - nums[i] + total] += dp[sum + total]; + } + } + dp = next; + } + + return Math.abs(S) > total ? 0 : dp[S + total]; + } +} +``` + + + + + +```python +class Solution: + def findTargetSumWays(self, nums, S): + total = sum(nums) + n = len(nums) + dp = [0] * (2 * total + 1) + + dp[nums[0] + total] = 1 + dp[-nums[0] + total] += 1 + + for i in range(1, n): + next_dp = [0] * (2 * total + 1) + for sum_val in range(-total, total + 1): + if dp[sum_val + total] > 0: + next_dp[sum_val + nums[i] + total] += dp[sum_val + total] + next_dp[sum_val - nums[i] + total] += dp[sum_val + total] + dp = next_dp + + return 0 if abs(S) > total else dp[S + total] + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(Tβ‹…N)$ + +> **Reason**: Each of the N dp arrays of size ttt has been filled just once. Here, T refers to the sum of the nums array and N refers to the length of the nums array. + +### Space Complexity: $O(T)$ + +> **Reason**: Two dp arrays of size 2β‹…T+1 are used, therefore the space usage is O(T). + +## References + +- **LeetCode Problem**: [Target Sum](https://leetcode.com/problems/target-sum/description/) + +- **Solution Link**: [Target Sum](https://leetcode.com/problems/target-sum/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0495-teemo-attacking.md b/solutions/lc-solutions/0400-0499/0495-teemo-attacking.md new file mode 100644 index 0000000..1cfcc5a --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0495-teemo-attacking.md @@ -0,0 +1,150 @@ +--- +id: teemo-attacking +title: Teemo Attacking +sidebar_label: 0495 - Teemo Attacking +tags: + - Greedy + - Array + - Simulation +description: "This is a solution to the Teemo Attacking problem on LeetCode." +--- + +## Problem Description + +Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effect ends, the timer for it is **reset**, and the poison effect will end `duration` seconds after the new attack. + +You are given a **non-decreasing** integer array `timeSeries`, where `timeSeries[i]` denotes that Teemo attacks Ashe at second `timeSeries[i]`, and an integer `duration`. + +Return the **total** number of seconds that Ashe is poisoned. + +### Examples + +**Example 1:** +``` +Input: timeSeries = [1,4], duration = 2 +Output: 4 +Explanation: Teemo's attacks on Ashe go as follows: +- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. +- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5. +Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total. +``` + +**Example 2:** + +``` +Input: timeSeries = [1,2], duration = 2 +Output: 3 +Explanation: Teemo's attacks on Ashe go as follows: +- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. +- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3. +Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total. +``` + +### Constraints + +- $1 <= timeSeries.length <= 10^4$ +- $0 <= timeSeries[i], duration <= 10^7$ +- `timeSeries` is sorted in **non-decreasing** order. + +## Solution for Teemo Attacking + +### Approach 1: One pass +#### Intuition + +The problem is an example of merge interval questions which are now quite popular in Google. + +Typically such problems could be solved in a linear time in the case of sorted input, and in O(Nlog⁑N) time otherwise. + +Here one deals with a sorted input, and the problem could be solved in one pass with a constant space. The idea is straightforward: consider only the interval between two attacks. Ashe spends in a poisoned condition the whole time interval if this interval is shorter than the poisoning time duration `duration`, and `duration` otherwise. + +#### Algorithm + +- Initiate total time in poisoned condition `total = 0`. + +- Iterate over `timeSeries` list. At each step add to the total time the minimum between interval length and the poisoning time duration `duration`. + +- Return `total + duration` to take the last attack into account. + +![image](https://assets.leetcode.com/static_assets/media/original_images/495/ashe.png) +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + int findPoisonedDuration(std::vector& timeSeries, int duration) { + int n = timeSeries.size(); + if (n == 0) return 0; + + int total = 0; + for(int i = 0; i < n - 1; ++i) + total += std::min(timeSeries[i + 1] - timeSeries[i], duration); + return total + duration; + } +}; +``` + + + + +```java +class Solution { + public int findPoisonedDuration(int[] timeSeries, int duration) { + int n = timeSeries.length; + if (n == 0) return 0; + + int total = 0; + for(int i = 0; i < n - 1; ++i) + total += Math.min(timeSeries[i + 1] - timeSeries[i], duration); + return total + duration; + } +} +``` + + + + + +```python +class Solution: + def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int: + n = len(timeSeries) + if n == 0: + return 0 + + total = 0 + for i in range(n - 1): + total += min(timeSeries[i + 1] - timeSeries[i], duration) + return total + duration +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: where N is the length of the input list since we iterate the entire list. + +### Space Complexity: $O(1)$ + +> **Reason**: it's a constant space solution. + +## References + +- **LeetCode Problem**: [Teemo Attacking](https://leetcode.com/problems/teemo-attacking/description/) + +- **Solution Link**: [Teemo Attacking](https://leetcode.com/problems/teemo-attacking/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/0496-next-greater-element-I.md b/solutions/lc-solutions/0400-0499/0496-next-greater-element-I.md new file mode 100644 index 0000000..f6bc980 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0496-next-greater-element-I.md @@ -0,0 +1,167 @@ +--- +id: next-greater-element-I +title: Next Greater Element I +sidebar_label: 0496-next-greater-element-I +tags: + - Array + - Hash Table + - Stack + - Monotonic Stack +description: "This is a solution to the next greater element I problem on LeetCode." +--- + +## Problem Description + +The next greater element of some element `x` in an array is the first greater element that is to the right of `x` in the same array. + +You are given two distinct 0-indexed integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`. + +For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the next greater element of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`. + +Return an array `ans` of length `nums1.length` such that `ans[i]` is the next greater element as described above. + +### Examples + +**Example 1:** + +``` +Input: nums1 = [4,1,2], nums2 = [1,3,4,2] +Output: [-1,3,-1] +Explanation: The next greater element for each value of nums1 is as follows: +- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. +- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3. +- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. +``` + +**Example 2:** + +``` +Input: nums1 = [2,4], nums2 = [1,2,3,4] +Output: [3,-1] +Explanation: The next greater element for each value of nums1 is as follows: +- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3. +- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1. +``` + +### Constraints + +- `1 <= nums1.length <= nums2.length <= 1000` +- `0 <= nums1[i], nums2[i] <= 104` +- All integers in `nums1` and `nums2` are unique. +- All the integers of `nums1` also appear in `nums2`. + + +## Solution for Assign Cookies + +### Approach: +The intuitive approach to solve this problem is by using a stack. First, we will iterate through nums2 because this is the array where we're finding the next greater elements. As we want to find the next greater element that occurs after the given element, the stack allows us to keep track of the elements we've seen but haven't yet found a greater element for. + +Here is the step-by-step intuition behind the solution: + +1. We will create a dictionary called m to map each element in nums2 to its next greater element. This will help in quickly looking up the result for each element in nums1. + +2. We will also create an empty stack, stk, to maintain the elements for which we have to find the next greater element. + +3. We go through each element v in nums2. For every element v, we do the following: + +If the stack is not empty, we check the last element in the stack. If the last element in the stack is less than v, it means that v is the next greater element for that stack's top element. So we pop the top from the stack and record v as the next greater element in our dictionary m. +We continue to compare v with the new top of the stack and do the above step until the stack is empty or the top of the stack is no longer less than v. +We push v onto the stack because we need to find the next greater element for it. + +4. Once we have completely processed nums2 in the above way, we have our m dictionary with the next greater elements for all elements in nums2 where they exist. + +5. Finally, for each element v in nums1, we look up our dictionary m. If v is in the dictionary, we put m[v] in the result array; otherwise, we put -1. + +This approach effectively tracks the elements that are yet to find their next greater element and finds the valid greater elements for them in a single pass through nums2 due to the stack's LIFO property. + + +## Code in Different Languages + + + + + +```cpp +class Solution { + public: + vector nextGreaterElement(vector& nums1, vector& nums2) { + vector ans; + unordered_map numToNextGreater; + stack stack; // a decreasing stack + + for (const int num : nums2) { + while (!stack.empty() && stack.top() < num) + numToNextGreater[stack.top()] = num, stack.pop(); + stack.push(num); + } + + for (const int num : nums1) + if (const auto it = numToNextGreater.find(num); + it != numToNextGreater.cend()) + ans.push_back(it->second); + else + ans.push_back(-1); + + return ans; + } +}; +``` + + + + +```java +class Solution { + public int[] nextGreaterElement(int[] nums1, int[] nums2) { + List ans = new ArrayList<>(); + Map numToNextGreater = new HashMap<>(); + Deque stack = new ArrayDeque<>(); // a decreasing stack + + for (final int num : nums2) { + while (!stack.isEmpty() && stack.peek() < num) + numToNextGreater.put(stack.pop(), num); + stack.push(num); + } + + for (final int num : nums1) + if (numToNextGreater.containsKey(num)) + ans.add(numToNextGreater.get(num)); + else + ans.add(-1); + + return ans.stream().mapToInt(Integer::intValue).toArray(); + } +} +``` + + + + + +```python +class Solution: + def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: + numToNextGreater = {} + stack = [] # a decreasing stack + + for num in nums2: + while stack and stack[-1] < num: + numToNextGreater[stack.pop()] = num + stack.append(num) + + return [numToNextGreater.get(num, -1) for num in nums1] +``` + + + +## Complexity Analysis + +### Time Complexity: O(n) + +### Space Complexity: O(n) + +## References + +- **LeetCode Problem**: [Next Greater Element I](https://leetcode.com/problems/next-greater-element-i/description/) + +- **Solution Link**: [Next Greater Element I](https://leetcode.com/problems/next-greater-element-i/solutions/) diff --git a/solutions/lc-solutions/0400-0499/0498-diagonal-traverse.md b/solutions/lc-solutions/0400-0499/0498-diagonal-traverse.md new file mode 100644 index 0000000..0dded98 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/0498-diagonal-traverse.md @@ -0,0 +1,565 @@ +--- +id: diagonal-traverse +title: Diagonal Traverse +sidebar_label: 0498 - Diagonal Traverse +tags: + - Matrix + - Array + - Simulation +description: "This is a solution to the Diagonal Traverse problem on LeetCode." +--- + +## Problem Description + +Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order. + +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2021/04/10/diag1-grid.jpg) +``` +Input: mat = [[1,2,3],[4,5,6],[7,8,9]] +Output: [1,2,4,7,5,3,6,8,9] +``` + +**Example 2:** + +``` +Input: mat = [[1,2],[3,4]] +Output: [1,2,3,4] +``` + +### Constraints + +- `m == mat.length` +- `n == mat[i].length` +- $1 \leq m, n \leq 10^4$ +- $1 \leq m * n \leq 10^4$ +- $-10^5 \leq mat[i][j] \leq 10^5$ + +## Solution for Diagonal Traverse + +### Approach 1: Diagonal Iteration and Reversal +#### Intuition + +A common strategy for solving a lot of programming problem is to first solve a stripped down, simpler version of them and then think what needs to be changed to achieve the original goal. Our first approach to this problem is also based on this very idea. So, instead of thinking about the zig-zag pattern of printing for the diagonals, let's say the problem statement simply asked us to print out the contents of the matrix, one diagonal after the other starting from the first element. Let's see what this problem would look like. +![image](https://assets.leetcode.com/static_assets/media/original_images/498/img1.png) + +The first row and the last column in this problem would serve as the starting point for the corresponding diagonal. Given an element inside a diagonal, say [i,j], we can either go up the diagonal by going one row up and one column ahead i.e. [iβˆ’1,j+1] or, we can go down the diagonal by going one row down and one column to the left i.e. [i+1,jβˆ’1]. Note that this applies to diagonals that go from right to left only. The math would change for the ones that go from left to right. + +This is a simple problem to solve, right? The only difference between this one and the original problem is that some of the diagonals are not printed in the right order. That's all we need to fix to get the right solution! + +#### Algorithm + +1. Initialize a result array that we will eventually return. + +2. We would have an outer loop that will go over each of the diagonals one by one. As mentioned before, the elements in the first row and the last column would actually be the heads of their corresponding diagonals. + +3. We then have an inner while loop that iterates over all the elements in the diagonal. We can calculate the number of elements in the corresponding diagonal by doing some math but we can simply iterate until one of the indices goes out of bounds. + +4. For each diagonal we will need a new list or dynamic array like data structure since we don't know what size to allocate. Again, we can do some math and calculate the size of that particular diagonal and allocate memory; but it's not necessary for this explanation. + +5. For odd numbered diagonals, we simply need to add the elements in our intermediary array, in reverse order to the final result array. + +![image](https://assets.leetcode.com/static_assets/media/original_images/498/img2.png) + +## Code in Different Languages + + + + + +```cpp +#include +#include + +class Solution { +public: + std::vector findDiagonalOrder(std::vector>& matrix) { + // Check for empty matrices + if (matrix.empty() || matrix[0].empty()) { + return std::vector(); + } + + // Variables to track the size of the matrix + int N = matrix.size(); + int M = matrix[0].size(); + + // The vector to store the result + std::vector result(N * M); + int k = 0; + std::vector intermediate; + + // We have to go over all the elements in the first + // row and the last column to cover all possible diagonals + for (int d = 0; d < N + M - 1; ++d) { + // Clear the intermediate vector every time we start + // to process another diagonal + intermediate.clear(); + + // We need to figure out the "head" of this diagonal + // The elements in the first row and the last column + // are the respective heads. + int r = d < M ? 0 : d - M + 1; + int c = d < M ? d : M - 1; + + // Iterate until one of the indices goes out of scope + // Take note of the index math to go down the diagonal + while (r < N && c > -1) { + intermediate.push_back(matrix[r][c]); + ++r; + --c; + } + + // Reverse even numbered diagonals. The + // article says we have to reverse odd + // numbered articles but here, the numbering + // is starting from 0 :P + if (d % 2 == 0) { + std::reverse(intermediate.begin(), intermediate.end()); + } + + // Copy elements from the intermediate vector to the result array + for (int i = 0; i < intermediate.size(); ++i) { + result[k++] = intermediate[i]; + } + } + return result; + } +}; + + +``` + + + + +```java +class Solution { + public int[] findDiagonalOrder(int[][] matrix) { + + // Check for empty matrices + if (matrix == null || matrix.length == 0) { + return new int[0]; + } + + // Variables to track the size of the matrix + int N = matrix.length; + int M = matrix[0].length; + + // The two arrays as explained in the algorithm + int[] result = new int[N*M]; + int k = 0; + ArrayList intermediate = new ArrayList(); + + // We have to go over all the elements in the first + // row and the last column to cover all possible diagonals + for (int d = 0; d < N + M - 1; d++) { + + // Clear the intermediate array every time we start + // to process another diagonal + intermediate.clear(); + + // We need to figure out the "head" of this diagonal + // The elements in the first row and the last column + // are the respective heads. + int r = d < M ? 0 : d - M + 1; + int c = d < M ? d : M - 1; + + // Iterate until one of the indices goes out of scope + // Take note of the index math to go down the diagonal + while (r < N && c > -1) { + + intermediate.add(matrix[r][c]); + ++r; + --c; + } + + // Reverse even numbered diagonals. The + // article says we have to reverse odd + // numbered articles but here, the numbering + // is starting from 0 :P + if (d % 2 == 0) { + Collections.reverse(intermediate); + } + + for (int i = 0; i < intermediate.size(); i++) { + result[k++] = intermediate.get(i); + } + } + return result; + } +} +``` + + + + + +```python +class Solution: + + def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]: + + # Check for empty matrices + if not matrix or not matrix[0]: + return [] + + # Variables to track the size of the matrix + N, M = len(matrix), len(matrix[0]) + + # The two arrays as explained in the algorithm + result, intermediate = [], [] + + # We have to go over all the elements in the first + # row and the last column to cover all possible diagonals + for d in range(N + M - 1): + + # Clear the intermediate array everytime we start + # to process another diagonal + intermediate.clear() + + # We need to figure out the "head" of this diagonal + # The elements in the first row and the last column + # are the respective heads. + r, c = 0 if d < M else d - M + 1, d if d < M else M - 1 + + # Iterate until one of the indices goes out of scope + # Take note of the index math to go down the diagonal + while r < N and c > -1: + intermediate.append(matrix[r][c]) + r += 1 + c -= 1 + + # Reverse even numbered diagonals. The + # article says we have to reverse odd + # numbered articles but here, the numbering + # is starting from 0 :P + if d % 2 == 0: + result.extend(intermediate[::-1]) + else: + result.extend(intermediate) + return result +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N.M)$ + +> **Reason**: considering an array with N rows and M columns, where odd numbered diagonals are processed twice due to element reversal, requiring O(K) for array clearing, making the overall complexity remain O(Nβ‹…M). + +### Space Complexity: $O(min(N,M))$ + +> **Reason**: as extra space is utilized by intermediate arrays storing diagonal elements, with a maximum space of min(N,M), as diagonals extend till one index goes out of scope. + +### Approach 2: Simulation + +#### Intuition + +This approach simply and plainly does what the problem statement asks us to do. It's pure simulation. However, in order to implement this simulation, we need to understand the walking patterns inside the array. Basically, in the previous approach, figuring out the head of the diagonal was pretty easy. In this case, it won't be that easy. We need to figure out two things for each diagonal: + +1. The direction in which we want to process it's elements and +2. The head or the starting point for the diagonal `depending upon its direction`. + +Let's see these two things annotated on a sample matrix. + +![image](https://assets.leetcode.com/static_assets/media/original_images/498/img3.png) + +Now that we know what two things we need to figure out, let's get to the part where we actually do it! The direction is pretty straightforward. We can simply use a boolean variable and keep alternating it to figure out the direction for a diagonal. That part is sorted. The slightly tricky part is figuring out the head of the next diagonal. + +The good part is, we already know the end of the previous diagonal. We can use that information to figure out the head of the next diagonal. + +**Next head when going UP** +Let's look at the two scenarios that we may come across when we are at the tail end of a downwards diagonal and we want to find the head of the next diagonal. + +![image](https://assets.leetcode.com/static_assets/media/original_images/498/img4.png) + +So, the general rule that we will be following when we want to find the head for an upwards going diagonal is that: +> The head would be the node directly below the tail of the previous diagonal. Unless the tail lies in the last row of the matrix in which case the head would be the node right next to the tail. + +**Next head when going DOWN** +Let's look at the two scenarios that we may come across when we are at the tail end of an upwards diagonal and we want to find the head of the next diagonal. + +![image](https://assets.leetcode.com/static_assets/media/original_images/498/img5.png) + +So, the general rule that we will be following when we want to find the head for a downwards going diagonal is that: +> The head would be the node to the right of the tail of the previous diagonal. Unless the tail lies in the last column of the matrix in which case the head would be the node directly below the tail. + +## Code in Different Languages + + + + + +```cpp +#include + +class Solution { +public: + std::vector findDiagonalOrder(std::vector>& matrix) { + // Check for empty matrices + if (matrix.empty() || matrix[0].empty()) { + return std::vector(); + } + + // Variables to track the size of the matrix + int N = matrix.size(); + int M = matrix[0].size(); + + // Indices that will help us progress through + // the matrix, one element at a time. + int row = 0, column = 0; + + // As explained in the article, this is the variable + // that helps us keep track of what direction we are + // processing the current diagonal + int direction = 1; + + // The final result array + std::vector result(N * M); + int r = 0; + + // The uber while loop which will help us iterate over all + // the elements in the array. + while (row < N && column < M) { + + // First and foremost, add the current element to + // the result matrix. + result[r++] = matrix[row][column]; + + // Move along in the current diagonal depending upon + // the current direction.[i, j] -> [i - 1, j + 1] if + // going up and [i, j] -> [i + 1][j - 1] if going down. + int new_row = row + (direction == 1 ? -1 : 1); + int new_column = column + (direction == 1 ? 1 : -1); + + // Checking if the next element in the diagonal is within the + // bounds of the matrix or not. If it's not within the bounds, + // we have to find the next head. + if (new_row < 0 || new_row == N || new_column < 0 || new_column == M) { + + // If the current diagonal was going in the upwards + // direction. + if (direction == 1) { + + // For an upwards going diagonal having [i, j] as its tail + // If [i, j + 1] is within bounds, then it becomes + // the next head. Otherwise, the element directly below + // i.e. the element [i + 1, j] becomes the next head + row += (column == M - 1 ? 1 : 0); + column += (column < M - 1 ? 1 : 0); + + } else { + + // For a downwards going diagonal having [i, j] as its tail + // if [i + 1, j] is within bounds, then it becomes + // the next head. Otherwise, the element directly below + // i.e. the element [i, j + 1] becomes the next head + column += (row == N - 1 ? 1 : 0); + row += (row < N - 1 ? 1 : 0); + } + + // Flip the direction + direction = 1 - direction; + + } else { + + row = new_row; + column = new_column; + } + } + return result; + } +}; + + +``` + + + + +```java +class Solution { + public int[] findDiagonalOrder(int[][] matrix) { + + // Check for empty matrices + if (matrix == null || matrix.length == 0) { + return new int[0]; + } + + // Variables to track the size of the matrix + int N = matrix.length; + int M = matrix[0].length; + + // Incides that will help us progress through + // the matrix, one element at a time. + int row = 0, column = 0; + + // As explained in the article, this is the variable + // that helps us keep track of what direction we are + // processing the current diaonal + int direction = 1; + + // The final result array + int[] result = new int[N*M]; + int r = 0; + + // The uber while loop which will help us iterate over all + // the elements in the array. + while (row < N && column < M) { + + // First and foremost, add the current element to + // the result matrix. + result[r++] = matrix[row][column]; + + // Move along in the current diagonal depending upon + // the current direction.[i, j] -> [i - 1, j + 1] if + // going up and [i, j] -> [i + 1][j - 1] if going down. + int new_row = row + (direction == 1 ? -1 : 1); + int new_column = column + (direction == 1 ? 1 : -1); + + // Checking if the next element in the diagonal is within the + // bounds of the matrix or not. If it's not within the bounds, + // we have to find the next head. + if (new_row < 0 || new_row == N || new_column < 0 || new_column == M) { + + // If the current diagonal was going in the upwards + // direction. + if (direction == 1) { + + // For an upwards going diagonal having [i, j] as its tail + // If [i, j + 1] is within bounds, then it becomes + // the next head. Otherwise, the element directly below + // i.e. the element [i + 1, j] becomes the next head + row += (column == M - 1 ? 1 : 0) ; + column += (column < M - 1 ? 1 : 0); + + } else { + + // For a downwards going diagonal having [i, j] as its tail + // if [i + 1, j] is within bounds, then it becomes + // the next head. Otherwise, the element directly below + // i.e. the element [i, j + 1] becomes the next head + column += (row == N - 1 ? 1 : 0); + row += (row < N - 1 ? 1 : 0); + } + + // Flip the direction + direction = 1 - direction; + + } else { + + row = new_row; + column = new_column; + } + } + return result; + } +} +``` + + + + + +```python +class Solution: + + def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]: + + # Check for an empty matrix + if not matrix or not matrix[0]: + return [] + + # The dimensions of the matrix + N, M = len(matrix), len(matrix[0]) + + # Incides that will help us progress through + # the matrix, one element at a time. + row, column = 0, 0 + + # As explained in the article, this is the variable + # that helps us keep track of what direction we are + # processing the current diaonal + direction = 1 + + # Final result array that will contain all the elements + # of the matrix + result = [] + + # The uber while loop which will help us iterate over all + # the elements in the array. + while row < N and column < M: + + # First and foremost, add the current element to + # the result matrix. + result.append(matrix[row][column]) + + # Move along in the current diagonal depending upon + # the current direction.[i, j] -> [i - 1, j + 1] if + # going up and [i, j] -> [i + 1][j - 1] if going down. + new_row = row + (-1 if direction == 1 else 1) + new_column = column + (1 if direction == 1 else -1) + + # Checking if the next element in the diagonal is within the + # bounds of the matrix or not. If it's not within the bounds, + # we have to find the next head. + if new_row < 0 or new_row == N or new_column < 0 or new_column == M: + + # If the current diagonal was going in the upwards + # direction. + if direction: + + # For an upwards going diagonal having [i, j] as its tail + # If [i, j + 1] is within bounds, then it becomes + # the next head. Otherwise, the element directly below + # i.e. the element [i + 1, j] becomes the next head + row += (column == M - 1) + column += (column < M - 1) + else: + + # For a downwards going diagonal having [i, j] as its tail + # if [i + 1, j] is within bounds, then it becomes + # the next head. Otherwise, the element directly below + # i.e. the element [i, j + 1] becomes the next head + column += (row == N - 1) + row += (row < N - 1) + + # Flip the direction + direction = 1 - direction + else: + row = new_row + column = new_column + + return result +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N.M)$ + +> **Reason**: since we process each element of the matrix exactly once. + +### Space Complexity: $O(1)$ + +> **Reason**: since we don't make use of any additional data structure. + +## References + +- **LeetCode Problem**: [Diagonal Traverse](https://leetcode.com/problems/diagonal-traverse/description/) + +- **Solution Link**: [Diagonal Traverse](https://leetcode.com/problems/diagonal-traverse/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0400-0499/_category_.json b/solutions/lc-solutions/0400-0499/_category_.json new file mode 100644 index 0000000..8761287 --- /dev/null +++ b/solutions/lc-solutions/0400-0499/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "0400-0499", + "position": 6, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (0400 - 0499)" + } +} diff --git a/solutions/lc-solutions/0500-0599/0500-Keyboard-Rows.md b/solutions/lc-solutions/0500-0599/0500-Keyboard-Rows.md new file mode 100644 index 0000000..8e1325e --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0500-Keyboard-Rows.md @@ -0,0 +1,319 @@ +--- +id: Keyboard-Rows +title: Keyboard-Rows +sidebar_label: Keyboard-Rows +tags: + - String + - Array + - LeetCode +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Keyboard-Rows](https://leetcode.com/problems/Keyboard-Rows/description/) | [Keyboard-Rows Solution on LeetCode](https://leetcode.com/problems/Keyboard-Rows/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + + +## Problem Description + +Given an array of strings `words`, return the words that can be typed using letters of the alphabet on only one row of the American keyboard. + +American keyboard rows: +1. "qwertyuiop" +2. "asdfghjkl" +3. "zxcvbnm" + +### Example 1 + +**Input:** `words = ["Hello","Alaska","Dad","Peace"]` +**Output:** `["Alaska","Dad"]` + +### Example 2 + +**Input:** `words = ["omk"]` +**Output:** `[]` + +### Example 3 + +**Input:** `words = ["adsdf","sfd"]` +**Output:** `["adsdf","sfd"]` + +### Constraints + +- `1 <= words.length <= 20` +- `1 <= words[i].length <= 100` +- `words[i]` consists of English letters (both lowercase and uppercase). + +## Approach + +We can solve this problem efficiently by checking each word to see if all its characters belong to the same row on the keyboard. We can utilize sets for the characters of each row for quick lookup. + +## Solution in Python + +```python +def findWords(words): + row1 = set("qwertyuiop") + row2 = set("asdfghjkl") + row3 = set("zxcvbnm") + + def check_word(word): + if word[0].lower() in row1: + row = row1 + elif word[0].lower() in row2: + row = row2 + else: + row = row3 + + for char in word: + if char.lower() not in row: + return False + return True + + result = [] + for word in words: + if check_word(word): + result.append(word) + + return result + +# Example usage: +words = ["Hello","Alaska","Dad","Peace"] +print(findWords(words)) # Output: ["Alaska","Dad"] +``` + +## Solution in Java + +```java +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class Solution { + public String[] findWords(String[] words) { + Set row1 = new HashSet<>(); + Set row2 = new HashSet<>(); + Set row3 = new HashSet<>(); + + for (char c : "qwertyuiop".toCharArray()) row1.add(c); + for (char c : "asdfghjkl".toCharArray()) row2.add(c); + for (char c : "zxcvbnm".toCharArray()) row3.add(c); + + List result = new ArrayList<>(); + + for (String word : words) { + if (isSingleRow(word, row1, row2, row3)) { + result.add(word); + } + } + + return result.toArray(new String[0]); + } + + private boolean isSingleRow(String word, Set row1, Set row2, Set row3) { + Set currentRow = determineRow(word.charAt(0), row1, row2, row3); + + for (int i = 1; i < word.length(); i++) { + if (!currentRow.contains(Character.toLowerCase(word.charAt(i)))) { + return false; + } + } + + return true; + } + + private Set determineRow(char c, Set row1, Set row2, Set row3) { + char lowerC = Character.toLowerCase(c); + + if (row1.contains(lowerC)) { + return row1; + } else if (row2.contains(lowerC)) { + return row2; + } else { + return row3; + } + } + + public static void main(String[] args) { + Solution sol = new Solution(); + String[] words = {"Hello","Alaska","Dad","Peace"}; + String[] result = sol.findWords(words); + for (String word : result) { + System.out.println(word); + } + } +} +``` + +## Solution in C++ + +```cpp +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector findWords(vector& words) { + unordered_set row1 {'q','w','e','r','t','y','u','i','o','p'}; + unordered_set row2 {'a','s','d','f','g','h','j','k','l'}; + unordered_set row3 {'z','x','c','v','b','n','m'}; + + vector result; + + for (const string& word : words) { + if (isSingleRow(word, row1, row2, row3)) { + result.push_back(word); + } + } + + return result; + } + + bool isSingleRow(const string& word, unordered_set& row1, unordered_set& row2, unordered_set& row3) { + unordered_set* currentRow = determineRow(word[0], row1, row2, row3); + + for (int i = 1; i < word.size(); i++) { + if (currentRow->find(tolower(word[i])) == currentRow->end()) { + return false; + } + } + + return true; + } + + unordered_set* determineRow(char c, unordered_set& row1, unordered_set& row2, unordered_set& row3) { + char lowerC = tolower(c); + + if (row1.find(lowerC) != row1.end()) { + return &row1; + } else if (row2.find(lowerC) != row2.end()) { + return &row2; + } else { + return &row3; + } + } +}; + +int main() { + Solution sol; + vector words = {"Hello","Alaska","Dad","Peace"}; + vector result = sol.findWords(words); + for (const string& word : result) { + cout << word << endl; + } + return 0; +} +``` + +## Solution in C + +```c +#include +#include +#include +#include + +bool isSingleRow(char* word, char* row1, char* row2, char* row3) { + char* currentRow; + if (strchr(row1, tolower(word[0]))) { + currentRow = row1; + } else if (strchr(row2, tolower(word[0]))) { + currentRow = row2; + } else { + currentRow = row3; + } + + for (int i = 1; i < strlen(word); i++) { + if (!strchr(currentRow, tolower(word[i]))) { + return false; + } + } + + return true; +} + +void findWords(char** words, int wordsSize, char** result, int* returnSize) { + char* row1 = "qwertyuiop"; + char* row2 = "asdfghjkl"; + char* row3 = "zxcvbnm"; + + *returnSize = 0; + for (int i = 0; i < wordsSize; i++) { + if (isSingleRow(words[i], row1, row2, row3)) { + result[*returnSize] = words[i]; + (*returnSize)++; + } + } +} + +int main() { + char* words[] = {"Hello","Alaska","Dad","Peace"}; + int wordsSize = 4; + char* result[wordsSize]; + int returnSize; + + findWords(words, wordsSize, result, &returnSize); + + for (int i = 0; i < returnSize; i++) { + printf("%s\n", result[i]); + } + + return 0; +} +``` + +## Solution in JavaScript + +```javascript +/** + * @param {string[]} words + * @return {string[]} + */ +var findWords = function(words) { + const row1 = new Set("qwertyuiop"); + const row2 = new Set("asdfghjkl"); + const row3 = new Set("zxcvbnm"); + + const isSingleRow = (word) => { + let firstChar = word[0].toLowerCase(); + if (row1.has(firstChar)) { + row = row1; + } else if (row2.has(firstChar)) { + row = row2; + } else { + row = row3; + } + + for (let i = 1; i < word.length; i++) { + if (!row.has(word[i].toLowerCase())) { + return false; + } + } + return true; + } + + let result = []; + for (let word of words) { + if (isSingleRow(word)) { + result.push(word); + } + } + + return result; +}; + +// Example usage: +let words = ["Hello","Alaska","Dad","Peace"]; +console.log(findWords(words)); // Output: ["Alaska","Dad"] +``` + +## Step-by-Step Algorithm + +1. **Input Parsing**: Read the input array of words. +2. **Keyboard Rows Initialization**: Define three sets representing characters in each row of the keyboard. +3. **Function Definition**: Implement a function to determine if a word can be typed using characters from a single keyboard row. +4. **Iteration and Filtering**: Iterate through each word in the input array and \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0502-IPO.md b/solutions/lc-solutions/0500-0599/0502-IPO.md new file mode 100644 index 0000000..5aaaa99 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0502-IPO.md @@ -0,0 +1,292 @@ +--- +id: IPO +title: IPO +sidebar_label: IPO +tags: + - Dynamic Programming + - Greedy Algorithm + - Priority Queue +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [IPO](https://leetcode.com/problems/IPO/description/) | [IPO Solution on LeetCode](https://leetcode.com/problems/IPO/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +You are given `n` projects where the ith project has a pure profit `profits[i]` and a minimum capital of `capital[i]` is needed to start it. Initially, you have `w` capital. When you finish a project, you obtain its pure profit, which is added to your total capital. + +Your goal is to pick a list of at most `k` distinct projects to maximize your final capital. + +## Constraints + +- `1 <= k <= 10^5` +- `0 <= w <= 10^9` +- `1 <= n <= 10^5` +- `0 <= profits[i] <= 10^4` +- `0 <= capital[i] <= 10^9` + +## Approach + +The problem can be approached using a combination of greedy strategy and efficient data structures: +1. **Priority Queue (Max-Heap)**: Use a max-heap to always select the project with the maximum profit that can be started with the current capital. +2. **Sorting**: Sort projects based on their capital requirements. +3. **Iterative Selection**: Iterate up to `k` times (or until no more projects can be started) to select the project with the highest profit that can be started with the current capital. + +### Solution in Different languages + +## Solution in Python + +```python +import heapq + +def findMaximizedCapital(k, w, profits, capital): + n = len(profits) + projects = sorted(zip(capital, profits)) # Sort projects by their capital requirements + available_projects = [] + idx = 0 + for _ in range(k): + while idx < n and projects[idx][0] <= w: + heapq.heappush(available_projects, -projects[idx][1]) # Max-heap for profits + idx += 1 + if available_projects: + w -= heapq.heappop(available_projects) # Add the profit from the best project + else: + break + return w + +# Example usage: +k = 2 +w = 0 +profits = [1, 2, 3] +capital = [0, 1, 1] +print(findMaximizedCapital(k, w, profits, capital)) # Output: 4 +``` + +## Solution in Java + +```java +import java.util.PriorityQueue; + +class Solution { + public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) { + int n = profits.length; + int[][] projects = new int[n][2]; + for (int i = 0; i < n; i++) { + projects[i][0] = capital[i]; + projects[i][1] = profits[i]; + } + Arrays.sort(projects, (a, b) -> a[0] - b[0]); // Sort projects by their capital requirements + PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> b - a); + int idx = 0; + for (int i = 0; i < k; i++) { + while (idx < n && projects[idx][0] <= w) { + maxHeap.offer(projects[idx][1]); // Max-heap for profits + idx++; + } + if (!maxHeap.isEmpty()) { + w += maxHeap.poll(); // Add the profit from the best project + } else { + break; + } + } + return w; + } +} +``` + +## Solution in C++ + +```cpp +#include +#include +#include +using namespace std; + +class Solution { +public: + int findMaximizedCapital(int k, int w, vector& profits, vector& capital) { + int n = profits.size(); + vector> projects(n); + for (int i = 0; i < n; ++i) { + projects[i] = {capital[i], profits[i]}; + } + sort(projects.begin(), projects.end()); // Sort projects by their capital requirements + priority_queue maxHeap; + int idx = 0; + for (int i = 0; i < k; ++i) { + while (idx < n && projects[idx].first <= w) { + maxHeap.push(projects[idx].second); // Max-heap for profits + ++idx; + } + if (!maxHeap.empty()) { + w += maxHeap.top(); // Add the profit from the best project + maxHeap.pop(); + } else { + break; + } + } + return w; + } +}; +``` + +## Solution in C + +```c +#include + +// Helper function to sort projects by capital requirement +int compare(const void *a, const void *b) { + int *projA = *(int **)a; + int *projB = *(int **)b; + return projA[0] - projB[0]; +} + +int findMaximizedCapital(int k, int w, int* profits, int profitsSize, int* capital, int capitalSize) { + int n = profitsSize; + int **projects = (int **)malloc(n * sizeof(int *)); + for (int i = 0; i < n; ++i) { + projects[i] = (int *)malloc(2 * sizeof(int)); + projects[i][0] = capital[i]; + projects[i][1] = profits[i]; + } + qsort(projects, n, sizeof(int *), compare); // Sort projects by their capital requirements + int idx = 0; + for (int i = 0; i < k; ++i) { + while (idx < n && projects[idx][0] <= w) { + w += projects[idx][1]; // Add the profit from the best project + ++idx; + } + if (idx == n) break; + } + for (int i = 0; i < n; ++i) { + free(projects[i]); + } + free(projects); + return w; +} +``` + +## Solution in JavaScript + +```javascript +class PriorityQueue { + constructor(comparator = (a, b) => a - b) { + this._heap = []; + this._comparator = comparator; + } + + size() { + return this._heap.length; + } + + isEmpty() { + return this.size() === 0; + } + + peek() { + return this.isEmpty() ? undefined : this._heap[0]; + } + + push(...values) { + values.forEach(value => { + this._heap.push(value); + this._siftUp(); + }); + return this.size(); + } + + pop() { + const poppedValue = this.peek(); + const bottom = this.size() - 1; + if (bottom > 0) { + this._swap(0, bottom); + } + this._heap.pop(); + this._siftDown(); + return poppedValue; + } + + _parent(idx) { + return Math.floor((idx - 1) / 2); + } + + _left(idx) { + return idx * 2 + 1; + } + + _right(idx) { + return idx * 2 + 2; + } + + _swap(i, j) { + [this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]]; + } + + _greater(i, j) { + return this._comparator(this._heap[i], this._heap[j]) < 0; + } + + _siftUp() { + let node = this.size() - 1; + while (node > 0 && this._greater(node, this._parent(node))) { + this._swap(node, this._parent(node)); + node = this._parent(node); + } + } + + _siftDown() { + let node = 0; + while ( + (this._left(node) < this.size() && this._greater(this._left(node), node)) || + (this._right(node) < this.size() && this._greater(this._right(node), node)) + ) { + let maxChild = (this._right(node) < this.size() && this._greater(this._right(node), this._left(node))) ? this._right(node) : this._left(node); + this._swap(node, maxChild); + node = maxChild; + } + } +} + +var findMaximizedCapital = function(k, w, profits, capital) { + const n = profits.length; + const projects = []; + for (let i = 0; i < n; i++) { + projects.push([capital[i], profits[i]]); + } + projects.sort((a, b) => a[0] - b[0]); // Sort projects by their capital requirements + const maxHeap = new PriorityQueue((a, b) => b - a); + let idx = 0; + for (let i = 0; i < k; i++) { + while (idx < n && projects[idx][0] <= w) { + maxHeap.push(projects[idx][1]); // Max-heap for profits + idx++; + } + if (!maxHeap.isEmpty()) { + w += maxHeap.pop(); // Add the profit from the best project + } else { + break; + } + } + return w; +}; +``` + +## Step-by-Step Algorithm + +1. **Input Parsing**: Convert input data into appropriate data structures (arrays, lists, or vectors). +2. **Sorting**: Sort projects based on their capital requirements. +3. **Priority Queue Initialization**: Initialize a max-heap (priority queue) to keep track of the most profitable projects that can be started with the current capital. +4. **Iterative Selection**: + - For up to `k` times, iterate through the sorted projects. + - Push all feasible projects (capital requirement <= current capital) into the max-heap. + - If the max-heap is not empty, pop the project with the maximum profit and add its profit to the current capital. + - Break the loop if no more projects can be started. +5. **Return Result**: Return the current capital after selecting up to `k` projects. + +## Conclusion + +The provided solutions efficiently solve the problem of selecting at most `k` projects to maximize capital using a combination of greedy strategy and priority queues. This approach ensures that the solution is optimal and runs within acceptable time limits for the given constraints. diff --git a/solutions/lc-solutions/0500-0599/0503-next-greater-element-2.md b/solutions/lc-solutions/0500-0599/0503-next-greater-element-2.md new file mode 100644 index 0000000..b4ccc2c --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0503-next-greater-element-2.md @@ -0,0 +1,225 @@ +--- +id: next-greater-element-ii +title: Next Greater Element II +sidebar_label: 0503-Next-Greater-Element-II +tags: +- Array +- Stack +- Monotonic Stack +description: "Given a circular integer array nums (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return the next greater number for every element in nums.." +--- + +## Problem + +Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return the next greater number for every element in nums. + +The next greater number of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return `-1` for this number. + +### Examples + +**Example 1:** +``` +Input: nums = [1,2,1] +Output: [2,-1,2] +Explanation: The first 1's next greater number is 2; +The number 2 can't find next greater number. +The second 1's next greater number needs to search circularly, which is also 2. +``` + +**Example 2:** + +``` +Input: nums = [1,2,3,4,3] +Output: [2,3,4,-1,4] +``` + +### Constraints + +- `1 <= nums.length <= 10^4`. +- `-10^9 <= nums[i] <= 10^9` + +--- + +## Solution for Next Greater Element II + + + +### Brute Force - Recursion + +#### Intuition +The idea is to make use of an array doublearr which is formed by concatenating two copies of the given array one after the other. Now, when we need to find out the next greater element for `arr[i]`, we can simply scan all the elements `doublearr[j]`. The first element found satisfying the given condition is the required result for `arr[i]`. If no such element is found, we put a `-1` at the appropriate position in the res array. + +#### Implementation +- Create an empty vector to store the next greater element for each element in the input array. + Duplicate the input array to create a circular array. This is done by appending the original array to itself. +- Start iterating through each element in the original array. +- For each element in the original array, search for the next greater element in the circular array + starting from the next position after the current element. +- If a greater element is found, update the corresponding index in the result vector with the value + of the greater element. If no greater element is found, keep the index in the result vector as -1. +- Once all elements have been processed, return the result vector containing the next greater + element for each element in the input array. + +#### Brute Force Solution + +#### Implementation + +``` +class Solution { + public: + vector nextGreaterElement(int N, vector& arr) { + vector res(N, -1); + vector doublearr(arr.begin(), arr.end()); + doublearr.insert(doublearr.end(), arr.begin(), arr.end()); + for (int i = 0; i < N; i++) { + for (int j = i + 1; j < doublearr.size(); j++) { + if (doublearr[j] > doublearr[i]) { + res[i] = doublearr[j]; + break; + } + } + } + return res; + // code here + } +}; +``` + +#### Code in Different Languages + + + + + ```python + class Solution: + def nextGreaterElement(self, N, arr): + res = [-1] * len(arr) + doublearr = arr + arr + for i in range(len(arr)): + for j in range(i + 1, len(doublearr)): + if doublearr[j] > doublearr[i]: + res[i] = doublearr[j] + break + return res + + ``` + + + + + +``` +class Solution { + static int[] nextGreaterElement(int N, int arr[]) { + int[] res = new int[arr.length]; + int[] doublearr = new int[arr.length * 2]; + System.arraycopy(arr, 0, doublearr, 0, arr.length); + System.arraycopy(arr, 0, doublearr, arr.length, arr.length); + for (int i = 0; i < arr.length; i++) { + res[i]=-1; + for (int j = i + 1; j < doublearr.length; j++) { + if (doublearr[j] > doublearr[i]) { + res[i] = doublearr[j]; + break; + } + } + } + return res; + } +} + +``` + + + + + ```cpp + class Solution { + public: + vector nextGreaterElement(int N, vector& arr) { + vector res(N, -1); + vector doublearr(arr.begin(), arr.end()); + doublearr.insert(doublearr.end(), arr.begin(), arr.end()); + for (int i = 0; i < N; i++) { + for (int j = i + 1; j < doublearr.size(); j++) { + if (doublearr[j] > doublearr[i]) { + res[i] = doublearr[j]; + break; + } + } + } + return res; + // code here + } +}; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(N^2)$ + - The function iterates through each element in the input array, resulting in $O(N)$ iterations. + For each element, it searches for the next greater element in the circular array, which may require iterating through the entire circular array in the worst case, resulting in another $O(N)$ iterations. + Therefore, the overall time complexity is $O(N^2)$. +- Space Complexity: $O(N)$ + - The function creates a duplicate circular array of size $2N$ to handle cases where the next greater element wraps around to the beginning of the array. Therefore, the additional space required is $O(N)$ to store this duplicate array. + - Additionally, the result vector to store the next greater element for each element in the input array also requires $O(N)$ space. +Therefore, the overall space complexity is $O(N)$. + + + + +### Optimized Approach +#### Intuition +This approach relies on the concept of a monotonic stack to efficiently find the next greater element for each element in the input array. It iterates through a concatenated version of the array to simulate a circular structure, ensuring that every element's next greater element is considered + +#### Approach +- Create a vector ans of size N, initialized with -1. This vector will store the next greater + elements for each element in the input vector arr. +- Create an empty stack st to store indices. +- Iterate through each index i from `0` to `2*N-1` using a for loop. +- Inside the loop, while the stack is not empty and the element at index `arr[st.top()]` is less than the current element `arr[i % N]`, update the ans vector at index `st.top()` with the current + element `arr[i % N]` and pop the top element from the stack. +- Push the current index `i % N` onto the stack. + After the loop, return the ans vector containing the next greater elements for each element in the input vector arr. + + + + + ```cpp + +class Solution { + public: + vector nextGreaterElement(int N, vector& arr) { + vector ans(N, -1); + stack st; + for (int i = 0; i < 2 * N; i++) { + while (!st.empty() and arr[st.top()] < arr[i % N]) { + ans[st.top()] = arr[i % N]; + st.pop(); + } + st.push(i % N); + } + return ans; + } +}; + ``` + + + + +#### Complexity Analysis +- Time Complexity: $ O(N)$ +- Space Complexity: $ O(N)$ + + + + +## References + +- **LeetCode Problem**: [Next Greater Element II](https://leetcode.com/problems/next-greater-element-ii/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/next-greater-element-ii/solutions/) + diff --git a/solutions/lc-solutions/0500-0599/0506-relative-ranks.md b/solutions/lc-solutions/0500-0599/0506-relative-ranks.md new file mode 100644 index 0000000..12d7d88 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0506-relative-ranks.md @@ -0,0 +1,119 @@ +--- +id: relative-ranks +title: Relative Ranks +level: easy +sidebar_label: Relative Ranks +tags: + - Array + - Sorting + - Java +description: "This document provides solutions for the Relative Ranks problem." +--- + +## Problem Statement + +You are given an integer array `score` of size `n`, where `score[i]` is the score of the `i`-th athlete in a competition. All the scores are guaranteed to be unique. + +The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank: + +- The 1st place athlete's rank is "Gold Medal". +- The 2nd place athlete's rank is "Silver Medal". +- The 3rd place athlete's rank is "Bronze Medal". +- For the 4th place to the `n`-th place athlete, their rank is their placement number (i.e., the `x`-th place athlete's rank is "x"). + +Return an array `answer` of size `n` where `answer[i]` is the rank of the `i`-th athlete. + +**Example 1:** + +Input: `score = [5,4,3,2,1]` + +Output: `["Gold Medal","Silver Medal","Bronze Medal","4","5"]` + +Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th]. + +**Example 2:** + +Input: `score = [10,3,8,9,4]` + +Output: `["Gold Medal","5","Bronze Medal","Silver Medal","4"]` + +Explanation: The placements are [1st, 5th, 3rd, 2nd, 4th]. + +**Constraints:** + +- `n == score.length` +- `1 <= n <= 10^4` +- `0 <= score[i] <= 10^6` +- All the values in `score` are unique. + +## Solutions + +### Approach + +To determine the ranks of the athletes based on their scores, we can follow these steps: + +1. **Store Scores and Indices**: + - Use a list to store the scores along with their original indices. + +2. **Sort the List**: + - Sort the list in descending order based on scores. + +3. **Assign Ranks**: + - Traverse through the sorted list and assign ranks accordingly: + - "Gold Medal" for the 1st highest score. + - "Silver Medal" for the 2nd highest score. + - "Bronze Medal" for the 3rd highest score. + - The placement number for the rest. + +### Java + +```java +class Solution { + public String[] findRelativeRanks(int[] score) { + String[] ret = new String[score.length]; + ArrayList list = new ArrayList<>(); + + for (int i = 0; i < score.length; i++) { + list.add(score[i]); + } + + Collections.sort(list, Collections.reverseOrder()); + + for (int i = 0; i < score.length; i++) { + int index = list.indexOf(score[i]) + 1; + if (index == 1) + ret[i] = "Gold Medal"; + else if (index == 2) + ret[i] = "Silver Medal"; + else if (index == 3) + ret[i] = "Bronze Medal"; + else + ret[i] = index + ""; + } + + return ret; + } +} +``` + +### Python +```Python +class Solution: + def findRelativeRanks(self, score: List[int]) -> List[str]: + ret = [""] * len(score) + sorted_scores = sorted(score, reverse=True) + + for i in range(len(score)): + rank = sorted_scores.index(score[i]) + 1 + if rank == 1: + ret[i] = "Gold Medal" + elif rank == 2: + ret[i] = "Silver Medal" + elif rank == 3: + ret[i] = "Bronze Medal" + else: + ret[i] = str(rank) + + return ret +``` + diff --git a/solutions/lc-solutions/0500-0599/0507-perfect-number.md b/solutions/lc-solutions/0500-0599/0507-perfect-number.md new file mode 100644 index 0000000..5195540 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0507-perfect-number.md @@ -0,0 +1,127 @@ +--- +id: perfect-number +title: Perfect Number +level: easy +sidebar_label: Perfect Number +tags: + - Math + - Java + - C++ +description: "This document provides solutions for the Perfect Number problem." +--- + +## Problem Statement + +A **perfect number** is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A positive integer `n` is given, and we need to determine whether it is a perfect number. + +**Example 1:** + +Input: `num = 28` + +Output: `true` + +Explanation: 28 = 1 + 2 + 4 + 7 + 14 + +**Example 2:** + +Input: `num = 6` + +Output: `true` + +Explanation: 6 = 1 + 2 + 3 + +**Example 3:** + +Input: `num = 496` + +Output: `true` + +**Example 4:** + +Input: `num = 8128` + +Output: `true` + +**Example 5:** + +Input: `num = 2` + +Output: `false` + +**Constraints:** + +- `1 <= num <= 10^8` + +## Solutions + +### Approach + +To determine if a number is perfect, we can follow these steps: + +1. **Initialize Sum**: + - Initialize a variable to store the sum of divisors. + +2. **Find Divisors**: + - Iterate from 1 to `num/2` and add all divisors of `num` to the sum. + +3. **Check Sum**: + - Compare the sum of divisors with the original number. If they are equal, the number is perfect. + +### Java + +```java +class Solution { + public boolean checkPerfectNumber(int num) { + if (num <= 1) return false; + int sum = 1; + for (int i = 2; i <= Math.sqrt(num); i++) { + if (num % i == 0) { + sum += i; + if (i != num / i) { + sum += num / i; + } + } + } + return sum == num; + } +} +``` + +### C++ + +```cpp +class Solution { +public: + bool checkPerfectNumber(int num) { + if (num <= 1) return false; + int sum = 1; + for (int i = 2; i <= sqrt(num); i++) { + if (num % i == 0) { + sum += i; + if (i != num / i) { + sum += num / i; + } + } + } + return sum == num; + } +}; +``` + +### Python + +```python +class Solution: + def checkPerfectNumber(self, num: int) -> bool: + if num <= 1: + return False + sum_divisors = 1 + for i in range(2, int(num ** 0.5) + 1): + if num % i == 0: + sum_divisors += i + if i != num // i: + sum_divisors += num // i + return sum_divisors == num +``` + +These solutions efficiently determine if a number is perfect by iterating through potential divisors up to the square root of the number, ensuring an optimal time complexity. \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0508-Most-Frequent-Subtree-Sum.md b/solutions/lc-solutions/0500-0599/0508-Most-Frequent-Subtree-Sum.md new file mode 100644 index 0000000..977bf5f --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0508-Most-Frequent-Subtree-Sum.md @@ -0,0 +1,181 @@ +--- +id: most-frequent-subtree-sum +title: Most Frequent Subtree Sum +sidebar_label: 0508-Most-Frequent-Subtree-Sum +tags: +- Tree +- Depth-First Search +- Hash Table +- Binary Tree +description: "Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order." +--- + +## Problem + +Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order. + +The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). + +### Examples + +**Example 1:** + +**Input:** `root = [5,2,-3]` +**Output:** `[2,-3,4]` +**Explanation:** The subtree sums are: + - Sum of the subtree rooted at node `5`: 4 (5 + 2 - 3) + - Sum of the subtree rooted at node `2`: 2 + - Sum of the subtree rooted at node `-3`: -3 + The most frequent subtree sums are [2, -3, 4], occurring once each. + +**Example 2:** + +**Input:** `root = [5,2,-5]` +**Output:** `[2]` +**Explanation:** The subtree sums are: + - Sum of the subtree rooted at node `5`: 2 (5 + 2 - 5) + - Sum of the subtree rooted at node `2`: 2 + - Sum of the subtree rooted at node `-5`: -5 + The most frequent subtree sum is 2, occurring twice. + +### Constraints + +- The number of nodes in the tree is in the range `[1, 10^4]`. +- `-10^5 <= Node.val <= 10^5` + +--- + +## Approach + +To solve this problem, we need to calculate the sum of all nodes for each subtree and count the frequency of each sum. Finally, we return the sums that have the highest frequency. + +### Steps: + +1. Use a hash table (dictionary) to store the frequency of each subtree sum. +2. Traverse the tree using depth-first search (DFS) to calculate the sum of each subtree. +3. For each node, calculate the subtree sum and update the frequency in the hash table. +4. Determine the maximum frequency and collect all sums that have this frequency. +5. Return the list of sums with the highest frequency. + +### Solution + +#### Java Solution + +```java +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +class Solution { + private Map countMap = new HashMap<>(); + private int maxCount = 0; + + public int[] findFrequentTreeSum(TreeNode root) { + if (root == null) return new int[0]; + dfs(root); + List result = new ArrayList<>(); + for (Map.Entry entry : countMap.entrySet()) { + if (entry.getValue() == maxCount) { + result.add(entry.getKey()); + } + } + return result.stream().mapToInt(i -> i).toArray(); + } + + private int dfs(TreeNode node) { + if (node == null) return 0; + int sum = node.val + dfs(node.left) + dfs(node.right); + countMap.put(sum, countMap.getOrDefault(sum, 0) + 1); + maxCount = Math.max(maxCount, countMap.get(sum)); + return sum; + } +} +``` +### C++ Solution + +```cpp +#include +#include +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + vector findFrequentTreeSum(TreeNode* root) { + unordered_map countMap; + int maxCount = 0; + vector result; + dfs(root, countMap, maxCount); + for (const auto& entry : countMap) { + if (entry.second == maxCount) { + result.push_back(entry.first); + } + } + return result; + } + +private: + int dfs(TreeNode* node, unordered_map& countMap, int& maxCount) { + if (node == nullptr) return 0; + int sum = node->val + dfs(node->left, countMap, maxCount) + dfs(node->right, countMap, maxCount); + countMap[sum]++; + maxCount = max(maxCount, countMap[sum]); + return sum; + } +}; +``` +### Python + +```python +from collections import defaultdict +from typing import List, Optional + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]: + if not root: + return [] + + def dfs(node): + if not node: + return 0 + total = node.val + dfs(node.left) + dfs(node.right) + count[total] += 1 + self.maxCount = max(self.maxCount, count[total]) + return total + + count = defaultdict(int) + self.maxCount = 0 + dfs(root) + return [s for s in count if count[s] == self.maxCount] +``` +### Complexity Analysis +**Time Complexity:** O(n) +>Reason: Each node is visited once during the DFS traversal. + +### Space Complexity: O(n) +>Reason: The space required to store the subtree sums and their frequencies in the hash table is proportional to the number of nodes. + +### References +LeetCode Problem: Most Frequent Subtree Sum \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0509-Fibonacci-Numbers.md b/solutions/lc-solutions/0500-0599/0509-Fibonacci-Numbers.md new file mode 100644 index 0000000..1de7d71 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0509-Fibonacci-Numbers.md @@ -0,0 +1,206 @@ +--- +id: Fibonacci-Numbers +title: Fibonacci-Numbers +sidebar_label: Fibonacci-Numbers +tags: + - Fibonacci + - Dynamic Programming + - Recursion + - Algorithms +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Fibonacci-Numbers](https://leetcode.com/problems/Fibonacci-Numbers/description/) | [Fibonacci-Numbers Solution on LeetCode](https://leetcode.com/problems/Fibonacci-Numbers/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +The Fibonacci numbers, commonly denoted F(n), form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, + +- F(0) = 0 +- F(1) = 1 +- F(n) = F(n-1) + F(n-2) for n > 1 + +Given an integer n, calculate F(n). + +### Examples + +### Example 1 +**Input:** `n = 2` +**Output:** `1` +**Explanation:** `F(2) = F(1) + F(0) = 1 + 0 = 1.` + +### Example 2 +**Input:** `n = 3` +**Output:** `2` +**Explanation:** `F(3) = F(2) + F(1) = 1 + 1 = 2.` + +### Example 3 +**Input:** `n = 4` +**Output:** `3` +**Explanation:** `F(4) = F(3) + F(2) = 2 + 1 = 3.` + +## Constraints + +- `0 <= n <= 30` + +## Approach + +There are several approaches to solve the Fibonacci problem: +1. **Recursive Approach**: Simple but inefficient due to redundant calculations. +2. **Iterative Approach**: Efficient using a loop to build up the Fibonacci sequence. +3. **Dynamic Programming Approach**: Efficiently store computed results to avoid redundant calculations. + +## Solution in different languages + +### Solution in Python +```python +def fibonacci(n): + if n == 0: + return 0 + elif n == 1: + return 1 + + prev1, prev2 = 0, 1 + for i in range(2, n + 1): + current = prev1 + prev2 + prev1, prev2 = prev2, current + + return prev2 + +# Example usage: +n = 4 +print(fibonacci(n)) # Output: 3 +``` + +### Solution in Java + +```java +public class Solution { + public int fibonacci(int n) { + if (n == 0) { + return 0; + } else if (n == 1) { + return 1; + } + + int prev1 = 0, prev2 = 1; + for (int i = 2; i <= n; i++) { + int current = prev1 + prev2; + prev1 = prev2; + prev2 = current; + } + + return prev2; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + int n = 4; + System.out.println(solution.fibonacci(n)); // Output: 3 + } +} +``` + +### Solution in C++ + +```cpp +#include +using namespace std; + +int fibonacci(int n) { + if (n == 0) { + return 0; + } else if (n == 1) { + return 1; + } + + int prev1 = 0, prev2 = 1; + for (int i = 2; i <= n; i++) { + int current = prev1 + prev2; + prev1 = prev2; + prev2 = current; + } + + return prev2; +} + +int main() { + int n = 4; + cout << fibonacci(n) << endl; // Output: 3 + return 0; +} +``` + +### Solution in C + +```c +#include + +int fibonacci(int n) { + if (n == 0) { + return 0; + } else if (n == 1) { + return 1; + } + + int prev1 = 0, prev2 = 1; + for (int i = 2; i <= n; i++) { + int current = prev1 + prev2; + prev1 = prev2; + prev2 = current; + } + + return prev2; +} + +int main() { + int n = 4; + printf("%d\n", fibonacci(n)); // Output: 3 + return 0; +} +``` + +### Solution in JavaScript + +```javascript +function fibonacci(n) { + if (n === 0) { + return 0; + } else if (n === 1) { + return 1; + } + + let prev1 = 0, prev2 = 1; + for (let i = 2; i <= n; i++) { + let current = prev1 + prev2; + prev1 = prev2; + prev2 = current; + } + + return prev2; +} + +// Example usage: +let n = 4; +console.log(fibonacci(n)); // Output: 3 +``` + +## Step-by-Step Algorithm + +1. **Base Cases**: + - If \( n = 0 \), return 0. + - If \( n = 1 \), return 1. + +2. **Iterative Calculation**: + - Initialize `prev1` to 0 and `prev2` to 1. + - Iterate from 2 to n: + - Calculate `current` as `prev1 + prev2`. + - Update `prev1` to `prev2` and `prev2` to `current`. + - After the loop, `prev2` contains the Fibonacci number for \( n \). + +## Conclusion + +The Fibonacci sequence can be efficiently computed using iterative or dynamic programming approaches to avoid redundant calculations. These methods provide a clear improvement over the naive recursive approach, especially for larger values of \( n \). The iterative approach is straightforward and runs in \( O(n) \) time complexity with \( O(1) \) space complexity, making it suitable for the given constraints \( 0 \leq n \leq 30 \). diff --git a/solutions/lc-solutions/0500-0599/0513-Find-Bottom-Left-Tree-Value.md b/solutions/lc-solutions/0500-0599/0513-Find-Bottom-Left-Tree-Value.md new file mode 100644 index 0000000..ae00810 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0513-Find-Bottom-Left-Tree-Value.md @@ -0,0 +1,154 @@ +--- +id: find-bottom-left-tree-value +title: Find Bottom Left Tree Value +sidebar_label: 0513-Find-Bottom-Left-Tree-Value +tags: +- Tree +- Depth-First Search +- Breadth-First Search +- Binary Tree +description: "Given the root of a binary tree, return the leftmost value in the last row of the tree." +--- + +## Problem + +Given the root of a binary tree, return the leftmost value in the last row of the tree. + +### Examples + +**Example 1:** + +**Input:** `root = [2,1,3]` +**Output:** `1` + +**Example 2:** + +**Input:** `root = [1,2,3,4,null,5,6,null,null,7]` +**Output:** `7` + +### Constraints + +- The number of nodes in the tree is in the range `[1, 10^4]`. +- `-2^31 <= Node.val <= 2^31 - 1` + +--- + +## Approach + +To find the leftmost value in the last row of the binary tree, we can use either Breadth-First Search (BFS) or Depth-First Search (DFS). The BFS approach involves traversing the tree level by level from left to right, ensuring that the first node encountered at the last level is the leftmost node. The DFS approach involves keeping track of the depth and updating the leftmost value when a deeper node is found. + +### Steps for BFS: + +1. Initialize a queue and enqueue the root node. +2. While the queue is not empty, process each level: + - Keep track of the first node at each level. + - Enqueue all child nodes of the current level nodes. +3. The leftmost value of the last processed level is the desired result. + +### Steps for DFS: + +1. Initialize variables to keep track of the maximum depth and the leftmost value. +2. Perform a DFS traversal, updating the leftmost value whenever a deeper node is found. + +### Solution + +#### Java Solution + +```java +import java.util.LinkedList; +import java.util.Queue; + +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +class Solution { + public int findBottomLeftValue(TreeNode root) { + Queue queue = new LinkedList<>(); + queue.add(root); + int bottomLeftValue = root.val; + + while (!queue.isEmpty()) { + TreeNode node = queue.poll(); + if (node.right != null) queue.add(node.right); + if (node.left != null) queue.add(node.left); + bottomLeftValue = node.val; + } + + return bottomLeftValue; + } +} +``` +### C++ Solution + +```cpp +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + int findBottomLeftValue(TreeNode* root) { + queue q; + q.push(root); + int bottomLeftValue = root->val; + + while (!q.empty()) { + TreeNode* node = q.front(); + q.pop(); + if (node->right) q.push(node->right); + if (node->left) q.push(node->left); + bottomLeftValue = node->val; + } + + return bottomLeftValue; + } +}; +``` +### Python + +```python +from collections import deque +from typing import Optional + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: + queue = deque([root]) + bottom_left_value = root.val + + while queue: + node = queue.popleft() + if node.right: + queue.append(node.right) + if node.left: + queue.append(node.left) + bottom_left_value = node.val + + return bottom_left_value +``` +### Complexity Analysis +**Time Complexity:** O(n) +>Reason: Each node is visited once during the traversal. + +**Space Complexity:** O(n) +>Reason: In the worst case, the space required for the queue or recursion stack is proportional to the number of nodes. + +### References +LeetCode Problem: Find Bottom Left Tree Value + diff --git a/solutions/lc-solutions/0500-0599/0515-find-largest-value-in-each-tree-row.md b/solutions/lc-solutions/0500-0599/0515-find-largest-value-in-each-tree-row.md new file mode 100644 index 0000000..d317bfa --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0515-find-largest-value-in-each-tree-row.md @@ -0,0 +1,465 @@ +--- +id: find-largest-value-in-each-tree-row +title: Find Largest Value in Each Tree Row +sidebar_label: 0515 - Find Largest Value in Each Tree Row +tags: + - Breadth-First Search + - Binary Tree + - Depth-First Search +description: "This is a solution to the Find Largest Value in Each Tree Row problem on LeetCode." +--- + +## Problem Description + +Given the root of a binary tree, return an array of the largest value in each row of the tree **(0-indexed)**. + +### Examples + +**Example 1:** + +![image](https://assets.leetcode.com/uploads/2020/08/21/largest_e1.jpg) +``` +Input: root = [1,3,2,5,3,null,9] +Output: [1,3,9] +``` + +**Example 2:** + +``` +Input: root = [1,2,3] +Output: [1,3] +``` + +### Constraints + +- The number of nodes in the tree will be in the range $[0, 10^4]$. +- $-2^{31} <= Node.val <= 2^{31} - 1$ + +## Solution for Find Largest Value in Each Tree Row + +### Approach 1: Breadth First Search (BFS) +#### Intuition +BFS is perfect when we are dealing specifically with rows/levels of a binary tree. With BFS, we handle one row of the tree at a time. + +Here, we need to find the maximum value in each row. We can simply perform a BFS and for each row, keep track of the maximum value we have seen so far. We will initialize an integer `currMax` to a small value like negative infinity. Then we go through the row and try to update `currMax` when we see larger values. After handling the row, we add `currMax` to our answer. +#### Algorithm + +1. If the `root` is null (empty) tree, just return an empty list. +2. Initialize the answer list `ans` and a `queue` with the `root` to perform BFS. +3. Perform BFS - while the `queue` is not empty: + - Initialize `currMax` to a small value and save the length of the queue in `currentLength`. + - Iterate `currentLength` times: + - Remove a `node` from the `queue`. + - Update `currMax` with `node.val` if it is larger. + - For each child of `node`, if it is not null, push it to the `queue`. + - Add `currMax` to `ans`. +4. Return ans. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector largestValues(TreeNode* root) { + if (root == nullptr) { + return vector{}; + } + + vector ans; + queue queue; + queue.push(root); + + while (!queue.empty()) { + int currentLength = queue.size(); + int currMax = INT_MIN; + + for (int i = 0; i < currentLength; i++) { + TreeNode* node = queue.front(); + queue.pop(); + currMax = max(currMax, node->val); + + if (node->left) { + queue.push(node->left); + } + + if (node->right) { + queue.push(node->right); + } + } + + ans.push_back(currMax); + } + + return ans; + } +}; +``` + + + + +```java +class Solution { + public List largestValues(TreeNode root) { + if (root == null) { + return new ArrayList(); + } + + List ans = new ArrayList(); + Queue queue = new LinkedList<>(); + queue.add(root); + + while (!queue.isEmpty()) { + int currentLength = queue.size(); + int currMax = Integer.MIN_VALUE; + + for (int i = 0; i < currentLength; i++) { + TreeNode node = queue.remove(); + currMax = Math.max(currMax, node.val); + + if (node.left != null) { + queue.add(node.left); + } + + if (node.right != null) { + queue.add(node.right); + } + } + + ans.add(currMax); + } + + return ans; + } +} +``` + + + + + +```python +class Solution: + def largestValues(self, root: Optional[TreeNode]) -> List[int]: + if not root: + return [] + + ans = [] + queue = deque([root]) + + while queue: + current_length = len(queue) + curr_max = float("-inf") + + for _ in range(current_length): + node = queue.popleft() + curr_max = max(curr_max, node.val) + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + + ans.append(curr_max) + + return ans +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: During the BFS, we visit each node in the tree once. At each node, we perform O(1) work. + +### Space Complexity: $O(N)$ + +> **Reason**: In a perfect binary tree, the final row has $$O(\frac{n}{2}) = O(n)$$ nodes, all of which will be in `queue`. + +### Approach 2: Depth First Search (DFS) + +#### Intuition +In BFS, we handle each row explicitly, so it's easy to just keep track of the maximum value as we traverse through the row. + +In DFS, the order in which we move through the tree is not related to the rows. Thus, we need to be more creative to find the maximum value in each row. The first observation to make is that each row can be described by the depth of its nodes. + +![image](https://assets.leetcode.com/static_assets/media/original_images/515/1.png) + +The depth of a node is its distance from the root. The root has a depth of `0`, and every child has a depth of `1` greater than its parent. You may also notice that in terms of indices, each node's depth corresponds to its index in the answer. + +For example, if `ans` is our answer list, then `ans[2]` holds the maximum value of all nodes with depth `2`. + +If we keep track of each node's depth during the traversal, then we can update `ans` directly. How do we keep track of the depth? We will pass an additional argument `depth` in our `dfs` function. When we initially call `dfs` with `root`, we will pass `depth = 0`. When we call dfs on a child, we will pass `depth + 1`. + +There is one problem: how do we know what length `ans` should be? We will initialize `ans` as an empty list. If we are at a `depth` that would be out of bounds if we tried to access `ans[depth]`, then we will simply initialize the current `node.val` as the maximum value seen at `depth` so far by pushing `node.val` to `ans`. + +#### Algorithm + +1. Initialize ans as an empty list. +2. Define a function dfs(node, depth): + - If node is null, return. + - If depth == ans.length, then push node.val to ans. Otherwise, try to update ans[depth] with node.val if its larger. + - Call dfs on node.left and node.right with depth + 1 as the second argument. +3. Call dfs(root, 0) and then return ans. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector ans; + + vector largestValues(TreeNode* root) { + dfs(root, 0); + return ans; + } + + void dfs(TreeNode* node, int depth) { + if (node == nullptr) { + return; + } + + if (depth == ans.size()) { + ans.push_back(node->val); + } else { + ans[depth] = max(ans[depth], node->val); + } + + dfs(node->left, depth + 1); + dfs(node->right, depth + 1); + } +}; +``` + + + + +```java +class Solution { + List ans; + + public List largestValues(TreeNode root) { + ans = new ArrayList(); + dfs(root, 0); + return ans; + } + + public void dfs(TreeNode node, int depth) { + if (node == null) { + return; + } + + if (depth == ans.size()) { + ans.add(node.val); + } else { + ans.set(depth, Math.max(ans.get(depth), node.val)); + } + + dfs(node.left, depth + 1); + dfs(node.right, depth + 1); + } +} +``` + + + + + +```python +class Solution: + def largestValues(self, root: Optional[TreeNode]) -> List[int]: + def dfs(node, depth): + if not node: + return + + if depth == len(ans): + ans.append(node.val) + else: + ans[depth] = max(ans[depth], node.val) + + dfs(node.left, depth + 1) + dfs(node.right, depth + 1) + + ans = [] + dfs(root, 0) + return ans +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: During the DFS, we visit each node in the tree once. At each node, we perform O(1) work. + +### Space Complexity: $O(H)$ + +> **Reason**: We use extra space for the recursion call stack. The most calls in the call stack at any given time will be the max depth of the tree. In the worst-case scenario where the tree is like a linked list, the max depth will be O(N). + +### Approach 3: DFS, Iterative + +#### Intuition + +We can also implement DFS iteratively using a stack. Each entry in the stack will be a pair `node, depth`. We will use a while loop to perform the DFS, with each iteration being analogous to a function call from the previous approach. As such, we will perform the same process in each while loop iteration: try to update `ans` with `node.val`, then push the children of `node` to the stack if they exist. + +#### Algorithm + +1. If the `root` is null (empty) tree, just return an empty list. +2. Initialize the answer list `ans` and a `stack` with `(root, 0)`. +3. While the `stack` is not empty: + - Pop `(node, depth)` from the stack. + - If `depth == ans.length`, then push `node.val` to `ans`. Otherwise, try to update `ans[depth]` with `node.val` if its larger. + - If `node.left` is not null, push `(node.left, depth + 1)` to `stack`. + - If `node.right` is not null, push `(node.right, depth + 1)` to `stack`. +4. Return `ans`. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector largestValues(TreeNode* root) { + if (root == nullptr) { + return vector{}; + } + + vector ans; + stack> stack; + stack.push(make_pair(root, 0)); + + while (!stack.empty()) { + pair pair = stack.top(); + stack.pop(); + TreeNode* node = pair.first; + int depth = pair.second; + + if (depth == ans.size()) { + ans.push_back(node->val); + } else { + ans[depth] = max(ans[depth], node->val); + } + + if (node->left) { + stack.push(make_pair(node->left, depth + 1)); + } + + if (node->right) { + stack.push(make_pair(node->right, depth + 1)); + } + } + + return ans; + } +}; +``` + + + + +```java +class Solution { + public List largestValues(TreeNode root) { + if (root == null) { + return new ArrayList(); + } + + List ans = new ArrayList<>(); + Stack> stack = new Stack<>(); + stack.push(new Pair<>(root, 0)); + + while (!stack.isEmpty()) { + Pair pair = stack.pop(); + TreeNode node = pair.getKey(); + int depth = pair.getValue(); + + if (depth == ans.size()) { + ans.add(node.val); + } else { + ans.set(depth, Math.max(ans.get(depth), node.val)); + } + + if (node.left != null) { + stack.push(new Pair<>(node.left, depth + 1)); + } + + if (node.right != null) { + stack.push(new Pair<>(node.right, depth + 1)); + } + } + + return ans; + } +} +``` + + + + + +```python +class Solution: + def largestValues(self, root: Optional[TreeNode]) -> List[int]: + if not root: + return [] + + ans = [] + stack = [(root, 0)] + + while stack: + node, depth = stack.pop() + if depth == len(ans): + ans.append(node.val) + else: + ans[depth] = max(ans[depth], node.val) + + if node.left: + stack.append((node.left, depth + 1)) + if node.right: + stack.append((node.right, depth + 1)) + + return ans +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: During the DFS, we visit each node in the tree once. At each node, we perform O(1) work. + +### Space Complexity: $O(H)$ + +> **Reason**: We use extra space for the recursion call stack. The most calls in the call stack at any given time will be the max depth of the tree. In the worst-case scenario where the tree is like a linked list, the max depth will be O(N). +> +> We pop the top node from the stack and then push its child nodes onto the stack based on the DFS traversal strategy. This process of pushing and popping forms a path-like structure within the stack, and the length of this path will not exceed the height of the tree. Therefore, O(H) space will be used. + + +## References + +- **LeetCode Problem**: [Find Largest Value in Each Tree Row](https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/) + +- **Solution Link**: [Find Largest Value in Each Tree Row](https://leetcode.com/problems/find-largest-value-in-each-tree-row/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0516-Longest-Palindromic-Subsequence.md b/solutions/lc-solutions/0500-0599/0516-Longest-Palindromic-Subsequence.md new file mode 100644 index 0000000..dce95c5 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0516-Longest-Palindromic-Subsequence.md @@ -0,0 +1,129 @@ +--- +id: longest-palindromic-subsequence +title: Longest Palindromic Subsequence +sidebar_label: 0516-Longest-Palindromic-Subsequence +tags: +- Dynamic Programming +- String +description: "Given a string s, find the longest palindromic subsequence's length in s." +--- + +## Problem + +Given a string `s`, find the longest palindromic subsequence's length in `s`. + +A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. + +### Examples + +**Example 1:** + +**Input:** `s = "bbbab"` +**Output:** `4` +**Explanation:** One possible longest palindromic subsequence is "bbbb". + +**Example 2:** + +**Input:** `s = "cbbd"` +**Output:** `2` +**Explanation:** One possible longest palindromic subsequence is "bb". + +### Constraints + +- `1 <= s.length <= 1000` +- `s` consists only of lowercase English letters. + +--- + +## Approach + +To solve this problem, we can use dynamic programming. We will create a 2D array `dp` where `dp[i][j]` represents the length of the longest palindromic subsequence in the substring `s[i:j+1]`. + +### Steps: + +1. Initialize a 2D array `dp` of size `n x n` where `n` is the length of the string `s`. Set all elements to 0. +2. For each single character, set `dp[i][i] = 1` because a single character is a palindrome of length 1. +3. Fill the `dp` array in a bottom-up manner: + - For each substring length `l` from 2 to `n`: + - For each starting index `i` from 0 to `n-l`: + - Set `j = i + l - 1`. + - If `s[i] == s[j]`, then `dp[i][j] = dp[i+1][j-1] + 2`. + - Otherwise, `dp[i][j] = max(dp[i+1][j], dp[i][j-1])`. +4. The result will be `dp[0][n-1]`, the length of the longest palindromic subsequence in the entire string. + +### Solution + +#### Java Solution + +```java +class Solution { + public int longestPalindromeSubseq(String s) { + int n = s.length(); + int[][] dp = new int[n][n]; + + for (int i = n - 1; i >= 0; i--) { + dp[i][i] = 1; + for (int j = i + 1; j < n; j++) { + if (s.charAt(i) == s.charAt(j)) { + dp[i][j] = dp[i + 1][j - 1] + 2; + } else { + dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); + } + } + } + + return dp[0][n - 1]; + } +} +``` +#### C++ Solution + +```cpp +class Solution { +public: + int longestPalindromeSubseq(string s) { + int n = s.length(); + vector> dp(n, vector(n, 0)); + + for (int i = n - 1; i >= 0; i--) { + dp[i][i] = 1; + for (int j = i + 1; j < n; j++) { + if (s[i] == s[j]) { + dp[i][j] = dp[i + 1][j - 1] + 2; + } else { + dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]); + } + } + } + + return dp[0][n - 1]; + } +}; +``` +#### Python Solution + +```python +class Solution: + def longestPalindromeSubseq(self, s: str) -> int: + n = len(s) + dp = [[0] * n for _ in range(n)] + + for i in range(n - 1, -1, -1): + dp[i][i] = 1 + for j in range(i + 1, n): + if s[i] == s[j]: + dp[i][j] = dp[i + 1][j - 1] + 2 + else: + dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) + + return dp[0][n - 1] +``` +### Complexity Analysis +**Time Complexity:** O(n^2) +>Reason: We are filling an n x n table, and each cell takes constant time to compute. + +**Space Complexity:** O(n^2) +>Reason: We use a 2D array dp of size n x n to store the intermediate results. + +### References +**LeetCode Problem:** Longest Palindromic Subsequence \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0518-Coin-Change-II.md b/solutions/lc-solutions/0500-0599/0518-Coin-Change-II.md new file mode 100644 index 0000000..df0380b --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0518-Coin-Change-II.md @@ -0,0 +1,123 @@ +--- +id: coin-change-2 +title: Coin Change 2 +sidebar_label: 0518-Coin-Change-2 +tags: +- Dynamic Programming +- Array +description: "You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the number of combinations that make up that amount." +--- + +## Problem + +You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return `0`. + +### Examples + +**Example 1:** + +**Input:** `amount = 5, coins = [1, 2, 5]` +**Output:** `4` +**Explanation:** There are four ways to make up the amount: +1. 5 = 5 +2. 5 = 2 + 2 + 1 +3. 5 = 2 + 1 + 1 + 1 +4. 5 = 1 + 1 + 1 + 1 + 1 + +**Example 2:** + +**Input:** `amount = 3, coins = [2]` +**Output:** `0` +**Explanation:** The amount of 3 cannot be made up just with coins of 2. + +**Example 3:** + +**Input:** `amount = 10, coins = [10]` +**Output:** `1` + +### Constraints + +- `1 <= coins.length <= 300` +- `1 <= coins[i] <= 5000` +- All the values of `coins` are unique. +- `0 <= amount <= 5000` + +--- + +## Approach + +To solve this problem, we can use dynamic programming. We will create a 1D array `dp` where `dp[i]` represents the number of ways to make the amount `i` using the given coins. + +### Steps: + +1. Initialize a 1D array `dp` of size `amount + 1` with all elements set to `0`. +2. Set `dp[0] = 1` because there is one way to make the amount `0`, which is to use no coins. +3. For each coin in the `coins` array: + - Update the `dp` array from the current coin's value up to the `amount`. + - For each amount `i` from the coin's value to `amount`, add the number of ways to make the amount `i - coin` to `dp[i]`. +4. The value `dp[amount]` will be the result. + +### Solution + +#### Java + +```java +class Solution { + public int change(int amount, int[] coins) { + int[] dp = new int[amount + 1]; + dp[0] = 1; + + for (int coin : coins) { + for (int i = coin; i <= amount; i++) { + dp[i] += dp[i - coin]; + } + } + + return dp[amount]; + } +} +``` +#### C++ +```cpp +#include +using namespace std; + +class Solution { +public: + int change(int amount, vector& coins) { + vector dp(amount + 1, 0); + dp[0] = 1; + + for (int coin : coins) { + for (int i = coin; i <= amount; i++) { + dp[i] += dp[i - coin]; + } + } + + return dp[amount]; + } +}; +``` +#### Python + +```python +class Solution: + def change(self, amount: int, coins: List[int]) -> int: + dp = [0] * (amount + 1) + dp[0] = 1 + + for coin in coins: + for i in range(coin, amount + 1): + dp[i] += dp[i - coin] + + return dp[amount] +``` +### Complexity Analysis +**Time Complexity:** O(n * amount) +>Reason: The nested loops iterate over the coins array and the amount, leading to a time complexity of O(n * amount), where n is the number of coins. + +**Space Complexity:** O(amount) +>Reason: The space complexity is O(amount) due to the 1D dp array used to store the number of combinations for each amount. + +### References +**LeetCode Problem:** Coin Change 2 \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0520-Detect-Capital.md b/solutions/lc-solutions/0500-0599/0520-Detect-Capital.md new file mode 100644 index 0000000..b8cf56a --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0520-Detect-Capital.md @@ -0,0 +1,133 @@ +--- +id: Detect-Capital +title: Detect Capital +sidebar_label: Detect Capital +tags: + - String + - Validation + - Easy +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Detect-Capital](https://leetcode.com/problems/Detect-Capital/description/) | [Detect-Capital Solution on LeetCode](https://leetcode.com/problems/Detect-Capital/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +We define the usage of capitals in a word to be right when one of the following cases holds: +1. All letters in this word are capitals, like "USA". +2. All letters in this word are not capitals, like "leetcode". +3. Only the first letter in this word is capital, like "Google". + +Given a string `word`, return `true` if the usage of capitals in it is right. + +### Examples + +#### Example 1: +- **Input:** `word = "USA"` +- **Output:** `true` + +#### Example 2: +- **Input:** `word = "FlaG"` +- **Output:** `false` + +### Constraints + +- `1 <= word.length <= 100` +- `word` consists of lowercase and uppercase English letters. + +## Approach + +To solve this problem, we can use straightforward checks to verify if the word meets any of the three defined conditions for the correct usage of capitals. + +1. **Check if all letters are capitals:** Use the `isupper()` method. +2. **Check if all letters are not capitals:** Use the `islower()` method. +3. **Check if only the first letter is capital:** Use slicing and the `isupper()` method for the first character and the `islower()` method for the rest. + +If any of these conditions are satisfied, return `true`; otherwise, return `false`. + +## Step-by-Step Algorithm + +1. If the entire word is uppercase, return `true`. +2. If the entire word is lowercase, return `true`. +3. If only the first character is uppercase and the rest are lowercase, return `true`. +4. Otherwise, return `false`. + +## Solution + +### Python +```python +def detectCapitalUse(word: str) -> bool: + if word.isupper() or word.islower() or (word[0].isupper() and word[1:].islower()): + return True + return False +``` + +### Java +```java +public class DetectCapital { + public boolean detectCapitalUse(String word) { + if (word.equals(word.toUpperCase()) || + word.equals(word.toLowerCase()) || + (Character.isUpperCase(word.charAt(0)) && word.substring(1).equals(word.substring(1).toLowerCase()))) { + return true; + } + return false; + } +} +``` + +### C++ +```cpp +class Solution { +public: + bool detectCapitalUse(string word) { + if (all_of(word.begin(), word.end(), ::isupper) || + all_of(word.begin(), word.end(), ::islower) || + (isupper(word[0]) && all_of(word.begin() + 1, word.end(), ::islower))) { + return true; + } + return false; + } +}; +``` + +### C +```c +#include +#include +#include + +bool detectCapitalUse(char* word) { + int len = strlen(word); + bool isAllUpper = true, isAllLower = true, isCapitalized = true; + + if (!isupper(word[0])) isCapitalized = false; + + for (int i = 0; i < len; ++i) { + if (!isupper(word[i])) isAllUpper = false; + if (!islower(word[i])) isAllLower = false; + if (i > 0 && !islower(word[i])) isCapitalized = false; + } + + return isAllUpper || isAllLower || isCapitalized; +} +``` + +### JavaScript +```javascript +function detectCapitalUse(word) { + if (word === word.toUpperCase() || + word === word.toLowerCase() || + (word[0] === word[0].toUpperCase() && word.slice(1) === word.slice(1).toLowerCase())) { + return true; + } + return false; +} +``` + +## Conclusion + +The given problem can be efficiently solved by checking for three specific conditions of capitalization. The solutions provided in Python, Java, C++, C, and JavaScript utilize string methods to determine if the word meets the criteria for correct usage of capitals. Each approach ensures that the solution is both concise and readable, with a time complexity of O(n), where n is the length of the word. \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0522-Longest-Uncommon-Subsequence-II.md b/solutions/lc-solutions/0500-0599/0522-Longest-Uncommon-Subsequence-II.md new file mode 100644 index 0000000..7093081 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0522-Longest-Uncommon-Subsequence-II.md @@ -0,0 +1,163 @@ +--- +id: longest-uncommon-subsequence-ii +title: Longest Uncommon Subsequence II +sidebar_label: 0522-Longest-Uncommon-Subsequence-II +tags: +- String +- Sorting +description: "Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1." +--- + +## Problem + +Given an array of strings `strs`, return the length of the longest uncommon subsequence between them. An uncommon subsequence is a subsequence that is not common to any other string in the array. + +A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`. + +### Examples + +**Example 1:** + +**Input:** `strs = ["aba","cdc","eae"]` +**Output:** `3` + +**Example 2:** + +**Input:** `strs = ["aaa","aaa","aa"]` +**Output:** `-1` + +### Constraints + +- `2 <= strs.length <= 50` +- `1 <= strs[i].length <= 10` +- `strs[i]` consists of lowercase English letters. + +--- + +## Approach + +To find the longest uncommon subsequence, we need to consider the following: + +1. If a string is unique in the list (i.e., it does not appear more than once), we need to check if it is not a subsequence of any other string. +2. If a string is not unique (i.e., it appears more than once), it cannot be an uncommon subsequence. +3. We can start by checking the strings in descending order of their lengths. This way, we can return the first string that meets the criteria as soon as we find it. + +### Steps: + +1. Sort the strings by length in descending order. +2. Check each string: + - If the string appears only once in the list. + - If it is not a subsequence of any other string longer than it. +3. If such a string is found, return its length. +4. If no such string is found, return `-1`. + +### Helper Function + +A helper function `is_subsequence` can be used to determine if one string is a subsequence of another. + +### Solution + +#### Java Solution + +```java +import java.util.*; + +class Solution { + public int findLUSlength(String[] strs) { + Arrays.sort(strs, (a, b) -> b.length() - a.length()); + for (int i = 0; i < strs.length; i++) { + boolean isSubsequence = false; + for (int j = 0; j < strs.length; j++) { + if (i != j && isSubsequence(strs[i], strs[j])) { + isSubsequence = true; + break; + } + } + if (!isSubsequence) { + return strs[i].length(); + } + } + return -1; + } + + private boolean isSubsequence(String a, String b) { + int i = 0, j = 0; + while (i < a.length() && j < b.length()) { + if (a.charAt(i) == b.charAt(j)) { + i++; + } + j++; + } + return i == a.length(); + } +} +``` +#### C++ Solution + +```cpp +#include +#include +#include +using namespace std; + +class Solution { +public: + int findLUSlength(vector& strs) { + sort(strs.begin(), strs.end(), [](const string &a, const string &b) { + return b.size() < a.size(); + }); + + for (int i = 0; i < strs.size(); i++) { + bool isSubsequence = false; + for (int j = 0; j < strs.size(); j++) { + if (i != j && isSubsequence(strs[i], strs[j])) { + isSubsequence = true; + break; + } + } + if (!isSubsequence) { + return strs[i].size(); + } + } + return -1; + } + +private: + bool isSubsequence(const string &a, const string &b) { + int i = 0, j = 0; + while (i < a.size() && j < b.size()) { + if (a[i] == b[j]) { + i++; + } + j++; + } + return i == a.size(); + } +}; +``` +#### Python Solution + +```python +class Solution: + def findLUSlength(self, strs: List[str]) -> int: + strs.sort(key=len, reverse=True) + + def is_subsequence(a, b): + it = iter(b) + return all(c in it for c in a) + + for i, s in enumerate(strs): + if all(not is_subsequence(s, strs[j]) for j in range(len(strs)) if i != j): + return len(s) + + return -1 +``` +### Complexity Analysis +**Time Complexity:** O(n^2 * l) +>Reason: Sorting the list takes O(n log n). Checking if a string is a subsequence of another string takes O(l) time, and this is done for each pair of strings, leading to O(n^2 * l) in total. + +**Space Complexity:** O(1) +>Reason: The space complexity is constant as we are not using any extra space proportional to the input size, other than the space required for sorting. + +### References +LeetCode Problem: Longest Uncommon Subsequence II \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0523-continuous-subarray-sum.md b/solutions/lc-solutions/0500-0599/0523-continuous-subarray-sum.md new file mode 100644 index 0000000..cc59105 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0523-continuous-subarray-sum.md @@ -0,0 +1,211 @@ +--- +id: continuous-subarray-sum +title: continuous-subarray-sum +sidebar_label: 0523 continuous subarray sum +tags: + - prefix sum + hashmap + - LeetCode + - Java + - Python + - C++ +description: This is a solution to the Continuous Subarray Sum problem on LeetCode +--- + +## Problem Description + +Given an integer array `nums` and an integer `k` return `true` if `nums` has a good subarray or `false` otherwise A good subarray is a subarray where + +- Its length is at least two and +- The sum of the elements of the subarray is a multiple of `k` + +Note that: +- A subarray is a contiguous part of the array +- An integer `x` is a multiple of `k` if there exists an integer `n` such that `$x = n * k$` 0 is always a multiple of `k` + +### Examples + +**Example 1:** + + + +## Problem Description + +Given an integer array nums and an integer k return true if nums has a good subarray or false otherwise +A good subarray is a subarray where: + + - its length is at least two and + - the sum of the elements of the subarray is a multiple of k +Note that: + - A subarray is a contiguous part of the array + - An integer x is a multiple of k if there exists an integer n such that $x = n * k$ 0 is always a multiple of k + +### Examples + +**Example 1:** + +``` + +Input: nums : [23,2,4,6,7], k : 6 +Output: true +Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6 + +``` + +**Example 2:** + + +``` +Input: root : nums : [23,2,6,4,7], k : 6 +Output: true +Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42 +42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer +``` + +**Example 3:** + + +``` +Input: nums : [23,2,6,4,7], k : 13 +Output: false +``` + + +### Constraints + +- $1 \leq \text{nums.length} \leq 105$ + + +--- + +## Solution for Continuous Subarray Sum Problem + +### Intuition +This is a prefix sum's problem Due to LC + + A good subarray is a subarray where: + its length is at least two and + the sum of the elements of the subarray is a multiple of k + +modulo k there are 0,1,...k-1 totally k possible for prefix sum (mod k) +For this constraint $1 \leq \text{nums.length} \leq 105$ an $O(n^2)$ solution may lead to TLE + + +A hash map with care on prefix sum mod k to use is however a tip The array version is used when `k>` instead of an array which is accepted by LC + - Since the computation uses `mod_k[prefix].front()`, a simple hash table `unordered_map mod_k`is sufficient for this need + - An acceptable version using array version when $k + + + + ```python +//python + + class Solution: + def checkSubarraySum(self, nums: List[int], k: int) -> bool: + n=len(nums) + if n<2: return False + mod_k={} + prefix=0 + mod_k[0]=-1 + for i, x in enumerate(nums): + prefix+=x + prefix%=k + if prefix in mod_k: + if i>mod_k[prefix]+1: + return True + else: + mod_k[prefix]=i + return False +``` + + + + + ```java +//java + + class Solution { + public boolean checkSubarraySum(int[] nums, int k) { + int n = nums.length, prefSum = 0; + Map firstOcc = new HashMap<>(); + firstOcc.put(0, 0); + + for (int i = 0; i < n; i++) { + prefSum = (prefSum + nums[i]) % k; + if (firstOcc.containsKey(prefSum)) { + if (i + 1 - firstOcc.get(prefSum) >= 2) { + return true; + } + } else { + firstOcc.put(prefSum, i + 1); + } + } + + return false; + } +} + +``` + + + + + ```cpp +//cpp + + class Solution { +public: + bool checkSubarraySum(vector& nums, int k) { + map mp ; + mp[0] = 0 ; + int sum = 0 ; + for(int i = 0 ; i< nums.size() ; i++ ) { + sum += nums[i] ; + int rem = sum%k ; + + if(mp.find(rem)==mp.end()){ + mp[rem] = i+1 ; + + }else if (mp[rem] < i ) { + return true ; + + } + + + } + return false ; + + } +}; + +``` + + +
+ + + + + +## References + +- **LeetCode Problem:** [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/) +- **Solution Link:** [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/submissions/1281964300/) +- **Authors GeeksforGeeks Profile:** [parikhit kurmi](https://www.geeksforgeeks.org/user/sololeveler673/) +- **Authors Leetcode:** [parikhit kurmi](https://leetcode.com/u/parikhitkurmi14/) \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0524-longest-word-in-dictionary-though-deleting.md b/solutions/lc-solutions/0500-0599/0524-longest-word-in-dictionary-though-deleting.md new file mode 100644 index 0000000..c4a63df --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0524-longest-word-in-dictionary-though-deleting.md @@ -0,0 +1,146 @@ +--- +id: longest-word-in-dictionary-through-deleting +title: Longest Word in Dictionary through Deleting +sidebar_label: 0524-longest-word-in-dictionary-through-deleting +tags: + - Array + - Two Pointers + - String + - Sorting + - Java + - Python + - C++ +description: This is a solution to the longest word in dictionary through deleting problem on LeetCode. +--- + +## Problem Description + +Given a string `s` and a string array `dictionary`, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string. + +### Examples + +**Example 1:** +Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"] +Output: "apple" + +**Example 2** +Input: s = "abpcplea", dictionary = ["a","b","c"] +Output: "a" + +### Constraints + +- `1 <= s.length <= 1000` +- `1 <= dictionary.length <= 1000` +- `1 <= dictionary[i].length <= 1000` +- `s` and `dictionary[i]` consist of lowercase English letters. + +## Solution + +### Intuition + +The intuition behind the solution is to use a two-pointer approach that can efficiently validate whether a word from the dictionary is a subsequence of the string s. Here's how we proceed: + +- Initialize two pointers, i for the index in the string s and j for the index in the current dictionary word. +- Increment i each time we examine a character in s. +- Increment j only when the characters at i in s and j in the dictionary word match. + A dictionary word is a subsequence of s if we can traverse through the entire word (i.e., j equals the length of the word) by selectively matching characters in s. +- By iterating through each word in the dictionary and applying the two-pointer technique, we can check which words can be formed. During the process, we also keep track of the longest word that satisfies the condition. If multiple words have the same length, we choose the one with the lowest lexicographical order, which is the same as saying the smallest in alphabetical order. + +The check function implements the two-pointer technique, and the outer loop through the dictionary selects the best candidate word according to the above-mentioned criteria. + +#### Code in Different Languages + + + + +```cpp +//cpp + +class Solution { +public: +string findLongestWord(string s, vector& d) { +string ans; + + for (const string& word : d) + if (isSubsequence(word, s)) + if (word.length() > ans.length() || + word.length() == ans.length() && word.compare(ans) < 0) + ans = word; + + return ans; + +} + +private: +// Returns true if a is a subsequence of b. +bool isSubsequence(const string& a, const string& b) { +int i = 0; +for (const char c : b) +if (i < a.length() && c == a[i]) +++i; +return i == a.length(); +}; +}; + +``` + + + + +```java +//java + +class Solution { +public String findLongestWord(String s, List d) { + String ans = ""; + + for (final String word : d) + if (isSubsequence(word, s)) + if (word.length() > ans.length() || + word.length() == ans.length() && word.compareTo(ans) < 0) + ans = word; + + return ans; +} + +// Returns true if a is a subsequence of b. +private boolean isSubsequence(final String a, final String b) { + int i = 0; + for (final char c : b.toCharArray()) + if (i < a.length() && c == a.charAt(i)) + ++i; + return i == a.length(); +} +} + +``` + + + + +```python +//python + +class Solution: +def findLongestWord(self, s: str, d: List[str]) -> str: + ans = '' + + for word in d: + i = 0 + for c in s: + if i < len(word) and c == word[i]: + i += 1 + if i == len(word): + if len(word) > len(ans) or len(word) == len(ans) and word < ans: + ans = word + + return ans +``` + + + + +## References + +- **LeetCode Problem:** [Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/description/) +- **Solution Link:** [Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/solutions/) diff --git a/solutions/lc-solutions/0500-0599/0525-Contiguous-Array.md b/solutions/lc-solutions/0500-0599/0525-Contiguous-Array.md new file mode 100644 index 0000000..7782b22 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0525-Contiguous-Array.md @@ -0,0 +1,131 @@ +--- +id: contiguous-array +title: Contiguous Array +sidebar_label: 0525-Contiguous-Array +tags: +- Array +- Hash Table +description: "Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1." +--- + +## Problem + +Given a binary array `nums`, return the maximum length of a contiguous subarray with an equal number of `0` and `1`. + +### Examples + +**Example 1:** + +**Input:** `nums = [0,1]` +**Output:** `2` +**Explanation:** [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. + +**Example 2:** + +**Input:** `nums = [0,1,0]` +**Output:** `2` +**Explanation:** [0, 1] (or [1, 0]) is the longest contiguous subarray with an equal number of 0 and 1. + +### Constraints + +- `1 <= nums.length <= 10^5` +- `nums[i]` is either `0` or `1`. + +--- + +## Approach + +To solve this problem, we can use a hash map to keep track of the cumulative sum of the transformed array where `0` is replaced by `-1` and `1` is kept as `1`. The idea is to find the subarray with a cumulative sum of zero. + +### Steps: + +1. Initialize a hash map to store the cumulative sum and its corresponding index. +2. Initialize `cumulative_sum` to `0` and `max_length` to `0`. +3. Traverse the array: + - Replace `0` with `-1`. + - Update the `cumulative_sum`. + - If the `cumulative_sum` is `0`, update `max_length` to the current index + 1. + - If the `cumulative_sum` has been seen before, calculate the subarray length and update `max_length` if it's larger than the current `max_length`. + - If the `cumulative_sum` has not been seen before, store it in the hash map with the current index. +4. Return `max_length`. + +### Solution + +#### Java + +```java +import java.util.HashMap; + +class Solution { + public int findMaxLength(int[] nums) { + HashMap map = new HashMap<>(); + map.put(0, -1); + int maxLength = 0, cumulativeSum = 0; + + for (int i = 0; i < nums.length; i++) { + cumulativeSum += (nums[i] == 0) ? -1 : 1; + if (map.containsKey(cumulativeSum)) { + maxLength = Math.max(maxLength, i - map.get(cumulativeSum)); + } else { + map.put(cumulativeSum, i); + } + } + + return maxLength; + } +} +``` +#### C++ + +```cpp +#include +#include +using namespace std; + +class Solution { +public: + int findMaxLength(vector& nums) { + unordered_map map; + map[0] = -1; + int maxLength = 0, cumulativeSum = 0; + + for (int i = 0; i < nums.size(); i++) { + cumulativeSum += (nums[i] == 0) ? -1 : 1; + if (map.find(cumulativeSum) != map.end()) { + maxLength = max(maxLength, i - map[cumulativeSum]); + } else { + map[cumulativeSum] = i; + } + } + + return maxLength; + } +}; +``` +#### Python + +```python +class Solution: + def findMaxLength(self, nums: List[int]) -> int: + count_map = {0: -1} + max_length = 0 + cumulative_sum = 0 + + for i, num in enumerate(nums): + cumulative_sum += -1 if num == 0 else 1 + if cumulative_sum in count_map: + max_length = max(max_length, i - count_map[cumulative_sum]) + else: + count_map[cumulative_sum] = i + + return max_length +``` +### Complexity Analysis +**Time Complexity:** O(n) +>Reason: We traverse the array once, and each lookup or insertion operation in the hash map is O(1) on average. + +**Space Complexity:** O(n) +>Reason: In the worst case, we may store up to n entries in the hash map. + +### References +**LeetCode Problem:** Contiguous Array \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0526-Beautiful-Arrangement.md b/solutions/lc-solutions/0500-0599/0526-Beautiful-Arrangement.md new file mode 100644 index 0000000..2899fcc --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0526-Beautiful-Arrangement.md @@ -0,0 +1,136 @@ +--- +id: beautiful-arrangement +title: Beautiful Arrangement +sidebar_label: 0526-Beautiful-Arrangement +tags: +- Array +- Dynamic Programming +- Bit Manipulation +- Backtracking +description: solution to the leetcode problem beautiful arrrangement. +--- + +## Problem + +Suppose you have `n` integers labeled `1` through `n`. A permutation of those `n` integers `perm` (1-indexed) is considered a beautiful arrangement if for every `i` (`1 <= i <= n`), either of the following is true: + +- `perm[i]` is divisible by `i`. +- `i` is divisible by `perm[i]`. + +Given an integer `n`, return the number of the beautiful arrangements that you can construct. + +### Examples + +**Example 1:** + +Input: `n = 2` +Output: `2` +Explanation: +The first beautiful arrangement is `[1,2]`: +- `perm[1] = 1` is divisible by `i = 1` +- `perm[2] = 2` is divisible by `i = 2` + +The second beautiful arrangement is `[2,1]`: +- `perm[1] = 2` is divisible by `i = 1` +- `i = 2` is divisible by `perm[2] = 1` + +**Example 2:** + +Input: `n = 1` +Output: `1` + +### Constraints: + +- $1 <= n <= 15$ +--- + +## Solution + +```cpp +class Solution { +public: + void solve(vector& nums, int n, int& ans, int cur_num){ + // base case + if (cur_num >= n + 1) { + ans++; + return; + } + + // recursive relation + for (int j = 1; j <= n; j++) { + if (nums[j] == 0 && (cur_num % j == 0 || j % cur_num == 0)) { + nums[j] = cur_num; + solve(nums, n, ans, cur_num + 1); + // backtracking + nums[j] = 0; + } + } + } + + int countArrangement(int n) { + vector nums(n + 1); + int ans = 0, ind = 1; + solve(nums, n, ans, ind); + return ans; + } +}; +``` + +```java +class Solution { + public void solve(int[] nums, int n, int[] ans, int curNum) { + // base case + if (curNum >= n + 1) { + ans[0]++; + return; + } + + // recursive relation + for (int j = 1; j <= n; j++) { + if (nums[j] == 0 && (curNum % j == 0 || j % curNum == 0)) { + nums[j] = curNum; + solve(nums, n, ans, curNum + 1); + // backtracking + nums[j] = 0; + } + } + } + + public int countArrangement(int n) { + int[] nums = new int[n + 1]; + int[] ans = new int[1]; + int ind = 1; + solve(nums, n, ans, ind); + return ans[0]; + } +} +``` + +```python +class Solution: + def solve(self, nums, n, ans, cur_num): + # base case + if cur_num >= n + 1: + ans[0] += 1 + return + + # recursive relation + for j in range(1, n + 1): + if nums[j] == 0 and (cur_num % j == 0 or j % cur_num == 0): + nums[j] = cur_num + self.solve(nums, n, ans, cur_num + 1) + # backtracking + nums[j] = 0 + + def countArrangement(self, n): + nums = [0] * (n + 1) + ans = [0] + cur_num = 1 + self.solve(nums, n, ans, cur_num) + return ans[0] +``` + +### Complexity Analysis + +- **Time Complexity:** $O(N!)$ +- **Space Complexity:** $O(N)$ diff --git a/solutions/lc-solutions/0500-0599/0527-Word-Abbreviation.md b/solutions/lc-solutions/0500-0599/0527-Word-Abbreviation.md new file mode 100644 index 0000000..1353046 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0527-Word-Abbreviation.md @@ -0,0 +1,188 @@ +--- +id: word-abbreviation +title: Word Abbreviation +sidebar_label: 0527-Word-Abbreviation +tags: +- Array +- String +- Prefix +description: solution to the leetcode problem Word Abbreviation. +--- + +## Problem + +Given an array of n distinct non-empty strings, you need to generate the minimal possible abbreviations for every word following the rules below: + +Begin with the first character and then the number of characters abbreviated, followed by the last character. +If there are any conflicts (i.e., more than one word shares the same abbreviation), a longer prefix is used instead of only the first character until the mapping from word to abbreviation becomes unique. In other words, a final abbreviation cannot map to more than one original word. +If the abbreviation doesn't make the word shorter, then keep it as the original word. + +### Examples + +**Example 1:** + +**Input:** + +```plaintext +words = ["like", "god", "internal", "me", "internet", "interval", "intension", "face", "intrusion"] +``` + +**Output:** + +```plaintext +["l2e", "god", "internal", "me", "i6t", "interval", "inte4n", "f2e", "intr4n"] +``` + +**Example 2:** + +**Input:** + +```plaintext +words = ["aa", "aaa"] +``` + +**Output:** + +```plaintext +["aa", "aaa"] +``` + +### Constraints + +- $1 <= words.length <= 400$ +- $2 <= words[i].length <= 400$ +- words[i] consists of lowercase English letters. +- All strings in `words` are unique. + +## Solution + +### Cpp + +```cpp +class Solution { +public: + vector wordsAbbreviation(vector& words) { + int n = words.size(); + vector result(n); + vector prefix(n, 1); + + for (int i = 0; i < n; ++i) { + result[i] = abbreviate(words[i], 1); + } + + for (int i = 0; i < n; ++i) { + while (true) { + unordered_set duplicates; + for (int j = i + 1; j < n; ++j) { + if (result[i] == result[j]) { + duplicates.insert(j); + } + } + if (duplicates.empty()) break; + + duplicates.insert(i); + for (int idx : duplicates) { + result[idx] = abbreviate(words[idx], ++prefix[idx]); + } + } + } + + return result; + } + +private: + string abbreviate(const string& word, int k) { + if (k >= word.length() - 2) { + return word; + } + return word.substr(0, k) + to_string(word.length() - 1 - k) + word.back(); + } +}; +``` + +### Java + +```java +import java.util.*; + +class Solution { + public List wordsAbbreviation(List words) { + int n = words.size(); + String[] result = new String[n]; + int[] prefix = new int[n]; + + for (int i = 0; i < n; ++i) { + result[i] = abbreviate(words.get(i), 1); + } + + for (int i = 0; i < n; ++i) { + while (true) { + Set duplicates = new HashSet<>(); + for (int j = i + 1; j < n; ++j) { + if (result[i].equals(result[j])) { + duplicates.add(j); + } + } + if (duplicates.isEmpty()) break; + + duplicates.add(i); + for (int idx : duplicates) { + result[idx] = abbreviate(words.get(idx), ++prefix[idx]); + } + } + } + + return Arrays.asList(result); + } + + private String abbreviate(String word, int k) { + if (k >= word.length() - 2) { + return word; + } + return word.substring(0, k) + (word.length() - 1 - k) + word.charAt(word.length() - 1); + } +} +``` +### Python + +```python +class Solution: + def wordsAbbreviation(self, words: List[str]) -> List[str]: + n = len(words) + result = ["" for _ in range(n)] + prefix = [1] * n + + for i in range(n): + result[i] = self.abbreviate(words[i], 1) + + for i in range(n): + while True: + duplicates = set() + for j in range(i + 1, n): + if result[i] == result[j]: + duplicates.add(j) + if not duplicates: + break + + duplicates.add(i) + for idx in duplicates: + prefix[idx] += 1 + result[idx] = self.abbreviate(words[idx], prefix[idx]) + + return result + + def abbreviate(self, word: str, k: int) -> str: + if k >= len(word) - 2: + return word + return word[:k] + str(len(word) - 1 - k) + word[-1] +``` + +### Complexity Analysis + +- **Time Complexity:** $O(N!)$ + - $N$ is the number of distinct integers or elements in the problem context. + - **Explanation:** The time complexity is factorial because it involves generating permutations of $N$ elements, which is $N!$. + +- **Space Complexity:** $O(N)$ + - $N$ represents the space required for variables or data structures that scale linearly with $N$. + - **Explanation:** The space complexity is linear because it typically involves storing variables or data structures proportional to $N$ in size. diff --git a/solutions/lc-solutions/0500-0599/0528-Random-Pick-with-Weight.md b/solutions/lc-solutions/0500-0599/0528-Random-Pick-with-Weight.md new file mode 100644 index 0000000..aa2e2f6 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0528-Random-Pick-with-Weight.md @@ -0,0 +1,153 @@ +--- +id: random-pick-with-weight +title: Random Pick With Weight +sidebar_label: 0528-Random-Pick-with-Weight +tags: +- Array +- Math +- Binary Search +- Prefix Sum +description: solution to the leetcode problem Random Pick With Weight. +--- + +## Problem + +You are given a 0-indexed array of positive integers `w` where `w[i]` describes the weight of the `i`th index. + +You need to implement the function `pickIndex()`, which randomly picks an index in the range `[0, w.length - 1]` (inclusive) and returns it. The probability of picking an index `i` is `w[i] / sum(w)`. + +For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., 25%), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., 75%). + +Sure, here is the markdown with input, output, and explanation all in one go: + +### Examples + +**Example 1:** + +Input: +``` +["Solution","pickIndex"] +[[[1]],[]] +``` +Output: +``` +[null,0] +``` +Explanation: +``` +Solution solution = new Solution([1]); +solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. +``` + +**Example 2:** + +Input: +``` +["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"] +[[[1,3]],[],[],[],[],[]] +``` +Output: +``` +[null,1,1,1,1,0] +``` +Explanation: +``` +Solution solution = new Solution([1, 3]); +solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. +solution.pickIndex(); // return 1 +solution.pickIndex(); // return 1 +solution.pickIndex(); // return 1 +solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. +``` + +Since this is a randomization problem, multiple answers are allowed. +All of the following outputs can be considered correct: +``` +[null,1,1,1,1,0] +[null,1,1,1,1,1] +[null,1,1,1,0,0] +[null,1,1,1,0,1] +[null,1,0,1,0,0] +...... +``` +and so on. + +### Constraints + +- $1 <= w.length <= 10^4$ +- $1 <= w[i] <= 10^5$ +- `pickIndex` will be called at most `10^4` times. +``` + + +## Solution + +```cpp +class Solution { + public: + Solution(vector& w) { + int last = 0; + for (auto const& len : w) { + range.push_back({last, last + len}); + last += len; + } + srand(time(nullptr)); + } + + int pickIndex() { + int logical_index = std::rand() % range.back().second; + int lo = 0, hi = range.size() - 1; + while (lo <= hi) { + int mid = (lo + hi)/2; + + if (logical_index >= range[mid].first && logical_index < range[mid].second) { + return mid; + } else if (logical_index < range[mid].first) { + hi = mid - 1; + } else { + lo = mid + 1; + } + } + return -1; + } + private: + vector> range; +}; +``` + +```java +class Solution { + + Random random; + int[] wSums; + + public Solution(int[] w) { + this.random = new Random(); + for(int i=1; i 0: + board[row][col] = str(num_mines) + else: + board[row][col] = 'B' + for dr, dc in directions: + dfs(row + dr, col + dc) + + click_r, click_c = click + if board[click_r][click_c] == 'M': + board[click_r][click_c] = 'X' + else: + dfs(click_r, click_c) + return board +``` + +## Solution in Java + +```java +class Solution { + int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}}; + + public char[][] updateBoard(char[][] board, int[] click) { + int m = board.length, n = board[0].length; + int row = click[0], col = click[1]; + + if (board[row][col] == 'M') { + board[row][col] = 'X'; + } else { + dfs(board, row, col); + } + + return board; + } + + private void dfs(char[][] board, int row, int col) { + int m = board.length, n = board[0].length; + if (row < 0 || row >= m || col < 0 || col >= n || board[row][col] != 'E') return; + + int mines = countAdjacentMines(board, row, col); + if (mines > 0) { + board[row][col] = (char) (mines + '0'); + } else { + board[row][col] = 'B'; + for (int[] dir : dirs) { + dfs(board, row + dir[0], col + dir[1]); + } + } + } + + private int countAdjacentMines(char[][] board, int row, int col) { + int m = board.length, n = board[0].length; + int count = 0; + for (int[] dir : dirs) { + int r = row + dir[0]; + int c = col + dir[1]; + if (r >= 0 && r < m && c >= 0 && c < n && board[r][c] == 'M') { + count++; + } + } + return count; + } +} +``` + +## Solution in C++ + +```cpp +class Solution { +public: + vector> updateBoard(vector>& board, vector& click) { + int m = board.size(), n = board[0].size(); + vector> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}}; + + function countAdjacentMines = [&](int row, int col) { + int count = 0; + for (auto& dir : directions) { + int nr = row + dir[0], nc = col + dir[1]; + if (nr >= 0 && nr < m && nc >= 0 && nc < n && board[nr][nc] == 'M') { + count++; + } + } + return count; + }; + + function dfs = [&](int row, int col) { + if (row < 0 || row >= m || col < 0 || col >= n || board[row][col] != 'E') return; + + int numMines = countAdjacentMines(row, col); + if (numMines > 0) { + board[row][col] = '0' + numMines; + } else { + board[row][col] = 'B'; + for (auto& dir : directions) { + dfs(row + dir[0], col + dir[1]); + } + } + }; + + int click_r = click[0], click_c = click[1]; + if (board[click_r][click_c] == 'M') { + board[click_r][click_c] = 'X'; + } else { + dfs(click_r, click_c); + } + + return board; + } +}; +``` + +## Solution in JavaScript + +```javascript +var updateBoard = function(board, click) { + const m = board.length, n = board[0].length; + const directions = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [-1, 1], [1, -1], [1, 1]]; + + function countAdjacentMines(row, col) { + let count = 0; + for (const [dr, dc] of directions) { + const nr = row + dr, nc = col + dc; + if (nr >= 0 && nr < m && nc >= 0 && nc < n && board[nr][nc] === 'M') { + count++; + } + } + return count; + } + + function dfs(row, col) { + if (row < 0 || row >= m || col < 0 || col >= n || board[row][col] !== 'E') return; + + const numMines = countAdjacentMines(row, col); + if (numMines > 0) { + board[row][col] = numMines.toString(); + } else { + board[row][col] = 'B'; + for (const [dr, dc] of directions) { + dfs(row + dr, col + dc); + } + } + } + + const [click_r, click_c] = click; + if (board[click_r][click_c] === 'M') { + board[click_r][click_c] = 'X'; + } else { + dfs(click_r, click_c); + } + + return board; +}; +``` + +## Step-by-Step Algorithm + +1. **Initialize Directions**: Define the eight possible directions (including diagonals) for exploring adjacent cells. +2. **Count Adjacent Mines**: Implement a function to count adjacent mines for a given cell. +3. **DFS or BFS**: Use DFS (Depth- + +First Search) or BFS (Breadth-First Search) to reveal cells based on the rules of the Minesweeper game. +4. **Edge Cases**: Handle edge cases like clicking on a mine ('M') which ends the game, or revealing adjacent cells recursively until no more can be revealed. + +## Conclusion + +This solution effectively simulates the Minesweeper game mechanics using recursion (DFS) or iteration (BFS) to reveal cells and update the game board accordingly. By following the rules provided and implementing efficient traversal methods, the solution ensures that all valid scenarios are covered, including game over conditions and successful completion of the game board reveal. diff --git a/solutions/lc-solutions/0500-0599/0530-bst-min-absolute-difference.md b/solutions/lc-solutions/0500-0599/0530-bst-min-absolute-difference.md new file mode 100644 index 0000000..e12e38e --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0530-bst-min-absolute-difference.md @@ -0,0 +1,232 @@ +--- +id: bst-min-absolute-difference +title: Minimum Absolute Difference in BST +sidebar_label: BST Minimum Absolute Difference +tags: + - Binary Search Tree + - Algorithms + - Trees +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Minimum Absolute Difference in BST](https://leetcode.com/problems/Minimum Absolute Difference in BST/description/) | [Minimum Absolute Difference in BST Solution on LeetCode](https://leetcode.com/problems/Minimum Absolute Difference in BST/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree. + +### Example 1: + +**Input:** `root = [4,2,6,1,3]` +**Output:** `1` + +### Example 2: + +**Input:** `root = [1,0,48,null,null,12,49]` +**Output:** `1` + +### Constraints: + +- `The number of nodes in the tree is in the range [2, 10^4].` +- `0 <= Node.val <= 10^5` + +## Approach + +1. Perform an in-order traversal of the BST. This traversal method will give us the node values in a sorted order. +2. Iterate through the sorted node values and find the minimum absolute difference between any two consecutive nodes. + +## Step-by-Step Algorithm + +1. Initialize a variable to store the previous node value (prev) and set it to None. +2. Initialize a variable to store the minimum difference (min_diff) and set it to infinity. +3. Define a helper function for in-order traversal: + - If the current node is None, return. + - Recursively call the helper function on the left subtree. + - If prev is not None, update min_diff with the minimum value between min_diff and the difference between the current node's value and prev. + - Update prev to the current node's value. + - Recursively call the helper function on the right subtree. +4. Call the helper function starting from the root. +5. Return the value of min_diff. + +## Solution + +### Python + +```python +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def getMinimumDifference(self, root: TreeNode) -> int: + self.prev = None + self.min_diff = float('inf') + + def in_order_traversal(node): + if not node: + return + + in_order_traversal(node.left) + + if self.prev is not None: + self.min_diff = min(self.min_diff, node.val - self.prev) + + self.prev = node.val + + in_order_traversal(node.right) + + in_order_traversal(root) + return self.min_diff +``` + +### Java + +```java +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +class Solution { + Integer prev = null; + int minDiff = Integer.MAX_VALUE; + + public int getMinimumDifference(TreeNode root) { + inOrderTraversal(root); + return minDiff; + } + + private void inOrderTraversal(TreeNode node) { + if (node == null) { + return; + } + + inOrderTraversal(node.left); + + if (prev != null) { + minDiff = Math.min(minDiff, node.val - prev); + } + prev = node.val; + + inOrderTraversal(node.right); + } +} +``` + +### C++ + +```cpp +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} +}; + +class Solution { +public: + int getMinimumDifference(TreeNode* root) { + int min_diff = INT_MAX; + TreeNode* prev = nullptr; + inOrderTraversal(root, prev, min_diff); + return min_diff; + } + +private: + void inOrderTraversal(TreeNode* node, TreeNode*& prev, int& min_diff) { + if (node == nullptr) { + return; + } + + inOrderTraversal(node->left, prev, min_diff); + + if (prev != nullptr) { + min_diff = std::min(min_diff, node->val - prev->val); + } + prev = node; + + inOrderTraversal(node->right, prev, min_diff); + } +}; +``` + +### C + +```c +#include +#include + +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; + +void inOrderTraversal(struct TreeNode* node, struct TreeNode** prev, int* min_diff) { + if (node == NULL) { + return; + } + + inOrderTraversal(node->left, prev, min_diff); + + if (*prev != NULL) { + *min_diff = (*min_diff < (node->val - (*prev)->val)) ? *min_diff : (node->val - (*prev)->val); + } + *prev = node; + + inOrderTraversal(node->right, prev, min_diff); +} + +int getMinimumDifference(struct TreeNode* root) { + int min_diff = INT_MAX; + struct TreeNode* prev = NULL; + inOrderTraversal(root, &prev, &min_diff); + return min_diff; +} +``` + +### JavaScript + +```javascript +class TreeNode { + constructor(val = 0, left = null, right = null) { + this.val = val; + this.left = left; + this.right = right; + } +} + +var getMinimumDifference = function(root) { + let prev = null; + let minDiff = Infinity; + + const inOrderTraversal = (node) => { + if (node === null) { + return; + } + + inOrderTraversal(node.left); + + if (prev !== null) { + minDiff = Math.min(minDiff, node.val - prev); + } + prev = node.val; + + inOrderTraversal(node.right); + }; + + inOrderTraversal(root); + return minDiff; +}; +``` + +## Conclusion + +The in-order traversal approach efficiently finds the minimum absolute difference between any two different nodes in a BST. The traversal ensures that node values are processed in a sorted order, allowing us to easily compute differences between consecutive nodes. \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0531-lonely-pixel-I.md b/solutions/lc-solutions/0500-0599/0531-lonely-pixel-I.md new file mode 100644 index 0000000..bef0f93 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0531-lonely-pixel-I.md @@ -0,0 +1,136 @@ +--- +id: Lonely-Pixel-I +title: Lonely Pixel I +sidebar_label: 0531- Lonely Pixel I +tags: + - Array + - Hash Table + - Matrix +description: "Given an m x n picture consisting of black 'B' and white 'W' pixels, return the number of black lonely pixels." +--- + +## Problem +Given an m x n picture consisting of black 'B' and white 'W' pixels, return the number of black lonely pixels. + +A black lonely pixel is a character 'B' that located at a specific position where the same row and same column don't have any other black pixels. + +### Examples + +**Example 1:** + +**Input:** `picture = "[["W","W","B"],["W","B","W"],["B","W","W"]]"` +**Output:** `3` +**Explanation:** All the three 'B's are black lonely pixels. + +**Example 2:** + +**Input:** ` picture = "[["B","B","B"],["B","B","W"],["B","B","B"]]"` +**Output:** `0` + +### Constraints +- m == picture.length +- n == picture[i].length +- `1 <= m, n <= 500` +- picture[i][j] is 'W' or 'B'. + +--- + +## Approach + +According to the problem description, we need to count the number of black pixels in each row and column, which are recorded in the arrays rows and cols respectively. Then we traverse each black pixel, check whether there is only one black pixel in its row and column. If so, we increment the answer by one. + +### Steps: + +1. Initialize two arrays, `rows` and `cols`, to count the number of 'B' pixels in each row and column, respectively. +2. Iterate through the 2D array to populate the `rows` and `cols` arrays with the count of 'B' pixels for each row and column. +3. Initialize a counter `ans` to keep track of the number of lonely pixels. +Iterate through the 2D array again. For each 'B' pixel, check if it is a lonely pixel by verifying if `rows[i]` and `cols[j]` are both equal to 1. +4. Return the count of lonely pixels. + +### Solution + +#### Java Solution + +```java +class Solution { + public int findLonelyPixel(char[][] picture) { + int m = picture.length, n = picture[0].length; + int[] rows = new int[m]; + int[] cols = new int[n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (picture[i][j] == 'B') { + ++rows[i]; + ++cols[j]; + } + } + } + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (picture[i][j] == 'B' && rows[i] == 1 && cols[j] == 1) { + ++ans; + } + } + } + return ans; + } +} +``` +#### C++ Solution + +```cpp +class Solution { +public: + int findLonelyPixel(vector>& picture) { + int m = picture.size(), n = picture[0].size(); + vector rows(m); + vector cols(n); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (picture[i][j] == 'B') { + ++rows[i]; + ++cols[j]; + } + } + } + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (picture[i][j] == 'B' && rows[i] == 1 && cols[j] == 1) { + ++ans; + } + } + } + return ans; + } +}; +``` +#### Python Solution + +```python +class Solution: + def findLonelyPixel(self, picture: List[List[str]]) -> int: + rows = [0] * len(picture) + cols = [0] * len(picture[0]) + for i, row in enumerate(picture): + for j, x in enumerate(row): + if x == "B": + rows[i] += 1 + cols[j] += 1 + ans = 0 + for i, row in enumerate(picture): + for j, x in enumerate(row): + if x == "B" and rows[i] == 1 and cols[j] == 1: + ans += 1 + return ans +``` +### Complexity Analysis +**Time Complexity:** O(m x n) +>Reason: We iterate over each element in the picture array to count the number of 'B' pixels in each row and column. + +**Space Complexity:** O(m + n) +>Reason: We use two additional arrays, `rows` and `cols`, each of size mm and nn respectively, to count the number of 'B' pixels in each row and column. + +### References +**LeetCode Problem:** Lonely Pixel I diff --git a/solutions/lc-solutions/0500-0599/0537-complex-number-multiplication.md b/solutions/lc-solutions/0500-0599/0537-complex-number-multiplication.md new file mode 100644 index 0000000..a3590ca --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0537-complex-number-multiplication.md @@ -0,0 +1,161 @@ +--- +id: complex-number-multiplication +title: Complex Number Multiplication +sidebar_label: 0537 - Complex Number Multiplication +tags: + - Math + - String + - Simulation +description: "This is a solution to the Complex Number Multiplication problem on LeetCode." +--- + +## Problem Description + +A complex number can be represented as a string on the form `"real+imaginaryi"` where: + +- `real` is the real part and is an integer in the range `[-100, 100]`. +- `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`. +- $i^2 == -1$. + +Given two complex numbers `num1` and `num2` as strings, return a string of the complex number that represents their multiplications. + + +### Examples + +**Example 1:** + + +``` +Input: num1 = "1+1i", num2 = "1+1i" +Output: "0+2i" +Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. +``` + +**Example 2:** + +``` +Input: num1 = "1+-1i", num2 = "1+-1i" +Output: "0+-2i" +Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. +``` + +### Constraints + +- `num1` and `num2` are valid complex numbers. + +## Solution for Complex Number Multiplication + +### Approach 1: +#### Algorithm + +Multiplication of two complex numbers can be done as: + +$(a+ib)Γ—(x+iy)=ax+i^2by+i(bx+ay)=axβˆ’by+i(bx+ay)$ + +We simply split up the real and the imaginary parts of the given complex strings based on the '+' and the 'i' symbols. We store the real parts of the two strings a and b as x[0] and y[0] respectively and the imaginary parts as x[1] and y[1] respectively. Then, we multiply the real and the imaginary parts as required after converting the extracted parts into integers. Then, we again form the return string in the required format and return the result. + + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +public: + std::string complexNumberMultiply(std::string num1, std::string num2) { + auto parseComplex = [](const std::string& s) -> std::pair { + std::stringstream ss(s); + std::string realPart, imagPart; + getline(ss, realPart, '+'); + getline(ss, imagPart, 'i'); + return {std::stoi(realPart), std::stoi(imagPart)}; + }; + + auto [a_real, a_img] = parseComplex(num1); + auto [b_real, b_img] = parseComplex(num2); + + int real = a_real * b_real - a_img * b_img; + int img = a_real * b_img + a_img * b_real; + + return std::to_string(real) + "+" + std::to_string(img) + "i"; + } +}; + + +``` + + + + +```java + +public class Solution { + + public String complexNumberMultiply(String a, String b) { + String x[] = a.split("\\+|i"); + String y[] = b.split("\\+|i"); + int a_real = Integer.parseInt(x[0]); + int a_img = Integer.parseInt(x[1]); + int b_real = Integer.parseInt(y[0]); + int b_img = Integer.parseInt(y[1]); + return (a_real * b_real - a_img * b_img) + "+" + (a_real * b_img + a_img * b_real) + "i"; + + } +} + +``` + + + + + +```python +class Solution: + def complexNumberMultiply(self, a: str, b: str) -> str: + def parse_complex(s: str): + real, imag = s.split('+') + imag = imag[:-1] # remove the trailing 'i' + return int(real), int(imag) + + a_real, a_img = parse_complex(a) + b_real, b_img = parse_complex(b) + + real = a_real * b_real - a_img * b_img + img = a_real * b_img + a_img * b_real + + return f"{real}+{img}i" +``` + + + +## Complexity Analysis + +### Time Complexity: $O(1)$ + +> **Reason**: Here splitting takes constant time as length of the string is very small `(<20)`. + +### Space Complexity: $O(1)$ + +> **Reason**: Constant extra space is used. + +## References + +- **LeetCode Problem**: [Complex Number Multiplication](https://leetcode.com/problems/complex-number-multiplication/description/) + +- **Solution Link**: [Complex Number Multiplication](https://leetcode.com/problems/complex-number-multiplication/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0538-Convert-BST-to-Greater-Tree.md b/solutions/lc-solutions/0500-0599/0538-Convert-BST-to-Greater-Tree.md new file mode 100644 index 0000000..f932118 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0538-Convert-BST-to-Greater-Tree.md @@ -0,0 +1,136 @@ +--- +id: convert-bst-to-greater-tree +title: Convert BST to Greater Tree +sidebar_label: 0538-Convert-BST-to-Greater-Tree +tags: +- Tree +- Depth-First Search +- Binary Search Tree +- Binary Tree +description: "Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST." +--- + +## Problem + +Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. + +### Examples + +**Example 1:** + +**Input:** `root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]` +**Output:** `[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]` + +**Example 2:** + +**Input:** `root = [0,null,1]` +**Output:** `[1,null,1]` + +### Constraints + +- The number of nodes in the tree is in the range `[0, 10^4]`. +- `-10^4 <= Node.val <= 10^4` +- All the values in the tree are unique. +- `root` is guaranteed to be a valid binary search tree. + +--- + +## Approach + +To convert a BST to a Greater Tree, we need to accumulate the sum of all nodes that are greater than the current node. This can be efficiently done using a reverse in-order traversal (right-root-left), which processes nodes from the largest to the smallest. + +### Steps: + +1. Initialize a variable to keep track of the running sum. +2. Perform a reverse in-order traversal of the tree. +3. During the traversal, update the value of each node to include the running sum. +4. Update the running sum with the value of the current node. + +### Solution + +#### Java Solution + +```java +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +class Solution { + private int sum = 0; + + public TreeNode convertBST(TreeNode root) { + if (root != null) { + convertBST(root.right); + sum += root.val; + root.val = sum; + convertBST(root.left); + } + return root; + } +} +``` +#### C++ Solution + +```cpp +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +private: + int sum = 0; +public: + TreeNode* convertBST(TreeNode* root) { + if (root != nullptr) { + convertBST(root->right); + sum += root->val; + root->val = sum; + convertBST(root->left); + } + return root; + } +}; +``` +#### Python Solution + +```python +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def convertBST(self, root: TreeNode) -> TreeNode: + self.sum = 0 + + def traverse(node): + if node: + traverse(node.right) + self.sum += node.val + node.val = self.sum + traverse(node.left) + + traverse(root) + return root +``` + +### Complexity Analysis +**Time Complexity:** O(n) +>Reason: Each node is visited once during the traversal. + +**Space Complexity:** O(h) +>Reason: The space complexity is determined by the recursion stack, which in the worst case (unbalanced tree) is O(n), but on average (balanced tree) is O(log n). + +### References +**LeetCode Problem:** Convert BST to Greater Tree \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0540-Single-Element-in-a-Sorted-Array.md b/solutions/lc-solutions/0500-0599/0540-Single-Element-in-a-Sorted-Array.md new file mode 100644 index 0000000..3decf56 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0540-Single-Element-in-a-Sorted-Array.md @@ -0,0 +1,227 @@ +--- +id: Single-Element-in-a-Sorted-Array +title: Single Element in a Sorted Array +sidebar_label: 0540-Single-Element-in-a-Sorted-Array +tags: + - Array + - Binary search + +description: "You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. + +Return the single element that appears only once." + +--- + + + +## Problem Statement + +You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. + +Return the single element that appears only once. + + +**Follow-up:** Your solution must run in O(log n) time and O(1) space. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [1,1,2,3,3,4,4,8,8] +Output: 2 +``` + +**Example 2:** + +```plaintext +Input: nums = [3,3,7,7,10,11,11] +Output: 10 +``` + +### Constraints + +- `1 <= nums.length <= 105` +- `0 <= nums[i] <= 105` + +## Solution + +We are going to use the Binary Search algorithm to optimize the approach. +We need to consider 2 different cases while using Binary Search in this problem. +Binary Search works by reducing the search space by half. +So, at first, we need to identify the halves and then eliminate them accordingly. +In addition to that, we need to check if the current element i.e. arr[mid] is the β€˜single element’. + +If we can resolve these two cases, we can easily apply Binary Search in this algorithm. + + +### Approach + +#### Algorithm + +The steps are as follows: + - If n == 1: This means the array size is 1. If the array contains only one element, we will return that element only. + - If arr[0] != arr[1]: This means the very first element of the array is the single element. So, we will return arr[0]. + - If arr[n-1] != arr[n-2]: This means the last element of the array is the single element. So, we will return arr[n-1]. + - Place the 2 pointers i.e. low and high: Initially, we will place the pointers excluding index 0 and n-1 like this: + low will point to index 1, and high will point to index n-2 i.e. the second last index. + - Calculate the β€˜mid’: Now, inside a loop, we will calculate the value of β€˜mid’ using the following formula: + mid = (low+high) // 2 ( β€˜//’ refers to integer division) + - Check if arr[mid] is the single element: + If arr[mid] != arr[mid-1] and arr[mid] != arr[mid+1]: If this condition is true for arr[mid], we can conclude arr[mid] is the single element. We will return arr[mid]. + - If (mid % 2 == 0 and arr[mid] == arr[mid+1]) + or (mid%2 == 1 and arr[mid] == arr[mid-1]): This means we are in the left half and we should eliminate it as our single element appears on the right. So, we will do this: + low = mid+1. + - Otherwise, we are in the right half and we should eliminate it as our single element appears on the left. So, we will do this: high = mid-1. + + + +#### Solution + +### Java Solution + +```Java + +import java.util.*; + +public class tUf { + public static int singleNonDuplicate(ArrayList arr) { + int n = arr.size(); // Size of the array. + + // Edge cases: + if (n == 1) + return arr.get(0); + if (!arr.get(0).equals(arr.get(1))) + return arr.get(0); + if (!arr.get(n - 1).equals(arr.get(n - 2))) + return arr.get(n - 1); + + int low = 1, high = n - 2; + while (low <= high) { + int mid = (low + high) / 2; + + // If arr[mid] is the single element: + if (!arr.get(mid).equals(arr.get(mid + 1)) && !arr.get(mid).equals(arr.get(mid - 1))) { + return arr.get(mid); + } + + // We are in the left: + if ((mid % 2 == 1 && arr.get(mid).equals(arr.get(mid - 1))) + || (mid % 2 == 0 && arr.get(mid).equals(arr.get(mid + 1)))) { + // Eliminate the left half: + low = mid + 1; + } + // We are in the right: + else { + // Eliminate the right half: + high = mid - 1; + } + } + + // Dummy return statement: + return -1; + } + + public static void main(String[] args) { + ArrayList arr = new ArrayList<>(Arrays.asList(1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6)); + int ans = singleNonDuplicate(arr); + System.out.println("The single element is: " + ans); + } +} + +``` + +### C++ Solution + +```cpp + +#include +using namespace std; + +int singleNonDuplicate(vector& arr) { + int n = arr.size(); //size of the array. + + //Edge cases: + if (n == 1) return arr[0]; + if (arr[0] != arr[1]) return arr[0]; + if (arr[n - 1] != arr[n - 2]) return arr[n - 1]; + + int low = 1, high = n - 2; + while (low <= high) { + int mid = (low + high) / 2; + + //if arr[mid] is the single element: + if (arr[mid] != arr[mid + 1] && arr[mid] != arr[mid - 1]) { + return arr[mid]; + } + + //we are in the left: + if ((mid % 2 == 1 && arr[mid] == arr[mid - 1]) + || (mid % 2 == 0 && arr[mid] == arr[mid + 1])) { + //eliminate the left half: + low = mid + 1; + } + //we are in the right: + else { + //eliminate the right half: + high = mid - 1; + } + } + + // dummy return statement: + return -1; +} + +int main() +{ + vector arr = {1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6}; + int ans = singleNonDuplicate(arr); + cout << "The single element is: " << ans << "\n"; + return 0; +} +``` + +### Python Solution + +```python +def singleNonDuplicate(arr): + n = len(arr) # Size of the array + + # Edge cases: + if n == 1: + return arr[0] + if arr[0] != arr[1]: + return arr[0] + if arr[n - 1] != arr[n - 2]: + return arr[n - 1] + + low = 1 + high = n - 2 + while low <= high: + mid = (low + high) // 2 + + # If arr[mid] is the single element: + if arr[mid] != arr[mid + 1] and arr[mid] != arr[mid - 1]: + return arr[mid] + + # We are in the left: + if (mid % 2 == 1 and arr[mid] == arr[mid - 1]) or (mid % 2 == 0 and arr[mid] == arr[mid + 1]): + # Eliminate the left half: + low = mid + 1 + # We are in the right: + else: + # Eliminate the right half: + high = mid - 1 + + # Dummy return statement: + return -1 + +arr = [1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6] +ans = singleNonDuplicate(arr) +print("The single element is:", ans) +``` + +### Complexity Analysis + +- **Time complexity**: $O(logN)$, N = size of the given array. +- **Space complexity**: $O(1)$ as we are not using any extra space. diff --git a/solutions/lc-solutions/0500-0599/0540-single-element-in-sorted-array.md b/solutions/lc-solutions/0500-0599/0540-single-element-in-sorted-array.md new file mode 100644 index 0000000..4370c94 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0540-single-element-in-sorted-array.md @@ -0,0 +1,184 @@ +--- +id: single-element-in-sorted-array +title: Single Element in a Sorted Array +sidebar_label: Single Element in Sorted Array +tags: + - Binary Search + - Algorithm + - O(log n) +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Single Element in a Sorted Array](https://leetcode.com/problems/Single Element in a Sorted Array/description/) | [Single Element in a Sorted Array Solution on LeetCode](https://leetcode.com/problems/single-element-in-sorted-array/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return the single element that appears only once. + +Your solution must run in O(log n) time and O(1) space. + +### Examples + +## Example 1: + +**Input:** `nums = [1,1,2,3,3,4,4,8,8]` +**Output:** `2` + +## Example 2: + +**Input:** `nums = [3,3,7,7,10,11,11]` +**Output:** `10` + +### Constraints + +- $1 \leq \text{nums.length} \leq 10^5$ +- $0 \leq \text{nums[i]} \leq 10^5$ + +## Approach + +To solve this problem in $O(log n)$ time complexity and $O(1)$ space complexity, we can use a binary search approach. The key observation is that if we split the array into pairs, the single element will disrupt the pairing. By checking the indices, we can determine which half of the array to search next. + +### Step-by-Step Algorithm + +1. Initialize `left` to 0 and `right` to `len(nums) - 1`. +2. Use a binary search loop: `while left < right`: + - Calculate the middle index `mid = left + (right - left) // 2`. + - Check if `mid` is even. If true, check if `nums[mid]` is equal to `nums[mid + 1]`. + - If they are equal, the single element is in the right half, so set `left = mid + 2`. + - Otherwise, the single element is in the left half, so set `right = mid`. + - If `mid` is odd, check if `nums[mid]` is equal to `nums[mid - 1]`. + - If they are equal, the single element is in the right half, so set `left = mid + 1`. + - Otherwise, the single element is in the left half, so set `right = mid - 1`. +3. When the loop exits, `left` will be at the single element. + +## Solution in Python + +```python +def singleNonDuplicate(nums): + left, right = 0, len(nums) - 1 + while left < right: + mid = left + (right - left) // 2 + if mid % 2 == 0: + if nums[mid] == nums[mid + 1]: + left = mid + 2 + else: + right = mid + else: + if nums[mid] == nums[mid - 1]: + left = mid + 1 + else: + right = mid - 1 + return nums[left] +``` + +## Solution in Java + +```java +public class Solution { + public int singleNonDuplicate(int[] nums) { + int left = 0, right = nums.length - 1; + while (left < right) { + int mid = left + (right - left) / 2; + if (mid % 2 == 0) { + if (nums[mid] == nums[mid + 1]) { + left = mid + 2; + } else { + right = mid; + } + } else { + if (nums[mid] == nums[mid - 1]) { + left = mid + 1; + } else { + right = mid - 1; + } + } + } + return nums[left]; + } +} +``` + +## Solution in C++ + +```cpp +class Solution { +public: + int singleNonDuplicate(vector& nums) { + int left = 0, right = nums.size() - 1; + while (left < right) { + int mid = left + (right - left) / 2; + if (mid % 2 == 0) { + if (nums[mid] == nums[mid + 1]) { + left = mid + 2; + } else { + right = mid; + } + } else { + if (nums[mid] == nums[mid - 1]) { + left = mid + 1; + } else { + right = mid - 1; + } + } + } + return nums[left]; + } +}; +``` + +## Solution in C + +```c +int singleNonDuplicate(int* nums, int numsSize){ + int left = 0, right = numsSize - 1; + while (left < right) { + int mid = left + (right - left) / 2; + if (mid % 2 == 0) { + if (nums[mid] == nums[mid + 1]) { + left = mid + 2; + } else { + right = mid; + } + } else { + if (nums[mid] == nums[mid - 1]) { + left = mid + 1; + } else { + right = mid - 1; + } + } + } + return nums[left]; +} +``` + +## Solution in JavaScript + +```javascript +function singleNonDuplicate(nums) { + let left = 0, right = nums.length - 1; + while (left < right) { + const mid = left + Math.floor((right - left) / 2); + if (mid % 2 === 0) { + if (nums[mid] === nums[mid + 1]) { + left = mid + 2; + } else { + right = mid; + } + } else { + if (nums[mid] === nums[mid - 1]) { + left = mid + 1; + } else { + right = mid - 1; + } + } + } + return nums[left]; +} +``` + +## Conclusion + +By leveraging binary search, we can efficiently find the single element that appears only once in a sorted array where every other element appears twice. This approach ensures an O(log n) time complexity and O(1) space complexity, making it an optimal solution for this problem. \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0541-reverse-string-ii.md b/solutions/lc-solutions/0500-0599/0541-reverse-string-ii.md new file mode 100644 index 0000000..6bd452b --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0541-reverse-string-ii.md @@ -0,0 +1,137 @@ +--- +id: reverse-string-ii +title: Reverse String II +sidebar_label: 0541 - Reverse String II +tags: + - String + - Two Pointers + - Recursion +description: "This is a solution to the Reverse String II problem on LeetCode." +--- + +## Problem Description + +Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string. + +If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original. + +### Examples + +**Example 1:** + +``` +Input: s = "abcdefg", k = 2 +Output: "bacdfeg" +``` + +**Example 2:** + +``` +Input: s = "abcd", k = 2 +Output: "bacd" +``` + +### Constraints + +- $1 \leq s.length \leq 10^4$ +- `s` consists of only lowercase English letters. +- $1 \leq k \leq 10^4$ + +## Solution for Reverse String II + +### Approach +#### Intuition and Algorithm + +We will reverse each block of 2k characters directly. + +Each block starts at a multiple of 2k: for example, 0, 2k, 4k, 6k, .... One thing to be careful about is we may not reverse each block if there aren't enough characters. + +To reverse a block of characters from i to j, we can swap characters in positions i++ and j--. + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +public: + std::string reverseStr(std::string s, int k) { + for (int start = 0; start < s.length(); start += 2 * k) { + int i = start; + int j = std::min(start + k - 1, static_cast(s.length()) - 1); + while (i < j) { + std::swap(s[i++], s[j--]); + } + } + return s; + } +}; + +``` + + + + +```java +class Solution { + public String reverseStr(String s, int k) { + char[] a = s.toCharArray(); + for (int start = 0; start < a.length; start += 2 * k) { + int i = start, j = Math.min(start + k - 1, a.length - 1); + while (i < j) { + char tmp = a[i]; + a[i++] = a[j]; + a[j--] = tmp; + } + } + return new String(a); + } +} +``` + + + + + +```python +class Solution(object): + def reverseStr(self, s, k): + a = list(s) + for i in xrange(0, len(a), 2*k): + a[i:i+k] = reversed(a[i:i+k]) + return "".join(a) +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: where N is the size of `s`. We build a helper array, plus reverse about half the characters in `s`. + +### Space Complexity: $O(N)$ + +> **Reason**: the size of `a`. + +## References + +- **LeetCode Problem**: [Reverse String II](https://leetcode.com/problems/reverse-string-ii/description/) + +- **Solution Link**: [Reverse String II](https://leetcode.com/problems/reverse-string-ii/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0542-01-Matrix.md b/solutions/lc-solutions/0500-0599/0542-01-Matrix.md new file mode 100644 index 0000000..44ab700 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0542-01-Matrix.md @@ -0,0 +1,284 @@ +--- +id: 01 Matrix +title: 01 Matrix +sidebar_label: 01-Matrix +tags: + - Binary Matrix + - BFS + - Dynamic Programming + - Algorithms +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [01 Matrix](https://leetcode.com/problems/01-Matrix/description/) | [01 Matrix Solution on LeetCode](https://leetcode.com/problems/01-Matrix/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +Given an m x n binary matrix `mat`, return the distance of the nearest 0 for each cell. + +The distance between two adjacent cells is 1. + +### Example 1 + +**Input:**`mat = [[0,0,0],[0,1,0],[0,0,0]]` +**Output:**`[[0,0,0],[0,1,0],[0,0,0]]` + +### Example 2 + +**Input:**`mat = [[0,0,0],[0,1,0],[1,1,1]]` +**Output:**`[[0,0,0],[0,1,0],[1,2,1]]` + +### Constraints + +- `m == mat.length` +- `n == mat[i].length` +- `1 <= m, n <= 10^4` +- `1 <= m * n <= 10^4` +- `mat[i][j]` is either 0 or 1. +- There is at least one 0 in `mat`. + +## Approach + +To solve this problem, we can use the Breadth-First Search (BFS) approach. The idea is to start from all the 0s and perform a multi-source BFS to update the distances to the nearest 0 for all 1s. + +### Step-by-Step Algorithm + +1. Initialize a queue and push all the cells containing 0s into the queue. +2. Create a `dist` matrix initialized with `inf` for cells containing 1s and 0 for cells containing 0s. +3. Perform BFS starting from all the 0s simultaneously: + - For each cell, pop it from the queue. + - For each neighboring cell, if the current distance + 1 is less than the stored distance, update the distance and push the neighbor into the queue. +4. Continue until the queue is empty. +5. Return the `dist` matrix. + +## Solutions + +### Python +```python +from collections import deque + +def updateMatrix(mat): + rows, cols = len(mat), len(mat[0]) + dist = [[float('inf')] * cols for _ in range(rows)] + queue = deque() + + for r in range(rows): + for c in range(cols): + if mat[r][c] == 0: + dist[r][c] = 0 + queue.append((r, c)) + + directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] + + while queue: + r, c = queue.popleft() + for dr, dc in directions: + nr, nc = r + dr, c + dc + if 0 <= nr < rows and 0 <= nc < cols: + if dist[nr][nc] > dist[r][c] + 1: + dist[nr][nc] = dist[r][c] + 1 + queue.append((nr, nc)) + + return dist +``` + +### Java +```java +import java.util.*; + +public class Solution { + public int[][] updateMatrix(int[][] mat) { + int rows = mat.length, cols = mat[0].length; + int[][] dist = new int[rows][cols]; + for (int[] row : dist) Arrays.fill(row, Integer.MAX_VALUE); + Queue queue = new LinkedList<>(); + + for (int r = 0; r < rows; r++) { + for (int c = 0; c < cols; c++) { + if (mat[r][c] == 0) { + dist[r][c] = 0; + queue.add(new int[] { r, c }); + } + } + } + + int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + + while (!queue.isEmpty()) { + int[] cell = queue.poll(); + int r = cell[0], c = cell[1]; + for (int[] d : directions) { + int nr = r + d[0], nc = c + d[1]; + if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) { + if (dist[nr][nc] > dist[r][c] + 1) { + dist[nr][nc] = dist[r][c] + 1; + queue.add(new int[] { nr, nc }); + } + } + } + } + + return dist; + } +} +``` + +### C++ +```cpp +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector> updateMatrix(vector>& mat) { + int rows = mat.size(), cols = mat[0].size(); + vector> dist(rows, vector(cols, INT_MAX)); + queue> q; + + for (int r = 0; r < rows; ++r) { + for (int c = 0; c < cols; ++c) { + if (mat[r][c] == 0) { + dist[r][c] = 0; + q.push({r, c}); + } + } + } + + vector> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + + while (!q.empty()) { + auto [r, c] = q.front(); q.pop(); + for (auto [dr, dc] : directions) { + int nr = r + dr, nc = c + dc; + if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) { + if (dist[nr][nc] > dist[r][c] + 1) { + dist[nr][nc] = dist[r][c] + 1; + q.push({nr, nc}); + } + } + } + } + + return dist; + } +}; +``` + +### C +```c +#include +#include +#include + +#define MAX 10000 + +typedef struct { + int row, col; +} Pair; + +Pair queue[MAX]; +int front = 0, rear = 0; + +void enqueue(int row, int col) { + queue[rear].row = row; + queue[rear].col = col; + rear = (rear + 1) % MAX; +} + +Pair dequeue() { + Pair p = queue[front]; + front = (front + 1) % MAX; + return p; +} + +int** updateMatrix(int** mat, int matSize, int* matColSize, int* returnSize, int** returnColumnSizes) { + int rows = matSize, cols = matColSize[0]; + int** dist = (int**)malloc(rows * sizeof(int*)); + for (int i = 0; i < rows; i++) { + dist[i] = (int*)malloc(cols * sizeof(int)); + for (int j = 0; j < cols; j++) { + dist[i][j] = (mat[i][j] == 0) ? 0 : INT_MAX; + } + } + + front = rear = 0; + for (int r = 0; r < rows; r++) { + for (int c = 0; c < cols; c++) { + if (mat[r][c] == 0) { + enqueue(r, c); + } + } + } + + int directions[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + + while (front != rear) { + Pair cell = dequeue(); + int r = cell.row, c = cell.col; + for (int i = 0; i < 4; i++) { + int nr = r + directions[i][0], nc = c + directions[i][1]; + if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) { + if (dist[nr][nc] > dist[r][c] + 1) { + dist[nr][nc] = dist[r][c] + 1; + enqueue(nr, nc); + } + } + } + } + + *returnSize = rows; + *returnColumnSizes = (int*)malloc(rows * sizeof(int)); + for (int i = 0; i < rows; i++) { + (*returnColumnSizes)[i] = cols; + } + + return dist; +} +``` + +### JavaScript +```javascript +var updateMatrix = function(mat) { + const rows = mat.length, cols = mat[0].length; + const dist = Array.from({ length: rows }, () => Array(cols).fill(Infinity)); + const queue = []; + + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + if (mat[r][c] === 0) { + dist[r][c] = 0; + queue.push([r, c]); + } + } + } + + const directions = [[1, 0], [-1, 0], [ + +0, 1], [0, -1]]; + + while (queue.length) { + const [r, c] = queue.shift(); + for (const [dr, dc] of directions) { + const nr = r + dr, nc = c + dc; + if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) { + if (dist[nr][nc] > dist[r][c] + 1) { + dist[nr][nc] = dist[r][c] + 1; + queue.push([nr, nc]); + } + } + } + } + + return dist; +}; +``` + +## Conclusion + +The problem of finding the distance to the nearest zero in a binary matrix can be efficiently solved using a multi-source Breadth-First Search (BFS) approach. This method ensures that all cells are visited in the shortest possible distance order, ensuring an optimal solution. \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0542-matrix.md b/solutions/lc-solutions/0500-0599/0542-matrix.md new file mode 100644 index 0000000..4a7ebe7 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0542-matrix.md @@ -0,0 +1,324 @@ +--- +id: matrix +title: 01 Matrix +sidebar_label: 0542 - 01 Matrix +tags: + - Array + - Matrix + - Dynamic Programming + - Breadth First Search +description: "This is a solution to the 542. 01 Matrix problem on LeetCode." +--- + +## Problem Description +Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. + +The distance between two adjacent cells is 1. + +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2021/04/24/01-1-grid.jpg) +``` +Input: mat = [[0,0,0],[0,1,0],[0,0,0]] +Output: [[0,0,0],[0,1,0],[0,0,0]] +``` + +**Example 2:** + +![image](https://assets.leetcode.com/uploads/2021/04/24/01-2-grid.jpg) +``` +Input: mat = [[0,0,0],[0,1,0],[1,1,1]] +Output: [[0,0,0],[0,1,0],[1,2,1]] +``` + +### Constraints + +- `m == mat.length` +- `n == mat[i].length` +- `1 <= m, n <= 10^4` +- `1 <= m * n <= 10^4` +- `mat[i][j] is either 0 or 1.` +- `There is at least one 0 in mat.` + +## Solution for 542. 01 Matrix Problem + +### Approach + +1. **Initialization:** + - Create a queue `q` to perform a Breadth-First Search (BFS). + - Create a `vis` matrix to keep track of visited cells. + - Create a `dis` matrix to store the distance of each cell from the nearest `0`. + +2. **Enqueue All Zeros:** + - Iterate through each cell in the matrix. + - If a cell contains `0`, enqueue it with a distance of `0` and mark it as visited in the `vis` matrix. + - If a cell contains `1`, mark it as not visited in the `vis` matrix. + +3. **Define Directions:** + - Define arrays `drow` and `dcol` to represent the four possible directions (up, right, down, left). + +4. **BFS Traversal:** + - While the queue is not empty: + - Dequeue the front element. + - For each direction: + - Calculate the new row and column indices. + - Check if the new indices are within the bounds and the cell is not visited. + - If valid, mark the cell as visited, enqueue it with the incremented distance, and update the `dis` matrix. + +5. **Return Result:** + - After the BFS completes, the `dis` matrix contains the required distances. + + + + #### Implementation + ```jsx live + function Solution(arr) { + var updateMatrix = function(mat) { + let n = mat.length; + let m = mat[0].length; + + let q = []; + let vis = Array.from({ length: n }, () => Array(m).fill(0)); + let dis = Array.from({ length: n }, () => Array(m).fill(0)); + + for (let i = 0; i < n; i++) { + for (let j = 0; j < m; j++) { + if (mat[i][j] === 0) { + q.push([[i, j], 0]); + vis[i][j] = 1; + } else { + vis[i][j] = 0; + } + } + } + let drow = [-1, 0, 1, 0]; + let dcol = [0, 1, 0, -1]; + + while (q.length) { + let [pos, steps] = q.shift(); + let [row, col] = pos; + dis[row][col] = steps; + for (let i = 0; i < 4; i++) { + let nrow = row + drow[i]; + let ncol = col + dcol[i]; + if (nrow >= 0 && ncol >= 0 && nrow < n && ncol < m && vis[nrow][ncol] === 0) { + vis[nrow][ncol] = 1; + q.push([[nrow, ncol], steps + 1]); + } + } + } + return dis; + }; + + const input = [[0,0,0],[0,1,0],[1,1,1]] + const output = updateMatrix(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n*m) $ + - Space Complexity: $ O(n*m)$ + + ## Code in Different Languages + + + + ```javascript + var updateMatrix = function(mat) { + let n = mat.length; + let m = mat[0].length; + + let q = []; + let vis = Array.from({ length: n }, () => Array(m).fill(0)); + let dis = Array.from({ length: n }, () => Array(m).fill(0)); + + for (let i = 0; i < n; i++) { + for (let j = 0; j < m; j++) { + if (mat[i][j] === 0) { + q.push([[i, j], 0]); + vis[i][j] = 1; + } else { + vis[i][j] = 0; + } + } + } + let drow = [-1, 0, 1, 0]; + let dcol = [0, 1, 0, -1]; + + while (q.length) { + let [pos, steps] = q.shift(); + let [row, col] = pos; + dis[row][col] = steps; + for (let i = 0; i < 4; i++) { + let nrow = row + drow[i]; + let ncol = col + dcol[i]; + if (nrow >= 0 && ncol >= 0 && nrow < n && ncol < m && vis[nrow][ncol] === 0) { + vis[nrow][ncol] = 1; + q.push([[nrow, ncol], steps + 1]); + } + } + } + return dis; +}; + + ``` + + + + + ```python + from collections import deque + +class Solution: + def updateMatrix(self, mat): + n = len(mat) + m = len(mat[0]) + + q = deque() + vis = [[0 for _ in range(m)] for _ in range(n)] + dis = [[0 for _ in range(m)] for _ in range(n)] + + for i in range(n): + for j in range(m): + if mat[i][j] == 0: + q.append(((i, j), 0)) + vis[i][j] = 1 + else: + vis[i][j] = 0 + + drow = [-1, 0, 1, 0] + dcol = [0, 1, 0, -1] + + while q: + (row, col), steps = q.popleft() + dis[row][col] = steps + for i in range(4): + nrow = row + drow[i] + ncol = col + dcol[i] + if 0 <= nrow < n and 0 <= ncol < m and vis[nrow][ncol] == 0: + vis[nrow][ncol] = 1 + q.append(((nrow, ncol), steps + 1)) + + return dis + + ``` + + + + + ```java + import java.util.LinkedList; +import java.util.Queue; + +public class Solution { + public int[][] updateMatrix(int[][] mat) { + int n = mat.length; + int m = mat[0].length; + + Queue q = new LinkedList<>(); + int[][] vis = new int[n][m]; + int[][] dis = new int[n][m]; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (mat[i][j] == 0) { + q.add(new int[]{i, j, 0}); + vis[i][j] = 1; + } else { + vis[i][j] = 0; + } + } + } + int[] drow = {-1, 0, 1, 0}; + int[] dcol = {0, 1, 0, -1}; + + while (!q.isEmpty()) { + int[] current = q.poll(); + int row = current[0]; + int col = current[1]; + int steps = current[2]; + dis[row][col] = steps; + for (int i = 0; i < 4; i++) { + int nrow = row + drow[i]; + int ncol = col + dcol[i]; + if (nrow >= 0 && ncol >= 0 && nrow < n && ncol < m && vis[nrow][ncol] == 0) { + vis[nrow][ncol] = 1; + q.add(new int[]{nrow, ncol, steps + 1}); + } + } + } + return dis; + } +} + + ``` + + + + ```cpp + class Solution { +public: + vector> updateMatrix(vector>& mat) { + int n = mat.size(); + int m = mat[0].size(); + + queue, int>> q; + vector> vis(n, vector(m, 0)); + vector> dis(n, vector(m, 0)); + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (mat[i][j] == 0) { + q.push({{i, j}, 0}); + vis[i][j] = 1; + } else { + vis[i][j] = 0; + } + } + } + int drow[] = {-1, 0, 1, 0}; + int dcol[] = {0, 1, 0, -1}; + + while (!q.empty()) { + int row = q.front().first.first; + int col = q.front().first.second; + int steps = q.front().second; + q.pop(); + dis[row][col] = steps; + for (int i = 0; i < 4; i++) { + int nrow = row + drow[i]; + int ncol = col + dcol[i]; + if (nrow >= 0 && ncol >= 0 && nrow < n && ncol < m && vis[nrow][ncol] == 0) { + vis[nrow][ncol] = 1; + q.push({{nrow, ncol}, steps + 1}); + } + } + } + return dis; + } +}; +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [542. 01 Matrix](https://leetcode.com/problems/01-matrix) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/01-matrix/solutions) diff --git a/solutions/lc-solutions/0500-0599/0543-Diameter-of-Binary-Tree.md b/solutions/lc-solutions/0500-0599/0543-Diameter-of-Binary-Tree.md new file mode 100644 index 0000000..a7a3598 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0543-Diameter-of-Binary-Tree.md @@ -0,0 +1,328 @@ +--- +id: diameter-of-a-binary-tree +title: Diameter of Binary tree +sidebar_label: 0543. Diameter of Binary tree + +tags: +- Binary Tree +- Diameter + +description: "This is a solution to the Diameter of Binary tree problem on LeetCode." +--- + +## Problem Description +Given the `root` of a binary tree, return *the length of the diameter of the tree*. +The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`. +The **length** of a path between two nodes is represented by the number of edges between them. +### Examples + +**Example 1:** + +![Example1](0543-Ex1.png) +``` +Input: root = [1,2,3,4,5] +Output: 3 +Explanataion: 3 is the length of the path [4,2,1,3] or [5,2,1,3]. +``` + +**Example 2:** + +``` +Input: root = [1,2] +Output: 1 +``` + + +### Constraints +- The number of nodes in the tree is in the range `[1, 10^4]`. +- `-100 <= Node.val <= 100` + + + +## Solution for Diameter of Binary tree +### Approach +#### Brute Force +- **Define a Helper Function**: + - Create a function to calculate the height of a tree. +- **Calculate Diameter**: + - For each node, calculate the diameter passing through that node. + - The diameter passing through a node is the sum of the heights of its left and right subtrees. + - Compare this diameter with the global maximum diameter. +- **Traverse Tree**: + - Perform a traversal of the tree (e.g., in-order, pre-order) to compute the diameter for each node. + +**Implementation:** +```cpp +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +int height(TreeNode* node) { + if (node == NULL) { + return 0; + } + return 1 + max(height(node->left), height(node->right)); +} + +int diameterOfBinaryTree(TreeNode* root) { + if (root == NULL) { + return 0; + } + + // Get the height of left and right sub-trees + int left_height = height(root->left); + int right_height = height(root->right); + + // Get the diameter of left and right sub-trees + int left_diameter = diameterOfBinaryTree(root->left); + int right_diameter = diameterOfBinaryTree(root->right); + + // Calculate diameter passing through the root + return max(left_height + right_height, max(left_diameter, right_diameter)); +} + +int main() { + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->right = new TreeNode(3); + root->left->left = new TreeNode(4); + root->left->right = new TreeNode(5); + + cout << "Diameter of the binary tree is: " << diameterOfBinaryTree(root) << endl; + + return 0; +} +``` + +**Complexity:** +- Time Complexity: `O(n^2)` because for each node, we are calculating the height which takes O(n) time. +- Space Complexity: `O(n)` due to the recursion stack. + +**Corner Cases:** +- Empty tree: Should return `0`. +- Single node tree: Should return `0` as there are no edges. + +#### Optimized Approach +- **Define a Helper Function:**: + - Create a function to calculate both the height and the diameter of the tree simultaneously. +- **Single Traversal**: + - Traverse the tree once, calculating the height and updating the maximum diameter at each node. + +**Implementation:** + +```cpp +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + int diameter; + + int height(TreeNode* node) { + if (node == NULL) { + return 0; + } + + int left_height = height(node->left); + int right_height = height(node->right); + + // Update the diameter if left_height + right_height is larger + diameter = max(diameter, left_height + right_height); + + // Height of the current node is max of heights of left and right subtrees plus 1 + return 1 + max(left_height, right_height); + } + + int diameterOfBinaryTree(TreeNode* root) { + diameter = 0; + height(root); + return diameter; + } +}; + +int main() { + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->right = new TreeNode(3); + root->left->left = new TreeNode(4); + root->left->right = new TreeNode(5); + + Solution solution; + cout << "Diameter of the binary tree is: " << solution.diameterOfBinaryTree(root) << endl; + + return 0; +} +``` + +**Complexity:** +- Time Complexity: `O(n)`since we are traversing each node only once. +- Space Complexity: `O(n)`due to the recursion stack. + +**Corner Cases:** +- Empty tree: Should return `0`. +- Single node tree: Should return `0` as there are no edges. + + + ## Code in Different Languages + + + + + + + ```javascript + var diameterOfBinaryTree = function(root) { + let diameter = 0; + + function height(node) { + if (node === null) return 0; + let leftHeight = height(node.left); + let rightHeight = height(node.right); + + // Update the diameter + diameter = Math.max(diameter, leftHeight + rightHeight); + + return 1 + Math.max(leftHeight, rightHeight); + } + + height(root); + return diameter; + }; + ``` + + + + + + + ```typescript + function diameterOfBinaryTree(root: TreeNode | null): number { + let diameter = 0; + + function height(node: TreeNode | null): number { + if (node === null) return 0; + let leftHeight = height(node.left); + let rightHeight = height(node.right); + + // Update the diameter + diameter = Math.max(diameter, leftHeight + rightHeight); + + return 1 + Math.max(leftHeight, rightHeight); + } + + height(root); + return diameter; + } + ``` + + + + + + + ```python + class Solution(object): + def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: + self.diameter = 0 + + def height(node: TreeNode) -> int: + if not node: + return 0 + left_height = height(node.left) + right_height = height(node.right) + + # Update the diameter + self.diameter = max(self.diameter, left_height + right_height) + + return 1 + max(left_height, right_height) + + height(root) + return self.diameter + ``` + + + + + + + ```java + import java.util.Arrays; + + class Solution { + private int diameter; + public int diameterOfBinaryTree(TreeNode root) { + diameter = 0; + + height(root); + return diameter; + } + + private int height(TreeNode node) { + if (node == null) { + return 0; + } + + int leftHeight = height(node.left); + int rightHeight = height(node.right); + + // Update the diameter + diameter = Math.max(diameter, leftHeight + rightHeight); + + return 1 + Math.max(leftHeight, rightHeight); + } + }; + ``` + + + + + + + ```cpp + class Solution { + public: + int diameter; + + int diameterOfBinaryTree(TreeNode* root) { + diameter = 0; + height(root); + return diameter; + } + private: + int height(TreeNode* node) { + if (node == nullptr) { + return 0; + } + + int leftHeight = height(node->left); + int rightHeight = height(node->right); + + // Update the diameter + diameter = max(diameter, leftHeight + rightHeight); + + return 1 + max(leftHeight, rightHeight); + } + }; + ``` + + + + +## References + +- **LeetCode Problem**: [Diameter of Binary tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/diameter-of-binary-tree/solutions/) \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0543-Ex1.png b/solutions/lc-solutions/0500-0599/0543-Ex1.png new file mode 100644 index 0000000..f4bf64f Binary files /dev/null and b/solutions/lc-solutions/0500-0599/0543-Ex1.png differ diff --git a/solutions/lc-solutions/0500-0599/0547-number-of-provinces.md b/solutions/lc-solutions/0500-0599/0547-number-of-provinces.md new file mode 100644 index 0000000..82fd090 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0547-number-of-provinces.md @@ -0,0 +1,339 @@ +--- +id: number-of-provinces +title: Number of Provinces +sidebar_label: 0547 - Number of Provinces +tags: +- Depth-First Search +- Breadth-First Search +- Union Find +- Graph +description: "This is a solution to the Number of Provincess problem on LeetCode." +--- + +## Problem Description +There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c. +A province is a group of directly or indirectly connected cities and no other cities outside of the group. +You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise. +Return the total number of provinces. + +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2020/12/24/graph1.jpg) +``` +Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]] +Output: 2 +``` + +**Example 2:** +![image](https://assets.leetcode.com/uploads/2020/12/24/graph2.jpg) +``` +Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]] +Output: 3 +``` + +### Constraints +- `1 <= n <= 200` +- `n == isConnected.length` +- `n == isConnected[i].length` +- `isConnected[i][j] is 1 or 0.` +- `isConnected[i][i] == 1` +- `isConnected[i][j] == isConnected[j][i]` + +## Solution for Number of Provinces + +### Intuition ans Approach +- To find the solution, we conceptualize the cities and the connections between them as a graph, where each city is a node and each direct connection is an edge. Now, the problem translates to finding the number of connected components in the graph. Each connected component will represent one province. + +- To do this, we use Depth-First Search (DFS). Here's the intuition behind using DFS: + +- We start with the first city and perform a DFS to mark all cities that are connected directly or indirectly to it. These cities form one province. +- Once the DFS is completed, we look for the next city that hasn't been visited yet and perform a DFS from that city to find another province. +- We repeat this process until all cities have been visited. +- Each time we initiate a DFS from a new unvisited city, we know that we've found a new province, so we increment our province count. The DFS ensures that we navigate through all the cities within a province before moving on to the next one. +- By doing the above steps using a vis (visited) list to keep track of which cities have been visited, we can effectively determine and count all the provinces. + + + + +#### Implementation + +```jsx live +function Solution() { + function dfs(root, vis, adj) { + vis[root] = 1; + for (let val of adj[root]) { + if (vis[val] === 0) { + dfs(val, vis, adj); + } + } +} + +function findCircleNum(isConnected) { + const n = isConnected.length; + let cnt = 0; + const vis = new Array(n + 1).fill(0); + const adj = Array.from({ length: n + 1 }, () => []); + + // Build adjacency list + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + if (i !== j && isConnected[i][j] === 1) { + adj[i + 1].push(j + 1); + } + } + } + + // Find all provinces + for (let i = 1; i <= n; i++) { + if (vis[i] === 0) { + cnt++; + dfs(i, vis, adj); + } + } + + return cnt; +} + + +const input = [[1,1,0],[1,1,0],[0,0,1]] +const output = findCircleNum(input); + return ( +
+

+ Input: {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); +} +``` + +### Code in Different Languages + + + + + ```javascript + function dfs(root, vis, adj) { + vis[root] = 1; + for (let val of adj[root]) { + if (vis[val] === 0) { + dfs(val, vis, adj); + } + } +} + +function findCircleNum(isConnected) { + const n = isConnected.length; + let cnt = 0; + const vis = new Array(n + 1).fill(0); + const adj = Array.from({ length: n + 1 }, () => []); + + // Build adjacency list + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + if (i !== j && isConnected[i][j] === 1) { + adj[i + 1].push(j + 1); + } + } + } + + // Find all provinces + for (let i = 1; i <= n; i++) { + if (vis[i] === 0) { + cnt++; + dfs(i, vis, adj); + } + } + + return cnt; +} + +``` + + + + ```typescript +class Solution { + dfs(root: number, vis: number[], adj: number[][]): void { + vis[root] = 1; + for (let val of adj[root]) { + if (vis[val] === 0) { + this.dfs(val, vis, adj); + } + } + } + + findCircleNum(isConnected: number[][]): number { + const n = isConnected.length; + let cnt = 0; + const vis = new Array(n + 1).fill(0); + const adj: number[][] = Array.from({ length: n + 1 }, () => []); + + // Build adjacency list + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + if (i !== j && isConnected[i][j] === 1) { + adj[i + 1].push(j + 1); + } + } + } + + // Find all provinces + for (let i = 1; i <= n; i++) { + if (vis[i] === 0) { + cnt++; + this.dfs(i, vis, adj); + } + } + + return cnt; + } +} + + ``` + + + + ```python + class Solution: + def dfs(self, root, vis, adj): + vis[root] = 1 + for val in adj[root]: + if not vis[val]: + self.dfs(val, vis, adj) + + def findCircleNum(self, isConnected): + n = len(isConnected) + cnt = 0 + vis = [0] * (n + 1) + adj = [[] for _ in range(n + 1)] + + # Build adjacency list + for i in range(n): + for j in range(n): + if i != j and isConnected[i][j] == 1: + adj[i + 1].append(j + 1) + + # Find all provinces + for i in range(1, n + 1): + if not vis[i]: + cnt += 1 + self.dfs(i, vis, adj) + + return cnt + ``` + + + +```java +import java.util.*; + +class Solution { + public void dfs(int root, int[] vis, List[] adj) { + vis[root] = 1; + for (int val : adj[root]) { + if (vis[val] == 0) { + dfs(val, vis, adj); + } + } + } + + public int findCircleNum(int[][] isConnected) { + int n = isConnected.length; + int cnt = 0; + int[] vis = new int[n + 1]; + List[] adj = new ArrayList[n + 1]; + + for (int i = 0; i <= n; i++) { + adj[i] = new ArrayList<>(); + } + + // Build adjacency list + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i != j && isConnected[i][j] == 1) { + adj[i + 1].add(j + 1); + } + } + } + + // Find all provinces + for (int i = 1; i <= n; i++) { + if (vis[i] == 0) { + cnt++; + dfs(i, vis, adj); + } + } + + return cnt; + } +} + +``` + + + +```cpp +class Solution { +public: + void dfs(int root, vector& vis, vector adj[]){ + + vis[root]=1; + for (auto val : adj[root]){ + if(!vis[val]){ + dfs(val,vis,adj); + } + } + } + + int findCircleNum(vector>& isConnected) { + + int n= isConnected.size(); + int cnt=0; + vector vis(n+1,0); + vector adj[n+1]; + for (int i=0; i + + +#### Complexity Analysis + ##### Time Complexity: + - The time complexity of the algorithm is $O(N^2)$, where N is the number of vertices (or cities) in the graph. This complexity arises because the algorithm involves visiting every vertex once and, for each vertex, iterating through all possible adjacent vertices to explore the edges. In the worst-case scenario, this results in checking every entry in the isConnected matrix once, which has $(N^2)$ entries. + +- The dfs function explores all connected vertices through recursive calls. Since each edge and vertex will only be visited once in the DFS traversal, the total number of operations performed will be related to the total number of vertices and edges. However, because the graph is represented by an N x N adjacency matrix and it must be fully inspected to discover all connections, the time is bounded by the size of the matrix $(N^2)$. + + ##### Space Complexity: + The space complexity of the algorithm is $O(N)$, which comes from the following: +- The recursion stack for DFS, which in the worst case, could store up to N frames if the graph is implemented as a linked structure such as a list of nodes (a path with all nodes connected end-to-end). +- The vis visited array, which is a boolean array of length N used to track whether each vertex has been visited or not to prevent cycles during the DFS. +- Given that N recursion calls could happen in a singly connected component spanning all the vertices, the space taken by the call stack should be considered in the final space complexity, merging it with the space taken by the array to $O(N)$. + +
+
+ +## References + +- **LeetCode Problem**: [Number of Provinces](https://leetcode.com/problems/number-of-provinces/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/number-of-provinces/solutions) + diff --git a/solutions/lc-solutions/0500-0599/0548-split-array-with-equal-sum.md b/solutions/lc-solutions/0500-0599/0548-split-array-with-equal-sum.md new file mode 100644 index 0000000..a76728d --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0548-split-array-with-equal-sum.md @@ -0,0 +1,141 @@ +--- +id: split-array-with-equal-sum +title: Split Array with Equal Sum +sidebar_label: 0548 - Split Array with Equal Sum +tags: + - Array + - Prefix Sum + - Divide and Conquer +description: "This is a solution to the Split Array with Equal Sum problem on LeetCode." +--- + +## Problem Description + +Given an array `nums` of length `n`, return `true` if there are four indices `i`, `j`, `k`, `l` (1 <= i < j < k < l < n-1) such that the sum of the subarrays `nums[0..i-1]`, `nums[i+1..j-1]`, `nums[j+1..k-1]`, and `nums[k+1..l-1]` are all equal. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,1,2,1,2,1] +Output: true +Explanation: i = 1, j = 3, k = 5, l = 6 satisfy the conditions. +``` + +**Example 2:** + +``` +Input: nums = [1,2,1,2,1,2,1,2] +Output: false +``` + +### Constraints + +- The array's length is `[7, 2000]`. +- `-10^6 <= nums[i] <= 10^6` + +## Solution for Split Array with Equal Sum + +### Approach: + +1. Use a prefix sum array to store the sum of elements from the start of the array to each index. +2. Iterate through possible positions of `j` and `k` to find valid indices. +3. Check if an index `i` before `j` and an index `l` after `k` exists so that the sums of the corresponding subarrays are equal. + +## Code in Different Languages + +### C++ + +```cpp +class Solution { +public: + bool splitArray(vector& nums) { + int n = nums.size(); + vector prefixSum(n, 0); + prefixSum[0] = nums[0]; + for (int i = 1; i < n; ++i) { + prefixSum[i] = prefixSum[i - 1] + nums[i]; + } + + for (int j = 3; j < n - 3; ++j) { + unordered_set sums; + for (int i = 1; i < j - 1; ++i) { + if (prefixSum[i - 1] == prefixSum[j - 1] - prefixSum[i]) { + sums.insert(prefixSum[i - 1]); + } + } + for (int k = j + 2; k < n - 1; ++k) { + if (prefixSum[n - 1] - prefixSum[k] == prefixSum[k - 1] - prefixSum[j] && sums.count(prefixSum[k - 1] - prefixSum[j])) { + return true; + } + } + } + return false; + } +}; +``` + +### Java + +```java +class Solution { + public boolean splitArray(int[] nums) { + int n = nums.length; + int[] prefixSum = new int[n]; + prefixSum[0] = nums[0]; + for (int i = 1; i < n; i++) { + prefixSum[i] = prefixSum[i - 1] + nums[i]; + } + + for (int j = 3; j < n - 3; j++) { + Set sums = new HashSet<>(); + for (int i = 1; i < j - 1; i++) { + if (prefixSum[i - 1] == prefixSum[j - 1] - prefixSum[i]) { + sums.add(prefixSum[i - 1]); + } + } + for (int k = j + 2; k < n - 1; k++) { + if (prefixSum[n - 1] - prefixSum[k] == prefixSum[k - 1] - prefixSum[j] && sums.contains(prefixSum[k - 1] - prefixSum[j])) { + return true; + } + } + } + return false; + } +} +``` + +### Python + +```python +class Solution: + def splitArray(self, nums: List[int]) -> bool: + n = len(nums) + prefix_sum = [0] * n + prefix_sum[0] = nums[0] + for i in range(1, n): + prefix_sum[i] = prefix_sum[i - 1] + nums[i] + + for j in range(3, n - 3): + sums = set() + for i in range(1, j - 1): + if prefix_sum[i - 1] == prefix_sum[j - 1] - prefix_sum[i]: + sums.add(prefix_sum[i - 1]) + for k in range(j + 2, n - 1): + if prefix_sum[n - 1] - prefix_sum[k] == prefix_sum[k - 1] - prefix_sum[j] and (prefix_sum[k - 1] - prefix_sum[j]) in sums: + return True + return False +``` + +## Complexity Analysis + +### Time Complexity: $O(n^2)$ +**Reason**: The algorithm iterates through all possible positions of `j` and `k`, and within these loops, it iterates through all possible positions of `i` and `l`. + +### Space Complexity: $O(n)$ +**Reason**: It uses a prefix sum array to store the sum of elements from the start of the array to each index, and a set to store the unique sums. + +## References + +- **LeetCode Problem**: [Split Array with Equal Sum](https://leetcode.com/problems/split-array-with-equal-sum/) diff --git a/solutions/lc-solutions/0500-0599/0549-binary-tree-longest-consecutive-sequence-ii.md b/solutions/lc-solutions/0500-0599/0549-binary-tree-longest-consecutive-sequence-ii.md new file mode 100644 index 0000000..9901af4 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0549-binary-tree-longest-consecutive-sequence-ii.md @@ -0,0 +1,207 @@ +--- +id: binary-tree-longest-consecutive-sequence-ii +title: Binary Tree Longest Consecutive Sequence-ii +sidebar_label: 0549-binary-tree-longest-consecutive-sequence-iiQ549-lc +tags: +- Depth-First Search +- Tree +- Binary Tree +description: "This is a solution to binary-tree-longest-consecutive-sequence-ii problem on LeetCode." +--- + +## Problem Description + +Given the `root` of a binary tree, return the length of the `longest consecutive path` in the tree. + +A consecutive path is a path where the values of the consecutive nodes in the path differ by one. This path can be either `increasing` or `decreasing`. + + ~ For example, `[1,2,3,4]` and `[4,3,2,1]` are both considered valid, but the path `[1,2,4,3]` is not valid. + +On the other hand, the path can be in the` child-Parent-child` order, where not necessarily be `parent-child` order. + +### Examples + +**Example 1:** + +``` +Input: root = [1,2,3] +Output: 2 +Explanation: The longest consecutive path is [1, 2] or [2, 1]. + +``` + +**Example 2:** + +``` +Input: root = [2,1,3] +Output: 3 +Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1]. + +``` + + +### Constraints + +- The number of nodes in the tree is in the range `[1, 3 * 104]`. +- `-3 * 10^4 <= Node.val <= 3 * 10^4` + +## Solution for Assign Cookies + +### Approach: + +1- Define a helper function dfs to perform a `depth-first search` on the tree. +2- Handle the base case where the current node is None, returning `[0, 0]`. +3- Initialize incr and decr to `1`, then perform `DFS` on the left and right children. +4- Update `incr` and `decr` based on the values of the left and right children relative to the current node. +5- Update the global ans variable to the maximum of ans and incr `+` `decr - 1`, then return `[incr, decr]`. + +## Code in Different Languages + +### C++ + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int ans; + + int longestConsecutive(TreeNode* root) { + ans = 0; + dfs(root); + return ans; + } + + vector dfs(TreeNode* root) { + if (!root) return {0, 0}; + int incr = 1, decr = 1; + auto left = dfs(root->left); + auto right = dfs(root->right); + if (root->left) { + if (root->left->val + 1 == root->val) incr = left[0] + 1; + if (root->left->val - 1 == root->val) decr = left[1] + 1; + } + if (root->right) { + if (root->right->val + 1 == root->val) incr = max(incr, right[0] + 1); + if (root->right->val - 1 == root->val) decr = max(decr, right[1] + 1); + } + ans = max(ans, incr + decr - 1); + return {incr, decr}; + } +}; + +``` +### Java + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int ans; + + public int longestConsecutive(TreeNode root) { + ans = 0; + dfs(root); + return ans; + } + + private int[] dfs(TreeNode root) { + if (root == null) { + return new int[] {0, 0}; + } + int incr = 1, decr = 1; + int[] left = dfs(root.left); + int[] right = dfs(root.right); + if (root.left != null) { + if (root.left.val + 1 == root.val) { + incr = left[0] + 1; + } + if (root.left.val - 1 == root.val) { + decr = left[1] + 1; + } + } + if (root.right != null) { + if (root.right.val + 1 == root.val) { + incr = Math.max(incr, right[0] + 1); + } + if (root.right.val - 1 == root.val) { + decr = Math.max(decr, right[1] + 1); + } + } + ans = Math.max(ans, incr + decr - 1); + return new int[] {incr, decr}; + } +} + +``` + +### Python + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def longestConsecutive(self, root: TreeNode) -> int: + def dfs(root): + if root is None: + return [0, 0] + nonlocal ans + incr = decr = 1 + i1, d1 = dfs(root.left) + i2, d2 = dfs(root.right) + if root.left: + if root.left.val + 1 == root.val: + incr = i1 + 1 + if root.left.val - 1 == root.val: + decr = d1 + 1 + if root.right: + if root.right.val + 1 == root.val: + incr = max(incr, i2 + 1) + if root.right.val - 1 == root.val: + decr = max(decr, d2 + 1) + ans = max(ans, incr + decr - 1) + return [incr, decr] + + ans = 0 + dfs(root) + return ans +``` + +## Complexity Analysis + +### Time Complexity: O(n) +**Reason**: The algorithm performs a depth-first search (DFS) on the binary tree. In a DFS, each node in the tree is visited exactly once. + +### Space Complexity: O(h) +**Reason**: It is determined by the maximum depth of the recursion stack. In the case of a binary tree, this is equal to the height of the tree, h. + +## References + +- **LeetCode Problem**: [Binary Tree Longest Consecutive Sequence-ii](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/) + diff --git a/solutions/lc-solutions/0500-0599/0550-game-play-analysis-iv.md b/solutions/lc-solutions/0500-0599/0550-game-play-analysis-iv.md new file mode 100644 index 0000000..7d2f7c3 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0550-game-play-analysis-iv.md @@ -0,0 +1,126 @@ +--- +id: game-play-analysis-iv +title: Game Play Analysis IV +sidebar_label: 0550-game-play-analysis-iv +tags: + - Database + +description: "This is a solution to game-play-analysis-iv problem on LeetCode." +--- + +## Problem Description + +Table: `Activity` + +``` ++--------------+---------+ +| Column Name | Type | ++--------------+---------+ +| player_id | int | +| device_id | int | +| event_date | date | +| games_played | int | ++--------------+---------+ +``` + +`(player_id, event_date)` is the primary key (combination of `columns` with unique values) of this table. +This table shows the activity of `players` of some games. +Each `row` is a record of a player who logged in and played a number of games `(possibly 0)` before logging out on someday using some device. + + +Write a solution to report the fraction of players that logged in again on the day after the day they first logged in, rounded to `2 decimal` places. In other words, you need to count the number of players that logged in for at least `two consecutive` days starting from their first login date, then `divide` that number by the total number of `players`. + +The result format is in the following example. + +### Examples + +**Example 1:** + +``` +Input: +Activity table: ++-----------+-----------+------------+--------------+ +| player_id | device_id | event_date | games_played | ++-----------+-----------+------------+--------------+ +| 1 | 2 | 2016-03-01 | 5 | +| 1 | 2 | 2016-03-02 | 6 | +| 2 | 3 | 2017-06-25 | 1 | +| 3 | 1 | 2016-03-02 | 0 | +| 3 | 4 | 2018-07-03 | 5 | ++-----------+-----------+------------+--------------+ +Output: ++-----------+ +| fraction | ++-----------+ +| 0.33 | ++-----------+ +Explanation: +Only the player with id 1 logged back in after the first day he had logged in so the answer is 1/3 = 0.33 + +``` + + +## Solution for Game Play Analysis IV + +### Approach: + +1- Use a Common Table Expression (CTE) to calculate and store the first + login date for each player. +2- Join the original Activity table with the CTE on player_id to access + both the login events and the first login date. +3- Use the DATEDIFF function to check if the event date is exactly one + day after the first login date. +4- Aggregate Results: Sum up the cases where the condition is true and + divide by the total number of unique players to get the desired + fraction. Round the result to two decimal places. + + +## Code in Different Languages + +### MySQL + +```MySQL +# Write your MySQL query statement below + +# First, let's store the first login date of each player. +WITH temp AS ( + SELECT player_id, MIN(event_date) AS first_login_date + FROM Activity + GROUP BY player_id +) + +# Calculate the fraction of players who logged in exactly one day after their first login. +SELECT + ROUND( + SUM(DATEDIFF(a.event_date, t.first_login_date) = 1) / COUNT(DISTINCT a.player_id), 2 + ) AS fraction +FROM Activity a +JOIN temp t ON a.player_id = t.player_id; + +``` +### Pandas + +```pandas +import pandas as pd + +def gameplay_analysis(activity: pd.DataFrame) -> pd.DataFrame: + activity["first"] = activity.groupby("player_id").event_date.transform(min) + activity_2nd_day = activity.loc[activity["first"] + pd.DateOffset(1) == activity["event_date"]] + return pd.DataFrame({"fraction":[round(len(activity_2nd_day) / activity.player_id.nunique(),2)]}) + +``` + + + +## Complexity Analysis + +### Time Complexity: O(n) +**Reason**: where n is the number of rows in the Activity table. This is because the query processes each row in the Activity table to calculate the first login date and checks the date difference for each login event. + +### Space Complexity: O(n) +**Reason**: The space complexity is O(n), where n is the number of players, because the CTE temp will store the first login date for each player. + +## References + +- **LeetCode Problem**: [Game Play Analysis IV](https://leetcode.com/problems/game-play-analysis-iv/) + diff --git a/solutions/lc-solutions/0500-0599/0551-student-attendance-record-i.md b/solutions/lc-solutions/0500-0599/0551-student-attendance-record-i.md new file mode 100644 index 0000000..25832bc --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0551-student-attendance-record-i.md @@ -0,0 +1,138 @@ +--- +id: student-attendance-record-i +title: Student Attendance Record I +sidebar_label: 0551-student-attendance-record-i +tags: + - String +description: "This is a solution to student-attendance-record-i problem on LeetCode." +--- + +## Problem Description + +You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: + + 1- `'A'`: Absent. + 2- `'L'`: Late. + 3- `'P'`: Present. + +The student is eligible for an attendance award if they meet both of the following criteria: + + 1- The student was absent `('A')` for strictly fewer than `2` days + total. + 2- The student was never late `('L')` for `3` or more consecutive + days. + +Return true if the student is eligible for an attendance award, or false otherwise. + +### Examples + +**Example 1:** + +``` +Input: s = "PPALLP" +Output: true +Explanation: The student has fewer than 2 absences and was never late 3 or more consecutive days. +``` + +**Example 2:** + +``` +Input: s = "PPALLL" +Output: false +Explanation: The student was late 3 consecutive days in the last 3 days, so is not eligible for the award. + +``` + + +### Constraints + +- `1 <= s.length <= 1000` +- `s[i] is either 'A', 'L', or 'P'.` + + +## Solution for Assign Cookies + +### Approach: + +1- We have to find that string s doesn't contain more than 1 A's and + more than 2 consective L's. +2- Therefore we are using forloop for calculating number of A's. + And we are using indexOf() --> JAVA or find() --> C++ for finding if "LLL" is present in the string or not. +3- Intialize count = 0 for calculating number of A's. + If count is more than or equal to 2 then return false. Since the students are only elligible for attendance when count of A is 1. +4- Now we have to check condition for consecutive L's. + If string s contains any substring that has LLL then it would return false. This could be done by applying indexOf() or find(). + If the indexOf() or find() returns an index then we will return false. +5- Return true for all the other cases since we have encountered wrong + ones first. + + +## Code in Different Languages + +### C++ + +```cpp +class Solution { +public: + bool checkRecord(string s) { + int count = 0; + for (auto& ch : s) { + if (ch == 'A') { + count++; + if (count >= 2) { + return false; + } + } + } + + if (s.find("LLL") != -1) { + return false; + } + + return true; + } +}; +``` +### Java + +```java +class Solution { + public boolean checkRecord(String s) { + int count = 0; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == 'A') { + count++; + if (count >= 2) { + return false; + } + } + } + + if (s.indexOf("LLL") != -1) { + return false; + } + + return true; + } +} + +``` + +### Python + +```python +class Solution: + def checkRecord(self, s: str) -> bool: + return False if s.find("LLL") >= 0 or s.count('A') > 1 else True +``` + +## Complexity Analysis + +### Time Complexity: O(n) + +### Space Complexity: O(1) + +## References + +- **LeetCode Problem**: [Student Attendance Record I](https://leetcode.com/problems/student-attendance-record-i/) + diff --git a/solutions/lc-solutions/0500-0599/0553-optimal-division.md b/solutions/lc-solutions/0500-0599/0553-optimal-division.md new file mode 100644 index 0000000..7091341 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0553-optimal-division.md @@ -0,0 +1,411 @@ +--- +id: optimal-division +title: Optimal Division +sidebar_label: 0553 - Optimal Division +tags: + - Dynamic Programming + - Math + - String +description: "This is a solution to the Optimal Division problem on LeetCode." +--- + +## Problem Description + +You are given an integer array `nums`. The adjacent integers in `nums` will perform the float division. + +For example, for `nums = [2,3,4]`, we will evaluate the expression `"2/3/4"`. +However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum. + +Return the corresponding expression that has the maximum value in string format. + +**Note:** your expression should not contain redundant parenthesis. + +### Examples + +**Example 1:** + +``` +Input: nums = [1000,100,10,2] +Output: "1000/(100/10/2)" +Explanation: 1000/(100/10/2) = 1000/((100/10)/2) = 200 +However, the bold parenthesis in "1000/((100/10)/2)" are redundant since they do not influence the operation priority. +So you should return "1000/(100/10/2)". +Other cases: +1000/(100/10)/2 = 50 +1000/(100/(10/2)) = 50 +1000/100/10/2 = 0.5 +1000/100/(10/2) = 2 +``` + +**Example 2:** + +``` +Input: nums = [2,3,4] +Output: "2/(3/4)" +Explanation: (2/(3/4)) = 8/3 = 2.667 +It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667 +``` + +### Constraints + +- `1 <= nums.length <= 10` +- `2 <= nums[i] <= 1000` +- There is only one optimal division for the given input. + +## Solution for Optimal Division + +### Approach #1 Brute Force +Brute force of this problem is to divide the list into two parts left and right and call function for these two parts. We will iterate i from start to end so that left=(start,i) and right=(i+1,end). + +left and right parts return their maximum and minimum value and corresponding strings. + +Minimum value can be found by dividing minimum of left by maximum of right i.e. minVal=left.min/right.max. + +Similarly,Maximum value can be found by dividing maximum of left value by minimum of right value. i.e. maxVal=left.max/right.min. + +Now, how to add parenthesis? As associativity of division operator is from left to right i.e. by default left most divide should be done first, we need not have to add paranthesis to the left part, but we must add parenthesis to the right part. + +eg- "2/(3/4)" will be formed as leftPart+"/"+"("+rightPart+")", assuming leftPart is "2" and rightPart is"3/4". + +One more point, we also don't require parenthesis to right part when it contains single digit. + +eg- "2/3", here left part is "2" and right part is "3" (contains single digit) . 2/(3) is not valid. + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include +#include +#include + +class Solution { +public: + std::string optimalDivision(std::vector& nums) { + T t = optimal(nums, 0, nums.size() - 1); + return t.max_str; + } + +private: + struct T { + float max_val, min_val; + std::string min_str, max_str; + }; + + T optimal(const std::vector& nums, int start, int end) { + T t; + if (start == end) { + t.max_val = nums[start]; + t.min_val = nums[start]; + t.min_str = std::to_string(nums[start]); + t.max_str = std::to_string(nums[start]); + return t; + } + t.min_val = FLT_MAX; + t.max_val = -FLT_MAX; + t.min_str = t.max_str = ""; + for (int i = start; i < end; ++i) { + T left = optimal(nums, start, i); + T right = optimal(nums, i + 1, end); + if (t.min_val > left.min_val / right.max_val) { + t.min_val = left.min_val / right.max_val; + t.min_str = left.min_str + "/" + (i + 1 != end ? "(" : "") + right.max_str + (i + 1 != end ? ")" : ""); + } + if (t.max_val < left.max_val / right.min_val) { + t.max_val = left.max_val / right.min_val; + t.max_str = left.max_str + "/" + (i + 1 != end ? "(" : "") + right.min_str + (i + 1 != end ? ")" : ""); + } + } + return t; + } +}; +``` + + + + +```java +public class Solution { + public String optimalDivision(int[] nums) { + T t = optimal(nums, 0, nums.length - 1, ""); + return t.max_str; + } + class T { + float max_val, min_val; + String min_str, max_str; + } + public T optimal(int[] nums, int start, int end, String res) { + T t = new T(); + if (start == end) { + t.max_val = nums[start]; + t.min_val = nums[start]; + t.min_str = "" + nums[start]; + t.max_str = "" + nums[start]; + return t; + } + t.min_val = Float.MAX_VALUE; + t.max_val = Float.MIN_VALUE; + t.min_str = t.max_str = ""; + for (int i = start; i < end; i++) { + T left = optimal(nums, start, i, ""); + T right = optimal(nums, i + 1, end, ""); + if (t.min_val > left.min_val / right.max_val) { + t.min_val = left.min_val / right.max_val; + t.min_str = left.min_str + "/" + (i + 1 != end ? "(" : "") + right.max_str + (i + 1 != end ? ")" : ""); + } + if (t.max_val < left.max_val / right.min_val) { + t.max_val = left.max_val / right.min_val; + t.max_str = left.max_str + "/" + (i + 1 != end ? "(" : "") + right.min_str + (i + 1 != end ? ")" : ""); + } + } + return t; + } +} +``` + + + + +```python +class Solution: + class T: + def __init__(self): + self.max_val = float('-inf') + self.min_val = float('inf') + self.min_str = "" + self.max_str = "" + + def optimalDivision(self, nums): + t = self.optimal(nums, 0, len(nums) - 1) + return t.max_str + + def optimal(self, nums, start, end): + t = self.T() + if start == end: + t.max_val = nums[start] + t.min_val = nums[start] + t.min_str = str(nums[start]) + t.max_str = str(nums[start]) + return t + + for i in range(start, end): + left = self.optimal(nums, start, i) + right = self.optimal(nums, i + 1, end) + + if t.min_val > left.min_val / right.max_val: + t.min_val = left.min_val / right.max_val + t.min_str = left.min_str + "/" + ("(" if i + 1 != end else "") + right.max_str + (")" if i + 1 != end else "") + + if t.max_val < left.max_val / right.min_val: + t.max_val = left.max_val / right.min_val + t.max_str = left.max_str + "/" + ("(" if i + 1 != end else "") + right.min_str + (")" if i + 1 != end else "") + + return t +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N!)$ + +> **Reason**: Number of permutations of expression after applying brackets will be in O(N!) where N is the number of items in the list. + +### Space Complexity: $O(N^2)$ + +> **Reason**: Depth of recursion tree will be O(N) and each node contains string of maximum length O(N). + +### Approach 2: Using Memorization +#### Algorithm + +In the above approach we called optimal function recursively for ever start and end. We can notice that there are many redundant calls in the above approach, we can reduce these calls by using memorization to store the result of different function calls. Here, memo array is used for this purpose. + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include +#include +#include + +class Solution { +public: + std::string optimalDivision(std::vector& nums) { + int n = nums.size(); + std::vector> memo(n, std::vector(n, nullptr)); + T* t = optimal(nums, 0, n - 1, memo); + return t->max_str; + } + +private: + struct T { + float max_val, min_val; + std::string min_str, max_str; + T() : max_val(-FLT_MAX), min_val(FLT_MAX), min_str(""), max_str("") {} + }; + + T* optimal(const std::vector& nums, int start, int end, std::vector>& memo) { + if (memo[start][end] != nullptr) { + return memo[start][end]; + } + T* t = new T(); + if (start == end) { + t->max_val = nums[start]; + t->min_val = nums[start]; + t->min_str = std::to_string(nums[start]); + t->max_str = std::to_string(nums[start]); + memo[start][end] = t; + return t; + } + + for (int i = start; i < end; ++i) { + T* left = optimal(nums, start, i, memo); + T* right = optimal(nums, i + 1, end, memo); + + if (t->min_val > left->min_val / right->max_val) { + t->min_val = left->min_val / right->max_val; + t->min_str = left->min_str + "/" + (i + 1 != end ? "(" : "") + right->max_str + (i + 1 != end ? ")" : ""); + } + if (t->max_val < left->max_val / right->min_val) { + t->max_val = left->max_val / right->min_val; + t->max_str = left->max_str + "/" + (i + 1 != end ? "(" : "") + right->min_str + (i + 1 != end ? ")" : ""); + } + } + memo[start][end] = t; + return t; + } +}; +``` + + + + +```java +public class Solution { + class T { + float max_val, min_val; + String min_str, max_str; + } + public String optimalDivision(int[] nums) { + T[][] memo = new T[nums.length][nums.length]; + T t = optimal(nums, 0, nums.length - 1, "", memo); + return t.max_str; + } + public T optimal(int[] nums, int start, int end, String res, T[][] memo) { + if (memo[start][end] != null) + return memo[start][end]; + T t = new T(); + if (start == end) { + t.max_val = nums[start]; + t.min_val = nums[start]; + t.min_str = "" + nums[start]; + t.max_str = "" + nums[start]; + memo[start][end] = t; + return t; + } + t.min_val = Float.MAX_VALUE; + t.max_val = Float.MIN_VALUE; + t.min_str = t.max_str = ""; + for (int i = start; i < end; i++) { + T left = optimal(nums, start, i, "", memo); + T right = optimal(nums, i + 1, end, "", memo); + if (t.min_val > left.min_val / right.max_val) { + t.min_val = left.min_val / right.max_val; + t.min_str = left.min_str + "/" + (i + 1 != end ? "(" : "") + right.max_str + (i + 1 != end ? ")" : ""); + } + if (t.max_val < left.max_val / right.min_val) { + t.max_val = left.max_val / right.min_val; + t.max_str = left.max_str + "/" + (i + 1 != end ? "(" : "") + right.min_str + (i + 1 != end ? ")" : ""); + } + } + memo[start][end] = t; + return t; + } +} +``` + + + + + +```python +class Solution: + class T: + def __init__(self): + self.max_val = float('-inf') + self.min_val = float('inf') + self.min_str = "" + self.max_str = "" + + def optimalDivision(self, nums): + n = len(nums) + memo = [[None] * n for _ in range(n)] + t = self.optimal(nums, 0, n - 1, memo) + return t.max_str + + def optimal(self, nums, start, end, memo): + if memo[start][end] is not None: + return memo[start][end] + + t = self.T() + if start == end: + t.max_val = nums[start] + t.min_val = nums[start] + t.min_str = str(nums[start]) + t.max_str = str(nums[start]) + memo[start][end] = t + return t + + for i in range(start, end): + left = self.optimal(nums, start, i, memo) + right = self.optimal(nums, i + 1, end, memo) + + if t.min_val > left.min_val / right.max_val: + t.min_val = left.min_val / right.max_val + t.min_str = left.min_str + "/" + ("(" if i + 1 != end else "") + right.max_str + (")" if i + 1 != end else "") + + if t.max_val < left.max_val / right.min_val: + t.max_val = left.max_val / right.min_val + t.max_str = left.max_str + "/" + ("(" if i + 1 != end else "") + right.min_str + (")" if i + 1 != end else "") + + memo[start][end] = t + return t +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N^3)$ + +> **Reason**: memo array of size $N^2$ is filled and filling of each cell of the memo array takes O(N) time. + +### Space Complexity: $O(N^3)$ + +> **Reason**: memo array of size $N^2$ where each cell of array contains string of length O(N). + +## References + +- **LeetCode Problem**: [Optimal Division](https://leetcode.com/problems/optimal-division/description/) + +- **Solution Link**: [Optimal Division](https://leetcode.com/problems/optimal-division/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0554-Brick-Wall.md b/solutions/lc-solutions/0500-0599/0554-Brick-Wall.md new file mode 100644 index 0000000..a9c57de --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0554-Brick-Wall.md @@ -0,0 +1,160 @@ +--- +id: Brick-Wall +title: Brick-Wall +sidebar_label: Brick-Wall +tags: + - hashmap + - LeetCode + - Java + - Python + - C++ +description: This is a solution to the. Brick-Wall problem on LeetCode +--- + +## Problem Description + +There is a rectangular brick wall in front of you with n rows of bricks. The ith row has some number of bricks each of the same height `(i.e., one unit)` but they can be of different widths. The total width of each row is the same. + +Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks. + +Given the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line. + +### Examples + +**Example 1:** + +``` + +Input: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]] +Output: 2 + +``` + +**Example 2:** + + +``` +Input: wall = [[1],[1],[1]] +Output: 3 +``` +### Constraints + +- $1 \leq \text{nums.length} \leq 105$ + + +--- + +## Solution for Brick-Wall + +### Intuition + + - The intuition is, for each gap, keep a counter of how many times the position of the gap appears in the wall. After that, we can just return the length of the wall minus the maximum number of gaps (the more gaps the better, and length of wall minus number of gaps is the number of bricks that we cross). + + + +### Approach + + - Create an empty dictionary called edge_counts. + - Loop through each row in the wall list: + a. Create a variable called edge_pos and set it to 0. + b. Loop through each brick width in the current row up to the second to last brick (since the last brick cannot form an edge). + i. Add the current brick width to edge_pos. + ii. Add 1 to the value in the edge_counts dictionary at the key of edge_pos, or add a new key-value pair with key edge_pos and value 1 if it doesn't exist. + - Return the difference between the length of the wall list and the maximum value in the edge_counts dictionary. If the edge_counts dictionary is empty, return the length of the wall list. + + + + + + +#### Code in Different Languages + + + + + + ```python +//python + +class Solution: + def leastBricks(self, wall: List[List[int]]) -> int: + edge_counts = {} + for row in wall: + edge_pos = 0 + for brick_width in row[:-1]: + edge_pos += brick_width + edge_counts[edge_pos] = edge_counts.get(edge_pos, 0) + 1 + return len(wall) - max(edge_counts.values(), default=0) + + +``` + + + + + ```java +//java +class Solution { + public int leastBricks(List> wall) { + Map map = new HashMap<>(); + int maxUntouched = 0; + + for (List row : wall) { + int brickEnd = 0; + + for (int i = 0; i < row.size() - 1; i++) { + brickEnd += row.get(i); // row.get(i) = brick size + map.put(brickEnd, map.getOrDefault(brickEnd, 0) + 1); + maxUntouched = Math.max(maxUntouched, map.get(brickEnd)); + } + } + + return wall.size() - maxUntouched; + } +} + +// TC: O(m * n), O(n) +// m -> height of the wall +// n -> width of the wall +``` + + + + + ```cpp +//cpp + +class Solution { +public: + int leastBricks(vector>& wall) { + unordered_map m; + int res = wall.size(), n = wall.size(); + + for (auto row : wall) { + + int curr_width = 0; + for (int i = 0; i < row.size()-1; i++) { + + curr_width += row[i]; + res = min(res, n - (++m[curr_width])); + } + } + return res; + } +}; + +``` + + + + + + + + +## References + +- **LeetCode Problem:** [Brick-Wall](https://leetcode.com/problems/brick-wall/) +- **Solution Link:** [Brick-Wall](https://leetcode.com/problems/brick-wall/submissions/) +- **Authors GeeksforGeeks Profile:** [parikhit kurmi](https://www.geeksforgeeks.org/user/sololeveler673/) +- **Authors Leetcode:** [parikhit kurmi](https://leetcode.com/u/parikhitkurmi14/) \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0555-split-concatenated-strings.md b/solutions/lc-solutions/0500-0599/0555-split-concatenated-strings.md new file mode 100644 index 0000000..cad731b --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0555-split-concatenated-strings.md @@ -0,0 +1,189 @@ +--- +id: split-concatenated-strings +title: Split Concatenated Strings +sidebar_label: 0555-split-concatenated-strings +tags: + - Greedy + - String + - Array +description: "This is a solution to split-concatenated-strings problem on LeetCode." +--- + +## Problem Description + +You are given an array of strings `strs`. You could concatenate these strings together into a loop, where for each string, you could choose to reverse it or not. Among all the possible loops + +Return the lexicographically largest string after cutting the loop, which will make the looped string into a regular one. + +Specifically, to find the lexicographically largest string, you need to experience two phases: + +1- Concatenate all the strings into a loop, where you can reverse some + strings or not and connect them in the same order as given. +2- Cut and make one breakpoint in any place of the loop, which will + make the looped string into a regular one starting from the character at the cutpoint. + +And your job is to find the lexicographically largest one among all the possible regular strings. + +### Examples + +**Example 1:** + +``` +Input: strs = ["abc","xyz"] +Output: "zyxcba" +Explanation: You can get the looped string "-abcxyz-", "-abczyx-", "-cbaxyz-", "-cbazyx-", where '-' represents the looped status. +The answer string came from the fourth looped one, where you could cut from the middle character 'a' and get "zyxcba". +``` + +**Example 2:** + +``` +Input: strs = ["abc"] +Output: "cba" + +``` + + +### Constraints + +- `1 <= strs.length <= 1000` +- `1 <= strs[i].length <= 1000` +- `1 <= sum(strs[i].length) <= 1000` +- `strs[i]` consists of lowercase English letters. + + + +## Solution for Assign Cookies + +### Approach: + +1- For each string in the input list, store the lexicographically + larger string between the original and its reverse. +2- Initialize an empty string to store the result. +3- For each string, concatenate the parts from the list excluding the + current string. +4- For each rotation of the current string, form possible concatenated + results by appending the rotated string before and after the concatenated parts. +5- Compare and update the result with the lexicographically largest + string formed. + + +## Code in Different Languages + +### C++ + +```cpp +class Solution { +public: + string splitLoopedString(vector& strs) { + for (auto& s : strs) { + string t{s.rbegin(), s.rend()}; + s = max(s, t); + } + int n = strs.size(); + string ans = ""; + for (int i = 0; i < strs.size(); ++i) { + auto& s = strs[i]; + string t; + for (int j = i + 1; j < n; ++j) { + t += strs[j]; + } + for (int j = 0; j < i; ++j) { + t += strs[j]; + } + for (int j = 0; j < s.size(); ++j) { + auto a = s.substr(j); + auto b = s.substr(0, j); + auto cur = a + t + b; + if (ans < cur) { + ans = cur; + } + reverse(a.begin(), a.end()); + reverse(b.begin(), b.end()); + cur = b + t + a; + if (ans < cur) { + ans = cur; + } + } + } + return ans; + } +}; +``` +### Java + +```java +class Solution { + public String splitLoopedString(String[] strs) { + int n = strs.length; + for (int i = 0; i < n; ++i) { + String s = strs[i]; + String t = new StringBuilder(s).reverse().toString(); + if (s.compareTo(t) < 0) { + strs[i] = t; + } + } + String ans = ""; + for (int i = 0; i < n; ++i) { + String s = strs[i]; + StringBuilder sb = new StringBuilder(); + for (int j = i + 1; j < n; ++j) { + sb.append(strs[j]); + } + for (int j = 0; j < i; ++j) { + sb.append(strs[j]); + } + String t = sb.toString(); + for (int j = 0; j < s.length(); ++j) { + String a = s.substring(j); + String b = s.substring(0, j); + String cur = a + t + b; + if (ans.compareTo(cur) < 0) { + ans = cur; + } + cur = new StringBuilder(b) + .reverse() + .append(t) + .append(new StringBuilder(a).reverse().toString()) + .toString(); + if (ans.compareTo(cur) < 0) { + ans = cur; + } + } + } + return ans; + } +} + +``` + +### Python + +```python +class Solution: + def splitLoopedString(self, strs: List[str]) -> str: + strs = [s[::-1] if s[::-1] > s else s for s in strs] + ans = ''.join(strs) + for i, s in enumerate(strs): + t = ''.join(strs[i + 1 :]) + ''.join(strs[:i]) + for j in range(len(s)): + a = s[j:] + b = s[:j] + ans = max(ans, a + t + b) + ans = max(ans, b[::-1] + t + a[::-1]) + return ans + +``` + +## Complexity Analysis + +### Time Complexity: O(n Γ— l^2) + **Reason**: where n is the number of strings in the vector and l is the average length of the strings. + +### Space Complexity: O(n Γ— l ) +**Reason**: Due to the space required for storing the modified strings and temporary concatenations. + +## References + +- **LeetCode Problem**: [Split Concatenated Strings](https://leetcode.com/problems/split-concatenated-strings/) + diff --git a/solutions/lc-solutions/0500-0599/0557-reverse-words-in-a-string-iii.md b/solutions/lc-solutions/0500-0599/0557-reverse-words-in-a-string-iii.md new file mode 100644 index 0000000..6fcc154 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0557-reverse-words-in-a-string-iii.md @@ -0,0 +1,361 @@ +--- +id: reverse-words-in-a-string-iii +title: Reverse Words in a String III +sidebar_label: 0557 - Reverse Words in a String III +tags: + - String + - Two Pointers + - Stack +description: "This is a solution to the Reverse Words in a String III problem on LeetCode." +--- + +## Problem Description + +Given a string `s`, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. + +### Examples + +**Example 1:** + +``` +Input: s = "Let's take LeetCode contest" +Output: "s'teL ekat edoCteeL tsetnoc" +``` + +**Example 2:** + +``` +Input: s = "Mr Ding" +Output: "rM gniD" +``` + +### Constraints + +- $1 <= s.length <= 5 * 10^4$ +- `s` contains printable **ASCII** characters. +- `s` does not contain any leading or trailing spaces. +- There is **at least one** word in `s`. +- All the words in `s` are separated by a single space. + +## Solution for Reverse Words in a String III + +### Overview + +The problem is a variation of similar reverse string problems, [Reverse Words In a String](https://leetcode.com/problems/reverse-words-in-a-string/description/) and [Reverse Words In String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/description/). + +In the first one, we had to reverse all characters, and in the second variation, we had to reverse the order of words. In this problem, we have to reverse the characters of each word in the sentences. + +### Approach 1: Traverse and Reverse each character one by one +#### Intuition + +To solve the problem let's look at the example carefully, + +``` +Input: "Let's take LeetCode contest"` + +Output: "s'teL ekat edoCteeL tsetnoc" +``` +There are a few observations here, + +- The characters of each word in the string are reversed, but the order of words remains the same. + + For example, in the input, the word `Let's` is the first word in the string. In the output, the characters in the word `Let's` are reversed to `s'teL`. But it is still at the first position in the string. + Similarly the second word `take` is reversed as `ekat` and placed at the same second position in the output string. + +- The words in the string are separated by a space character. So we can say that to build the output string, we must extract and reverse the substring between 2 consecutive space characters. + +![image](https://assets.leetcode.com/static_assets/media/original_images/557/second_observation.png) + +Using this intuition, let's understand how to implement this problem. + +#### Algorithm + +By analyzing the above two key observations, we can derive the following algorithm, + +- Find the starting and ending position of each word in the string. + + As a space character is a separator for each word, we are finding the substrings having a space character before its first character and after its last character. + + > Note: Take care of 2 edge cases here, the first word does not have a space before its first character. Similarly, the last word does not have a space after its last character. + +- For each identified word, reverse the characters of the word one by one. + +**Steps-** +Traverse the string from left to right, starting from $0^{th}$ to $n^{th}$ index. As we traverse, the pointer `strIndex` tracks each character.The implementation can be divided into 2 steps, + +1. Find the start and end index of every word + + - Traverse over the string until the current pointer `strIndex` points to a space character. + + - As `strIndex` points to the space character, the index `strIndex - 1` points to the last character of the current word. + + ![image](https://assets.leetcode.com/static_assets/media/original_images/557/current_pointer_traversal.png) + + - Let's understand how to find the first character of the word, + + - For the first word, its first character is always the first character of the string. + + - For the remaining words, the first character would be the character after the last space character. + + Thus, to mark the start of the current character, we must keep track of the last found space character. Let's use a variable lastSpaceIndex. The variable will be initialized to -1 and updated every time we find the next space character. + + ![image](https://assets.leetcode.com/static_assets/media/original_images/557/start_and_end_index.png) + + The first character of the current word is thus `lastSpaceIndex + 1.` + +2. Reverse the characters within the word + + - Now that we have the first and last index of the current word, we have to reverse the current word and append it to the result string. + + - To reverse the current word, we can traverse it in reverse order i.e start from the end index strIndex - 1 to the first index i.e lastSpaceIndex + 1, appending each character one by one to the result string. + + - To separate the current word from the next, append a space character (" ") at the end after the reverse operation. However, for the last word, this step is skipped. + +Repeat 1 and 2 for all the words in the string. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + string reverseWords(string s) { + string result; + int lastSpaceIndex = -1; + for (int strIndex = 0; strIndex < s.length(); strIndex++) { + if ((strIndex == s.length() - 1) || s[strIndex] == ' ') { + int reverseStrIndex = + (strIndex == s.length() - 1) ? strIndex : strIndex - 1; + for (; reverseStrIndex > lastSpaceIndex; reverseStrIndex--) { + result += s[reverseStrIndex]; + } + if (strIndex != s.length() - 1) { + result += ' '; + } + lastSpaceIndex = strIndex; + } + } + return result; + } +}; +``` + + + +```java +class Solution { + + public String reverseWords(String s) { + StringBuilder result = new StringBuilder(); + int lastSpaceIndex = -1; + for (int strIndex = 0; strIndex < s.length(); strIndex++) { + if ((strIndex == s.length() - 1) || s.charAt(strIndex) == ' ') { + int reverseStrIndex = (strIndex == s.length() - 1) ? strIndex : strIndex - 1; + for (; reverseStrIndex > lastSpaceIndex; reverseStrIndex--) { + result.append(s.charAt(reverseStrIndex)); + } + if (strIndex != s.length() - 1) { + result.append(' '); + } + lastSpaceIndex = strIndex; + } + } + return new String(result); + } +} +``` + + + + + +```python +class Solution: + def reverseWords(self, s: str) -> str: + result = "" + last_space_index = -1 + for str_index in range(len(s)): + if str_index == len(s) - 1 or s[str_index] == ' ': + reverse_str_index = str_index if str_index == len(s) - 1 else str_index - 1 + while reverse_str_index > last_space_index: + result += s[reverse_str_index] + reverse_str_index -= 1 + if str_index != len(s) - 1: + result += ' ' + last_space_index = str_index + return result +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: Every character in the string is traversed twice. First, to find the end of the current word, and second to reverse the word and append it to the result. Thus the time complexity is, O(N+N)=O(N). + +### Space Complexity: $O(1)$ + +> **Reason**: We use constant extra space to track the last space index. You could also argue that we are using O(n) space to build the output string (we normally don't count the output as part of the space complexity, but in this case we are temporarily using some space to build it). + +### Approach 2: Using Two Pointers +#### Intuition + +In the previous approach, the words were reversed by copying every character into another string one by one in reverse order. This operation takes O(N) time, where `N` is the length of the word. + +However, there is another optimal approach to reverse the string in O(N/2) time in place using two pointer approach. + +In this solution, we will traverse the string and find every word's start and end index. Then, we will reverse each word using the two-pointer approach. + +Approach to reverse a string using a two-pointer approach + +1. Find the start and end index of every word given by `startIndex` and `endIndex`. + +2. Swap the characters in the word pointed by `startIndex` and `endIndex`. + +3. Increment `startIndex` by 1 and decrement `endIndex` by 1. + +4. Repeat steps 2 and 3 until `startIndex < endIndex`. + +![image](https://assets.leetcode.com/static_assets/media/original_images/557/2_pointer_approach.png) + +Here's the code snippet for reversing the string stored in character array `chArray` using two pointer approach. +``` +while (startIndex < endIndex) { + char temp = chArray[startIndex]; + chArray[startIndex] = chArray[endIndex]; + chArray[endIndex] = temp; + startIndex++; + endIndex--; +} +``` +#### Algorithm + +- The variable `lastSpaceIndex` stores the index of space character last found. Initialize its value to `-1`. + +- Traverse over each character of the string from $0^{th}$ index to $n^{th}$ index using pointer `strIndex`. + +- As `strIndex` points to a space character, mark the start and end index of the current word in the variables `startIndex` and `endIndex` as, + + - The startIndex of the current word is the value of lastSpaceIndex + 1. + - The endIndex of the current word is the value of strIndex - 1. + +- Reverse the characters in the current word using two pointer approach. + +- Update the lastSpaceIndex to the value of strIndex i.e the index of current space character. The next iteration will refer to this variable to identify the start position of the next word. + +- Repeat the process for all the words in the string. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + string reverseWords(string s) { + int lastSpaceIndex = -1; + int len = (int)s.size(); + for (int strIndex = 0; strIndex <= len; strIndex++) { + if (strIndex == len || s[strIndex] == ' ') { + int startIndex = lastSpaceIndex + 1; + int endIndex = strIndex - 1; + while (startIndex < endIndex) { + char temp = s[startIndex]; + s[startIndex] = s[endIndex]; + s[endIndex] = temp; + startIndex++; + endIndex--; + } + lastSpaceIndex = strIndex; + } + } + return s; + }; +}; +``` + + + +```java +class Solution { + + public String reverseWords(String s) { + int lastSpaceIndex = -1; + char[] chArray = s.toCharArray(); + int len = s.length(); + for (int strIndex = 0; strIndex <= len; strIndex++) { + if (strIndex == len || chArray[strIndex] == ' ') { + int startIndex = lastSpaceIndex + 1; + int endIndex = strIndex - 1; + while (startIndex < endIndex) { + char temp = chArray[startIndex]; + chArray[startIndex] = chArray[endIndex]; + chArray[endIndex] = temp; + startIndex++; + endIndex--; + } + lastSpaceIndex = strIndex; + } + } + return new String(chArray); + } + +} +``` + + + + + +```python +class Solution: + def reverseWords(self, s: str) -> str: + last_space_index = -1 + len_s = len(s) + s_list = list(s) + for str_index in range(len_s + 1): + if str_index == len_s or s[str_index] == ' ': + start_index = last_space_index + 1 + end_index = str_index - 1 + while start_index < end_index: + s_list[start_index], s_list[end_index] = s_list[end_index], s_list[start_index] + start_index += 1 + end_index -= 1 + last_space_index = str_index + return ''.join(s_list) +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: The outer loop iterates over N characters to find the `start` and `end` index of every word. The algorithm to reverse the word also iterates N times to perform N/2 swaps. Thus, the time complexity is O(N+N)=O(N). + +### Space Complexity: $O(1)$ + +> **Reason**: We use constant extra space to track the last space index. You could also argue that we are using O(n) space to build the output string (we normally don't count the output as part of the space complexity, but in this case we are temporarily using some space to build it). + + +## References + +- **LeetCode Problem**: [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/description/) + +- **Solution Link**: [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0560-subarray-sum-equals-k.md b/solutions/lc-solutions/0500-0599/0560-subarray-sum-equals-k.md new file mode 100644 index 0000000..4de755e --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0560-subarray-sum-equals-k.md @@ -0,0 +1,172 @@ +--- +id: subarray-sum-equals-k +title: Subarray Sum Equals K +sidebar_label: Subarray Sum Equals K +tags: + - Array + - HashMap + - Prefix Sum +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [subarray-sum-equals-k](https://leetcode.com/problems/subarray-sum-equals-k/description/) | [subarray-sum-equals-k Solution on LeetCode](https://leetcode.com/problems/subarray-sum-equals-k/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +Given an array of integers `nums` and an integer `k`, return the total number of subarrays whose sum equals to `k`. + +A subarray is a contiguous non-empty sequence of elements within an array. + +### Example 1 + +**Input**: `nums = [1,1,1], k = 2` +**Output**: `2` + +### Example 2 + +**Input**: `nums = [1,2,3], k = 3` +**Output**: `2` + +### Constraints + +- `1 <= nums.length <= 2 * 10^4` +- `-1000 <= nums[i] <= 1000` +- `-10^7 <= k <= 10^7` + +## Approach + +To solve this problem efficiently, we can use a HashMap (dictionary in Python) to keep track of the cumulative sum of elements up to the current index and the number of times each cumulative sum has been encountered. This approach allows us to determine the number of subarrays that sum to `k` in linear time. + +### Step-by-Step Algorithm + +1. Initialize a dictionary `prefix_sum_count` to store the frequency of prefix sums. Start with the prefix sum `0` having a count of `1`. +2. Initialize `current_sum` to `0` and `count` to `0`. +3. Iterate through each element in the array: + - Add the current element to `current_sum`. + - If `current_sum - k` exists in `prefix_sum_count`, it means there are subarrays ending at the current index that sum to `k`. Add the count of `current_sum - k` to `count`. + - Increment the count of `current_sum` in `prefix_sum_count`. +4. Return `count`. + +## Solution in Python + +```python +def subarraySum(nums, k): + prefix_sum_count = {0: 1} + current_sum = 0 + count = 0 + + for num in nums: + current_sum += num + if (current_sum - k) in prefix_sum_count: + count += prefix_sum_count[current_sum - k] + if current_sum in prefix_sum_count: + prefix_sum_count[current_sum] += 1 + else: + prefix_sum_count[current_sum] = 1 + + return count +``` + +## Solution in Java + +```java +import java.util.HashMap; +import java.util.Map; + +public class Solution { + public int subarraySum(int[] nums, int k) { + Map prefixSumCount = new HashMap<>(); + prefixSumCount.put(0, 1); + int current_sum = 0; + int count = 0; + + for (int num : nums) { + current_sum += num; + if (prefixSumCount.containsKey(current_sum - k)) { + count += prefixSumCount.get(current_sum - k); + } + prefixSumCount.put(current_sum, prefixSumCount.getOrDefault(current_sum, 0) + 1); + } + + return count; + } +} +``` + +## Solution in C++ + +```cpp +#include +#include + +class Solution { +public: + int subarraySum(std::vector& nums, int k) { + std::unordered_map prefixSumCount = {{0, 1}}; + int current_sum = 0; + int count = 0; + + for (int num : nums) { + current_sum += num; + if (prefixSumCount.find(current_sum - k) != prefixSumCount.end()) { + count += prefixSumCount[current_sum - k]; + } + prefixSumCount[current_sum]++; + } + + return count; + } +}; +``` + +## Solution in C + +```c +#include +#include + +int subarraySum(int* nums, int numsSize, int k) { + int *prefixSumCount = (int*)calloc(numsSize * 2000, sizeof(int)); // Assuming numsSize <= 20000 + prefixSumCount[numsSize] = 1; // Initial prefix sum 0 + + int current_sum = 0; + int count = 0; + + for (int i = 0; i < numsSize; i++) { + current_sum += nums[i]; + int target_sum = current_sum - k; + count += prefixSumCount[target_sum + numsSize]; + prefixSumCount[current_sum + numsSize]++; + } + + free(prefixSumCount); + return count; +} +``` + +## Solution in JavaScript + +```javascript +var subarraySum = function(nums, k) { + let prefixSumCount = {0: 1}; + let current_sum = 0; + let count = 0; + + for (let num of nums) { + current_sum += num; + if (prefixSumCount[current_sum - k] !== undefined) { + count += prefixSumCount[current_sum - k]; + } + prefixSumCount[current_sum] = (prefixSumCount[current_sum] || 0) + 1; + } + + return count; +}; +``` + +## Conclusion + +The described algorithm efficiently finds the number of subarrays that sum up to a given value `k` using a HashMap to store prefix sums. This approach ensures that the solution runs in linear time, making it suitable for large input sizes. \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0563-binary-tree-tilt.md b/solutions/lc-solutions/0500-0599/0563-binary-tree-tilt.md new file mode 100644 index 0000000..a2d9241 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0563-binary-tree-tilt.md @@ -0,0 +1,221 @@ +--- +id: binary-tree-tilt +title: Binary Tree Tilt +sidebar_label: 0563 - Binary Tree Tilt +tags: + - Recursion + - Depth First Search + - Binary Tree +description: "This is a solution to the Binary Tree Tilt problem on LeetCode." +--- + +## Problem Description + +Given the root of a binary tree, return the sum of every tree node's **tilt**. + +The **tilt** of a tree node is the **absolute difference** between the sum of all left subtree node values and all right subtree node **values**. If a node does not have a left child, then the sum of the left subtree node **values** is treated as `0`. The rule is similar if the node does not have a right child. + +### Examples +**Example 1:** + +![image](https://assets.leetcode.com/uploads/2020/10/20/tilt1.jpg) +``` +Input: root = [1,2,3] +Output: 1 +Explanation: +Tilt of node 2 : |0-0| = 0 (no children) +Tilt of node 3 : |0-0| = 0 (no children) +Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3) +Sum of every tilt : 0 + 0 + 1 = 1 +``` + +**Example 2:** + +![image](https://assets.leetcode.com/uploads/2020/10/20/tilt2.jpg) +``` +Input: root = [4,2,9,3,5,null,7] +Output: 15 +Explanation: +Tilt of node 3 : |0-0| = 0 (no children) +Tilt of node 5 : |0-0| = 0 (no children) +Tilt of node 7 : |0-0| = 0 (no children) +Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5) +Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7) +Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16) +Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15 +``` + +### Constraints + +- The number of nodes in the tree is in the range [0, $10^4$]. +- `1000 <= Node.val <= 1000` + +## Solution for Binary Tree Tilt + +### Overview +First of all, let us clarify the concept of **tilt** for a given node in a tree. + +In order to calculate the tilt value for a node, we need to know the sum of nodes in its left and right subtrees respectively. + +Assume that we have a function `valueSum(node)` which gives the sum of all nodes, starting from the input node, then the sum of the node's left subtree would be `valueSum(node.left)`. +Similarly, the sum of its right subtree would be `valueSum(node.right)`. + +With the above functions, we can then define the tilt value of a node as follows: + +$tilt(node)=∣valueSum(node.left)βˆ’valueSum(node.right)∣$ + +Given the above formula, we show an example on how the tilt value of each node looks like, in the following graph: + +![image](https://assets.leetcode.com/static_assets/media/original_images/563/563_tilt_example.png) +Note: when a subtree is empty, its value sum is zero. +As a result, the tilt value for a leaf node would be zero, since both the left and right subtree of a leaf node are empty. + +### Approach 1: Post-Order DFS Traversal +#### Intuition + +> The overall idea is that we traverse each node, and calculate the tilt value for each node. At the end, we sum up all the tilt values, which is the desired result of the problem. + +There are in general two strategies to traverse a tree data structure, namely Breadth-First Search (**BFS**) and Depth-First Search (**DFS**). + +Concerning the DFS strategy, it can further be divided into three categories: Pre-Order, In-Order and Post-Order, depending on the relative order of visit among the node and its children nodes. + +Sometimes, both strategies could work for a specific problem. In other cases, one of them might be more adapted to the problem. +In our case here, the DFS is a more optimized choice, as one will see later. +More specifically, we could apply the **Post-Order DFS** traversal here. + +#### Algorithm +As we discussed before, in order to calculate the tilt value for a node, we need to calculate the sum of its left and right subtrees respectively. + +Let us first implement the function `valueSum(node)` which returns the sum of values for all nodes starting from the given `node`, which can be summarized with the following recursive formula: + +$valueSum(node)=node.val+valueSum(node.left)+valueSum(node.right)$ + +Furthermore, the tilt value of a node also depends on the value sum of its left and right subtrees, as follows: + +$tilt(node)=∣valueSum(node.left)βˆ’valueSum(node.right)∣$ + +Intuitively, we could combine the above calculations within a single recursive function. +In this way, we only need to traverse each node once and only once. + +> More specifically, we will traverse the tree in the post-order DFS, i.e. we visit a node's left and right subtrees before processing the value of the current node. + +## Code in Different Languages + + + + + +```cpp +#include + +class Solution { +private: + int totalTilt; + + int valueSum(TreeNode* node) { + if (node == nullptr) + return 0; + + int leftSum = valueSum(node->left); + int rightSum = valueSum(node->right); + int tilt = std::abs(leftSum - rightSum); + totalTilt += tilt; + + return node->val + leftSum + rightSum; + } + +public: + int findTilt(TreeNode* root) { + totalTilt = 0; + valueSum(root); + return totalTilt; + } +}; + +``` + + + + +```java +class Solution { + private int totalTilt = 0; + + protected int valueSum(TreeNode node) { + if (node == null) + return 0; + + int leftSum = this.valueSum(node.left); + int rightSum = this.valueSum(node.right); + int tilt = Math.abs(leftSum - rightSum); + this.totalTilt += tilt; + + // return the sum of values starting from this node. + return node.val + leftSum + rightSum; + } + + public int findTilt(TreeNode root) { + this.totalTilt = 0; + this.valueSum(root); + return this.totalTilt; + } +} +``` + + + + + +```python +class Solution: + def findTilt(self, root: TreeNode) -> int: + total_tilt = 0 + + def valueSum(node): + nonlocal total_tilt + + if not node: + return 0 + + left_sum = valueSum(node.left) + right_sum = valueSum(node.right) + tilt = abs(left_sum - right_sum) + total_tilt += tilt + + return left_sum + right_sum + node.val + + valueSum(root) + + return total_tilt +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: We traverse each node once and only once. During the traversal, we calculate the tilt value for each node. + +### Space Complexity: $O(N)$ + +> **Reason**: +> - Although the variables that we used in the algorithm are of constant-size, we applied recursion in the algorithm which incurs additional memory consumption in function call stack. +> +> - In the worst case where the tree is not well balanced, the recursion could pile up N times. As a result, the space complexity of the algorithm is O(N). + +## References + +- **LeetCode Problem**: [Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/description/) + +- **Solution Link**: [Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0564- Find the Closest Palindrome.md b/solutions/lc-solutions/0500-0599/0564- Find the Closest Palindrome.md new file mode 100644 index 0000000..9f69224 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0564- Find the Closest Palindrome.md @@ -0,0 +1,134 @@ +--- +id: find-the-closest-palindrome +title: Find the Closest Palindrome +sidebar_label: 564 Find the Closest Palindrome +tags: +- Java +- string +- Math +description: "This document provides a solution where we need to find the nearest palindrome to a given number n, the idea is to generate potential palindromic candidates close to n and then determine which one is closest in terms of absolute difference. " +--- + +## Problem + +Given a string $n$ representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return **the smaller one**. + +The closest is defined as the absolute difference minimized between two integers. + +### Examples + +**Example 1:** + +``` +Input: n = "123" + +Output: "121" + +``` + +**Example 2:** + +``` +Input: n = "1" + +Output: "0" + +Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0. + +``` + +### Constraints + +- $1 \leq n.length \leq 18$ +- $n$ consists of only digits. +- $n$ does not have leading zeros. +- $n$ is representing an integer in the range [1, $10^18$ - 1]. + +--- + +## Approach + +To solve the problem, we need to understand the nature of the allowed moves: + +1. **Generate Candidate Palindromes**: + + - Generate palindromes by reflecting the first half of the number. + + - Create palindromes by incrementing or decrementing the first half of the number. + + - Consider edge cases such as numbers with all $9's$ or all $0's$. + +2. **Calculate Distances**: + + - For each candidate palindrome, compute the absolute difference from the original number $n$. + +3. **Select the Closest Palindrome**: + + - Among all candidates, select the one with the smallest absolute difference. In case of ties, choose the smaller number. + +## Solution for Finding the Closest Palindrome + +The given problem involves To find the nearest palindrome to a given number 'n', the idea is to generate potential palindromic candidates close to 'n' and then determine which one is closest in terms of absolute difference. + +#### Code in Java + +```java +class Solution { + public String nearestPalindromic(String n) { + long num = Long.parseLong(n); + int len = n.length(); + + // Edge cases for 1, 0, 10, 100, etc. + long smaller = (long) Math.pow(10, len - 1) - 1; + long larger = (long) Math.pow(10, len) + 1; + + // Middle palindrome by modifying the first half + long prefix = Long.parseLong(n.substring(0, (len + 1) / 2)); + long candidate1 = createPalindrome(prefix, len % 2 == 0); + long candidate2 = createPalindrome(prefix - 1, len % 2 == 0); + long candidate3 = createPalindrome(prefix + 1, len % 2 == 0); + + // Collecting all candidates + long[] candidates = {smaller, larger, candidate1, candidate2, candidate3}; + + // Finding the nearest palindrome + long nearest = -1; + for (long candidate : candidates) { + if (candidate != num) { + if (nearest == -1 || Math.abs(candidate - num) < Math.abs(nearest - num) || + (Math.abs(candidate - num) == Math.abs(nearest - num) && candidate < nearest)) { + nearest = candidate; + } + } + } + + return String.valueOf(nearest); + } + + private long createPalindrome(long prefix, boolean isEvenLength) { + String strPrefix = String.valueOf(prefix); + StringBuilder sb = new StringBuilder(strPrefix); + if (!isEvenLength) { + sb.setLength(sb.length() - 1); + } + return Long.parseLong(strPrefix + sb.reverse().toString()); + } +} + +``` + +### Complexity Analysis + +#### Time Complexity: $O(log(n))$ + +> **Reason**: Time Complexity is $O(log(n))$, Comparing a constant number of candidates (5 in this case) involves checking their absolute differences with the original number. + +#### Space Complexity: $O(1)$ + +> **Reason**: $O(1)$ additional space, excluding the space required to store the input and output since we only use a fixed number of variables. + +# References + +- **LeetCode Problem:** [Find the Closest Palindrome](https://leetcode.com/problems/find-the-closest-palindrome/description/) +- **Solution Link:** [Find the Closest Palindrome Solution on LeetCode](https://leetcode.com/problems/find-the-closest-palindrome/solutions/) +- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/vivekvardhan43862/) diff --git a/solutions/lc-solutions/0500-0599/0565-array-nesting.md b/solutions/lc-solutions/0500-0599/0565-array-nesting.md new file mode 100644 index 0000000..3a41c95 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0565-array-nesting.md @@ -0,0 +1,279 @@ +--- +id: array-nesting +title: Array Nesting +sidebar_label: 0565 - Array Nesting +tags: + - Depth-First Search + - Array + - Dynamic Programming +description: "This is a solution to the Array Nesting problem on LeetCode." +--- + +## Problem Description + +You are given an integer array `nums` of length `n` where `nums` is a permutation of the numbers in the range `[0, n - 1]`. + +You should build a set `s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... }` subjected to the following rule: + +- The first element in `s[k]` starts with the selection of the element `nums[k]` of `index = k`. +- The next element in `s[k]` should be `nums[nums[k]]`, and then `nums[nums[nums[k]]]`, and so on. +- We stop adding right before a duplicate element occurs in `s[k]`. +- Return the longest length of a set `s[k]`. + +### Examples + +**Example 1:** + +``` +Input: nums = [5,4,0,3,1,6,2] +Output: 4 +Explanation: +nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2. +One of the longest sets s[k]: +s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0} +``` + +**Example 2:** + +``` +Input: nums = [0,1,2] +Output: 1 +``` + +### Constraints + +- $1 <= nums.length <= 10^5$ +- $0 <= nums[i] < nums.length$ +- All the values of `nums` are **unique**. + +## Solution for Array Nesting + +### Approach #1 Brute Force [Time Limit Exceeded] + +The simplest method is to iterate over all the indices of the given nums array. For every index i chosen, we find the element nums[i] and increment the count for a new element added for the current index i. Since nums[i] has to act as the new index for finding the next element belonging to the set corresponding to the index i, the new index is j=nums[i]. + +We continue this process of index updation and keep on incrementing the count for new elements added to the set corresponding to the index i. Now, since all the elements in nums lie in the range (0,...,Nβˆ’1), the new indices generated will never lie outside the array size limits. But, we'll always reach a point where the current element becomes equal to the element nums[i] with which we started the nestings in the first place. Thus, after this, the new indices generated will be just the repetitions of the previously generated ones, and thus would not lead to an increase in the size of the current set. Thus, this condition of the current number being equal to the starting number acts as the terminating condition for count incrementation for a particular index. + +We do the same process for every index chosen as the starting index. At the end, the maximum value of count obtained gives the size of the largest set. + +## Code in Different Languages + + + + + +```cpp +#include +#include // For std::max + +class Solution { +public: + int arrayNesting(std::vector& nums) { + int res = 0; + int n = nums.size(); + std::vector visited(n, false); + + for (int i = 0; i < n; i++) { + if (!visited[i]) { + int start = nums[i], count = 0; + do { + start = nums[start]; + count++; + visited[start] = true; + } while (start != nums[i]); + res = std::max(res, count); + } + } + return res; + } +}; + + +``` + + + + +```java +public class Solution { + public int arrayNesting(int[] nums) { + int res = 0; + for (int i = 0; i < nums.length; i++) { + int start = nums[i], count = 0; + do { + start = nums[start]; + count++; + } + while (start != nums[i]); + res = Math.max(res, count); + + } + return res; + } +} +``` + + + + + +```python +class Solution: + def arrayNesting(self, nums): + res = 0 + visited = [False] * len(nums) + + for i in range(len(nums)): + if not visited[i]: + start = nums[i] + count = 0 + while True: + start = nums[start] + count += 1 + visited[start] = True + if start == nums[i]: + break + res = max(res, count) + + return res +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N^2)$ + +> **Reason**: In worst case, for example- [1,2,3,4,5,0], loop body will be executed $N^2$ times. + +### Space Complexity: $O(1)$ + +> **Reason**: Constant space is used. + +### Approach #2 Using Visited Array +#### Algorithm + +In the last approach, we observed that in the worst case, all the elements of the nums array are added to the sets corresponding to all the starting indices. But, all these sets correspond to the same set of elements only, leading to redundant calculations. + +We consider a simple example and see how this problem can be resolved. From the figure below, we can see that the elements in the current nesting shown by arrows form a cycle. Thus, the same elements will be added to the current set irrespective of the first element chosen to be added to the set out of these marked elements. + +![image](https://assets.leetcode.com/static_assets/media/original_images/565/Array_Nesting.PNG) + +Thus, when we add an element nums[j] to a set corresponding to any of the indices, we mark its position as visited in a visited array. This is done so that whenever this index is chosen as the starting index in the future, we do not go for redundant count calculations, since we've already considered the elements linked with this index, which will be added to a new(duplicate) set. + +By doing so, we ensure that the duplicate sets aren't considered again and again. + +Further, we can also observe that no two elements at indices i and j will lead to a jump to the same index k, since it would require nums[i]=nums[j]=k, which isn't possible since all the elements are distinct. Also, because of the same reasoning, no element outside any cycle could lead to an element inside the cycle. Because of this, the use of visited array goes correctly. + +## Code in Different Languages + + + + + +```cpp +#include +#include // For std::max + +class Solution { +public: + int arrayNesting(std::vector& nums) { + std::vector visited(nums.size(), false); + int res = 0; + + for (int i = 0; i < nums.size(); i++) { + if (!visited[i]) { + int start = nums[i], count = 0; + do { + start = nums[start]; + count++; + visited[start] = true; + } while (start != nums[i]); + res = std::max(res, count); + } + } + return res; + } +}; + +``` + + + + +```java +public class Solution { + public int arrayNesting(int[] nums) { + boolean[] visited = new boolean[nums.length]; + int res = 0; + for (int i = 0; i < nums.length; i++) { + if (!visited[i]) { + int start = nums[i], count = 0; + do { + start = nums[start]; + count++; + visited[start] = true; + } + while (start != nums[i]); + res = Math.max(res, count); + } + } + return res; + } +} + +``` + + + + + +```python +class Solution: + def arrayNesting(self, nums): + visited = [False] * len(nums) + res = 0 + + for i in range(len(nums)): + if not visited[i]: + start = nums[i] + count = 0 + while True: + start = nums[start] + count += 1 + visited[start] = True + if start == nums[i]: + break + res = max(res, count) + + return res + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: Every element of the nums array will be considered at most once. + +### Space Complexity: $O(N)$ + +> **Reason**: visited array of size N is used. + +## References + +- **LeetCode Problem**: [Array Nesting](https://leetcode.com/problems/array-nesting/description/) + +- **Solution Link**: [Array Nesting](https://leetcode.com/problems/array-nesting/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0572-subtree-of-another-tree.md b/solutions/lc-solutions/0500-0599/0572-subtree-of-another-tree.md new file mode 100644 index 0000000..d9e6437 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0572-subtree-of-another-tree.md @@ -0,0 +1,169 @@ +--- +id: subtree-of-another-tree +title: Subtree of Another Tree(LeetCode) +sidebar_label: 0572-Subtree of Another Tree +tags: + - Tree + - Depth-first search + - String matching + - Binary Tree + - Hash Function +description: Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise. +--- + +## Problem Statement + +Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. + +A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. + +### Examples + +**Example 1:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/ba7a84cb-159d-42f1-8f1f-7f38228290cf) + +```plaintext +Input: root = [3,4,5,1,2], subRoot = [4,1,2] +Output: true +``` + +**Example 2:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/e55e6532-0895-4552-b27d-c877b7498e26) + +```plaintext +Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2] +Output: false +``` + +### Constraints + +- The number of nodes in the root `tree` is in the range `[1, 2000]`. +- The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. +- `-104 <= root.val <= 104` +- `-104 <= subRoot.val <= 104` + +## Solution + +The problem is to determine whether one binary tree (subRoot) is a subtree of another binary tree (root). We will discuss two solutions: a naive approach and an optimized approach using serialization and the KMP algorithm. + +### Approach 1: Naive Solution + +#### Algorithm + +1. Traverse each node in the main tree (root). +2. For each node, check if the subtree rooted at this node matches `subRoot` using a helper function. +3. The helper function recursively checks if two trees are identical by comparing the current nodes and their left and right subtrees. +4. Return `true` if any subtree matches `subRoot`, otherwise return `false`. + +#### Implementation + +```Java +class Solution { + public boolean isSubtree(TreeNode root, TreeNode subRoot) { + if (root == null) return false; + if (isSameTree(root, subRoot)) return true; + return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot); + } + + private boolean isSameTree(TreeNode s, TreeNode t) { + if (s == null && t == null) return true; + if (s == null || t == null) return false; + if (s.val != t.val) return false; + return isSameTree(s.left, t.left) && isSameTree(s.right, t.right); + } +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(M * N)$ - where M is the number of nodes in root, and N is the number of nodes in subRoot. +- **Space complexity**: $O(H)$ - where H is the height of root due to the recursion stack. + +### Approach 2: Serialize in Preorder then KMP + +#### Algorithm + +1. Serialize both `root` and `subRoot` using preorder traversal, including markers for null nodes to ensure uniqueness of the serialization. +2. Use the KMP (Knuth-Morris-Pratt) algorithm to check if the serialized string of `subRoot` is a substring of the serialized string of `root`. + +#### Implementation + +```Java +class Solution { + public boolean isSubtree(TreeNode root, TreeNode subRoot) { + String tree1 = serialize(root); + String tree2 = serialize(subRoot); + return kmp(tree1, tree2); + } + + private String serialize(TreeNode root) { + StringBuilder sb = new StringBuilder(); + serializeHelper(root, sb); + return sb.toString(); + } + + private void serializeHelper(TreeNode root, StringBuilder sb) { + if (root == null) { + sb.append("#,"); + return; + } + sb.append(root.val).append(","); + serializeHelper(root.left, sb); + serializeHelper(root.right, sb); + } + + private boolean kmp(String s, String p) { + int[] lps = buildLPS(p); + int i = 0, j = 0; + while (i < s.length()) { + if (s.charAt(i) == p.charAt(j)) { + i++; + j++; + } + if (j == p.length()) { + return true; + } else if (i < s.length() && s.charAt(i) != p.charAt(j)) { + if (j != 0) { + j = lps[j - 1]; + } else { + i++; + } + } + } + return false; + } + + private int[] buildLPS(String p) { + int[] lps = new int[p.length()]; + int len = 0, i = 1; + while (i < p.length()) { + if (p.charAt(i) == p.charAt(len)) { + len++; + lps[i] = len; + i++; + } else { + if (len != 0) { + len = lps[len - 1]; + } else { + lps[i] = 0; + i++; + } + } + } + return lps; + } +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(M + N)$ +- **Space complexity**: $O(M + N)$ + +### Conclusion + +* The Naive Solution is straightforward but less efficient for large trees due to its O(M * N) time complexity. +* The Optimized Solution using serialization and KMP is more efficient with a time complexity of O(M + N), making it suitable for larger trees. +* Both solutions have linear space complexity relative to the size of the trees they handle. diff --git a/solutions/lc-solutions/0500-0599/0576-out-of-boundary-paths.md b/solutions/lc-solutions/0500-0599/0576-out-of-boundary-paths.md new file mode 100644 index 0000000..a5cae73 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0576-out-of-boundary-paths.md @@ -0,0 +1,243 @@ +--- +id: out-of-boundary-paths +title: Out of Boundary Paths +sidebar_label: 0576 - Out of Boundary Paths +tags: + - Memoization + - Dynamic Programming + - Recursion +description: "This is a solution to the Out of Boundary Paths problem on LeetCode." +--- + +## Problem Description + +There is an `m x n` grid with a ball. The ball is initially at the position `[startRow, startColumn]`. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply **at most** `maxMove` moves to the ball. + +Given the five integers `m`, `n`, `maxMove`, `startRow`, `startColumn`, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo $10^9 + 7$. + +### Examples + +**Example 1:** + +![image](https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_1.png) +``` +Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 +Output: 6 +``` + +**Example 2:** + +![image](https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_2.png) +``` +Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1 +Output: 12 +``` + +### Constraints + +- `1 <= m, n <= 50` +- `0 <= maxMove <= 50` +- `0 <= startRow < m` +- `0 <= startColumn < n` + +## Solution for Out of Boundary Paths + +### Approach 1: Brute Force [Time Limit Exceeded] +#### Algorithm + +In the brute force approach, we try to take one step in every direction and decrement the number of pending moves for each step taken. Whenever we reach out of the boundary while taking the steps, we deduce that one extra path is available to take the ball out. + +In order to implement the same, we make use of a recursive function `findPaths(m,n,N,i,j)` which takes the current number of moves(N) along with the current position(i,j) as some of the parameters and returns the number of moves possible to take the ball out with the current pending moves from the current position. Now, we take a step in every direction and update the corresponding indices involved along with the current number of pending moves. + +Further, if we run out of moves at any moment, we return a 0 indicating that the current set of moves doesn't take the ball out of boundary. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + int findPaths(int m, int n, int N, int i, int j) { + if (i == m || j == n || i < 0 || j < 0) return 1; + if (N == 0) return 0; + return findPaths(m, n, N - 1, i - 1, j) + + findPaths(m, n, N - 1, i + 1, j) + + findPaths(m, n, N - 1, i, j - 1) + + findPaths(m, n, N - 1, i, j + 1); + } +}; + + +``` + + + + +```java +class Solution { + public int findPaths(int m, int n, int N, int i, int j) { + if (i == m || j == n || i < 0 || j < 0) return 1; + if (N == 0) return 0; + return findPaths(m, n, N - 1, i - 1, j) + + findPaths(m, n, N - 1, i + 1, j) + + findPaths(m, n, N - 1, i, j - 1) + + findPaths(m, n, N - 1, i, j + 1); + } +} +``` + + + + + +```python +class Solution: + def findPaths(self, m: int, n: int, N: int, i: int, j: int) -> int: + if i == m or j == n or i < 0 or j < 0: + return 1 + if N == 0: + return 0 + return (self.findPaths(m, n, N - 1, i - 1, j) + + self.findPaths(m, n, N - 1, i + 1, j) + + self.findPaths(m, n, N - 1, i, j - 1) + + self.findPaths(m, n, N - 1, i, j + 1)) + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(4^N)$ + +> **Reason**: Size of recursion tree will be $4^N$. Here, N refers to the number of moves allowed. + +### Space Complexity: $O(N)$ + +> **Reason**: The depth of the recursion tree can go upto N. + +### Approach 2: Recursion with Memoization +#### Algorithm +In the brute force approach, while going through the various branches of the recursion tree, we could reach the same position with the same number of moves left. + +Thus, a lot of redundant function calls are made with the same set of parameters leading to a useless increase in runtime. We can remove this redundancy by making use of a memoization array, memo. memo[i][j][k] is used to store the number of possible moves leading to a path out of the boundary if the current position is given by the indices (i,j) and number of moves left is k. + +Thus, now if a function call with some parameters is repeated, the memo array will already contain valid values corresponding to that function call resulting in pruning of the search space. + +## Code in Different Languages + + + + + +```cpp +#include +#include // For memset + +class Solution { +public: + int M = 1000000007; + + int findPaths(int m, int n, int N, int i, int j) { + std::vector>> memo(m, std::vector>(n, std::vector(N + 1, -1))); + return findPaths(m, n, N, i, j, memo); + } + +private: + int findPaths(int m, int n, int N, int i, int j, std::vector>>& memo) { + if (i == m || j == n || i < 0 || j < 0) return 1; + if (N == 0) return 0; + if (memo[i][j][N] >= 0) return memo[i][j][N]; + memo[i][j][N] = ( + (findPaths(m, n, N - 1, i - 1, j, memo) + findPaths(m, n, N - 1, i + 1, j, memo)) % M + + (findPaths(m, n, N - 1, i, j - 1, memo) + findPaths(m, n, N - 1, i, j + 1, memo)) % M + ) % M; + return memo[i][j][N]; + } +}; + +``` + + + + +```java +class Solution { + int M = 1000000007; + + public int findPaths(int m, int n, int N, int i, int j) { + int[][][] memo = new int[m][n][N + 1]; + for (int[][] l : memo) for (int[] sl : l) Arrays.fill(sl, -1); + return findPaths(m, n, N, i, j, memo); + } + + public int findPaths(int m, int n, int N, int i, int j, int[][][] memo) { + if (i == m || j == n || i < 0 || j < 0) return 1; + if (N == 0) return 0; + if (memo[i][j][N] >= 0) return memo[i][j][N]; + memo[i][j][N] = ( + (findPaths(m, n, N - 1, i - 1, j, memo) + findPaths(m, n, N - 1, i + 1, j, memo)) % M + + (findPaths(m, n, N - 1, i, j - 1, memo) + findPaths(m, n, N - 1, i, j + 1, memo)) % M + ) % M; + return memo[i][j][N]; + } +} +``` + + + + + +```python +class Solution: + M = 1000000007 + + def findPaths(self, m: int, n: int, N: int, i: int, j: int) -> int: + memo = [[[-1 for _ in range(N + 1)] for _ in range(n)] for _ in range(m)] + return self.findPathsMemo(m, n, N, i, j, memo) + + def findPathsMemo(self, m: int, n: int, N: int, i: int, j: int, memo: list) -> int: + if i == m or j == n or i < 0 or j < 0: + return 1 + if N == 0: + return 0 + if memo[i][j][N] >= 0: + return memo[i][j][N] + memo[i][j][N] = ( + (self.findPathsMemo(m, n, N - 1, i - 1, j, memo) + self.findPathsMemo(m, n, N - 1, i + 1, j, memo)) % self.M + + (self.findPathsMemo(m, n, N - 1, i, j - 1, memo) + self.findPathsMemo(m, n, N - 1, i, j + 1, memo)) % self.M + ) % self.M + return memo[i][j][N] + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(mnN)$ + +> **Reason**: We need to fill the memo array once with dimensions mΓ—nΓ—N. Here, m, n refer to the number of rows and columns of the given grid respectively. N refers to the total number of allowed moves. + +### Space Complexity: $O(mnN)$ + +> **Reason**: memo array of size mΓ—nΓ—N is used. + +## References + +- **LeetCode Problem**: [Out of Boundary Paths](https://leetcode.com/problems/out-of-boundary-paths/description/) + +- **Solution Link**: [Out of Boundary Paths](https://leetcode.com/problems/out-of-boundary-paths/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0583-Delete-operations-for-2-strings.md b/solutions/lc-solutions/0500-0599/0583-Delete-operations-for-2-strings.md new file mode 100644 index 0000000..4dac772 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0583-Delete-operations-for-2-strings.md @@ -0,0 +1,159 @@ +--- +id: delete-operations-for-2-strings +title: delete operations for 2 strings +sidebar_label: 583-delete operations for 2 strings +tags: +- Recursion +- Dynamic Programming +- Java +- Cpp +- Python +description: "Given two strings , return the min no of steps in which you can make one string to another." +--- + +## Problem + +Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same. + +In one step, you can delete exactly one character in either string. + +### Examples + +**Example 1:** + +**Input:** word1 = "sea", word2 = "eat" +**Output:** 2 +**Explanation:** You need one step to make "sea" to "ea" and another step to make "eat" to "ea". + +**Example 2:** + +**Input:** word1 = "leetcode", word2 = "etco" +**Output:** 4 + +### Constraints + +- `1 <= word1.length, word2.length <= 500` + - `word1` and `word2` consist of only lowercase English characters. + + + +--- + +## Approach + +In this we will try to find the longest common subsequence among them , then subtract the sum of the length of both the strings from the length of the lcs multiply by 2. + +### Steps: + +1. Create a 2D table dp of size (m+1) x (n+1), where m and n are the lengths of the two input strings. Initialize all elements in the table to -1, which will serve as a flag to indicate that no result has been stored yet. + +2. Fill the Memoization Table + +Iterate through the table and fill it with the results of subproblems. For each cell dp[i][j], consider the following cases: + +If i or j is 0, the longest common subsequence is 0 (since one of the strings is empty). +If the current characters at positions i-1 and j-1 in the two strings are the same, then the longest common subsequence is one more than the longest common subsequence of the substrings up to i-1 and j-1. +Otherwise, the longest common subsequence is the maximum of the longest common subsequences of the substrings up to i-1 and j, and the substrings up to i and j-1. +3. Read the Memoization Table + +The value at dp[m][n] represents the length of the longest common subsequence. You can use this value to construct the actual subsequence by tracing back the table from dp[m][n] to dp[0][0]. + +4. Construct the Longest Common Subsequence + +To construct the longest common subsequence, start from the bottom-right corner of the table and move diagonally up-left if the current characters match, or move up or left if they don’t. When you reach a cell with a value of -1, stop and backtrack to the previous cell. + +5. Calculation of the final ans + +To calculate the final ans we have to subtract the twice the length of the lcs from the sum of the length of both the strings. + +### Solution + +#### Java Solution + +```java +import java.util.Arrays; + +class Solution { + + public int longest(String s , String t , int ind1 , int ind2 , int [][]dp){ + if(ind1 <0 || ind2<0) return 0; + if(dp[ind1][ind2]!=-1) return dp[ind1][ind2]; + if(s.charAt(ind1)== t.charAt(ind2)) return dp[ind1][ind2] = 1 + longest(s , t ,ind1-1 , ind2-1 , dp); + else return dp[ind1][ind2] = Math.max(longest(s ,t, ind1-1 , ind2 , dp) , longest(s ,t , ind1 , ind2-1 , dp)); + } + public int minDistance(String word1, String word2) { + int n = word1.length(); + int m = word2.length(); + + int dp[][] = new int[n][m]; + for(int i[] : dp){ + Arrays.fill(i,-1); + } + int len = longest( word1 , word2, n-1 , m-1 , dp); + return (n+m) - 2*len; + } +} + + +``` +### C++ Solution + +```cpp +#include +using namespace std; + +class Solution { +public: + int longest(string s, string t, int ind1, int ind2, vector>& dp) { + if (ind1 < 0 || ind2 < 0) return 0; + if (dp[ind1][ind2] != -1) return dp[ind1][ind2]; + if (s[ind1] == t[ind2]) { + dp[ind1][ind2] = 1 + longest(s, t, ind1 - 1, ind2 - 1, dp); + } else { + dp[ind1][ind2] = max(longest(s, t, ind1 - 1, ind2, dp), longest(s, t, ind1, ind2 - 1, dp)); + } + return dp[ind1][ind2]; + } + + int minDistance(string word1, string word2) { + int n = word1.length(); + int m = word2.length(); + vector> dp(n, vector(m, -1)); + int length = longest(word1, word2, n - 1, m - 1, dp); + return (n + m) - 2 * length; + } +}; +``` +### Python Solution + +```python +class Solution: + + def longest(self, s, t, ind1, ind2, dp): + if ind1 < 0 or ind2 < 0: + return 0 + if dp[ind1][ind2] != -1: + return dp[ind1][ind2] + if s[ind1] == t[ind2]: + dp[ind1][ind2] = 1 + self.longest(s, t, ind1 - 1, ind2 - 1, dp) + else: + dp[ind1][ind2] = max(self.longest(s, t, ind1 - 1, ind2, dp), self.longest(s, t, ind1, ind2 - 1, dp)) + return dp[ind1][ind2] + + def minDistance(self, word1, word2): + n = len(word1) + m = len(word2) + dp = [[-1] * m for _ in range(n)] + length = self.longest(word1, word2, n - 1, m - 1, dp) + return (n + m) - 2 * length +``` + +### Complexity Analysis +**Time Complexity:** O(m * n) +>where n and m are lengths of the first and second string respectively. + +**Space Complexity:** O(n*m) +>Reason: We are using the extra space in the form of dp array. + +### References +**LeetCode Problem:** Delete operations for 2 strings \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0587-Erect-The-Fence.md b/solutions/lc-solutions/0500-0599/0587-Erect-The-Fence.md new file mode 100644 index 0000000..edaa688 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0587-Erect-The-Fence.md @@ -0,0 +1,279 @@ +--- +id: Erect The Fence +title: Erect The Fence +sidebar_label: Erect-The-Fence +tags: + - Algorithms + - Geometry + - Convex Hull +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Erect The Fence](https://leetcode.com/problems/Erect The Fence/description/) | [Erect The Fence Solution on LeetCode](https://leetcode.com/problems/Erect-The-Fence/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +You are given an array `trees` where `trees[i] = [xi, yi]` represents the location of a tree in the garden. + +Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if all the trees are enclosed. + +Return the coordinates of trees that are exactly located on the fence perimeter. You may return the answer in any order. + +### Example 1 + +**Input:**`trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]` +**Output:**`[[1,1],[2,0],[4,2],[3,3],[2,4]]` +**Explanation:** +All the trees will be on the perimeter of the fence except the tree at `[2, 2]`, which will be inside the fence. + +### Example 2 + +**Input:**`trees = [[1,2],[2,2],[4,2]]` +**Output:**`[[4,2],[2,2],[1,2]]` +**Explanation:** +The fence forms a line that passes through all the trees. + +## Constraints + +- `1 <= trees.length <= 3000` +- `trees[i].length == 2` +- `0 <= xi, yi <= 100` +- All the given positions are unique. + +## Approach + +To solve this problem, we can use the **Convex Hull** algorithm. Specifically, we will use the **Monotone Chain Algorithm** to find the convex hull of the given points. The convex hull is the smallest polygon that can enclose all the given points. + +### Steps: +1. **Sort the points**: Sort the array of points lexicographically (first by x-coordinate, and in case of a tie, by y-coordinate). +2. **Build the lower hull**: + - Initialize an empty list for the lower hull. + - Iterate over the sorted points and maintain the lower hull using a stack. + - Remove the last point from the stack if it makes a non-left turn with the next point. +3. **Build the upper hull**: + - Similarly, build the upper hull by iterating over the sorted points in reverse order. +4. **Combine the hulls**: Concatenate the lower and upper hulls to get the convex hull. + +## Solution in Different Languages + +### Solution in Python +```python +def outerTrees(trees): + def orientation(p, q, r): + return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]) + + trees.sort() + lower = [] + for tree in trees: + while len(lower) >= 2 and orientation(lower[-2], lower[-1], tree) < 0: + lower.pop() + lower.append(tree) + + upper = [] + for tree in reversed(trees): + while len(upper) >= 2 and orientation(upper[-2], upper[-1], tree) < 0: + upper.pop() + upper.append(tree) + + return list(set(lower + upper)) + +# Example Usage +trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] +print(outerTrees(trees)) +``` + +### Solution in Java +```java +import java.util.*; + +public class Solution { + public List outerTrees(int[][] trees) { + Arrays.sort(trees, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); + List lower = new ArrayList<>(), upper = new ArrayList<>(); + + for (int[] tree : trees) { + while (lower.size() >= 2 && orientation(lower.get(lower.size() - 2), lower.get(lower.size() - 1), tree) < 0) + lower.remove(lower.size() - 1); + lower.add(tree); + } + + for (int i = trees.length - 1; i >= 0; i--) { + int[] tree = trees[i]; + while (upper.size() >= 2 && orientation(upper.get(upper.size() - 2), upper.get(upper.size() - 1), tree) < 0) + upper.remove(upper.size() - 1); + upper.add(tree); + } + + Set result = new HashSet<>(lower); + result.addAll(upper); + return new ArrayList<>(result); + } + + private int orientation(int[] p, int[] q, int[] r) { + return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]); + } + + public static void main(String[] args) { + Solution sol = new Solution(); + int[][] trees = {{1, 1}, {2, 2}, {2, 0}, {2, 4}, {3, 3}, {4, 2}}; + List result = sol.outerTrees(trees); + for (int[] point : result) { + System.out.println(Arrays.toString(point)); + } + } +} +``` + +### Solution in C++ +```cpp +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector> outerTrees(vector>& trees) { + sort(trees.begin(), trees.end()); + vector> lower, upper; + + for (const auto& tree : trees) { + while (lower.size() >= 2 && orientation(lower[lower.size() - 2], lower[lower.size() - 1], tree) < 0) + lower.pop_back(); + lower.push_back(tree); + } + + for (int i = trees.size() - 1; i >= 0; i--) { + const auto& tree = trees[i]; + while (upper.size() >= 2 && orientation(upper[upper.size() - 2], upper[upper.size() - 1], tree) < 0) + upper.pop_back(); + upper.push_back(tree); + } + + set> result(lower.begin(), lower.end()); + result.insert(upper.begin(), upper.end()); + return vector>(result.begin(), result.end()); + } + +private: + int orientation(const vector& p, const vector& q, const vector& r) { + return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]); + } +}; +``` + +### Solution in C +```c +#include +#include + +typedef struct { + int x, y; +} Point; + +int compare(const void* a, const void* b) { + Point* p1 = (Point*)a; + Point* p2 = (Point*)b; + return (p1->x != p2->x) ? (p1->x - p2->x) : (p1->y - p2->y); +} + +int orientation(Point p, Point q, Point r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +void addPoint(Point* hull, int* size, Point p) { + while (*size >= 2 && orientation(hull[*size - 2], hull[*size - 1], p) < 0) { + (*size)--; + } + hull[(*size)++] = p; +} + +Point* outerTrees(Point* trees, int treesSize, int* returnSize) { + qsort(trees, treesSize, sizeof(Point), compare); + Point* hull = (Point*)malloc(treesSize * 2 * sizeof(Point)); + int size = 0; + + for (int i = 0; i < treesSize; i++) { + addPoint(hull, &size, trees[i]); + } + + for (int i = treesSize - 1, t = size + 1; i >= 0; i--) { + addPoint(hull, &size, trees[i]); + } + + *returnSize = size; + return hull; +} + +int main() { + Point trees[] = {{1, 1}, {2, 2}, {2, 0}, {2, 4}, {3, 3}, {4, 2}}; + int returnSize; + Point* result = outerTrees(trees, 6, &returnSize); + + for (int i = 0; i < returnSize; i++) { + printf("[%d, %d] ", result[i].x, result[i].y); + } + + free(result); + return 0; +} +``` + +### Solution in JavaScript +```javascript +function outerTrees(trees) { + function orientation(p, q, r) { + return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]); + } + + + + trees.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]); + const lower = []; + for (const tree of trees) { + while (lower.length >= 2 && orientation(lower[lower.length - 2], lower[lower.length - 1], tree) < 0) { + lower.pop(); + } + lower.push(tree); + } + + const upper = []; + for (let i = trees.length - 1; i >= 0; i--) { + const tree = trees[i]; + while (upper.length >= 2 && orientation(upper[upper.length - 2], upper[upper.length - 1], tree) < 0) { + upper.pop(); + } + upper.push(tree); + } + + const result = new Set([...lower, ...upper].map(JSON.stringify)); + return Array.from(result).map(JSON.parse); +} + +// Example Usage +const trees = [[1, 1], [2, 2], [2, 0], [2, 4], [3, 3], [4, 2]]; +console.log(outerTrees(trees)); +``` + +## Step by Step Algorithm + +1. **Sort the points**: First, sort the array of points lexicographically. +2. **Build the lower hull**: + - Initialize an empty list `lower`. + - Iterate over the sorted array and for each point, do the following: + - While there are at least two points in the `lower` list and the angle formed by the last two points and the current point makes a non-left turn, remove the last point from the `lower` list. + - Add the current point to the `lower` list. +3. **Build the upper hull**: + - Initialize an empty list `upper`. + - Iterate over the sorted array in reverse order and for each point, do the following: + - While there are at least two points in the `upper` list and the angle formed by the last two points and the current point makes a non-left turn, remove the last point from the `upper` list. + - Add the current point to the `upper` list. +4. **Combine the hulls**: Concatenate the `lower` and `upper` lists, remove duplicates, and return the result. + +## Conclusion + +The Convex Hull algorithm, specifically the Monotone Chain Algorithm, provides an efficient way to determine the minimum length of rope needed to fence a garden with given tree positions. This approach ensures that all trees are enclosed with the minimum perimeter, making it an optimal solution for this problem. \ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0589-N-ary-Tree-Preorder-Traversal.md b/solutions/lc-solutions/0500-0599/0589-N-ary-Tree-Preorder-Traversal.md new file mode 100644 index 0000000..ab95647 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0589-N-ary-Tree-Preorder-Traversal.md @@ -0,0 +1,157 @@ +--- +id: n-ary-tree-preorder-traversal +title: N-ary Tree Preorder Traversal(LeetCode) +sidebar_label: 0589-N-ary Tree Preorder Traversal +tags: + - Stack + - Tree + - Depth-first search +description: Given the root of an n-ary tree, return the preorder traversal of its nodes' values. +--- + +## Problem Statement + +Given the `root` of an n-ary tree, return the preorder traversal of its nodes' values. + +Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) + +### Examples + +**Example 1:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/10ac19a3-6628-46b8-99fe-1da89fa67210) + +```plaintext +Input: root = [1,null,3,2,4,null,5,6] +Output: [1,3,5,6,2,4] +``` + +**Example 2:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/b40bd1b8-ad90-47fc-b034-7aa97b4ca6a6) + +```plaintext +Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] +Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10] +``` + +### Constraints + +- The number of nodes in the tree is in the range `[0, 104]`. +- `0 <= Node.val <= 104` +- The height of the n-ary tree is less than or equal to `1000`. + +## Solution + +Preorder traversal is a common tree traversal method where the nodes are visited in the order: root, then the children from left to right. We will explore two approaches to perform preorder traversal on an N-ary tree: a recursive solution and an iterative solution. + +### Approach 1: Recursive Solution + +#### Algorithm + +1. Define a recursive function `dfs` that takes a node and an output list as arguments. +2. If the node is `None`, return immediately. +3. Append the value of the node to the output list. +4. Recursively call the `dfs` function on each child of the node. +5. The main function `preorder` initializes the output list and calls the `dfs` function with the root node. + +#### Implementation + +```Python +# Definition for a Node. +class Node(object): + def __init__(self, val=None, children=None): + self.val = val + self.children = children + +class Solution(object): + def preorder(self, root): + """ + :type root: Node + :rtype: List[int] + """ + + output = [] + + # Perform DFS on the root and get the output stack + self.dfs(root, output) + + # Return the output of all the nodes. + return output + + def dfs(self, root, output): + # If root is none, return + if root is None: + return + + # For preorder, we first add the root value + output.append(root.val) + + # Then add all the children to the output + for child in root.children: + self.dfs(child, output) +``` + +### Complexity Analysis + +- **Time complexity**: $O(N)$ - where N is the number of nodes in the tree. Each node is visited exactly once. +- **Space complexity**: $O(H)$ - where H is the height of the tree. This is due to the recursion stack. + +### Approach 2: Iterative Solution + +#### Algorithm + +1. Initialize a stack with the root node. +2. Initialize an empty output list. +3. While the stack is not empty: +* Pop the last element from the stack and append its value to the output list. +* Extend the stack with the children of the popped node in reverse order. +4. Return the output list. + +#### Implementation + +```Python +# Definition for a Node. +class Node(object): + def __init__(self, val=None, children=None): + self.val = val + self.children = children + +class Solution(object): + def preorder(self, root): + """ + :type root: Node + :rtype: List[int] + """ + if root is None: + return [] + + stack = [root] + output = [] + + # Till there is an element in the stack, the loop runs. + while stack: + # Pop the last element from the stack and store it into temp. + temp = stack.pop() + + # Append the value of temp to output + output.append(temp.val) + + # Add the children of the temp into the stack in reverse order. + # Children of 1 = [3, 2, 4], if not reversed then 4 will be popped out first from the stack. + # If reversed then stack = [4, 2, 3]. Here 3 will pop out first. + # This continues till the stack is empty. + stack.extend(temp.children[::-1]) + + # Return the output + return output +``` + +### Complexity Analysis + +- **Time complexity**: $O(N)$ +- **Space complexity**: $O(N) + +### Conclusion + +Both the recursive and iterative solutions for preorder traversal of an N-ary tree have similar time complexities of O(N), making them efficient for large trees. The recursive solution has a space complexity of O(H), making it potentially less efficient for deep trees due to the recursion stack. The iterative solution has a space complexity of O(N), which can handle all nodes without the risk of a stack overflow. The choice between the two approaches depends on the specific constraints and requirements of the problem at hand. diff --git a/solutions/lc-solutions/0500-0599/0590-N-ary-Tree-Postorder-Traversal.md b/solutions/lc-solutions/0500-0599/0590-N-ary-Tree-Postorder-Traversal.md new file mode 100644 index 0000000..0bbcaa4 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0590-N-ary-Tree-Postorder-Traversal.md @@ -0,0 +1,127 @@ +--- +id: n-ary-tree-postorder-traversal +title: N-ary Tree Postorder Traversal(LeetCode) +sidebar_label: 0590-N-ary Tree Postorder Traversal +tags: + - Stack + - Tree + - Depth-first Search +description: Given the root of an n-ary tree, return the postorder traversal of its nodes' values. +--- + +## Problem Statement + +Given the `root` of an n-ary tree, return the postorder traversal of its nodes' values. + +Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) + +### Examples + +**Example 1:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/e09ffccb-f2c1-4e3f-9a4b-e554cc82ff86) + +```plaintext +Input: root = [1,null,3,2,4,null,5,6] +Output: [5,6,3,2,4,1] +``` + +**Example 2:** + +![image](https://github.com/PradnyaGaitonde/codeharborhub.github.io/assets/116059908/d38f03bc-d137-45ba-980c-763da4a0901c) + +```plaintext +Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] +Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1] +``` + +### Constraints + +- The number of nodes in the tree is in the range `[0, 104]`. +- `0 <= Node.val <= 104` +- The height of the n-ary tree is less than or equal to `1000`. + +## Solution + +Postorder traversal is another common tree traversal method where the nodes are visited in the order: all children from left to right, then the root. We will explore two approaches to perform postorder traversal on an N-ary tree: an iterative solution and a recursive solution. + +### Approach 1: Iterative Solution + +#### Algorithm + +1. Initialize an empty `list` list to store the result. +2. If the root is `null`, return the empty list. +3. Initialize a stack and push the root node onto the stack. +4. While the stack is not empty: +* Pop the last element from the stack. +* Append the value of the popped node to the list. +* Push all children of the popped node onto the stack. +5. Reverse the list to get the correct postorder traversal. +6. Return the list. + +#### Implementation + +```Java +class Solution { + public List postorder(Node root) { + List list = new ArrayList<>(); + if (root == null) return list; + + Stack stack = new Stack<>(); + stack.add(root); + + while (!stack.isEmpty()) { + root = stack.pop(); + list.add(root.val); + for (Node node: root.children) + stack.add(node); + } + Collections.reverse(list); + return list; + } +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(N)$ +- **Space complexity**: $O(N)$ + +### Approach 2: Recursive Solution + +#### Algorithm + +1. Initialize an empty list `list` to store the result. +2. Define a recursive function `postorder` that takes a node as an argument. +3. If the node is `null`, return the list. +4. Recursively call the `postorder` function on each child of the node. +5. Append the value of the node to the list after visiting all children. +6. Return the list. + +#### Implementation + +```Java +class Solution { + List list = new ArrayList<>(); + public List postorder(Node root) { + if (root == null) + return list; + + for (Node node: root.children) + postorder(node); + + list.add(root.val); + + return list; + } +} +``` + +### Complexity Analysis + +- **Time complexity**: $O(N)$ +- **Space complexity**: $O(H)$ + +### Conclusion + +Both the iterative and recursive solutions for postorder traversal of an N-ary tree have similar time complexities of O(N), making them efficient for large trees. The recursive solution has a space complexity of O(H), making it potentially less efficient for deep trees due to the recursion stack. The iterative solution has a space complexity of O(N), which can handle all nodes without the risk of a stack overflow. The choice between the two approaches depends on the specific constraints and requirements of the problem at hand. diff --git a/solutions/lc-solutions/0500-0599/0591-tag-validator.md b/solutions/lc-solutions/0500-0599/0591-tag-validator.md new file mode 100644 index 0000000..30d0015 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0591-tag-validator.md @@ -0,0 +1,302 @@ +--- +id: tag-validator +title: Tag Validator +sidebar_label: 0591 - Tag Validator +tags: + - Iterator + - Stack + - String +description: "This is a solution to the Tag Validator problem on LeetCode." +--- + +## Problem Description + +Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. + +A code snippet is valid if all the following rules hold: + +1. The code must be wrapped in a **valid closed tag**. Otherwise, the code is invalid. +2. A **closed tag** (not necessarily valid) has exactly the following format : `TAG_CONTENT`. Among them, `` is the start tag, and `` is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is **valid** if and only if the TAG_NAME and TAG_CONTENT are valid. +3. A **valid** `TAG_NAME` only contain **upper-case letters**, and has length in range [1,9]. Otherwise, the `TAG_NAME` is **invalid**. +4. A **valid** `TAG_CONTENT` may contain other **valid closed tags, cdata** and any characters (see note1) **EXCEPT** unmatched `<`, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the `TAG_CONTENT` is **invalid**. +5. A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested. +6. A `<` is unmatched if you cannot find a subsequent `>`. And when you find a `<` or `` should be parsed as TAG_NAME (not necessarily valid). +7. The cdata has the following format : ``. The range of `CDATA_CONTENT` is defined as the characters between ``. +8. `CDATA_CONTENT` may contain **any characters**. The function of cdata is to forbid the validator to parse `CDATA_CONTENT`, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as **regular characters**. + +### Examples +**Example 1:** + +``` +Input: code = "
This is the first line ]]>
" +Output: true +Explanation: +The code is wrapped in a closed tag :
and
. +The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. +Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. +So TAG_CONTENT is valid, and then the code is valid. Thus return true. +``` + +**Example 2:** + +``` +Input: code = "
>> ![cdata[]] ]>]]>]]>>]
" +Output: true +Explanation: +We first separate the code into : start_tag|tag_content|end_tag. +start_tag -> "
" +end_tag -> "
" +tag_content could also be separated into : text1|cdata|text2. +text1 -> ">> ![cdata[]] " +cdata -> "]>]]>", where the CDATA_CONTENT is "
]>" +text2 -> "]]>>]" +The reason why start_tag is NOT "
>>" is because of the rule 6. +The reason why cdata is NOT "]>]]>]]>" is because of the rule 7. +``` + +### Constraints + +- `1 <= code.length <= 500` +- `code` consists of English letters, digits, `'<'`, `'>'`, `'/'`, `'!'`, `'['`, `']'`, `'.'`, and `' '`. + +## Solution for Tag Validator + +### Approach: Stack +Summarizing the given problem, we can say that we need to determine whether a tag is valid or not, by checking the following properties. + +1. The code should be wrapped in a valid closed tag. + +2. The `TAG_NAME` should be valid. + +3. The `TAG_CONTENT` should be valid. + +4. The cdata should be valid. + +5. All the tags should be closed. i.e. each start-tag should have a corresponding end-tag and vice-versa and the order of the tags should be correct as well. + +In order to check the validity of all these, firstly, we need to identify which parts of the given code string act as which part from the above-mentioned categories. To understand how it's done, we'll go through the implementation and the reasoning behind it step by step. + +We iterate over the given code string. Whenever a `<` is encountered(unless we are currently inside ``), it indicates the beginning of either a `TAG_NAME`(start tag or end tag) or the beginning of cdata as per the conditions given in the problem statement. + +If the character immediately following this `<` is an `!`, the characters following this `<` can't be a part of a valid `TAG_NAME`, since only upper-case letters(in case of a start tag) or `/` followed by upper-case letters(in the case of an end tag). Thus, the choice now narrows down to only **cdata**. Thus, we need to check if the current bunch of characters following `` following the current `` exists, the code string is considered as invalid. Apart from this, the `` do not have any constraints on them. + +If the character immediately following the `<` encountered isn't an `!`, this `<` can only mark the beginning of `TAG_NAME`. Now, since a valid start tag can't contain anything except upper-case letters if a `/` is found after `<`, the `` following the `<` to find out the substring(say s), that constitutes the `TAG_NAME`. This s should satisfy all the criteria to constitute a valid `TAG_NAME`. Thus, for every such s, we check if it contains all upper-case letters and also check its length(It should be between 1 to 9). If any of the criteria isn't fulfilled, s doesn't constitute a valid `TAG_NAME`. Hence, the code string turns out to be invalid as well. + +Apart from checking the validity of the `TAG_NAME`, we also need to ensure that the tags always exist in pairs. i.e. for every start-tag, a corresponding end-tag should always exist. Further, we can note that in case of multiple `TAG_NAME`'s, the `TAG_NAME` whose start-tag comes later than the other ones, should have its end-tag appearing before the end-tags of those other `TAG_NAME`'s. i.e. the tag that starts later should end first. + +From this, we get the intuition that we can make use of a stack to check the existence of matching start and end-tags. Thus, whenever we find out a valid start-tag, as mentioned above, we push its `TAG_NAME` string onto a stack. Now, whenever an end-tag is found, we compare its `TAG_NAME` with the `TAG_NAME` at the top of the stack and remove this element from the stack. If the two don't match, this implies that either the current end-tag has no corresponding start-tag or there is a problem with the ordering of the tags. The two need to match for the tag-pair to be valid since there can't exist an end-tag without a corresponding start-tag and vice-versa. Thus, if a match isn't found, we can conclude that the given code string is invalid. + +Now, after the complete code string has been traversed, the stack should be empty if all the start-tags have their corresponding end-tags as well. If the stack isn't empty, this implies that some start-tag doesn't have the corresponding end-tag, violating the closed-tag's validity condition. + +Further, we also need to ensure that the given code is completely enclosed within closed tags. For this, we need to ensure that the first **cdata** found is also inside the closed tags. Thus, when we find a possibility of the presence of **cdata**, we proceed further only if we've already found a start tag, indicated by a non-empty stack. Further, to ensure that no data lies after the last end-tag, we need to ensure that the stack doesn't become empty before we reach the end of the given code string since an empty stack indicates that the last end-tag has been encountered. +## Code in Different Languages + + + + + +```cpp +#include +#include + +class Solution { +private: + std::stack stack; + bool contains_tag = false; + + bool isValidTagName(std::string s, bool ending) { + if (s.length() < 1 || s.length() > 9) + return false; + for (int i = 0; i < s.length(); i++) { + if (!isupper(s[i])) + return false; + } + if (ending) { + if (!stack.empty() && stack.top() == s) + stack.pop(); + else + return false; + } else { + contains_tag = true; + stack.push(s); + } + return true; + } + + bool isValidCdata(std::string s) { + return s.find("[CDATA[") == 0; + } + +public: + bool isValid(std::string code) { + if (code[0] != '<' || code[code.length() - 1] != '>') + return false; + for (int i = 0; i < code.length(); i++) { + bool ending = false; + int closeindex; + if (stack.empty() && contains_tag) + return false; + if (code[i] == '<') { + if (!stack.empty() && code[i + 1] == '!') { + closeindex = code.find("]]>", i + 1); + if (closeindex < 0 || !isValidCdata(code.substr(i + 2, closeindex - i - 2))) + return false; + } else { + if (code[i + 1] == '/') { + i++; + ending = true; + } + closeindex = code.find('>', i + 1); + if (closeindex < 0 || !isValidTagName(code.substr(i + 1, closeindex - i - 1), ending)) + return false; + } + i = closeindex; + } + } + return stack.empty() && contains_tag; + } +}; + + +``` + + + + +```java +public class Solution { + Stack < String > stack = new Stack < > (); + boolean contains_tag = false; + public boolean isValidTagName(String s, boolean ending) { + if (s.length() < 1 || s.length() > 9) + return false; + for (int i = 0; i < s.length(); i++) { + if (!Character.isUpperCase(s.charAt(i))) + return false; + } + if (ending) { + if (!stack.isEmpty() && stack.peek().equals(s)) + stack.pop(); + else + return false; + } else { + contains_tag = true; + stack.push(s); + } + return true; + } + public boolean isValidCdata(String s) { + return s.indexOf("[CDATA[") == 0; + } + public boolean isValid(String code) { + if (code.charAt(0) != '<' || code.charAt(code.length() - 1) != '>') + return false; + for (int i = 0; i < code.length(); i++) { + boolean ending = false; + int closeindex; + if(stack.isEmpty() && contains_tag) + return false; + if (code.charAt(i) == '<') { + if (!stack.isEmpty() && code.charAt(i + 1) == '!') { + closeindex = code.indexOf("]]>", i + 1); + if (closeindex < 0 || !isValidCdata(code.substring(i + 2, closeindex))) + return false; + } else { + if (code.charAt(i + 1) == '/') { + i++; + ending = true; + } + closeindex = code.indexOf('>', i + 1); + if (closeindex < 0 || !isValidTagName(code.substring(i + 1, closeindex), ending)) + return false; + } + i = closeindex; + } + } + return stack.isEmpty() && contains_tag; + } +} +``` + + + + + +```python +class Solution: + def __init__(self): + self.stack = [] + self.contains_tag = False + + def isValidTagName(self, s, ending): + if len(s) < 1 or len(s) > 9: + return False + if not all(c.isupper() for c in s): + return False + if ending: + if self.stack and self.stack[-1] == s: + self.stack.pop() + else: + return False + else: + self.contains_tag = True + self.stack.append(s) + return True + + def isValidCdata(self, s): + return s.startswith("[CDATA[") + + def isValid(self, code): + if code[0] != '<' or code[-1] != '>': + return False + i = 0 + while i < len(code): + ending = False + if not self.stack and self.contains_tag: + return False + if code[i] == '<': + if self.stack and code[i + 1] == '!': + closeindex = code.find("]]>", i + 1) + if closeindex < 0 or not self.isValidCdata(code[i + 2:closeindex]): + return False + else: + if code[i + 1] == '/': + i += 1 + ending = True + closeindex = code.find('>', i + 1) + if closeindex < 0 or not self.isValidTagName(code[i + 1:closeindex], ending): + return False + i = closeindex + i += 1 + return not self.stack and self.contains_tag + + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: We traverse over the given code string of length N. + +### Space Complexity: $O(N)$ + +> **Reason**: The stack can grow upto a size of n/3 in the worst case. e.g. In case of ``, N=12 and number of tags = 12/3 = 4. + +## References + +- **LeetCode Problem**: [Tag Validator](https://leetcode.com/problems/tag-validator/description/) + +- **Solution Link**: [Tag Validator](https://leetcode.com/problems/tag-validator/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0592-fraction-addition-and-subtraction.md b/solutions/lc-solutions/0500-0599/0592-fraction-addition-and-subtraction.md new file mode 100644 index 0000000..6f2986d --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0592-fraction-addition-and-subtraction.md @@ -0,0 +1,262 @@ +--- +id: fraction-addition-and-subtraction +title: Fraction Addition and Subtraction +sidebar_label: 0592 - Fraction Addition and Subtraction +tags: + - Math + - Simulation + - String +description: "This is a solution to the Fraction Addition and Subtraction problem on LeetCode." +--- + +## Problem Description + +Given a string `expression` representing an expression of fraction addition and subtraction, return the calculation result in string format. + +The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator `1`. So in this case, `2` should be converted to `2/1`. + +### Examples +**Example 1:** + +``` +Input: expression = "-1/2+1/2" +Output: "0/1" +``` + +**Example 2:** + +``` +Input: expression = "-1/2+1/2+1/3" +Output: "1/3 +``` + +### Constraints + +- The input string only contains `'0'` to `'9'`, `'/'`, `'+'` and `'-'`. So does the output. +- Each fraction (input and output) has the format `Β±numerator/denominator`. If the first input fraction or the output is positive, then `'+'` will be omitted. +- The input only contains valid **irreducible** fractions, where the **numerator** and **denominator** of each fraction will always be in the range `[1, 10]`. If the denominator is `1`, it means this fraction is actually an integer in a fraction format defined above. +- The number of given fractions will be in the range `[1, 10]`. +- The numerator and denominator of the **final result** are guaranteed to be valid and in the range of **32-bit** int. + +## Solution for Fraction Addition and Subtraction + +### Approach 1: Using LCM +The first obvious step to be undertaken is to split the given string into individual fractions. We split the string based on `+` and `-` sign. We store the signs in the order in which they appear in the string in sign array. Further, after getting the individual fractions, we further split the fractions based on `/` sign. Thus, we obtain the individual numerator and denominator parts. We store the same in num and den arrays respectively. + +Now, we've got the data ready to be worked upon. In order to see the method we've used in this implementation, we'll take an example and understand the way we work on it. + +Let's say, the given fraction is: + +$$\frac{3}{2}+\frac{5}{3}-\frac{7}{6}$$ + +We need to equalize all the denominators so as to be able to add and subtract the numerators easily. The nearest value the denominators can be scaled upto is the LCM of all the denominators. Thus, we need to find the LCM of all the denominators and then multiply all the denominators with appropriate integer factors to make them equal to the LCM. But, in order to keep the individual fraction values unchanged, we need to multiply the individual numerators also with the same factors. +In order to find the LCM, we can go as follows. We use the method lcm(a,b,c)=lcm(lcm(a,b),c). Thus, if we can compute the lcm of two denominators, we can keep on repeating the process iteratively over the denominators to get the overall lcm. To find the lcm of two numbers a and b, we use lcm(a,b)=(aβˆ—b)/gcd(a,b). For the above example, the lcm turns out to be 6. +Thus, we scale up the denominators to 6 as follows: + +$$\frac{3*3}{2*3}+\frac{5*2}{3*2}-\frac{7}{6}$$ + +Thus, we can observe that, the scaling factor for a fraction $$\frac{num}{den}$$ is given by: $numβˆ—x/den*x$, where x is the corresponding scaling factor. Note that, $denβˆ—x=lcm$. Thus, $x=lcm/denx$. Thus, we find out the corresponding scaling factor $x_i$ for each fraction. + +After this, we can directly add or subtract the new scaled numerators. + +In the current example, we obtain $$\frac{12}{6}$$ as the result. Now, we need to convert this into an irreducible fraction. Thus, if we obtain $$\frac{num_i}{den_i}$$ as the final result, we need to find a largest factor y, which divides both $num_i$ and $den_i$. Such a number, as we know, is the gcd of $num_i$ and $den_i$. + +Thus, to convert the result $$\frac{num_i}{den_i}$$ we divide both the numerator and denominator by the gcd of the two numbers y to obtain the final irreducible $$\frac{num_i/y}{den_i/y}$$ + +Note: A problem with this approach is that we find the lcm of all the denominators in a single go and then reduce the overall fraction at the end. Thus, the lcm value could become very large and could lead to an overflow. But, this solution suffices for the current range of numbers. + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include +#include + +class Solution { +public: + std::string fractionAddition(std::string expression) { + std::vector sign; + for (int i = 1; i < expression.length(); i++) { + if (expression[i] == '+' || expression[i] == '-') + sign.push_back(expression[i]); + } + std::vector num, den; + std::istringstream iss(expression); + std::string sub, subsub; + while (std::getline(iss, sub, '+')) { + std::istringstream iss2(sub); + while (std::getline(iss2, subsub, '-')) { + if (!subsub.empty()) { + std::size_t pos = subsub.find('/'); + num.push_back(std::stoi(subsub.substr(0, pos))); + den.push_back(std::stoi(subsub.substr(pos + 1))); + } + } + } + if (expression[0] == '-') num[0] = -num[0]; + int lcm = 1; + for (int x : den) { + lcm = lcm_(lcm, x); + } + + int res = lcm / den[0] * num[0]; + for (int i = 1; i < num.size(); i++) { + if (sign[i - 1] == '+') res += lcm / den[i] * num[i]; + else res -= lcm / den[i] * num[i]; + } + int g = gcd(std::abs(res), std::abs(lcm)); + return std::to_string(res / g) + "/" + std::to_string(lcm / g); + } + +private: + int lcm_(int a, int b) { + return a * b / gcd(a, b); + } + + int gcd(int a, int b) { + while (b != 0) { + int t = b; + b = a % b; + a = t; + } + return a; + } +}; + +``` + + + + +```java +class Solution { + public String fractionAddition(String expression) { + List sign = new ArrayList<>(); + for (int i = 1; i < expression.length(); i++) { + if (expression.charAt(i) == '+' || expression.charAt(i) == '-') + sign.add(expression.charAt(i)); + } + List num = new ArrayList<>(); + List den = new ArrayList<>(); + for (String sub : expression.split("\\+")) { + for (String subsub : sub.split("-")) { + if (subsub.length() > 0) { + String[] fraction = subsub.split("/"); + num.add(Integer.parseInt(fraction[0])); + den.add(Integer.parseInt(fraction[1])); + } + } + } + if (expression.charAt(0) == '-') num.set(0, -num.get(0)); + int lcm = 1; + for (int x : den) { + lcm = lcm_(lcm, x); + } + + int res = lcm / den.get(0) * num.get(0); + for (int i = 1; i < num.size(); i++) { + if (sign.get(i - 1) == '+') res += lcm / den.get(i) * num.get(i); + else res -= lcm / den.get(i) * num.get(i); + } + int g = gcd(Math.abs(res), Math.abs(lcm)); + return (res / g) + "/" + (lcm / g); + } + + public int lcm_(int a, int b) { + return a * b / gcd(a, b); + } + + public int gcd(int a, int b) { + while (b != 0) { + int t = b; + b = a % b; + a = t; + } + return a; + } +} +``` + + + + + +```python +from typing import List + +class Solution: + def fractionAddition(self, expression: str) -> str: + sign: List[str] = [] + for i in range(1, len(expression)): + if expression[i] in ['+', '-']: + sign.append(expression[i]) + + num: List[int] = [] + den: List[int] = [] + for sub in expression.split('+'): + for subsub in sub.split('-'): + if subsub: + fraction = subsub.split('/') + num.append(int(fraction[0])) + den.append(int(fraction[1])) + + if expression[0] == '-': + num[0] = -num[0] + + lcm = 1 + for x in den: + lcm = self.lcm(lcm, x) + + res = lcm // den[0] * num[0] + for i in range(1, len(num)): + if sign[i-1] == '+': + res += lcm // den[i] * num[i] + else: + res -= lcm // den[i] * num[i] + + g = self.gcd(abs(res), abs(lcm)) + return f"{res // g}/{lcm // g}" + + def lcm(self, a: int, b: int) -> int: + return a * b // self.gcd(a, b) + + def gcd(self, a: int, b: int) -> int: + while b != 0: + t = b + b = a % b + a = t + return a +``` + + + +## Complexity Analysis + +### Time Complexity: $O(nlogx)$ + +> **Reason**: Euclidean GCD algorithm takes O(log⁑(ab)) time for finding gcd of two numbers a and b. Here n refers to the number of fractions in the input string and x is the maximum possible value of denominator. + +### Space Complexity: $O(n)$ + +> **Reason**: Size of num, denand sign list grows upto n. + +## References + +- **LeetCode Problem**: [Fraction Addition and Subtraction](https://leetcode.com/problems/fraction-addition-and-subtraction/description/) + +- **Solution Link**: [Fraction Addition and Subtraction](https://leetcode.com/problems/fraction-addition-and-subtraction/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0593-valid-square.md b/solutions/lc-solutions/0500-0599/0593-valid-square.md new file mode 100644 index 0000000..735cf14 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0593-valid-square.md @@ -0,0 +1,150 @@ +--- +id: valid-square +title: Valid Square +sidebar_label: 0593 - Valid Square +tags: + - Math + - Geometry + - Sorting +description: "This is a solution to the Valid Square problem on LeetCode." +--- + +## Problem Description + +Given the coordinates of four points in 2D space `p1`, `p2`, `p3` and `p4`, return `true` if the four points construct a square. + +The coordinate of a point pi is represented as `[xi, yi]`. The input is **not** given in any order. + +A **valid square** has four equal sides with positive length and four equal angles (90-degree angles). + +### Examples +**Example 1:** + +``` +Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] +Output: true +``` + +**Example 2:** + +``` +Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12] +Output: false +``` + +### Constraints + +- `p1.length == p2.length == p3.length == p4.length == 2` +- $-10^4 <= xi, yi <= 10^4$ + +## Solution for Valid Square +### Approach: Using Sorting + +We can make use of maths to simplify this problem a bit. If we sort the given set of points based on their x-coordinate values, and in the case of a tie, based on their y-coordinate value, we can obtain an arrangement, which directly reflects the arrangement of points on a valid square boundary possible. + +Consider the only possible cases as shown in the figure below: +![image](https://assets.leetcode.com/static_assets/media/original_images/593_Valid_Square_1.PNG) +In each case, after sorting, we obtain the following conclusion regarding the connections of the points: + +1. p0p1, p1p3, p3p2 and p2p0 form the four sides of any valid square. + +2. p0p3 and p1p2 form the diagonals of the square. + +Thus, once the sorting of the points is done, based on the above knowledge, we can directly compare p0p1, p1p3, p3p2 and p2p0 or equality of lengths(corresponding to the sides); and p0p3 and p1p2 for equality of lengths(corresponding to the diagonals). + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +public: + double dist(std::vector& p1, std::vector& p2) { + return (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[0] - p1[0]) * (p2[0] - p1[0]); + } + bool validSquare(std::vector& p1, std::vector& p2, std::vector& p3, std::vector& p4) { + std::vector> p = {p1, p2, p3, p4}; + std::sort(p.begin(), p.end(), [](const std::vector& l1, const std::vector& l2) { + return l1[0] != l2[0] ? l1[0] < l2[0] : l1[1] < l2[1]; + }); + return dist(p[0], p[1]) != 0 && dist(p[0], p[1]) == dist(p[1], p[3]) && dist(p[1], p[3]) == dist(p[3], p[2]) && dist(p[3], p[2]) == dist(p[2], p[0]) && dist(p[0], p[3]) == dist(p[1], p[2]); + } +}; + + +``` + + + + +```java +public class Solution { + public double dist(int[] p1, int[] p2) { + return (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[0] - p1[0]) * (p2[0] - p1[0]); + } + public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) { + int[][] p={p1,p2,p3,p4}; + Arrays.sort(p, (l1, l2) -> l2[0] == l1[0] ? l1[1] - l2[1] : l1[0] - l2[0]); + return dist(p[0], p[1]) != 0 && dist(p[0], p[1]) == dist(p[1], p[3]) && dist(p[1], p[3]) == dist(p[3], p[2]) && dist(p[3], p[2]) == dist(p[2], p[0]) && dist(p[0],p[3])==dist(p[1],p[2]); + } +} + +``` + + + + + +```python +import math + +class Solution: + def dist(self, p1, p2): + return (p2[1] - p1[1]) ** 2 + (p2[0] - p1[0]) ** 2 + + def validSquare(self, p1, p2, p3, p4): + points = [p1, p2, p3, p4] + points.sort(key=lambda x: (x[0], x[1])) + + return self.dist(points[0], points[1]) != 0 and \ + self.dist(points[0], points[1]) == self.dist(points[1], points[3]) and \ + self.dist(points[1], points[3]) == self.dist(points[3], points[2]) and \ + self.dist(points[3], points[2]) == self.dist(points[2], points[0]) and \ + self.dist(points[0], points[3]) == self.dist(points[1], points[2]) + + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(1)$ + +> **Reason**: Sorting 4 points takes constant time. + +### Space Complexity: $O(1)$ + +> **Reason**: Constant space is required. + +## References + +- **LeetCode Problem**: [Valid Square](https://leetcode.com/problems/valid-square/description/) + +- **Solution Link**: [Valid Square](https://leetcode.com/problems/valid-square/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/0599-minimum-index-sum-of-two-lists.md b/solutions/lc-solutions/0500-0599/0599-minimum-index-sum-of-two-lists.md new file mode 100644 index 0000000..19ffbcd --- /dev/null +++ b/solutions/lc-solutions/0500-0599/0599-minimum-index-sum-of-two-lists.md @@ -0,0 +1,265 @@ +--- +id: minimum-index-sum-of-two-lists +title: Minimum Index Sum of Two Lists +sidebar_label: 0599 - Minimum Index Sum of Two Lists +tags: + - Hash Table + - Array + - Heap (Priority Queue) +description: "This is a solution to the Minimum Index Sum of Two Lists problem on LeetCode." +--- + +## Problem Description + +Given two arrays of strings `list1` and `list2`, find the **common strings with the least index sum**. + +A **common string** is a string that appeared in both `list1` and `list2`. + +A **common string with the least index sum** is a common string such that if it appeared at `list1[i]` and `list2[j]` then `i + j` should be the minimum value among all the other **common strings**. + +Return all the **common strings with the least index sum**. Return the answer in **any order**. + +### Examples +**Example 1:** + +``` +Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"] +Output: ["Shogun"] +Explanation: The only common string is "Shogun". +``` + +**Example 2:** + +``` +Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Shogun","Burger King"] +Output: ["Shogun"] +Explanation: The common string with the least index sum is "Shogun" with index sum = (0 + 1) = 1. +``` + +### Constraints + +- `1 <= list1.length, list2.length <= 1000` +- `1 <= list1[i].length, list2[i].length <= 30` +- `list1[i]` and `list2[i]` consist of spaces `' '` and English letters. +- All the strings of `list1` are **unique**. +- All the strings of `list2` are **unique**. +- There is at least a common string between `list1` and `list2`. + +## Solution for Minimum Index Sum of Two Lists +### Approach #1 Using HashMap + +In this approach, we compare every string in list1 and list2 by traversing over the whole list list2 for every string chosen from list1. We make use of a hashmap map, which contains elements of the form $$(sum:list_{sum})$$. Here, sum refers to the sum of indices of matching elements and $$list_{sum}$$ refers to the list of matching strings whose indices' sum equals sumsumsum. + +Thus, while doing the comparisons, whenever a match between a string at $i^{th}$ index of list1 and $j^{th}$ index of list2 is found, we make an entry in the map corresponding to the sum $i+j$, if this entry isn't already present. If an entry with this sum already exists, we need to keep a track of all the strings which lead to the same index sum. Thus, we append the current string to the list of strings corresponding to sum $i+j$. + +At the end, we traverse over the keys of the map and find out the list of strings corresponding to the key reprsenting the minimum sum. + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include +#include +#include + +class Solution { +public: + std::vector findRestaurant(std::vector& list1, std::vector& list2) { + std::unordered_map> map; + for (int i = 0; i < list1.size(); ++i) { + for (int j = 0; j < list2.size(); ++j) { + if (list1[i] == list2[j]) { + int sum = i + j; + map[sum].push_back(list1[i]); + } + } + } + int min_index_sum = INT_MAX; + for (const auto& pair : map) { + min_index_sum = std::min(min_index_sum, pair.first); + } + return map[min_index_sum]; + } +}; + +``` + + + + +```java +public class Solution { + public String[] findRestaurant(String[] list1, String[] list2) { + HashMap < Integer, List < String >> map = new HashMap < > (); + for (int i = 0; i < list1.length; i++) { + for (int j = 0; j < list2.length; j++) { + if (list1[i].equals(list2[j])) { + if (!map.containsKey(i + j)) + map.put(i + j, new ArrayList < String > ()); + map.get(i + j).add(list1[i]); + } + } + } + int min_index_sum = Integer.MAX_VALUE; + for (int key: map.keySet()) + min_index_sum = Math.min(min_index_sum, key); + String[] res = new String[map.get(min_index_sum).size()]; + return map.get(min_index_sum).toArray(res); + } +} + +``` + + + + + +```python +from typing import List +from collections import defaultdict + +class Solution: + def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: + index_map = defaultdict(list) + for i, rest1 in enumerate(list1): + for j, rest2 in enumerate(list2): + if rest1 == rest2: + index_map[i + j].append(rest1) + + min_index_sum = min(index_map.keys()) + return index_map[min_index_sum] +``` + + + +## Complexity Analysis + +### Time Complexity: $O(l_1 * l_2 * x)$ + +> **Reason**: Every item of list1 is compared with all the items of list2. $l_1$ and $l_2$ are the lengths of list1 and list2 respectively. And x refers to average string length. + +### Space Complexity: $O(l_1 * l_2 * x)$ + +> **Reason**: In worst case all items of list1 and list2 are same. In that case, hashmap size grows upto $l_1βˆ—l_2βˆ—x$, where x refers to average string length + +### Approach #2 Without Using HashMap +#### Algorithm + +Another method could be to traverse the various sum(index sum) values and determine if any such string exists in list1 and list2 such that the sum of its indices in the two lists equals sum. + +Now, we know that the value of index sum could range from 0 to m + n - 1. Here, m and n refer to the length of lists list1 and list2 respectively. Thus, we choose every value of sum in ascending order. For every sum chosen, we iterate over list1. Suppose, currently the string at the ith index in list1 is being considered. Now, in order for the index sum to be the one corresponding to matching strings in list1 and list2, the string at index j in list2 should match the string at index i in list1, such that sum = i + j. + +Or, stating in other terms, the string at index j in list2 should be equal to the string at index i in list1, such that j = sum - i. Thus, for a particular sum and i (from list1), we can directly determine that we need to check the element at index j = sum - i in list2, instead of traversing the whole list2. + +Doing such checks/comparisons, iterate over all the indices of list1 for every sum value chosen. Whenever a match occurs between list1 and list2, we put the matching string in a list res. + +We do the same process of checking the strings for all the values of sum in ascending order. After completing every iteration over list1 for a particular sum, we check if the res list is empty or not. If it is empty, we need to continue the process with the next sum value considered. If not, the current res gives the required list with minimum index sum. This is because we are already considering the index sum values in ascending order. So, the first list to be found is the required resultant list. + + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +public: + std::vector findRestaurant(std::vector& list1, std::vector& list2) { + std::vector res; + int m = list1.size(); + int n = list2.size(); + for (int sum = 0; sum < m + n - 1; ++sum) { + for (int i = 0; i <= sum; ++i) { + if (i < m && sum - i < n && list1[i] == list2[sum - i]) { + res.push_back(list1[i]); + } + } + if (!res.empty()) { + break; + } + } + return res; + } +}; + + +``` + + + + +```java +public class Solution { + public String[] findRestaurant(String[] list1, String[] list2) { + List < String > res = new ArrayList < > (); + for (int sum = 0; sum < list1.length + list2.length - 1; sum++) { + for (int i = 0; i <= sum; i++) { + if (i < list1.length && sum - i < list2.length && list1[i].equals(list2[sum - i])) + res.add(list1[i]); + } + if (res.size() > 0) + break; + } + return res.toArray(new String[res.size()]); + } +} +``` + + + + + +```python +from typing import List + +class Solution: + def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: + res = [] + m, n = len(list1), len(list2) + for sum in range(m + n - 1): + for i in range(sum + 1): + if i < m and sum - i < n and list1[i] == list2[sum - i]: + res.append(list1[i]) + if res: + break + return res + +``` + + + +## Complexity Analysis + +### Time Complexity: $O((l_1 * l_2)^2 * x)$ + +> **Reason**: There are two nested loops upto l1+l2 and string comparison takes x time. Here, x refers to the average string length. + +### Space Complexity: $O(r * x)$ + +> **Reason**: res list is used to store the result. Assuming r is the length of resresres. + +## References + +- **LeetCode Problem**: [Minimum Index Sum of Two Lists](https://leetcode.com/problems/minimum-index-sum-of-two-lists/description/) + +- **Solution Link**: [Minimum Index Sum of Two Lists](https://leetcode.com/problems/minimum-index-sum-of-two-lists/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0500-0599/567-permutation-in-string.md b/solutions/lc-solutions/0500-0599/567-permutation-in-string.md new file mode 100644 index 0000000..c75ee00 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/567-permutation-in-string.md @@ -0,0 +1,225 @@ +--- +id: permutation-in-string +title: 567. Permutation in String +sidebar_label: 567. Permutation in String +tags: +- String +- Two Pointer +- Sliding Window +- Hash Table + +description: "This is a solution to the 567. Permutation in String problem on LeetCode." +--- + +## Problem Description +Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. + +In other words, return true if one of s1's permutations is the substring of s2. + + + ### Examples +**Example 1:** +``` +Input: s1 = "ab", s2 = "eidbaooo" +Output: true +Explanation: s2 contains one permutation of s1 ("ba"). +``` + +### Constraints +- `1 <= s1.length, s2.length <= 10^4` +- `s1 and s2 consist of lowercase English letters.` +## Solution for 567. Permutation in String + + + + + #### Implementation + ```jsx live + function Solution(arr) { + + function areVectorsEqual(a, b) { + for (let i = 0; i < 26; i++) { + if (a[i] !== b[i]) return false; + } + return true; + } + + function checkInclusion(s1, s2) { + if (s2.length < s1.length) return false; + let freqS1 = Array(26).fill(0); + for (let c of s1) freqS1[c.charCodeAt(0) - 'a'.charCodeAt(0)]++; + + let freqS2 = Array(26).fill(0); + let i = 0, j = 0; + + while (j < s2.length) { + freqS2[s2[j].charCodeAt(0) - 'a'.charCodeAt(0)]++; + + if (j - i + 1 === s1.length) { + if (areVectorsEqual(freqS1, freqS2)) return true; + } + + if (j - i + 1 < s1.length) j++; + else { + freqS2[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)]--; + i++; + j++; + } + } + return false; + } + + + const input = s1 = "ab", s2 = "eidbaooo" + const output = checkInclusion(s1 , s2) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(nlogn) $ + - Space Complexity: $ O(n)$ + + ## Code in Different Languages + + + + ```python + class Solution: + def areVectorsEqual(self, a, b): + for i in range(26): + if a[i] != b[i]: + return False + return True + + def checkInclusion(self, s1: str, s2: str) -> bool: + if len(s2) < len(s1): + return False + freqS1 = [0] * 26 + for c in s1: + freqS1[ord(c) - ord('a')] += 1 + + freqS2 = [0] * 26 + i = 0 + j = 0 + + while j < len(s2): + freqS2[ord(s2[j]) - ord('a')] += 1 + + if j - i + 1 == len(s1): + if self.areVectorsEqual(freqS1, freqS2): + return True + + if j - i + 1 < len(s1): + j += 1 + else: + freqS2[ord(s2[i]) - ord('a')] -= 1 + i += 1 + j += 1 + + return False + + ``` + + + + + ```java +public class Solution { + private boolean areVectorsEqual(int[] a, int[] b) { + for (int i = 0; i < 26; i++) { + if (a[i] != b[i]) return false; + } + return true; + } + + public boolean checkInclusion(String s1, String s2) { + if (s2.length() < s1.length()) return false; + int[] freqS1 = new int[26]; + for (char c : s1.toCharArray()) freqS1[c - 'a']++; + + int[] freqS2 = new int[26]; + int i = 0, j = 0; + + while (j < s2.length()) { + freqS2[s2.charAt(j) - 'a']++; + + if (j - i + 1 == s1.length()) { + if (areVectorsEqual(freqS1, freqS2)) return true; + } + + if (j - i + 1 < s1.length()) j++; + else { + freqS2[s2.charAt(i) - 'a']--; + i++; + j++; + } + } + return false; + } +} + + ``` + + + + + + ```cpp + class Solution { + bool areVectorsEqual(vector a, vector b){ + for(int i=0; i<26; i++){ + if(a[i]!=b[i]) return false; + } + return true; + } +public: + bool checkInclusion(string s1, string s2) { + if(s2.size() freqS1(26, 0); + for(char c: s1) freqS1[c-'a']++; + + vector freqS2(26, 0); + int i=0, j=0; + + while(j + + +
+
+ +## References + +- **LeetCode Problem**: [567. Permutation in String](https://leetcode.com/problems/permutation-in-string/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/permutation-in-string/) + diff --git a/solutions/lc-solutions/0500-0599/_category_.json b/solutions/lc-solutions/0500-0599/_category_.json new file mode 100644 index 0000000..b104fd4 --- /dev/null +++ b/solutions/lc-solutions/0500-0599/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "0500-0599", + "position": 7, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (0500 - 0599)" + } +} diff --git a/solutions/lc-solutions/0500-0599/cutwall-grid.jpg b/solutions/lc-solutions/0500-0599/cutwall-grid.jpg new file mode 100644 index 0000000..457cade Binary files /dev/null and b/solutions/lc-solutions/0500-0599/cutwall-grid.jpg differ diff --git a/solutions/lc-solutions/0600-0699/0606-Construct-String-from-Binary-Tree.md b/solutions/lc-solutions/0600-0699/0606-Construct-String-from-Binary-Tree.md new file mode 100644 index 0000000..7b973c7 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/0606-Construct-String-from-Binary-Tree.md @@ -0,0 +1,133 @@ +--- +id: construct-string-from-binary-tree +title: Construct String from Binary Tree +sidebar_label: 0606-Construct-String-from-Binary-Tree +tags: +- Tree +- Depth-First Search +- Binary Tree +description: "Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way." +--- + +## Problem + +Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way. + +### Examples +**Example 1:** + +![Screenshot of the application](.././../../assets/606%20ex1.png) + +**Input:** `root = [1,2,3,4]` +**Output:** `"1(2(4))(3)"` +**Explanation:** Originally, it needs to be `"1(2(4)())(3()())"`, but you need to omit all the unnecessary empty parenthesis pairs. And it will be `"1(2(4))(3)"` + +**Example 2:** + +![Screenshot of the application](.././../../assets/606%20ex2.png) + +**Input:** `root = [1,2,3,null,4]` +**Output:** `"1(2()(4))(3)"` +**Explanation:** Originally, it needs to be `"1(2()(4)())(3()())"`, but you need to omit all the unnecessary empty parenthesis pairs. And it will be `"1(2()(4))(3)"` + +### Constraints + +- The number of nodes in the tree is in the range `[1, 10^4]`. +- `-5000 <= Node.val <= 5000` + +--- + +## Approach + +To construct the string from the binary tree with the preorder traversal, we need to follow these steps: + +1. If the current node is `null`, return an empty string. +2. Add the value of the current node to the result string. +3. If the left child is `null` but the right child is not `null`, add `()` to represent the left child. +4. Recursively add the left child string. +5. Recursively add the right child string if it exists. + +### Solution + +#### Java Solution + +```java +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +class Solution { + public String tree2str(TreeNode root) { + if (root == null) return ""; + String result = Integer.toString(root.val); + if (root.left != null || root.right != null) { + result += "(" + tree2str(root.left) + ")"; + if (root.right != null) { + result += "(" + tree2str(root.right) + ")"; + } + } + return result; + } +} +``` +#### C++ Solution + +```cpp +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + string tree2str(TreeNode* root) { + if (!root) return ""; + string result = to_string(root->val); + if (root->left || root->right) { + result += "(" + tree2str(root->left) + ")"; + if (root->right) { + result += "(" + tree2str(root->right) + ")"; + } + } + return result; + } +}; +``` +#### Python Solution + +```python +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def tree2str(self, root: TreeNode) -> str: + if not root: + return "" + result = str(root.val) + if root.left or root.right: + result += f"({self.tree2str(root.left)})" + if root.right: + result += f"({self.tree2str(root.right)})" + return result +``` +### Complexity Analysis +**Time Complexity:** O(n) +>Reason: Each node is visited once during the traversal. + +**Space Complexity:** O(h) +>Reason: The space complexity is determined by the recursion stack, which in the worst case (unbalanced tree) is O(n), but on average (balanced tree) is O(log n). + +### References +**LeetCode Problem:** Construct String from Binary Tree diff --git a/solutions/lc-solutions/0600-0699/0608-Tree-Node.md b/solutions/lc-solutions/0600-0699/0608-Tree-Node.md new file mode 100644 index 0000000..f4fb842 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/0608-Tree-Node.md @@ -0,0 +1,101 @@ +--- +id: tree-node +title: Tree Node +sidebar_label: 0608-Tree-Node +tags: +- Database +description: "SQL Schema: Given a table with nodes, write an SQL query to find all nodes which are the only child nodes." +--- + +## Problem + +Given a table `Tree`, write an SQL query to find all nodes which are the only child nodes. + +The `Tree` table contains these columns: + +- `id`: integer +- `p_id`: integer (parent id) + +### Examples + +**Example:** + +**Input:** +Tree table: +``` ++----+------+ +| id | p_id | ++----+------+ +| 1 | null | +| 2 | 1 | +| 3 | 1 | +| 4 | 2 | +| 5 | 2 | +| 6 | 3 | +| 7 | 4 | +| 8 | 5 | ++----+------+ +``` +**Output:** +``` ++----+ +| id | ++----+ +| 6 | +| 7 | +| 8 | ++----+ +``` +Explanation: Nodes `6`, `7`, and `8` are the only child nodes. + +### Constraints + +- `id` is the primary key column for this table. +- Each row of this table contains information about the `id` of a node and the `id` of its parent node. + +--- + +## Approach + +To solve this problem, we need to find nodes that have no siblings. In other words, we need to find nodes where there is only one child per parent. + +### Steps: + +1. Count the number of children for each parent. +2. Select the nodes where the parent has exactly one child. + +### Solution + +#### SQL + +```sql +SELECT + id +FROM + Tree +WHERE + p_id IN ( + SELECT + p_id + FROM + Tree + GROUP BY + p_id + HAVING + COUNT(*) = 1 + ); +``` +### Explanation +1) The subquery selects p_id values from the Tree table and groups them by p_id. It then uses the HAVING clause to filter groups with a count of exactly one, meaning those p_id values with only one child. + +2) The outer query then selects the id values where the p_id matches the ones returned by the subquery, which ensures that we get nodes that are the only child nodes. + +### Complexity Analysis +**Time Complexity:** O(n log n) +>Reason: The complexity primarily comes from the grouping and counting operations. Depending on the database system, this can vary, but in general, it is expected to be O(n log n). + +**Space Complexity:** O(n) +>Reason: The space complexity is mainly due to the storage of intermediate results, which can be linear in the size of the input. + +### References +**LeetCode Problem:** Tree Node \ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/0609-find-duplicate-file-in-system.md b/solutions/lc-solutions/0600-0699/0609-find-duplicate-file-in-system.md new file mode 100644 index 0000000..a6d99eb --- /dev/null +++ b/solutions/lc-solutions/0600-0699/0609-find-duplicate-file-in-system.md @@ -0,0 +1,334 @@ +--- +id: find-duplicate-file-in-system +title: Find Duplicate File in System +sidebar_label: 0609 - Find Duplicate File in System +tags: + - String + - Hash Table + - Array +description: "This is a solution to the Find Duplicate File in System problem on LeetCode." +--- + +## Problem Description + +Given a list `paths` of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in **any order**. + +A group of duplicate files consists of at least two files that have the same content. + +A single directory info string in the input list has the following format: + +- `"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"` + +It means there are `n` files `(f1.txt, f2.txt ... fn.txt)` with content `(f1_content, f2_content ... fn_content)` respectively in the directory `"root/d1/d2/.../dm"`. Note that `n >= 1` and `m >= 0`. If `m = 0`, it means the directory is just the root directory. + +The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format: + +- `"directory_path/file_name.txt"` + +### Examples + +**Example 1:** + +``` +Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"] +Output: [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]] +``` + +**Example 2:** + +``` +Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"] +Output: [["root/a/2.txt","root/c/d/4.txt"],["root/a/1.txt","root/c/3.txt"]] +``` + +### Constraints + +- $1 \leq \text{paths.length} \leq 2 \times 10^4$ +- $1 \leq paths[i].length \leq 3000$ +- $1 \leq sum(paths[i].length) \leq 5 * 10^5$ +- `paths[i]` consist of English letters, digits, `'/'`, `'.'`, `'('`, `')'`, and `' '`. +- You may assume no files or directories share the same name in the same directory. +- You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info. + +## Solution for Find Duplicate File in System + +### Approach 1 Brute Force [Time Limit Exceeded] + +For the brute force solution, firstly we obtain the directory paths, the filenames and file contents separately by appropriately splitting the elements of the pathspathspaths list. While doing so, we keep on creating a list which contains the full path of every file along with the contents of the file. The list contains data in the form + +> [[file_1_full_path,file_1_contents],[file_2_full_path,file_2_contents]...,[file_n_full_path,file_n_contents]] + +Once this is done, we iterate over this list. For every element i chosen from the list, we iterate over the whole list to find another element j whose file contents are the same as the $i^{th}$ element. For every such element found, we put the $j^{th}$ element's file path in a temporary list l and we also mark the $j^{th}$ element as visited so that this element isn't considered again in the future. Thus, when we reach the end of the array for every $i^{th}$ element, we obtain a list of file paths in l, which have the same contents as the file corresponding to the $i^{th}$ element. If this list isn't empty, it indicates that there exists content duplicate to the $i^{th}$ element. Thus, we also need to put the $i^{th}$ element's file path in the l. + +At the end of each iteration, we put this list l obtained in the resultant list res and reset the list l for finding the duplicates of the next element. + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include +#include +#include + +class Solution { +public: + std::vector> findDuplicate(std::vector& paths) { + std::vector> list; + for (const auto& path : paths) { + std::istringstream iss(path); + std::string dir; + iss >> dir; + std::string file; + while (iss >> file) { + auto pos = file.find('('); + std::string fileName = file.substr(0, pos); + std::string content = file.substr(pos + 1, file.size() - pos - 2); + list.emplace_back(dir + "/" + fileName, content); + } + } + + std::vector visited(list.size(), false); + std::vector> res; + for (size_t i = 0; i < list.size() - 1; ++i) { + if (visited[i]) continue; + std::vector l; + for (size_t j = i + 1; j < list.size(); ++j) { + if (list[i].second == list[j].second) { + l.push_back(list[j].first); + visited[j] = true; + } + } + if (!l.empty()) { + l.push_back(list[i].first); + res.push_back(l); + } + } + return res; + } +}; + +``` + + + + +```java +public class Solution { + public List < List < String >> findDuplicate(String[] paths) { + List < String[] > list = new ArrayList < > (); + for (String path: paths) { + String[] values = path.split(" "); + for (int i = 1; i < values.length; i++) { + String[] name_cont = values[i].split("\\("); + name_cont[1] = name_cont[1].replace(")", ""); + list.add(new String[] { + values[0] + "/" + name_cont[0], name_cont[1] + }); + } + } + boolean[] visited = new boolean[list.size()]; + List < List < String >> res = new ArrayList < > (); + for (int i = 0; i < list.size() - 1; i++) { + if (visited[i]) + continue; + List < String > l = new ArrayList < > (); + for (int j = i + 1; j < list.size(); j++) { + if (list.get(i)[1].equals(list.get(j)[1])) { + l.add(list.get(j)[0]); + visited[j] = true; + } + } + if (l.size() > 0) { + l.add(list.get(i)[0]); + res.add(l); + } + } + return res; + } +} + +``` + + + + + +```python +from collections import defaultdict + +class Solution: + def findDuplicate(self, paths): + list_ = [] + for path in paths: + values = path.split(" ") + for i in range(1, len(values)): + name_cont = values[i].split("(") + name_cont[1] = name_cont[1].replace(")", "") + list_.append([values[0] + "/" + name_cont[0], name_cont[1]]) + + visited = [False] * len(list_) + res = [] + for i in range(len(list_) - 1): + if visited[i]: + continue + l = [] + for j in range(i + 1, len(list_)): + if list_[i][1] == list_[j][1]: + l.append(list_[j][0]) + visited[j] = True + if l: + l.append(list_[i][0]) + res.append(l) + + return res +``` + + + +## Complexity Analysis + +### Time Complexity: $O(n \times x + f^2 \times s)$ + +> **Reason**: Creation of list will take O(nβˆ—x), where n is the number of directories and x is the average string length. Every file is compared with every other file. Let f files are there with average size of s, then files comparision will take O(f2βˆ—s), equals can take O(s). Here, Worst case will be when all files are unique. + +### Space Complexity: $O(n \times x)$ + +> **Reason**: Size of lists res and list can grow upto nβˆ—x. + +### Approach 2 Using HashMap +#### Algorithm + +In this approach, firstly we obtain the directory paths, the file names and their contents separately by appropriately splitting each string in the given paths list. In order to find the files with duplicate contents, we make use of a HashMap map, which stores the data in the form (contents,list_of_file_paths_with_this_content). Thus, for every file's contents, we check if the same content already exist in the hashmap. If so, we add the current file's path to the list of files corresponding to the current contents. Otherwise, we create a new entry in the map, with the current contents as the key and the value being a list with only one entry(the current file's path). + +At the end, we find out the contents corresponding to which atleast two file paths exist. We obtain the resultant list res, which is a list of lists containing these file paths corresponding to the same contents. + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector> findDuplicate(vector& paths) { + unordered_map> map; + for (const string& path : paths) { + istringstream iss(path); + vector values((istream_iterator(iss)), istream_iterator()); + for (size_t i = 1; i < values.size(); ++i) { + size_t pos = values[i].find('('); + string name = values[i].substr(0, pos); + string content = values[i].substr(pos + 1, values[i].size() - pos - 2); + map[content].push_back(values[0] + "/" + name); + } + } + vector> res; + for (const auto& pair : map) { + if (pair.second.size() > 1) { + res.push_back(pair.second); + } + } + return res; + } +}; + +``` + + + + +```java + +public class Solution { + public List < List < String >> findDuplicate(String[] paths) { + HashMap < String, List < String >> map = new HashMap < > (); + for (String path: paths) { + String[] values = path.split(" "); + for (int i = 1; i < values.length; i++) { + String[] name_cont = values[i].split("\\("); + name_cont[1] = name_cont[1].replace(")", ""); + List < String > list = map.getOrDefault(name_cont[1], new ArrayList < String > ()); + list.add(values[0] + "/" + name_cont[0]); + map.put(name_cont[1], list); + } + } + List < List < String >> res = new ArrayList < > (); + for (String key: map.keySet()) { + if (map.get(key).size() > 1) + res.add(map.get(key)); + } + return res; + } +} + +``` + + + + + +```python +from collections import defaultdict + +class Solution: + def findDuplicate(self, paths): + file_map = defaultdict(list) + + for path in paths: + values = path.split(" ") + for i in range(1, len(values)): + name_cont = values[i].split("(") + name_cont[1] = name_cont[1].replace(")", "") + file_map[name_cont[1]].append(values[0] + "/" + name_cont[0]) + + res = [] + for key, value in file_map.items(): + if len(value) > 1: + res.append(value) + + return res + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(n \times x)$ + +> **Reason**: n strings of average length x is parsed. + +### Space Complexity: $O(n \times x)$ + +> **Reason**: map and res size grows upto nβˆ—x. + +## References + +- **LeetCode Problem**: [Find Duplicate File in System](https://leetcode.com/problems/find-duplicate-file-in-system/description/) + +- **Solution Link**: [Find Duplicate File in System](https://leetcode.com/problems/find-duplicate-file-in-system/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/0611-valid-triangle-number.md b/solutions/lc-solutions/0600-0699/0611-valid-triangle-number.md new file mode 100644 index 0000000..a749058 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/0611-valid-triangle-number.md @@ -0,0 +1,243 @@ +--- +id: valid-triangle-number +title: Valid Triangle Number +sidebar_label: 0611 - Valid Triangle Number +tags: + - Two Pointers + - Sorting + - Binary Tree +description: "This is a solution to the Valid Triangle Number problem on LeetCode." +--- + +## Problem Description + +Given an integer array `nums`, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. + +### Examples + +**Example 1:** + +``` +Input: nums = [2,2,3,4] +Output: 3 +Explanation: Valid combinations are: +2,3,4 (using the first 2) +2,3,4 (using the second 2) +2,2,3 +``` + +**Example 2:** + +``` +Input: nums = [4,2,3,4] +Output: 4 +``` + +### Constraints + +- `1 <= nums.length <= 1000` +- `0 <= nums[i] <= 1000` + +## Solution for Valid Triangle Number + +### Approach 1 Brute Force [Time Limit Exceeded] + +The condition for the triplets (a,b,c) representing the lengths of the sides of a triangle, to form a valid triangle, is that the sum of any two sides should always be greater than the third side alone. i.e. a+b>c, b+c>a, a+c>b. + +The simplest method to check this is to consider every possible triplet in the given nums array and checking if the triplet satisfies the three inequalities mentioned above. Thus, we can keep a track of the count of the number of triplets satisfying these inequalities. When all the triplets have been considered, the count gives the required result. + +> Caution: The brute force approach is included here because it is an intuitive way to approach this problem. However, when there are $10^3$ numbers, the if statement will be checked approximately $10^9$ times. Thus, this approach will result in TLE. In the following approaches we will discuss ways to optimize our solution. + +## Code in Different Languages + + + + + +```cpp +#include + +class Solution { +public: + int triangleNumber(std::vector& nums) { + int count = 0; + for (size_t i = 0; i < nums.size() - 2; i++) { + for (size_t j = i + 1; j < nums.size() - 1; j++) { + for (size_t k = j + 1; k < nums.size(); k++) { + if (nums[i] + nums[j] > nums[k] && + nums[i] + nums[k] > nums[j] && + nums[j] + nums[k] > nums[i]) { + count++; + } + } + } + } + return count; + } +}; + +``` + + + + +```java +class Solution { + public int triangleNumber(int[] nums) { + int count = 0; + for (int i = 0; i < nums.length - 2; i++) { + for (int j = i + 1; j < nums.length - 1; j++) { + for (int k = j + 1; k < nums.length; k++) { + if (nums[i] + nums[j] > nums[k] && + nums[i] + nums[k] > nums[j] && + nums[j] + nums[k] > nums[i]) { + count++; + } + } + } + } + return count; + } +} +``` + + + + + +```python +class Solution: + def triangleNumber(self, nums): + count = 0 + for i in range(len(nums) - 2): + for j in range(i + 1, len(nums) - 1): + for k in range(j + 1, len(nums)): + if nums[i] + nums[j] > nums[k] and \ + nums[i] + nums[k] > nums[j] and \ + nums[j] + nums[k] > nums[i]: + count += 1 + return count +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N^3)$ + +> **Reason**: Three nested loops are there to check every triplet. + +### Space Complexity: $O(1)$ + +> **Reason**: Constant space is used. + +### Approach 2 Using Binary Search +#### Algorithm + +If we sort the given `nums` array once, we can solve the problem more efficiently. This is because if we consider a triplet `(a, b, c)` such that $$a \leq b \leq c$$, we need not check all three inequalities for the validity of the triangle formed by them. Only the condition $$a + b > c$$ is necessary. This happens because $$c \geq b$$ and $$c \geq a$$. Thus, adding any number to c will always produce a sum greater than either a or b considered alone. Therefore, the inequalities $$c + a > b$$ and $$c + b > a$$ are satisfied implicitly by the property $$a < b < c$$. + +From this, we get the idea that we can sort the given `nums` array. Then, for every pair `(nums[i], nums[j])` considered from the beginning of the array, such that $$j > i$$ (leading to $$nums[j] \geq nums[i]$$, we can find the count of elements `nums[k]` (where $$k > j$$), which satisfy the inequality $$nums[k] > nums[i] + nums[j]$$. We can do this for every pair (i, j) considered to get the required result. + +We can also observe that, since we've sorted the `nums` array, as we traverse towards the right for choosing the index `k` (for number `nums[k]`), the value of `nums[k]` could increase or remain the same (doesn't decrease relative to the previous value). Thus, there will exist a right limit on the value of index `k`, such that the elements satisfy $$nums[k] > nums[i] + nums[j]$$. Any elements beyond this value of `k` won't satisfy this inequality as well, which is obvious. + +Thus, if we can find this right limit value of `k` (indicating the element just greater than $$nums[i] + nums[j]$$), we can conclude that all the elements in the `nums` array in the range $$(j + 1, k - 1)$$ (both included) satisfy the required inequality. Thus, the count of elements satisfying the inequality will be given by $$k - j - 1$$. + +Since the `nums` array has been sorted, we can use Binary Search to find this right limit of `k`. + +Another point to be observed is that once we find a right limit index $$k_{(i,j)}$$ for a particular pair (i,j) chosen, when we choose a higher value of j for the same value of i, we need not start searching for the right limit $$k_{(i,j+1)}$$ from the index j+2j. Instead, we can start off from the index $$k_{(i,j)}$$ directly where we left off for the last j chosen. + +This holds correct because when we choose a higher value of j(higher or equal nums[j] than the previous one), all the nums[k], such that $$k < k_{(i,j)}$$ will obviously satisfy nums[i]+nums[j]>nums[k] for the new value of j chosen. + +By taking advantage of this observation, we can limit the range of Binary Search for k to shorter values for increasing values of j considered while choosing the pairs (i,j). + +## Code in Different Languages + + + + + + +```java +public class Solution { + int binarySearch(int nums[], int l, int r, int x) { + while (r >= l && r < nums.length) { + int mid = (l + r) / 2; + if (nums[mid] >= x) + r = mid - 1; + else + l = mid + 1; + } + return l; + } + public int triangleNumber(int[] nums) { + int count = 0; + Arrays.sort(nums); + for (int i = 0; i < nums.length - 2; i++) { + int k = i + 2; + for (int j = i + 1; j < nums.length - 1 && nums[i] != 0; j++) { + k = binarySearch(nums, k, nums.length - 1, nums[i] + nums[j]); + count += k - j - 1; + } + } + return count; + } +} + +``` + + + + + +```python +class Solution: + def binary_search(self, nums, l, r, x): + while r >= l and r < len(nums): + mid = (l + r) // 2 + if nums[mid] >= x: + r = mid - 1 + else: + l = mid + 1 + return l + + def triangleNumber(self, nums): + count = 0 + nums.sort() + for i in range(len(nums) - 2): + k = i + 2 + for j in range(i + 1, len(nums) - 1): + if nums[i] == 0: + continue + k = self.binary_search(nums, k, len(nums) - 1, nums[i] + nums[j]) + count += k - j - 1 + return count + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(n^2logn)$ + +> **Reason**: In worst case inner loop will take nlog⁑n (binary search applied N times). + +### Space Complexity: $O(logn)$ + +> **Reason**: Sorting takes O(log⁑n) space. + +## References + +- **LeetCode Problem**: [Valid Triangle Number](https://leetcode.com/problems/valid-triangle-number/description/) + +- **Solution Link**: [Valid Triangle Number](https://leetcode.com/problems/valid-triangle-number/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/0617-Merge-Two-Binary-Trees.md b/solutions/lc-solutions/0600-0699/0617-Merge-Two-Binary-Trees.md new file mode 100644 index 0000000..86e8b1e --- /dev/null +++ b/solutions/lc-solutions/0600-0699/0617-Merge-Two-Binary-Trees.md @@ -0,0 +1,135 @@ +--- +id: merge-two-binary-trees +title: Merge Two Binary Trees +sidebar_label: 0617-Merge-Two-Binary-Trees +tags: +- Tree +- Depth-First Search +- Breadth-First Search +description: "Given two binary trees, merge them into a new binary tree by adding the values of overlapping nodes." +--- + +## Problem + +You are given two binary trees `root1` and `root2`. Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree. + +### Examples + +**Example 1:** + +**Input:** `root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]` +**Output:** `[3,4,5,5,4,null,7]` + +**Example 2:** + +**Input:** `root1 = [1], root2 = [1,2]` +**Output:** `[2,2]` + +### Constraints + +- The number of nodes in both trees is in the range `[0, 2000]`. +- `-10^4 <= Node.val <= 10^4` + +--- + +## Approach + +To solve this problem, we can use a recursive depth-first search (DFS) approach. The idea is to traverse both trees simultaneously and sum the values of overlapping nodes. + +### Steps: + +1. **Base Case:** If both nodes are `null`, return `null`. +2. If one of the nodes is `null`, return the other node. +3. Create a new tree node with the sum of the values of the overlapping nodes. +4. Recursively merge the left children. +5. Recursively merge the right children. +6. Return the merged tree. + +### Solution + +#### Java + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { + if (root1 == null) { + return root2; + } + if (root2 == null) { + return root1; + } + TreeNode merged = new TreeNode(root1.val + root2.val); + merged.left = mergeTrees(root1.left, root2.left); + merged.right = mergeTrees(root1.right, root2.right); + return merged; + } +} +``` +#### C++ + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) { + if (root1 == nullptr) { + return root2; + } + if (root2 == nullptr) { + return root1; + } + TreeNode* merged = new TreeNode(root1->val + root2->val); + merged->left = mergeTrees(root1->left, root2->left); + merged->right = mergeTrees(root1->right, root2->right); + return merged; + } +}; +``` + +#### Python + +```python +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: + if not root1: + return root2 + if not root2: + return root1 + merged = TreeNode(root1.val + root2.val) + merged.left = self.mergeTrees(root1.left, root2.left) + merged.right = self.mergeTrees(root1.right, root2.right) + return merged +``` +### Complexity Analysis +**Time Complexity:** O(n) +>Reason: The algorithm visits each node in the tree once, where n is the total number of nodes in both trees combined. + +**Space Complexity:** O(h) +>Reason: The space complexity is determined by the height h of the tree due to the recursion stack. In the worst case, the height of the tree is O(n) for a skewed tree, but O(log n) for a balanced tree. + +### References +**LeetCode Problem:** Merge Two Binary Trees \ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/0621-task-scheduler.md b/solutions/lc-solutions/0600-0699/0621-task-scheduler.md new file mode 100644 index 0000000..866f306 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/0621-task-scheduler.md @@ -0,0 +1,431 @@ +--- +id: task-scheduler +title: Task Scheduler +sidebar_label: 0621 - Task Scheduler +tags: + - Heap + - Greedy + - Hash Table +description: "This is a solution to the Task Scheduler problem on LeetCode." +--- + +## Problem Description + +You are given an array of CPU tasks, each represented by letters A to Z, and a cooling time, n. Each cycle or interval allows the completion of one task. Tasks can be completed in any order, but there's a constraint: identical tasks must be separated by at least n intervals due to cooling time. + +​Return the minimum number of intervals required to complete all tasks. + +### Examples + +**Example 1:** + +``` +Input: tasks = ["A","A","A","B","B","B"], n = 2 + +Output: 8 + +Explanation: A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B. + +After completing task A, you must wait two cycles before doing A again. The same applies to task B. In the 3rd interval, neither A nor B can be done, so you idle. By the 4th cycle, you can do A again as 2 intervals have passed. +``` + +**Example 2:** + +``` +Input: tasks = ["A","C","A","B","D","B"], n = 1 + +Output: 6 + +Explanation: A possible sequence is: A -> B -> C -> D -> A -> B. + +With a cooling interval of 1, you can repeat a task after just one other task. +``` + +### Constraints + +- $1 \leq \text{tasks.length} \leq 10^4$ +- `tasks[i]` is an uppercase English letter. +- $0 \leq n \leq 100$ + +## Solution for Task Scheduler + +### Overview + +We are given characters, which are tasks to be scheduled in the CPU. The objective is to find the minimum time required to complete all tasks while including a cooldown period between two identical tasks. The cooldown period is represented by a non-negative integer `n`. During each unit of time, the CPU can either complete a task or stay idle. The goal is to optimize the schedule to minimize the total time required to process all the tasks. + +Key Observations: +1. Tasks represented by the same character are considered identical. +2. Repeated tasks should be at least n intervals apart from each other because of the cooling time. +3. You can put the idle time effectively in between two repetative tasks to schedule them. + +All approaches use a greedy strategy, meaning decisions are made step by step, focusing on what seems best in the moment to reach the overall best solution. To show that this type of approach works well, let's use some illustrations. We can prove its effectiveness by showing what happens if we assume the opposite and reach a contradiction. + +Using proof by contradiction, we can demonstrate that selecting the task with the lowest frequency increases idle time for the scheduler, thereby failing to maximize efficiency. Conversely, choosing tasks with higher frequencies maximizes efficiency. + +The Greedy approach optimizes efficiency by prioritizing tasks based on their frequency, thereby reducing intervals and minimizing idle time for the scheduler. This strategy ultimately leads to the maximization of overall efficiency. + +### Approach 1: Using Priority Queue / Max Heap +#### Intuition +To count the occurrences of each task while prioritizing those with the highest frequency, we use a frequency map and a max heap (priority queue), where frequencies are stored as negative values to simulate max heap behavior. + +In each iteration, a cycle of length `n + 1` is considered, signifying the time needed to execute tasks without violating the cooling period constraint. For instance, if there are 2 tasks `(A)` and `n = 2`, the iterations required would be `A-Idle-Idle-A` (`n + 1` iterations before picking a new task `A`). + +During each iteration: + +- Tasks with the highest frequency are popped from the max heap. In the case of frequency ties, any tied task can be chosen. +- The chosen task's frequency is reduced by 1. If remaining occurrences exist, they are added to a temporary array. +- This process continues until the cycle is completed. + +After completing the cycle: + +- The temporary array is used to rebuild the heap with updated frequencies of tasks encountered during the cycle. This ensures that updated frequencies are preserved when tasks are popped from the heap. + +Post-cycle processing: + +- A counter (`time`) is incremented by the actual number of tasks processed in the current cycle (`taskCount`). +- If the heap is not empty, extra idle time (`n + 1`) is added to account for the cooling period (n cycles + 1 extra idle time). +- If the heap is empty, only the remaining tasks in the cycle need consideration (`taskCount`). + +This process is repeated until the heap is empty. The `time` variable is incremented by the actual number of tasks processed in each cycle, with adjustments for idle time when required. + +**For a better understanding of the intuition let us view an example:** + +Given a task list (e.g., `['A', 'A', 'A', 'B', 'B', 'B']`) and a cooldown period `n` (e.g., 2), we aim to minimize the idle time during task execution. + +1. Create a frequency map (`freq`) to track task occurrences: `{'A': 3, 'B': 3}`. +2. Initialize a max heap (`pq`) with negative frequencies: [-3, -3]. +3. Define the cycle length as `n + 1` (e.g., `2 + 1 = 3`) to avoid violating the cooldown idle period. + +Cycle Repetition: + +Repeat cycles until the heap is empty: + +- In the first cycle, choose 'A' and 'B', resulting in `[-2, -2]`. +- Rebuild heap: `[-2, -2]`, and increment time: 2 tasks processed + cooldown idle. +- In the second cycle, choose 'A' and 'B' again, resulting in `[-1, -1]`. +- Rebuild heap: `[-1, -1]`, and increment time: 2 tasks processed + cooldown idle. +- Continue cycles until the heap is empty. + +The accumulated time spent on tasks and idle periods gives the final result: `3 + 3 + 2 = 8` (A-B-IDLE-A-B-IDLE-A-B). + +#### Algorithm + +- Initialize an array freq of size 26 to store the frequency of each task. +- Iterate through the tasks array and update the frequency of each task in the freq array. +- Create a priority queue pq and insert the frequencies of the tasks into the queue. +- Initialize a variable time to keep track of the total time taken. +- While the priority queue is not empty, repeat the following steps: + - Initialize a variable cycle to n + 1, which represents the cooling interval plus one (for the current task). + - Initialize an empty array store to store frequencies of tasks that still need to be processed. + - Initialize a variable taskCount to keep track of the number of tasks processed in the current cycle. + - While cycle is greater than 0 and the priority queue is not empty, repeat the following steps: + - Decrement cycle. + - Pop the top element (task frequency) from the priority queue. + - If the popped frequency is greater than 1, decrement it by 1 and store it in the store array. + - Increment taskCount as it keeps track of the number of tasks processed in the current cycle. + - After processing tasks in the cycle, restore the updated frequencies (stored in the store array) back to the priority queue. + - Update the time by adding either taskCount (if the priority queue is empty) or n + 1 (cooling interval) to the total time. +- Finally, return the total time. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + int leastInterval(vector& tasks, int n) { + // Building frequency map + int freq[26] = {0}; + for (char &ch : tasks) { + freq[ch - 'A']++; + } + + // Max heap to store frequencies + priority_queue pq; + for (int i = 0; i < 26; i++) { + if (freq[i] > 0) { + pq.push(freq[i]); + } + } + + int time = 0; + // Process tasks until the heap is empty + while (!pq.empty()) { + int cycle = n + 1; + vector store; + int taskCount = 0; + // Execute tasks in each cycle + while (cycle-- && !pq.empty()) { + if (pq.top() > 1) { + store.push_back(pq.top() - 1); + } + pq.pop(); + taskCount++; + } + // Restore updated frequencies to the heap + for (int &x : store) { + pq.push(x); + } + // Add time for the completed cycle + time += (pq.empty() ? taskCount : n + 1); + } + return time; + } +}; +``` + + + + +```java +class Solution { + public int leastInterval(char[] tasks, int n) { + // Build frequency map + int[] freq = new int[26]; + for (char ch : tasks) { + freq[ch - 'A']++; + } + + // Max heap to store frequencies + PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); + for (int i = 0; i < 26; i++) { + if (freq[i] > 0) { + pq.offer(freq[i]); + } + } + + int time = 0; + // Process tasks until the heap is empty + while (!pq.isEmpty()) { + int cycle = n + 1; + List store = new ArrayList<>(); + int taskCount = 0; + // Execute tasks in each cycle + while (cycle-- > 0 && !pq.isEmpty()) { + int currentFreq = pq.poll(); + if (currentFreq > 1) { + store.add(currentFreq - 1); + } + taskCount++; + } + // Restore updated frequencies to the heap + store.forEach(pq::offer); + // Add time for the completed cycle + time += (pq.isEmpty() ? taskCount : n + 1); + } + return time; + } +} +``` + + + + + +```python +class Solution: + def leastInterval(self, tasks: List[str], n: int) -> int: + # Build frequency map + freq = [0] * 26 + for ch in tasks: + freq[ord(ch) - ord('A')] += 1 + + # Max heap to store frequencies + pq = [-f for f in freq if f > 0] + heapq.heapify(pq) + + time = 0 + # Process tasks until the heap is empty + while pq: + cycle = n + 1 + store = [] + task_count = 0 + # Execute tasks in each cycle + while cycle > 0 and pq: + current_freq = -heapq.heappop(pq) + if current_freq > 1: + store.append(-(current_freq - 1)) + task_count += 1 + cycle -= 1 + # Restore updated frequencies to the heap + for x in store: + heapq.heappush(pq, x) + # Add time for the completed cycle + time += task_count if not pq else n + 1 + return time +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: In the worst case, all tasks must be processed, and each task might be inserted and extracted from the priority queue. The priority queue operations (insertion and extraction) have a time complexity of O(log⁑k) each. Therefore, the overall time complexity is O(Nβ‹…log⁑k). Since k is at maximum 26, log⁑k is a constant term. We can simplify the time complexity to O(N). This is a linear time complexity with a high constant factor.. + +### Space Complexity: $O(1)$ + +> **Reason**: The space complexity is mainly determined by the frequency array and the priority queue. The frequency array has a constant size of 26, and the priority queue can have a maximum size of 26 when all distinct tasks are present. Therefore, the overall space complexity is $O(1)$ or $O(26)$, which is considered constant. + +### Approach 2 Filling the Slots and Sorting +#### Intuition +We need to find the minimum time required to complete all tasks given the constraint that at least `n` units of time must elapse between two identical tasks. To minimize the time, we should first consider scheduling the most frequent tasks so that they are separated by `n` units of time. Then, we can fill the idle slots with the remaining tasks. + +**Example:** + +Consider the task list `['A', 'A', 'A', 'B', 'B', 'B']` with `n = 2`. + +1. Calculate the frequency array: `[3, 3, 0, ..., 0]`, as 'A' appears 3 times and 'B' appears 3 times. +2. Sort the frequency array in ascending order: `[0, 0, ..., 3, 3]`. +3. Calculate `maxFreq` as `freq[25] - 1`. In this case, `maxFreq = 3 - 1 = 2`. +4. Calculate the number of idle slots: `idleSlots = maxFreq * n = 2 * 2 = 4`. +5. The loop starts from the second highest frequency (index 24 in the sorted array) and goes down to the lowest frequency. This ensures that the highest frequency task's idle slots are considered only once, as it was accounted for when calculating `maxFreq` in the earlier step. +6. In each iteration, subtract the minimum of `maxFreq` and the current frequency from idleSlots. For the first iteration, subtract `min(2, 2) = 2` from idleSlots, resulting in `idleSlots = 4 - 2 = 2`. +7. If `idleSlots > 0`, add the remaining idle slots to the total number of tasks. In this example, there are 2 idle slots, so the final result is obtained by adding these idle slots (2) to the total number of tasks (6). +8. Thus, the minimum time required to complete all tasks, considering the cooldown period, is `8`. + +#### Algorithm + +- Create a freq array of size 26 to keep track of the count of each task. +- Iterate through the tasks array and update the frequency array with the frequency of each task. +- Sort the frequency array in non-decreasing order (ascending order = smallest to largest). This is done to process tasks with higher frequencies first. +- Calculate the maximum frequency of the most frequent task. Subtract 1 because we want to find the number of intervals, not the number of occurrences. +- Calculate the number of idleSlots that will be required by multiplying the maximum frequency by the cooldown period. +- Iterate over the frequency array from the second highest frequency to the lowest frequency. + - Subtract the minimum of the maximum frequency and the current frequency from the idleSlots. +- If there are any idleSlots left, add them to the total number of tasks and return this as the answer. Otherwise, return the total number of tasks. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + int leastInterval(vector& tasks, int n) { + // Create a frequency array to keep track of the count of each task + vector freq(26); + for (char task : tasks) { + freq[task - 'A']++; + } + + // Sort the frequency array in non-decreasing order + sort(freq.begin(), freq.end()); + // Calculate the maximum frequency of any task + int maxFreq = freq[25] - 1; + // Calculate the number of idle slots that will be required + int idleSlots = maxFreq * n; + + // Iterate over the frequency array from the second highest frequency to the lowest frequency + for (int i = 24; i >= 0 && freq[i] > 0; i--) { + // Subtract the minimum of the maximum frequency and the current frequency from the idle slots + idleSlots -= min(maxFreq, freq[i]); + } + + // If there are any idle slots left, add them to the total number of tasks + return idleSlots > 0 ? idleSlots + tasks.size() : tasks.size(); + } +}; +``` + + + + +```java +class Solution { + public int leastInterval(char[] tasks, int n) { + // Create a frequency array to keep track of the count of each task + int[] freq = new int[26]; + for (char task : tasks) { + freq[task - 'A']++; + } + + // Sort the frequency array in non-decreasing order + Arrays.sort(freq); + // Calculate the maximum frequency of any task + int maxFreq = freq[25] - 1; + // Calculate the number of idle slots that will be required + int idleSlots = maxFreq * n; + + // Iterate over the frequency array from the second highest frequency to the lowest frequency + for (int i = 24; i >= 0 && freq[i] > 0; i--) { + // Subtract the minimum of the maximum frequency and the current frequency from the idle slots + idleSlots -= Math.min(maxFreq, freq[i]); + } + + // If there are any idle slots left, add them to the total number of tasks + return idleSlots > 0 ? idleSlots + tasks.length : tasks.length; + } +} +``` + + + + + +```python +class Solution: + def leastInterval(self, tasks: List[str], n: int) -> int: + # Create a frequency array to keep track of the count of each task + freq = [0] * 26 + for task in tasks: + freq[ord(task) - ord('A')] += 1 + + # Sort the frequency array in non-decreasing order + freq.sort() + # Calculate the maximum frequency of any task + max_freq = freq[25] - 1 + # Calculate the number of idle slots that will be required + idle_slots = max_freq * n + # Iterate over the frequency array from the second highest frequency to the lowest frequency + + for i in range(24, -1, -1): + # Subtract the minimum of the maximum frequency and the current frequency from the idle slots + idle_slots -= min(max_freq, freq[i]) + + # If there are any idle slots left, add them to the total number of tasks + return idle_slots + len(tasks) if idle_slots > 0 else len(tasks) +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: The time complexity of the algorithm is O(26log⁑26+N), where 26log⁑26 is the time complexity of sorting the frequency array, and N is the length of the input task list, which is the dominating term. + +### Space Complexity: $O(1)$ + +> **Reason**: The frequency array has a size of 26. + +:::note +Some extra space is used when we sort arrays in place. The space complexity of the sorting algorithm depends on the programming language. + +- In Python, the sort method sorts a list using the Timsort algorithm which is a combination of Merge Sort and Insertion Sort and has $O(N)$ additional space. +- In Java, Arrays.sort() is implemented using a variant of the Quick Sort algorithm which has a space complexity of $O(log⁑N)$ for sorting two arrays. +- In C++, the sort() function is implemented as a hybrid of Quick Sort, Heap Sort, and Insertion Sort, with a worse-case space complexity of $O(log⁑N)$. + +We sort the frequency array, which has a size of 26. The space used for sorting takes $O(26)$ or $O(log⁑26)$, which is constant, so the space complexity of the algorithm is $O(26)$, which is constant, i.e. $O(1)$. +::: + +## References + +- **LeetCode Problem**: [Task Scheduler](https://leetcode.com/problems/task-scheduler/description/) + +- **Solution Link**: [Task Scheduler](https://leetcode.com/problems/task-scheduler/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/0629-K-Inverse-Pairs-Array.md b/solutions/lc-solutions/0600-0699/0629-K-Inverse-Pairs-Array.md new file mode 100644 index 0000000..9fbe5f3 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/0629-K-Inverse-Pairs-Array.md @@ -0,0 +1,161 @@ +--- +id: k-inverse-pairs-array +title: K Inverse Pairs Array +sidebar_label: 0629 - K Inverse Pairs Array +tags: + - Dynammic Programming + - C++ + - Java + - Python +description: "This is a solution to the K Inverse Pairs Array problem on LeetCode." +--- + +## Problem Description + +For an integer array nums, an inverse pair is a pair of integers `[i, j]` where `0 <= i < j < nums`.length and `nums[i] > nums[j]`. + +Given two integers n and k, return the number of different arrays consisting of numbers from `1 to n` such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo `109 + 7`. + +### Examples + +**Example 1:** + +``` +Input: n = 3, k = 0 +Output: 1 +Explanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs. + +``` +**Example 2:** + +``` +Input: n = 3, k = 1 +Output: 2 +Explanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair. + +``` +### Constraints + +- `1 <= n <= 1000` +- `0 <= k <= 1000` + +## Solution for K Inverse Pairs Array + +### Approach + +`dp[n][k]` denotes the number of arrays that have k inverse pairs for array composed of `1 to n` +we can establish the recursive relationship between `dp[n][k]` and `dp[n-1][i]`: + +if we put n as the last number then all the k inverse pair should come from the first `n-1` numbers +if we put n as the second last number then there's 1 inverse pair involves n so the rest `k-1` comes from the first n-1 numbers +... +if we put n as the first number then there's `n-1` inverse pairs involve n so the rest `k-(n-1)` comes from the first `n-1` numbers + +`dp[n][k] = dp[n-1][k]+dp[n-1][k-1]+dp[n-1][k-2]+...+dp[n-1][k+1-n+1]+dp[n-1][k-n+1]` + +It's possible that some where in the right hand side the second array index become negative, since we cannot generate negative inverse pairs we just treat them as 0, but still leave the item there as a place holder. + +`dp[n][k] = dp[n-1][k]+dp[n-1][k-1]+dp[n-1][k-2]+...+dp[n-1][k+1-n+1]+dp[n-1][k-n+1]` +`dp[n][k+1] = dp[n-1][k+1]+dp[n-1][k]+dp[n-1][k-1]+dp[n-1][k-2]+...+dp[n-1][k+1-n+1]` + +so by deducting the first line from the second line, we have + +`dp[n][k+1] = dp[n][k]+dp[n-1][k+1]-dp[n-1][k+1-n]` + + +## Code in Different Languages + + + + + +```cpp +int kInversePairs(int n, int k) { + vector dp(k+1, 0); + int mod = 1e9+7; + for(int i=1; i<=n; i++){ + vector tmp(k+1, 0); + tmp[0] = 1; + for(int j =1; j<=k; j++){ + long long val = (dp[j] + mod - ((j-i) >=0 ? dp[j-i] : 0))%mod; + tmp[j] = (tmp[j-1] + val)%mod; + } + dp = tmp; + } + return (dp[k] + mod - (k>0 ? dp[k-1] : 0))%mod; + } + +``` + + + + +```java + public static int kInversePairs(int n, int k) { + int mod = 1000000007; + if (k > n*(n-1)/2 || k < 0) return 0; + if (k == 0 || k == n*(n-1)/2) return 1; + long[][] dp = new long[n+1][k+1]; + dp[2][0] = 1; + dp[2][1] = 1; + for (int i = 3; i <= n; i++) { + dp[i][0] = 1; + for (int j = 1; j <= Math.min(k, i*(i-1)/2); j++) { + dp[i][j] = dp[i][j-1] + dp[i-1][j]; + if (j >= i) dp[i][j] -= dp[i-1][j-i]; + dp[i][j] = (dp[i][j]+mod) % mod; + } + } + return (int) dp[n][k]; + } +``` + + + + + +```python +class Solution: + def kInversePairs(self, n: int, k: int) -> int: + + max_possible_inversions = (n * (n-1)//2) + if k > max_possible_inversions: + return 0 + if k == 0 or k == max_possible_inversions: + return 1 + + MOD = pow(10,9) + 7 + + dp = [[0]*(k+1) for _ in range(n+1)] + + for i in range(1, n+1): + dp[i][0] = 1 + + dp[2][1] = 1 + + for i in range(3,n+1): + max_possible_inversions = min(k, i*(i-1)//2) + for j in range(1, max_possible_inversions + 1): + dp[i][j] = dp[i][j-1] + dp[i-1][j] + if j>=i: + dp[i][j] -= dp[i-1][j - i] + dp[i][j] = (dp[i][j] + MOD) % MOD + + return dp[n][k] + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N*k)$ + +### Space Complexity: $O(N*k)$ + + +## References + +- **LeetCode Problem**: [Kth Largest Element in a Stream](https://leetcode.com/problems/k-inverse-pairs-array/description/) + +- **Solution Link**: [Kth Largest Element in a Stream](https://leetcode.com/problems/k-inverse-pairs-array/solutions/) diff --git a/solutions/lc-solutions/0600-0699/0630-Course-Schedule-III.md b/solutions/lc-solutions/0600-0699/0630-Course-Schedule-III.md new file mode 100644 index 0000000..7627695 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/0630-Course-Schedule-III.md @@ -0,0 +1,135 @@ +--- +id: course-schedule-III +title: Course Schedule III +sidebar_label: 0630 - Course Schedule III +tags: + - Heap + - Array + - Greedy + - Sorting +description: "This is a solution to the Course Schedule III problem on LeetCode." +--- + +## Problem Description + +There are n different online courses numbered from `1 to n`. You are given an array courses where `courses[i] = [durationi, lastDayi]` indicate that the `ith` course should be taken continuously for durationi days and must be finished before or on lastDayi. + +You will start on the 1st day and you cannot take two or more courses simultaneously. + +Return the maximum number of courses that you can take. + +### Examples + +**Example 1:** + +``` +Input: courses = [[100,200],[200,1300],[1000,1250],[2000,3200]] +Output: 3 +Explanation: +There are totally 4 courses, but you can take 3 courses at most: +First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day. +Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. +Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. +The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date + +``` +**Example 2:** +``` +Input: courses = [[1,2]] +Output: 1 + +``` +### Constraints + +- `1 <= courses.length <= 10^4` +- `1 <= durationi, lastDayi <= 10^4` + +## Solution for Course Schedule III + +### Approach + +Sort all the courses by their ending time. When considering the first `K` courses, they all end before end. A necessary and sufficient condition for our schedule to be valid, is that `(for all K)`, the courses we choose to take within the first K of them, have total duration less than end. + +For each `K`, we will greedily remove the largest-length course until the total duration `start is <= end`. To select these largest-length courses, we will use a max heap. start will maintain the loop invariant that it is the sum of the lengths of the courses we have currently taken. + +Clearly, this greedy choice makes the number of courses used maximal for each K. When considering potential future K, there's never a case where we preferred having a longer course to a shorter one, so indeed our greedy choice dominates all other candidates. + + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + int scheduleCourse(vector>& courses) { + if(courses.size() <= 0) return 0; + sort(courses.begin(), courses.end(), [](const vector& a, vector& b) { + return a[1] < b[1]; + }); + priority_queue q; + int sum = 0; + for(auto i : courses) { + sum += i[0]; + q.push(i[0]); + if(sum > i[1]) { + sum -= q.top(); + q.pop(); + } + } + return q.size(); + } +}; +``` + + + + +```java +public class Solution { + public int scheduleCourse(int[][] courses) { + Arrays.sort(courses,(a,b)->a[1]-b[1]); //Sort the courses by their deadlines (Greedy! We have to deal with courses with early deadlines first) + PriorityQueue pq=new PriorityQueue<>((a,b)->b-a); + int time=0; + for (int[] c:courses) + { + time+=c[0]; // add current course to a priority queue + pq.add(c[0]); + if (time>c[1]) time-=pq.poll(); //If time exceeds, drop the previous course which costs the most time. (That must be the best choice!) + } + return pq.size(); + } +} +``` + + + + + +```python +def scheduleCourse(self, A): + pq = [] + start = 0 + for t, end in sorted(A, key = lambda (t, end): end): + start += t + heapq.heappush(pq, -t) + while start > end: + start += heapq.heappop(pq) + return len(pq) +``` + + + +## Complexity Analysis + +### Time Complexity: $O(Nβ‹…log(N))$ + +### Space Complexity: $O(N)$ + +## References + +- **LeetCode Problem**: [Kth Largest Element in a Stream](https://leetcode.com/problems/course-schedule-iii/description/) + +- **Solution Link**: [Kth Largest Element in a Stream](https://leetcode.com/problems/course-schedule-iii/solutions/) diff --git a/solutions/lc-solutions/0600-0699/0633-sum-of-square-numbers.md b/solutions/lc-solutions/0600-0699/0633-sum-of-square-numbers.md new file mode 100644 index 0000000..d828d74 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/0633-sum-of-square-numbers.md @@ -0,0 +1,271 @@ +--- +id: sum-of-square-numbers +title: Sum of Square Numbers +sidebar_label: 0633. Sum of Square Numbers + +tags: +- numbers +- C++ +- Java +- Python +- Javascript +- Binary Search +- Sum of Square Numbers + +description: "This is a solution to the Sum of Square Numbers problem on LeetCode." +--- + +## Problem Description +Given a non-negative integer c, decide whether there're two integers `a` and `b` such that `a^2 + b^2 = c`. + +### Examples + +**Example 1:** +``` +Input: c = 5 +Output: true +Explanation: 1 * 1 + 2 * 2 = 5 +``` + +**Example 2:** +``` +Input: s = c = 3 +Output: false +``` + +### Constraints +- `0 <= c <= 231 - 1` + + +## Solution for Sum of Square Numbers +### Approach +#### Brute Force +- Iterate over all possible values of `a` from `0` to `sqrt(c)`. +- For each value of `a`, iterate over all possible values of `b` from `0` to `sqrt(c)`. +- Check if `a^2 + b^2`equals `c`. +- If such a pair `(a, b)` is found, return `true`. +- If no such pair is found after all iterations, return `false`. + +**Implementation:** +```python +def judgeSquareSum(c: int) -> bool: + for a in range(int(c**0.5) + 1): + for b in range(int(c**0.5) + 1): + if a * a + b * b == c: + return True + return False +``` + +**Complexity:** +- Time Complexity: `O(c)`, since we iterate over all pairs `(a, b)` up to `sqrt(c)`. +- Space Complexity: O(1), as we only use a constant amount of extra space. + + +#### Optimized Approach +- Iterate over possible values of `a` from `0` to `sqrt(c)`. +- For each value of `a`, calculate `b^2 = c - a^2`. +- Check if `b^2` is a perfect square. +- If `b^2` is a perfect square, return `true`. +- If no such pair `(a, b)` is found, return `false`. + + +**Implementation:** + +```python +import math + +def judgeSquareSum(c: int) -> bool: + def is_square(n: int) -> bool: + root = int(math.sqrt(n)) + return n == root * root + + for a in range(int(math.sqrt(c)) + 1): + b_squared = c - a * a + if is_square(b_squared): + return True + return False + +# Example Usage +c = 5 +print(judgeSquareSum(c)) # Output: True, because 1^2 + 2^2 = 5 +``` + +**Complexity:** +- Time Complexity: `O(Sqrt(logc))`, where `sqrt` and `is_square` checks are logarithmic in terms of their input sizes. +- Space Complexity: O(1) as we only use a constant amount of extra space. + +**Corner Cases:** +- Zero Input: If `c = 0`, the output should be `true` since `0^2 + 0^2 = 0`. +- Small Inputs: For small values of `c` such as `1, 2, 3,` ensure correct handling. +- Large Inputs: Ensure that the solution handles large values of `c` efficiently. +- Prime Numbers: Check behavior when `c` is a prime number, as prime numbers cannot be expressed as a sum of squares except for specific primes. + + + + + +#### Implementation + + ```jsx live + function Solution() { + const judgeSquareSum = function(c) { + const isSquare = (n) => { + const root = Math.floor(Math.sqrt(n)); + return n === root * root; + }; + + for (let a = 0; a * a <= c; a++) { + const bSquared = c - a * a; + if (isSquare(bSquared)) { + return true; + } + } + return false; + }; + + const input = 5 + const output = judgeSquareSum(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {JSON.stringify(output)} +

+
+ ); + } + ``` + +#### Complexity Analysis +- Time Complexity: `O(Sqrt(logc))`, where `sqrt` and `is_square` checks are logarithmic in terms of their input sizes. +- Space Complexity: `O(1)` as we only use a constant amount of extra space. + + ## Code in Different Languages + + + + + + + ```javascript + var judgeSquareSum = function(c) { + const isSquare = (n) => { + const root = Math.floor(Math.sqrt(n)); + return n === root * root; + }; + + for (let a = 0; a * a <= c; a++) { + const bSquared = c - a * a; + if (isSquare(bSquared)) { + return true; + } + } + return false; + }; + ``` + + + + + + + ```typescript + function judgeSquareSum(c: number): boolean { + const isSquare = (n: number): boolean => { + const root = Math.floor(Math.sqrt(n)); + return n === root * root; + }; + + for (let a = 0; a * a <= c; a++) { + const bSquared = c - a * a; + if (isSquare(bSquared)) { + return true; + } + } + return false; + }; + ``` + + + + + + + ```python + class Solution: + def judgeSquareSum(self, c: int) -> bool: + def isSquare(n: int) -> bool: + root = int(n**0.5) + return n == root * root + + for a in range(int(c**0.5) + 1): + b_squared = c - a * a + if isSquare(b_squared): + return True + return False + ``` + + + + + + + ```java + class Solution { + public boolean judgeSquareSum(int c) { + for (int a = 0; a * a <= c; a++) { + int bSquared = c - a * a; + if (isSquare(bSquared)) { + return true; + } + } + return false; + } + + private boolean isSquare(int n) { + int root = (int) Math.sqrt(n); + return n == root * root; + } + } + ``` + + + + + + + ```cpp + class Solution { + public: + bool judgeSquareSum(int c) { + auto isSquare = [](long long n) { + long long root = static_cast(sqrt(n)); + return n == root * root; + }; + + for (long long a = 0; a * a <= c; a++) { + long long bSquared = c - a * a; + if (isSquare(bSquared)) { + return true; + } + } + return false; + } + }; + + ``` + + + + +
+
+ +## References + +- **LeetCode Problem**: [Squares of a Sorted Array](https://leetcode.com/problems/sum-of-square-numbers/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/sum-of-square-numbers/solutions/) \ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/0659-split-array-into-consecutive-subsequences.md b/solutions/lc-solutions/0600-0699/0659-split-array-into-consecutive-subsequences.md new file mode 100644 index 0000000..a7555d5 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/0659-split-array-into-consecutive-subsequences.md @@ -0,0 +1,313 @@ +--- +id: split-array-into-consecutive-subsequences +title: Split Array into Consecutive Subsequences +sidebar_label: 659. Split Array into Consecutive Subsequences + + +tags: +- Array +- Hash Table +- Greedy +- Heap (Priority Queue) + +description: "This is a solution to the Split Array into Consecutive Subsequences problem on LeetCode." +--- + +## Problem Description +You are given an integer array nums that is sorted in non-decreasing order. + +Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true: + +Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer). +All subsequences have a length of 3 or more. +Return true if you can split nums according to the above conditions, or false otherwise. + +A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not). + + +### Examples + +**Example 1:** +``` +Input: nums = [1,2,3,3,4,5] +Output: true +Explanation: nums can be split into the following subsequences: +[1,2,3,3,4,5] --> 1, 2, 3 +[1,2,3,3,4,5] --> 3, 4, 5 +``` + +**Example 2:** +``` +Input: nums = [1,2,3,3,4,4,5,5] +Output: true +Explanation: nums can be split into the following subsequences: +[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5 +[1,2,3,3,4,4,5,5] --> 3, 4, 5 +``` + + +### Constraints +- `1 <= nums.length <= 10^4` +- `-1000 <= nums[i] <= 1000` +- `nums is sorted in non-decreasing order.` + +## Solution for Split Array into Consecutive Subsequences + +### Approach +#### Data Structures +1. **`left` Counter:** + - Keeps track of the frequency of each number in the array. + - Helps to know how many of a particular number are left to be placed in a subsequence. + +2. **`end` Counter:** + - Keeps track of the subsequences that end at a particular number. + - Helps to know if a number can be appended to an existing subsequence. + +### Algorithm +1. **Initialization:** + - Count the frequency of each number in the array `A` using the `left` counter. + +2. **Iteration through the Array:** + - For each number `i` in `A`, do the following: + - If `i` is no longer available in `left` (its count is zero), skip it. + - Decrease the count of `i` in `left`. + + - **Check if `i` can extend a previous subsequence:** + - If there is a subsequence ending at `i-1` (i.e., `end[i - 1] > 0`): + - Decrease the count of subsequences ending at `i-1`. + - Increase the count of subsequences ending at `i`. + + - **Else, Check if `i` can start a new subsequence:** + - If there are available `i+1` and `i+2` in `left`: + - Decrease the count of `i+1` and `i+2` in `left`. + - Increase the count of subsequences ending at `i+2`. + + - **If neither of the above conditions hold:** + - Return `False` because `i` cannot be part of a valid subsequence. + +3. **Return `True`:** + - If all numbers have been processed without any issues, return `True`. + +### Intuition +- The main idea is to use a greedy approach to build valid subsequences. +- By maintaining counters (`left` and `end`), we can efficiently manage the formation and extension of subsequences. +- We prioritize extending existing subsequences to ensure that subsequences of length at least 3 are formed whenever possible. +- If extending is not possible, we check if a new subsequence can be started. +- The algorithm ensures that every number is either used to extend a subsequence or to start a new valid subsequence, making it both efficient and correct. + + + + #### Implementation + ```jsx live + function Solution(arr) { + function isPossible(A) { + const left = new Map(); + const end = new Map(); + + for (let num of A) { + left.set(num, (left.get(num) || 0) + 1); + } + + for (let num of A) { + if (left.get(num) === 0) continue; + left.set(num, left.get(num) - 1); + + if ((end.get(num - 1) || 0) > 0) { + end.set(num - 1, end.get(num - 1) - 1); + end.set(num, (end.get(num) || 0) + 1); + } else if ((left.get(num + 1) || 0) > 0 && (left.get(num + 2) || 0) > 0) { + left.set(num + 1, left.get(num + 1) - 1); + left.set(num + 2, left.get(num + 2) - 1); + end.set(num + 2, (end.get(num + 2) || 0) + 1); + } else { + return false; + } + } + + return true; + } + + const input =[1,2,3,3,4,5] + const output = isPossible(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(N) $ + - Space Complexity: $ O(N)$ + + ## Code in Different Languages + + + + ```javascript + function isPossible(A) { + const left = new Map(); + const end = new Map(); + + for (let num of A) { + left.set(num, (left.get(num) || 0) + 1); + } + + for (let num of A) { + if (left.get(num) === 0) continue; + left.set(num, left.get(num) - 1); + + if ((end.get(num - 1) || 0) > 0) { + end.set(num - 1, end.get(num - 1) - 1); + end.set(num, (end.get(num) || 0) + 1); + } else if ((left.get(num + 1) || 0) > 0 && (left.get(num + 2) || 0) > 0) { + left.set(num + 1, left.get(num + 1) - 1); + left.set(num + 2, left.get(num + 2) - 1); + end.set(num + 2, (end.get(num + 2) || 0) + 1); + } else { + return false; + } + } + + return true; +} + ``` + + + + + ```typescript + function isPossible(A: number[]): boolean { + const left = new Map(); + const end = new Map(); + + for (let num of A) { + left.set(num, (left.get(num) || 0) + 1); + } + + for (let num of A) { + if ((left.get(num) || 0) === 0) continue; + left.set(num, (left.get(num) || 0) - 1); + + if ((end.get(num - 1) || 0) > 0) { + end.set(num - 1, (end.get(num - 1) || 0) - 1); + end.set(num, (end.get(num) || 0) + 1); + } else if ((left.get(num + 1) || 0) > 0 && (left.get(num + 2) || 0) > 0) { + left.set(num + 1, (left.get(num + 1) || 0) - 1); + left.set(num + 2, (left.get(num + 2) || 0) - 1); + end.set(num + 2, (end.get(num + 2) || 0) + 1); + } else { + return false; + } + } + + return true; +} + + ``` + + + + ```python + def isPossible(self, A): + left = collections.Counter(A) + end = collections.Counter() + for i in A: + if not left[i]: continue + left[i] -= 1 + if end[i - 1] > 0: + end[i - 1] -= 1 + end[i] += 1 + elif left[i + 1] and left[i + 2]: + left[i + 1] -= 1 + left[i + 2] -= 1 + end[i + 2] += 1 + else: + return False + return True + ``` + + + + + ```java + import java.util.HashMap; +import java.util.Map; + +public class Solution { + public boolean isPossible(int[] A) { + Map left = new HashMap<>(); + Map end = new HashMap<>(); + + for (int num : A) { + left.put(num, left.getOrDefault(num, 0) + 1); + } + + for (int num : A) { + if (left.get(num) == 0) continue; + left.put(num, left.get(num) - 1); + + if (end.getOrDefault(num - 1, 0) > 0) { + end.put(num - 1, end.get(num - 1) - 1); + end.put(num, end.getOrDefault(num, 0) + 1); + } else if (left.getOrDefault(num + 1, 0) > 0 && left.getOrDefault(num + 2, 0) > 0) { + left.put(num + 1, left.get(num + 1) - 1); + left.put(num + 2, left.get(num + 2) - 1); + end.put(num + 2, end.getOrDefault(num + 2, 0) + 1); + } else { + return false; + } + } + + return true; + } +} + + ``` + + + + + ```cpp + bool isPossible(vector& A) { + unordered_map left, end; + for (int i: A) { + left[i]++; + } + for (int i: A) { + if (left[i] == 0) continue; + left[i]--; + if (end[i - 1] > 0) { + end[i - 1]--; + end[i]++; + } else if (left[i + 1] > 0 && left[i + 2] > 0) { + left[i + 1]--; + left[i + 2]--; + end[i + 2]++; + } else { + return false; + } + } + return true; + } + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/split-array-into-consecutive-subsequences/description/) + diff --git a/solutions/lc-solutions/0600-0699/0693-binary-number-with-alternating-bits.md b/solutions/lc-solutions/0600-0699/0693-binary-number-with-alternating-bits.md new file mode 100644 index 0000000..3ed0819 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/0693-binary-number-with-alternating-bits.md @@ -0,0 +1,157 @@ +--- +id: binary-number-with-alternating-bits +title: Binary Number with Alternating Bits +sidebar_label: 0693 - Binary Number with Alternating Bits +tags: + - Bit Manipulation + - String + - Bitmask +description: "This is a solution to the Binary Number with Alternating Bits problem on LeetCode." +--- + +## Problem Description + +Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. + +### Examples + +**Example 1:** + +``` +Input: n = 5 +Output: true +Explanation: The binary representation of 5 is: 101 +``` + +**Example 2:** + +``` +Input: n = 7 +Output: false +Explanation: The binary representation of 7 is: 111. +``` + +### Constraints + +- $$1 \leq n \leq 2^{31} - 1$$ + +## Solution for Binary Number with Alternating Bits + +### Approach 1: Convert to String +#### Intuition and Algorithm + +Let's convert the given number into a string of binary digits. Then, we should simply check that no two adjacent digits are the same. + +## Code in Different Languages + + + + + +```java +class Solution { + public boolean hasAlternatingBits(int n) { + String bits = Integer.toBinaryString(n); + for (int i = 0; i < bits.length() - 1; i++) { + if (bits.charAt(i) == bits.charAt(i+1)) { + return false; + } + } + return true; + } +} +``` + + + + + +```python +class Solution(object): + def hasAlternatingBits(self, n): + bits = bin(n) + return all(bits[i] != bits[i+1] + for i in xrange(len(bits) - 1)) +``` + + + +## Complexity Analysis + +### Time Complexity: $O(1)$ + +> **Reason**: For arbitrary inputs, we do $O(w)$ work, where w is the number of bits in `n`. However, $w \leq 32$. + +### Space Complexity: $O(1)$ + +> **Reason**: or alternatively $O(w)$. + +### Approach 2: Divide By Two +#### Algorithm + +We can get the last bit and the rest of the bits via `n % 2` and `n // 2` operations. Let's remember `cur`, the last bit of `n`. If the last bit ever equals the last bit of the remaining, then two adjacent bits have the same value, and the answer is `False`. Otherwise, the answer is `True`. + +Also note that instead of `n % 2` and `n // 2`, we could have used operators `n & 1` and `n >>= 1` instead. + +## Code in Different Languages + + + + + +```java +class Solution { + public boolean hasAlternatingBits(int n) { + int cur = n % 2; + n /= 2; + while (n > 0) { + if (cur == n % 2) return false; + cur = n % 2; + n /= 2; + } + return true; + } +} +``` + + + + + +```python +class Solution(object): + def hasAlternatingBits(self, n): + n, cur = divmod(n, 2) + while n: + if cur == n % 2: return False + n, cur = divmod(n, 2) + return True +``` + + + +## Complexity Analysis + +### Time Complexity: $O(1)$ + +> **Reason**: For arbitrary inputs, we do $O(w)$ work, where w is the number of bits in n. However, $w \leq 32$. + +### Space Complexity: $O(1)$ + +> **Reason**: constant space is used. + +## References + +- **LeetCode Problem**: [Binary Number with Alternating Bits](https://leetcode.com/problems/binary-number-with-alternating-bits/description/) + +- **Solution Link**: [Binary Number with Alternating Bits](https://leetcode.com/problems/binary-number-with-alternating-bits/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/0695-max-area-of-island.md b/solutions/lc-solutions/0600-0699/0695-max-area-of-island.md new file mode 100644 index 0000000..225aee5 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/0695-max-area-of-island.md @@ -0,0 +1,229 @@ +--- +id: 695-max-area-of-island +title: Max Area of Island +sidebar_label: 0695 - Max Area of Island +tags: + - Depth-First Search + - Recursion + - Breadth-First Search +description: "This is a solution to the Max Area of Island problem on LeetCode." +--- + +## Problem Description + +You are given an `m x n` binary matrix `grid`. An island is a group of `1`'s (representing land) connected **4-directionally** (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. + +The **area** of an island is the number of cells with a value `1` in the island. + +Return the maximum **area** of an island in `grid`. If there is no island, return `0`. + +### Examples + +**Example 1:** + +![image](https://assets.leetcode.com/uploads/2021/05/01/maxarea1-grid.jpg) +``` +Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]] +Output: 6 +Explanation: The answer is not 11, because the island must be connected 4-directionally. +``` + +**Example 2:** + +``` +Input: grid = [[0,0,0,0,0,0,0,0]] +Output: 0 +``` + +### Constraints + +- `m == grid.length` +- `n == grid[i].length` +- `1 <= m, n <= 50` +- `grid[i][j]` is either 0 or 1. + +## Solution for Max Area of Island + +### Approach 1: Depth-First Search (Recursive) +#### Intuition and Algorithm + +We want to know the area of each connected shape in the grid, then take the maximum of these. + +If we are on a land square and explore every square connected to it 4-directionally (and recursively squares connected to those squares, and so on), then the total number of squares explored will be the area of that connected shape. + +To ensure we don't count squares in a shape more than once, let's use `seen` to keep track of squares we haven't visited before. It will also prevent us from counting the same shape more than once. +## Code in Different Languages + + + + + +```java +class Solution { + int[][] grid; + boolean[][] seen; + + public int area(int r, int c) { + if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || + seen[r][c] || grid[r][c] == 0) + return 0; + seen[r][c] = true; + return (1 + area(r+1, c) + area(r-1, c) + + area(r, c-1) + area(r, c+1)); + } + + public int maxAreaOfIsland(int[][] grid) { + this.grid = grid; + seen = new boolean[grid.length][grid[0].length]; + int ans = 0; + for (int r = 0; r < grid.length; r++) { + for (int c = 0; c < grid[0].length; c++) { + ans = Math.max(ans, area(r, c)); + } + } + return ans; + } +} +``` + + + + + +```python +class Solution(object): + def maxAreaOfIsland(self, grid): + seen = set() + def area(r, c): + if not (0 <= r < len(grid) and 0 <= c < len(grid[0]) + and (r, c) not in seen and grid[r][c]): + return 0 + seen.add((r, c)) + return (1 + area(r+1, c) + area(r-1, c) + + area(r, c-1) + area(r, c+1)) + + return max(area(r, c) + for r in range(len(grid)) + for c in range(len(grid[0]))) +``` + + + +## Complexity Analysis + +### Time Complexity: $O(R \times C)$ + +> **Reason**: where R is the number of rows in the given grid, and C is the number of columns. We visit every square once. + +### Space Complexity: $O(R \times C)$ + +> **Reason**: the space used by `seen` to keep track of visited squares and the space used by the call stack during our recursion. + +### Approach 2: Depth-First Search (Iterative) +#### Intuition and Algorithm + +We can try the same approach using a stack-based, (or "iterative") depth-first search. + +Here, `seen` will represent squares that have either been visited or are added to our list of squares to visit (`stack`). For every starting land square that hasn't been visited, we will explore 4-directionally around it, adding land squares that haven't been added to `seen` to our `stack`. + +On the side, we'll keep a count `shape` of the total number of squares seen during the exploration of this shape. We'll want the running max of these counts. + +## Code in Different Languages + + + + + +```java +class Solution { + public int maxAreaOfIsland(int[][] grid) { + boolean[][] seen = new boolean[grid.length][grid[0].length]; + int[] dr = new int[]{1, -1, 0, 0}; + int[] dc = new int[]{0, 0, 1, -1}; + + int ans = 0; + for (int r0 = 0; r0 < grid.length; r0++) { + for (int c0 = 0; c0 < grid[0].length; c0++) { + if (grid[r0][c0] == 1 && !seen[r0][c0]) { + int shape = 0; + Stack stack = new Stack(); + stack.push(new int[]{r0, c0}); + seen[r0][c0] = true; + while (!stack.empty()) { + int[] node = stack.pop(); + int r = node[0], c = node[1]; + shape++; + for (int k = 0; k < 4; k++) { + int nr = r + dr[k]; + int nc = c + dc[k]; + if (0 <= nr && nr < grid.length && + 0 <= nc && nc < grid[0].length && + grid[nr][nc] == 1 && !seen[nr][nc]) { + stack.push(new int[]{nr, nc}); + seen[nr][nc] = true; + } + } + } + ans = Math.max(ans, shape); + } + } + } + return ans; + } +} +``` + + + + + +```python +class Solution(object): + def maxAreaOfIsland(self, grid): + seen = set() + ans = 0 + for r0, row in enumerate(grid): + for c0, val in enumerate(row): + if val and (r0, c0) not in seen: + shape = 0 + stack = [(r0, c0)] + seen.add((r0, c0)) + while stack: + r, c = stack.pop() + shape += 1 + for nr, nc in ((r-1, c), (r+1, c), (r, c-1), (r, c+1)): + if (0 <= nr < len(grid) and 0 <= nc < len(grid[0]) + and grid[nr][nc] and (nr, nc) not in seen): + stack.append((nr, nc)) + seen.add((nr, nc)) + ans = max(ans, shape) + return ans +``` + + + +## Complexity Analysis + +### Time Complexity: $O(R \times C)$ + +> **Reason**: where R is the number of rows in the given grid, and C is the number of columns. We visit every square once. + +### Space Complexity: $O(R \times C)$ + +> **Reason**: the space used by seen to keep track of visited squares and the space used by stack. + +## References + +- **LeetCode Problem**: [Max Area of Island](https://leetcode.com/problems/max-area-of-island/description/) + +- **Solution Link**: [Max Area of Island](https://leetcode.com/problems/max-area-of-island/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/0696-count-binary -ubstrings.md b/solutions/lc-solutions/0600-0699/0696-count-binary -ubstrings.md new file mode 100644 index 0000000..41bd388 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/0696-count-binary -ubstrings.md @@ -0,0 +1,194 @@ +--- +id: count-binary-substrings +title: Count Binary Substrings +sidebar_label: 0696 - Count Binary Substrings +tags: + - String + - Two Pointers + - Sliding Window +description: "This is a solution to the Count Binary Substrings problem on LeetCode." +--- + +## Problem Description + +Given a binary string `s`, return the number of non-empty substrings that have the same number of `0`'s and `1`'s, and all the `0`'s and all the `1`'s in these substrings are grouped consecutively. + +Substrings that occur multiple times are counted the number of times they occur. + +### Examples + +**Example 1:** + +``` +Input: s = "00110011" +Output: 6 +Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01". +Notice that some of these substrings repeat and are counted the number of times they occur. +Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together. +``` + +**Example 2:** + +``` +Input: s = "10101" +Output: 4 +Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's. +``` + +### Constraints + +- $1 <= s.length <= 10^5$ +- `s[i]` is either `'0'` or `'1'`. + +## Solution for Count Binary Substrings + +### Approach 1: Group By Character +#### Intuition + +We can convert the string `s` into an array groups that represents the length of same-character contiguous blocks within the string. For example, if `s = "110001111000000"`, then `groups = [2, 3, 4, 6]`. + +For every binary string of the form `'0' * k + '1' * k` or `'1' * k + '0' * k`, the middle of this string must occur between two groups. + +Let's try to count the number of valid binary strings between `groups[i]` and `groups[i+1]`. If we have `groups[i] = 2, groups[i+1] = 3`, then it represents either "00111" or "11000". We clearly can make `min(groups[i], groups[i+1])` valid binary strings within this string. Because the binary digits to the left or right of this string must change at the boundary, our answer can never be larger. + +#### Algorithm + +Let's create `groups` as defined above. The first element of `s` belongs in its own group. From then on, each element either doesn't match the previous element, so that it starts a new group of size 1, or it does match, so that the size of the most recent group increases by 1. + +Afterward, we will take the sum of `min(groups[i-1], groups[i])`. + +## Code in Different Languages + + + + + +```java +class Solution { + public int countBinarySubstrings(String s) { + int[] groups = new int[s.length()]; + int t = 0; + groups[0] = 1; + for (int i = 1; i < s.length(); i++) { + if (s.charAt(i-1) != s.charAt(i)) { + groups[++t] = 1; + } else { + groups[t]++; + } + } + + int ans = 0; + for (int i = 1; i <= t; i++) { + ans += Math.min(groups[i-1], groups[i]); + } + return ans; + } +} +``` + + + + + +```python +class Solution(object): + def countBinarySubstrings(self, s): + groups = [1] + for i in xrange(1, len(s)): + if s[i-1] != s[i]: + groups.append(1) + else: + groups[-1] += 1 + + ans = 0 + for i in xrange(1, len(groups)): + ans += min(groups[i-1], groups[i]) + return ans +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: where N is the length of s. Every loop is through $O(N)$ items with $O(1)$ work inside the for-block. + +### Space Complexity: $O(N)$ + +> **Reason**: the space used by `groups`. + +### Approach 2: Linear Scan +#### Intuition and Algorithm + +We can amend our Approach #1 to calculate the answer on the fly. Instead of storing `groups`, we will remember only `prev = groups[-2]` and `cur = groups[-1]`. Then, the answer is the sum of `min(prev, cur)` over each different final `(prev, cur)` we see. + +## Code in Different Languages + + + + + +```java +class Solution { + public int countBinarySubstrings(String s) { + int ans = 0, prev = 0, cur = 1; + for (int i = 1; i < s.length(); i++) { + if (s.charAt(i-1) != s.charAt(i)) { + ans += Math.min(prev, cur); + prev = cur; + cur = 1; + } else { + cur++; + } + } + return ans + Math.min(prev, cur); + } +} +``` + + + + + +```python +class Solution(object): + def countBinarySubstrings(self, s): + ans, prev, cur = 0, 0, 1 + for i in xrange(1, len(s)): + if s[i-1] != s[i]: + ans += min(prev, cur) + prev, cur = cur, 1 + else: + cur += 1 + + return ans + min(prev, cur) +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: where N is the length of s. Every loop is through $O(N)$ items with $O(1)$ work inside the for-block. + +### Space Complexity: $O(1)$ + +> **Reason**: the space used by `prev`, `cur`, and `ans`. + +## References + +- **LeetCode Problem**: [Count Binary Substrings](https://leetcode.com/problems/count-binary-substrings/description/) + +- **Solution Link**: [Count Binary Substrings](https://leetcode.com/problems/count-binary-substrings/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/0697-degree-of-an-array.md b/solutions/lc-solutions/0600-0699/0697-degree-of-an-array.md new file mode 100644 index 0000000..34c6ef5 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/0697-degree-of-an-array.md @@ -0,0 +1,141 @@ +--- +id: degree-of-an-array +title: Degree of an Array +sidebar_label: 0697 - Degree of an Array +tags: + - Hash Table + - Array + - Sliding Window +description: "This is a solution to the Degree of an Array problem on LeetCode." +--- + +## Problem Description + +Given a non-empty array of non-negative integers `nums`, the **degree** of this array is defined as the maximum frequency of any one of its elements. + +Your task is to find the smallest possible length of a (contiguous) subarray of `nums`, that has the same degree as `nums`. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,2,3,1] +Output: 2 +Explanation: +The input array has a degree of 2 because both elements 1 and 2 appear twice. +Of the subarrays that have the same degree: +[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] +The shortest length is 2. So return 2. +``` + +**Example 2:** + +``` +Input: nums = [1,2,2,3,1,4,2] +Output: 6 +Explanation: +The degree is 3 because the element 2 is repeated 3 times. +So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6. +``` + +### Constraints + +- `nums.length` will be between 1 and 50,000. +- `nums[i]` will be an integer between 0 and 49,999. + +## Solution for Degree of an Array + +### Approach: Left and Right Index +#### Intuition and Algorithm + +An array that has degree `d`, must have some element `x` occur `d` times. If some subarray has the same degree, then some element `x` (that occurred d times), still occurs `d` times. The shortest such subarray would be from the first occurrence of `x` until the last occurrence. + +For each element in the given array, let's know `left`, the index of its first occurrence; and `right`, the index of its last occurrence. For example, with `nums = [1,2,3,2,5]` we have `left[2] = 1` and `right[2] = 3`. + +Then, for each element `x` that occurs the maximum number of times, `right[x] - left[x] + 1` will be our candidate answer, and we'll take the minimum of those candidates. + +## Code in Different Languages + + + + + +```java +class Solution { + public int findShortestSubArray(int[] nums) { + Map left = new HashMap(), + right = new HashMap(), count = new HashMap(); + + for (int i = 0; i < nums.length; i++) { + int x = nums[i]; + if (left.get(x) == null) { + left.put(x, I); + } + right.put(x, i); + count.put(x, count.getOrDefault(x, 0) + 1); + } + + int ans = nums.length; + int degree = Collections.max(count.values()); + for (int x: count.keySet()) { + if (count.get(x) == degree) { + ans = Math.min(ans, right.get(x) - left.get(x) + 1); + } + } + return ans; + } +} +``` + + + + + +```python +class Solution(object): + def findShortestSubArray(self, nums): + left, right, count = {}, {}, {} + for i, x in enumerate(nums): + if x not in left: + left[x] = i + right[x] = i + count[x] = count.get(x, 0) + 1 + + ans = len(nums) + degree = max(count.values()) + for x in count: + if count[x] == degree: + ans = min(ans, right[x] - left[x] + 1) + + return ans +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: where N is the length of `nums`. Every loop is through $O(N)$ items with $O(1)$ work inside the for-block. + +### Space Complexity: $O(N)$ + +> **Reason**: the space used by `left`, `right`, and `count`. + + +## References + +- **LeetCode Problem**: [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/description/) + +- **Solution Link**: [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/600-Non-negative Integers without Consecutive Ones.md b/solutions/lc-solutions/0600-0699/600-Non-negative Integers without Consecutive Ones.md new file mode 100644 index 0000000..ea3e211 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/600-Non-negative Integers without Consecutive Ones.md @@ -0,0 +1,209 @@ +--- +id: non-negative-integers-without-consecutive-ones +title: Non-negative Integers without Consecutive Ones +sidebar_label: Non-negative Integers without Consecutive Ones +tags: + - Dynamic Programming + - Bit Manipulation + - Algorithms + - DSA + - Python + - C++ + - Java + - JavaScript +description: "This page explains the problem of finding non-negative integers without consecutive ones." +--- + +# Non-negative Integers without Consecutive Ones + +## 1. Problem Description + +Given a non-negative integer $n$, find the number of non-negative integers less than or equal to $n$ that do not contain consecutive ones in their binary representation. + +## 2. Examples + +### Example 1: +**Input:** $n = 5$ +**Output:** $5$ +**Explanation:** +There are five such numbers: 0, 1, 2, 4, 5. +Their binary representations are: 0 (0), 1 (1), 2 (10), 4 (100), 5 (101). + +### Example 2: +**Input:** $n = 10$ +**Output:** $8$ +**Explanation:** +There are eight such numbers: 0, 1, 2, 4, 5, 8, 9, 10. +Their binary representations are: 0 (0), 1 (1), 2 (10), 4 (100), 5 (101), 8 (1000), 9 (1001), 10 (1010). + +## 3. Constraints + +- $0 <= n <= 10^9$ + +## 4. Algorithm + +### Approach: +The problem can be approached using dynamic programming. We need to count the numbers up to $n$ that do not have consecutive ones in their binary representation. This can be solved by considering the binary digits of $n$. + +1. **Initialize Variables:** + - $dp0[i]$: Number of valid integers of length $i$ ending with $0$. + - $dp1[i]$: Number of valid integers of length $i$ ending with $1$. + +2. **Base Case:** + - $dp0[1] = 1$: Only one number of length 1 ending with $0$ (i.e., $0$). + - $dp1[1] = 1$: Only one number of length 1 ending with $1$ (i.e., $1$). + +3. **DP Transition:** + - For each bit position from 2 to the length of $n$ in binary: + - $dp0[i] = dp0[i-1] + dp1[i-1]$ : If the current bit is $0$, the previous bit can be either $0$ or $1$. + - $dp1[i] = dp0[i-1]$ : If the current bit is $1$, the previous bit must be $0$. + +4. **Calculate Result:** + - Sum up all the valid numbers up to the highest bit of $n$. + +### Example Calculation: + +For $n = 5$ (binary $101$): +1. Calculate the number of valid integers for each bit length. +2. Use the DP arrays to count valid integers. + +## 5. Implementation (Code for 4 Languages) + + + + ```python + def findIntegers(n): + bin_n = bin(n)[2:] + length = len(bin_n) + dp0 = [0] * (length + 1) + dp1 = [0] * (length + 1) + dp0[1] = dp1[1] = 1 + for i in range(2, length + 1): + dp0[i] = dp0[i - 1] + dp1[i - 1] + dp1[i] = dp0[i - 1] + result = dp0[length] + dp1[length] + for i in range(1, length): + if bin_n[i] == '1' and bin_n[i - 1] == '1': + break + if bin_n[i] == '0' and bin_n[i - 1] == '0': + result -= dp1[length - i] + return result + + # Example usage: + print(findIntegers(5)) # Output: 5 + ``` + + + + ```cpp + #include + #include + using namespace std; + + int findIntegers(int n) { + vector bin; + while (n) { + bin.push_back(n % 2); + n /= 2; + } + int length = bin.size(); + vector dp0(length + 1, 0), dp1(length + 1, 0); + dp0[1] = dp1[1] = 1; + for (int i = 2; i <= length; ++i) { + dp0[i] = dp0[i - 1] + dp1[i - 1]; + dp1[i] = dp0[i - 1]; + } + int result = dp0[length] + dp1[length]; + for (int i = length - 2; i >= 0; --i) { + if (bin[i] == 1 && bin[i + 1] == 1) break; + if (bin[i] == 0 && bin[i + 1] == 0) result -= dp1[i + 1]; + } + return result; + } + + // Example usage: + int main() { + cout << findIntegers(5) << endl; // Output: 5 + return 0; + } + ``` + + + + ```java + public class NonNegativeIntegers { + public int findIntegers(int n) { + String binN = Integer.toBinaryString(n); + int length = binN.length(); + int[] dp0 = new int[length + 1]; + int[] dp1 = new int[length + 1]; + dp0[1] = dp1[1] = 1; + for (int i = 2; i <= length; i++) { + dp0[i] = dp0[i - 1] + dp1[i - 1]; + dp1[i] = dp0[i - 1]; + } + int result = dp0[length] + dp1[length]; + for (int i = 1; i < length; i++) { + if (binN.charAt(i) == '1' && binN.charAt(i - 1) == '1') break; + if (binN.charAt(i) == '0' && binN.charAt(i - 1) == '0') result -= dp1[length - i]; + } + return result; + } + + public static void main(String[] args) { + NonNegativeIntegers solution = new NonNegativeIntegers(); + System.out.println(solution.findIntegers(5)); // Output: 5 + } + } + ``` + + + + ```javascript + function findIntegers(n) { + const binN = n.toString(2); + const length = binN.length; + const dp0 = new Array(length + 1).fill(0); + const dp1 = new Array(length + 1).fill(0); + dp0[1] = dp1[1] = 1; + for (let i = 2; i <= length; i++) { + dp0[i] = dp0[i - 1] + dp1[i - 1]; + dp1[i] = dp0[i - 1]; + } + let result = dp0[length] + dp1[length]; + for (let i = 1; i < length; i++) { + if (binN[i] === '1' && binN[i - 1] === '1') break; + if (binN[i] === '0' && binN[i - 1] === '0') result -= dp1[length - i]; + } + return result; + } + + // Example usage: + console.log(findIntegers(5)); // Output: 5 + ``` + + + +## 8. Complexity Analysis + +- **Time Complexity:** $O(log n)$, where $n$ is the input number. This is because we are working with the binary representation of $n$, which has a length of $O(log n)$. +- **Space Complexity:** $O(log n)$, due to the storage of the $dp0$ and $dp1$ arrays and the binary representation of $n$. + +## 9. Advantages and Disadvantages + +### Advantages: +- Efficiently solves the problem using dynamic programming. +- Works well for large values of $n$ up to $(10^9)$. + +### Disadvantages: +- Requires understanding of bit manipulation and dynamic programming concepts. + +## 10. References + +- [GeeksforGeeks - Non-negative Integers without Consecutive Ones](https://www.geeksforgeeks.org/non-negative-integers-without-consecutive-ones/) +- [LeetCode - Non-negative Integers without Consecutive Ones](https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/) + + +- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/) + +This Markdown file includes a detailed explanation of the problem, an algorithmic approach, code implementations in four programming languages, complexity analysis, advantages and disadvantages, and references. \ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/601-Human-Traffic-of-stadium.md b/solutions/lc-solutions/0600-0699/601-Human-Traffic-of-stadium.md new file mode 100644 index 0000000..70f9069 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/601-Human-Traffic-of-stadium.md @@ -0,0 +1,122 @@ +--- +id: human-traffic-of-stadium +title: Human-Traffic-Of-Stadium +sidebar_label: Human Traffic Of Stadium +tags: + - Sql + - Database + - Pandas +description: "This question solve important question of sql which gives us knowledge about writing of sql command." +--- + +# Non-negative Integers without Consecutive Ones + +## 1. Problem Description +``` ++---------------+---------+ +| Column Name | Type | ++---------------+---------+ +| id | int | +| visit_date | date | +| people | int | ++---------------+---------+ +visit_date is the column with unique values for this table. +Each row of this table contains the visit date and visit id to the stadium with the number of people during the visit. +As the id increases, the date increases as well. +``` +Write a solution to display the records with three or more rows with consecutive `id`'s, and the number of people is greater than or equal to 100 for each. + +Return the result table ordered by `visit_date` in ascending order. + +The result format is in the following example. +## 2. Examples + +### Example 1: +**Input:** +``` +Stadium table: ++------+------------+-----------+ +| id | visit_date | people | ++------+------------+-----------+ +| 1 | 2017-01-01 | 10 | +| 2 | 2017-01-02 | 109 | +| 3 | 2017-01-03 | 150 | +| 4 | 2017-01-04 | 99 | +| 5 | 2017-01-05 | 145 | +| 6 | 2017-01-06 | 1455 | +| 7 | 2017-01-07 | 199 | +| 8 | 2017-01-09 | 188 | ++------+------------+-----------+ +``` +**Output:** +``` ++------+------------+-----------+ +| id | visit_date | people | ++------+------------+-----------+ +| 5 | 2017-01-05 | 145 | +| 6 | 2017-01-06 | 1455 | +| 7 | 2017-01-07 | 199 | +| 8 | 2017-01-09 | 188 | ++------+------------+-----------+ +``` +**Explanation:** +The four rows with ids 5, 6, 7, and 8 have consecutive ids and each of them has >= 100 people attended. Note that row 8 was included even though the visit_date was not the next day after row 7. +The rows with ids 2 and 3 are not included because we need at least three consecutive ids. + +### Idea +I've seen pretty many solutions using join of three tables or creating temporary tables with `n^3 `rows. With my `5-years`' working experience on data analysis, I can guarantee you this method will cause you "out of spool space" issue when you deal with a large table in big data field. + +I recommend you to learn and master window functions like `lead`, `lag` and use them as often as you can in your codes. These functions are very fast, and whenever you find yourself creating duplicate temp tables, you should ask yourself: can I solve this with window functions. + + +## 5. Implementation (Code for 4 Languages) + + + + ```Pandas + import pandas as pd + +def human_traffic(stadium: pd.DataFrame) -> pd.DataFrame: + stadium = stadium[stadium.people >= 100].sort_values(by='id') + third = (stadium.id.diff() == 1)\ + & (stadium.id.diff().shift(1) == 1) + return stadium[third | third.shift(-1) | third.shift(-2)] + + + ``` + + + + ```SQL + SELECT ID + , visit_date + , people +FROM ( + SELECT ID + , visit_date + , people + , LEAD(people, 1) OVER (ORDER BY id) nxt + , LEAD(people, 2) OVER (ORDER BY id) nxt2 + , LAG(people, 1) OVER (ORDER BY id) pre + , LAG(people, 2) OVER (ORDER BY id) pre2 + FROM Stadium +) cte +WHERE (cte.people >= 100 AND cte.nxt >= 100 AND cte.nxt2 >= 100) + OR (cte.people >= 100 AND cte.nxt >= 100 AND cte.pre >= 100) + OR (cte.people >= 100 AND cte.pre >= 100 AND cte.pre2 >= 100) + ``` + + + + +### Complexity Analysis +**Time Complexity:** $O(nlogn)$ + + +**Space Complexity:** $O(n)$ + +## 10. References + +- [LeetCode - Human-Traffic-Of-Stadium](https://leetcode.com/problems/human-traffic-of-stadium/solutions/911779/mysql-use-window-function-for-big-data/) + + diff --git a/solutions/lc-solutions/0600-0699/602-friend-requests-2.md b/solutions/lc-solutions/0600-0699/602-friend-requests-2.md new file mode 100644 index 0000000..773a96a --- /dev/null +++ b/solutions/lc-solutions/0600-0699/602-friend-requests-2.md @@ -0,0 +1,130 @@ +--- +id: friend-requests-ii-who-has-the-most-friends +title: Friend Requests II Who Has the Most Friends +sidebar_label: Friend Requests II +tags: [sql, database, pandas] +description: "This question solve important question of sql which gives us knowledge about writing of sql command." +--- + +## 1. Problem Description +``` ++----------------+---------+ +| Column Name | Type | ++----------------+---------+ +| requester_id | int | +| accepter_id | int | +| accept_date | date | ++----------------+---------+ +(requester_id, accepter_id) is the primary key (combination of columns with unique values) for this table. +This table contains the ID of the user who sent the request, the ID of the user who received the request, and the date when the request was accepted. + +``` +Write a solution to find the people who have the most friends and the most friends number. + +The test cases are generated so that only one person has the most friends. + +The result format is in the following example. +## 2. Examples + +### Example 1: +**Input:** +``` +RequestAccepted table: ++--------------+-------------+-------------+ +| requester_id | accepter_id | accept_date | ++--------------+-------------+-------------+ +| 1 | 2 | 2016/06/03 | +| 1 | 3 | 2016/06/08 | +| 2 | 3 | 2016/06/08 | +| 3 | 4 | 2016/06/09 | ++--------------+-------------+-------------+ + +``` +**Output:** +``` ++----+-----+ +| id | num | ++----+-----+ +| 3 | 3 | ++----+-----+ + +``` +**Explanation:** +The person with id 3 is a friend of people 1, 2, and 4, so he has three friends in total, which is the most number than any others. + +### Idea +- Combine two columns into one list to find all people who either sent or received friend requests. +``` + SELECT β†’ This command retrieves data from a database + +AS β†’ This command renames a column with an alias (temporary name). In most database languages, we can skip the AS keyword and get the same result + +UNION ALL β†’ This operator combines the result-set of two or more SELECT statements (every SELECT statement must have the same number/data type/order of columns). It returns all rows from the query and it does not remove duplicate rows between the various SELECT statements +``` +- Calculate the number of friends each person has. +``` +COUNT() β†’ This function returns the number of rows + +Asterisk (*) β†’ This symbol specifies that the query should return all columns of the queried tables +``` +- Group the results to show all records related to the same person. +``` +GROUP BY β†’ This command groups rows that have the same values into summary rows, typically to perform aggregate functions on them +``` +- Arrange the results by the number of friends in descending order. +``` +ORDER BY β†’ This command sorts the result-set in ascending (smallest to largest) order by default + +DESC β†’ This keyword sorts the records in descending (largest to smallest) order +``` +- Show the person with the most friends. +``` +LIMIT β†’ This clause specifies the number of records to return +``` + +## 5. Implementation + + + + ```Pandas + import pandas as pd + +def most_friends(request_accepted: pd.DataFrame) -> pd.DataFrame: + + ctr = Counter(chain(request_accepted.requester_id.to_list(), + request_accepted. accepter_id.to_list())) + + mx= max(ctr, key = lambda x: ctr[x]) + + return pd.DataFrame({'id':[mx], 'num':[ctr[mx]]}) + + ``` + + + + ```SQL + SELECT id, COUNT(*) AS num +FROM ( + SELECT requester_id AS id FROM RequestAccepted + UNION ALL + SELECT accepter_id FROM RequestAccepted +) AS friends_count +GROUP BY id +ORDER BY num DESC +LIMIT 1; + ``` + + + + +### Complexity Analysis +**Time Complexity:** $O(n)$ + + +**Space Complexity:** $O(u)$ where `N ~ len(request_accepted)` and `U ~ the count of unique ids`. + +## 10. References + +- [LeetCode - Friend Requests II: Who Has the Most Friends](https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends/solutions/3803211/union-all-is-what-you-need-don-t-overcomplicate/) + + diff --git a/solutions/lc-solutions/0600-0699/605-can-place-flowers.md b/solutions/lc-solutions/0600-0699/605-can-place-flowers.md new file mode 100644 index 0000000..12a462c --- /dev/null +++ b/solutions/lc-solutions/0600-0699/605-can-place-flowers.md @@ -0,0 +1,137 @@ +--- +id: can-place-flowers +title: Can Place Flowers (Leetcode) +sidebar_label: 0605-CanPlaceFlowers +description: You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Can Place Flowers](https://leetcode.com/problems/can-place-flowers/description/) | [Can Place Flowers Solution on LeetCode](https://leetcode.com/problems/can-place-flowers/solutions) | [Aaradhya Singh ](https://leetcode.com/u/keira_09/) | + + +## Problem Description + +You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. + +Given an integer array flowerbed containing $0$'s and $1$'s, where $0$ means empty and 1 means not empty, and an integer $n$, return true if $n$ new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise. + +### Examples + +#### Example 1 + +- **Input:** $flowerbed = [1,0,0,0,1], n = 1$ +- **Output:** $true$ + + +#### Example 2 + +- **Input:** $flowerbed = [1,0,0,0,1], n = 2$ +- **Output:** $false$ + +### Constraints + +- $1 <= flowerbed.length <= 2 * 104$ +- $flowerbed[i]$ is 0 or 1. +- There are no two adjacent flowers in $flowerbed$. +- $1 <= k <= 109$ + + +### Intuition + +The code aims to determine if it's possible to plant n flowers in a flowerbed without violating the no-adjacent-flowers rule. It iterates through the flowerbed array and checks if a flower can be planted at each position by ensuring the current position and its adjacent positions are empty (or out of bounds). If a flower can be planted, it updates the position and decrements the count of flowers left to plant. The process continues until either all flowers are planted or all positions are checked. If the count of flowers to be planted reaches zero, it returns true, indicating success; otherwise, it returns false. + + +### Approach + +1. **Initialize Variables:** + + - Determine the size of the flowerbed array. + +2. **Iterate Through the Flowerbed:** + + - Use a for loop to traverse each position in the flowerbed array. + - Continue the loop as long as there are positions to check and flowers to plant (n > 0). + +3. **Check Conditions for Planting a Flower:** + + - At each position i, check if the current position is empty (flowerbed[i] == 0). + - Also, check if the previous position (if it exists) is empty or out of bounds (i == 0 || flowerbed[i - 1] == 0). + - Similarly, check if the next position (if it exists) is empty or out of bounds (i == size - 1 || flowerbed[i + 1] == 0). + +4. **Plant the Flower:** + + - If all conditions are met, plant a flower at position i by setting flowerbed[i] = 1. + - Decrease the count of flowers left to plant (n--). + +5. **Check if All Flowers Are Planted:** + + - After the loop, check if the count of flowers left to plant is zero. + - If n is zero, return true indicating that all flowers have been successfully planted. + - If n is not zero, return false indicating that it's not possible to plant all n flowers. + +### Solution Code + +#### Python + +```py +class Solution: + def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: + size = len(flowerbed) + + for i in range(size): + if n == 0: + return True + if flowerbed[i] == 0 and (i == 0 or flowerbed[i - 1] == 0) and (i == size - 1 or flowerbed[i + 1] == 0): + flowerbed[i] = 1 # Place a flower + n -= 1 # Decrease the remaining flowers to place + + return n == 0 +``` + +#### Java + +```java +class Solution { + public boolean canPlaceFlowers(int[] flowerbed, int n) { + int size = flowerbed.length; + + for (int i = 0; i < size && n > 0; i++) { + if (flowerbed[i] == 0 && + (i == 0 || flowerbed[i - 1] == 0) && + (i == size - 1 || flowerbed[i + 1] == 0)) { + flowerbed[i] = 1; // Place a flower + n--; // Decrease the remaining flowers to place + } + } + + return n == 0; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + bool canPlaceFlowers(vector& flowerbed, int n) { + int size = flowerbed.size(); + for (int i = 0; i < size && n > 0; i++) { + if (flowerbed[i] == 0 && + (i == 0 || flowerbed[i - 1] == 0) && + (i == size - 1 || flowerbed[i + 1] == 0)) { + flowerbed[i] = 1; // Place a flower + n--; // Decrease the remaining flowers to place + } + } + return n == 0; + } +}; +``` + +### Conclusion + +The provided code effectively determines whether it is possible to plant n flowers in a given flowerbed array without violating the no-adjacent-flowers rule. By iterating through the array and checking each position for the possibility of planting a flower based on the state of the adjacent positions, the code ensures that flowers are planted only where allowed. The solution modifies the array in place and uses a greedy approach to place as many flowers as possible. The time complexity of this approach is $O(n)$, where nn is the length of the flowerbed array, as each position is checked once. The space complexity is $O(1)$ since the solution only uses a constant amount of extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/622-design-circular-queue.md b/solutions/lc-solutions/0600-0699/622-design-circular-queue.md new file mode 100644 index 0000000..4505eee --- /dev/null +++ b/solutions/lc-solutions/0600-0699/622-design-circular-queue.md @@ -0,0 +1,321 @@ +--- +id: design-circular-queue +title: Design Circular Queue (Leetcode) +sidebar_label: 0622-DesignCircularQueue +description: Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer".One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Design Circular Queue](https://leetcode.com/problems/design-circular-queue/description/) | [Design Circular Queue Solution on LeetCode](https://leetcode.com/problems/design-circular-queue/solutions) | [Aaradhya Singh ](https://leetcode.com/u/keira_09/) | + + +## Problem Description + +Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer". + +One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values. + +Implement the $MyCircularQueue$ class: + +- $MyCircularQueue(k)$ Initializes the object with the size of the queue to be k. +- $int Front()$ Gets the front item from the queue. If the queue is empty, return -1. +- $int Rear()$ Gets the last item from the queue. If the queue is empty, return -1. +- $boolean enQueue(int value)$ Inserts an element into the circular queue. Return true if the operation is successful. +- $boolean deQueue()$ Deletes an element from the circular queue. Return true if the operation is successful. +- $boolean isEmpty()$ Checks whether the circular queue is empty or not. +- $boolean isFull()$ Checks whether the circular queue is full or not. + +You must solve the problem without using the built-in queue data structure in your programming language. + +### Examples + +#### Example 1 + +- **Input:** $["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"]$ +$[[3], [1], [2], [3], [4], [], [], [], [4], []]$ +- **Output:** $[null, true, true, true, false, 3, true, true, true, 4]$ +- **Explanation:** +MyCircularQueue myCircularQueue = new MyCircularQueue(3);
+myCircularQueue.enQueue(1); // return True +myCircularQueue.enQueue(2); // return True +myCircularQueue.enQueue(3); // return True +myCircularQueue.enQueue(4); // return False +myCircularQueue.Rear(); // return 3 +myCircularQueue.isFull(); // return True +myCircularQueue.deQueue(); // return True +myCircularQueue.enQueue(4); // return True +myCircularQueue.Rear(); // return 4 + + + +### Constraints + +- $1 <= k <= 1000$ +- $0 <= value <= 1000$ +- At most 3000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull. + + +### Intuition + +The code implements a circular queue, which is a data structure that efficiently manages a fixed-size queue with wrap-around capabilities. The circular queue is implemented using an array and maintains pointers for the front and rear of the queue, along with a counter to keep track of the number of elements. The enQueue function adds an element to the rear of the queue, adjusting the rear pointer to wrap around if necessary, while the deQueue function removes an element from the front, adjusting the front pointer similarly. The Front and Rear functions return the front and rear elements, respectively. The isEmpty and isFull functions check if the queue is empty or full based on the count. This design allows for efficient enqueue and dequeue operations while maintaining a fixed size and supporting wrap-around indexing. + +### Approach + +1. **Initialization:** + + - The constructor MyCircularQueue(int k) initializes the circular queue with a fixed size k. It allocates memory for the array arr of size k, and initializes the front and rear pointers to -1 to indicate an empty queue. The count variable is also initialized to 0 to keep track of the number of elements in the queue. + +2. **Enqueue Operation:** + + - The enQueue(int value) method adds an element to the rear of the queue. + - First, it checks if the queue is full by calling the isFull() method. + - If the queue is full, it returns false. + - If the queue is empty (checked using isEmpty()), it sets the front pointer to 0. + - It then calculates the new position of the rear pointer using modulo operation (rear + 1) % size to handle wrap-around. + - The element is added to the new rear position, and the count is incremented. + - Finally, it returns true indicating the enqueue operation was successful. + +3. **Dequeue Operation:** + + - The deQueue() method removes an element from the front of the queue. + - First, it checks if the queue is empty by calling the isEmpty() method. + - If the queue is empty, it returns false. + - If the front and rear pointers are equal, it means the queue will be empty after this operation, so both pointers are reset to -1. + - Otherwise, it calculates the new position of the front pointer using modulo operation (front + 1) % size to handle wrap-around. + - The count is decremented. + - Finally, it returns true indicating the dequeue operation was successful. + +4. **Front and Rear Operations:** + + - The Front() method returns the element at the front of the queue. + - It checks if the queue is empty using isEmpty(). + - If the queue is empty, it returns -1. + - Otherwise, it returns the element at the front pointer. + - The Rear() method returns the element at the rear of the queue. + - It checks if the queue is empty using isEmpty(). + - If the queue is empty, it returns -1. + - Otherwise, it returns the element at the rear pointer. + +5. **Empty and Full Checks:** + + - The isEmpty() method checks if the queue is empty by comparing the count to 0. + - If count is 0, it returns true; otherwise, it returns false. + - The isFull() method checks if the queue is full by comparing the count to the size of the queue. + - If count is equal to size, it returns true; otherwise, it returns false. + +### Solution Code + +#### Python + +```py +class MyCircularQueue: + def __init__(self, k: int): + self.size = k + self.arr = [0] * k + self.front = -1 + self.rear = -1 + self.count = 0 + + def enQueue(self, value: int) -> bool: + if self.isFull(): + return False + + if self.isEmpty(): + self.front = 0 + + self.rear = (self.rear + 1) % self.size + self.arr[self.rear] = value + self.count += 1 + return True + + def deQueue(self) -> bool: + if self.isEmpty(): + return False + + if self.front == self.rear: + self.front = self.rear = -1 + else: + self.front = (self.front + 1) % self.size + + self.count -= 1 + return True + + def Front(self) -> int: + if self.isEmpty(): + return -1 + + return self.arr[self.front] + + def Rear(self) -> int: + if self.isEmpty(): + return -1 + + return self.arr[self.rear] + + def isEmpty(self) -> bool: + return self.count == 0 + + def isFull(self) -> bool: + return self.count == self.size +``` + +#### Java + +```java +class MyCircularQueue { + private int[] arr; + private int size; + private int front; + private int rear; + private int count; + + public MyCircularQueue(int k) { + size = k; + arr = new int[size]; + front = -1; + rear = -1; + count = 0; + } + + public boolean enQueue(int value) { + if (isFull()) { + return false; + } + + if (isEmpty()) { + front = 0; + } + + rear = (rear + 1) % size; + arr[rear] = value; + count++; + return true; + } + + public boolean deQueue() { + if (isEmpty()) { + return false; + } + + if (front == rear) { + front = rear = -1; + } else { + front = (front + 1) % size; + } + + count--; + return true; + } + + public int Front() { + if (isEmpty()) { + return -1; + } + + return arr[front]; + } + + public int Rear() { + if (isEmpty()) { + return -1; + } + + return arr[rear]; + } + + public boolean isEmpty() { + return count == 0; + } + + public boolean isFull() { + return count == size; + } +} +``` + +#### C++ + +```cpp +class MyCircularQueue { +private: + int* arr; + int size; + int front; + int rear; + int count; + +public: + MyCircularQueue(int k) { + size = k; + arr = new int[size]; + front = -1; + rear = -1; + count = 0; + } + + ~MyCircularQueue() { + delete[] arr; + } + + bool enQueue(int value) { + if (isFull()) { + return false; // Queue is full + } + + if (isEmpty()) { + front = 0; + } + + rear = (rear + 1) % size; + arr[rear] = value; + count++; + return true; + } + + bool deQueue() { + if (isEmpty()) { + return false; // Queue is empty + } + + if (front == rear) { + front = rear = -1; + } else { + front = (front + 1) % size; + } + + count--; + return true; + } + + int Front() { + if (isEmpty()) { + return -1; // Queue is empty + } + + return arr[front]; + } + + int Rear() { + if (isEmpty()) { + return -1; // Queue is empty + } + + return arr[rear]; + } + + bool isEmpty() { + return count == 0; + } + + bool isFull() { + return count == size; + } +}; +``` + +### Conclusion + +The provided code implementation of a circular queue offers efficient enqueue, dequeue, and access operations with a fixed-size capacity. Enqueue and dequeue operations have a time complexity of $O(1)$, as they involve updating pointers and array accesses. Accessing the front or rear element also has a time complexity of $O(1)$. The space complexity of the circular queue is $O(n)$, where $n$ is the fixed size of the queue, as it uses an array to store the elements. Overall, this implementation provides a convenient and performant solution for managing a circular queue with constant-time complexity for core operations and linear space complexity. \ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/628-maximum-product-of-three-numbers.md b/solutions/lc-solutions/0600-0699/628-maximum-product-of-three-numbers.md new file mode 100644 index 0000000..0150916 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/628-maximum-product-of-three-numbers.md @@ -0,0 +1,83 @@ +--- +id: maximum-product-of-three-numbers +title: Maximum Product of Three Numbers +sidebar_label: 628 Maximum Product of Three Numbers +tags: + - Math + - Vector + - LeetCode + - C++ +description: "This is a solution to the Maximum Product of Three Numbers problem on LeetCode." +--- + +## Problem Description + +Given an integer array nums, find three numbers whose product is maximum and return the maximum product. + +### Examples + +**Example 1:** + +``` + +Input: nums = [1,2,3] +Output: 6 +``` + +**Example 2:** + +``` +Input: nums = [1,2,3,4] +Output: 24 +``` + +**Example 2:** + +``` +Input: nums = [-1,-2,-3] +Output: -6 +``` + +### Constraints + +- $3 \leq \text{nums.length} \leq 10^4$. +- $-1000 \leq \text{Node.val} \leq 1000$. + +### Approach + +To solve this problem(third maximum element) we will sort the given array and then return the product of last three numbers but there are chances that product of two smallest negative number(starting first two numbers generally) with largest positive number will be greater than last three numbers product so we will check that also. + +#### Code in C++ + +```cpp +class Solution { +public: + int maximumProduct(vector& nums) { + sort(nums.begin(),nums.end()); + int n=nums.size(); + int l=nums[n-3]*nums[n-2]*nums[n-1]; // prouduct of maximum numbers + int p=nums[0]*nums[1]*nums[n-1];// here we are checking if (num[0] and num[1] is negative so may this product will be greater than the product(l) which is product of last three maximum numbers) + if(p>l){ + return p; + } + return l; + } +}; +``` + +#### code in Python + +```python +class Solution(object): + def maximumProduct(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + nums.sort() + p=nums[0]*nums[1]*nums[-1] #Calculate the product of the two smallest numbers (negative numbers) and the largest number in the sorted list. + l=nums[-1]*nums[-2]*nums[-3] #Calculate the product of the three largest numbers in the sorted list. + return max(l,p) + +``` + diff --git a/solutions/lc-solutions/0600-0699/641-design-circular-deque.md b/solutions/lc-solutions/0600-0699/641-design-circular-deque.md new file mode 100644 index 0000000..268c2db --- /dev/null +++ b/solutions/lc-solutions/0600-0699/641-design-circular-deque.md @@ -0,0 +1,486 @@ +--- +id: design-circular-deque +title: Design Circular Deque (Leetcode) +sidebar_label: 0641-DesignCircularDeque +description: Design your implementation of the circular double-ended queue (deque). +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Design Circular Deque](https://leetcode.com/problems/design-circular-deque/description/) | [Design Circular Deque Solution on LeetCode](https://leetcode.com/problems/design-circular-deque/solutions) | [Aaradhya Singh ](https://leetcode.com/u/keira_09/) | + + +## Problem Description + +Design your implementation of the circular double-ended queue (deque). + +Implement the MyCircularDeque class: + +- **MyCircularDeque(int k)** Initializes the deque with a maximum size of $k$. +- **boolean insertFront()** Adds an item at the front of Deque. Returns true if the operation is successful, or false otherwise. +- **boolean insertLast()** Adds an item at the rear of Deque. Returns true if the operation is successful, or false otherwise. +- **boolean deleteFront()** Deletes an item from the front of Deque. Returns true if the operation is successful, or false otherwise. +- **boolean deleteLast()** Deletes an item from the rear of Deque. Returns true if the operation is successful, or false otherwise. +- **int getFront()** Returns the front item from the Deque. Returns -1 if the deque is empty. +- **int getRear()** Returns the last item from Deque. Returns -1 if the deque is empty. +- **boolean isEmpty()** Returns true if the deque is empty, or false otherwise. +- **boolean isFull()** Returns true if the deque is full, or false otherwise. + + +### Examples + +#### Example 1 + +- **Input:** $["MyCircularDeque", "insertLast", "insertLast", "insertFront", "insertFront", "getRear", "isFull", "deleteLast", "insertFront", "getFront"]$ +$[[3], [1], [2], [3], [4], [], [], [], [4], []]$ +- **Output:** $[null, true, true, true, false, 2, true, true, true, 4]$ +- **Explanation:** + +```py +MyCircularDeque myCircularDeque = new MyCircularDeque(3); +myCircularDeque.insertLast(1); // return True +myCircularDeque.insertLast(2); // return True +myCircularDeque.insertFront(3); // return True +myCircularDeque.insertFront(4); // return False, the queue is full. +myCircularDeque.getRear(); // return 2 +myCircularDeque.isFull(); // return True +myCircularDeque.deleteLast(); // return True +myCircularDeque.insertFront(4); // return True +myCircularDeque.getFront(); // return 4 +``` + +### Constraints + +- $1 \leq k \leq 1000$ +- $0 \leq value \leq 1000$ +- At most 2000 calls will be made to insertFront, insertLast, deleteFront, deleteLast, getFront, getRear, isEmpty, isFull. + + +### Intuition + +The intuition behind the implementation of the $MyCircularDeque$ class is to efficiently manage a double-ended queue (deque) using a circular array. This design allows for constant-time insertion and deletion operations at both the front and rear ends. By leveraging the circular nature of the array, the deque can wrap around to the beginning of the array when it reaches the end, thereby making optimal use of the available space. The class maintains front and rear pointers to track the positions for insertion and deletion, and checks for conditions such as the deque being full or empty to handle these operations appropriately. This circular array implementation ensures that operations are performed in $O(1)$ time, making it highly efficient for managing double-ended queues. + + +### Approach + +1. **Initialization:** + +- The **MyCircularDeque** class is initialized with a fixed size $k$. +- An array arr of size $k$ is created to store the deque elements. +- Two pointers front and rear are initialized to -1 to indicate an empty deque. + +2. **Insert Front:** + +- Check if the deque is full. If it is, return false. +- If the deque is empty, set both front and rear to 0. +- If front is at the beginning of the array and the array is not full, wrap around front to the end of the array. +- Otherwise, decrement front. +- Insert the value at the front position. + +3. **Insert Last:** + +- Check if the deque is full. If it is, return false. +- If the deque is empty, set both front and rear to 0. +- If rear is at the end of the array and the array is not full, wrap around rear to the beginning of the array. +- Otherwise, increment rear. +- Insert the value at the rear position. + +4. **Delete Front:** + +- Check if the deque is empty. If it is, return false. +- Retrieve the value at the front position and set that position to -1. +- If front equals rear, it means there is only one element, so reset both front and rear to -1. +- If front is at the end of the array, wrap around front to the beginning. +- Otherwise, increment front. + +5. **Delete Last:** + +- Check if the deque is empty. If it is, return false. +- Retrieve the value at the rear position and set that position to -1. +- If front equals rear, it means there is only one element, so reset both front and rear to -1. +- If rear is at the beginning of the array, wrap around rear to the end. +- Otherwise, decrement rear. + +6. **Get Front:** + +- Check if the deque is empty. If it is, return -1. +- Return the value at the front position. + +7. **Get Rear:** + +- Check if the deque is empty. If it is, return -1. +- Return the value at the rear position. + +8. **Is Empty:** + +- Return true if both front and rear are -1, indicating the deque is empty. +- Otherwise, return false. + +9. **Is Full:** + +- Return true if the deque is full. This is determined if front is 0 and rear is size - 1 or if rear + 1 modulo size equals front. +- Otherwise, return false. + +### Solution Code + +#### Python + +```py +class MyCircularDeque: + + def __init__(self, k: int): + self.size = k + self.arr = [-1] * self.size + self.front = -1 + self.rear = -1 + + def insertFront(self, value: int) -> bool: + if self.isFull(): + return False + + if self.isEmpty(): + self.front = self.rear = 0 + elif self.front == 0: + self.front = self.size - 1 + else: + self.front -= 1 + + self.arr[self.front] = value + return True + + def insertLast(self, value: int) -> bool: + if self.isFull(): + return False + + if self.isEmpty(): + self.front = self.rear = 0 + elif self.rear == self.size - 1: + self.rear = 0 + else: + self.rear += 1 + + self.arr[self.rear] = value + return True + + def deleteFront(self) -> bool: + if self.isEmpty(): + return False + + self.arr[self.front] = -1 + + if self.front == self.rear: + self.front = self.rear = -1 + elif self.front == self.size - 1: + self.front = 0 + else: + self.front += 1 + + return True + + def deleteLast(self) -> bool: + if self.isEmpty(): + return False + + self.arr[self.rear] = -1 + + if self.front == self.rear: + self.front = self.rear = -1 + elif self.rear == 0: + self.rear = self.size - 1 + else: + self.rear -= 1 + + return True + + def getFront(self) -> int: + if self.isEmpty(): + return -1 + return self.arr[self.front] + + def getRear(self) -> int: + if self.isEmpty(): + return -1 + return self.arr[self.rear] + + def isEmpty(self) -> bool: + return self.front == -1 and self.rear == -1 + + def isFull(self) -> bool: + return (self.front == 0 and self.rear == self.size - 1) or (self.front != 0 and (self.rear + 1) % self.size == self.front) +``` + +#### Java + +```java +class MyCircularDeque { + + private int[] arr; + private int size; + private int front; + private int rear; + + public MyCircularDeque(int k) { + size = k; + arr = new int[size]; + front = -1; + rear = -1; + } + + public boolean insertFront(int value) { + if (isFull()) { + return false; + } + + if (isEmpty()) { + front = rear = 0; + } else if (front == 0) { + front = size - 1; + } else { + front--; + } + + arr[front] = value; + return true; + } + + public boolean insertLast(int value) { + if (isFull()) { + return false; + } + + if (isEmpty()) { + front = rear = 0; + } else if (rear == size - 1) { + rear = 0; + } else { + rear++; + } + + arr[rear] = value; + return true; + } + + public boolean deleteFront() { + if (isEmpty()) { + return false; + } + + arr[front] = -1; + + if (front == rear) { + front = rear = -1; + } else if (front == size - 1) { + front = 0; + } else { + front++; + } + + return true; + } + + public boolean deleteLast() { + if (isEmpty()) { + return false; + } + + arr[rear] = -1; + + if (front == rear) { + front = rear = -1; + } else if (rear == 0) { + rear = size - 1; + } else { + rear--; + } + + return true; + } + + public int getFront() { + if (isEmpty()) { + return -1; + } + return arr[front]; + } + + public int getRear() { + if (isEmpty()) { + return -1; + } + return arr[rear]; + } + + public boolean isEmpty() { + return front == -1 && rear == -1; + } + + public boolean isFull() { + return (front == 0 && rear == size - 1) || (front != 0 && (rear + 1) % size == front); + } +} +``` + +#### C++ + +```cpp +class MyCircularDeque { +public: + int* arr; + int size; + int front; + int rear; + + MyCircularDeque(int k) { + size = k; + arr = new int[size]; + front = -1; + rear = -1; + } + + bool insertFront(int value) { + if (isFull()) // if array is full. + { + return false; + } + + else if (isEmpty()) // if array is empty + { + front = rear = 0; + } + + else if (front == 0 && rear != size - 1) // maintaining circulation + { + front = size - 1; + } + + else // normal flow + { + front--; + } + arr[front] = value; + return true; + } + + bool insertLast(int value) { + if (isFull()) // if array is full. + { + return false; + } + + else if (isEmpty()) // if array is empty + { + front = rear = 0; + } + + else if (rear == size - 1 && front != 0) // maintaining circulation + { + rear = 0; + } + + else // normal flow + { + rear++; + } + arr[rear] = value; + return true; + } + + bool deleteFront() { + if (isEmpty()) // if array is empty + { + return false; + } + + int ans = arr[front]; + arr[front] = -1; + if (front == rear) // if one element + { + front = rear = -1; + } + + else if (front == size - 1) // maintaining circulation + { + front = 0; + } + + else + { + front++; + } + return true; + } + + bool deleteLast() { + if (isEmpty()) // if array is empty + { + return false; + } + + int ans = arr[rear]; + arr[rear] = -1; + if (front == rear) // if one element + { + front = rear = -1; + } + + else if (rear == 0) // maintaining circulation + { + rear = size - 1; + } + + else + { + rear--; + } + return true; + } + + int getFront() { + if (isEmpty()) // if array is empty + { + return -1; + } + + int ans = arr[front]; + return ans; + } + + int getRear() { + if (isEmpty()) // if array is empty + { + return -1; + } + + int ans = arr[rear]; + return ans; + } + + bool isEmpty() { + if (front == -1 && rear == -1) + { + return true; + } + else + { + return false; + } + } + + bool isFull() { + if ((front == 0 && rear == size - 1) || (front != 0 && (rear + 1) % size == front)) + { + return true; + } + else + { + return false; + } + } +}; +``` + +### Conclusion + +The **MyCircularDeque** class effectively implements a circular deque using an array, allowing for efficient insertion and deletion operations at both the front and rear. The class maintains pointers for the front and rear of the deque and uses modular arithmetic to handle wrapping around the array. The isFull and isEmpty methods ensure correct operation and prevent overflow or underflow. The time complexity for each operation (insertFront, insertLast, deleteFront, deleteLast) is $O(1)$, making the operations highly efficient. The space complexity is $O(k)$, where $k$ is the size of the deque, due to the fixed-size array used for storage. diff --git a/solutions/lc-solutions/0600-0699/643-maximum-average-subarray-I.md b/solutions/lc-solutions/0600-0699/643-maximum-average-subarray-I.md new file mode 100644 index 0000000..ec51f08 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/643-maximum-average-subarray-I.md @@ -0,0 +1,164 @@ +--- +id: maximum-average-subarray-1 +title: Maximum Average Subarray I (Leetcode) +sidebar_label: 0643-MaximumAverageSubarrayI +description: You are given an integer array nums consisting of n elements, and an integer k.Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/description/) | [Maximum Average Subarray I Solution on LeetCode](https://leetcode.com/problems/maximum-average-subarray-i/solutions) | [Aaradhya Singh ](https://leetcode.com/u/keira_09/) | + + +## Problem Description + +You are given an integer array nums consisting of n elements, and an integer k. + +Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted. + +### Examples + +#### Example 1 + +- **Input:** $nums = [1,12,-5,-6,50,3], k = 4$ +- **Output:** $12.75000$ +- **Explanation:** Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 + + +#### Example 2 + +- **Input:** $nums = [5], k = 1$ +- **Output:** $5.00000$ + +### Constraints + +- $n == nums.length$ +- $1 <= k <= n <= 105$ +- $-104 <= nums[i] <= 104$ + + +### Intuition + +The goal of this code is to find the maximum average value of any contiguous subarray of length k within the given array nums. The solution uses a sliding window approach to efficiently compute the sum of elements for each subarray of length k. Initially, it calculates the sum of the first k elements. Then, for each subsequent subarray, it adjusts the sum by adding the next element in the sequence and subtracting the first element of the previous subarray, thereby maintaining a running sum. This approach ensures that the sum is recalculated in constant time, making the algorithm efficient. The maximum sum encountered is then divided by k to obtain the maximum average. + + +### Approach + +1. **Initialization:** + +- Create a variable result to store the maximum average. +- Create a variable number and initialize it to the lowest possible double value using `std::numeric_limits::lowest()`. +- Create a variable temp to keep track of the current sum of the subarray of length k. +- Create a variable n and set it equal to k. + +2. **Calculate Initial Sum:** + +- Iterate through the first k elements of the array nums and calculate their sum. Store this sum in temp. + +3. **Sliding Window Calculation:** + +- Use a for loop to iterate through the array starting from the element at index k. +- For each iteration, update temp by adding the current element (nums[i + k - 1]) and subtracting the element that is no longer in the subarray (nums[i - 1]). +- Update number to be the maximum of temp and number. + +4. **Calculate Maximum Average:** + +- Divide number by k to get the maximum average of any subarray of length k. + +5. **Return Result:** + +- Return result, which now holds the maximum average. + +### Solution Code + +#### Python + +```py +import math + +class Solution: + def findMaxAverage(self, nums: List[int], k: int) -> float: + result = 0.0 + number = -math.inf + temp = 0.0 + n = k + + # Calculate the initial sum of the first k elements + for i in range(k): + temp += nums[i] + + number = max(temp, number) + + # Sliding window calculation + for i in range(1, len(nums) - k + 1): + temp = temp + nums[i + k - 1] - nums[i - 1] + number = max(temp, number) + + result = number / k + return result +``` + +#### Java + +```java +public class Solution { + public double findMaxAverage(int[] nums, int k) { + double result = 0.0; + double number = Double.NEGATIVE_INFINITY; + double temp = 0.0; + int n = k; + + // Calculate the initial sum of the first k elements + for (int i = 0; i < k; i++) { + temp += nums[i]; + } + + number = Math.max(temp, number); + + // Sliding window calculation + for (int i = 1; i <= nums.length - k; i++) { + temp = temp + nums[i + k - 1] - nums[i - 1]; + number = Math.max(temp, number); + } + + result = number / (double) k; + return result; + } +} +``` + +#### C++ + +```cpp +#include +class Solution { +public: + double findMaxAverage(vector& nums, int k) { + double result; + double number = std::numeric_limits::lowest(); + double temp = 0; + int n = k; + + for (int i = 0; i <= nums.size() - k ; ++i){ + if (i == 0) { + while (n != 0) { + temp += nums[i + n - 1] ; + n--; + } + } + + else {temp = temp + nums[i + k - 1] - nums[i - 1];} + number = max(temp , number); + } + + result = number / static_cast(k); + return result; + } +}; +``` + +### Conclusion + +The provided code implements a solution to find the maximum average of any contiguous subarray of length k within the given array nums. It employs a sliding window approach to efficiently compute the sum of elements for each subarray. The algorithm iterates through the array once, updating the sum and maximum average as it progresses. The time complexity of the solution is $O(n)$, where nn is the number of elements in the array nums, as it makes a single pass through the array. The space complexity is $O(1)$ since the algorithm uses only a constant amount of extra space regardless of the input size. \ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/645-set-mismatch.md b/solutions/lc-solutions/0600-0699/645-set-mismatch.md new file mode 100644 index 0000000..fd2d371 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/645-set-mismatch.md @@ -0,0 +1,169 @@ +--- +id: set mismatch +title: Set Mismatch +sidebar_label: 645-Set Mismatch +tags: + - Arrays + - Hashing + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Set Mismatch problem on LeetCode." +sidebar_position: 3 +--- + +## Problem Description + +You have a set of integers `s`, which originally contains all the numbers from 1 to `n`. Unfortunately, due to some error, one of the numbers in `s` got duplicated to another number in the set, which results in repetition of one number and loss of another number. + +You are given an integer array `nums` representing the data status of this set after the error. + +Find the number that occurs twice and the number that is missing and return them in the form of an array. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,2,4] +Output: [2,3] +``` + +**Example 2:** + +``` +Input: nums = [1,1] +Output: [1,2] +``` + +### Constraints + +- `2 <= nums.length <= 10^4` +- `1 <= nums[i] <= 10^4` + +--- + +## Solution for Find Error Numbers Problem + +To solve this problem, you need to identify the duplicated number and the missing number in the array. + +### Approach: Counting Frequency + +1. **Count Frequencies:** Use a dictionary or a list to count the frequency of each number in the array. +2. **Identify Duplicated and Missing Numbers:** + - The number with a frequency of 2 is the duplicated number. + - The number with a frequency of 0 (among the numbers from 1 to n) is the missing number. + +### Brute Force Approach + +The brute force approach involves iterating over the numbers from 1 to `n` and checking their frequency in the given array. This can be achieved by: + +1. Initializing an array to count the frequency of each number. +2. Iterating through the input array to update the frequency count. +3. Checking which number has a frequency of 2 (the duplicated number) and which number has a frequency of 0 (the missing number). + +### Optimized Approach + +The optimized approach avoids using extra space and iterates through the input array only twice: + +1. Iterate through the array and mark the corresponding indices as visited by flipping the sign of the elements. +2. In the second pass, the index with a positive value indicates the missing number, and the duplicate can be identified by the repeated index encountered in the first pass. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector findErrorNums(vector& nums) { + int n = nums.size(); + vector freq(n + 1, 0); + vector result(2, 0); + + + for (int num : nums) { + freq[num]++; + } + + + for (int i = 1; i <= n; i++) { + if (freq[i] == 2) result[0] = i; + else if (freq[i] == 0) result[1] = i; + } + + return result; + } +}; +``` + + + + + +```java +class Solution { + public int[] findErrorNums(int[] nums) { + int[] freq = new int[nums.length + 1]; + int[] result = new int[2]; + + + for (int num : nums) { + freq[num]++; + } + + + for (int i = 1; i < freq.length; i++) { + if (freq[i] == 2) result[0] = i; + else if (freq[i] == 0) result[1] = i; + } + + return result; + } +} +``` + + + + + +```python +class Solution: + def findErrorNums(self, nums: List[int]) -> List[int]: + freq = [0] * (len(nums) + 1) + result = [0, 0] + + + for num in nums: + freq[num] += 1 + + + for i in range(1, len(freq)): + if freq[i] == 2: + result[0] = i + elif freq[i] == 0: + result[1] = i + + return result +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(n)$, where `n` is the length of the input array. +- **Space Complexity**: $O(n)$, due to the frequency array used to count occurrences of each number. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/647-palindromic-substrings.md b/solutions/lc-solutions/0600-0699/647-palindromic-substrings.md new file mode 100644 index 0000000..0b4e21f --- /dev/null +++ b/solutions/lc-solutions/0600-0699/647-palindromic-substrings.md @@ -0,0 +1,182 @@ +--- +id: palindromic-substrings +title: Palindromic Substrings +sidebar_label: 647-Palindromic Substrings +tags: + - String Manipulation + - Dynamic Programming + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Palindromic Substrings problem on LeetCode." +sidebar_position: 11 +--- + +## Problem Description + +Given a string `s`, return the number of palindromic substrings in it.A string is a palindrome when it reads the same backward as forward. + +A substring is a contiguous sequence of characters within the string. + +### Examples + +**Example 1:** + +``` +Input: s = "abc" +Output: 3 +Explanation: Three palindromic strings: "a", "b", "c". +``` + +**Example 2:** + +``` +Input: s = "aaa" +Output: 6 +Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". +``` + +### Constraints + +- `1 <= s.length <= 1000` +- `s` consists of lowercase English letters. + +--- + +## Solution for Count Palindromic Substrings Problem + +To solve this problem, we need to count all the palindromic substrings in the given string `s`. + +### Approach: Expand Around Center + +The idea is to consider each possible center of a palindrome and expand outwards as long as we have a valid palindrome. For each center, count the palindromic substrings. + +#### Steps: + +1. **Identify Centers:** + - There are 2*n - 1 centers for palindromes in a string of length `n` (including the space between characters for even-length palindromes). + +2. **Expand Around Center:** + - For each center, expand outwards to check if the substring is a palindrome. If it is, increment the count. + +### Brute Force Approach + +The brute force approach involves checking all substrings and verifying if each substring is a palindrome. This is inefficient and has a time complexity of $O(n^3)$. + +### Optimized Approach + +The optimized approach, using the Expand Around Center method, has a time complexity of $O(n^2)$. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int countSubstrings(string s) { + int n = s.size(); + int count = 0; + + for (int i = 0; i < n; ++i) { + count += countPalindromesAroundCenter(s, i, i); // Odd length + count += countPalindromesAroundCenter(s, i, i + 1); // Even length + } + + return count; + } + +private: + int countPalindromesAroundCenter(const string& s, int left, int right) { + int count = 0; + + while (left >= 0 && right < s.size() && s[left] == s[right]) { + ++count; + --left; + ++right; + } + + return count; + } +}; +``` + + + + + +```java +class Solution { + public int countSubstrings(String s) { + int n = s.length(); + int count = 0; + + for (int i = 0; i < n; i++) { + count += countPalindromesAroundCenter(s, i, i); // Odd length + count += countPalindromesAroundCenter(s, i, i + 1); // Even length + } + + return count; + } + + private int countPalindromesAroundCenter(String s, int left, int right) { + int count = 0; + + while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { + count++; + left--; + right++; + } + + return count; + } +} +``` + + + + + +```python +class Solution: + def countSubstrings(self, s: str) -> int: + n = len(s) + count = 0 + + for i in range(n): + count += self.countPalindromesAroundCenter(s, i, i) # Odd length + count += self.countPalindromesAroundCenter(s, i, i + 1) # Even length + + return count + + def countPalindromesAroundCenter(self, s: str, left: int, right: int) -> int: + count = 0 + + while left >= 0 and right < len(s) and s[left] == s[right]: + count += 1 + left -= 1 + right += 1 + + return count +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(n^2)$, where `n` is the length of the input string `s`. +- **Space Complexity**: $O(1)$, as we only use constant extra space. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/648-replace-words.md b/solutions/lc-solutions/0600-0699/648-replace-words.md new file mode 100644 index 0000000..155f6fd --- /dev/null +++ b/solutions/lc-solutions/0600-0699/648-replace-words.md @@ -0,0 +1,262 @@ +--- +id: replace-words +title: Replace Words +sidebar_label: 648-Replace Words +tags: + - Trie + - Hash Table + - String Manipulation + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Replace Words problem on LeetCode." +sidebar_position: 3 +--- + +## Problem Description + +In English, we have a concept called a root, which can be followed by some other word to form another longer word - let's call this word a derivative. For example, when the root "help" is followed by the word "ful," we can form a derivative "helpful." + +Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the derivatives in the sentence with the root forming it. If a derivative can be replaced by more than one root, replace it with the root that has the shortest length. + +Return the sentence after the replacement. + +### Examples + +**Example 1:** + +``` +Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery" +Output: "the cat was rat by the bat" +``` + +**Example 2:** + +``` +Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs" +Output: "a a b c" +``` + +### Constraints + +- `1 <= dictionary.length <= 1000` +- `1 <= dictionary[i].length <= 100` +- `dictionary[i]` consists of only lowercase letters. +- `1 <= sentence.length <= 10^6` +- `sentence` consists of only lowercase letters and spaces. +- The number of words in `sentence` is in the range [1, 1000]. +- The length of each word in `sentence` is in the range [1, 1000]. +- Every two consecutive words in `sentence` will be separated by exactly one space. +- `sentence` does not have leading or trailing spaces. + +--- + +## Solution for Replace Words Problem + +To solve this problem, we need to efficiently replace the derivatives in the sentence with their respective roots from the dictionary. We can approach this problem using a Trie data structure for efficient prefix matching. + +### Approach: Trie Data Structure + +1. **Build the Trie:** + - Insert all the roots from the dictionary into a Trie. + - Each node in the Trie represents a character, and the path from the root to any node represents a prefix of one or more roots. + +2. **Replace Derivatives:** + - For each word in the sentence, traverse the Trie to find the shortest prefix (root). + - If found, replace the word with the root; otherwise, keep the word as is. + +### Code in Different Languages + + + + + +```cpp +class TrieNode { +public: + unordered_map children; + string word = ""; +}; + +class Trie { +public: + TrieNode* root; + + Trie() { + root = new TrieNode(); + } + + void insert(string word) { + TrieNode* node = root; + for (char c : word) { + if (node->children.find(c) == node->children.end()) { + node->children[c] = new TrieNode(); + } + node = node->children[c]; + } + node->word = word; + } + + string searchRoot(string word) { + TrieNode* node = root; + for (char c : word) { + if (node->children.find(c) == node->children.end()) { + return word; + } + node = node->children[c]; + if (!node->word.empty()) { + return node->word; + } + } + return word; + } +}; + +class Solution { +public: + string replaceWords(vector& dictionary, string sentence) { + Trie trie; + for (string root : dictionary) { + trie.insert(root); + } + + stringstream ss(sentence); + string word; + string result; + + while (ss >> word) { + if (!result.empty()) result += " "; + result += trie.searchRoot(word); + } + + return result; + } +}; +``` + + + + + +```java +class TrieNode { + Map children = new HashMap<>(); + String word = ""; +} + +class Trie { + TrieNode root; + + public Trie() { + root = new TrieNode(); + } + + public void insert(String word) { + TrieNode node = root; + for (char c : word.toCharArray()) { + node.children.putIfAbsent(c, new TrieNode()); + node = node.children.get(c); + } + node.word = word; + } + + public String searchRoot(String word) { + TrieNode node = root; + for (char c : word.toCharArray()) { + if (!node.children.containsKey(c)) { + return word; + } + node = node.children.get(c); + if (!node.word.isEmpty()) { + return node.word; + } + } + return word; + } +} + +class Solution { + public String replaceWords(List dictionary, String sentence) { + Trie trie = new Trie(); + for (String root : dictionary) { + trie.insert(root); + } + + String[] words = sentence.split(" "); + StringBuilder result = new StringBuilder(); + + for (String word : words) { + if (result.length() > 0) { + result.append(" "); + } + result.append(trie.searchRoot(word)); + } + + return result.toString(); + } +} +``` + + + + + +```python +class TrieNode: + def __init__(self): + self.children = {} + self.word = "" + +class Trie: + def __init__(self): + self.root = TrieNode() + + def insert(self, word): + node = self.root + for char in word: + if char not in node.children: + node.children[char] = TrieNode() + node = node.children[char] + node.word = word + + def searchRoot(self, word): + node = self.root + for char in word: + if char not in node.children: + return word + node = node.children[char] + if node.word: + return node.word + return word + +class Solution: + def replaceWords(self, dictionary: List[str], sentence: str) -> str: + trie = Trie() + for root in dictionary: + trie.insert(root) + + words = sentence.split() + for i in range(len(words)): + words[i] = trie.searchRoot(words[i]) + + return ' '.join(words) +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(N + L)$, where `N` is the total number of characters in the dictionary and `L` is the length of the sentence. +- **Space Complexity**: $O(N)$, where `N` is the total number of characters in the dictionary. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0600-0699/682-baseball-game.md b/solutions/lc-solutions/0600-0699/682-baseball-game.md new file mode 100644 index 0000000..eb26e85 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/682-baseball-game.md @@ -0,0 +1,199 @@ +--- +id: baseball-game +title: Baseball Game +sidebar_label: 682-Baseball Game +tags: + - Array + - Stack + - Simulation + +description: "This is a solution to baseball game in leetcode " +--- + +## Problem Description + +You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record. + +You are given a list of strings operations, where operations[i] is the ith operation you must apply to the record and is one of the following: + +1. An integer `x`. +Record a new score of x. +2. `+`. +Record a new score that is the sum of the previous two scores. +3. `D`. +Record a new score that is the double of the previous score. +4. `C`. +Invalidate the previous score, removing it from the record. +Return the sum of all the scores on the record after applying all the operations. + +The test cases are generated such that the answer and all intermediate calculations fit in a 32-bit integer and that all operations are valid. + + + + +### Examples + +**Example 1:** + +``` +Input: ops = ["5","2","C","D","+"] +Output: 30 +Explanation: +"5" - Add 5 to the record, record is now [5]. +"2" - Add 2 to the record, record is now [5, 2]. +"C" - Invalidate and remove the previous score, record is now [5]. +"D" - Add 2 * 5 = 10 to the record, record is now [5, 10]. +"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15]. +The total sum is 5 + 10 + 15 = 30. + +``` +**Example 2:** +``` +Input: ops = ["5","-2","4","C","D","9","+","+"] +Output: 27 +Explanation: +"5" - Add 5 to the record, record is now [5]. +"-2" - Add -2 to the record, record is now [5, -2]. +"4" - Add 4 to the record, record is now [5, -2, 4]. +"C" - Invalidate and remove the previous score, record is now [5, -2]. +"D" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4]. +"9" - Add 9 to the record, record is now [5, -2, -4, 9]. +"+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5]. +"+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14]. +The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27. + + ``` + +**Example 3:** +``` +Input: ops = ["1","C"] +Output: 0 +Explanation: +"1" - Add 1 to the record, record is now [1]. +"C" - Invalidate and remove the previous score, record is now []. +Since the record is empty, the total sum is 0. + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(n)$ + +*** Space Complexity:** $O(n)$ + +### Constraints + +- `1 <= operations.length <= 1000` +- `operations[i]` is "C", "D", "+", or a string representing an integer in the range `[-3 * 104, 3 * 104]`. +- For operation "+", there will always be at least two previous scores on the record. + +### Solution +## Approach +If you are using arrays, the approach is similar but requires managing an array instead of a stack. Here's a concise explanation: + +To calculate points using an array, iterate through the operations list while maintaining an array to store the scores. For each operation: +- If it's a number, convert it to an integer and append it to the array. +- If it's "+", sum the last two scores in the array and append the result. +- If it's "C", remove the last score from the array. +- If it's "D", double the last score in the array and append the result. + +Finally, sum all the values in the array to get the total score. This method ensures that each operation is processed correctly, and the final score is computed based on the updated array. + +## Code in Different Languages + + + + + +```cpp + +class Solution { +public: + int calPoints(std::vector& operations) { + std::vector points; + int sum = 0; + + for (const std::string& op : operations) { + if (op == "+") { + int last = points[points.size() - 1]; + int secondLast = points[points.size() - 2]; + points.push_back(last + secondLast); + } else if (op == "C") { + points.pop_back(); + } else if (op == "D") { + points.push_back(2 * points.back()); + } else { + points.push_back(std::stoi(op)); + } + } + + for (int point : points) { + sum += point; + } + + return sum; + } +}; + + +``` + + + + +```java +class Solution { + public int calPoints(String[] operations) { + ArrayList a=new ArrayList<>(); + int sum=0; + for(String ch:operations){ + if(ch.equals("+")){ + sum=a.get(a.size()-1)+a.get(a.size()-2); + a.add(sum); + } + else if(ch.equals("C")){ + a.remove(a.size()-1); + } + else if(ch.equals("D")){ + a.add(2*a.get(a.size()-1)); + }else{ + a.add(Integer.parseInt(ch)); + } + } + int sum2=0; + for(int i:a){ + sum2+=i; + }return sum2; + } +} + +``` + + + + +```python +class Solution: + def calPoints(self, operations: list[str]) -> int: + points = [] + + for op in operations: + if op == "+": + points.append(points[-1] + points[-2]) + elif op == "C": + points.pop() + elif op == "D": + points.append(2 * points[-1]) + else: + points.append(int(op)) + + return sum(points) + +``` + + + +## References + +- **LeetCode Problem**: [Baseball Game](https://leetcode.com/problems/baseball-game/description/) + +- **Solution Link**: [Baseball Game](https://leetcode.com/problems/baseball-game/post-solution/?submissionId=1270600925) diff --git a/solutions/lc-solutions/0600-0699/_category_.json b/solutions/lc-solutions/0600-0699/_category_.json new file mode 100644 index 0000000..748a0c6 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "0600-0699", + "position": 8, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (0600 - 0699)" + } +} diff --git a/solutions/lc-solutions/0600-0699/screenshot.png b/solutions/lc-solutions/0600-0699/screenshot.png new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/solutions/lc-solutions/0600-0699/screenshot.png @@ -0,0 +1 @@ + diff --git a/solutions/lc-solutions/0700-0799/0700-search-in-a-binary-search-tree.md b/solutions/lc-solutions/0700-0799/0700-search-in-a-binary-search-tree.md new file mode 100644 index 0000000..9d9d871 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0700-search-in-a-binary-search-tree.md @@ -0,0 +1,260 @@ +--- +id: search-in-a-binary-search-tree +title: Search in a Binary Search Tree +sidebar_label: 700. Search in a Binary Search Tree + +tags: +- Binary Tree +- BST +- Search + +description: "This is a solution to the Search in a Binary Search Tree problem on LeetCode." +--- + +## Problem Description +You are given the `root` of a binary search tree (BST) and an integer `val`. +Find the node in the BST that the node's value equals `val` and return the subtree rooted with that node. If such a node does not exist, return `null`. +### Examples + +**Example 1:** + +![Example1](image.png) +``` +Input: root = [4,2,7,1,3], val = 2 +Output: [2,1,3] +``` + +**Example 2:** + +![Example2](image-1.png) +``` +Input: root = [4,2,7,1,3], val = 5 +Output: [] + +``` + + +### Constraints +- The number of nodes in the tree is in the range `[1, 5000]`. +- `1 <= Node.val <= 10^7` +- `root` is a binary search tree. +- `1 <= val <= 10^7` + + + +## Solution for Search in a Binary Search Tree +### Approach +#### Brute Force +- **Traverse the Tree**: Perform a level-order or in-order traversal of the tree. +- **Compare Values**: At each node, compare its value with the given value `val`. +- **Return Subtree**: If the node’s value equals `val`, return the subtree rooted at that node. +- **Return Null**: If the traversal completes without finding the node, return `null`. + +**Implementation:** +```python +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +def findNode(root, val): + if root is None: + return None + + queue = [root] + while queue: + node = queue.pop(0) + if node.val == val: + return node + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + + return None + +# Example usage +root = TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(7)) +val = 2 +subtree = findNode(root, val) +print(subtree.val if subtree else "Node not found") +``` + +**Complexity:** +- Time Complexity: `O(n)` - We might have to visit every node in the tree. +- Space Complexity: `O(n)` - In the worst case, the queue can hold all nodes in the tree (for level-order traversal). + +**Corner Cases:** +- Empty tree: Should return `null`. +- Value not found: Should return `null`. + +#### Optimized Approach +- **Leverage BST Properties**: Use the properties of the BST (left subtree contains nodes with values less than the root, and the right subtree contains nodes with values greater than the root). +- **Binary Search**: Traverse the tree using a binary search-like approach: + - If `val` is less than the current node’s value, move to the left child. + - If `val` is greater than the current node’s value, move to the right child. + - If `val` equals the current node’s value, return the current node. +- **Return Null**: If a leaf node is reached without finding the value, return `null`. + +**Implementation:** + +```python +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +def findNode(root, val): + current = root + while current: + if current.val == val: + return current + elif val < current.val: + current = current.left + else: + current = current.right + return None + +# Example usage +root = TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(7)) +val = 2 +subtree = findNode(root, val) +print(subtree.val if subtree else "Node not found") +``` + +**Complexity:** +- Time Complexity: `O(h)`- `h` is the height of the tree. In the worst case, it can be O(n) for a skewed tree, but in a balanced tree, it is O(log n). +- Space Complexity: `O(1)`- We are not using any extra space except for the input and output. + +**Corner Cases:** +- Empty tree: Should return `null`. +- Value not found: Should return `null`. +- Single node tree: If the single node does not match `val`, should return `null`. + + + ## Code in Different Languages + + + + + + + ```javascript + var searchBST = function(root, val) { + if (root === null) { + return null; + } else { + if (root.val === val) { + return root; + } else if (root.val < val) { + return searchBST(root.right, val); + } else { + return searchBST(root.left, val); + } + } + }; + ``` + + + + + + + ```typescript + function searchBST(root: TreeNode | null, val: number): TreeNode | null { + if (root === null) { + return null; + } else { + if (root.val === val) { + return root; + } else if (root.val < val) { + return searchBST(root.right, val); + } else { + return searchBST(root.left, val); + } + } + } + ``` + + + + + + + ```python + + class Solution(object): + def searchBST(self, root, val): + if root is None: + return None + else: + if root.val == val: + return root + elif root.val < val: + return self.searchBST(root.right, val) + else: + return self.searchBST(root.left, val) + ``` + + + + + + + ```java + import java.util.Arrays; + + class Solution { + public TreeNode searchBST(TreeNode root, int val) { + if (root == null) { + return null; + } else { + if (root.val == val) { + return root; + } else if (root.val < val) { + return searchBST(root.right, val); + } else { + return searchBST(root.left, val); + } + } + } + } + ``` + + + + + + + ```cpp + class Solution { + public: + TreeNode* searchBST(TreeNode* root, int val) { + if(root==NULL){ + return NULL; + } + else{ + if(root->val == val){ + return root; + }else if(root->val < val){ + return searchBST(root->right,val); + }else{ + return searchBST(root->left,val); + } + return NULL; + } + return NULL; + } + }; + ``` + + + + +## References + +- **LeetCode Problem**: [Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/description) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/search-in-a-binary-search-tree/solutions) \ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/0701-Insert-Into-A-Binary-Search-Tree.md b/solutions/lc-solutions/0700-0799/0701-Insert-Into-A-Binary-Search-Tree.md new file mode 100644 index 0000000..7c72d91 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0701-Insert-Into-A-Binary-Search-Tree.md @@ -0,0 +1,110 @@ +--- +id: insert-into-a-binary-search-tree +title: Insert into a Binary Search Tree +sidebar_label: 701. Insert into a Binary Search Tree + +tags: +- Binary Tree +- BST +- Tree + +description: "This is a solution to the Insert into a Binary Search Tree problem on LeetCode." +--- + +## Problem Description +You are given the `root` node of a binary search tree (BST) and a `value` to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. + +Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them. + +### Examples + +**Example 1:** + +![Example1](https://github.com/user-attachments/assets/c7df9581-e34c-4cde-a8a3-5b19d37d60c7) + +``` +Input: root = [4,2,7,1,3], val = 5 +Output: [4,2,7,1,3,5] +``` +![Sol1](https://github.com/user-attachments/assets/a454cca0-8878-44e3-8c22-1be2c870cce1) + + +**Example 2:** + +``` +Input: root = [40,20,60,10,30,50,70], val = 25 +Output: [40,20,60,10,30,50,70,null,null,25] + +``` + +**Example 3:** + +``` +Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 +Output: [4,2,7,1,3,5] + +``` + + +### Constraints + +Certainly! Here is the Markdown for the given constraints without changing any word or statement: + +### Constraints + +- The number of nodes in the tree will be in the range `[0, 10^4]`. +- `-10^8 <= Node.val <= 10^8` +- All the values `Node.val` are unique. +- `-10^8 <= val <= 10^8` +- It's guaranteed that val does not exist in the original BST. + + + + +## Solutions + +```cpp + TreeNode* insertIntoBST(TreeNode* a, int x) { + + if(!a) return new TreeNode(x); + + if(xval) + a->left=insertIntoBST(a->left,x); + else + a->right=insertIntoBST(a->right,x); + + return a; + } +``` + +```java +class Solution { + public TreeNode insertIntoBST(TreeNode root, int val) { + if(root == null){ + return new TreeNode(val); + } + + if(val < root.val){ + root.left = insertIntoBST(root.left, val); + } + else{ + root.right = insertIntoBST(root.right, val); + } + + return root; + } +} +``` + +```python +class Solution: + def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: + if root is None: return TreeNode(val) + if root.val > val: root.left = self.insertIntoBST(root.left, val) + else: root.right = self.insertIntoBST(root.right, val) + return root +``` +### Complexity Analysis + +- **Time Complexity:** $O(H)$, where $H$ is the height of the BST. In the worst case, the height $H$ can be $N$ for skewed trees. +- **Space Complexity:** $O(H)$, due to the recursive calls on the call stack. In the worst case, $H$ can be $N$ for skewed trees. diff --git a/solutions/lc-solutions/0700-0799/0703-kth-largest-element-in-a-stream.md b/solutions/lc-solutions/0700-0799/0703-kth-largest-element-in-a-stream.md new file mode 100644 index 0000000..7cb2c52 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0703-kth-largest-element-in-a-stream.md @@ -0,0 +1,193 @@ +--- +id: kth-largest-element-in-a-Stream +title: Kth Largest Element in a Stream +sidebar_label: 0703 - Kth Largest Element in a Stream +tags: + - Heap + - Design + - Data Stream +description: "This is a solution to the Kth Largest Element in a Stream problem on LeetCode." +--- + +## Problem Description + +Design a class to find the $k^{th}$ largest element in a stream. Note that it is the kth largest element in the sorted order, not the $k^{th}$ distinct element. + +Implement `KthLargest` class: + +- `KthLargest(int k, int[] nums)` Initializes the object with the integer `k` and the stream of integers `nums`. +- `int add(int val)` Appends the integer `val` to the stream and returns the element representing the $k^{th}$ largest element in the stream. + +### Examples + +**Example 1:** + +``` +Input +["KthLargest", "add", "add", "add", "add", "add"] +[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]] +Output +[null, 4, 5, 5, 8, 8] + +Explanation +KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]); +kthLargest.add(3); // return 4 +kthLargest.add(5); // return 5 +kthLargest.add(10); // return 5 +kthLargest.add(9); // return 8 +kthLargest.add(4); // return 8 +``` + +### Constraints + +- $1 \leq k \leq 10^4$ +- $0 \leq nums.length \leq 10^4$ +- $-10^4 \leq nums[i] \leq 10^4$ +- $-10^4 \leq val \leq 10^4$ +- At most $10^4$ calls will be made to `add`. +- It is guaranteed that there will be at least `k` elements in the array when you search for the $k^{th}$ element. + +## Solution for Kth Largest Element in a Stream + +### Approach 1: Heap + +A heap is a data structure that is capable of giving you the smallest (or largest) element (by some criteria) in constant time, while also being able to add elements and remove the smallest (or largest) element in only logarithmic time. Imagine if you wanted to replicate this functionality naively with an array. To make sure we can find the smallest element in constant time, let's just keep our array sorted, so that the last element is always the largest (or smallest, depending on if we're sorting in ascending or descending order). Removing the largest/smallest element will take $O(1)$ time as we are popping from the end of the array. However, to add a new element, we first need to find where the element should be inserted and then insert it by shifting the array, which requires $O(n)$ time. Now, there are potential improvements to this approach, like using a deque for removals and insertions and binary searching to find insertion points, but the point is that a heap makes it so we don't need to worry about any of that. + +In summary, a heap: + +- Stores elements, and can find the smallest (min-heap) or largest (max-heap) element stored in $O(1)$. +- Can add elements and remove the smallest (min-heap) or largest (max-heap) element in $O(log⁑(n))$. +- Can perform insertions and removals while always maintaining the first property. + +The capability to remove and insert elements in $log⁑(n)$ time makes heaps extremely useful. For example, many problems that can be naively solved in $O(n^2)$ time, can be solved in $O(nβ‹…log⁑(n))$ time by using a heap. To put this in perspective, for an input size of $n = 10^5$ elements, $nβ‹…log⁑(n)$ is over **6000** times smaller than $n^2$. + +So now that we know what a heap does, how does it help solve this problem? Let's say we have some stream of numbers, `nums = [6, 2, 3, 1, 7]`, and `k = 3`. Because the input is small, we can clearly see the kth smallest element is `3`. Although, earlier we said that a heap can only find an element in $O(1)$ time if it's a minimum or maximum (depending on choice of implementation). Well, a heap is also capable of removing the smallest element quickly, so what if we just keep removing the smallest element from `nums` until `nums.length == k`? In this case, we would have `nums = [3, 6, 7]`, and a heap can now give us our answer in $O(1)$ time. + +That's the key to solving this problem - use a min-heap (min means that the heap will remove/find the smallest element, a max heap is the same thing but for the largest element) and keep the heap at size `k`. That way, the smallest element in the heap (the one we can access in $O(1)$) will always be the kth largest element. This way, when adding a number to the heap with `add()`, we can do it very quickly in $log⁑(n)$ time. If our heap exceeds size `k`, then we can also remove it very quickly. In the end, the smallest element in the heap will be the answer. + +#### Algorithm + +1. In the constructor, create a min heap using the elements from `nums`. Then, pop from the heap until `heap.length == k`. +2. For every call to `add()`: + - First, push `val` into `heap`. + - Next, check if `heap.length > k`. If so, pop from the heap. + - Finally, return the smallest value from the heap, which we can get in $O(1)$ time. + +## Code in Different Languages + + + + + +```cpp +#include + +class KthLargest { +private: + int k; + std::priority_queue, std::greater> heap; + +public: + KthLargest(int k, std::vector nums) { + this->k = k; + for (int num : nums) { + heap.push(num); + if (heap.size() > k) { + heap.pop(); + } + } + } + + int add(int val) { + heap.push(val); + if (heap.size() > k) { + heap.pop(); + } + return heap.top(); + } +}; + +``` + + + + +```java +class KthLargest { + private static int k; + private PriorityQueue heap; + + public KthLargest(int k, int[] nums) { + this.k = k; + heap = new PriorityQueue<>(); + + for (int num: nums) { + heap.offer(num); + } + + while (heap.size() > k) { + heap.poll(); + } + } + + public int add(int val) { + heap.offer(val); + if (heap.size() > k) { + heap.poll(); + } + + return heap.peek(); + } +} +``` + + + + + +```python +class KthLargest: + def __init__(self, k: int, nums: List[int]): + self.k = k + self.heap = nums + heapq.heapify(self.heap) + + while len(self.heap) > k: + heapq.heappop(self.heap) + + def add(self, val: int) -> int: + heapq.heappush(self.heap, val) + if len(self.heap) > self.k: + heapq.heappop(self.heap) + return self.heap[0] +``` + + + +## Complexity Analysis + +### Time Complexity: $O(Nβ‹…log(N)+Mβ‹…log(k))$ + +> **Reason**: The time complexity is split into two parts. First, the constructor needs to turn `nums` into a heap of size `k`. In Python, `heapq.heapify()` can turn nums into a heap in $O(N)$ time. Then, we need to remove from the heap until there are only k elements in it, which means removing `N - k` elements. Since k can be, say 1, in terms of big O this is N operations, with each operation costing $log⁑(N)$. Therefore, the constructor costs $O(N + Nβ‹…log⁑(N))=O(Nβ‹…log⁑(N))$. +> +> Next, every call to `add()` involves adding an element to `heap` and potentially removing an element from `heap`. Since our heap is of size `k`, every call to `add()` at worst costs $O(2 \times log⁑(k))=O(log⁑(k))$. That means `M` calls to add() costs $O(Mβ‹…log⁑(k))$. + +### Space Complexity: $O(N)$ + +> **Reason**: The only extra space we use is the `heap`. While during `add()` calls we limit the size of the heap to `k`, in the constructor we start by converting `nums` into a heap, which means the heap will initially be of size `N`. + +## References + +- **LeetCode Problem**: [Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/description/) + +- **Solution Link**: [Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/0704-binary-search.md b/solutions/lc-solutions/0700-0799/0704-binary-search.md new file mode 100644 index 0000000..414f409 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0704-binary-search.md @@ -0,0 +1,339 @@ +--- +id: binary-search +title: Binary Search +sidebar_label: 0704 - Binary Search +tags: + - Binary Search + - Array + - Binary Tree +description: "This is a solution to the Binary Search problem on LeetCode." +--- + +## Problem Description + +Given an array of integers `nums` which is sorted in ascending order, and an integer target, write a function to search `target` in `nums`. If target exists, then return its index. Otherwise, return `-1`. + +You must write an algorithm with $O(log n)$ runtime complexity. + +### Examples + +**Example 1:** + +``` +Input: nums = [-1,0,3,5,9,12], target = 9 +Output: 4 +Explanation: 9 exists in nums and its index is 4 +``` + +**Example 2:** + +``` +Input: nums = [-1,0,3,5,9,12], target = 2 +Output: -1 +Explanation: 2 does not exist in nums so return -1 +``` + +### Constraints + +- $1 \leq nums.length \leq 10^4$ +- $-10^4 < nums[i], target < 10^4$ +- All the integers in nums are **unique**. +- `nums` is sorted in ascending order. + +## Solution for Binary Search + +### Approach 1: Find the Exact Value +#### Intuition + +We start from the most basic and elementary template. + +First, we define the search space using two boundary indexes, `left` and `right`, all possible indexes are within the inclusive range `[left, right]`. We shall continue searching over the search space as long as it is not empty. A general way is to use a while loop with the condition `left <= right`, so we can break out of this loop if we empty the range or trigger other conditions which we will discuss later. + +![image](https://assets.leetcode.com/static_assets/media/original_images/704_re/b1.png) + +The next step is to find the 'pivot point', the middle index that divides the search space into two halves. We need to compare the value at the middle index `nums[mid]` with target, the purpose of this step is to cut one half that is guaranteed not to contain `target`. + +- If `nums[mid] = target`, it means we find `target`, and the job is done! We can break the loop by returning mid. +- If `nums[mid] < target`, combined with the array is sorted, we know that all values in the left half are smaller than target, so we can safely cut this half by letting `left = mid + 1`. +- If `nums[mid] > target`, it means all values in the right half are larger than `target` and can be cut safely! + +![image](https://assets.leetcode.com/static_assets/media/original_images/704_re/b2.png) + +Does this loop ever stop? Yes, take the following picture as an example, suppose we are searching over an array of size 1, in this case, `left`, `right`, and `mid` all stand for the only index in the array. In any of the three conditions, we trigger one of the break statements and stop the loop. + +![image](https://assets.leetcode.com/static_assets/media/original_images/704_re/b3.png) + +#### Algorithm +1. Initialize the boundaries of the search space as `left = 0` and `right = nums.size - 1`. +2. If there are elements in the range `[left, right]`, we find the middle index `mid = (left + right) / 2` and compare the middle value `nums[mid]` with `target`: + - If `nums[mid] = target`, return `mid`. + - If `nums[mid] < target`, let `left = mid + 1` and repeat step 2. + - If `nums[mid] > target`, let `right = mid - 1` and repeat step 2. +3. We finish the loop without finding `target`, return `-1`. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + int search(vector& nums, int target) { + // Set the left and right boundaries + int left = 0, right = int(nums.size()) - 1; + + // Under this condition + while (left <= right) { + // Get the middle index and the middle value. + int mid = left + (right - left) / 2; + + // Case 1, return the middle index. + if (nums[mid] == target) { + return mid; + } + // Case 2, discard the smaller half. + else if (nums[mid] < target) { + left = mid + 1; + } + // Case 3, discard the larger half. + else { + right = mid - 1; + } + } + + // If we finish the search without finding target, return -1. + return -1; + } +}; + +``` + + + + +```java +class Solution { + public int search(int[] nums, int target) { + // Set the left and right boundaries + int left = 0, right = nums.length - 1; + + // Under this condition + while (left <= right) { + // Get the middle index and the middle value. + int mid = left + (right - left) / 2; + + // Case 1, return the middle index. + if (nums[mid] == target) { + return mid; + } + // Case 2, discard the smaller half. + else if (nums[mid] < target) { + left = mid + 1; + } + // Case 3, discard the larger half. + else { + right = mid - 1; + } + } + + // If we finish the search without finding target, return -1. + return -1; + } +} +``` + + + + + +```python +class Solution: + def search(self, nums: List[int], target: int) -> int: + # Set the left and right boundaries + left = 0 + right = len(nums) - 1 + + # Under this condition + while left <= right: + # Get the middle index and the middle value. + mid = (left + right) // 2 + + # Case 1, return the middle index. + if nums[mid] == target: + return mid + # Case 2, discard the smaller half. + elif nums[mid] < target: + left = mid + 1 + # Case 3, discard the larger half. + else: + right = mid - 1 + + # If we finish the search without finding target, return -1. + return -1 +``` + + + +## Complexity Analysis + +### Time Complexity: $O(log n)$ + +> **Reason**: `nums` is divided into half each time. In the worst-case scenario, we need to cut `nums` until the range has no element, and it takes logarithmic time to reach this break condition. + +### Space Complexity: $O(1)$ + +> **Reason**: During the loop, we only need to record three indexes, left, right, and mid, they take constant space. + +### Approach 2: Find Upper bound +#### Intuition + +Here we introduce an alternative way to implement binary search: instead of looking for target in the array `nums`, we look for the insert position where we can put `target` in without disrupting the order. + +![image](https://assets.leetcode.com/static_assets/media/original_images/704_re/u1.png) + +Generally, we have two inserting ways, insert into the rightmost possible position which we called finding the **upper bound**, and insert into the leftmost possible position which we called finding the **lower bound**. We will implement them in the following approaches. + +Take the picture below as an example. Assume that we want to insert `9` into array `A`. If we look for the **upper bound**, we have to insert `9` to the right of all existing `9`s in the array. Similarly, if we look for the **lower bound**, we have to insert `9` to the left of all existing 9s. (Although we don't have duplicate elements in this problem, having duplicate elements is more common in problems so we would better know this concept in advance!) + +![image](https://assets.leetcode.com/static_assets/media/original_images/704_re/u3.png) + +Now we start the binary search. Similar to the previous approach, we still use `left` and `right` as two boundary indexes. The question is, what is the next step after we find the middle index `mid`? + +![image](https://assets.leetcode.com/static_assets/media/original_images/704_re/upper2.png) + +- If `nums[mid] < target`, the insert position is on `mid`'s right, so we let `left = mid + 1` to discard the left half and `mid`. + +- If `nums[mid] = target`, the insert position is on `mid`'s right, so we let `left = mid + 1` to discard the left half and `mid`. + +![image](https://assets.leetcode.com/static_assets/media/original_images/704_re/u4.png) + +- If `nums[mid] > target`, `mid` can also be the insert position. So we let `right = mid` to discard the right half while keeping `mid`. + +Therefore, we merged the two conditions `nums[mid] = target` and `nums[mid] < target` and there are only two conditions in the `if-else` statement! + +![image](https://assets.leetcode.com/static_assets/media/original_images/704_re/upper5.png) + +Once the loop stops, `left` stands for the insert position and `left - 1` is the largest element that is no larger than `target`. We just need to check if `nums[left - 1]` equals target. Note this boundary condition where `left = 0`, which means all elements in `nums` are larger than `target`, so there is no target in `nums`. + +#### Algorithm + +1. Initialize the boundaries of the search space as `left = 0` and `right = nums.size` (Note that the maximum insert position can be `nums.size`) +2. If there are elements in the range `[left, right]`, we find the middle index `mid = (left + right) / 2` and compare the middle value `nums[mid]` with target: + - If `nums[mid] <= target`, let `left = mid + 1` and repeat step 2. + - If `nums[mid] > target`, let `right = mid` and repeat step 2. +3. We finish the loop and `left` stands for the insert position: + - If `left > 0` and `nums[left - 1] = target`, return `left - 1`. + - Otherwise, return `-1`. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + int search(vector& nums, int target) { + // Set the left and right boundaries + int left = 0, right = int(nums.size()); + + while (left < right) { + int mid = left + (right - left) / 2; + if (nums[mid] <= target) { + left = mid + 1; + } else { + right = mid; + } + } + + if (left > 0 and nums[left - 1] == target) { + return left - 1; + } else { + return -1; + } + } +}; +``` + + + + +```java +class Solution { + public int search(int[] nums, int target) { + // Set the left and right boundaries + int left = 0, right = nums.length; + + while (left < right) { + int mid = left + (right - left) / 2; + if (nums[mid] <= target) { + left = mid + 1; + } else { + right = mid; + } + } + + if (left > 0 && nums[left - 1] == target) { + return left - 1; + } else { + return -1; + } + } +} +``` + + + + + +```python +class Solution: + def search(self, nums: List[int], target: int) -> int: + # Set the left and right boundaries + left = 0 + right = len(nums) + + while left < right: + mid = (left + right) // 2 + if nums[mid] <= target: + left = mid + 1 + else: + right = mid + + if left > 0 and nums[left - 1] == target: + return left - 1 + else: + return -1 +``` + + + +## Complexity Analysis + +### Time Complexity: $O(logn)$ + +> **Reason**: `nums` is divided into half each time. In the worst-case scenario, we need to cut `nums` until the range has no element, it takes logarithmic time to reach this break condition. + + +### Space Complexity: $O(1)$ + +> **Reason**: During the loop, we only need to record three indexes, `left`, `right`, and `mid`, they take constant space. + +## References + +- **LeetCode Problem**: [Binary Search](https://leetcode.com/problems/binary-search/description/) + +- **Solution Link**: [Binary Search](https://leetcode.com/problems/binary-search/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/0706-design-hashmap.md b/solutions/lc-solutions/0700-0799/0706-design-hashmap.md new file mode 100644 index 0000000..613c211 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0706-design-hashmap.md @@ -0,0 +1,241 @@ +--- +id: design-hashmap +title: Design HashMap +sidebar_label: 706. Design HashMap +tags: + - Hash Table + - Design + - HashMap +description: "This is a solution to the Design HashMap problem on LeetCode." +--- + +## Problem Description +Design a HashMap without using any built-in hash table libraries. + +Implement the `MyHashMap` class: + +- `MyHashMap()` initializes the object with an empty map. +- `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`. +- `int get(int key)` returns the `value` to which the specified `key` is mapped, or `-1` if this map contains no mapping for the `key`. +- `void remove(int key)` removes the `key` and its corresponding `value` if the map contains the mapping for the `key`. + +### Examples + +**Example 1:** + +``` +Input: +["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"] +[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]] +Output: +[null, null, null, 1, -1, null, 1, null, -1] + +Explanation: +MyHashMap myHashMap = new MyHashMap(); +myHashMap.put(1, 1); // The map is now [[1,1]] +myHashMap.put(2, 2); // The map is now [[1,1], [2,2]] +myHashMap.get(1); // return 1, The map is now [[1,1], [2,2]] +myHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]] +myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value) +myHashMap.get(2); // return 1, The map is now [[1,1], [2,1]] +myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]] +myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]] +``` + +### Constraints + +- `0 <= key, value <= 10^6` +- At most `10^4` calls will be made to `put`, `get`, and `remove`. + +## Solution for Design HashMap + +### Approach + +#### Array-Based Implementation +- **Array Initialization**: Use an array to store the values with a size large enough to accommodate the given constraints. +- **Direct Indexing**: Use the key as an index to store the value in the array. +- **Handling Removal**: Use a special value (like `-1`) to denote the removal of a key. + +**Implementation:** + +```python +class MyHashMap: + + def __init__(self): + self.size = 1000001 + self.hashmap = [-1] * self.size + + def put(self, key: int, value: int) -> None: + self.hashmap[key] = value + + def get(self, key: int) -> int: + return self.hashmap[key] + + def remove(self, key: int) -> None: + self.hashmap[key] = -1 + +# Example usage +myHashMap = MyHashMap() +myHashMap.put(1, 1) +myHashMap.put(2, 2) +print(myHashMap.get(1)) # returns 1 +print(myHashMap.get(3)) # returns -1 (not found) +myHashMap.put(2, 1) # update the existing value +print(myHashMap.get(2)) # returns 1 +myHashMap.remove(2) # remove the mapping for 2 +print(myHashMap.get(2)) # returns -1 (not found) +``` + +**Complexity:** +- Time Complexity: `O(1)` for `put`, `get`, and `remove` operations. +- Space Complexity: `O(n)`, where `n` is the range of keys (1,000,001). + +**Corner Cases:** +- Handling updates: Ensure that the value is updated if the key already exists. +- Handling removals: Ensure that the key is marked as removed. + +## Code in Different Languages + + + + + + +```javascript +var MyHashMap = function() { + this.size = 1000001; + this.map = new Array(this.size).fill(-1); +}; + +MyHashMap.prototype.put = function(key, value) { + this.map[key] = value; +}; + +MyHashMap.prototype.get = function(key) { + return this.map[key]; +}; + +MyHashMap.prototype.remove = function(key) { + this.map[key] = -1; +}; +``` + + + + + + +```typescript +class MyHashMap { + private size: number; + private map: number[]; + + constructor() { + this.size = 1000001; + this.map = new Array(this.size).fill(-1); + } + + put(key: number, value: number): void { + this.map[key] = value; + } + + get(key: number): number { + return this.map[key]; + } + + remove(key: number): void { + this.map[key] = -1; + } +} +``` + + + + + + +```python +class MyHashMap: + + def __init__(self): + self.size = 1000001 + self.hashmap = [-1] * self.size + + def put(self, key: int, value: int) -> None: + self.hashmap[key] = value + + def get(self, key: int) -> int: + return self.hashmap[key] + + def remove(self, key: int) -> None: + self.hashmap[key] = -1 +``` + + + + + + +```java +class MyHashMap { + private int size; + private int[] map; + + public MyHashMap() { + size = 1000001; + map = new int[size]; + Arrays.fill(map, -1); + } + + public void put(int key, int value) { + map[key] = value; + } + + public int get(int key) { + return map[key]; + } + + public void remove(int key) { + map[key] = -1; + } +} +``` + + + + + + +```cpp +class MyHashMap { +public: + int size; + vector map; + + MyHashMap() { + size = 1000001; + map.resize(size, -1); + } + + void put(int key, int value) { + map[key] = value; + } + + int get(int key) { + return map[key]; + } + + void remove(int key) { + map[key] = -1; + } +}; +``` + + + + +## References + +- **LeetCode Problem**: [Design HashMap](https://leetcode.com/problems/design-hashmap/description) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/design-hashmap/solutions) diff --git a/solutions/lc-solutions/0700-0799/0709-to-lower-case.md b/solutions/lc-solutions/0700-0799/0709-to-lower-case.md new file mode 100644 index 0000000..b698590 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0709-to-lower-case.md @@ -0,0 +1,113 @@ +--- +id: to-lower-case +title: To Lower Case +sidebar_label: 0709-To Lower Case +tags: + - String + +description: "This is a solution to To Lower Case in leetcode" +--- + +## Problem Description + +Given a string s, return the string after replacing every uppercase letter with the same lowercase letter. + +### Examples + +**Example 1:** + +``` +Input: s = "Hello" +Output: "hello" + +``` + +**Example 2:** + +``` +Input: s = "here" +Output: "here" +``` + +## Complexity Analysis + +*** Time Complexity:** $O(n)$ + +*** Space Complexity:** $O(1)$ + +### Constraints + +- `1 <= s.length <= 100` + +**Solution for Kth Largest Element in a Stream** + +- `s` consists of printable ASCII characters. + + +### Solution +## Approach +The simple approach is use built in function to convert given string to lower case. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + string toLowerCase(string s) { + string result; + for (char c : s) { + if (c >= 'A' && c <= 'Z') { + result += (char)(c + 32); + } else { + result += c; + } + } + return result; + } +}; + +``` + + + + +```java +class Solution { +public: + string toLowerCase(string s) { + for (int i = 0; i < s.size(); ++i) { + if (s[i] >= 'A' && s[i] <= 'Z') { + s[i] = s[i] + ('a' - 'A'); + } + } + return s; + } +}; +``` + + + + +## Complexity Analysis + +### Time Complexity: +> The toLowerCase method iterates through each character `c` in the input string `s`. +The iteration involves a single pass through the string, so the time complexity is `O(n)`, where `n` is the length of the input string `s`. +Within each iteration, checking if `c` is an uppercase letter ('A' to 'Z') and converting it involves constant time operations (ord(c), chr()), which do not change the overall time complexity. +Therefore, the time complexity of the toLowerCase method is O(n). + +### Space Complexity: $O(N)$ + +The method uses a list result to store the characters of the resulting lowercase string. +Initially, an empty list result is created, which takes constant space. +The space used by result grows as it accumulates characters from the input string s. +Since the list result holds at most n characters (where n is the length of s), the space complexity is O(n). +Therefore, the space complexity of the toLowerCase method is O(n). + +## References + +- **LeetCode Problem**: [Kth Largest Element in a Stream](https://leetcode.com/problems/to-lower-case/description/) \ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/0713-subarray-product-less-than-k.md b/solutions/lc-solutions/0700-0799/0713-subarray-product-less-than-k.md new file mode 100644 index 0000000..7b305d7 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0713-subarray-product-less-than-k.md @@ -0,0 +1,281 @@ +--- +id: subarray-product-less-than-k +title: Subarray Product Less Than K +sidebar_label: 713. Subarray Product Less Than K + +tags: +- Array +- Sliding Window + +description: "This is a solution to the Subarray Product Less Than K problem on LeetCode." +--- + +## Problem Description +Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k. +### Examples + +**Example 1:** +``` +Input: nums = [10,5,2,6], k = 100 +Output: 8 +Explanation: The 8 subarrays that have product less than 100 are: +[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6] +Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k. +``` + +**Example 2:** +``` +Input: nums = [1,2,3], k = 0 +Output: 0 + +``` + + +### Constraints +- `1 <= nums.length <= 3 * 10^4` +- `1 <= nums[i] <= 1000` +- `0 <= k <= 10^6` + +## Solution for Path With Minimum Effort Problem +### Approach +#### Brute Force +- Generate All the Subarray and Check whether the which subarray has product less than K. + +#### Optimized Approach - Sliding Window +##### Initialize Pointers and Variables: + +- Use two pointers, i and j, to represent the start and end of the current subarray, respectively. +- Initialize prod to 1 to keep track of the product of elements in the current window. +- Initialize cnt to 0 to count the number of valid subarrays. +##### Expand the Window: + +- Start with both pointers at the beginning of the array. Expand the window by moving the j pointer to the right, multiplying the product prod by the new element nums[j]. +##### Check the Product: + +- If the product prod is less than k, all subarrays ending at j and starting from any position between i and j are valid. Therefore, add j - i + 1 to cnt. +Shrink the Window: + +- If the product prod is greater than or equal to k, move the i pointer to the right until the product is less than k. Each time you move i, divide prod by nums[i]. +##### Repeat: + +- Continue expanding the window with j and adjusting i as needed until j reaches the end of the array. +##### Return the Result: + +- The total count cnt is the number of subarrays with a product less than k. + + + + + + #### Implementation + ```jsx live + function Solution(arr) { + var numSubarrayProductLessThanK = function(nums, k) { + let i = 0; + let j = 0; + let cnt = 0; + let prod = 1; + while (j < nums.length) { + prod *= nums[j]; + if (prod < k) { + cnt += j - i + 1; + } else { + while (prod >= k && i <= j) { + prod /= nums[i]; + i++; + } + if (prod < k) { + cnt += j - i + 1; + } + } + j++; + } + return cnt; + }; + + const input =[10,5,2,6] + const k = 100 + const output = numSubarrayProductLessThanK(input , k) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(N) $ + - Space Complexity: $ O(1)$ + + ## Code in Different Languages + + + + ```javascript + var numSubarrayProductLessThanK = function(nums, k) { + let i = 0; + let j = 0; + let cnt = 0; + let prod = 1; + while (j < nums.length) { + prod *= nums[j]; + if (prod < k) { + cnt += j - i + 1; + } else { + while (prod >= k && i <= j) { + prod /= nums[i]; + i++; + } + if (prod < k) { + cnt += j - i + 1; + } + } + j++; + } + return cnt; +}; + + ``` + + + + + ```typescript + function numSubarrayProductLessThanK(nums: number[], k: number): number { + let i = 0; + let j = 0; + let cnt = 0; + let prod = 1; + while (j < nums.length) { + prod *= nums[j]; + if (prod < k) { + cnt += j - i + 1; + } else { + while (prod >= k && i <= j) { + prod /= nums[i]; + i++; + } + if (prod < k) { + cnt += j - i + 1; + } + } + j++; + } + return cnt; +} + + ``` + + + + ```python + class Solution: + def numSubarrayProductLessThanK(self, nums, k): + i = 0 + j = 0 + cnt = 0 + prod = 1 + while j < len(nums): + prod *= nums[j] + if prod < k: + cnt += j - i + 1 + else: + while prod >= k and i <= j: + prod /= nums[i] + i += 1 + if prod < k: + cnt += j - i + 1 + j += 1 + return cnt + + ``` + + + + + ```java + class Solution { + public int numSubarrayProductLessThanK(int[] nums, int k) { + int i = 0; + int j = 0; + long cnt = 0; + long prod = 1; + while (j < nums.length) { + prod *= nums[j]; + if (prod < k) { + cnt += j - i + 1; + } else { + while (prod >= k && i <= j) { + prod /= nums[i]; + i++; + } + if (prod < k) { + cnt += j - i + 1; + } + } + j++; + } + return (int) cnt; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + int numSubarrayProductLessThanK(vector& nums, int k) { + int i=0; + int j=0; + long long cnt = 0; + long long prod = 1; + while(j=k) + { + while(prod>=k && i<=j) + { + prod/=nums[i]; + i++; + } + + if(prod + + +
+
+ +## References + +- **LeetCode Problem**: [Subarray Product Less Than K](https://leetcode.com/problems/subarray-product-less-than-k/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/subarray-product-less-than-k/solutions) + diff --git a/solutions/lc-solutions/0700-0799/0717-1-bit-and-2-bit-characters.md b/solutions/lc-solutions/0700-0799/0717-1-bit-and-2-bit-characters.md new file mode 100644 index 0000000..d6248e8 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0717-1-bit-and-2-bit-characters.md @@ -0,0 +1,197 @@ +--- +id: 1-bit-and-2-bit-characters +title: 1-bit and 2-bit Characters +sidebar_label: 0717 - 1-bit and 2-bit Characters +tags: + - Array + - Greedy + - Bit Manipulation +description: "This is a solution to the 1-bit and 2-bit Characters problem on LeetCode." +--- + +## Problem Description + +We have two special characters: + +- The first character can be represented by one bit `0`. +- The second character can be represented by two bits (`10` or `11`). + +Given a binary array `bits` that ends with `0`, return `true` if the last character must be a one-bit character. + +### Examples + +**Example 1:** + +``` +Input: bits = [1,0,0] +Output: true +Explanation: The only way to decode it is two-bit character and one-bit character. +So the last character is one-bit character. +``` + +**Example 2:** + +``` +Input: bits = [1,1,1,0] +Output: false +Explanation: The only way to decode it is two-bit character and two-bit character. +So the last character is not one-bit character. +``` + +### Constraints + +- `1 <= bits.length <= 1000` +- `bits[i]` is either `0` or `1`. + +## Solution for 1-bit and 2-bit Characters + +### Approach 1: Increment Pointer + +#### Intuition and Algorithm + +When reading from the i-th position, if `bits[i] == 0`, the next character must have 1 bit; else if `bits[i] == 1`, the next character must have 2 bits. We increment our read-pointer `i` to the start of the next character appropriately. At the end, if our pointer is at `bits.length - 1`, then the last character must have a size of 1 bit. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + bool isOneBitCharacter(vector& bits) { + int i = 0; + while (i < bits.size() - 1) { + i += bits[i] + 1; + } + return i == bits.size() - 1; + } +}; + +``` + + + + +```java +class Solution { + public boolean isOneBitCharacter(int[] bits) { + int i = 0; + while (i < bits.length - 1) { + i += bits[i] + 1; + } + return i == bits.length - 1; + } +} + +``` + + + + + +```python +class Solution(object): + def isOneBitCharacter(self, bits): + i = 0 + while i < len(bits) - 1: + i += bits[i] + 1 + return i == len(bits) - 1 + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: `N` is the length of `bits`. + +### Space Complexity: $O(1)$ + +> **Reason**: the space used by `i`. + +### Approach 2: Greedy + +#### Intuition and Algorithm + +The second-last `0` must be the end of a character (or, the beginning of the array if it doesn't exist). Looking from that position forward, the array `bits` takes the form `[1, 1, ..., 1, 0]` where there are zero or more `1`'s present in total. It is easy to show that the answer is `true` if and only if there is an even number of ones present. + +In our algorithm, we will find the second last zero by performing a linear scan from the right. We present two slightly different approaches below. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + bool isOneBitCharacter(vector& bits) { + int i = bits.size() - 2; + while (i >= 0 && bits[i] > 0) { + i--; + } + return (bits.size() - i) % 2 == 0; + } +}; + +``` + + + + +```java +class Solution { + public boolean isOneBitCharacter(int[] bits) { + int i = bits.length - 2; + while (i >= 0 && bits[i] > 0) { + i--; + } + return (bits.length - i) % 2 == 0; + } +} +``` + + + + + +```python +class Solution(object): + def isOneBitCharacter(self, bits): + parity = bits.pop() + while bits and bits.pop(): parity ^= 1 + return parity == 0 +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: `N` is the length of `bits`. + +### Space Complexity: $O(1)$ + +> **Reason**: the space used by `parity` (or `i`). + +## References + +- **LeetCode Problem**: [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters/description/) + +- **Solution Link**: [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/0725-split-linked-list-in-parts.md b/solutions/lc-solutions/0700-0799/0725-split-linked-list-in-parts.md new file mode 100644 index 0000000..48894b4 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0725-split-linked-list-in-parts.md @@ -0,0 +1,300 @@ +--- +id: split-linked-list-in-parts +title: Split Linked List in Parts +sidebar_label: 0725 - Split Linked List in Parts +tags: + - Linked List + - Math + - Array +description: "This is a solution to the Split Linked List in Parts problem on LeetCode." +--- + +## Problem Description + +Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts. + +The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null. + +The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later. + +Return an array of the `k` parts. + +### Examples +**Example 1:** + +![image](https://assets.leetcode.com/uploads/2021/06/13/split1-lc.jpg) +``` +Input: head = [1,2,3], k = 5 +Output: [[1],[2],[3],[],[]] +Explanation: +The first element output[0] has output[0].val = 1, output[0].next = null. +The last element output[4] is null, but its string representation as a ListNode is []. +``` + +**Example 2:** + +![image](https://assets.leetcode.com/uploads/2021/06/13/split2-lc.jpg) +``` +Input: head = [1,2,3,4,5,6,7,8,9,10], k = 3 +Output: [[1,2,3,4],[5,6,7],[8,9,10]] +Explanation: +The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts. +``` + +### Constraints + +- The number of nodes in the list is in the range `[0, 1000]`. +- `0 <= Node.val <= 1000` +- `1 <= k <= 50` + +## Solution for Split Linked List in Parts + +### Approach 1: Create New Lists + +#### Intuition and Algorithm + +If there are N nodes in the linked list root, then there are N/k items in each part, plus the first N%k parts have an extra item. We can count N with a simple loop. + +Now for each part, we have calculated how many nodes that part will have: `width + (i < remainder ? 1 : 0)`. We create a new list and write the part to that list. + +Our solution showcases constructs of the form `a = b = c`. Note that this syntax behaves differently for different languages. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector splitListToParts(ListNode* root, int k) { + ListNode* cur = root; + int N = 0; + while (cur != nullptr) { + cur = cur->next; + N++; + } + + int width = N / k, rem = N % k; + + vector ans(k, nullptr); + cur = root; + for (int i = 0; i < k; ++i) { + ListNode* head = new ListNode(0), *write = head; + for (int j = 0; j < width + (i < rem ? 1 : 0); ++j) { + write = write->next = new ListNode(cur ? cur->val : 0); + if (cur) { + cur = cur->next; + } + } + ans[i] = head->next; + } + return ans; + } +}; +``` + + + + +```java +class Solution { + public ListNode[] splitListToParts(ListNode root, int k) { + ListNode cur = root; + int N = 0; + while (cur != null) { + cur = cur.next; + N++; + } + + int width = N / k, rem = N % k; + + ListNode[] ans = new ListNode[k]; + cur = root; + for (int i = 0; i < k; ++i) { + ListNode head = new ListNode(0), write = head; + for (int j = 0; j < width + (i < rem ? 1 : 0); ++j) { + write = write.next = new ListNode(cur.val); + if (cur != null) { + cur = cur.next; + } + } + ans[i] = head.next; + } + return ans; + } +} +``` + + + + + +```python +class Solution(object): + def splitListToParts(self, root, k): + cur = root + for N in xrange(1001): + if not cur: break + cur = cur.next + width, remainder = divmod(N, k) + + ans = [] + cur = root + for i in xrange(k): + head = write = ListNode(None) + for j in xrange(width + (i < remainder)): + write.next = write = ListNode(cur.val) + if cur: cur = cur.next + ans.append(head.next) + return ans +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N+k)$ + +> **Reason**: where N is the number of nodes in the given list. If k is large, it could still require creating many new empty lists. + +### Space Complexity: $O(max(N,k))$ + +> **Reason**: the space used in writing the answer. + +### Approach 2: Split Input List +#### Intuition and Algorithm + +As in Approach 1, we know the size of each part. Instead of creating new lists, we will split the input list directly and return a list of pointers to nodes in the original list as appropriate. + +Our solution proceeds similarly. For a part of size `L = width + (i < remainder ? 1 : 0)`, instead of stepping `L` times, we will step `L - 1` times, and our final time will also sever the link between the last node from the previous part and the first node from the next part. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector splitListToParts(ListNode* root, int k) { + ListNode* cur = root; + int N = 0; + while (cur != nullptr) { + cur = cur->next; + N++; + } + + int width = N / k, rem = N % k; + + vector ans(k, nullptr); + cur = root; + for (int i = 0; i < k; ++i) { + ListNode* head = cur; + for (int j = 0; j < width + (i < rem ? 1 : 0) - 1; ++j) { + if (cur != nullptr) { + cur = cur->next; + } + } + if (cur != nullptr) { + ListNode* prev = cur; + cur = cur->next; + prev->next = nullptr; + } + ans[i] = head; + } + return ans; + } +}; +``` + + + + +```java +class Solution { + public ListNode[] splitListToParts(ListNode root, int k) { + ListNode cur = root; + int N = 0; + while (cur != null) { + cur = cur.next; + N++; + } + + int width = N / k, rem = N % k; + + ListNode[] ans = new ListNode[k]; + cur = root; + for (int i = 0; i < k; ++i) { + ListNode head = cur; + for (int j = 0; j < width + (i < rem ? 1 : 0) - 1; ++j) { + if (cur != null) { + cur = cur.next; + } + } + if (cur != null) { + ListNode prev = cur; + cur = cur.next; + prev.next = null; + } + ans[i] = head; + } + return ans; + } +} +``` + + + + + +```python +class Solution(object): + def splitListToParts(self, root, k): + cur = root + for N in xrange(1001): + if not cur: break + cur = cur.next + width, remainder = divmod(N, k) + + ans = [] + cur = root + for i in xrange(k): + head = cur + for j in xrange(width + (i < remainder) - 1): + if cur: cur = cur.next + if cur: + cur.next, cur = None, cur.next + ans.append(head) + return ans +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N+k)$ + +> **Reason**: where N is the number of nodes in the given list. If k is large, it could still require creating many new empty lists. + +### Space Complexity: $O(k)$ + +> **Reason**: the additional space used in writing the answer. + +## References + +- **LeetCode Problem**: [Split Linked List](https://leetcode.com/problems/split-linked-list-in-parts/description/) + +- **Solution Link**: [Split Linked List](https://leetcode.com/problems/split-linked-list-in-parts/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/0726-number-of-atoms.md b/solutions/lc-solutions/0700-0799/0726-number-of-atoms.md new file mode 100644 index 0000000..333bebb --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0726-number-of-atoms.md @@ -0,0 +1,463 @@ +--- +id: number-of-atoms +title: Number of Atoms +sidebar_label: 0726 - Number of Atoms +tags: + - Stack + - Recursion + - String +description: "This is a solution to the Number of Atoms problem on LeetCode." +--- + +## Problem Description + +Given a string `formula` representing a chemical formula, return the count of each atom. + +The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name. + +One or more digits representing that element's count may follow if the count is greater than `1`. If the count is `1`, no digits will follow. + +- For example, `"H2O"` and `"H2O2"` are possible, but `"H1O2"` is impossible. + +Two formulas are concatenated together to produce another formula. + +- For example, `"H2O2He3Mg4"` is also a formula. + +A formula placed in parentheses, and a count (optionally added) is also a formula. + +- For example, `"(H2O2)"` and `"(H2O2)3"` are formulas. + +Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on. + +The test cases are generated so that all the values in the output fit in a **32-bit** integer. + +### Examples + +**Example 1:** + +``` +Input: formula = "H2O" +Output: "H2O" +Explanation: The count of elements are {'H': 2, 'O': 1}. +``` +**Example 2:** + +``` +Input: formula = "Mg(OH)2" +Output: "H2MgO2" +Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}. +``` + +### Constraints + +- `1 <= formula.length <= 1000` +- `formula` consists of English letters, digits, `'('`, and `')'`. +- `formula` is always valid. + +## Solution for Number of Atoms + +### Approach 1: Recursion +#### Intuition and Algorithm + +Write a function `parse` that parses the formula from index `i`, returning a map `count` from names to multiplicities (the number of times that name is recorded). + +We will put `i` in the global state: our `parse` function increments `i` throughout any future calls to `parse`. + +- When we see a `'('`, we will parse whatever is inside the brackets (up to the closing ending bracket) and add it to our count. + +- Otherwise, we should see an uppercase character: we will parse the rest of the letters to get the name, and add that (plus the multiplicity if there is one.) + +- At the end, if there is a final multiplicity (representing the multiplicity of a bracketed sequence), we'll multiply our answer by this. + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +private: + int i; + +public: + std::string countOfAtoms(std::string formula) { + std::string ans; + i = 0; + std::map count = parse(formula); + for (const auto& [name, multiplicity] : count) { + ans += name; + if (multiplicity > 1) { + ans += std::to_string(multiplicity); + } + } + return ans; + } + + std::map parse(std::string formula) { + int N = formula.length(); + std::map count; + while (i < N && formula[i] != ')') { + if (formula[i] == '(') { + i++; + for (const auto& [name, multiplicity] : parse(formula)) { + count[name] += multiplicity; + } + } else { + int iStart = i++; + while (i < N && islower(formula[i])) { + i++; + } + std::string name = formula.substr(iStart, i - iStart); + iStart = i; + while (i < N && isdigit(formula[i])) { + i++; + } + int multiplicity = iStart < i ? std::stoi(formula.substr(iStart, i - iStart)) : 1; + count[name] += multiplicity; + } + } + int iStart = ++i; + while (i < N && isdigit(formula[i])) { + i++; + } + if (iStart < i) { + int multiplicity = std::stoi(formula.substr(iStart, i - iStart)); + for (auto& [name, count_] : count) { + count_ *= multiplicity; + } + } + return count; + } +}; + + +``` + + + + +```java +class Solution { + int i; + public String countOfAtoms(String formula) { + StringBuilder ans = new StringBuilder(); + i = 0; + Map count = parse(formula); + for (String name: count.keySet()) { + ans.append(name); + int multiplicity = count.get(name); + if (multiplicity > 1) { + ans.append("" + multiplicity); + } + } + return new String(ans); + } + + public Map parse(String formula) { + int N = formula.length(); + Map count = new TreeMap(); + while (i < N && formula.charAt(i) != ')') { + if (formula.charAt(i) == '(') { + i++; + for (Map.Entry entry: parse(formula).entrySet()) { + count.put(entry.getKey(), count.getOrDefault(entry.getKey(), 0) + entry.getValue()); + } + } else { + int iStart = i++; + while (i < N && Character.isLowerCase(formula.charAt(i))) { + i++; + } + String name = formula.substring(iStart, i); + iStart = i; + while (i < N && Character.isDigit(formula.charAt(i))) { + i++; + } + int multiplicity = iStart < i ? Integer.parseInt(formula.substring(iStart, i)) : 1; + count.put(name, count.getOrDefault(name, 0) + multiplicity); + } + } + int iStart = ++i; + while (i < N && Character.isDigit(formula.charAt(i))) { + i++; + } + if (iStart < i) { + int multiplicity = Integer.parseInt(formula.substring(iStart, i)); + for (String key: count.keySet()) { + count.put(key, count.get(key) * multiplicity); + } + } + return count; + } +} +``` + + + + + +```python +class Solution { + int i; + public String countOfAtoms(String formula) { + StringBuilder ans = new StringBuilder(); + i = 0; + Map count = parse(formula); + for (String name: count.keySet()) { + ans.append(name); + int multiplicity = count.get(name); + if (multiplicity > 1) { + ans.append("" + multiplicity); + } + } + return new String(ans); + } + + public Map parse(String formula) { + int N = formula.length(); + Map count = new TreeMap(); + while (i < N && formula.charAt(i) != ')') { + if (formula.charAt(i) == '(') { + i++; + for (Map.Entry entry: parse(formula).entrySet()) { + count.put(entry.getKey(), count.getOrDefault(entry.getKey(), 0) + entry.getValue()); + } + } else { + int iStart = i++; + while (i < N && Character.isLowerCase(formula.charAt(i))) { + i++; + } + String name = formula.substring(iStart, i); + iStart = i; + while (i < N && Character.isDigit(formula.charAt(i))) { + i++; + } + int multiplicity = iStart < i ? Integer.parseInt(formula.substring(iStart, i)) : 1; + count.put(name, count.getOrDefault(name, 0) + multiplicity); + } + } + int iStart = ++i; + while (i < N && Character.isDigit(formula.charAt(i))) { + i++; + } + if (iStart < i) { + int multiplicity = Integer.parseInt(formula.substring(iStart, i)); + for (String key: count.keySet()) { + count.put(key, count.get(key) * multiplicity); + } + } + return count; + } +} +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N^2)$ + +> **Reason**: where N is the length of the formula. It is $O(N)$ to parse through the formula, but each of $O(N)$ multiplicities after a bracket may increment the count of each name in the formula (inside those brackets), leading to an $O(N^2)$ complexity. + +### Space Complexity: $O(N)$ + +> **Reason**: We aren't recording more intermediate information than what is contained in the formula. + +### Approach 2: Stack +#### Intuition and Algorithm + +Instead of recursion, we can simulate the call stack by using a stack of `counts` directly. + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include +#include +#include + +class Solution { +public: + std::string countOfAtoms(std::string formula) { + int N = formula.length(); + std::stack> stack; + std::map top_map; + stack.push(top_map); + + for (int i = 0; i < N;) { + if (formula[i] == '(') { + std::map new_map; + stack.push(new_map); + i++; + } else if (formula[i] == ')') { + std::map top = stack.top(); + stack.pop(); + int iStart = ++i, multiplicity = 1; + while (i < N && std::isdigit(formula[i])) { + i++; + } + if (i > iStart) { + multiplicity = std::stoi(formula.substr(iStart, i - iStart)); + } + for (auto it = top.begin(); it != top.end(); ++it) { + int v = it->second; + stack.top()[it->first] = stack.top().count(it->first) ? stack.top()[it->first] + v * multiplicity : v * multiplicity; + } + } else { + int iStart = i++; + while (i < N && std::islower(formula[i])) { + i++; + } + std::string name = formula.substr(iStart, i - iStart); + iStart = i; + while (i < N && std::isdigit(formula[i])) { + i++; + } + int multiplicity = i > iStart ? std::stoi(formula.substr(iStart, i - iStart)) : 1; + stack.top()[name] = stack.top().count(name) ? stack.top()[name] + multiplicity : multiplicity; + } + } + + std::string ans; + for (auto it = stack.top().begin(); it != stack.top().end(); ++it) { + ans += it->first; + int multiplicity = it->second; + if (multiplicity > 1) { + ans += std::to_string(multiplicity); + } + } + return ans; + } +}; + + +``` + + + + +```java +class Solution { + public String countOfAtoms(String formula) { + int N = formula.length(); + Stack> stack = new Stack(); + stack.push(new TreeMap()); + + for (int i = 0; i < N;) { + if (formula.charAt(i) == '(') { + stack.push(new TreeMap()); + i++; + } else if (formula.charAt(i) == ')') { + Map top = stack.pop(); + int iStart = ++i, multiplicity = 1; + while (i < N && Character.isDigit(formula.charAt(i))) { + i++; + } + if (i > iStart) { + multiplicity = Integer.parseInt(formula.substring(iStart, i)); + } + for (String c: top.keySet()) { + int v = top.get(c); + stack.peek().put(c, stack.peek().getOrDefault(c, 0) + v * multiplicity); + } + } else { + int iStart = i++; + while (i < N && Character.isLowerCase(formula.charAt(i))) { + i++; + } + String name = formula.substring(iStart, i); + iStart = i; + while (i < N && Character.isDigit(formula.charAt(i))) { + i++; + } + int multiplicity = i > iStart ? Integer.parseInt(formula.substring(iStart, i)) : 1; + stack.peek().put(name, stack.peek().getOrDefault(name, 0) + multiplicity); + } + } + + StringBuilder ans = new StringBuilder(); + for (String name: stack.peek().keySet()) { + ans.append(name); + int multiplicity = stack.peek().get(name); + if (multiplicity > 1) { + ans.append("" + multiplicity); + } + } + return new String(ans); + } +} +``` + + + + + +```python +class Solution(object): + def countOfAtoms(self, formula): + N = len(formula) + stack = [collections.Counter()] + i = 0 + while i < N: + if formula[i] == '(': + stack.append(collections.Counter()) + i += 1 + elif formula[i] == ')': + top = stack.pop() + i += 1 + i_start = i + while i < N and formula[i].isdigit(): i += 1 + multiplicity = int(formula[i_start: i] or 1) + for name, v in top.items(): + stack[-1][name] += v * multiplicity + else: + i_start = i + i += 1 + while i < N and formula[i].islower(): i += 1 + name = formula[i_start: i] + i_start = i + while i < N and formula[i].isdigit(): i += 1 + multiplicity = int(formula[i_start: i] or 1) + stack[-1][name] += multiplicity + + return "".join(name + (str(stack[-1][name]) if stack[-1][name] > 1 else '') + for name in sorted(stack[-1])) +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N^2)$ + +> **Reason**: where N is the length of the formula. It is $O(N)$ to parse through the formula, but each of $O(N)$ multiplicities after a bracket may increment the count of each name in the formula (inside those brackets), leading to an $O(N^2)$ complexity. + +### Space Complexity: $O(N)$ + +> **Reason**: We aren't recording more intermediate information than what is contained in the formula. + + +## References + +- **LeetCode Problem**: [Number of Atoms](https://leetcode.com/problems/number-of-atoms/description/) + +- **Solution Link**: [Number of Atoms](https://leetcode.com/problems/number-of-atoms/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/0728-self-dividing-numbers.md b/solutions/lc-solutions/0700-0799/0728-self-dividing-numbers.md new file mode 100644 index 0000000..7a13e77 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0728-self-dividing-numbers.md @@ -0,0 +1,186 @@ +--- +id: self-dividing-numbers +title: Self Dividing Numbers +sidebar_label: 0728 - Self Dividing Numbers +tags: + - Recursion + - Array + - Math +description: "This is a solution to the Self Dividing Numbers problem on LeetCode." +--- + +## Problem Description + +A **self-dividing number** is a number that is divisible by every digit it contains. + +For example, `128` is a **self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`. +A **self-dividing number** is not allowed to contain the digit zero. + +Given two integers `left` and `right`, return a list of all the **self-dividing numbers** in the range `[left, right]`. + +### Examples + +**Example 1:** + +``` +Input: left = 1, right = 22 +Output: [1,2,3,4,5,6,7,8,9,11,12,15,22] +``` + +**Example 2:** + +``` +Input: left = 47, right = 85 +Output: [48,55,66,77] +``` + +### Constraints + +- $1 \leq left \leq right \leq 10^4$ + +## Solution for Self Dividing Numbers + +### Approach: Brute Force +#### Intuition and Algorithm + +For each number in the given range, we will directly test if that number is self-dividing. + +By definition, we want to test each whether each digit is non-zero and divide the number. For example, with `128`, we want to test `d != 0 && 128 % d == 0` for `d = 1, 2, 8`. To do that, we need to iterate over each digit of the number. + +A straightforward approach to that problem would be to convert the number into a character array (string in Python), and then convert it back to an integer to perform the modulo operation when checking `n % d == 0`. + +We could also continually divide the number by 10 and peek at the last digit. That is shown as a variation in a comment. + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +public: + std::vector selfDividingNumbers(int left, int right) { + std::vector ans; + for (int n = left; n <= right; ++n) { + if (selfDividing(n)) { + ans.push_back(n); + } + } + return ans; + } + + bool selfDividing(int n) { + int temp = n; + while (temp > 0) { + int digit = temp % 10; + if (digit == 0 || n % digit != 0) { + return false; + } + temp /= 10; + } + return true; + } +}; + +``` + + + + +```java +class Solution { + public List selfDividingNumbers(int left, int right) { + List ans = new ArrayList(); + for (int n = left; n <= right; ++n) { + if (selfDividing(n)) { + ans.add(n); + } + } + return ans; + } + public boolean selfDividing(int n) { + for (char c: String.valueOf(n).toCharArray()) { + if (c == '0' || (n % (c - '0') > 0)) { + return false; + } + } + return true; + } + /* + Alternate implementation of selfDividing: + public boolean selfDividing(int n) { + int x = n; + while (x > 0) { + int d = x % 10; + x /= 10; + if (d == 0 || (n % d) > 0) { + return false; + } + } + return true; + */ +} +``` + + + + + +```python +class Solution(object): + def selfDividingNumbers(self, left, right): + def self_dividing(n): + for d in str(n): + if d == '0' or n % int(d) > 0: + return False + return True + """ + An alternate implementation of self_dividing: + def self_dividing(n): + x = n + while x > 0: + x, d = divmod(x, 10) + if d == 0 or n % d > 0: + return False + return True + """ + ans = [] + for n in range(left, right + 1): + if self_dividing(n): + ans.append(n) + return ans #Equals filter(self_dividing, range(left, right+1)) + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(D)$ + +> **Reason**: where D is the number of integers in the range [L,R], and assuming $log⁑(R)$ is bounded (In general, the complexity would be $O(Dlog⁑R)$). + +### Space Complexity: $O(D)$ + +> **Reason**: the length of the answer + +## References + +- **LeetCode Problem**: [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/description/) + +- **Solution Link**: [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/0729-my-calendar-i.md b/solutions/lc-solutions/0700-0799/0729-my-calendar-i.md new file mode 100644 index 0000000..362034a --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0729-my-calendar-i.md @@ -0,0 +1,258 @@ +--- +id: my-calendar-i +title: My Calendar I +sidebar_label: 0729 - My Calendar I +tags: + - Binary Search + - Tree + - Binary Tree +description: "This is a solution to the My Calendar I problem on LeetCode." +--- + +## Problem Description + +You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **double booking**. + +A **double booking** happens when two events have some non-empty intersection (i.e., some moment is common to both events.). + +The event can be represented as a pair of integers `start` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`. + +Implement the `MyCalendar` class: + +- `MyCalendar()` Initializes the calendar object. +- `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **double booking**. Otherwise, return `false` and do not add the event to the calendar. + +### Examples + +**Example 1:** + +``` +Input +["MyCalendar", "book", "book", "book"] +[[], [10, 20], [15, 25], [20, 30]] +Output +[null, true, false, true] + +Explanation +MyCalendar myCalendar = new MyCalendar(); +myCalendar.book(10, 20); // return True +myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event. +myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20. +``` + +### Constraints + +- $0 \leq start < end \leq 10^9$ +- At most `1000` calls will be made to `book`. + +## Solution for My Calendar I +### Overview + +The primary challenge in this problem is to find a proper data structure and an efficient algorithm to maintain all valid events, including **querying** potentially conflicting existing events and **inserting** new valid events. + +In this solution article, we first start with a straightforward idea of brute force to warm up, then one step forward, we improve the naive approach to keep all existing events in sorted order and reduce the time complexity. + +### Approach 1: Brute Force +#### Intuition + +When booking a new event `[start, end)`, check if every current event conflicts with the new event. If none of them do, we can book the event. + +#### Algorithm + +We will maintain a list of interval events (not necessarily sorted). Evidently, two events `[s1, e1)` and `[s2, e2)` do not conflict if and only if one of them starts after the other one ends: either `e1 <= s2` OR `e2 <= s1`. By De Morgan's laws, this means the events conflict when `s1 < e2` AND `s2 < e1`. + +## Code in Different Languages + + + + + +```cpp +class MyCalendar { +private: + vector> calendar; + +public: + bool book(int start, int end) { + for (const auto [s, e] : calendar) { + if (start < e && s < end) { + return false; + } + } + calendar.emplace_back(start, end); + return true; + } +}; +``` + + + + +```java +public class MyCalendar { + List calendar; + + MyCalendar() { + calendar = new ArrayList(); + } + + public boolean book(int start, int end) { + for (int[] iv: calendar) { + if (iv[0] < end && start < iv[1]) { + return false; + } + } + calendar.add(new int[]{start, end}); + return true; + } +} +``` + + + + + +```python +class MyCalendar: + + def __init__(self): + self.calendar = [] + + def book(self, start, end): + for s, e in self.calendar: + if s < end and start < e: + return False + self.calendar.append((start, end)) + return True +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N^2)$ + +> **Reason**: For each new event, we process every previous event to decide whether the new event can be booked. This leads to $O(N^2)$ complexity. + +### Space Complexity: $O(N)$ + +> **Reason**: the size of the calendar + +### Approach 2: Sorted List + Binary Search +#### Intuition + +If we maintained our events in sorted order, we could check whether an event could be booked in $O(log⁑N)$ time (where N is the number of events already booked) by binary searching for where the event should be placed. We would also have to insert the event in our sorted structure. + +#### Algorithm + +1. Initialize with an empty sorted list data structure calendar. +2. For every new interval`[start, end)` in `book()` invokation, we check if there is a conflict on each side with neighboring intervals. + - Lookup the first index idx, which maps to an element `[s1,e1)` in calendar and `s > start`, and this step can be conducted by binary search (see this explore card) as we keep `calendar` in sorted order by starting points of intervals. (Notice that there may not be such an idx because `start >= all` kept intervals. In this case, we don't need to check the following step) + - Check if `end > s1`. If yes, `[start, end)` and `[s1,e1)` must be overlapped, `[start, end)` is illegal, and we should return false for the invokation now. + - Roll back to the index `idx-1`, which maps to an element `[s2,e2)` in calendar and s1 is the largest staring points that satisfy `s1 <= start`. (Similarly, notice that there may be no element at `idx-1` because `idx` is the 0-th index. In this case, we don't need to check the following step either) + - Check if `e2 > start`. If yes, `[s2,e2)` and `[start, end)` must be overlapped, `[start, end)` is illegal, and we should return false for the invokation now. + - If `[start, end)` passes all checkings above, we insert this valid interval at `idx` in `calendar`. + +## Code in Different Languages + + + + + +```cpp +class MyCalendar { +private: + set> calendar; + +public: + bool book(int start, int end) { + const pair event{start, end}; + const auto nextEvent = calendar.lower_bound(event); + if (nextEvent != calendar.end() && nextEvent->first < end) { + return false; + } + + if (nextEvent != calendar.begin()) { + const auto prevEvent = prev(nextEvent); + if (prevEvent->second > start) { + return false; + } + } + + calendar.insert(event); + return true; + } +}; +``` + + + + +```java +class MyCalendar { + TreeMap calendar; + + MyCalendar() { + calendar = new TreeMap(); + } + + public boolean book(int start, int end) { + Integer prev = calendar.floorKey(start), + next = calendar.ceilingKey(start); + if ((prev == null || calendar.get(prev) <= start) && + (next == null || end <= next)) { + calendar.put(start, end); + return true; + } + return false; + } +} +``` + + + + + +```python +from sortedcontainers import SortedList + +class MyCalendar: + def __init__(self): + self.calendar = SortedList() + + def book(self, start: int, end: int) -> bool: + idx = self.calendar.bisect_right((start, end)) + if (idx > 0 and self.calendar[idx-1][1] > start) or (idx < len(self.calendar) and self.calendar[idx][0] < end): + return False + self.calendar.add((start, end)) + return True +``` + + + +## Complexity Analysis + +### Time Complexity: $O(NlogN)$ + +> **Reason**: For each new event, we search that the event is legal in $O(log⁑N)$ time, then insert it in $O(log⁑N)$ time. + + +### Space Complexity: $O(N)$ + +> **Reason**: The size of the data structures used. + +## References + +- **LeetCode Problem**: [My Calendar I](https://leetcode.com/problems/my-calendar-i/description/) + +- **Solution Link**: [My Calendar I](https://leetcode.com/problems/my-calendar-i/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/0733-flood-fill.md b/solutions/lc-solutions/0700-0799/0733-flood-fill.md new file mode 100644 index 0000000..1d0c18f --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0733-flood-fill.md @@ -0,0 +1,189 @@ +--- +id: flood-fill +title: Flood Fill +sidebar_label: 0733 - Flood Fill +tags: + - Depth-First Search + - Recursion + - Breadth-First Search +description: "This is a solution to the Flood Fill problem on LeetCode." +--- + +## Problem Description + +An image is represented by an `m x n` integer grid image where `image[i][j]` represents the pixel value of the image. + +You are also given three integers `sr`, `sc`, and `color`. You should perform a **flood fill** on the image starting from the pixel `image[sr][sc]`. + +To perform a **flood fill**, consider the starting pixel, plus any pixels connected **4-directionally** to the starting pixel of the same color as the starting pixel, plus any pixels connected **4-directionally** to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with `color`. + +Return the modified image after performing the flood fill. + +### Examples + +**Example 1:** + +![image](https://assets.leetcode.com/uploads/2021/06/01/flood1-grid.jpg) +``` +Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2 +Output: [[2,2,2],[2,2,0],[2,0,1]] +Explanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color. +Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel. +``` + +**Example 2:** + +``` +Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0 +Output: [[0,0,0],[0,0,0]] +Explanation: The starting pixel is already colored 0, so no changes are made to the image. +``` + +### Constraints + +- $m == image.length$ +- $n == image[i].length$ +- $1 \leq m, n \leq 50$ +- $0 \leq sr < m$ +- $0 \leq sc < n$ +- $0 \leq image[i][j], color < 2^{16}$ + +## Solution for Flood Fill + +### Approach: Depth-First Search +#### Intuition + +We perform the algorithm explained in the problem description: paint the starting pixels, plus adjacent pixels of the same color, and so on. + +#### Algorithm + +Say `color` is the color of the starting pixel. Let's flood fill the starting pixel: we change the color of that pixel to the new color, then check the 4 neighboring pixels to make sure they are valid pixels of the same `color`, and of the valid ones, we flood fill those, and so on. + +We can use a function `dfs` to perform a flood fill on a target pixel. + + + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector> floodFill(vector>& image, int sr, int sc, int newColor) { + int color = image[sr][sc]; + if (color != newColor) { + dfs(image, sr, sc, color, newColor); + } + return image; + } + + void dfs(vector>& image, int r, int c, int color, int newColor) { + if (image[r][c] == color) { + image[r][c] = newColor; + if (r >= 1) { + dfs(image, r - 1, c, color, newColor); + } + if (c >= 1) { + dfs(image, r, c - 1, color, newColor); + } + if (r + 1 < image.size()) { + dfs(image, r + 1, c, color, newColor); + } + if (c + 1 < image[0].size()) { + dfs(image, r, c + 1, color, newColor); + } + } + } +}; + +``` + + + + +```java +class Solution { + public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { + int color = image[sr][sc]; + if (color != newColor) { + dfs(image, sr, sc, color, newColor); + } + return image; + } + public void dfs(int[][] image, int r, int c, int color, int newColor) { + if (image[r][c] == color) { + image[r][c] = newColor; + if (r >= 1) { + dfs(image, r - 1, c, color, newColor); + } + if (c >= 1) { + dfs(image, r, c - 1, color, newColor); + } + if (r + 1 < image.length) { + dfs(image, r + 1, c, color, newColor); + } + if (c + 1 < image[0].length) { + dfs(image, r, c + 1, color, newColor); + } + } + } +} +``` + + + + + +```python +class Solution(object): + def floodFill(self, image, sr, sc, newColor): + R, C = len(image), len(image[0]) + color = image[sr][sc] + if color == newColor: + return image + def dfs(r, c): + if image[r][c] == color: + image[r][c] = newColor + if r >= 1: + dfs(r-1, c) + if r + 1 < R: + dfs(r + 1, c) + if c >= 1: + dfs(r, c - 1) + if c + 1 < C: + dfs(r, c + 1) + + dfs(sr, sc) + return image +``` + + + +## Complexity Analysis + +### Time Complexity: $O(N)$ + +> **Reason**: where N is the number of pixels in the image. We might process every pixel. + +### Space Complexity: $O(N)$ + +> **Reason**: the size of the implicit call stack when calling `dfs`. + +## References + +- **LeetCode Problem**: [Flood Fill](https://leetcode.com/problems/flood-fill/description/) + +- **Solution Link**: [Flood Fill](https://leetcode.com/problems/flood-fill/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/0741-cherry-pickup.md b/solutions/lc-solutions/0700-0799/0741-cherry-pickup.md new file mode 100644 index 0000000..fdae84a --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0741-cherry-pickup.md @@ -0,0 +1,378 @@ +--- +id: cherry-pickup +title: Cherry Pickup +sidebar_label: 0745 - Cherry Pickup +tags: + - Dynamic Programming + - Memoization + - Recursion +description: "This is a solution to the Cherry Pickup problem on LeetCode." +--- + +## Problem Description + +You are given an `n x n` `grid` representing a field of cherries, each cell is one of three possible integers. + +- `0` means the cell is empty, so you can pass through, +- `1` means the cell contains a cherry that you can pick up and pass through, or +- `-1` means the cell contains a thorn that blocks your way. + +Return the maximum number of cherries you can collect by following the rules below: + +- Starting at the position `(0, 0)` and reaching `(n - 1, n - 1)` by moving right or down through valid path cells (cells with value `0` or `1`). +- After reaching `(n - 1, n - 1)`, returning to `(0, 0)` by moving left or up through valid path cells. +- When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell `0`. +- If there is no valid path between `(0, 0)` and `(n - 1, n - 1)`, then no cherries can be collected. + +### Examples + +**Example 1:** + +![image](https://assets.leetcode.com/uploads/2020/12/14/grid.jpg) +``` +Input +["WordFilter", "f"] +[[["apple"]], ["a", "e"]] +Output +[null, 0] +Explanation +WordFilter wordFilter = new WordFilter(["apple"]); +wordFilter.f("a", "e"); // return 0, because the word at index 0 has prefix = "a" and suffix = "e". +``` +**Example 2:** + +``` +Input: grid = [[1,1,-1],[1,-1,1],[-1,1,1]] +Output: 0 +``` + +### Constraints + +- `n == grid.length` +- `n == grid[i].length` +- `1 <= n <= 50` +- `grid[i][j] is -1, 0, or 1.` +- `grid[0][0] != -1` +- `grid[n - 1][n - 1] != -1` + +## Solution for Cherry Pickup + +## Approach 1: Dynamic Programming (Top Down) +### Intuition + +Instead of walking from end to beginning, let's reverse the second leg of the path, so we are only considering two paths from the beginning to the end. + +Notice after `t` steps, each position `(r, c)` we could be, is on the line `r + c = t`. So if we have two people at positions `(r1, c1)` and `(r2, c2)`, then `r2 = r1 + c1 - c2`. That means the variables `r1, c1, c2` uniquely determine 2 people who have walked the same `r1 + c1` number of steps. This sets us up for dynamic programming quite nicely. + +### Algorithm + +Let `dp[r1][c1][c2]` be the most number of cherries obtained by two people starting at `(r1, c1)` and `(r2, c2)` and walking towards `(N - 1, N - 1)` picking up cherries, where `r2 = r1 + c1 - c2`. + +If `grid[r1][c1]` and `grid[r2][c2]` are not thorns, then the value of `dp[r1][c1][c2]` is `(grid[r1][c1] + grid[r2][c2])`, plus the maximum of `dp[r1 + 1][c1][c2]`, `dp[r1][c1 + 1][c2]`, `dp[r1 + 1][c1][c2 + 1]`, `dp[r1][c1 + 1][c2 + 1]` as appropriate. We should also be careful to not double count in case `(r1, c1) == (r2, c2)`. + +Why did we say it was the maximum of `dp[r + 1][c1][c2]` etc.? It corresponds to the 4 possibilities for persons 1 and 2 moving down and right: + +- Person 1 down and person 2 down: `dp[r1 + 1][c1][c2]`; +- Person 1 right and person 2 down: `dp[r1][c1 + 1][c2]`; +- Person 1 down and person 2 right: `dp[r1 + 1][c1][c2 + 1]`; +- Person 1 right and person 2 right: `dp[r1][c1 + 1][c2 + 1]`; + +### Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +private: + std::vector>> memo; + std::vector> grid; + int N; + +public: + int cherryPickup(std::vector>& grid) { + this->grid = grid; + N = grid.size(); + memo = std::vector>>(N, std::vector>(N, std::vector(N, INT_MIN))); + return std::max(0, dp(0, 0, 0)); + } + + int dp(int r1, int c1, int c2) { + int r2 = r1 + c1 - c2; + if (N == r1 || N == r2 || N == c1 || N == c2 || + grid[r1][c1] == -1 || grid[r2][c2] == -1) { + return -999999; + } else if (r1 == N - 1 && c1 == N - 1) { + return grid[r1][c1]; + } else if (memo[r1][c1][c2] != INT_MIN) { + return memo[r1][c1][c2]; + } else { + int ans = grid[r1][c1]; + if (c1 != c2) { + ans += grid[r2][c2]; + } + ans += std::max(std::max(dp(r1, c1 + 1, c2 + 1), dp(r1 + 1, c1, c2 + 1)), + std::max(dp(r1, c1 + 1, c2), dp(r1 + 1, c1, c2))); + memo[r1][c1][c2] = ans; + return ans; + } + } +}; + + +``` + + + + +```java +class Solution { + int[][][] memo; + int[][] grid; + int N; + public int cherryPickup(int[][] grid) { + this.grid = grid; + N = grid.length; + memo = new int[N][N][N]; + for (int[][] layer: memo) { + for (int[] row: layer) { + Arrays.fill(row, Integer.MIN_VALUE); + } + } + return Math.max(0, dp(0, 0, 0)); + } + public int dp(int r1, int c1, int c2) { + int r2 = r1 + c1 - c2; + if (N == r1 || N == r2 || N == c1 || N == c2 || + grid[r1][c1] == -1 || grid[r2][c2] == -1) { + return -999999; + } else if (r1 == N - 1 && c1 == N - 1) { + return grid[r1][c1]; + } else if (memo[r1][c1][c2] != Integer.MIN_VALUE) { + return memo[r1][c1][c2]; + } else { + int ans = grid[r1][c1]; + if (c1 != c2) { + ans += grid[r2][c2]; + } + ans += Math.max(Math.max(dp(r1, c1 + 1, c2 + 1), dp(r1 + 1, c1, c2 + 1)), + Math.max(dp(r1, c1 + 1, c2), dp(r1 + 1, c1, c2))); + memo[r1][c1][c2] = ans; + return ans; + } + } +} +``` + + + + + +```python +class Solution(object): + def cherryPickup(self, grid): + N = len(grid) + memo = [[[None] * N for _1 in xrange(N)] for _2 in xrange(N)] + def dp(r1, c1, c2): + r2 = r1 + c1 - c2 + if (N == r1 or N == r2 or N == c1 or N == c2 or + grid[r1][c1] == -1 or grid[r2][c2] == -1): + return float('-inf') + elif r1 == c1 == N-1: + return grid[r1][c1] + elif memo[r1][c1][c2] is not None: + return memo[r1][c1][c2] + else: + ans = grid[r1][c1] + (c1 != c2) * grid[r2][c2] + ans += max(dp(r1, c1 + 1, c2 + 1), dp(r1 + 1, c1, c2 + 1), + dp(r1, c1 + 1, c2), dp(r1 + 1, c1, c2)) + + memo[r1][c1][c2] = ans + return ans + + return max(0, dp(0, 0, 0)) +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(N^3)$ + +> **Reason**: where N is the length of grid. Our dynamic programming has $N^3$ states, and each state is calculated once. + +#### Space Complexity: $O(N^3)$ + +> **Reason**: the size of `memo`. + +## Approach 2: Dynamic Programming (Bottom Up) +### Intuition + +Like in Approach 2, we have the idea of dynamic programming. + +Say `r1 + c1 = t` is the `t`-th layer. Since our recursion only references the next layer, we only need to keep two layers in memory at a time. + +### Algorithm + +At time `t`, let `dp[c1][c2]` be the most cherries that we can pick up for two people going from `(0, 0)` to `(r1, c1)` and `(0, 0)` to `(r2, c2)`, where `r1 = t-c1`, `r2 = t-c2`. Our dynamic program proceeds similarly to Approach 2. + +### Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +public: + int cherryPickup(std::vector>& grid) { + int N = grid.size(); + std::vector> dp(N, std::vector(N, INT_MIN)); + dp[0][0] = grid[0][0]; + + for (int t = 1; t <= 2 * N - 2; ++t) { + std::vector> dp2(N, std::vector(N, INT_MIN)); + + for (int i = std::max(0, t - (N - 1)); i <= std::min(N - 1, t); ++i) { + for (int j = std::max(0, t - (N - 1)); j <= std::min(N - 1, t); ++j) { + if (grid[i][t - i] == -1 || grid[j][t - j] == -1) { + continue; + } + int val = grid[i][t - i]; + if (i != j) { + val += grid[j][t - j]; + } + for (int pi = i - 1; pi <= i; ++pi) { + for (int pj = j - 1; pj <= j; ++pj) { + if (pi >= 0 && pj >= 0) { + dp2[i][j] = std::max(dp2[i][j], dp[pi][pj] + val); + } + } + } + } + } + dp = std::move(dp2); + } + return std::max(0, dp[N - 1][N - 1]); + } +}; + + +``` + + + + +```java +class Solution { + public int cherryPickup(int[][] grid) { + int N = grid.length; + int[][] dp = new int[N][N]; + for (int[] row: dp) { + Arrays.fill(row, Integer.MIN_VALUE); + } + dp[0][0] = grid[0][0]; + + for (int t = 1; t <= 2*N - 2; ++t) { + int[][] dp2 = new int[N][N]; + for (int[] row: dp2) { + Arrays.fill(row, Integer.MIN_VALUE); + } + + for (int i = Math.max(0, t - (N - 1)); i <= Math.min(N - 1, t); ++i) { + for (int j = Math.max(0, t - (N - 1)); j <= Math.min(N - 1, t); ++j) { + if (grid[i][t - i] == -1 || grid[j][t - j] == -1) { + continue; + } + int val = grid[i][t-i]; + if (i != j) { + val += grid[j][t - j]; + } + for (int pi = i - 1; pi <= i; ++pi) { + for (int pj = j - 1; pj <= j; ++pj) { + if (pi >= 0 && pj >= 0) { + dp2[i][j] = Math.max(dp2[i][j], dp[pi][pj] + val); + } + } + } + } + } + dp = dp2; + } + return Math.max(0, dp[N - 1][N - 1]); + } +} +``` + + + + + +```python +class Solution(object): + def cherryPickup(self, grid): + N = len(grid) + dp = [[float('-inf')] * N for _ in xrange(N)] + dp[0][0] = grid[0][0] + for t in xrange(1, 2 * N - 1): + dp2 = [[float('-inf')] * N for _ in xrange(N)] + for i in xrange(max(0, t - (N - 1)), min(N - 1, t) + 1): + for j in xrange(max(0, t - (N - 1)), min(N - 1, t) + 1): + if grid[i][t - i] == -1 or grid[j][t - j] == -1: + continue + val = grid[i][t - i] + if i != j: + val += grid[j][t - j] + dp2[i][j] = max(dp[pi][pj] + val + for pi in (i - 1, i) for pj in (j - 1, j) + if pi >= 0 and pj >= 0) + dp = dp2 + return max(0, dp[N - 1][N - 1]) +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(N^3)$ + +> **Reason**: where N is the length of `grid`. We have three for-loops of size N. + + +#### Space Complexity: $O(N^2)$ + +> **Reason**: the sizes of `dp` and `dp2`. + +## Video Solution + + + +## References + +- **LeetCode Problem**: [Cherry Pickup](https://leetcode.com/problems/cherry-pickup/description/) + +- **Solution Link**: [Cherry Pickup](https://leetcode.com/problems/cherry-pickup/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/0745-prefix-and-suffix-search.md b/solutions/lc-solutions/0700-0799/0745-prefix-and-suffix-search.md new file mode 100644 index 0000000..6d97a82 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0745-prefix-and-suffix-search.md @@ -0,0 +1,663 @@ +--- +id: prefix-and-suffix-search +title: Prefix and Suffix Search +sidebar_label: 0745 - Prefix and Suffix Search +tags: + - String + - Hash Table + - Depth-First Search +description: "This is a solution to the Prefix and Suffix Search problem on LeetCode." +--- + +## Problem Description + +Design a special dictionary that searches the words in it by a prefix and a suffix. + +Implement the `WordFilter` class: + +- `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary. +- `f(string pref, string suff)` Returns the index of the word in the dictionary, which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`. + +### Examples + +**Example 1:** + +``` +Input +["WordFilter", "f"] +[[["apple"]], ["a", "e"]] +Output +[null, 0] +Explanation +WordFilter wordFilter = new WordFilter(["apple"]); +wordFilter.f("a", "e"); // return 0, because the word at index 0 has prefix = "a" and suffix = "e". +``` + +### Constraints + +- $1 \leq words.length \leq 10^4$ +- $1 \leq words[i].length \leq 7$ +- $1 \leq pref.length, suff.length \leq 7$ +- `words[i]`, pref and suff consist of lowercase English letters only. +- At most $10^4$ calls will be made to the function `f`. + +## Solution for Prefix and Suffix Search + +## Approach 1: Trie + Set Intersection +### Intuition and Algorithm + +We use two tries to separately find all words that match the prefix, plus all words that match the suffix. Then, we try to find the highest-weight element in the intersection of these sets. + +Of course, these sets could still be large, so we might TLE if we aren't careful. + +### Code in Different Languages + + + + + +```cpp +#include +#include + +class TrieNode { +public: + TrieNode* children[26]; + std::unordered_set weight; + TrieNode() { + for (int i = 0; i < 26; i++) { + children[i] = nullptr; + } + } +}; + +class WordFilter { +private: + TrieNode trie1, trie2; +public: + WordFilter(std::vector& words) { + int wt = 0; + for (const std::string& word : words) { + TrieNode* cur = &trie1; + cur->weight.insert(wt); + for (char c : word) { + if (cur->children[c - 'a'] == nullptr) { + cur->children[c - 'a'] = new TrieNode(); + } + cur = cur->children[c - 'a']; + cur->weight.insert(wt); + } + + cur = &trie2; + cur->weight.insert(wt); + for (int j = word.length() - 1; j >= 0; j--) { + char c = word[j]; + if (cur->children[c - 'a'] == nullptr) { + cur->children[c - 'a'] = new TrieNode(); + } + cur = cur->children[c - 'a']; + cur->weight.insert(wt); + } + wt++; + } + } + + int f(std::string prefix, std::string suffix) { + TrieNode* cur1 = &trie1, *cur2 = &trie2; + for (char c : prefix) { + if (cur1->children[c - 'a'] == nullptr) { + return -1; + } + cur1 = cur1->children[c - 'a']; + } + for (int j = suffix.length() - 1; j >= 0; j--) { + char c = suffix[j]; + if (cur2->children[c - 'a'] == nullptr) { + return -1; + } + cur2 = cur2->children[c - 'a']; + } + + int ans = -1; + for (int w1 : cur1->weight) { + if (w1 > ans && cur2->weight.count(w1)) { + ans = w1; + } + } + + return ans; + } +}; + +``` + + + + +```java +class WordFilter { + TrieNode trie1, trie2; + public WordFilter(String[] words) { + trie1 = new TrieNode(); + trie2 = new TrieNode(); + int wt = 0; + for (String word: words) { + char[] ca = word.toCharArray(); + + TrieNode cur = trie1; + cur.weight.add(wt); + for (char letter: ca) { + if (cur.children[letter - 'a'] == null) { + cur.children[letter - 'a'] = new TrieNode(); + } + cur = cur.children[letter - 'a']; + cur.weight.add(wt); + } + + cur = trie2; + cur.weight.add(wt); + for (int j = ca.length - 1; j >= 0; --j) { + char letter = ca[j]; + if (cur.children[letter - 'a'] == null) { + cur.children[letter - 'a'] = new TrieNode(); + } + cur = cur.children[letter - 'a']; + cur.weight.add(wt); + } + wt++; + } + } + + public int f(String prefix, String suffix) { + TrieNode cur1 = trie1, cur2 = trie2; + for (char letter: prefix.toCharArray()) { + if (cur1.children[letter - 'a'] == null) { + return -1; + } + cur1 = cur1.children[letter - 'a']; + } + char[] ca = suffix.toCharArray(); + for (int j = ca.length - 1; j >= 0; --j) { + char letter = ca[j]; + if (cur2.children[letter - 'a'] == null) { + return -1; + } + cur2 = cur2.children[letter - 'a']; + } + + int ans = -1; + for (int w1: cur1.weight) { + if (w1 > ans && cur2.weight.contains(w1)) { + ans = w1; + } + } + + return ans; + } +} + +class TrieNode { + TrieNode[] children; + Set weight; + public TrieNode() { + children = new TrieNode[26]; + weight = new HashSet(); + } +} +``` + + + + + +```python +Trie = lambda: collections.defaultdict(Trie) +WEIGHT = False + +class WordFilter: + def __init__(self, words: List[str]): + self.trie1 = Trie() #prefix + self.trie2 = Trie() #suffix + for weight, word in enumerate(words): + cur = self.trie1 + self.addw(cur, weight) + for letter in word: + cur = cur[letter] + self.addw(cur, weight) + + cur = self.trie2 + self.addw(cur, weight) + for letter in word[::-1]: + cur = cur[letter] + self.addw(cur, weight) + + def addw(self, node, w): + if WEIGHT not in node: + node[WEIGHT] = {w} + else: + node[WEIGHT].add(w) + + def f(self, pref: str, suff: str) -> int: + cur1 = self.trie1 + for letter in pref: + if letter not in cur1: + return -1 + cur1 = cur1[letter] + + cur2 = self.trie2 + for letter in suff[::-1]: + if letter not in cur2: r + eturn -1 + cur2 = cur2[letter] + + return max(cur1[WEIGHT] & cur2[WEIGHT], default=-1) +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(NK+Q(N+K))$ + +> **Reason**: where `N` is the number of words, `K` is the maximum length of a word, and Q is the number of queries. If we use memoization in our solution, we could produce tighter bounds for this complexity, as the complex queries are somewhat disjoint. + +#### Space Complexity: $O(NK)$ + +> **Reason**: the size of the tries. + +## Approach 2: Paired Trie +### Intuition and Algorithm + +Say we are inserting the word `apple`. We could insert `('a', 'e'), ('p', 'l'), ('p', 'p'), ('l', 'p'), ('e', 'a')` into our trie. Then, if we had equal length queries like `prefix = "ap", suffix = "le"`, we could find the node `trie['a', 'e']['p', 'l']` in our trie. This seems promising. + +What about queries that aren't equal? We should just insert them like normal. For example, to capture a case like `prefix = "app", suffix = "e"`, we could create nodes `trie['a', 'e']['p', None]['p', None]`. + +After inserting these pairs into our trie, our searches are straightforward. + +### Code in Different Languages + + + + + +```cpp +#include + +class TrieNode { +public: + std::unordered_map children; + int weight; + TrieNode() { + weight = 0; + } +}; + +class WordFilter { +private: + TrieNode trie; + +public: + WordFilter(std::vector& words) { + int wt = 0; + for (const std::string& word : words) { + TrieNode* cur = ≜ + cur->weight = wt; + int L = word.length(); + for (int i = 0; i < L; ++i) { + TrieNode* tmp = cur; + for (int j = i; j < L; ++j) { + int code = (word[j] - '`') * 27; + if (tmp->children.count(code) == 0) { + tmp->children[code] = new TrieNode(); + } + tmp = tmp->children[code]; + tmp->weight = wt; + } + + tmp = cur; + for (int k = L - 1 - i; k >= 0; --k) { + int code = (word[k] - '`'); + if (tmp->children.count(code) == 0) { + tmp->children[code] = new TrieNode(); + } + tmp = tmp->children[code]; + tmp->weight = wt; + } + + int code = (word[i] - '`') * 27 + (word[L - 1 - i] - '`'); + if (cur->children.count(code) == 0) { + cur->children[code] = new TrieNode(); + } + cur = cur->children[code]; + cur->weight = wt; + } + wt++; + } + } + + int f(std::string prefix, std::string suffix) { + TrieNode* cur = ≜ + int i = 0, j = suffix.length() - 1; + while (i < prefix.length() || j >= 0) { + char c1 = i < prefix.length() ? prefix[i] : '`'; + char c2 = j >= 0 ? suffix[j] : '`'; + int code = (c1 - '`') * 27 + (c2 - '`'); + if (cur->children.count(code) == 0) { + return -1; + } + cur = cur->children[code]; + i++; + j--; + } + return cur->weight; + } +}; + + +``` + + + + +```java +class WordFilter { + TrieNode trie; + public WordFilter(String[] words) { + trie = new TrieNode(); + int wt = 0; + for (String word: words) { + TrieNode cur = trie; + cur.weight = wt; + int L = word.length(); + char[] chars = word.toCharArray(); + for (int i = 0; i < L; ++i) { + + TrieNode tmp = cur; + for (int j = i; j < L; ++j) { + int code = (chars[j] - '`') * 27; + if (tmp.children.get(code) == null) { + tmp.children.put(code, new TrieNode()); + } + tmp = tmp.children.get(code); + tmp.weight = wt; + } + + tmp = cur; + for (int k = L - 1 - i; k >= 0; --k) { + int code = (chars[k] - '`'); + if (tmp.children.get(code) == null) { + tmp.children.put(code, new TrieNode()); + } + tmp = tmp.children.get(code); + tmp.weight = wt; + } + + int code = (chars[i] - '`') * 27 + (chars[L - 1 - i] - '`'); + if (cur.children.get(code) == null) { + cur.children.put(code, new TrieNode()); + } + cur = cur.children.get(code); + cur.weight = wt; + + } + wt++; + } + } + + public int f(String prefix, String suffix) { + TrieNode cur = trie; + int i = 0, j = suffix.length() - 1; + while (i < prefix.length() || j >= 0) { + char c1 = i < prefix.length() ? prefix.charAt(i) : '`'; + char c2 = j >= 0 ? suffix.charAt(j) : '`'; + int code = (c1 - '`') * 27 + (c2 - '`'); + cur = cur.children.get(code); + if (cur == null) { + return -1; + } + i++; + j--; + } + return cur.weight; + } +} + +class TrieNode { + Map children; + int weight; + public TrieNode() { + children = new HashMap(); + weight = 0; + } +} +``` + + + + + +```python +Trie = lambda: collections.defaultdict(Trie) +WEIGHT = False + +class WordFilter: + def __init__(self, words: List[str]): + self.trie = Trie() + + for weight, word in enumerate(words): + cur = self.trie + cur[WEIGHT] = weight + for i, x in enumerate(word): + #Put all prefixes and suffixes + tmp = cur + for letter in word[i:]: + tmp = tmp[letter, None] + tmp[WEIGHT] = weight + + tmp = cur + for letter in word[:-i or None][::-1]: + tmp = tmp[None, letter] + tmp[WEIGHT] = weight + + #Advance letters + cur = cur[x, word[~i]] + cur[WEIGHT] = weight + + def f(self, pref: str, suff: str) -> int: + cur = self.trie + for a, b in zip_longest(pref, suff[::-1]): + if (a, b) not in cur: + return -1 + cur = cur[a, b] + return cur[WEIGHT] +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(NK^2+QK)$ + +> **Reason**: where `N` is the number of words, `K` is the maximum length of a word, and `Q` is the number of queries. + + +#### Space Complexity: $O(NK^2)$ + +> **Reason**: the size of the trie. + +## Approach 3: Trie of Suffix Wrapped Words +### Intuition and Algorithm + +Intuition and Algorithm + +Consider the word `'apple'`. For each suffix of the word, we could insert that suffix, followed by `'#'`, followed by the word, all into the trie. + +For example, we will insert `'#apple', 'e#apple', 'le#apple', 'ple#apple', 'pple#apple', 'apple#apple'` into the trie. Then for a query like `prefix = "ap", suffix = "le"`, we can find it by querying our trie for `le#ap`. + +### Code in Different Languages + + + + + +```cpp +class TrieNode { +public: + TrieNode* children[27]; + int weight; + TrieNode() { + memset(children, 0, sizeof(children)); + weight = 0; + } +}; + +class WordFilter { +public: + TrieNode trie; + WordFilter(vector& words) { + for (int weight = 0; weight < words.size(); ++weight) { + string word = words[weight] + "{"; + for (int i = 0; i < word.length(); ++i) { + TrieNode* cur = ≜ + cur->weight = weight; + for (int j = i; j < 2 * word.length() - 1; ++j) { + int k = word[j % word.length()] - 'a'; + if (!cur->children[k]) { + cur->children[k] = new TrieNode(); + } + cur = cur->children[k]; + cur->weight = weight; + } + } + } + } + + int f(string prefix, string suffix) { + TrieNode* cur = ≜ + for (char letter : (suffix + '{' + prefix)) { + if (!cur->children[letter - 'a']) { + return -1; + } + cur = cur->children[letter - 'a']; + } + return cur->weight; + } +}; + + + + +``` + + + + +```java +class WordFilter { + TrieNode trie; + public WordFilter(String[] words) { + trie = new TrieNode(); + for (int weight = 0; weight < words.length; ++weight) { + String word = words[weight] + "{"; + for (int i = 0; i < word.length(); ++i) { + TrieNode cur = trie; + cur.weight = weight; + for (int j = i; j < 2 * word.length() - 1; ++j) { + int k = word.charAt(j % word.length()) - 'a'; + if (cur.children[k] == null) { + cur.children[k] = new TrieNode(); + } + cur = cur.children[k]; + cur.weight = weight; + } + } + } + } + public int f(String prefix, String suffix) { + TrieNode cur = trie; + for (char letter: (suffix + '{' + prefix).toCharArray()) { + if (cur.children[letter - 'a'] == null) { + return -1; + } + cur = cur.children[letter - 'a']; + } + return cur.weight; + } +} + +class TrieNode { + TrieNode[] children; + int weight; + public TrieNode() { + children = new TrieNode[27]; + weight = 0; + } +} +``` + + + + + +```python +Trie = lambda: collections.defaultdict(Trie) +WEIGHT = False + +class WordFilter: + def __init__(self, words: List[str]): + self.trie = Trie() + + for weight, word in enumerate(words): + word += '#' + for i in range(len(word)): + cur = self.trie + cur[WEIGHT] = weight + for j in range(i, 2 * len(word) - 1): + cur = cur[word[j % len(word)]] + cur[WEIGHT] = weight + + def f(self, pref: str, suff: str) -> int: + cur = self.trie + for letter in suff + '#' + pref: + if letter not in cur: + return -1 + cur = cur[letter] + return cur[WEIGHT] +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(NK^2+QK)$ + +> **Reason**: `nums` is divided into half each time. In the worst-case scenario, we need to cut `nums` until the range has no element, it takes logarithmic time to reach this break condition. + +#### Space Complexity: $O(NK^2)$ + +> **Reason**: the size of the trie. + +## Video Solution + + + +## References + +- **LeetCode Problem**: [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/description/) + +- **Solution Link**: [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/0747-Largest-Number-Atleast-Twice-Of-Others.md b/solutions/lc-solutions/0700-0799/0747-Largest-Number-Atleast-Twice-Of-Others.md new file mode 100644 index 0000000..7d4ac15 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0747-Largest-Number-Atleast-Twice-Of-Others.md @@ -0,0 +1,189 @@ +--- +id: largest-number-atleast-twice-of-others +title: Largest Number At Least Twice of Others +sidebar_label: 747-Largest-Number-Atleast-Twice-Of-Other +tags: + - Array + - Sorting +--- + +## Problem Description +You are given an integer array `nums` where the largest integer is unique. + +Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return `-1` otherwise. + +### Example + +**Example 1:** + + +``` +Input: nums = [3,6,1,0] +Output: 1 +Explanation: 6 is the largest integer. +For every other number in the array x, 6 is at least twice as big as x. +The index of value 6 is 1, so we return 1. +``` +**Example 2:** +``` +Input: nums = [1,2,3,4] +Output: -1 +Explanation: 4 is less than twice the value of 3, so we return -1. +``` +### Constraints + +- `0 <= nums[i] <= 100` + +## Solution Approach + +### Intuition: + +To efficiently determine Largest Number At Least Twice of Others +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + +class Solution { + dominantIndex(nums) { + let cnt = 0, index = -1; + let maxi = -Infinity, smax = -Infinity; + for(let i = 0; i < nums.length; i++){ + if(nums[i] >= maxi){ + smax = maxi; + maxi = nums[i]; + index = i; + } else if(nums[i] < maxi && nums[i] >= smax){ + smax = nums[i]; + } + } + if(maxi >= 2 * smax) return index; + return -1; + } +} + + + + + + ``` + + + + + ```typescript + class Solution { + dominantIndex(nums: number[]): number { + let cnt = 0, index = -1; + let maxi = -Infinity, smax = -Infinity; + for(let i = 0; i < nums.length; i++){ + if(nums[i] >= maxi){ + smax = maxi; + maxi = nums[i]; + index = i; + } else if(nums[i] < maxi && nums[i] >= smax){ + smax = nums[i]; + } + } + if(maxi >= 2 * smax) return index; + return -1; + } +} + + + + + ``` + + + + + ```python + class Solution: + def dominantIndex(self, nums): + cnt = 0 + index = -1 + maxi = float('-inf') + smax = float('-inf') + for i in range(len(nums)): + if nums[i] >= maxi: + smax = maxi + maxi = nums[i] + index = i + elif nums[i] < maxi and nums[i] >= smax: + smax = nums[i] + if maxi >= 2 * smax: + return index + return -1 + + + + + + ``` + + + + + ```java + public class Solution { + public int dominantIndex(int[] nums) { + int cnt = 0, index = -1; + int maxi = Integer.MIN_VALUE, smax = Integer.MIN_VALUE; + for(int i = 0; i < nums.length; i++){ + if(nums[i] >= maxi){ + smax = maxi; + maxi = nums[i]; + index = i; + } else if(nums[i] < maxi && nums[i] >= smax){ + smax = nums[i]; + } + } + if(maxi >= 2 * smax) return index; + return -1; + } +} + + + + + ``` + + + + + ```cpp +class Solution { +public: + int dominantIndex(vector& nums) { + int cnt=0, index = -1; + int maxi = INT_MIN; + int smax = INT_MIN; + for(int i=0; i=maxi){ + smax = maxi; + maxi = nums[i]; + index = i; + } + else if(nums[i]=smax){ + smax = nums[i]; + } + } + if(maxi>=2*smax) return index; + return -1; + } +}; +``` + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(n)$$ where n is the length of the input array nums. This is because the algorithm iterates through the array once, performing a constant amount of work for each element. +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/0752-open-the-lock.md b/solutions/lc-solutions/0700-0799/0752-open-the-lock.md new file mode 100644 index 0000000..276b7dc --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0752-open-the-lock.md @@ -0,0 +1,455 @@ +--- +id: open-the-lock +title: Open the Lock +sidebar_label: 0752 - Open the Lock +tags: + - Breadth-First Search + - Hash Table + - String +description: "This is a solution to the Open the Lock problem on LeetCode." +--- + +## Problem Description + +You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: `'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'`. The wheels can rotate freely and wrap around: for example we can turn `'9'` to be `'0'`, or `'0'` to be `'9'`. Each move consists of turning one wheel one slot. + +The lock initially starts at `'0000'`, a string representing the state of the 4 wheels. + +You are given a list of `deadends` dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. + +Given a `target` representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. + +### Examples + +**Example 1:** + +``` +Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202" +Output: 6 +Explanation: +A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202". +Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid, +because the wheels of the lock become stuck after the display becomes the dead end "0102". +``` +**Example 2:** + +``` +Input: deadends = ["8888"], target = "0009" +Output: 1 +Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009". +``` + +### Constraints + +- `1 <= deadends.length <= 500` +- `deadends[i].length == 4` +- `target.length == 4` +- `target` **will not be** in the list `deadends`. +- `target` and `deadends[i]` consist of digits only. + +## Solution for Open the Lock + +## Overview + +For simplicity, let's say any combination of any state of all wheels represents one lock combination. e.g. `'0000', '1000', '2000', ...` etc. all represent a lock combination. + +Say we are currently at combination `'0000'`, and we make one wheel turn. Now we are at combination 1000. This combination change due to one wheel turn can be visualized as traversing a graph from node 1 (`combination '0000'`) to node 2 (`combination '1000'`). + +It can be better understood with the help of the following image: + +![image](https://assets.leetcode.com/static_assets/media/original_images/752/Slide1.jpg) + +In this graph, each node represents a lock combination, and the edge represents one wheel turn. + +According to the problem statement, we start from the lock combination `'0000'`. We can make one wheel turn at a time and need to find the minimum steps required to reach the target lock combination. + +As we observed, each lock combination is a graph's node, and each wheel turn is an edge connecting two nodes. The given problem statement can be re-worded as: "We start from node `lock combination '0000'` and have to find the minimum number of edges to traverse to reach the target lock combination node." Thus, the given problem can be converted into a graph traversal problem. + +To traverse nodes in a graph, we mainly utilize two algorithms: depth-first search (DFS), and breadth-first search (BFS). If you are new to these algorithms we recommend reading our Depth-First Search and Breadth-First Search explore cards. + +We can solve this problem using both traversals, but given the constraints, the depth-first search will result in a TLE. This is because DFS explores as deeply as possible along each branch before backtracking. It doesn't necessarily explore nodes in any particular order; it might go deep into a branch before exploring other branches. + +BFS is well-suited for finding the shortest path in unweighted graphs, which makes it a good fit for this problem because BFS explores nodes level by level. It starts from the source node and explores all its neighbors before moving on to the next level of neighbors. Due to its level-order exploration strategy, BFS guarantees that the first time it reaches a node, it has found the shortest path to that node. + +![image](https://assets.leetcode.com/static_assets/media/original_images/752/Slide2.jpg) + +## Approach: Breadth-First Search +### Intuition + +We will keep a queue, `pending_combinations`, containing the lock combinations yet to be visited using BFS. +Initially, it will contain the starting combination `'0000'`. + +We will visit each combination stored in the queue one by one. If the current popped combination is the target combination, we will return the number of edges traversed (number of wheel turns we made) to reach this combination. BFS guarantees the shortest path in an unweighted graph, so as soon as we find an answer, we know it is the optimal one. +Otherwise, we will generate new combinations from the current combination, by rotating each of the four wheels to the next slot digit and the previous slot digit one by one. Then we will push the new combinations into the queue. + +![image](https://assets.leetcode.com/static_assets/media/original_images/752/Slide3.jpg) + +We will keep two additional data structures to quickly fetch the next and the previous slot digits for the current slot digits whenever needed. + +Notice that we might reach the same lock combinations, again and again, using different paths, and these duplicate combinations will always generate the same next combinations. + +![image](https://assets.leetcode.com/static_assets/media/original_images/752/Slide4.jpg) + +So, we will keep one additional data structure to mark visited combinations to avoid traversing on a combination more than once. +We also have some dead-end combinations from which we can't proceed further. We can consider these combinations as visited combinations because we cannot generate new combinations using these combinations. + +Thus, we will keep a hash set visited_combinations, insert the dead-end combinations in it initially, and will insert the visited combinations while doing the BFS. + +### Algorithm + +1. Initialization: + + - Create two character maps, `next_slot` to map the current slot digit with its next slot digit, and `prev_slot` to map the current slot digit with its previous slot digit. + - Create a hash set `visited_combinations`, initially containing all `deadends` array combinations. + - Create a queue `pending_combinations` to traverse all combinations in level-wise BFS. + - Create an integer variable `turns` initially storing `0`, to denote the number of wheel turns made. + +2. If `visited_combinations` contains the starting combination `'0000'` then we can never reach the target combination and will return `-1`. + +3. Insert the starting combination `'0000'` in the queue and mark it as visited. + +4. While there are elements in the queue, iterate on all current level combinations using a for loop: + + - Pop the current combination from the front of the queue. + - If the current combination is the target combination return `turns`. + - Otherwise, iterate on all four wheels; for each wheel, generate the new combination by turning the respective wheel to the next slot and the previous slot. If the new combination is not present in `visited_combinations` then push it in the queue and mark it as visited. + - After iterating on all current level combinations increment `turns` by `1`. + +5. If we never reach the target combination, then, return `-1`. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int openLock(vector& deadends, string target) { + // Map the next slot digit for each current slot digit. + unordered_map nextSlot = { + {'0', '1'}, + {'1', '2'}, + {'2', '3'}, + {'3', '4'}, + {'4', '5'}, + {'5', '6'}, + {'6', '7'}, + {'7', '8'}, + {'8', '9'}, + {'9', '0'} + }; + // Map the previous slot digit for each current slot digit. + unordered_map prevSlot = { + {'0', '9'}, + {'1', '0'}, + {'2', '1'}, + {'3', '2'}, + {'4', '3'}, + {'5', '4'}, + {'6', '5'}, + {'7', '6'}, + {'8', '7'}, + {'9', '8'} + }; + + // Hash set to store visited and dead-end combinations. + unordered_set visitedCombinations(deadends.begin(), deadends.end()); + // Queue to store combinations generated after each turn. + queue pendingCombinations; + + // Count the number of wheel turns made. + int turns = 0; + + // If the starting combination is also a dead-end, + // then we can't move from the starting combination. + if (visitedCombinations.find("0000") != visitedCombinations.end()) { + return -1; + } + + // Start with the initial combination '0000'. + pendingCombinations.push("0000"); + visitedCombinations.insert("0000"); + + while (!pendingCombinations.empty()) { + // Explore all the combinations of the current level. + for (int currLevelNodesCount = pendingCombinations.size(); + currLevelNodesCount > 0; --currLevelNodesCount) { + // Get the current combination from the front of the queue. + string currentCombination = pendingCombinations.front(); + pendingCombinations.pop(); + + // If the current combination matches the target, + // return the number of turns/level. + if (currentCombination == target) { + return turns; + } + + // Explore all possible new combinations by turning each wheel in both directions. + for (int wheel = 0; wheel < 4; wheel += 1) { + // Generate the new combination by turning the wheel to the next digit. + string newCombination = currentCombination; + newCombination[wheel] = nextSlot[newCombination[wheel]]; + // If the new combination is not a dead-end and was never visited, + // add it to the queue and mark it as visited. + if (visitedCombinations.find(newCombination) == visitedCombinations.end()) { + pendingCombinations.push(newCombination); + visitedCombinations.insert(newCombination); + } + + // Generate the new combination by turning the wheel to the previous digit. + newCombination = currentCombination; + newCombination[wheel] = prevSlot[newCombination[wheel]]; + // If the new combination is not a dead-end and is never visited, + // add it to the queue and mark it as visited. + if (visitedCombinations.find(newCombination) == visitedCombinations.end()) { + pendingCombinations.push(newCombination); + visitedCombinations.insert(newCombination); + } + } + } + // We will visit the next-level combinations. + turns += 1; + } + // We never reached the target combination. + return -1; + } +}; +``` + + + + +```java +class Solution { + public int openLock(String[] deadends, String target) { + // Map the next slot digit for each current slot digit. + Map nextSlot = Map.of( + '0', '1', + '1', '2', + '2', '3', + '3', '4', + '4', '5', + '5', '6', + '6', '7', + '7', '8', + '8', '9', + '9', '0' + ); + // Map the previous slot digit for each current slot digit. + Map prevSlot = Map.of( + '0', '9', + '1', '0', + '2', '1', + '3', '2', + '4', '3', + '5', '4', + '6', '5', + '7', '6', + '8', '7', + '9', '8' + ); + + // Set to store visited and dead-end combinations. + Set visitedCombinations = new HashSet<>(Arrays.asList(deadends)); + // Queue to store combinations generated after each turn. + Queue pendingCombinations = new LinkedList(); + + // Count the number of wheel turns made. + int turns = 0; + + // If the starting combination is also a dead-end, + // then we can't move from the starting combination. + if (visitedCombinations.contains("0000")) { + return -1; + } + + // Start with the initial combination '0000'. + pendingCombinations.add("0000"); + visitedCombinations.add("0000"); + + while (!pendingCombinations.isEmpty()) { + // Explore all the combinations of the current level. + int currLevelNodesCount = pendingCombinations.size(); + for (int i = 0; i < currLevelNodesCount; i++) { + // Get the current combination from the front of the queue. + String currentCombination = pendingCombinations.poll(); + + // If the current combination matches the target, + // return the number of turns/level. + if (currentCombination.equals(target)) { + return turns; + } + + // Explore all possible new combinations by turning each wheel in both directions. + for (int wheel = 0; wheel < 4; wheel += 1) { + // Generate the new combination by turning the wheel to the next digit. + StringBuilder newCombination = new StringBuilder(currentCombination); + newCombination.setCharAt(wheel, nextSlot.get(newCombination.charAt(wheel))); + // If the new combination is not a dead-end and was never visited, + // add it to the queue and mark it as visited. + if (!visitedCombinations.contains(newCombination.toString())) { + pendingCombinations.add(newCombination.toString()); + visitedCombinations.add(newCombination.toString()); + } + + // Generate the new combination by turning the wheel to the previous digit. + newCombination = new StringBuilder(currentCombination); + newCombination.setCharAt(wheel, prevSlot.get(newCombination.charAt(wheel))); + // If the new combination is not a dead-end and is never visited, + // add it to the queue and mark it as visited. + if (!visitedCombinations.contains(newCombination.toString())) { + pendingCombinations.add(newCombination.toString()); + visitedCombinations.add(newCombination.toString()); + } + } + } + // We will visit next-level combinations. + turns += 1; + } + // We never reached the target combination. + return -1; + } +} +``` + + + + + +```python +class Solution: + def openLock(self, deadends: List[str], target: str) -> int: + # Map the next slot digit for each current slot digit. + next_slot = { + "0": "1", + "1": "2", + "2": "3", + "3": "4", + "4": "5", + "5": "6", + "6": "7", + "7": "8", + "8": "9", + "9": "0", + } + # Map the previous slot digit for each current slot digit. + prev_slot = { + "0": "9", + "1": "0", + "2": "1", + "3": "2", + "4": "3", + "5": "4", + "6": "5", + "7": "6", + "8": "7", + "9": "8", + } + + # Set to store visited and dead-end combinations. + visited_combinations = set(deadends) + # Queue to store combinations generated after each turn. + pending_combinations = deque() + + # Count the number of wheel turns made. + turns = 0 + + # If the starting combination is also a dead-end, + # then we can't move from the starting combination. + if "0000" in visited_combinations: + return -1 + + # Start with the initial combination '0000'. + pending_combinations.append("0000") + visited_combinations.add("0000") + + while pending_combinations: + # Explore all combinations of the current level. + curr_level_nodes_count = len(pending_combinations) + for _ in range(curr_level_nodes_count): + # Get the current combination from the front of the queue. + current_combination = pending_combinations.popleft() + + # If the current combination matches the target, + # return the number of turns/level. + if current_combination == target: + return turns + + # Explore all possible new combinations + # by turning each wheel in both directions. + for wheel in range(4): + # Generate the new combination + # by turning the wheel to the next digit. + new_combination = list(current_combination) + new_combination[wheel] = next_slot[new_combination[wheel]] + new_combination_str = "".join(new_combination) + # If the new combination is not a dead-end and + # was never visited, + # add it to the queue and mark it as visited. + if new_combination_str not in visited_combinations: + pending_combinations.append(new_combination_str) + visited_combinations.add(new_combination_str) + + # Generate the new combination + # by turning the wheel to the previous digit. + new_combination = list(current_combination) + new_combination[wheel] = prev_slot[new_combination[wheel]] + new_combination_str = "".join(new_combination) + # If the new combination is not a dead-end and + # is never visited, + # add it to the queue and mark it as visited. + if new_combination_str not in visited_combinations: + pending_combinations.append(new_combination_str) + visited_combinations.add(new_combination_str) + + # We will visit next-level combinations. + turns += 1 + + # We never reached the target combination. + return -1 +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(4(d+10^4))$ + +> **Reason**: +> - Initializing the hash maps with `n` key-value pairs, and the hash set with `d` combinations of length `w` will take $O(2 \cdot n)$ and $O(d \cdot w)$ time respectively. +> - In the worst case, we might iterate on all $n^w$ unique combinations, and for each combination, we perform $2 \cdot w$. Thus, it will take $O(n^w \cdot 2 \cdot w)=O(n^w \cdot w)$ time. +> - So, this approach will take $O(n+(d+n^w) \cdot w) = O(10+(d+10^4) \cdot 4) = O(4(d+10^4))$ time. + +#### Space Complexity: $O(4(d+10^4))$ + +> **Reason**: +> - The hash maps with `n` key-value pairs, and the hash set with `d` combinations of length `w` will take $O(2 \cdot n)$ and $O(d \cdot w)$ space respectively. +> - In the worst case, we might push all $n^w$ wunique combinations of length w in the queue and the hash set. Thus, it will take $O(n^w \cdot w)$ space. +>- So, this approach will take $O(n+(d+n^w) \cdot w) = O(4(d+10^4))$ space. + +## Video Solution + + + +## References + +- **LeetCode Problem**: [Open the Lock](https://leetcode.com/problems/open-the-lock/description/) + +- **Solution Link**: [Open the Lock](https://leetcode.com/problems/open-the-lock/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/0755-pour-water.md b/solutions/lc-solutions/0700-0799/0755-pour-water.md new file mode 100644 index 0000000..3bc8e3d --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0755-pour-water.md @@ -0,0 +1,176 @@ +--- +id: pour-water +title: Pour Water. +sidebar_label: 0755-pour-water +tags: + - Array + - Simulation +description: "This is a solution to Pour Water problem on LeetCode." +--- + +## Problem Description + +You are given an elevation map represents as an integer array `heights` where `heights[i]` representing the `height` of the terrain at index `i`. The width at each index is `1`. You are also given two integers `volume` and `k`. `volume` units of water will fall at index `k`. + +Water first drops at the index `k` and rests on top of the highest terrain or water at that index. Then, it flows according to the following rules: + +β€’ If the droplet would eventually fall by moving left, then move left. +β€’ Otherwise, if the droplet would eventually fall by moving right, then + move right. +β€’ Otherwise, rise to its current position. + +Here, "**eventually fall**" means that the droplet will eventually be at a lower level if it moves in that direction. Also, level means the height of the terrain plus any water in that column. + +We can assume there is infinitely high terrain on the two sides out of bounds of the array. Also, there could not be partial water being spread out evenly on more than one grid block, and each unit of water has to be in exactly one block. + +### Examples + +**Example 1:** + +``` +Input: heights = [2,1,1,2,1,2,2], volume = 4, k = 3 +Output: [2,2,2,3,2,2,2] +Explanation: The first drop of water lands at index k = 3. When moving left or right, the water can only move to the same level or a lower level. (By level, we mean the total height of the terrain plus any water in that column.) +Since moving left will eventually make it fall, it moves left. (A droplet "made to fall" means go to a lower height than it was at previously.) Since moving left will not make it fall, it stays in place. + +The next droplet falls at index k = 3. Since the new droplet moving left will eventually make it fall, it moves left. Notice that the droplet still preferred to move left, even though it could move right (and moving right makes it fall quicker.) + +The third droplet falls at index k = 3. Since moving left would not eventually make it fall, it tries to move right. Since moving right would eventually make it fall, it moves right. +Finally, the fourth droplet falls at index k = 3. Since moving left would not eventually make it fall, it tries to move right. Since moving right would not eventually make it fall, it stays in place. + +``` + +**Example 2:** + +``` +Input: heights = [1,2,3,4], volume = 2, k = 2 +Output: [2,3,3,4] +Explanation: The last droplet settles at index 1, since moving further left would not cause it to eventually fall to a lower height. +``` + +**Example 3:** + +``` +Input: heights = [3,1,3], volume = 5, k = 1 +Output: [4,4,4] + +``` + +### Constraints + +- `1 <= heights.length <= 100` +- `0 <= heights[i] <= 99` +- `0 <= volume <= 2000` +- `0 <= k < heights.length` + + +## Solution for Assign Cookies + +### Approach: + +1- For each unit of water, try to move left from the starting index k + to find the lowest point. + +2- If no lower point is found on the left, try to move right from the + starting index k to find the lowest point. + +3- If a lower point is found, add water there. + +4- If no lower point is found on either side, add water at the starting + index k. + +5- Repeat the process for the given volume of water and return the + modified heights. + + +## Code in Different Languages + +### C++ + +```cpp +class Solution { +public: + vector pourWater(vector& heights, int volume, int k) { + while (volume--) { + bool find = false; + for (int d = -1; d < 2 && !find; d += 2) { + int i = k, j = k; + while (i + d >= 0 && i + d < heights.size() && heights[i + d] <= heights[i]) { + if (heights[i + d] < heights[i]) { + j = i + d; + } + i += d; + } + if (j != k) { + find = true; + ++heights[j]; + } + } + if (!find) { + ++heights[k]; + } + } + return heights; + } +}; +``` +### Java + +```java +class Solution { + public int[] pourWater(int[] heights, int volume, int k) { + while (volume-- > 0) { + boolean find = false; + for (int d = -1; d < 2 && !find; d += 2) { + int i = k, j = k; + while (i + d >= 0 && i + d < heights.length && heights[i + d] <= heights[i]) { + if (heights[i + d] < heights[i]) { + j = i + d; + } + i += d; + } + if (j != k) { + find = true; + ++heights[j]; + } + } + if (!find) { + ++heights[k]; + } + } + return heights; + } +} + +``` + +### Python + +```python +class Solution: + def pourWater(self, heights: List[int], volume: int, k: int) -> List[int]: + for _ in range(volume): + for d in (-1, 1): + i = j = k + while 0 <= i + d < len(heights) and heights[i + d] <= heights[i]: + if heights[i + d] < heights[i]: + j = i + d + i += d + if j != k: + heights[j] += 1 + break + else: + heights[k] += 1 + return heights +``` + +## Complexity Analysis + +### Time Complexity: O(Volume Γ— n) + +### Space Complexity: O(1) + +## References + +- **LeetCode Problem**: [Pour Water](https://leetcode.com/problems/pour-water/description/) + diff --git a/solutions/lc-solutions/0700-0799/0756-pyramid-transition-matrix.md b/solutions/lc-solutions/0700-0799/0756-pyramid-transition-matrix.md new file mode 100644 index 0000000..335e6df --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0756-pyramid-transition-matrix.md @@ -0,0 +1,210 @@ +--- +id: pyramid-transition-matrix +title: Pyramid Transition Matrix +sidebar_label: 0756-pyramid-transition-matrix +tags: + - Bit Manipulation + - Depth-First Search + - Breadth-First Search + +description: "This is a solution to pyramid-transition-matrix problem on LeetCode." +--- + +## Problem Description + +You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains **one less block** than the row beneath it and is centered on top. + +To make the pyramid aesthetically pleasing, there are only specific **triangular patterns** that are allowed. A triangular pattern consists of a **single block** stacked on top of **two blocks**. The patterns are given as a list of three-letter strings allowed, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block. + + β€’ For example, `"ABC"` represents a triangular pattern with a `'C'` + blockstacked on top of an `'A' (left)` and `'B' (right)` block. Note that this is different from `"BAC"` where `'B'` is on the `left` bottom and `'A'` is on the `right` bottom. + +You start with a bottom row of blocks bottom, given as a single string, that you **must** use as the base of the pyramid. + +Given `bottom` and `allowed`, return `true` if you can build the pyramid all the way to the top such that **every triangular** pattern in the pyramid is in `allowed`, or `false` otherwise. + +### Examples + +**Example 1:** + +``` +Input: bottom = "BCD", allowed = ["BCC","CDE","CEA","FFF"] +Output: true +Explanation: The allowed triangular patterns are shown on the right. +Starting from the bottom (level 3), we can build "CE" on level 2 and then build "A" on level 1. +There are three triangular patterns in the pyramid, which are "BCC", "CDE", and "CEA". All are allowed. +``` + +**Example 2:** + +``` +Input: bottom = "AAAA", allowed = ["AAB","AAC","BCD","BBE","DEF"] +Output: false +Explanation: The allowed triangular patterns are shown on the right. +Starting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1. +``` + + +### Constraints + +- `2 <= bottom.length <= 6` +- `0 <= allowed.length <= 216` +- `allowed[i].length == 3` +- The letters in all input strings are from the set `{'A', 'B', 'C', 'D', 'E', 'F'}`. + - All the values of allowed are **unique**. + + +## Solution for Assign Cookies + +### Approach: + +1- Create a matrix to store possible transitions and initialize a stack for traversal. +2- Build a mapping dictionary from the allowed list for quick lookup of transitions. +3- Use a stack-based approach to iterate through possible transitions from the bottom row upwards. +4- For each position, find parent characters and check possible transitions, updating the matrix and stack as necessary. +5- If all positions are successfully filled, return True; otherwise, backtrack and return False if no valid transition exists. + + +## Code in Different Languages + +### C++ + +```cpp +class Solution { + unordered_set invalid; + bool solve(string bottom, int i, unordered_map mp, string z) + { + int n=bottom.size(); + int m=z.size(); + if(n<2) + return true; + if(invalid.count(bottom)) + return false; + if(m==n-1) + return solve(z, 0, mp, ""); + if(m>1 && mp.find(z.substr(m-2,2))==mp.end()) + return false; + for(char ch:mp[bottom.substr(i,2)]){ + z.push_back(ch); + if(solve(bottom, i+1, mp, z)) + return true; + z.pop_back(); + } + invalid.insert(bottom); + return false; + } +public: + bool pyramidTransition(string bottom, vector& allowed) { + unordered_map mp; + for(int i=0;i allowed) { + Map> map = new HashMap<>(); + for (String s : allowed) { + String k = s.substring(0, 2); + Set set = map.getOrDefault(k, new HashSet<>()); + set.add(s.charAt(2)); + map.put(k, set); + } + Map dp = new HashMap<>(); + boolean res = search2(bottom + "#", map, dp); + return res; + } + private boolean search2(String s, Map> map, Map dp) { + if (s.length() == 1) return true; + if (dp.containsKey(s)) return dp.get(s) == 1; + String key = s.substring(0, 2); + if (key.charAt(1) == '#') return search2(s.substring(2) + "#", map, dp); + for (Character c : map.getOrDefault(key, new HashSet<>())) { + boolean r = search2(s.substring(1) + c, map, dp); + if (r) { + dp.put(s, 1); + return true; + } + } + dp.put(s, 0); + return false; + } + private boolean search(String s, Map> map, Map dp) { + if (s.length() == 2) { + return map.containsKey(s); + } + if (s.length() < 2) return false; + List nextLevel = new ArrayList<>(); + nextLevel.add(""); + for (int i = 0; i < s.length() - 1; i++) { + List list = new ArrayList<>(); + String k = s.substring(i, i + 2); + if (!map.containsKey(k)) return false; + for (Character e : map.get(k)) { + for (String ps : nextLevel) { + list.add(ps + e); + } + } + nextLevel = list; + } + boolean res = false; + for (String e : nextLevel) { + res = search(e, map, dp); + if (res) return true; + } + return false; + } +} +``` + +### Python + +```python +class Solution: + def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool: + n = len(bottom) + mat = [[('X', -1) for _ in range(n-1-i)] for i in range(n-1)] + stack = [(row, l-row) for l in range(n-1) for row in range(l+1)] + mapping = {} + for a in allowed: + if a[:2] not in mapping: + mapping[a[:2]] = [a[2]] + else: + mapping[a[:2]].append(a[2]) + pos = 0 + def find_parents(row, col): + if row == 0: + return bottom[col:col+2] + return mat[row-1][col][0] + mat[row-1][col+1][0] + + while pos >= 0 and pos < len(stack): + row, col = stack[pos] + me, idx = mat[row][col] + parents = find_parents(row, col) + options = mapping.get(parents, []) + if idx+1 < len(options): + idx += 1 + me = options[idx] + mat[row][col] = (me, idx) + pos += 1 + else: + pos -= 1 + return pos >= len(stack) +``` + +## Complexity Analysis + +### Time Complexity: O(K Γ— n^2) + +### Space Complexity: O(n^2) + +## References + +- **LeetCode Problem**: [Pyramid Transition Matrix](https://leetcode.com/problems/pyramid-transition-matrix/) + diff --git a/solutions/lc-solutions/0700-0799/0767-reorganize-string.md b/solutions/lc-solutions/0700-0799/0767-reorganize-string.md new file mode 100644 index 0000000..10c9487 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0767-reorganize-string.md @@ -0,0 +1,194 @@ +--- +id: reorganize-string +title: Reorganize String +sidebar_label: 0767-Reorganize String +tags: + - Leet code + - heapq +description: "Solution to leetocde 767" +--- + +## Problem Statement + +Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. + +Return any possible rearrangement of `s` or return `""` if not possible. + +### Example 1 + +``` +**Input**: `s = "aab"` + +**Output**: `"aba"` +``` + +### Example 2 + +``` +**Input**: `s = "aaab"` + +**Output**: `""` +``` + +### Constraints + +- $(1 \leq \text{s.length} \leq 500)$ +- `s` consists of lowercase English letters. + +## Algorithm + +1. **Counting Frequencies**: We count the frequency of each character using `Counter`. + +2. **Max-Heap**: We store the frequency as a negative value because `heapq` in Python is a min-heap. By storing negative values, the character with the highest positive frequency will be at the root of the heap. + +3. **Heap Operations**: We pop from the heap and append the character to the result. If the previous character still has a remaining count, we push it back into the heap. + +4. **Final Check**: After constructing the result, we check if its length matches the input string. If not, it's impossible to rearrange the string as required. + +### Code Implementation + +### Solution in Python + +```python +import heapq +from collections import Counter + +class Solution: + def reorganizeString(self, s: str) -> str: + freq_map = Counter(s) + + # Max heap to store characters by frequency + max_heap = [(-freq, char) for char, freq in freq_map.items()] + heapq.heapify(max_heap) + + result = [] + prev_freq, prev_char = 0, '' + + while max_heap: + freq, char = heapq.heappop(max_heap) + result.append(char) + + # If the previous character frequency is > 0, push it back into the heap + if prev_freq < 0: + heapq.heappush(max_heap, (prev_freq, prev_char)) + + # Decrease frequency and set the previous character to current + prev_freq, prev_char = freq + 1, char + + result_str = ''.join(result) + + # If the reorganized string is of the same length as the input string, return it + return result_str if len(result_str) == len(s) else "" +``` + +### C++ Solution + +```cpp +#include +#include +#include + +class Solution { +public: + std::string reorganizeString(std::string s) { + std::unordered_map freqMap; + for (char c : s) { + freqMap[c]++; + } + + std::priority_queue> maxHeap; + for (auto& pair : freqMap) { + maxHeap.push({pair.second, pair.first}); + } + + std::string result = ""; + std::pair prev = {-1, '#'}; // To store the previous character + + while (!maxHeap.empty()) { + auto current = maxHeap.top(); + maxHeap.pop(); + + result += current.second; + + if (prev.first > 0) { + maxHeap.push(prev); + } + + current.first--; + prev = current; + } + + return result.size() == s.size() ? result : ""; + } +}; +``` + +### Java Solution + +```java +import java.util.PriorityQueue; +import java.util.HashMap; +import java.util.Map; + +class Solution { + public String reorganizeString(String s) { + Map freqMap = new HashMap<>(); + for (char c : s.toCharArray()) { + freqMap.put(c, freqMap.getOrDefault(c, 0) + 1); + } + + PriorityQueue> maxHeap = new PriorityQueue<>( + (a, b) -> b.getValue() - a.getValue()); + + maxHeap.addAll(freqMap.entrySet()); + + StringBuilder result = new StringBuilder(); + Map.Entry prev = null; + + while (!maxHeap.isEmpty()) { + Map.Entry current = maxHeap.poll(); + result.append(current.getKey()); + + if (prev != null && prev.getValue() > 0) { + maxHeap.offer(prev); + } + + current.setValue(current.getValue() - 1); + prev = current; + } + + return result.length() == s.length() ? result.toString() : ""; + } +} +``` + +### JavaScript Solution + +```javascript +function reorganizeString(s) { + const freqMap = {}; + for (const char of s) { + freqMap[char] = (freqMap[char] || 0) + 1; + } + + const maxHeap = Object.entries(freqMap).map(([char, freq]) => [-freq, char]); + maxHeap.sort((a, b) => a[0] - b[0]); + + let result = ""; + let prev = null; + + while (maxHeap.length > 0) { + const [freq, char] = maxHeap.shift(); + result += char; + + if (prev && prev[0] < 0) { + maxHeap.push(prev); + maxHeap.sort((a, b) => a[0] - b[0]); + } + + prev = [freq + 1, char]; + } + + return result.length === s.length ? result : ""; +} +``` diff --git a/solutions/lc-solutions/0700-0799/0769-max-chunks-to-make-sorted.md b/solutions/lc-solutions/0700-0799/0769-max-chunks-to-make-sorted.md new file mode 100644 index 0000000..48b30c0 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0769-max-chunks-to-make-sorted.md @@ -0,0 +1,154 @@ +--- +id: max-chunks-to-make-sorted +title: Max Chunks To Make Sorted +sidebar_label: 0769- Max Chunks To Make Sorted +tags: + - Leet code +description: "Solution to leetocde 769" +--- + +## Problem Statement + +You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. + +We split `arr` into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. + +Return the largest number of chunks we can make to sort the array. + +### Example 1 + +**Input**: `arr = [4,3,2,1,0]` + +**Output**: `1` + +**Explanation**: +Splitting into two or more chunks will not return the required result. +For example, splitting into `[4, 3], [2, 1, 0]` will result in `[3, 4, 0, 1, 2]`, which isn't sorted. + +### Example 2 + +**Input**: `arr = [1,0,2,3,4]` + +**Output**: `4` + +**Explanation**: +We can split into two chunks, such as `[1, 0], [2, 3, 4]`. +However, splitting into `[1, 0], [2], [3], [4]` is the highest number of chunks possible. + +### Constraints + +- `n == arr.length` +- `1 <= n <= 10` +- `0 <= arr[i] < n` +- All the elements of `arr` are unique. + +### Algorithm + +- **Idea**: The idea is to iterate through the array and keep track of the maximum value encountered so far. At any index `i`, if the maximum value encountered so far is equal to `i`, it means we can form a chunk ending at index `i`. +- **Logic**: If the maximum value up to the current index is equal to the index itself, it means all elements before and including this index can be sorted independently to form part of the final sorted array. +- **Implementation**: Use a loop to iterate through the array and maintain `max_so_far`, which keeps the maximum value seen so far. Whenever `max_so_far` equals the current index `i`, increment the chunk count. + +### Code implementation + +### Python Solution + +```python +class Solution: + def maxChunksToSorted(self, arr: List[int]) -> int: + max_so_far = 0 + chunks = 0 + + for i in range(len(arr)): + max_so_far = max(max_so_far, arr[i]) + if max_so_far == i: + chunks += 1 + + return chunks + +``` + +### C++ Solution + +```cpp +#include +#include + +class Solution { +public: + int maxChunksToSorted(std::vector& arr) { + int max_so_far = 0; + int chunks = 0; + + for (int i = 0; i < arr.size(); ++i) { + max_so_far = std::max(max_so_far, arr[i]); + if (max_so_far == i) { + ++chunks; + } + } + + return chunks; + } +}; + +// Example usage: +#include + +int main() { + Solution solution; + std::vector arr1 = {4, 3, 2, 1, 0}; + std::vector arr2 = {1, 0, 2, 3, 4}; + std::cout << solution.maxChunksToSorted(arr1) << std::endl; // Output: 1 + std::cout << solution.maxChunksToSorted(arr2) << std::endl; // Output: 4 + return 0; +} +``` + +### Java Solution + +```java +class Solution { + public int maxChunksToSorted(int[] arr) { + int maxSoFar = 0; + int chunks = 0; + + for (int i = 0; i < arr.length; ++i) { + maxSoFar = Math.max(maxSoFar, arr[i]); + if (maxSoFar == i) { + ++chunks; + } + } + + return chunks; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + int[] arr1 = {4, 3, 2, 1, 0}; + int[] arr2 = {1, 0, 2, 3, 4}; + System.out.println(solution.maxChunksToSorted(arr1)); // Output: 1 + System.out.println(solution.maxChunksToSorted(arr2)); // Output: 4 + } +} +``` + +### JavaScript Solution + +```javascript +var maxChunksToSorted = function (arr) { + let maxSoFar = 0; + let chunks = 0; + + for (let i = 0; i < arr.length; ++i) { + maxSoFar = Math.max(maxSoFar, arr[i]); + if (maxSoFar === i) { + ++chunks; + } + } + + return chunks; +}; + +// Example usage: +console.log(maxChunksToSorted([4, 3, 2, 1, 0])); // Output: 1 +console.log(maxChunksToSorted([1, 0, 2, 3, 4])); // Output: 4 +``` diff --git a/solutions/lc-solutions/0700-0799/0771-jewels-and-stones.md b/solutions/lc-solutions/0700-0799/0771-jewels-and-stones.md new file mode 100644 index 0000000..4632db8 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0771-jewels-and-stones.md @@ -0,0 +1,124 @@ +--- +id: jewels-and-stones +title: Jewels and Stones +sidebar_label: 771 Jewels and Stones +tags: +- HashTable +- String +description: "This is a solution to the Jewels and Stones on leetcode" +--- + +## Problem Description + +You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels. +Letters are case sensitive, so "a" is considered a different type of stone from "A". + + +### Examples + +**Example 1:** +``` +Input: jewels = "aA", stones = "aAAbbbb" +Output: 3 +``` + +**Example 2:** +``` +Input: jewels = "z", stones = "ZZ" +Output: 0 + +``` + + + +### Constraints +- `1 <= jewels.length, stones.length <= 50` +- `jewels and stones consist of only English letters.` +- `All the characters of jewels are unique.` + + +## Solution for Koko Eating Bananas +### Intuition +The problem requires us to determine how many characters from the jewels string are present in the stones string. Each character in jewels represents a type of jewel, and each character in stones represents a stone that may contain one of these jewels. The goal is to count how many stones are jewels. + +### Approach +We use a hash-based data structure (an unordered_set in C++ or a HashSet in Java) to store characters from the jewels string. This allows for average $O(1)$ time complexity for membership checks.and we iterate to each character in stones string if that character is present in jewel we increment the count and we return count. + + +#### Complexity Analysis + + - Time Complexity: $O(J+S)$, where J is the length of jewels and S is the length of stones. + - Space Complexity: $O(J)$ , where J is no of distinct characters in jewels. + +## Code in Different Languages + + + + + + ```java + import java.util.*; + class Solution { + public int numJewelsInStones(String jewels, String stones) { + HashSet jewelSet = new HashSet<>(); + for (char jewel : jewels.toCharArray()) { + jewelSet.add(jewel); + } + + int count = 0; + for (char stone : stones.toCharArray()) { + if (jewelSet.contains(stone)) { + count++; + } + } + return count; + }} + + ``` + + + + + + ```python + class Solution: + def numJewelsInStones(self, jewels: str, stones: str) -> int: + jewels1=list(jewels) + stones1=list(stones) + c=0 + for i in stones1: + if i in jewels: + c+=1 + return c + + ``` + + + + + ```cpp + #include + #include + + class Solution { + public: + int numJewelsInStones(std::string jewels, std::string stones) { + std::unordered_set jewelSet(jewels.begin(), jewels.end()); + int count = 0; + for (char stone : stones) { + if (jewelSet.find(stone) != jewelSet.end()) { + count++; + } + } + return count; + } + }; + + ``` + + + +## References + +- **LeetCode Problem**: [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/solutions/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/jewels-and-stones/post-solution/?submissionId=1279731526) diff --git a/solutions/lc-solutions/0700-0799/0787-cheapest-flights-within-k-stops.md b/solutions/lc-solutions/0700-0799/0787-cheapest-flights-within-k-stops.md new file mode 100644 index 0000000..fa0ef35 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0787-cheapest-flights-within-k-stops.md @@ -0,0 +1,529 @@ +--- +id: cheapest-flights-within-k-stops +title: Cheapest Flights Within K Stops +sidebar_label: 0787 - Cheapest-Flights-Within-K-Stops +tags: + - Dfs + - Bfs + - JavaScript + - TypeScript + - c++ +description: "This is a solution to the Cheapest Flights Within K Stops problem on LeetCode." +--- + +In this page, we will solve the Cheapest Flights Within K Stops problem using two different approaches: Breadth First Search and Depth First Search technique. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei. + +You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1. + +### Examples + +**Example 1:** + +```plaintext +Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 +Output: 700 +``` + +**Example 2:** + +```plaintext +Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 +Output: 200 +``` + + +### Constraints + +- `1 <= n <= 100` +- `0 <= flights.length <= (n * (n - 1) / 2)` +- `flights[i].length == 3` +- `0 <= fromi, toi < n` +- `fromi != toi` +- `1 <= pricei <= 104` +- `0 <= src, dst, k < n` +- `src != dst` +- There will not be any multiple flights between two cities. + + + +--- + +## Solution for Cheapest Flights Within K Stops Problem + +### Intuition and Approach + +To solve the problem of finding the minimum cost to reach a destination from a source with a restriction on the number of stops, we can use Dijkstra’s Algorithm with a key modification. Instead of prioritizing minimum distance, we prioritize the minimum number of stops in the priority queue. This ensures that we explore paths with fewer stops, which helps us avoid premature termination of the algorithm due to exceeding the stop limit. + +However, since the number of stops increases monotonically (by 1 each iteration), we don't actually need a priority queue. A simple queue is sufficient because we always pop the element with the lesser number of stops first, thus eliminating the extra log(N) complexity associated with insertion and deletion in a priority queue. This change improves the algorithm's efficiency. + + + + +### Approach 1: Breadth First Search + +To solve the problem, create an adjacency list and initialize a queue to store pairs. Set up a distance array with large values to mark unvisited nodes and set the source node's distance to 0. Push the source node into the queue with distance 0 and 0 stops. Process the queue by popping elements, and for each adjacent node, update the distance and push it back into the queue if the current distance is less and the stop count is below K. Continue until the queue is empty. If the destination is reached within the required stops, return the distance; otherwise, return -1 if no valid path exists. + +#### Codes in Different Languages + + + + + ```javascript + var findCheapestPrice = function(n, flights, src, dst, K) { + let graph = {} // {from: { to: price }, {to: price}} + + for (let [source, destination, price] of flights){ + if (!graph.hasOwnProperty(source)) { + graph[source] = {} + } + graph[source][destination] = price + } + + let queue = [[0,src,0]] + + while (queue.length ) { + let [price, city, connections] = queue.shift() + if (city == dst) return price + if (connections > K) continue + + if (graph[city]) { + for (let nextStops in graph[city]) { + let cost = graph[city][nextStops] + queue.push([cost + price, nextStops, connections + 1]) + } + } + queue.sort((a,b) => a[0]-b[0]) + + } + return -1 + } + ``` + + + + + ```typescript + function findCheapestPrice(n: number, flights: number[][], src: number, dst: number, k: number): number { + const adj = new Map(); + const visited = new Array(n).fill(Number.MAX_VALUE); + visited[src] = 0; + + for (const [from, to, price] of flights) { + if (!adj.has(from)) { + adj.set(from, []); + } + adj.get(from).push([to, price]); + } + + const queue = [[src, 0]]; + k++; + + while (k-- > 0 && queue.length > 0) { + const size = queue.length; + for (let i = 0; i < size; i++) { + const [currNode, currPrice] = queue.shift(); + if (adj.has(currNode)) { + for (const [nextNode, nextPrice] of adj.get(currNode)) { + const newPrice = currPrice + nextPrice; + if (newPrice < visited[nextNode]) { + visited[nextNode] = newPrice; + queue.push([nextNode, newPrice]); + } + } + } + } + } + + return visited[dst] === Number.MAX_VALUE ? -1 : visited[dst]; + }; + ``` + + + + + ```python + class Solution: + def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: + graph = [[] for _ in range(n)] + minHeap = [(0, src, k + 1)] # (d, u, stops) + dist = [[math.inf] * (k + 2) for _ in range(n)] + + for u, v, w in flights: + graph[u].append((v, w)) + + while minHeap: + d, u, stops = heapq.heappop(minHeap) + if u == dst: + return d + if stops > 0: + for v, w in graph[u]: + newDist = d + w + if newDist < dist[v][stops - 1]: + dist[v][stops - 1] = newDist + heapq.heappush(minHeap, (newDist, v, stops - 1)) + + return -1 + + ``` + + + + + ```java + class Solution { + public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { + List>[] graph = new List[n]; + // (d, u, stops) + Queue minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); + int[][] dist = new int[n][k + 2]; + Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); + + for (int i = 0; i < n; ++i) + graph[i] = new ArrayList<>(); + + for (int[] f : flights) { + final int u = f[0]; + final int v = f[1]; + final int w = f[2]; + graph[u].add(new Pair<>(v, w)); + } + + minHeap.offer(new int[] {0, src, k + 1}); // Start with node src with d == 0 + dist[src][k + 1] = 0; + + while (!minHeap.isEmpty()) { + final int d = minHeap.peek()[0]; + final int u = minHeap.peek()[1]; + final int stops = minHeap.poll()[2]; + if (u == dst) + return d; + if (stops > 0) + for (Pair pair : graph[u]) { + final int v = pair.getKey(); + final int w = pair.getValue(); + final int newDist = d + w; + if (newDist < dist[v][stops - 1]) { + dist[v][stops - 1] = newDist; + minHeap.offer(new int[] {d + w, v, stops - 1}); + } + } + } + + return -1; + } + } + ``` + + + + + ```cpp + class Solution { + public: + int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) { + + //{to,price} + vector> adj[n]; + + for(auto x : flights){ + + int from = x[0]; + int to = x[1]; + int price = x[2]; + + adj[from].push_back({to,price}); + } + + vector dist(n,1e9); + dist[src] = 0; + + // {stops,{node,dist}} + queue>> q; + q.push({0,{src,0}}); + + while(!q.empty()){ + + auto it = q.front(); + q.pop(); + + int stops = it.first; + int node = it.second.first; + int cost = it.second.second; + + if(stops>k) continue; + + for(auto itr : adj[node]){ + int adjNode = itr.first; + int edgw = itr.second; + + if(cost+edgw < dist[adjNode] && stops<=k){ + dist[adjNode] = cost + edgw; + q.push({stops+1,{adjNode,cost+edgw}}); + } + } + + } + + if(dist[dst]==1e9) return -1; + return dist[dst]; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(N)$$ +- Space Complexity: $$O(|E|+|V|)$$ +- Where `N` is the Number of flights / Number of edges.. +- Where `E` = Number of edges (flights.size()) and `V` = Number of Airports. + + + + + + +### Approach 2: Depth First Search + +The cheapest flight price from a source city to a destination city with a maximum number of allowed stops using Depth-First Search (DFS) and memoization. The dfs function recursively explores all possible flight paths, returning 0 when the destination is reached and a large constant inf for invalid paths with negative stops. A memoization table dp stores intermediate results to avoid redundant calculations. + +In the findCheapestPrice function, dp is initialized to -1, and the flight data is processed to build an adjacency list adj and a cost matrix cost. The dfs function is then called with k + 1 stops, as the problem allows up to k stops plus the destination. The function returns the minimum cost found or -1 if the destination is unreachable within the allowed stops, ensuring an efficient exploration of all valid routes. + + + +#### Code in Different Languages + + + + + ```javascript + var findCheapestPrice = function (n, flights, src, dst, k) { + let map = {} + + for (let [x, y, z] of flights) { + if (!map[y]) map[y] = [] + map[y].push([x, y, z]) + } + + let min = Infinity; + + let iterate = (end, sum, count) => { + if (count > k || sum > min) return; + + if (end == src) { + min = Math.min(min, sum) + return; + } + if (!map[end]) return; + + for (let [x, y, z] of map[end]) { + iterate(x, sum + z, count + 1) + } + } + iterate(dst, 0, -1) + return min == Infinity ? -1 : min; + }; + ``` + + + + + ```typescript + class Solution { + private readonly inf: number = 1e8; + private dp: number[][]; + + constructor() { + this.dp = Array.from({ length: 101 }, () => Array(101).fill(-1)); + } + + private dfs(node: number, k: number, dest: number, cost: number[][], adj: number[][]): number { + if (k < 0) { + return this.inf; + } + + if (node === dest) { + return 0; + } + + if (this.dp[node][k] !== -1) { + return this.dp[node][k]; + } + + let ans: number = this.inf; + for (let i of adj[node]) { + ans = Math.min(ans, cost[node][i] + this.dfs(i, k - 1, dest, cost, adj)); + } + + return this.dp[node][k] = ans; + } + + public findCheapestPrice(n: number, flights: number[][], src: number, dst: number, k: number): number { + // Reset dp array + this.dp = Array.from({ length: 101 }, () => Array(101).fill(-1)); + + let cost: number[][] = Array.from({ length: n }, () => Array(n).fill(0)); + let adj: number[][] = Array.from({ length: n }, () => []); + + for (let e of flights) { + adj[e[0]].push(e[1]); + cost[e[0]][e[1]] = e[2]; + } + + let ans: number = this.dfs(src, k + 1, dst, cost, adj); + return ans === this.inf ? -1 : ans; + } + } + + ``` + + + + + ```python + class Solution: + def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: + adjlist = [[] for _ in range(n)] + + + for source, dest, weight in flights: + adjlist[dest].append((source, weight)) + # print(adjlist) + dptable = [[float("inf")]*(n) for _ in range(k+2)] + dptable[0][src] = 0 + + for row in range(1, k+2): + for col in range(n): + dptable[row][col] = dptable[row-1][col] + + for pred, wt in adjlist[col]: + dptable[row][col] = min(dptable[row][col], dptable[row-1][pred]+wt) + + + for row in dptable: + print(row) + return dptable[k+1][dst] if dptable[k+1][dst] != inf else -1 + + ``` + + + + + ```java + import java.util.Vector; + class Solution { + int dp[][] = new int[101][101]; + int solve(int src, int dst, int k, Map>> mp){ + if(src == dst){ + if(k >= 0) + return 0; + + return (int)1e8; + } + + if(k <= 0) + return (int)1e8; + + if(dp[src][k] != -1) return dp[src][k]; + + int a = (int)1e8; + if(mp.containsKey(src)){ + for (Pair x : mp.get(src)) { + a = Math.min(a, solve(x.getValue(), dst, k - 1, mp) + x.getKey()); + } + } + return dp[src][k] = a; + } + public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { + Map>> mp = new HashMap<>(); + for(int[] x: flights){ + Vector> vec = new Vector<>(); + if(mp.containsKey(x[0])){ + vec = mp.get(x[0]); + vec.add(new Pair<>(x[2], x[1])); + mp.put(x[0], vec); + } + else{ + vec.add(new Pair<>(x[2], x[1])); + mp.put(x[0], vec); + } + } + + for(int i=0; i<101; i++){ + Arrays.fill(dp[i], -1); + } + + int ans = solve(src, dst, k+1, mp); + return ans >= 1e8 ? -1 : ans; + } + } + ``` + + + + + ```cpp + class Solution { + const int inf = 1e8; + int dp[101][101]; + + public: + int dfs(int node, int k, int dest, vector> &cost, vector adj[]) + { + if (k < 0) + return inf; + + if (node == dest) + return 0; + + if (dp[node][k] != -1) + return dp[node][k]; + + int ans = inf; + for (auto i : adj[node]) + ans = min(ans, cost[node][i] + dfs(i, k - 1, dest, cost, adj)); + + return dp[node][k] = ans; + } + int findCheapestPrice(int n, vector> &flights, int src, int dst, int k) + { + memset(dp, -1, sizeof dp); + + vector> cost(n, vector(n)); + vector adj[n]; + for (auto e : flights) + { + adj[e[0]].push_back(e[1]); + cost[e[0]][e[1]] = e[2]; + } + + int ans = dfs(src, k + 1, dst, cost, adj); + return ans == inf ? -1 : ans; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(|E|+|V|)$$ +- Space Complexity: $$O(|E|+|V|)$$ +- Where `E` = Number of edges (flights.size()) and `V` = Number of Airports. + + + + + + +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/cheapest-flights-within-k-stops/description/) +- **Solution Link:** [Cheapest Flights Within K Stops Solution on LeetCode](https://leetcode.com/problems/cheapest-flights-within-k-stops/solutions/115541/java-c-python-priority-queue-solution-tle-now/) diff --git a/solutions/lc-solutions/0700-0799/0791-custom-sort-string.md b/solutions/lc-solutions/0700-0799/0791-custom-sort-string.md new file mode 100644 index 0000000..9c89ea9 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0791-custom-sort-string.md @@ -0,0 +1,322 @@ +--- +id: custom-sort-string +title: Custom Sort String +sidebar_label: 0791 - Custom Sort String +tags: + - String + - Hash Table + - Sorting +description: "This is a solution to the Custom Sort String problem on LeetCode." +--- + +## Problem Description + +You are given two strings `order` and `s`. All the characters of `order` are **unique** and were sorted in some custom order previously. + +Permute the characters of `s` so that they match the order that `order` was sorted. More specifically, if a character `x` occurs before a character `y` in order, then `x` should occur before `y` in the permuted string. + +Return any permutation of `s` that satisfies this property. + +### Examples + +**Example 1:** + +``` +Input: order = "cba", s = "abcd" +Output: "cbad" +Explanation: "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a". +Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs. +``` + +**Example 1:** + +``` +Input: order = "bcafg", s = "abcd" +Output: "bcad" +Explanation: The characters "b", "c", and "a" from order dictate the order for the characters in s. The character "d" in s does not appear in order, so its position is flexible. +Following the order of appearance in order, "b", "c", and "a" from s should be arranged as "b", "c", "a". "d" can be placed at any position since it's not in order. The output "bcad" correctly follows this rule. Other arrangements like "bacd" or "bcda" would also be valid, as long as "b", "c", "a" maintain their order. +``` + +### Constraints + +- `1 <= order.length <= 26` +- `1 <= s.length <= 200` +- order and `s` consist of lowercase English letters. +- All the characters of order are **unique**. + +## Solution for Custom Sort String + +## Approach 1: Custom Comparator +### Intuition + +A comparator is a tool used to define (or redefine) an order between two items of the same class or data type. Most languages allow for the use of a custom comparator. This means that we can define a rule that determines how an array is sorted, and leverage built-in sort functions for custom sort. + +Recall that a comparator takes two values `c1` and `c2` as parameters and returns the following: + +1. If c1 comes before c2, return a negative integer. +2. If c1 comes after c2, return a positive integer. +3. If c1 and c2 are equal, return 000. +Letter `c1` should come before `c2` in the sorted order of `s` if and only if the index of `c1` in the order string is less than the index of `c2`. By evaluating `c1` and `c2` as integer indices, we can use subtraction to achieve a return value that abides by the three rules described above. + +Let's consider the following example: let `s = "bdadeec"` and `order = "edcba"`. Letter "e" is at index 0 in `order`, whereas letter "b" is at index 3. Because $0 < 3$, "e" should come before "b" in the result string. Therefore, the return result is $0 - 3 = -3$, a negative number that adheres to the first rule listed above. + +Taking into account all possible relationships between pairs of letters, the result string is "eeddcba". + +### Algorithm +1. Create a character array of input string `s` to allow modification. +2. Use the built-in sort method and define the comparator function as the difference between the index of `c1` and the index of `c2` in order. +3. Concatenate the character array into a string. +4. Return this resulting string. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + string customSortString(string order, string s) { + // Define the custom comparator as lambda + sort(s.begin(), s.end(), [order](char c1, char c2) { + return order.find(c1) < order.find(c2); + }); + return s; + } +}; +``` + + + + +```java +class Solution { + public String customSortString(String order, String s) { + // Create char array for editing + int N = s.length(); + Character[] result = new Character[N]; + for (int i = 0; i < N; i++) { + result[i] = s.charAt(i); + } + + // Define the custom comparator + Arrays.sort(result, (c1, c2) -> { + // The index of the character in order determines the value to be sorted by + return order.indexOf(c1) - order.indexOf(c2); + }); + + // Return the result + String resultString = ""; + for (Character c: result) { + resultString += c; + } + return resultString; + } +} +``` + + + + + +```python +from collections import Counter + +class Solution: + def customSortString(self, order: str, s: str) -> str: + # Create a counter for the characters in s + char_count = Counter(s) + + # Initialize the result string + result = "" + + # Add the characters in the order string to the result + for char in order: + if char in char_count: + result += char * char_count[char] + del char_count[char] + + # Add the remaining characters to the result + for char, count in char_count.items(): + result += char * count + + return result + +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(NlogN)$ + +> **Reason**: Sorting an array of length N requires $O(Nlog⁑N)$ time, and the indices of `order` have to be retrieved for each distinct letter, which results in an $O(Nlog⁑N+K)$ complexity. K is at most 26, the number of unique English letters, so we can simplify the time complexity to $O(Nlog⁑N)$. + +#### Space Complexity: $O(N)$ + +> **Reason**: +>The space complexity of the sorting algorithm depends on the programming language. +> - In Java, Arrays.sort() is implemented using a variant of the Quick Sort algorithm, which has a space complexity of $O(log⁑N)$ for sorting two arrays. The Java solution also uses an auxiliary array of length N. This is the dominating term for the Java solution. +> - In C++, the sort() function is implemented as a hybrid of Quick Sort, Heap Sort, and Insertion Sort, with a worse-case space complexity of $O(log⁑⁑N)$. This is the main space used by the C++ solution. + + +## Approach 2: Frequency Table and Counting +### Intuition + +Because the `order` string already gives us the explicit ordering to sort all the letters, we can generate a sorted version of `s` without calling upon an $O(Nlog⁑N)$ algorithm. Let's create a frequency table where the key equals a character `c`, and the value equals how many times `c` appears in the string `s`. Then, for each character in order, append the number of occurrences of that character in `s` to the resulting string. After iterating through `order`, any remaining characters in `s` can be appended to the end without disrupting the defined sorting order. + +### Algorithm +1. Initialize a frequency table (here we use a Hashmap, but a frequency array works too). +2. Populate the frequency table by incrementing `freq[letter]` for each letter in `s`. +3. For each character of `order`, append to `result` the same frequency it appears in `s`. +4. Iterate through the frequency table to find any remaining letters of `s` not in order, and append these letters to `result`. +5. Return the resulting string. + +### Code in Different Languages + + + + + +```cpp +class Solution { + public: + string customSortString(string order, string s) { + // Create a frequency table + unordered_map freq; + + // Initialize frequencies of letters + // freq[c] = frequency of char c in s + for (char letter : s) { + freq[letter]++; + } + + // Iterate order string to append to result + string result = ""; + for (char letter : order) { + while (freq[letter]-- > 0) { + result += letter; + } + } + + // Iterate through freq and append remaining letters + // This is necessary because some letters may not appear in `order` + for (auto & [letter, count] : freq) { + while (count-- > 0) { + result += letter; + } + } + + // Return the result + return result; + } +}; +``` + + + + +```java +class Solution { + public String customSortString(String order, String s) { + // Create a frequency table + Map freq = new HashMap<>(); + + // Initialize frequencies of letters + // freq[c] = frequency of char c in s + int N = s.length(); + for (int i = 0; i < N; i++) { + char letter = s.charAt(i); + freq.put(letter, freq.getOrDefault(letter, 0) + 1); + } + + // Iterate order string to append to result + int K = order.length(); + StringBuilder result = new StringBuilder(); + for (int i = 0; i < K; i++) { + char letter = order.charAt(i); + while (freq.getOrDefault(letter, 0) > 0) { + result.append(letter); + freq.put(letter, freq.get(letter) - 1); + } + } + + // Iterate through freq and append remaining letters + // This is necessary because some letters may not appear in `order` + for (char letter : freq.keySet()) { + int count = freq.get(letter); + while (count > 0) { + result.append(letter); + count--; + } + } + + // Return the result + return result.toString(); + } +} +``` + + + + + +```python +from collections import Counter + +class Solution: + def customSortString(self, order: str, s: str) -> str: + # Create a frequency table + freq = Counter(s) + + # Iterate order string to append to result + result = [] + for letter in order: + result.extend([letter] * freq.pop(letter, 0)) + + # Iterate through freq and append remaining letters + result.extend([letter * count for letter, count in freq.items()]) + + # Return the result + return ''.join(result) + +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(N)$ + +> **Reason**: It takes $O(N)$ time to populate the frequency table, and all other hashmap operations performed take $O(1)$ time in the average case. Building the result string also takes $O(N)$ time because each letter from `s` is appended to the result in the custom order, making the overall time complexity $O(N)$. + +#### Space Complexity: $O(N)$ + +> **Reason**: A hash map and a `result` string are created, which results in an additional space complexity of $O(N)$. + + +## Video Solution + + + +## References + +- **LeetCode Problem**: [Custom Sort String](https://leetcode.com/problems/custom-sort-string/description/) + +- **Solution Link**: [Custom Sort String](https://leetcode.com/problems/custom-sort-string/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/0796-rotate-string.md b/solutions/lc-solutions/0700-0799/0796-rotate-string.md new file mode 100644 index 0000000..d17b142 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/0796-rotate-string.md @@ -0,0 +1,324 @@ +--- +id: rotate-string +title: Rotate String +sidebar_label: 0796 - Rotate String +tags: + - String + - String Matching + - Queue +description: "This is a solution to the Rotate String problem on LeetCode." +--- + +## Problem Description + +Given two strings `s` and goal, return `true` if and only if `s` can become `goal` after some number of **shifts** on `s`. + +A **shift** on `s` consists of moving the leftmost character of `s` to the rightmost position. + +For example, if `s = "abcde"`, then it will be `"bcdea"` after one shift. + +### Examples + +**Example 1:** + +``` +Input: s = "abcde", goal = "cdeab" +Output: true +``` + +**Example 2:** + +``` +Input: s = "abcde", goal = "abced" +Output: false +``` + +### Constraints + +- `1 <= s.length, goal.length <= 100` +- `s` and `goal` consist of lowercase English letters. + +## Solution for Rotate String + +## Approach 1: Brute Force +### Intuition + +For each rotation of `A`, let's check if it equals `B`. + +### Algorithm + +More specifically, say we rotate `A` by `s`. Then, instead of `A[0], A[1], A[2], ...`, we have `A[s], A[s+1], A[s+2], ...`; and we should check that `A[s] == B[0]`, `A[s+1] == B[1]`, `A[s+2] == B[2]`, etc. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + bool rotateString(string A, string B) { + if (A.length() != B.length()) + return false; + if (A.length() == 0) + return true; + + for (int s = 0; s < A.length(); ++s) { + bool match = true; + for (int i = 0; i < A.length(); ++i) { + if (A[(s+i) % A.length()] != B[i]) { + match = false; + break; + } + } + if (match) + return true; + } + return false; + } +}; + + +``` + + + + +```java +class Solution { + public boolean rotateString(String A, String B) { + if (A.length() != B.length()) + return false; + if (A.length() == 0) + return true; + + search: + for (int s = 0; s < A.length(); ++s) { + for (int i = 0; i < A.length(); ++i) { + if (A.charAt((s+i) % A.length()) != B.charAt(i)) + continue search; + } + return true; + } + return false; + } +} +``` + + + + + +```python +class Solution(object): + def rotateString(self, A, B): + if len(A) != len(B): + return False + if len(A) == 0: + return True + + for s in xrange(len(A)): + if all(A[(s+i) % len(A)] == B[i] for i in xrange(len(A))): + return True + return False +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(N^2)$ + +> **Reason**: where `N` is the length of `A`. For each rotation `s`, we check up to `N` elements in `A` and `B`. + +#### Space Complexity: $O(1)$ + +> **Reason**: We only use pointers to elements of `A` and `B`. + +## Approach 2: Simple Check +### Intuition and Algorithm + +All rotations of `A` are contained in `A+A`. Thus, we can simply check whether `B` is a substring of `A+A`. We also need to check `A.length == B.length`, otherwise we will fail cases like `A = "a", B = "aa"`. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + bool rotateString(string A, string B) { + return A.length() == B.length() && (A + A).find(B) != string::npos; + } +}; + +``` + + + + +```java +class Solution { + public boolean rotateString(String A, String B) { + return A.length() == B.length() && (A + A).contains(B); + } +} +``` + + + + + +```python +class Solution(object): + def rotateString(self, A, B): + return len(A) == len(B) and B in A+A +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(N^2)$ + +> **Reason**: where `N` is the length of `A`. + + +#### Space Complexity: $O(N)$ + +> **Reason**: the space used building `A+A`. + +## Approach 3: Rolling Hash +### Intuition + +Our approach comes down to quickly checking whether want to check whether `B` is a substring of `A2 = A+A`. Specifically, (if `N = A.length`) we should check whether `B = A2[0:N]`, or `B = A2[1:N+1]`, or `B = A2[2:N+2]` and so on. To check this, we can use a rolling hash. + +### Algorithm + +For a string `S`, say `hash(S) = (S[0] * P**0 + S[1] * P**1 + S[2] * P**2 + ...) % MOD`, where `X**Y` represents exponentiation, and `S[i]` is the ASCII character code of the string at that index. + +The idea is that `hash(S)` has output that is approximately uniformly distributed between `[0, 1, 2, ..., MOD-1]`, and so if `hash(S) == hash(T)` it is very likely that `S == T`. + +Now say we have a hash `hash(A)`, and we want the hash of `A[1], A[2], ..., A[N-1], A[0]`. We can subtract `A[0]` from the hash, divide by `P`, and add `A[0] * P**(N-1)`. (Our division is under the finite field $\mathbb{F}_\text{MOD}$- done by multiplying by the modular inverse `Pinv = pow(P, MOD-2, MOD)`.) +### Code in Different Languages + + + + + +```java +import java.math.BigInteger; +class Solution { + public boolean rotateString(String A, String B) { + if (A.equals(B)) return true; + + int MOD = 1_000_000_007; + int P = 113; + int Pinv = BigInteger.valueOf(P).modInverse(BigInteger.valueOf(MOD)).intValue(); + + long hb = 0, power = 1; + for (char x: B.toCharArray()) { + hb = (hb + power * x) % MOD; + power = power * P % MOD; + } + + long ha = 0; power = 1; + char[] ca = A.toCharArray(); + for (char x: ca) { + ha = (ha + power * x) % MOD; + power = power * P % MOD; + } + + for (int i = 0; i < ca.length; ++i) { + char x = ca[i]; + ha += power * x - x; + ha %= MOD; + ha *= Pinv; + ha %= MOD; + if (ha == hb && (A.substring(i+1) + A.substring(0, i+1)).equals(B)) + return true; + + } + return false; + } +} +``` + + + + + +```python +class Solution(object): + def rotateString(self, A, B): + MOD = 10**9 + 7 + P = 113 + Pinv = pow(P, MOD-2, MOD) + + hb = 0 + power = 1 + for x in B: + code = ord(x) - 96 + hb = (hb + power * code) % MOD + power = power * P % MOD + + ha = 0 + power = 1 + for x in A: + code = ord(x) - 96 + ha = (ha + power * code) % MOD + power = power * P % MOD + + if ha == hb and A == B: return True + for i, x in enumerate(A): + code = ord(x) - 96 + ha += power * code + ha -= code + ha *= Pinv + ha %= MOD + if ha == hb and A[i+1:] + A[:i+1] == B: + return True + return False +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(N)$ + +> **Reason**: where `N` is the length of `A`. + + +#### Space Complexity: $O(N)$ + +> **Reason**: to perform the final check `A_rotation == B`. + + +## Video Solution + + + +## References + +- **LeetCode Problem**: [Rotate String](https://leetcode.com/problems/rotate-string/description/) + +- **Solution Link**: [Rotate String](https://leetcode.com/problems/rotate-string/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0700-0799/785-is-graph-bipartite.md b/solutions/lc-solutions/0700-0799/785-is-graph-bipartite.md new file mode 100644 index 0000000..9d1bfac --- /dev/null +++ b/solutions/lc-solutions/0700-0799/785-is-graph-bipartite.md @@ -0,0 +1,217 @@ +--- +id: is-graph-bipartite +title: 785. Is Graph Bipartite? +sidebar_label: 785. Is Graph Bipartite? +tags: +- Graph +- BFS +- DFS + + +description: "This is a solution to the 785. Is Graph Bipartite? problem on LeetCode." +--- + +## Problem Description +There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties: + +There are no self-edges (graph[u] does not contain u). +There are no parallel edges (graph[u] does not contain duplicate values). +If v is in graph[u], then u is in graph[v] (the graph is undirected). +The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them. +A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B. + +Return true if and only if it is bipartite. + ### Examples +**Example 1:** +``` +Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]] +Output: false +Explanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other. +``` + +### Constraints +- `graph.length == n` +- `1 <= n <= 100` +- `0 <= graph[u].length < n` +- `0 <= graph[u][i] <= n - 1` +- `graph[u] does not contain u.` +- `All the values of graph[u] are unique.` +- `If graph[u] contains v, then graph[v] contains u.` + +## Solution for 785. Is Graph Bipartite? + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function dfs(graph, node, colors, color) { + colors[node] = color; + for (const neighbor of graph[node]) { + if (colors[neighbor] === color) { + return false; + } + if (!colors[neighbor]) { + if (!dfs(graph, neighbor, colors, -color)) { + return false; + } + } + } + return true; + } + + isBipartite = function(graph) { + const n = graph.length; + const colors = new Array(n).fill(0); + for (let i = 0; i < n; i++) { + if (!colors[i]) { + if (!dfs(graph, i, colors, 1)) { + return false; + } + } + } + return true; + } + const input =[[1,2,3],[0,2],[0,1,3],[0,2]] + const output = isBipartite(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n) $ + - Space Complexity: $ O(n)$ + + ## Code in Different Languages + + + + ```python + from typing import List +from collections import deque + +class Solution: + def isBipartite(self, gr: List[List[int]]) -> bool: + n = len(gr) + colour = [0] * n + + for node in range(n): + if colour[node] != 0: + continue + + q = deque() + q.append(node) + colour[node] = 1 + + while q: + cur = q.popleft() + + for ne in gr[cur]: + if colour[ne] == 0: + colour[ne] = -colour[cur] + q.append(ne) + elif colour[ne] != -colour[cur]: + return False + + return True + ``` + + + + + ```java + import java.util.ArrayDeque; +import java.util.Queue; + +class Solution { + public boolean isBipartite(int[][] gr) { + int n = gr.length; + int[] colour = new int[n]; + + for (int node = 0; node < n; node++) { + if (colour[node] != 0) { + continue; + } + + Queue q = new ArrayDeque<>(); + q.add(node); + colour[node] = 1; + + while (!q.isEmpty()) { + int cur = q.poll(); + + for (int ne : gr[cur]) { + if (colour[ne] == 0) { + colour[ne] = -colour[cur]; + q.add(ne); + } else if (colour[ne] != -colour[cur]) { + return false; + } + } + } + } + + return true; + } +} + ``` + + + + + + ```cpp + class Solution { + public: + bool check(int start,vector>& adj,vector& color){ + queueq; + color[start]=0; + q.push(start); + while(!q.empty()){ + int prev=q.front(); + q.pop(); + for(auto curr: adj[prev]){ + if(color[curr]==-1){ + color[curr]=!color[prev]; + q.push(curr); + } + else if(color[curr]==color[prev]) return false; + } + } + return true; + } + + bool isBipartite(vector>& adj) { + int n=adj.size(); + vector color(n,-1); + for(int i=0;i + + +
+
+ +## References + +- **LeetCode Problem**: [785. Is Graph Bipartite?](https://leetcode.com/problems/is-graph-bipartite/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/is-graph-bipartite/) + diff --git a/solutions/lc-solutions/0700-0799/786-k-th-smallest-prime-fraction.md b/solutions/lc-solutions/0700-0799/786-k-th-smallest-prime-fraction.md new file mode 100644 index 0000000..c115f92 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/786-k-th-smallest-prime-fraction.md @@ -0,0 +1,219 @@ +--- +id: k-th-smallest-prime-fraction +title: 786. K-th Smallest Prime Fraction +sidebar_label: 786. K-th Smallest Prime Fraction +tags: +- String + +description: "This is a solution to the 786. K-th Smallest Prime Fraction problem on LeetCode." +--- + +## Problem Description +You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k. +For every i and j where `0 <= i < j < arr.length`, we consider the fraction `arr[i] / arr[j].` +Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j]. + + + ### Examples +**Example 1:** +``` +Input: arr = [1,2,3,5], k = 3 +Output: [2,5] +Explanation: The fractions to be considered in sorted order are: +1/5, 1/3, 2/5, 1/2, 3/5, and 2/3. +The third fraction is 2/5. +``` + +### Constraints +- `2 <= arr.length <= 1000` +- `1 <= arr[i] <= 3 * 10^4` +- `arr[0] == 1` +- `arr[i] is a prime number for i > 0.` +- `All the numbers of arr are unique and sorted in strictly increasing order.` +- `1 <= k <= arr.length * (arr.length - 1) / 2` + +## Solution for 786. K-th Smallest Prime Fraction + + + + + #### Implementation + ```jsx live + function Solution(arr) { + var kthSmallestPrimeFraction = function(arr, k) { + let left = 0, right = 1; + let res = []; + + while (left <= right) { + let mid = left + (right - left) / 2; + let j = 1, total = 0, num = 0, den = 0; + let maxFrac = 0; + + for (let i = 0; i < arr.length; ++i) { + while (j < arr.length && arr[i] >= arr[j] * mid) { + ++j; + } + + total += arr.length - j; + + if (j < arr.length && maxFrac < arr[i] * 1.0 / arr[j]) { + maxFrac = arr[i] * 1.0 / arr[j]; + num = i; + den = j; + } + } + + if (total === k) { + res = [arr[num], arr[den]]; + break; + } + + if (total > k) { + right = mid; + } else { + left = mid; + } + } + + return res; +}; + const input =arr = [1,2,3,5], k = 3 + const output = kthSmallestPrimeFraction(input ,k) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n^2) $ + - Space Complexity: $ O(n^2)$ + + ## Code in Different Languages + + + + ```python + class Solution: + def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]: + n = len(arr) + left, right = 0, 1 + res = [] + + while left <= right: + mid = left + (right - left) / 2 + j, total, num, den = 1, 0, 0, 0 + maxFrac = 0 + for i in range(n): + while j < n and arr[i] >= arr[j] * mid: + j += 1 + + total += n - j + + if j < n and maxFrac < arr[i] * 1.0 / arr[j]: + maxFrac = arr[i] * 1.0 / arr[j] + num, den = i, j + + if total == k: + res = [arr[num], arr[den]] + break + + if total > k: + right = mid + else: + left = mid + + return res + ``` + + + + + ```java +class Solution { + public int[] kthSmallestPrimeFraction(int[] arr, int k) { + int n = arr.length; + double left = 0, right = 1, mid; + int[] res = new int[2]; + + while (left <= right) { + mid = left + (right - left) / 2; + int j = 1, total = 0, num = 0, den = 0; + double maxFrac = 0; + for (int i = 0; i < n; ++i) { + while (j < n && arr[i] >= arr[j] * mid) { + ++j; + } + + total += n - j; + + if (j < n && maxFrac < arr[i] * 1.0 / arr[j]) { + maxFrac = arr[i] * 1.0 / arr[j]; + num = i; + den = j; + } + } + + if (total == k) { + res[0] = arr[num]; + res[1] = arr[den]; + break; + } + + if (total > k) { + right = mid; + } else { + left = mid; + } + } + + return res; + } +} + ``` + + + + + + ```cpp + class Solution { +public: + vector kthSmallestPrimeFraction(vector& arr, int k) { + priority_queue>, vector>>, greater>>> pq; + for(int i = 0; i < arr.size(); i++) { + for(int j = i + 1; j < arr.size(); j++) { + pq.push(make_pair(double(arr[i])/arr[j], make_pair(arr[i], arr[j]))); + } + } + + while(k-- > 1) { + pq.pop(); + } + + return {pq.top().second.first, pq.top().second.second}; + } +}; + +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [786. K-th Smallest Prime Fraction](https://leetcode.com/problems/k-th-smallest-prime-fraction/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/k-th-smallest-prime-fraction/) + diff --git a/solutions/lc-solutions/0700-0799/790-Domino and Tromino Tiling.md b/solutions/lc-solutions/0700-0799/790-Domino and Tromino Tiling.md new file mode 100644 index 0000000..0b40971 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/790-Domino and Tromino Tiling.md @@ -0,0 +1,99 @@ +--- +id: domino-and-tromino-tiling +title: Domino and Tromino Tiling +sidebar_label: Domino and Tromino Tiling +tags: [Dynamic Programming, Combinatorics, Math, C++, Python, Java] +description: Solve the problem of finding the number of ways to tile a 2 x n board using 2 x 1 dominos and tromino shapes. +--- + +## Problem Statement + +### Problem Description + +You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes. + +Given an integer `n`, return the number of ways to tile a 2 x `n` board. Since the answer may be very large, return it modulo $10^9 + 7$. + +In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile. + +### Examples + +**Example 1:** +``` +Input: n = 3 +Output: 5 +``` +**Explanation:** The five different ways are shown above. + + +### Constraints + +- $1 \leq n \leq 1000$ + +## Solution + +### Intuition + +To solve this problem, we can use dynamic programming. Let's define `dp[i]` as the number of ways to tile a 2 x `i` board. The recurrence relation can be derived based on the ways we can place the last tile(s) on the board. + +### Time Complexity and Space Complexity Analysis + +- **Time Complexity**: The solution involves a single loop through the board length `n`, making the time complexity $O(n)$. +- **Space Complexity**: The space complexity is $O(n)$ to store the dynamic programming array. + +### Code + +#### C++ + +```cpp +class Solution { +public: + int numTilings(int n) { + if (n == 1) return 1; + if (n == 2) return 2; + const int MOD = 1e9 + 7; + vector dp(n + 1); + dp[0] = 1; + dp[1] = 1; + dp[2] = 2; + for (int i = 3; i <= n; ++i) { + dp[i] = (dp[i - 1] + dp[i - 2] + 2 * dp[i - 3]) % MOD; + } + return dp[n]; + } +}; +``` +#### Java + +```java +class Solution { + public int numTilings(int n) { + if (n == 1) return 1; + if (n == 2) return 2; + int MOD = 1000000007; + long[] dp = new long[n + 1]; + dp[0] = 1; + dp[1] = 1; + dp[2] = 2; + for (int i = 3; i <= n; ++i) { + dp[i] = (dp[i - 1] + dp[i - 2] + 2 * dp[i - 3]) % MOD; + } + return (int) dp[n]; + } +} +``` +#### Python +```python +class Solution: + def numTilings(self, n: int) -> int: + if n == 1: return 1 + if n == 2: return 2 + MOD = 10**9 + 7 + dp = [0] * (n + 1) + dp[0] = 1 + dp[1] = 1 + dp[2] = 2 + for i in range(3, n + 1): + dp[i] = (dp[i - 1] + dp[i - 2] + 2 * dp[i - 3]) % MOD + return dp[n] +``` diff --git a/solutions/lc-solutions/0700-0799/792 - Number of Matching Subsequences.md b/solutions/lc-solutions/0700-0799/792 - Number of Matching Subsequences.md new file mode 100644 index 0000000..e996bd0 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/792 - Number of Matching Subsequences.md @@ -0,0 +1,140 @@ +--- +id: number-of-matching-subsequences +title: Number of Matching Subsequences +sidebar_label: 792 - Number of Matching Subsequences +tags: [Trie, Two Pointers, Hash Table, C++, Java, Python] +description: Solve the problem of counting the number of words that are subsequences of a given string using various efficient methods. +--- + +## Problem Statement + +### Problem Description + +You are given a string `s` and an array of strings `words`. The task is to return the number of `words[i]` that are subsequences of `s`. + +A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. + +For example, "ace" is a subsequence of "abcde". + +### Example + +**Example 1:** +``` +Input: s = "abcde", words = ["a","bb","acd","ace"] +Output: 3 +``` + +**Explanation:** There are three strings in `words` that are subsequences of `s`: "a", "acd", "ace". + +**Example 2:** +``` +Input: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"] +Output: 2 +``` + +### Constraints + +- $1 \leq \text{s.length} \leq 5 \times 10^4$ +- $1 \leq \text{words.length} \leq 5000$ +- $1 \leq \text{words[i].length} \leq 50$ +- `s` and `words[i]` consist of only lowercase English letters. + +## Solution + +### Intuition + +To efficiently count the number of subsequences, we can use different methods, including Trie, Two Pointers, and Hash Table. The goal is to check for each word in `words` whether it can be formed as a subsequence of `s`. + +### Methods + +#### Method 1: Two Pointers + +For each word in `words`, we can use two pointers to check if it is a subsequence of `s`. One pointer iterates through `s`, and the other iterates through the current word. We match characters and advance both pointers accordingly. + +**Time Complexity:** +The time complexity is $O(n \cdot m)$, where `n` is the length of `s` and `m` is the total number of characters in `words`. + +#### Method 2: Hash Table and Bucketing + +We can use a hash table where each key is a character from `a` to `z` and each value is a list of iterators. For each character in `s`, we update the hash table to see if there are any words that can progress to the next character. + +**Time Complexity:** +The time complexity is $O(n + m)$, where `n` is the length of `s` and `m` is the total length of all words in `words`. + +### Code + +#### C++ + +```cpp +class Solution { +public: + int numMatchingSubseq(string s, vector& words) { + vector> waiting(128); + for (int i = 0; i < words.size(); ++i) { + waiting[words[i][0]].push_back(i); + } + + int res = 0; + for (char c : s) { + vector advance = move(waiting[c]); + waiting[c].clear(); + for (int idx : advance) { + if (++words[idx].length() == words[idx].size()) { + ++res; + } else { + waiting[words[idx][words[idx].length()]].push_back(idx); + } + } + } + return res; + } +}; +``` +#### Java +```java +class Solution { + public int numMatchingSubseq(String s, String[] words) { + List[] waiting = new ArrayList[128]; + for (int c = 0; c <= 127; ++c) { + waiting[c] = new ArrayList<>(); + } + for (int i = 0; i < words.length; ++i) { + waiting[words[i].charAt(0)].add(new int[]{i, 1}); + } + + int res = 0; + for (char c : s.toCharArray()) { + List advance = waiting[c]; + waiting[c] = new ArrayList<>(); + for (int[] arr : advance) { + if (arr[1] == words[arr[0]].length()) { + ++res; + } else { + waiting[words[arr[0]].charAt(arr[1]++)].add(arr); + } + } + } + return res; + } +} +``` +#### Python +```python +class Solution: + def numMatchingSubseq(self, s: str, words: List[str]) -> int: + from collections import defaultdict + waiting = defaultdict(list) + for i, word in enumerate(words): + waiting[word[0]].append((i, 1)) + + res = 0 + for c in s: + advance = waiting[c] + waiting[c] = [] + for i, j in advance: + if j == len(words[i]): + res += 1 + else: + waiting[words[i][j]].append((i, j + 1)) + return res +``` diff --git a/solutions/lc-solutions/0700-0799/795 - Number of Subarrays with Bounded Maximum.md b/solutions/lc-solutions/0700-0799/795 - Number of Subarrays with Bounded Maximum.md new file mode 100644 index 0000000..3aedfb1 --- /dev/null +++ b/solutions/lc-solutions/0700-0799/795 - Number of Subarrays with Bounded Maximum.md @@ -0,0 +1,105 @@ +--- +id: number-of-subarrays-with-bounded-maximum +title: Number of Subarrays with Bounded Maximum +sidebar_label: Number of Subarrays with Bounded Maximum +tags: [Array, Sliding Window, C++, Python, Java] +description: Solve the problem of finding the number of contiguous non-empty subarrays where the maximum element is within a given range. +--- + +## Problem Statement + +### Problem Description + +Given an integer array `nums` and two integers `left` and `right`, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range `[left, right]`. + +The test cases are generated so that the answer will fit in a 32-bit integer. + +### Example + +**Example 1:** +``` +Input: nums = [2,1,4,3], left = 2, right = 3 +Output: 3 +``` +**Explanation:** There are three subarrays that meet the requirements: [2], [2, 1], [3]. + + +**Example 2:** +``` +Input: nums = [2,9,2,5,6], left = 2, right = 8 +Output: 7 +``` + +### Constraints + +- $1 \leq nums.length \leq 10^5$ +- $0 \leq nums[i] \leq 10^9$ +- $0 \leq left \leq right \leq 10^9$ + +## Solution + +### Intuition + +To solve this problem, we can use a sliding window approach. The idea is to maintain a window of subarrays whose maximum elements are within the given range `[left, right]`. We can keep track of the start and end of this window and count the number of valid subarrays. + +### Time Complexity and Space Complexity Analysis + +- **Time Complexity**: The solution involves a single pass through the array, making the time complexity $O(n)$. +- **Space Complexity**: The space complexity is $O(1)$ since we are using a constant amount of extra space. + +### Code + +#### C++ + +```cpp +class Solution { +public: + int numSubarrayBoundedMax(vector& nums, int left, int right) { + int count = 0, start = -1, last = -1; + for (int i = 0; i < nums.size(); i++) { + if (nums[i] > right) { + start = i; + } + if (nums[i] >= left) { + last = i; + } + count += last - start; + } + return count; + } +}; +``` + +#### Java +```java +class Solution { + public int numSubarrayBoundedMax(int[] nums, int left, int right) { + int count = 0, start = -1, last = -1; + for (int i = 0; i < nums.length; i++) { + if (nums[i] > right) { + start = i; + } + if (nums[i] >= left) { + last = i; + } + count += last - start; + } + return count; + } +} +``` +#### Python +```python +class Solution: + def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: + count = 0 + start = -1 + last = -1 + for i in range(len(nums)): + if nums[i] > right: + start = i + if nums[i] >= left: + last = i + count += last - start + return count +``` diff --git a/solutions/lc-solutions/0700-0799/_category_.json b/solutions/lc-solutions/0700-0799/_category_.json new file mode 100644 index 0000000..52d34bc --- /dev/null +++ b/solutions/lc-solutions/0700-0799/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "0700-0799", + "position": 9, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (0700 - 0799)" + } +} diff --git a/solutions/lc-solutions/0700-0799/image-1.png b/solutions/lc-solutions/0700-0799/image-1.png new file mode 100644 index 0000000..e69bd12 Binary files /dev/null and b/solutions/lc-solutions/0700-0799/image-1.png differ diff --git a/solutions/lc-solutions/0700-0799/image.png b/solutions/lc-solutions/0700-0799/image.png new file mode 100644 index 0000000..a7e6d09 Binary files /dev/null and b/solutions/lc-solutions/0700-0799/image.png differ diff --git a/solutions/lc-solutions/0800- 0899/0823-Binary-Trees-With-Factors.md b/solutions/lc-solutions/0800- 0899/0823-Binary-Trees-With-Factors.md new file mode 100644 index 0000000..b1a12d2 --- /dev/null +++ b/solutions/lc-solutions/0800- 0899/0823-Binary-Trees-With-Factors.md @@ -0,0 +1,143 @@ +--- +id: binary-trees-with-factors +title: Binary Trees With Factors +sidebar_label: 0823-Binary-Trees-With-Factors +tags: + - Dynamic Programming + - Trees + - Hashing + - C++ + - Java + - Python +description: "This document provides a solution to the Binary Trees With Factors problem, where we need to count the number of binary trees that can be formed with a given array of integers such that each node's value is the product of its children's values." +--- + +## Problem + +Given an array of unique integers, `arr`, where each integer `arr[i]` is greater than 1, we need to return the number of binary trees we can make. Each non-leaf node's value should be equal to the product of its children's values. + +The answer may be too large, so return it modulo `10^9 + 7`. + +### Examples + +**Example 1:** + +Input: arr = [2, 4] +Output: 3 +Explanation: We can make these trees: [2], [4], [4, 2, 2] + +**Example 2:** + +Input: arr = [2, 4, 5, 10] +Output: 7 +Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2] + +### Constraints + +- `1 <= arr.length <= 1000` +- `2 <= arr[i] <= 10^9` +- All the values of `arr` are unique. + +### Approach + +To solve this problem, we can use dynamic programming and a hash map to store the number of trees that can be formed with each value as the root. The steps are as follows: + +1. Sort the array to ensure that we consider smaller values first. +2. Use a hash map to store the number of ways to form a tree with each value. +3. Iterate through each value in the sorted array, and for each value, iterate through all previously seen values. If the current value can be divided by one of the previously seen values, and the result is also in the array, update the count of trees for the current value. + +### Solution + +#### Code in Different Languages + +### C++ Solution +```cpp +#include +#include +#include + +using namespace std; + +class Solution { +public: + int numFactoredBinaryTrees(vector& arr) { + sort(arr.begin(), arr.end()); + unordered_map dp; + long result = 0, mod = 1e9 + 7; + + for (int i = 0; i < arr.size(); ++i) { + dp[arr[i]] = 1; + for (int j = 0; j < i; ++j) { + if (arr[i] % arr[j] == 0 && dp.count(arr[i] / arr[j])) { + dp[arr[i]] = (dp[arr[i]] + dp[arr[j]] * dp[arr[i] / arr[j]]) % mod; + } + } + result = (result + dp[arr[i]]) % mod; + } + + return result; + } +}; +``` +### Java Solution + +```java +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class Solution { + public int numFactoredBinaryTrees(int[] arr) { + Arrays.sort(arr); + Map dp = new HashMap<>(); + long result = 0, mod = 1_000_000_007; + + for (int i = 0; i < arr.length; ++i) { + dp.put(arr[i], 1L); + for (int j = 0; j < i; ++j) { + if (arr[i] % arr[j] == 0 && dp.containsKey(arr[i] / arr[j])) { + dp.put(arr[i], (dp.get(arr[i]) + dp.get(arr[j]) * dp.get(arr[i] / arr[j])) % mod); + } + } + result = (result + dp.get(arr[i])) % mod; + } + + return (int) result; + } +} +``` +### Python Solution + +```python +def numFactoredBinaryTrees(arr): + arr.sort() + dp = {} + mod = 10**9 + 7 + + for num in arr: + dp[num] = 1 + for prev in dp: + if num % prev == 0 and num // prev in dp: + dp[num] = (dp[num] + dp[prev] * dp[num // prev]) % mod + + return sum(dp.values()) % mod + +# Test +arr = [2, 4, 5, 10] +print(numFactoredBinaryTrees(arr)) # Output: 7 +``` + +### Complexity Analysis +**Time Complexity:** O(n^2) + +>Reason: We use two nested loops to check pairs of numbers and update the count of trees. + +**Space Complexity:** O(n) + +>Reason: We use a dictionary to store the number of ways to form a tree with each value. + +This solution efficiently counts the number of binary trees that can be formed using the given array by utilizing dynamic programming and a hash map. The time complexity is quadratic, and the space complexity is linear, making it suitable for the problem constraints. + +### References +**LeetCode Problem:** Binary Trees With Factors + diff --git a/solutions/lc-solutions/0800- 0899/0846-hand-of-straights.md b/solutions/lc-solutions/0800- 0899/0846-hand-of-straights.md new file mode 100644 index 0000000..61d047e --- /dev/null +++ b/solutions/lc-solutions/0800- 0899/0846-hand-of-straights.md @@ -0,0 +1,187 @@ +--- +id: hand-of-straights +title: 846. Hand of Straights +sidebar_label: 846. Hand of Straights +tags: +- Array +- Hash Table +- Greedy +- Sorting + +description: "This is a solution to the 846. Hand of Straights." +--- + +## Problem Description +Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards. + +Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise. + + ### Examples +**Example 1:** +``` +Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 + +Output: true + +Explanation: +Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8] +``` + +**Example 2:** +``` +Input: [1,2,3,4,5], groupSize = 4 + +Output: false + +Explanation: +Alice's hand can not be rearranged into groups of 4. +``` + +### Constraints +- `1 <= hand.length <= 10^4` +- `0 <= hand[i] <= 10^9` +- `1 <= groupSize <= hand.length` +## Solution for 846. Hand of Straights + +The problem is about arranging cards into groups of consecutive sequences. The key observation is that, to form valid groups, each smallest number in the group should lead to groupSize - 1 consecutive numbers following it. If we can always find such sequences starting from the smallest number, then it is possible to arrange the cards into the desired groups. + +## Approach + +1. **Sort the Cards**: The first step is to sort the cards. Sorting helps us to easily identify and form consecutive sequences. + +2. **Find Successors**: For each number in the sorted array, if it hasn't already been used in a group (indicated by a value of -1), try to form a group starting with that number. Use a helper function findSuccessors to check if it is possible to form a valid group starting from the current number. + +3. **Mark Used Cards**: Once a card is used in a group, mark it as `-1` to indicate it has been processed. + +4. **Check Group Formation**: For each number, use the helper function to see if a group of groupSize consecutive numbers can be formed. If at any point, it is not possible to form such a group, return false. + +5. **Completion Check**: If all numbers can be grouped correctly, return true. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + bool findSuccessors(vector& hand, int groupSize, int i, int n) { + int next = hand[i] + 1; + hand[i] = -1; // Mark as used + int count = 1; + i += 1; + while (i < n && count < groupSize) { + if (hand[i] == next) { + next = hand[i] + 1; + hand[i] = -1; + count++; + } + i++; + } + return count == groupSize; + } + + bool isNStraightHand(vector& hand, int groupSize) { + int n = hand.size(); + if (n % groupSize != 0) return false; + std::sort(hand.begin(), hand.end()); + for (int i = 0; i < n; i++) { + if (hand[i] >= 0) { + if (!findSuccessors(hand, groupSize, i, n)) return false; + } + } + return true; + } +}; +``` + + + +```java +class Solution { + public boolean findsucessors(int[] hand, int groupSize, int i, int n) { + int f = hand[i] + 1; + hand[i] = -1; + int count = 1; + i += 1; + while (i < n && count < groupSize) { + if (hand[i] == f) { + f = hand[i] + 1; + hand[i] = -1; + count++; + } + i++; + } + if (count != groupSize) + return false; + else + return true; + } + + public boolean isNStraightHand(int[] hand, int groupSize) { + int n = hand.length; + if (n % groupSize != 0) + return false; + Arrays.sort(hand); + int i = 0; + for (; i < n; i++) { + if (hand[i] >= 0) { + if (!findsucessors(hand, groupSize, i, n)) + return false; + } + } + return true; + } +} +``` + + + + + + +```python +class Solution(object): + def find_successors(self, hand, groupSize, i, n): + next_val = hand[i] + 1 + hand[i] = -1 # Mark as used + count = 1 + i += 1 + while i < n and count < groupSize: + if hand[i] == next_val: + next_val = hand[i] + 1 + hand[i] = -1 + count += 1 + i += 1 + return count == groupSize + + def isNStraightHand(self, hand, groupSize): + n = len(hand) + if n % groupSize != 0: + return False + hand.sort() + for i in range(n): + if hand[i] >= 0: + if not self.find_successors(hand, groupSize, i, n): + return False + return True +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: Sorting the array takes $(O(n \log n))$. The subsequent grouping operation in the worst case can take $(O(n \times groupSize))$, leading to an overall time complexity of $(O(n \log n + n \times groupSize))$. +- **Space Complexity**: IThe space complexity is $(O(1))$ for the in-place operations (aside from the input array). + +--- + +

Authors:

+ +
+{['nagalakshmi08'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/0800-0899/0805 - Split Array With Same Average.md b/solutions/lc-solutions/0800-0899/0805 - Split Array With Same Average.md new file mode 100644 index 0000000..2a56d70 --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0805 - Split Array With Same Average.md @@ -0,0 +1,153 @@ +--- +id: split-array-with-same-average +title: Split Array With Same Average +sidebar_label: 0805 Split Array With Same Average +tags: + - Java + - Math + - Array + - Binary Search + - Dynamic Programming + - Bitmask +description: "This document provides a solution where we split an array into two non-empty subsets such that both subsets have the same average." +--- + +## Problem + +You are given an integer array $nums$. + +You should move each element of $nums$ into one of the two arrays $A$ and $B$ such that $A$ and $B$ are non-empty, and $average(A) == average(B)$. + +Return $true$ if it is possible to achieve that and $false$ otherwise. + +**Note** that for an array $arr$, $average(arr)$ is the sum of all the elements of $arr$ over the length of $arr$. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,3,4,5,6,7,8] + +Output: true + +Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5 . + +``` + +**Example 2:** + +``` +Input: nums = [3,1] + +Output: false + +``` + +### Constraints + +- $1 <= nums.length <= 30$ +- $0 <= nums[i] <= 10^4$ + +--- + +## Approach + +To solve the problem, we need to understand the nature of the allowed moves: + +1. **Calculate Total Sum**: + + - First, calculate the total sum of the array. + +2. **Sort the Array**: + + - Sorting helps in pruning the search space. + +3. **Iterate Over Possible Sizes**: + + - Iterate over possible subset sizes from 1 to n/2. For each size, check if the corresponding subset sum can be an integer. + +4. **Check for Possible Partition**: + + - Use a recursive function with memoization to check if it’s possible to partition the array into subsets with the required sum and size. + +## Solution for Split Array With Same Average + +- The problem requires us to split an array into two non-empty subsets such that both subsets have the same average. + +- For two subsets to have the same average, the sum of elements in each subset divided by their respective lengths must be equal. + +#### Code in Java + +```java +import java.util.Arrays; + +class Solution { + public boolean splitArraySameAverage(int[] nums) { + int n = nums.length; + int totalSum = Arrays.stream(nums).sum(); + + Arrays.sort(nums); + + for (int size = 1; size <= n / 2; size++) { + if (totalSum * size % n == 0) { + int target = totalSum * size / n; + if (canPartition(nums, size, target, 0)) { + return true; + } + } + } + + return false; + } + + private boolean canPartition(int[] nums, int size, int target, int start) { + if (size == 0) { + return target == 0; + } + + for (int i = start; i <= nums.length - size; i++) { + if (i > start && nums[i] == nums[i - 1]) { + continue; + } + + if (nums[i] > target) { + break; + } + + if (canPartition(nums, size - 1, target - nums[i], i + 1)) { + return true; + } + } + + return false; + } + + public static void main(String[] args) { + Solution sol = new Solution(); + + // Test cases + int[] nums1 = {1, 2, 3, 4, 5, 6, 7, 8}; + System.out.println(sol.splitArraySameAverage(nums1)); // Output: true + + int[] nums2 = {3, 1}; + System.out.println(sol.splitArraySameAverage(nums2)); // Output: false + } +} +``` + +### Complexity Analysis + +#### Time Complexity: $O(2^ n/2)$ + +> **Reason**: Time Complexity is $O(2^ n/2)$. Because Each half of the array can generate $O(2^ n/2)$ subsets. + +#### Space Complexity: $O(2^ n/2)$ + +> **Reason**: The space complexity is $O(2^ n/2)$, Because it helps in Storing subset sums and sizes. + +# References + +- **LeetCode Problem:** [Split Array With Same Average](https://leetcode.com/problems/split-array-with-same-average/description/) +- **Solution Link:** [Split Array With Same Average Solution on LeetCode](https://leetcode.com/problems/split-array-with-same-average/solutions/) +- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/vivekvardhan43862/) diff --git a/solutions/lc-solutions/0800-0899/0806-Number-of-Lines-To-Write-String.md b/solutions/lc-solutions/0800-0899/0806-Number-of-Lines-To-Write-String.md new file mode 100644 index 0000000..213666c --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0806-Number-of-Lines-To-Write-String.md @@ -0,0 +1,71 @@ +--- +id: number-of-lines-to-write-string +title: Number of Lines To Write String +sidebar_label: 806- Number of Lines To Write String +tags: + - Array + - String +description: Write the string ss across multiple lines with each line no wider than 100 pixels, counting the total number of lines and the width of the last line, given the widths of each letter. +sidebar_position: 0806 +--- + +## Problem Description + +You are given a string `s` of lowercase English letters and an array `widths` denoting how many pixels wide each lowercase English letter is. Specifically, `widths[0]` is the width of `'a'`, `widths[1]` is the width of 'b', and so on. + +You are trying to write `s` across several lines, where each line is no longer than 100 pixels. Starting at the beginning of `s`, write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in `s`, continue writing as many letters as you can on the second line. Continue this process until you have written all of `s`. + +Return an array `result` of length 2 where: + +- `result[0]` is the total number of lines. +- `result[1]` is the width of the last line in pixels. + +### Example 1 + +- **Input:** `widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "abcdefghijklmnopqrstuvwxyz"` +- **Output:** `[3,60]` +- **Explanation:** `You can write s as follows: +abcdefghij // 100 pixels wide +klmnopqrst // 100 pixels wide +uvwxyz // 60 pixels wide +There are a total of 3 lines, and the last line is 60 pixels wide.` + +### Constraints + +- `widths.length == 26` +- `2 <= widths[i] <= 10` + +## Approach + +We initialize variables sum to keep track of the running sum of widths and numOfLines to store the number of lines needed. We iterate through each character of the string s, calculate its width using the provided array widths, and update the sum. If adding the width of the current character doesn't exceed the maximum width, we continue adding to the sum. If it exceeds, we increment the numOfLines and reset the sum to the width of the current character. Finally, we return an array containing the number of lines and the remaining width. + +### Solution Code + +#### Java + +```Java +class Solution { + public int numberOfArithmeticSlices(int[] nums) { + int arithmeticSliceCount = 0; + int currentSliceLength = 0; + int difference = 3000; + for (int i = 0; i < nums.length - 1; ++i) { + if (nums[i + 1] - nums[i] == difference) { + ++currentSliceLength; + } else { + difference = nums[i + 1] - nums[i]; + currentSliceLength = 0; + } + arithmeticSliceCount += currentSliceLength; + } + return arithmeticSliceCount; + } +} + +``` + +- Time Complexity + The time complexity is o(n). + +- Space Complexity + The space complexity is O(1). diff --git a/solutions/lc-solutions/0800-0899/0809-expressive-Words.md b/solutions/lc-solutions/0800-0899/0809-expressive-Words.md new file mode 100644 index 0000000..d9f8f09 --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0809-expressive-Words.md @@ -0,0 +1,94 @@ +--- +id: expressive-words +title: Expressive Words +sidebar_label: 809- Expressive Words +tags: + - Array + - String + - Two pointer +description: Given a string s and an array of query strings words, return the number of words that can be transformed into s by extending groups of identical characters in the word to have a size of three or more. +sidebar_position: 0809 +--- + +## Problem Description + +Sometimes people repeat letters to represent extra feeling. For example: + +`"hello" -> "heeellooo"` +`"hi" -> "hiiii"` +In these strings like "heeellooo", we have groups of adjacent letters that are all the same: `"h", "eee", "ll", "ooo"`. + +You are given a string `s` and an array of query strings `words`. A query word is stretchy if it can be made to be equal to s by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is three or more. + +For example, starting with `"hello"`, we could do an extension on the group "o" to get "hellooo", but we cannot get "helloo" since the group "oo" has a size less than three. Also, we could do another extension like `"ll" -> "lllll"` to get `"helllllooo"`. If `s = "helllllooo"`, then the query word `"hello"` would be stretchy because of these two extension operations: `query = "hello" -> "hellooo" -> "helllllooo" = s`. +Return the number of query strings that are stretchy. + +### Example 1 + +- **Input:** `s = "heeellooo", words = ["hello", "hi", "helo"]` +- **Output:** `1` +- **Explanation:** `We can extend "e" and "o" in the word "hello" to get "heeellooo". +We can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more.` + +### Constraints + +- `1 <= s.length, words.length <= 100` +- `1 <= words[i].length <= 100` + +## Approach + +The approach iterates through each word in the words array, checking if it can be transformed into s by comparing groups of consecutive identical characters and ensuring the necessary extensions can be made. The helper function verifies this by counting the occurrences of each character in both s and the word, ensuring the transformation rules are met. + +#### Java + +```Java +class Solution { + public int expressiveWords(final String s, final String[] words) { + int count = 0; + + for(final String word : words) + if(helper(s, word)) + count++; + + return count; + } + + private boolean helper(final String s, final String word) { + if(s.length() < word.length()) + return false; + + int i = 0, j = 0; + + while(i < s.length() && j < word.length()) { + if(s.charAt(i) != word.charAt(j)) + return false; + + final char curr = word.charAt(j); + int sCount = 0; + + while(i < s.length() && s.charAt(i) == curr) { + sCount++; + i++; + } + + int wordCount = 0; + + while(j < word.length() && word.charAt(j) == curr) { + wordCount++; + j++; + } + + if(sCount - wordCount < 0 || (sCount - wordCount != 0 && sCount < 3)) + return false; + } + + return i >= s.length() && j >= word.length(); + } +} +``` + +- Time Complexity + The time complexity is o(n). + +- Space Complexity + The space complexity is O(1). diff --git a/solutions/lc-solutions/0800-0899/0810- Chalkboard-XOR-Game.md b/solutions/lc-solutions/0800-0899/0810- Chalkboard-XOR-Game.md new file mode 100644 index 0000000..3af9d69 --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0810- Chalkboard-XOR-Game.md @@ -0,0 +1,66 @@ +--- +id: chalkboard-xor-game +title: Chalkboard XOR Game +sidebar_label: 810- Chalkboard XOR Game +tags: + - Array + - Math + - Game Theory +description: Alice and Bob take turns erasing one number from the chalkboard. If removing a number makes the bitwise XOR of all remaining numbers become 0, the player who made that move loses. If at any player's turn, the XOR of all numbers on the chalkboard is already 0, that player wins. Alice starts first, and both play optimally to avoid losing. +sidebar_position: 0810 +--- + +## Problem Description + +You are given an array of integers `nums` represents the numbers written on a chalkboard. + +Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become `0`, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is `0`. + +Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to `0`, then that player wins. + +Return `true` if and only if Alice wins the game, assuming both players play optimally. + +### Example 1 + +- **Input:** `nums = [1,1,2]` +- **Output:** `false` +- **Explanation:** `Alice has two choices: erase 1 or erase 2. +If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. +If Alice erases 2 first, now nums become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.` + +### Constraints + +- `1 <= nums.length <= 1000` +- `0 <= nums[i] < 216` + +## Approach + +All even counts can be cancelled, similarly all odd counts will be cancelled but the thing which will remain is that if their exists even number of odd counts then only alice wins. + +Their is an edge case that if already the xor of complete array is 0. + +### Solution Code + +#### Cpp + +```Cpp +class Solution { +public: + bool xorGame(vector& nums) { + ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); + int oc = 0, XOR = 0; + unordered_map mp; + for(auto &x : nums) ++mp[x], XOR ^= x; + if(XOR == 0) return true; + for(auto &x : mp) oc += (x.second % 2); + return (oc % 2 == 0); + } +}; + +``` + +- Time Complexity + The time complexity is o(n). + +- Space Complexity + The space complexity is O(1). diff --git a/solutions/lc-solutions/0800-0899/0811 - Subdomain-Visit-Count.md b/solutions/lc-solutions/0800-0899/0811 - Subdomain-Visit-Count.md new file mode 100644 index 0000000..40d060d --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0811 - Subdomain-Visit-Count.md @@ -0,0 +1,93 @@ +--- +id: subdomain-visit-count +title: Subdomain Visit Count +sidebar_label: 811- Subdomain Visit Count +tags: + - Array + - String + - Hash Table +description: Given an array of count-paired domains, return an array showing the total visit counts for each subdomain and its parent domains. +sidebar_position: 0811 +--- + +## Problem Description + +A website domain `"discuss.leetcode.com"` consists of various subdomains. At the top level, we have `"com"`, at the next level, we have `"leetcode.com"` and at the lowest level, `"discuss.leetcode.com"`. When we visit a domain like `"discuss.leetcode.com"`, we will also visit the parent domains `"leetcode.com"` and `"com"` implicitly. + +A count-paired domain is a domain that has one of the two formats `"rep d1.d2.d3"` or `"rep d1.d2"` where `rep` is the number of visits to the domain and d1.d2.d3 is the domain itself. + +For example, `"9001 discuss.leetcode.com"` is a count-paired domain that indicates that `discuss.leetcode.com` was visited `9001` times. +Given an array of count-paired domains cpdomains, return an array of the count-paired domains of each subdomain in the input. You may return the answer in any order. + +### Example 1 + +- **Input:** `cpdomains = ["9001 discuss.leetcode.com"]` +- **Output:** `["9001 leetcode.com","9001 discuss.leetcode.com","9001 com"]` +- **Explanation:** `We only have one website domain: "discuss.leetcode.com". +As discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times.` + +### Constraints + +- `1 <= cpdomain.length <= 100` +- `1 <= cpdomain[i].length <= 100` + +## Approach + +Just store each & every valid substring in a HashMap with its frequency count. +Update the frequency count whenever the same string is encounterd. +Finally, create a new string using each key-value pair of the HashMap & add that new string to the final list. + +### Solution Code + +#### Java + +```Java +class Solution { + HashMap hm= new HashMap<>(); + + public List subdomainVisits(String[] cpdomains) { + List result= new ArrayList<>(); + + for(String s: cpdomains){ + addToList(s); + } + + for(String s: hm.keySet()){ + StringBuilder sb= new StringBuilder( Integer.toString(hm.get(s)) ); + sb.append(" "); + sb.append( s ); + result.add( sb.toString() ); + } + return result; + } + + public void addToList(String s){ + String[] split1= s.split(" "); + int n= Integer.parseInt(split1[0]); + String[] split2= split1[1].split("\\."); + int l= split2.length; + + for(int i=0; i +#include +#include + +using namespace std; + +class Solution { +public: + double largestTriangleArea(vector>& points) { + double max_area = 0; + int n = points.size(); + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + for (int k = j + 1; k < n; ++k) { + double area = 0.5 * abs( + points[i][0] * (points[j][1] - points[k][1]) + + points[j][0] * (points[k][1] - points[i][1]) + + points[k][0] * (points[i][1] - points[j][1]) + ); + max_area = max(max_area, area); + } + } + } + return max_area; + } +}; +``` + +## Python Code + +```python +from itertools import combinations + +class Solution: + def largestTriangleArea(self, points: List[List[int]]) -> float: + return max( + 0.5 * abs( + x1 * (y2 - y3) + + x2 * (y3 - y1) + + x3 * (y1 - y2) + ) + for (x1, y1), (x2, y2), (x3, y3) in combinations(points, 3) + ) +``` + +## Java Code + +```java +import java.util.List; +import java.util.ArrayList; + +class Solution { + public double largestTriangleArea(int[][] points) { + double maxArea = 0; + int n = points.length; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + for (int k = j + 1; k < n; ++k) { + double area = 0.5 * Math.abs( + points[i][0] * (points[j][1] - points[k][1]) + + points[j][0] * (points[k][1] - points[i][1]) + + points[k][0] * (points[i][1] - points[j][1]) + ); + maxArea = Math.max(maxArea, area); + } + } + } + return maxArea; + } +} +``` + +## JavaScript Code + +```javascript +/** + * @param {number[][]} points + * @return {number} + */ +var largestTriangleArea = function (points) { + let maxArea = 0; + const n = points.length; + for (let i = 0; i < n; ++i) { + for (let j = i + 1; j < n; ++j) { + for (let k = j + 1; k < n; ++k) { + let area = + 0.5 * + Math.abs( + points[i][0] * (points[j][1] - points[k][1]) + + points[j][0] * (points[k][1] - points[i][1]) + + points[k][0] * (points[i][1] - points[j][1]) + ); + maxArea = Math.max(maxArea, area); + } + } + } + return maxArea; +}; +``` diff --git a/solutions/lc-solutions/0800-0899/0817-Linked-List-Components.md b/solutions/lc-solutions/0800-0899/0817-Linked-List-Components.md new file mode 100644 index 0000000..349706f --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0817-Linked-List-Components.md @@ -0,0 +1,190 @@ +--- +id: linked-list-components +title: Linked List Components +sidebar_label: 0817-Linked-List-Components +tags: + - Linked Lists + - Hashing + - C++ + - Java + - Python +description: "This document provides a solution to the Linked List Components problem, where we need to count the number of connected components in a linked list." +--- + +## Problem + +You are given the head of a linked list containing unique integer values and an integer array `nums` that is a subset of the linked list values. + +Return the number of connected components in `nums`, where two values are connected if they appear consecutively in the linked list. + +### Examples + +**Example 1:** + +Input: head = [0,1,2,3], nums = [0,1,3] +Output: 2 +Explanation: 0 and 1 are connected, so [0, 1] forms one component. 3 is a single component. + +**Example 2:** + +Input: head = [0,1,2,3,4], nums = [0,3,1,4] +Output: 2 +Explanation: 0 and 1 are connected, so [0, 1] forms one component. 3 and 4 are connected, so [3, 4] forms another component. + +### Constraints + +- The number of nodes in the linked list is in the range `[1, 10^4]`. +- `0 <= Node.val < 10^4` +- All values in the linked list are unique. +- All values in `nums` are unique. +- `nums` is a subset of the linked list values. + +### Approach + +To solve this problem, we can use a set to store the values in `nums` for quick lookup. We then iterate through the linked list, checking if each node's value is in the set. We count components by checking if the current node starts a new component, which happens if it's in `nums` but the previous node isn't, or if it's the first node. + +The detailed steps are: + +1. Store all elements of `nums` in a set. +2. Initialize a counter for the components. +3. Traverse the linked list, incrementing the counter when encountering a new component. +4. Return the counter. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include + +using namespace std; + +struct ListNode { + int val; + ListNode* next; + ListNode(int x) : val(x), next(NULL) {} +}; + +int numComponents(ListNode* head, vector& nums) { + unordered_set num_set(nums.begin(), nums.end()); + int count = 0; + bool in_component = false; + + while (head != NULL) { + if (num_set.find(head->val) != num_set.end()) { + if (!in_component) { + in_component = true; + count++; + } + } else { + in_component = false; + } + head = head->next; + } + + return count; +} +``` + +### Java Solution + +```java +import java.util.HashSet; +import java.util.Set; + +public class LinkedListComponents { + public static class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } + } + + public int numComponents(ListNode head, int[] nums) { + Set numSet = new HashSet<>(); + for (int num : nums) { + numSet.add(num); + } + + int count = 0; + boolean inComponent = false; + + while (head != null) { + if (numSet.contains(head.val)) { + if (!inComponent) { + inComponent = true; + count++; + } + } else { + inComponent = false; + } + head = head.next; + } + + return count; + } + + public static void main(String[] args) { + ListNode head = new ListNode(0); + head.next = new ListNode(1); + head.next.next = new ListNode(2); + head.next.next.next = new ListNode(3); + + int[] nums = {0, 1, 3}; + LinkedListComponents solution = new LinkedListComponents(); + System.out.println(solution.numComponents(head, nums)); // Output: 2 + } +} +``` + +### Python Solution + +```python +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +def numComponents(head, nums): + num_set = set(nums) + count = 0 + in_component = False + + while head: + if head.val in num_set: + if not in_component: + in_component = True + count += 1 + else: + in_component = False + head = head.next + + return count + +# Test +head = ListNode(0) +head.next = ListNode(1) +head.next.next = ListNode(2) +head.next.next.next = ListNode(3) + +nums = [0, 1, 3] +print(numComponents(head, nums)) # Output: 2 +``` + +### Complexity Analysis + +**Time Complexity:** O(n) + +> Reason: We traverse the linked list once and perform constant-time operations for each node. + +**Space Complexity:** O(n) + +> Reason: We use a set to store the elements of nums, which takes O(n) space. + +This solution efficiently counts the number of connected components in a linked list by leveraging a set for quick lookups and a linear traversal of the linked list. The time complexity is linear, and the space complexity is linear as well, making it suitable for large input sizes. + +### References + +**LeetCode Problem:** Linked List Components diff --git a/solutions/lc-solutions/0800-0899/0819-Most-Common-Word.md b/solutions/lc-solutions/0800-0899/0819-Most-Common-Word.md new file mode 100644 index 0000000..5c95bc2 --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0819-Most-Common-Word.md @@ -0,0 +1,190 @@ +--- +id: most-common-word +title: Most Common Word +sidebar_label: 0819-Most-Common-Word +tags: + - Strings + - Hashing + - C++ + - Java + - Python +description: "This document provides a solution to the Most Common Word problem, where we need to find the most frequent word in a paragraph that is not in a list of banned words." +--- + +## Problem + +Given a string `paragraph` and a string array of the `banned` words, return the most frequent word that is not banned. It is guaranteed there is at least one word that isn't banned, and the answer is unique. + +### Examples + +**Example 1:** + +Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"] +Output: "ball" +Explanation: +"hit" occurs 3 times, but it is a banned word. +"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. + +**Example 2:** + +Input: paragraph = "a.", banned = [] +Output: "a" + +### Constraints + +- `1 <= paragraph.length <= 1000` +- The `paragraph` consists of English letters, space, or the punctuation symbols: "!?',;.". +- There are no two consecutive punctuation characters in `paragraph`. +- `1 <= banned.length <= 100` +- `1 <= banned[i].length <= 10` +- The `banned[i]` consists of only lowercase English letters. + +### Approach + +To solve this problem, we need to: + +1. Clean and split the paragraph into words. +2. Store the banned words in a set for quick lookup. +3. Use a dictionary to count the occurrences of each non-banned word. +4. Identify the word with the highest count. + +Detailed steps: + +1. Convert all letters in the paragraph to lowercase. +2. Replace punctuation with spaces to facilitate splitting into words. +3. Split the cleaned paragraph into words. +4. Count the occurrences of each word that is not in the banned list. +5. Return the word with the highest frequency. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +#include +#include +#include +#include + +using namespace std; + +string mostCommonWord(string paragraph, vector& banned) { + unordered_set banned_set(banned.begin(), banned.end()); + unordered_map word_count; + string word; + int max_count = 0; + string result; + + for (char& c : paragraph) { + c = isalnum(c) ? tolower(c) : ' '; + } + + istringstream iss(paragraph); + while (iss >> word) { + if (banned_set.find(word) == banned_set.end()) { + word_count[word]++; + if (word_count[word] > max_count) { + max_count = word_count[word]; + result = word; + } + } + } + + return result; +} + +int main() { + string paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."; + vector banned = {"hit"}; + cout << mostCommonWord(paragraph, banned) << endl; // Output: "ball" +} +``` + +### Java Solution + +```java +import java.util.*; + +public class MostCommonWord { + public String mostCommonWord(String paragraph, String[] banned) { + Set bannedSet = new HashSet<>(Arrays.asList(banned)); + Map wordCount = new HashMap<>(); + String[] words = paragraph.toLowerCase().split("\\W+"); + int maxCount = 0; + String result = ""; + + for (String word : words) { + if (!bannedSet.contains(word)) { + wordCount.put(word, wordCount.getOrDefault(word, 0) + 1); + if (wordCount.get(word) > maxCount) { + maxCount = wordCount.get(word); + result = word; + } + } + } + + return result; + } + + public static void main(String[] args) { + MostCommonWord solution = new MostCommonWord(); + String paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."; + String[] banned = {"hit"}; + System.out.println(solution.mostCommonWord(paragraph, banned)); // Output: "ball" + } +} +``` + +### Python Solution + +```python +import re +from collections import defaultdict + +def mostCommonWord(paragraph, banned): + banned_set = set(banned) + word_count = defaultdict(int) + + # Normalize the paragraph + normalized_str = re.sub(r'[^\w\s]', ' ', paragraph).lower() + + # Split the paragraph into words + words = normalized_str.split() + + # Count the occurrences of each word + max_count = 0 + result = "" + for word in words: + if word not in banned_set: + word_count[word] += 1 + if word_count[word] > max_count: + max_count = word_count[word] + result = word + + return result + +# Test +paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." +banned = ["hit"] +print(mostCommonWord(paragraph, banned)) # Output: "ball" +``` + +### Complexity Analysis + +**Time Complexity:** O(n) + +> Reason: We traverse the paragraph and words array, each operation inside the loop takes constant time. + +**Space Complexity:** O(n) + +> Reason: We use extra space for the set of banned words and the dictionary to count word occurrences. + +This solution efficiently finds the most common word in a paragraph that is not banned by using a set for quick lookup and a dictionary for counting occurrences. The time complexity is linear, and the space complexity is linear as well, making it suitable for large input sizes. + +### References + +**LeetCode Problem:** Most Common Word diff --git a/solutions/lc-solutions/0800-0899/0821- Shortest-Distance-to-a-Character.md b/solutions/lc-solutions/0800-0899/0821- Shortest-Distance-to-a-Character.md new file mode 100644 index 0000000..d6f55f0 --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0821- Shortest-Distance-to-a-Character.md @@ -0,0 +1,87 @@ +--- +id: shortest-distance-to-a-character +title: Shortest Distance to a Character +sidebar_label: 821- Shortest Distance to a Character +tags: + - Array + - String + - Two pointer +description: Given a string ss and a character cc that appears in ss, return an array where each element at index ii represents the minimum distance from ii to any occurrence of cc in ss. +sidebar_position: 0821 +--- + +## Problem Description + +Given a string s and a character c that occurs in s, return an array of integers answer where `answer.length == s.length` and `answer[i]` is the distance from index i to the closest occurrence of character c in s. + +The distance between two indices i and j is `abs(i - j)`, where abs is the absolute value function. + +### Example 1 + +- **Input:** `s = "loveleetcode", c = "e"` +- **Output:** `[3,2,1,0,1,0,0,1,2,2,1,0]` +- **Explanation:** `The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed). +The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3. +The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2. +For index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1. +The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.` + +### Constraints + +- `1 <= s.length <= 10` + +## Approach + +This approach first identifies all positions of the character cc in the string and stores them in a list. Then, it iterates through each character in the string and calculates the shortest distance to the nearest cc by comparing distances to the closest occurrences of cc on both sides (if applicable), and updates the result array accordingly. + +#### Java + +```Java +class Solution { + public int[] shortestToChar(String s, char c) + { + int[] result = new int[s.length()]; + List cPositions = new ArrayList<>(); + + int currPos = 0; + + for (int i = 0; i < s.length(); i++) + { + if (s.charAt(i) == c) cPositions.add(i); + } + + int k = 0; + for (int i = 0; i < s.length(); i++) + { + if (currPos == cPositions.size()) + { + result[k++] = i - cPositions.get(currPos - 1); + } + else + { + int p = cPositions.get(currPos); + + if (i == p) + { + result[k++] = 0; + currPos++; + } + else if (currPos == 0) result[k++] = p - i; + else + { + int p2 = cPositions.get(currPos - 1); + result[k++] = Math.min(i - p2, p - i); + } + } + } + + return result; + } +} +``` + +- Time Complexity + The time complexity is $o(n)$. + +- Space Complexity + The space complexity is $O(1)$. diff --git a/solutions/lc-solutions/0800-0899/0822-Card-Flipping-Game.md b/solutions/lc-solutions/0800-0899/0822-Card-Flipping-Game.md new file mode 100644 index 0000000..693903f --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0822-Card-Flipping-Game.md @@ -0,0 +1,168 @@ +--- +id: card-flipping-game +title: Card Flipping Game +sidebar_label: 0822-Card-Flipping-Game +tags: + - Arrays + - Hashing + - C++ + - Java + - Python +description: "This document provides a solution to the Card Flipping Game problem, where we need to find the smallest number that is on the front of a card and not on the back of any card." +--- + +## Problem + +You are given two integer arrays `fronts` and `backs` representing the fronts and backs of `n` cards respectively. If `fronts[i]` and `backs[i]` are the same for card `i`, we cannot use it. We need to find the smallest number that is on the front of a card and not on the back of any card. + +### Examples + +**Example 1:** + +Input: fronts = [1,2,4,4,7], backs = [1,3,4,1,3] +Output: 2 +Explanation: If you flip the second card, the number 2 is on the front, which is not on the back of any card. + +**Example 2:** + +Input: fronts = [1], backs = [1] +Output: 0 +Explanation: There is no number that is on the front of a card and not on the back of any card. + +### Constraints + +- `n == fronts.length == backs.length` +- `1 <= n <= 1000` +- `1 <= fronts[i], backs[i] <= 2000` + +### Approach + +To solve this problem, we can follow these steps: + +1. Identify all numbers that appear on both the front and back of the same card and store them in a set. +2. Initialize a variable to track the smallest valid number. +3. Traverse through the fronts and backs arrays to find the smallest number that is not in the set. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +#include + +using namespace std; + +int flipgame(vector& fronts, vector& backs) { + unordered_set same; + int n = fronts.size(); + + for (int i = 0; i < n; ++i) { + if (fronts[i] == backs[i]) { + same.insert(fronts[i]); + } + } + + int result = INT_MAX; + + for (int i = 0; i < n; ++i) { + if (same.find(fronts[i]) == same.end()) { + result = min(result, fronts[i]); + } + if (same.find(backs[i]) == same.end()) { + result = min(result, backs[i]); + } + } + + return result == INT_MAX ? 0 : result; +} + +int main() { + vector fronts = {1, 2, 4, 4, 7}; + vector backs = {1, 3, 4, 1, 3}; + cout << flipgame(fronts, backs) << endl; // Output: 2 +} +``` + +### Java Solution + +```java +import java.util.HashSet; +import java.util.Set; + +public class CardFlippingGame { + public int flipgame(int[] fronts, int[] backs) { + Set same = new HashSet<>(); + int n = fronts.length; + + for (int i = 0; i < n; ++i) { + if (fronts[i] == backs[i]) { + same.add(fronts[i]); + } + } + + int result = Integer.MAX_VALUE; + + for (int i = 0; i < n; ++i) { + if (!same.contains(fronts[i])) { + result = Math.min(result, fronts[i]); + } + if (!same.contains(backs[i])) { + result = Math.min(result, backs[i]); + } + } + + return result == Integer.MAX_VALUE ? 0 : result; + } + + public static void main(String[] args) { + CardFlippingGame solution = new CardFlippingGame(); + int[] fronts = {1, 2, 4, 4, 7}; + int[] backs = {1, 3, 4, 1, 3}; + System.out.println(solution.flipgame(fronts, backs)); // Output: 2 + } +} +``` + +### Python Solution + +```python +def flipgame(fronts, backs): + same = set() + + for f, b in zip(fronts, backs): + if f == b: + same.add(f) + + result = float('inf') + + for x in fronts + backs: + if x not in same: + result = min(result, x) + + return result if result != float('inf') else 0 + +# Test +fronts = [1, 2, 4, 4, 7] +backs = [1, 3, 4, 1, 3] +print(flipgame(fronts, backs)) # Output: 2 +``` + +### Complexity Analysis + +**Time Complexity:** O(n) + +> Reason: We traverse the fronts and backs arrays twice, which takes linear time. + +**Space Complexity:** O(n) + +> Reason: We use a set to store the same values, which in the worst case, could store all values in the array. + +This solution efficiently finds the smallest number on the front of a card that is not on the back of any card by using a set for quick lookups and a linear traversal of the arrays. The time complexity is linear, and the space complexity is linear as well, making it suitable for large input sizes. + +### References + +**LeetCode Problem:** Card Flipping Game diff --git a/solutions/lc-solutions/0800-0899/0823-Binary-Trees-With-Factors.md b/solutions/lc-solutions/0800-0899/0823-Binary-Trees-With-Factors.md new file mode 100644 index 0000000..a33ef4b --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0823-Binary-Trees-With-Factors.md @@ -0,0 +1,147 @@ +--- +id: binary-trees-with-factors +title: Binary Trees With Factors +sidebar_label: 0823-Binary-Trees-With-Factors +tags: + - Dynamic Programming + - Trees + - Hashing + - C++ + - Java + - Python +description: "This document provides a solution to the Binary Trees With Factors problem, where we need to count the number of binary trees that can be formed with a given array of integers such that each node's value is the product of its children's values." +--- + +## Problem + +Given an array of unique integers, `arr`, where each integer `arr[i]` is greater than 1, we need to return the number of binary trees we can make. Each non-leaf node's value should be equal to the product of its children's values. + +The answer may be too large, so return it modulo `10^9 + 7`. + +### Examples + +**Example 1:** + +Input: arr = [2, 4] +Output: 3 +Explanation: We can make these trees: [2], [4], [4, 2, 2] + +**Example 2:** + +Input: arr = [2, 4, 5, 10] +Output: 7 +Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2] + +### Constraints + +- `1 <= arr.length <= 1000` +- `2 <= arr[i] <= 10^9` +- All the values of `arr` are unique. + +### Approach + +To solve this problem, we can use dynamic programming and a hash map to store the number of trees that can be formed with each value as the root. The steps are as follows: + +1. Sort the array to ensure that we consider smaller values first. +2. Use a hash map to store the number of ways to form a tree with each value. +3. Iterate through each value in the sorted array, and for each value, iterate through all previously seen values. If the current value can be divided by one of the previously seen values, and the result is also in the array, update the count of trees for the current value. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +#include + +using namespace std; + +class Solution { +public: + int numFactoredBinaryTrees(vector& arr) { + sort(arr.begin(), arr.end()); + unordered_map dp; + long result = 0, mod = 1e9 + 7; + + for (int i = 0; i < arr.size(); ++i) { + dp[arr[i]] = 1; + for (int j = 0; j < i; ++j) { + if (arr[i] % arr[j] == 0 && dp.count(arr[i] / arr[j])) { + dp[arr[i]] = (dp[arr[i]] + dp[arr[j]] * dp[arr[i] / arr[j]]) % mod; + } + } + result = (result + dp[arr[i]]) % mod; + } + + return result; + } +}; +``` + +### Java Solution + +```java +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class Solution { + public int numFactoredBinaryTrees(int[] arr) { + Arrays.sort(arr); + Map dp = new HashMap<>(); + long result = 0, mod = 1_000_000_007; + + for (int i = 0; i < arr.length; ++i) { + dp.put(arr[i], 1L); + for (int j = 0; j < i; ++j) { + if (arr[i] % arr[j] == 0 && dp.containsKey(arr[i] / arr[j])) { + dp.put(arr[i], (dp.get(arr[i]) + dp.get(arr[j]) * dp.get(arr[i] / arr[j])) % mod); + } + } + result = (result + dp.get(arr[i])) % mod; + } + + return (int) result; + } +} +``` + +### Python Solution + +```python +def numFactoredBinaryTrees(arr): + arr.sort() + dp = {} + mod = 10**9 + 7 + + for num in arr: + dp[num] = 1 + for prev in dp: + if num % prev == 0 and num // prev in dp: + dp[num] = (dp[num] + dp[prev] * dp[num // prev]) % mod + + return sum(dp.values()) % mod + +# Test +arr = [2, 4, 5, 10] +print(numFactoredBinaryTrees(arr)) # Output: 7 +``` + +### Complexity Analysis + +**Time Complexity:** O(n^2) + +> Reason: We use two nested loops to check pairs of numbers and update the count of trees. + +**Space Complexity:** O(n) + +> Reason: We use a dictionary to store the number of ways to form a tree with each value. + +This solution efficiently counts the number of binary trees that can be formed using the given array by utilizing dynamic programming and a hash map. The time complexity is quadratic, and the space complexity is linear, making it suitable for the problem constraints. + +### References + +**LeetCode Problem:** Binary Trees With Factors diff --git a/solutions/lc-solutions/0800-0899/0825- Friends-Of-Appropriate-Ages.md b/solutions/lc-solutions/0800-0899/0825- Friends-Of-Appropriate-Ages.md new file mode 100644 index 0000000..d571753 --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0825- Friends-Of-Appropriate-Ages.md @@ -0,0 +1,74 @@ +--- +id: friends-of-appropriate-ages +title: Friends Of Appropriate Ages +sidebar_label: 825- Friends Of Appropriate Ages +tags: + - Array + - Binary Search + - Sorting +description: Calculate the total number of friend requests made between persons based on their ages, following specific conditions that determine when a friend request is not sent. +sidebar_position: 0825 +--- + +## Problem Description + +There are n persons on a social media website. You are given an integer array ages where `ages[i]` is the age of the ith person. + +A Person x will not send a friend request to a person `y (x != y)` if any of the following conditions is true: + +`age[y] <= 0.5 * age[x] + 7` +`age[y] > age[x]` +`age[y] > 100 && age[x] < 100` +Otherwise, x will send a friend request to y. + +Note that if x sends a request to y, y will not necessarily send a request to x. Also, a person will not send a friend request to themself. + +Return the total number of friend requests made. + +### Example 1 + +- **Input:** `ages = [16,16]` +- **Output:** `2` +- **Explanation:** `2 people friend request each other.` + +### Constraints + +- `n == ages.length` +- `1 <= ages[i] <= 120` + +## Approach + +This approach first counts the occurrences of each age using a frequency array map. It then computes the cumulative counts to facilitate range queries. For each person, it determines the valid age range for sending friend requests and calculates the total possible friend requests by leveraging the cumulative counts, subtracting the invalid and self-request cases. + +#### Java + +```Java +class Solution { + public int numFriendRequests(int[] ages) { + int map[]=new int[121]; + for(int j=0;j=ages[i]){ + continue; + } + totalFriend+=map[ages[i]]-map[cond]-1; + } + return totalFriend; + } +} +``` + +- Time Complexity + The time complexity is o(n). + +- Space Complexity + The space complexity is o(1). + e space complexity is O(1). diff --git a/solutions/lc-solutions/0800-0899/0826-most-profit-assigning-work.md b/solutions/lc-solutions/0800-0899/0826-most-profit-assigning-work.md new file mode 100644 index 0000000..3fb3a2a --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0826-most-profit-assigning-work.md @@ -0,0 +1,190 @@ +--- +id: most-profit-assigning-work +title: Most Profit Assigning Work +sidebar_label: 826 - Most Profit Assigning Work +tags: + - Leet code +description: "Solution to leetocde 826" +--- + +## Problem Statement + +You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where: + +difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and +worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]). +Every worker can be assigned at most one job, but one job can be completed multiple times. + +### Example 1 + +**Input**: `difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]` + +**Output**: `100` + +**Explanation**: +Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately. + +### Example 2 + +**Input**: `difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]` + +**Output**: `0` + + + +### Constraints + +- `n == difficulty.length` +- `n == profit.length` +- `m == worker.length` +- `1 <= n, m <= 104` +- `1 <= difficulty[i], profit[i], worker[i] <= 105` + + +### Approach + + +**1 Initialization:** + +- Determine the maximum job difficulty. +- Initialize a maxProfitUpToDifficulty array to store the maximum profit for each difficulty level up to the maximum difficulty. + +**2 Fill the Profit Lookup Table:** + +- For each job, update the maxProfitUpToDifficulty array to ensure it holds the maximum profit for the given difficulty. +- Convert the maxProfitUpToDifficulty array to a cumulative maximum profit array, where each index i will have the maximum profit possible for difficulties from 0 to i. +- Calculate Total Profit: +- For each worker, use their ability to look up the corresponding maximum profit from the maxProfitUpToDifficulty array and sum up the total - profit. + +**3 Complexity** + +- Time Complexity: ( O(n + m + d) ), where ( n ) is the number of jobs, ( m ) is the number of workers, and ( d ) is the maximum difficulty. +- Space Complexity: ( O(d) ) for the maxProfitUpToDifficulty array. + + +### Code implementation + +### Python Solution + +```python +class Solution(object): + def maxProfitAssignment(self, difficulty, profit, worker): + max_difficulty = max(difficulty) + max_profit_up_to_difficulty = [0] * (max_difficulty + 1) + + for d, p in zip(difficulty, profit): + max_profit_up_to_difficulty[d] = max(max_profit_up_to_difficulty[d], p) + + for i in range(1, max_difficulty + 1): + max_profit_up_to_difficulty[i] = max(max_profit_up_to_difficulty[i], max_profit_up_to_difficulty[i - 1]) + + total_profit = 0 + for ability in worker: + if ability > max_difficulty: + total_profit += max_profit_up_to_difficulty[max_difficulty] + else: + total_profit += max_profit_up_to_difficulty[ability] + + return total_profit + + +``` + +### C++ Solution + +```cpp +class Solution { +public: + int maxProfitAssignment(vector& difficulty, vector& profit, vector& worker) { + int maxDifficulty = *max_element(difficulty.begin(), difficulty.end()); + vector maxProfitUpToDifficulty(maxDifficulty + 1, 0); + + for (int i = 0; i < difficulty.size(); ++i) { + maxProfitUpToDifficulty[difficulty[i]] = max(maxProfitUpToDifficulty[difficulty[i]], profit[i]); + } + + for (int i = 1; i <= maxDifficulty; ++i) { + maxProfitUpToDifficulty[i] = max(maxProfitUpToDifficulty[i], maxProfitUpToDifficulty[i - 1]); + } + + int totalProfit = 0; + for (int ability : worker) { + if (ability > maxDifficulty) { + totalProfit += maxProfitUpToDifficulty[maxDifficulty]; + } else { + totalProfit += maxProfitUpToDifficulty[ability]; + } + } + + return totalProfit; + } +}; +``` + +### Java Solution + +```java +class Solution { + public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) { + int maxDifficulty = 0; + for (int d : difficulty) { + maxDifficulty = Math.max(maxDifficulty, d); + } + + int[] maxProfitUpToDifficulty = new int[maxDifficulty + 1]; + for (int i = 0; i < difficulty.length; i++) { + maxProfitUpToDifficulty[difficulty[i]] = Math.max(maxProfitUpToDifficulty[difficulty[i]], profit[i]); + } + + for (int i = 1; i <= maxDifficulty; i++) { + maxProfitUpToDifficulty[i] = Math.max(maxProfitUpToDifficulty[i], maxProfitUpToDifficulty[i - 1]); + } + + int totalProfit = 0; + for (int ability : worker) { + if (ability > maxDifficulty) { + totalProfit += maxProfitUpToDifficulty[maxDifficulty]; + } else { + totalProfit += maxProfitUpToDifficulty[ability]; + } + } + + return totalProfit; + } + +} +``` + +### JavaScript Solution + +```javascript +/** + * @param {number[]} difficulty + * @param {number[]} profit + * @param {number[]} worker + * @return {number} + */ +var maxProfitAssignment = function(difficulty, profit, worker) { + let maxDifficulty = Math.max(...difficulty); + let maxProfitUpToDifficulty = new Array(maxDifficulty + 1).fill(0); + + for (let i = 0; i < difficulty.length; i++) { + maxProfitUpToDifficulty[difficulty[i]] = Math.max(maxProfitUpToDifficulty[difficulty[i]], profit[i]); + } + + for (let i = 1; i <= maxDifficulty; i++) { + maxProfitUpToDifficulty[i] = Math.max(maxProfitUpToDifficulty[i], maxProfitUpToDifficulty[i - 1]); + } + + let totalProfit = 0; + for (let ability of worker) { + if (ability > maxDifficulty) { + totalProfit += maxProfitUpToDifficulty[maxDifficulty]; + } else { + totalProfit += maxProfitUpToDifficulty[ability]; + } + } + + return totalProfit; +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/0800-0899/0827-making-a-large-island.md b/solutions/lc-solutions/0800-0899/0827-making-a-large-island.md new file mode 100644 index 0000000..dcc18af --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0827-making-a-large-island.md @@ -0,0 +1,244 @@ +--- +id: making-a-large-island +title: Making a Large Island +sidebar_label: 0827-making-a-large-island +tags: + - Array + - Dept-First Search + - Breadth-First Search + - Union Find + - Matrix +description: "This is a solution to making a large island problem on LeetCode." +--- + +## Problem Description + +You are given an `n x n` binary matrix `grid`. You are allowed to change **at most one** `0` to be `1`. + +Return the size of the largest Island in `grid` after applying this operation. + +An **island** is a `4-directionally` connected group of 1s. + +### Examples + +**Example 1:** + +``` +Input: grid = [[1,0],[0,1]] +Output: 3 +**Explanation:** Change one 0 to 1 and connect two 1s, then we get an island with area = 3. +``` + +**Example 2:** + +``` +Input: grid = [[1,1],[1,0]] +Output: 4 +**Explanation:** Change the 0 to 1 and make the island bigger, only one island with area = 4. +``` + +**Example 3:** + +``` +Input: grid = [[1,1],[1,1]] +Output: 4 +**Explanation:** Can't change any 0 to 1, only one island with area = 4. +``` + +### Constraints + +- `n == grid.length` +- `n == grid[i].lengt` +- `1 <= n <= 500.` +- `grid[i][j] is either 0 or 1.` + + +## Solution for Assign Cookies + +### Approach: + +Calculate the islands and count and then calculate the largest area possible. +Here is the step-by-step intuition behind the solution: + +1- We would be calculating the islands and their respective area and storing them in a hashMap for further reference. + +2- This could be done using simple dfs. + +3- calculate the largest area possible. + +4- Then we will be iterating through all the cells containing water `(0)` and try changing them into land and check all the four sides contains any piece of land. if yes,then we would take the max of it and return. we will also check whether a chink of island is used only once not multiple times. + +The provided snippet is a overall overview of MAX AREA OF ISLAND try to solve this problem before attempting this. + + + +## Code in Different Languages + +### C++ + +```cpp + class Solution { +public: + int largestIsland(vector>& grid) { + int n = grid.size(); + int ref = 2, maxArea = -1; + unordered_map mp; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) { + int k = find_val(ref, grid, i, j); + mp[ref] = k; + ref += 1; + maxArea = max(maxArea, k); + } + } + } + + mp[0] = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 0) { + int sum = 0; + unordered_set seen; + if (i > 0) seen.insert(grid[i-1][j]); + if (j > 0) seen.insert(grid[i][j-1]); + if (i < n-1) seen.insert(grid[i+1][j]); + if (j < n-1) seen.insert(grid[i][j+1]); + for (int val : seen) { + sum += mp[val]; + } + maxArea = max(maxArea, sum + 1); + } + } + } + return maxArea; + } + + int find_val(int ref, vector>& grid, int i, int j) { + if (i < 0 || j < 0 || i >= grid.size() || j >= grid[0].size() || grid[i][j] == 0 || grid[i][j] == ref) { + return 0; + } + grid[i][j] = ref; + return 1 + find_val(ref, grid, i+1, j) + find_val(ref, grid, i-1, j) + find_val(ref, grid, i, j+1) + find_val(ref, grid, i, j-1); + } +}; + +``` +### Java + +```java +class Solution { + public int largestIsland(int[][] grid) { + int n=grid.length; + int ref=2,max=-1; + HashMap mp=new HashMap<>(); + + //MAX AREA OF ISLAND + for(int i=0;i0){ + sum+=(int)mp.get(grid[i-1][j]); + up=grid[i-1][j]; + } + if(j>0&&grid[i][j-1]!=up) { + sum+=(int)mp.get(grid[i][j-1]); + left=grid[i][j-1]; + } + if(i=arr.length||j>=arr[0].length||arr[i][j]==0||arr[i][j]==ref){ + return 0; + } + arr[i][j]=ref; + return 1+((find_val(ref,arr,i+1,j)+find_val(ref,arr,i-1,j)+find_val(ref,arr,i,j+1)+find_val(ref,arr,i,j-1))); + } +} + +``` + +### Python + +```python +class Solution: + def largestIsland(self, grid: List[List[int]]) -> int: + def find_val(ref, grid, i, j): + if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]) or grid[i][j] == 0 or grid[i][j] == ref: + return 0 + grid[i][j] = ref + return 1 + (find_val(ref, grid, i+1, j) + find_val(ref, grid, i-1, j) + find_val(ref, grid, i, j+1) + find_val(ref, grid, i, j-1)) + + n = len(grid) + ref = 2 + max_area = -1 + mp = {} + + for i in range(n): + for j in range(n): + if grid[i][j] == 1: + k = find_val(ref, grid, i, j) + mp[ref] = k + ref += 1 + max_area = max(max_area, k) + + mp[0] = 0 + for i in range(n): + for j in range(n): + if grid[i][j] == 0: + sum_area = 0 + seen = set() + if i > 0: + seen.add(grid[i-1][j]) + if j > 0: + seen.add(grid[i][j-1]) + if i < n-1: + seen.add(grid[i+1][j]) + if j < n-1: + seen.add(grid[i][j+1]) + for k in seen: + sum_area += mp.get(k, 0) + max_area = max(max_area, sum_area + 1) + + return max_area + +``` + +## Complexity Analysis + +### Time Complexity: O(n^2) + +### Space Complexity: O(n^2) + +## References + +- **LeetCode Problem**: [ Making a Large Island](https://leetcode.com/problems/making-a-large-island/) + diff --git a/solutions/lc-solutions/0800-0899/0828-count-unique-characters-of-all-substrings-of-a-given-string.md b/solutions/lc-solutions/0800-0899/0828-count-unique-characters-of-all-substrings-of-a-given-string.md new file mode 100644 index 0000000..da8a218 --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0828-count-unique-characters-of-all-substrings-of-a-given-string.md @@ -0,0 +1,147 @@ +--- +id: count-unique-characters-of-all-substrings-of-a-given-string +title: Count Unique Characters of all Substrings of a given String. +sidebar_label: 0828-count-unique-characters-of-all-substrings-of-a-given-string +tags: + - Harsh Table + - String + - Dynamic Programming +description: "This is a solution to count unique characters of all substrings of a given-string problem on LeetCode." +--- + +## Problem Description + +Let's define a function `countUniqueChars(s)` that returns the number of unique characters in `s`. + +- For example, calling `countUniqueChars(s)` if `s = "LEETCODE"` then + `"L"`, `"T"`, `"C"`, `"O"`, `"D"` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s)` = 5. + +Given a string s, return the sum of `countUniqueChars(t)` where t is a substring of `s`. The test cases are generated such that the answer fits in a `32-bit integer`. + +Notice that some substrings can be repeated so in this case you have to count the repeated ones too. + +### Examples + +**Example 1:** + +``` +Input: s = "ABC" +Output: 10 +**Explanation:** Change one 0 to 1 and connect two 1s, then we get an island with area = 3All possible substrings are: "A","B","C","AB","BC" and "ABC". +Every substring is composed with only unique letters. +Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10. +``` + +**Example 2:** + +``` +Input:s = "ABA" +Output: 8 +**Explanation:** The same as example 1, except countUniqueChars("ABA") = 1. +``` + +**Example 3:** + +``` +Input: s = "LEETCODE" +Output: 92 +``` + +### Constraints + +- `1 <= s.length <= 10^5` +- `s consists of uppercase English letters only.` + + +## Solution for Assign Cookies + +### Approach: + +Let's think about how a character can be found as a unique character. + +Think about string `"XAXAXXAX"` and focus on making the second `"A"` a unique character. +We can take `"XA(XAXX)AX"` and between `"()"` is our substring. +We can see here, to make the second "A" counted as a uniq character, we need to: + + 1- insert `"("` somewhere between the first and second `A` + 2- insert `")"` somewhere between the second and third `A` + +For step 1 we have `"A(XA"` and `"AX(A"`, 2 possibility. +For step 2 we have `"A)XXA"`, `"AX)XA"` and `"AXX)A"`, 3 possibilities. + +So there are in total 2 * 3 = 6 ways to make the second A a unique character in a substring. +In other words, there are only 6 substring, in which this A contribute 1 point as unique string. + +Instead of counting all unique characters and struggling with all possible substrings, +we can count for every char in S, how many ways to be found as a unique char. +We count and sum, and it will be out answer. + + + +## Code in Different Languages + +### C++ + +```cpp + int uniqueLetterString(string S) { + int index[26][2], res = 0, N = S.length(), mod = pow(10, 9) + 7; + memset(index, -1, sizeof(int) * 52); + for (int i = 0; i < N; ++i) { + int c = S[i] - 'A'; + res = (res + (i - index[c][1]) * (index[c][1] - index[c][0]) % mod) % mod; + index[c][0] = index[c][1]; + index[c][1] = i; + } + for (int c = 0; c < 26; ++c) + res = (res + (N - index[c][1]) * (index[c][1] - index[c][0]) % mod) % mod; + return res; + } + + +``` +### Java + +```java + public int uniqueLetterString(String S) { + int[][] index = new int[26][2]; + for (int i = 0; i < 26; ++i) Arrays.fill(index[i], -1); + int res = 0, N = S.length(), mod = (int)Math.pow(10, 9) + 7; + for (int i = 0; i < N; ++i) { + int c = S.charAt(i) - 'A'; + res = (res + (i - index[c][1]) * (index[c][1] - index[c][0]) % mod) % mod; + index[c] = new int[] {index[c][1], i}; + } + for (int c = 0; c < 26; ++c) + res = (res + (N - index[c][1]) * (index[c][1] - index[c][0]) % mod) % mod; + return res; + } + + +``` + +### Python + +```python + def uniqueLetterString(self, S): + index = {c: [-1, -1] for c in ascii_uppercase} + res = 0 + for i, c in enumerate(S): + k, j = index[c] + res += (i - j) * (j - k) + index[c] = [j, i] + for c in index: + k, j = index[c] + res += (len(S) - j) * (j - k) + return res % (10**9 + 7) +``` + +## Complexity Analysis + +### Time Complexity: O(N) + +### Space Complexity: O(1) + +## References + +- **LeetCode Problem**: [Count Unique Characters of all Substrings of a given String.](https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/) + diff --git a/solutions/lc-solutions/0800-0899/0829-consecutive-numbers-sum.md b/solutions/lc-solutions/0800-0899/0829-consecutive-numbers-sum.md new file mode 100644 index 0000000..e47e31a --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0829-consecutive-numbers-sum.md @@ -0,0 +1,129 @@ +--- +id: consecutive-numbers-sum +title: Consecutive Numbers Sum +sidebar_label: 0829-consecutive-numbers-sum +tags: + - Math + - Enumeration +description: "This is a solution to consecutive-numbers-sum problem on LeetCode." +--- + +## Problem Description +Given an integer `n`, return the number of ways you can write `n` as the sum of consecutive positive integers. + +### Examples + +**Example 1:** + +``` +Input: n = 5 +Output: 2 +**Explanation**: 5 = 2 + 3 +``` + +**Example 2:** + +``` +Input: n = 9 +Output: 3 +**Explanation:** 9 = 4 + 5 = 2 + 3 + 4 +``` + +**Example 3:** + +``` +Input: n = 15 +Output: 4 +**Explanation:** 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 + +``` + +### Constraints + +- `1 <= n <= 10^9` + + +## Solution for Assign Cookies + +### Approach: + +1- Discard all factors 2 from N. + +2- Check all odd number i if N is divided by i. + +3- Calculate the count of factors i that N has. + +4- Update res *= count. + +5- If N==1, we have found all primes and just return res. + +6- Otherwise, N will be equal to P and we should do res *= count + 1 where count = 1. + + +## Code in Different Languages + +### C++ + +```cpp +class Solution { +public: + int consecutiveNumbersSum(int N) { + int res = 1, count; + while (N % 2 == 0) N /= 2; + for (int i = 3; i * i <= N; res *= count + 1, i += 2) + for (count = 0; N % i == 0; N /= i, count++); + return N == 1 ? res : res * 2; + } +}; +``` +### Java + +```java +class Solution { + public int consecutiveNumbersSum(int N) { + int res = 1, count; + while (N % 2 == 0) N /= 2; + for (int i = 3; i * i <= N; i += 2) { + count = 0; + while (N % i == 0) { + N /= i; + count++; + } + res *= count + 1; + } + return N == 1 ? res : res * 2; + } +} + + +``` + +### Python + +```python +class Solution(object): + def consecutiveNumbersSum(self, N): + res = 1 + i = 3 + while N % 2 == 0: + N /= 2 + while i * i <= N: + count = 0 + while N % i == 0: + N /= i + count += 1 + res *= count + 1 + i += 2 + return res if N == 1 else res * 2 +``` + +## Complexity Analysis + +### Time Complexity: O(logN) + +### Space Complexity: O(1) + +## References + +- **LeetCode Problem**: [Consecutive Numbers Sum](https://leetcode.com/problems/consecutive-numbers-sum/) + diff --git a/solutions/lc-solutions/0800-0899/0830-positions-of-large-groups.md b/solutions/lc-solutions/0800-0899/0830-positions-of-large-groups.md new file mode 100644 index 0000000..4b3540b --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0830-positions-of-large-groups.md @@ -0,0 +1,122 @@ +--- +id: positions-of-large-groups +title: Positions of Large Groups +sidebar_label: 0830-positions-of-large-groups +tags: + - String +description: "This is a solution to positions-of-large-groups problem on LeetCode." +--- + +## Problem Description +In a string `s` of lowercase letters, these letters form consecutive groups of the same character. + +For example, a string like `s = "abbxxxxzyy"` has the groups `"a"`, `"bb"`, `"xxxx"`, `"z"`, and `"yy"`. + +A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx"` has the interval `[3,6]`. +` +A group is considered **large** if it has `3` or more characters. + +Return the intervals of every **large** group sorted in **increasing order** by start index. + +### Examples + +**Example 1:** + +``` +Input: s = "abbxxxxzzy" +Output: [[3,6]] +**Explanation**: "xxxx" is the only large group with start index 3 and end index 6. +``` + +**Example 2:** + +``` +Input: s = "abc" +Output: [] +**Explanation:** We have groups "a", "b", and "c", none of which are large groups. +``` + +**Example 3:** + +``` +Input: s = "abcdddeeeeaabbbcd" +Output: [[3,5],[6,9],[12,14]] +**Explanation:** The large groups are "ddd", "eeee", and "bbb". + +``` + +### Constraints + +- `1 <= s.length <= 1000` +- `s contains lowercase English letters only.` + + +## Solution for Assign Cookies + +### Approach: + +1- For every groups, find its start index `i` and end index `j - 1`. + +2- Group length is `j - i`, if it's no less than 3, add `(i, j)` to result. + + +## Code in Different Languages + +### C++ + +```cpp +class Solution { + public: + vector> largeGroupPositions(string S) { + vector> res; + for (int i = 0, j = 0; i < S.size(); i = j) { + while (j < S.size() && S[j] == S[i]) ++j; + if (j - i >= 3) + res.push_back({i, j - 1}); + } + return res; + } +}; +``` +### Java + +```java +class Solution { + public List> largeGroupPositions(String S) { + List> res = new ArrayList<>(); + for (int i = 0, j = 0; i < S.length(); i = j) { + while (j < S.length() && S.charAt(j) == S.charAt(i)) ++j; + if (j - i >= 3) + res.add(Arrays.asList(i, j - 1)); + } + return res; + } +} + + +``` + +### Python + +```python +class Solution(object): + def largeGroupPositions(self, S): + i, j, N = 0, 0, len(S) + res = [] + while i < N: + while j < N and S[j] == S[i]: j += 1 + if j - i >= 3: res.append([i, j - 1]) + i = j + return res +``` + +## Complexity Analysis + +### Time Complexity: O(N) + +### Space Complexity: O(N) + +## References + +- **LeetCode Problem**: [Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups/description/) + diff --git a/solutions/lc-solutions/0800-0899/0851- Loud-and-Rich.md b/solutions/lc-solutions/0800-0899/0851- Loud-and-Rich.md new file mode 100644 index 0000000..4a4bc85 --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0851- Loud-and-Rich.md @@ -0,0 +1,131 @@ +--- +id: loud-and-rich +title: Loud and Rich +sidebar_label: 851- Loud and Rich +tags: + - Array + - Graph + - Depth-First Search +description: Return an integer array answer where answer[x] = y indicates that y is the person with the least quietness among all individuals who have equal to or more money than person x. +sidebar_position: 0851 +--- + +## Problem Description + +There is a group of n people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. + +You are given an array richer where `richer[i] = [ai, bi]` indicates that ai has more money than bi and an integer array quiet where `quiet[i]` is the quietness of the ith person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time). + +Return an integer array answer where `answer[x] = y` if y is the least quiet person (that is, the person y with the smallest value of `quiet[y]`) among all people who definitely have equal to or more money than the person x. + +### Example 1 + +- **Input:** `richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]` +- **Output:** `[5,5,2,5,4,5,6,7]` +- **Explanation:** `answer[0] = 5. +Person 5 has more money than 3, which has more money than 1, which has more money than 0. +The only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0. +answer[7] = 7. +Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7. +The other answers can be filled out with similar reasoning.` + +### Constraints + +- `n == quiet.length` +- `0 <= quiet[i] < n` +- `0 <= richer.length <= n * (n - 1) / 2` + +## Approach + +The approach uses breadth-first search (BFS) to find all people richer than each person, then constructs an updated adjacency list updated_adj to store these relationships. For each person, it identifies the least quiet person among those richer or equally wealthy by comparing quietness values and returns the corresponding indices in the result array. + +#### Java + +```Java +class Solution { + Map> updated_adj; + public int[] loudAndRich(int[][] richer, int[] quiet) { + int n=quiet.length; + ArrayList> adj = new ArrayList<>(); + for(int i =0;i()); + adj.get(i).add(i); + } + + for(int [] arr: richer) + { + int src = arr[0]; + int dst = arr[1]; + adj.get(dst).add(src); + } + updated_adj = new HashMap<>(); + for (int i = 0; i < n; i++) { + updated_adj.put(i, new HashSet<>()); + updated_adj.get(i).add(i); + } + // Map> updated_adj = new ArrayList<>(); + for(int i=0;i hs=updated_adj.get(i); + System.out.println(hs); + ArrayList al = new ArrayList<>(); + for(int ele : hs) + { + al.add(quiet[ele]); + } + System.out.println(al); + Collections.sort(al); + System.out.println(al); + + int check=al.get(0); + int index = getIndex(check,quiet); + System.out.println(index); + result[i]=index; + System.out.println(); + } + + return result; + + } + public static void bfs(ArrayList> adj,Map> updated_adj,int start) + { + Queue q = new LinkedList<>(); + q.add(start); + while(!q.isEmpty()) + { + int node = q.poll(); + for(int neigh : adj.get(node)) + { + if(!updated_adj.get(start).contains(neigh)) + { + updated_adj.get(start).add(neigh); + q.add(neigh); + } + } + + + } + } + public static int getIndex(int ele,int[] quiet) + { + for(int i=0;i=0;i--){ + max_suffix=Math.max(arr[i],max_suffix); + suffix[i]=max_prefix; + } + int idx=-1; + for(int i=0;i{ + int pos; + int speed; + + public Car(int pos, int speed){ + this.pos = pos; + this.speed = speed; + } + + public int compareTo(Car otherCar){ + return otherCar.pos - this.pos; + } +} + +class Solution { + public int carFleet(int target, int[] position, int[] speed) { + Car[] cars = new Car[position.length]; + Stack stack = new Stack<>(); + for(int i = 0; i "ba"` + +### Constraints + +- `1 <= s1.length <= 20` +- `s2.length == s1.length` + +## Approach + +This approach recursively finds the minimum number of swaps needed to transform string a into string b. It first aligns characters that are already perfectly matched, then recursively explores all possible swaps for mismatched characters, choosing the swap that results in the least additional swaps needed. The swap function is used to interchange characters, and checkAllOptions explores all possible swaps to find the optimal sequence. +#### Java + +```Java +class Solution { + public int kSimilarity(String a, String b) { + int ans = 0; + char[] achars = a.toCharArray(); + char[] bchars = b.toCharArray(); + ans += getAllPerfectMatches(achars, bchars); + for (int i = 0; i < achars.length; i++) { + if (achars[i] == bchars[i]) { + continue; + } + return ans + checkAllOptions(achars, bchars, i, b); + } + return ans; + } + private int checkAllOptions(char[] achars, char[] bchars, int i, String b) { + int ans = Integer.MAX_VALUE; + for (int j = i + 1; j < achars.length; j++) { + if (achars[j] == bchars[i] && achars[j] != bchars[j]) { + swap(achars, i, j); + ans = Math.min(ans, 1 + kSimilarity(new String(achars), b)); + swap(achars, i, j); + } + } + return ans; + } + private int getAllPerfectMatches(char[] achars, char[] bchars) { + int ans = 0; + for (int i = 0; i < achars.length; i++) { + if (achars[i] == bchars[i]) { + continue; + } + for (int j = i + 1; j < achars.length; j++) { + if (achars[j] == bchars[i] && bchars[j] == achars[i]) { + swap(achars, i, j); + ans++; + break; + } + } + } + return ans; + } + private void swap(char[] a, int i, int j) { + char temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } +} + +``` + +- Time Complexity + The time complexity is $o(n)$. + +- Space Complexity + The space complexity is $O(1)$. diff --git a/solutions/lc-solutions/0800-0899/0855- Exam-Room.md b/solutions/lc-solutions/0800-0899/0855- Exam-Room.md new file mode 100644 index 0000000..bf93def --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0855- Exam-Room.md @@ -0,0 +1,127 @@ +--- +id: exam-room +title: Exam Room +sidebar_label: 855- Exam Room +tags: + - Design + - Heap + - Ordered set +description: Design a class ExamRoom that simulates an exam room where students sit to maximize their distance from others, and includes methods for a student to take the optimal seat and to leave a specified seat. +sidebar_position: 0855 +--- + +## Problem Description + +There is an exam room with n seats in a single row labeled from `0` to `n - 1`. + +When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0. + +Design a class that simulates the mentioned exam room. + +Implement the `ExamRoom` class: + +`ExamRoom(int n)` Initializes the object of the exam room with the number of the seats n. +`int seat()` Returns the label of the seat at which the next student will set. +`void leave(int p)` Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p. + +### Example 1 + +- **Input:** `["ExamRoom", "seat", "seat", "seat", "seat", "leave", "seat"] +[[10], [], [], [], [], [4], []]` +- **Output:** `[null, 0, 9, 4, 2, null, 5]` +- **Explanation:** `ExamRoom examRoom = new ExamRoom(10); +examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. +examRoom.seat(); // return 9, the student sits at the last seat number 9. +examRoom.seat(); // return 4, the student sits at the last seat number 4. +examRoom.seat(); // return 2, the student sits at the last seat number 2. +examRoom.leave(4); +examRoom.seat(); // return 5, the student sits at the last seat number 5.` + +### Constraints + +- `1 <= n <= 109` +- `It is guaranteed that there is a student sitting at seat p` + +## Approach + +The ExamRoom class uses two TreeSets: available to store available intervals of seats and taken to store occupied seats. When a student takes a seat, the seat that maximizes the distance to the closest student is chosen, and the interval is updated. When a student leaves, the intervals are adjusted to reflect the newly available seat. The TreeSet is used to efficiently manage and retrieve the intervals and seats. +#### Java + +```Java +class ExamRoom { + + private final int max; + private final TreeSet available; + private final TreeSet taken; + + public ExamRoom(int n) { + this.max = n - 1; + this.available = new TreeSet<>((a, b) -> { + var distA = getMinDistance(a); + var distB = getMinDistance(b); + return distA == distB ? a.s - b.s : distB - distA; + }); + this.available.add(new Interval(0, max)); + this.taken = new TreeSet<>(); + } + + public int seat() { + var inter = available.pollFirst(); + var idx = getInsertPosition(inter); + taken.add(idx); + if ((idx - 1) - inter.s >= 0) + available.add(new Interval(inter.s, idx - 1)); + if (inter.e - (idx + 1) >= 0) + available.add(new Interval(idx + 1, inter.e)); + return idx; + } + + public void leave(int p) { + taken.remove(p); + var lo = taken.lower(p); + if (lo == null) + lo = -1; + var hi = taken.higher(p); + if (hi == null) + hi = max + 1; + available.remove(new Interval(lo + 1, p - 1)); + available.remove(new Interval(p + 1, hi - 1)); + available.add(new Interval(lo + 1, hi - 1)); + } + + private int getInsertPosition(Interval inter) { + if (inter.s == 0) + return 0; + else if (inter.e == max) + return max; + else + return inter.s + (inter.e - inter.s) / 2; + } + + private int getMinDistance(Interval in) { + return in.s == 0 || in.e == max ? in.e - in.s : (in.e - in.s) / 2; + } + + private final class Interval { + private final int s; + private final int e; + + Interval(int s, int e) { + this.s = s; + this.e = e; + } + + @Override + public String toString() { + return "[" + s + "," + e + "]"; + } + } +} + +``` + +- Time Complexity + The time complexity is $O(logN)$. + +- Space Complexity + The space complexity is $O(1)$. diff --git a/solutions/lc-solutions/0800-0899/0858- Mirror-Reflection.md b/solutions/lc-solutions/0800-0899/0858- Mirror-Reflection.md new file mode 100644 index 0000000..335ec51 --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0858- Mirror-Reflection.md @@ -0,0 +1,60 @@ +--- +id: mirror-reflection +title: Mirror Reflection +sidebar_label: 858- Mirror Reflection +tags: + - Math + - Geometry + - Number Theory +description: Given a square room with mirrored walls and receptors at corners, a laser ray emitted from the southwest corner reflects off mirrors and reaches a receptor based on specified conditions. +sidebar_position: 0858 +--- + +## Problem Description + +There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0, 1, and 2`. + +The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the `0th` receptor. + +Given the two integers p and q, return the number of the receptor that the ray meets first. + +The test cases are guaranteed so that the ray will meet a receptor eventually. + +### Example 1 + +- **Input:** `p = 2, q = 1` +- **Output:** `2` +- **Explanation:** `The ray meets receptor 2 the first time it gets reflected back to the left wall.` + +### Constraints + +- `1 <= q <= p <= 1000` + +## Approach + +This Java function mirrorReflection determines where a laser ray, starting from the southwest corner of a square room with mirrored walls, will reflect and reach a receptor. It continuously reduces the room dimensions p and q by dividing them by 2 while both are even, simulating the path of the laser until it reaches a receptor. Depending on whether p or q becomes odd first, it returns 0, 1, or 2 indicating the receptor the laser reaches first (based on their positions in the room). + +#### Java + +```Java +class Solution { + + // taken help + public int mirrorReflection(int p, int q) { + while(p%2==0 && q%2==0){ + p=p/2; + q=q/2; + } + + if(p%2==0) return 2; + if(q%2==0) return 0; + return 1; + } +} +``` + +- Time Complexity + The time complexity is $o(n)$. + +- Space Complexity + The space complexity is $O(1)$. diff --git a/solutions/lc-solutions/0800-0899/0861-score-after-flipping-matrix.md b/solutions/lc-solutions/0800-0899/0861-score-after-flipping-matrix.md new file mode 100644 index 0000000..fba1ff1 --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0861-score-after-flipping-matrix.md @@ -0,0 +1,179 @@ +--- +id: score-after-flipping-matrix +title: Score After Flipping Matrix +level: medium +sidebar_label: Score After Flipping Matrix +tags: + - Array + - Greedy + - Matrix + - Java +description: "This document provides solutions for the Score After Flipping Matrix problem." +--- + +## Problem Statement + +You are given an `m x n` binary matrix `grid`. + +A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's). + +Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers. + +Return the highest possible score after making any number of moves (including zero moves). + +**Example 1:** + +Input: `grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]` + +Output: `39` + +Explanation: `0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39` + +**Example 2:** + +Input: `grid = [[0]]` + +Output: `1` + +**Constraints:** + +- `m == grid.length` +- `n == grid[i].length` +- `1 <= m, n <= 20` +- `grid[i][j]` is `0` or `1`. + +## Solutions + +### Approach + +To maximize the score, follow these steps: + +1. **Row Flipping:** + + - Ensure that each row starts with a `1` by flipping rows where the first element is `0`. + +2. **Column Flipping:** + + - For each column, if the number of `0`s exceeds the number of `1`s, flip the column to maximize the number of `1`s in that column. + +3. **Calculate Score:** + - Convert each row from binary to decimal and sum these values to get the final score. + +### Java + +```java +class Solution { + public int matrixScore(int[][] grid) { + int m = grid.length; + int n = grid[0].length; + int i = 0, j = 0; + + for (i = 0; i < m; i++) { + if (grid[i][0] == 0) { + flipRow(grid, i); + } + } + + for (j = 0; j < n; j++) { + if (searchColZeroes(grid, j) > searchColOnes(grid, j)) { + flipCol(grid, j); + } + } + + int sum = 0; + for (i = 0; i < grid.length; i++) { + int count = 0; + int temp = grid[0].length - 1; + for (j = 0; j < grid[0].length; j++) { + count += (int) (grid[i][j] * Math.pow(2, temp--)); + } + sum += count; + } + return sum; + } + + public int searchColZeroes(int[][] grid, int j) { + int count = 0; + for (int temp = 0; temp < grid.length; temp++) { + if (grid[temp][j] == 0) { + count++; + } + } + return count; + } + + public int searchColOnes(int[][] grid, int j) { + int count = 0; + for (int temp = 0; temp < grid.length; temp++) { + if (grid[temp][j] == 1) { + count++; + } + } + return count; + } + + public void flipCol(int[][] grid, int j) { + for (int temp = 0; temp < grid.length; temp++) { + grid[temp][j] = (grid[temp][j] == 0) ? 1 : 0; + } + } + + public void flipRow(int[][] grid, int i) { + for (int temp = 0; temp < grid[0].length; temp++) { + grid[i][temp] = (grid[i][temp] == 0) ? 1 : 0; + } + } +} +``` + +### Python + +```Python +class Solution: + def matrixScore(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + + # Step 1: Ensure all rows start with '1' by flipping rows where grid[i][0] == 0 + for i in range(m): + if grid[i][0] == 0: + self.flipRow(grid, i) + + # Step 2: Ensure each column has more '1's than '0's by flipping columns if necessary + for j in range(n): + if self.searchColZeroes(grid, j) > self.searchColOnes(grid, j): + self.flipCol(grid, j) + + # Step 3: Calculate the matrix score + score = 0 + for i in range(m): + row_sum = 0 + for j in range(n): + row_sum += grid[i][j] * (1 << (n - 1 - j)) # Equivalent to grid[i][j] * 2^(n-1-j) + score += row_sum + + return score + + def searchColZeroes(self, grid: List[List[int]], j: int) -> int: + count = 0 + for i in range(len(grid)): + if grid[i][j] == 0: + count += 1 + return count + + def searchColOnes(self, grid: List[List[int]], j: int) -> int: + count = 0 + for i in range(len(grid)): + if grid[i][j] == 1: + count += 1 + return count + + def flipCol(self, grid: List[List[int]], j: int) -> None: + for i in range(len(grid)): + grid[i][j] = 1 - grid[i][j] + + def flipRow(self, grid: List[List[int]], i: int) -> None: + for j in range(len(grid[0])): + grid[i][j] = 1 - grid[i][j] + +``` diff --git a/solutions/lc-solutions/0800-0899/0863-All-nodes-distance-K-in-binary-tree.md b/solutions/lc-solutions/0800-0899/0863-All-nodes-distance-K-in-binary-tree.md new file mode 100644 index 0000000..ab672cc --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0863-All-nodes-distance-K-in-binary-tree.md @@ -0,0 +1,314 @@ +--- +id: All-Nodes-Distance-K-in-Binary-Tree +title: All Nodes Distance K in Binary Tree +sidebar_label: 863 - All Nodes Distance K in Binary Tree +tags: + - Leet code +description: "Solution to leetocde 863" +--- + +## Problem Statement +Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node. + +You can return the answer in any order. + +### Example 1 + +**Input**: `root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2` + +**Output**: `[7,4,1]` + +**Explanation**: +The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1. + +### Example 2 + +**Input**: `root = [1], target = 1, k = 3` + +**Output**: `[]` + + +### Constraints + +- `The number of nodes in the tree is in the range [1, 500]` +- `0 <= Node.val <= 500` +- `All the values Node.val are unique` +- `target is the value of one of the nodes in the tree` +- `0 <= k <= 1000` + +### Approach + +Start a BFS from the root node of the binary tree. We will use a queue to perform the BFS traversal. Initialize an empty queue and push the root node into it. + +While the queue is not empty, perform the following steps: + +Get the current size of the queue (number of nodes at the current level). +Iterate through all the nodes at the current level. +For each node, check if it has a left child. If it does, store the parent-child relationship by mapping the left child's value to its parent node in an unordered_map called "parent". +Similarly, if the current node has a right child, store the parent-child relationship for the right child. +After processing the children of the current node, remove it from the queue. +After the BFS traversal, we will have the parent-child relationship stored in the "parent" unordered_map. + +Now, we need to perform another BFS traversal to find all the nodes at a distance of k from the target node. Initialize another empty queue and push the target node into it. + +While the value of k is greater than 0 and the queue is not empty, perform the following steps: + +Get the current size of the queue (number of nodes at the current level). +Iterate through all the nodes at the current level. +Mark the current node as visited by adding its value to the "visited" unordered_map. +If the current node has a left child and it has not been visited yet, push it into the queue. +If the current node has a right child and it has not been visited yet, push it into the queue. +If the current node has a parent and the parent node has not been visited yet, push the parent node into the queue. +After processing the current node and its children/parent, remove it from the queue. +After the BFS traversal, we will have all the nodes at a distance of k from the target node stored in the queue. + +Finally, we can extract the values of the nodes from the queue and store them in a vector called "ans". Return the "ans" vector as the result. + + + +**Time complexity:** O(n) + + + +**Space complexity:** O(n) + + + +### Code implementation + +### Python Solution + +```python +class Solution: + def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]: + ans = [] + parent = {} + queue = deque() + queue.append(root) + + while queue: + size = len(queue) + for _ in range(size): + top = queue.popleft() + + if top.left: + parent[top.left.val] = top + queue.append(top.left) + + if top.right: + parent[top.right.val] = top + queue.append(top.right) + + visited = {} + queue.append(target) + while k > 0 and queue: + size = len(queue) + + for _ in range(size): + top = queue.popleft() + + visited[top.val] = 1 + + if top.left and top.left.val not in visited: + queue.append(top.left) + + if top.right and top.right.val not in visited: + queue.append(top.right) + + if top.val in parent and parent[top.val].val not in visited: + queue.append(parent[top.val]) + + k -= 1 + + while queue: + ans.append(queue.popleft().val) + + return ans + +``` + +### C++ Solution + +```cpp +class Solution { +public: + vector distanceK(TreeNode* root, TreeNode* target, int k) { + vector ans; + unordered_map parent; + queue q; + q.push(root); + + while(!q.empty()){ + int si = q.size(); + for(int i = 0; i < si; i++){ + auto top = q.front(); + q.pop(); + + if(top -> left){ + parent[top->left->val] = top; + q.push(top->left); + } + + if(top -> right){ + parent[top->right->val] = top; + q.push(top->right); + } + } + } + + unordered_map visited; + q.push(target); + while(k-- && !q.empty()){ + int size = q.size(); + + for(int i = 0; i < size; i++){ + auto top = q.front(); + q.pop(); + + visited[top -> val] = 1; + + if(top -> left && !visited[top->left->val]){ + q.push(top -> left); + } + + if(top -> right && !visited[top->right->val]){ + q.push(top -> right); + } + + if(parent[top->val] && !visited[parent[top->val] -> val]){ + q.push(parent[top->val]); + } + + } + } + + while(!q.empty()){ + ans.push_back(q.front()->val); + q.pop(); + } + return ans; + } +}; +``` + +### Java Solution + +```java +class Solution { + public List distanceK(TreeNode root, TreeNode target, int k) { + List ans = new ArrayList<>(); + Map parent = new HashMap<>(); + Queue queue = new LinkedList<>(); + queue.offer(root); + + while (!queue.isEmpty()) { + int size = queue.size(); + for (int i = 0; i < size; i++) { + TreeNode top = queue.poll(); + + if (top.left != null) { + parent.put(top.left.val, top); + queue.offer(top.left); + } + + if (top.right != null) { + parent.put(top.right.val, top); + queue.offer(top.right); + } + } + } + + Map visited = new HashMap<>(); + queue.offer(target); + while (k > 0 && !queue.isEmpty()) { + int size = queue.size(); + + for (int i = 0; i < size; i++) { + TreeNode top = queue.poll(); + + visited.put(top.val, 1); + + if (top.left != null && !visited.containsKey(top.left.val)) { + queue.offer(top.left); + } + + if (top.right != null && !visited.containsKey(top.right.val)) { + queue.offer(top.right); + } + + if (parent.containsKey(top.val) && !visited.containsKey(parent.get(top.val).val)) { + queue.offer(parent.get(top.val)); + } + } + + k--; + } + + while (!queue.isEmpty()) { + ans.add(queue.poll().val); + } + return ans; + } +} +``` + +### JavaScript Solution + +```javascript +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} target + * @param {number} k + * @return {number[]} + */ +var distanceK = function(root, target, k) { + let adjList = {}, visited = {}, result = []; + + const buildAdjList = function(node) { + if(!node) return null; + + if(!adjList[node.val]) adjList[node.val] = []; + + if(node.left) { + if(!adjList[node.left.val]) adjList[node.left.val] = []; + + adjList[node.val].push(node.left.val); + adjList[node.left.val].push(node.val); + } + if(node.right) { + if(!adjList[node.right.val]) adjList[node.right.val] = []; + + adjList[node.val].push(node.right.val); + adjList[node.right.val].push(node.val); + } + + buildAdjList(node.left); + buildAdjList(node.right); + } + + buildAdjList(root); + + + const dfs = function(source, dist = 0) { + visited[source] = true; + if(k == dist) result.push(source); + + for(const dest of adjList[source] || []) { + if(!visited[dest]) { + dfs(dest, dist + 1); + } + } + } + + dfs(target.val) + + return result; +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/0800-0899/0865 -smallest- subtree-with-all-the-deepest-nodes.md b/solutions/lc-solutions/0800-0899/0865 -smallest- subtree-with-all-the-deepest-nodes.md new file mode 100644 index 0000000..fb103b5 --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0865 -smallest- subtree-with-all-the-deepest-nodes.md @@ -0,0 +1,203 @@ +--- +id: smallest-subtree-with-all-the-deepest-nodes +title: Smallest Subtree with all the Deepest Nodes +sidebar_label: 865 - Smallest Subtree with all the Deepest Nodes +tags: + - Leet code +description: "Solution to leetocde 865" +--- + +## Problem Statement +Given the root of a binary tree, the depth of each node is the shortest distance to the root. + +Return the smallest subtree such that it contains all the deepest nodes in the original tree. + +A node is called the deepest if it has the largest depth possible among any node in the entire tree. + +The subtree of a node is a tree consisting of that node, plus the set of all descendants of that node. + +### Example 1 + +**Input**: `root = [3,5,1,6,2,0,8,null,null,7,4]` + +**Output**: `[2,7,4]` + +**Explanation**: +The middle node of the list is node 3. + +### Example 2 + +**Input**: `root = [1]` + +**Output**: `[1]` + +**Explanation**: +The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest. + +### Constraints + +- `The number of nodes in the tree will be in the range [1, 500]` +- `0 <= Node.val <= 500` +- `The values of the nodes in the tree are unique.` + + +### Approach + +Write a sub function deep(TreeNode root). +Return a pair(int depth, TreeNode subtreeWithAllDeepest) + +In sub function deep(TreeNode root): + +if root == null, +return pair(0, null) + +if left depth == right depth, +deepest nodes both in the left and right subtree, +return pair (left.depth + 1, root) + +if left depth > right depth, +deepest nodes only in the left subtree, +return pair (left.depth + 1, left subtree) + +if left depth < right depth, +deepest nodes only in the right subtree, +return pair (right.depth + 1, right subtree) + +**Time complexity:** O(N) + + +**Space complexity:** O(height) + + + +### Code implementation + +### Python Solution + +```python +class Solution: + def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode: + found = False + ans = TreeNode(-1) + + def dfs(node,p,q): + nonlocal found, ans + if not node: return [] + + left = dfs(node.left,left_node,right_node) + right = dfs(node.right,left_node,right_node) + + total = [*left,*right] + total.append(node.val) + + if p.val in total and q.val in total and not found: + ans = (node) + found = True + + return total + + def find_depth(root): + q = deque() + q.append(root) + + while q: + l,r = None,None + no_nodes = len(q) + for i in range(len(q)): + a = q.popleft() + if i == 0: l = a + if i == no_nodes-1: r = a + + if a.left: q.append(a.left) + if a.right: q.append(a.right) + + return l,r + + left_node,right_node = find_depth(root) + dfs(root,left_node,right_node) + + return ans + +``` + +### C++ Solution + +```cpp +class Solution { +public: + int height(TreeNode* root) { + if (!root) return 0; + return max(height(root->left) + 1, height(root->right) + 1); + } + TreeNode* subtreeWithAllDeepest(TreeNode* root) { + if (!root) return NULL; + + int left = height(root->left); + int right = height(root->right); + + if (left == right) return root; + if (left > right) return subtreeWithAllDeepest(root->left); + return subtreeWithAllDeepest(root->right); + } +}; +``` + +### Java Solution + +```java +class Solution { + int maxDepth = Integer.MIN_VALUE; + TreeNode result = null; + public TreeNode subtreeWithAllDeepest(TreeNode root) { + postOrder(root, 0); + return result; + } + public int postOrder(TreeNode node, int deep) { + if (node == null) { + return deep; + } + int left = postOrder(node.left, deep + 1); + int right = postOrder(node.right, deep + 1); + int curDepth = Math.max(left, right); + maxDepth = Math.max(maxDepth, curDepth); + if (left == maxDepth && right == maxDepth) { + result = node; + } + return curDepth; + } +} +``` + +### JavaScript Solution + +```javascript + +const subtreeWithAllDeepest = function(root) { + const node = dfs(root) + return node[0] +}; + +const dfs = (node) => { + // If the node is undefined, we have reached the bottom. Return the count as a starting point. + if ((node?.val === undefined)) { + return [null, 0] + } + const left = dfs(node?.left, node) + const right = dfs(node?.right, node) + + // As we bubble up the tree, increment the count to compare depths. + left[1] += 1 + right[1] += 1 + + // Bubble up the left or the right sides existing values depending on the depth. + if (left[1] > right[1]) { + return left + } else if (right[1] > left[1]) { + return right + } else if (right[1] === left[1]) { + // If both sides are the same depth, this is a subtree. Replace the value with the current parent node. + // If there are no other subtrees, this one will always 'win' and bubble up. + return [node, right[1]] + } +} +``` \ No newline at end of file diff --git a/solutions/lc-solutions/0800-0899/0867-Transpose-Matrix.md b/solutions/lc-solutions/0800-0899/0867-Transpose-Matrix.md new file mode 100644 index 0000000..115370d --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0867-Transpose-Matrix.md @@ -0,0 +1,62 @@ +--- +id: transpose-matrix +title: Transpose Matrix +sidebar_label: 867-Transpose-Matrix +tags: + - Araay + - Matrix + - Simulation + +--- + +## Problem Description +Given a 2D integer array `matrix`, return the transpose of `matrix`. + + +### Example + +**Example 1:** + +``` +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] +Output: [[1,4,7],[2,5,8],[3,6,9]] +``` + +**Example 2:** +``` +Input: matrix = [[1,2,3],[4,5,6]] +Output: [[1,4],[2,5],[3,6]] +``` + +### Constraints + +- `1 <= m * n <= 105` + +## Solution Approach + +### Intuition: + +To efficiently determine the transpose of the matrix + + +## Solution Implementation + +### Code (C++): + +```cpp +class Solution { +public: + vector> transpose(vector>& matrix) { + int m = matrix.size(); + int n = matrix[0].size(); + vector> ans(n, vector(m)); + for(int i=0; i + + + ```java + class Solution { + public int minEatingSpeed(int[] piles, int h) { + int l = 1; + int r = 0; + for (int i : piles) { + r = Math.max(r, i); + } + int ans = r; + while (l <= r) { + int m = l + (r - l) / 2; + long division = 0; + for (int i : piles) { + division += (i + m - 1) / m; + } + if (division <= h) { + ans = m; + r = m - 1; + } else { + l = m + 1; + } + } + return ans; + } + } + ``` + + + + + ```python + class Solution: + def minEatingSpeed(self, piles, h): + l, r = 1, max(piles) + ans = r + + while l <= r: + m = (l + r) // 2 + division = 0 + for i in piles: + division += (i + m - 1) // m + if division <= h: + ans = m + r = m - 1 + else: + l = m + 1 + + return ans + ``` + + + + + ```c++ + #include + #include + #include + #include + + class Solution { + public: + int minEatingSpeed(std::vector& piles, int h) { + int l = 1; + int r = *std::max_element(piles.begin(), piles.end()); + int ans = r; + + while (l <= r) { + int m = l + (r - l) / 2; + long long division = 0; + for (int i : piles) { + division += (i + m - 1) / m; + } + if (division <= h) { + ans = m; + r = m - 1; + } else { + l = m + 1; + } + } + + return ans; + } + }; + ``` + + + +## References + +- **LeetCode Problem**: [Koko Eating Bananas](https://leetcode.com/problems/koko-eating-bananas/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/koko-eating-bananas/post-solution/?submissionId=1295704443) diff --git a/solutions/lc-solutions/0800-0899/0876-middle-of-the-linked-list.md b/solutions/lc-solutions/0800-0899/0876-middle-of-the-linked-list.md new file mode 100644 index 0000000..823fc70 --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0876-middle-of-the-linked-list.md @@ -0,0 +1,163 @@ +--- +id: middle-of-the-linked-list +title: Middle of the Linked List +sidebar_label: 876 - Middle of the Linked List +tags: + - Leet code +description: "Solution to leetocde 876" +--- + +## Problem Statement +Given the head of a singly linked list, return the middle node of the linked list. + +If there are two middle nodes, return the second middle node. + +### Example 1 + +**Input**: `head = [1,2,3,4,5]` + +**Output**: `[3,4,5]` + +**Explanation**: +The middle node of the list is node 3. + +### Example 2 + +**Input**: `head = [1,2,3,4,5,6]` + +**Output**: ` [4,5,6]` + +**Explanation**: +Since the list has two middle nodes with values 3 and 4, we return the second one. + +### Constraints + +- `The number of nodes in the list is in the range [1, 100]` +- `1 <= Node.val <= 100` + + +### Approach + +- Define a helper function size to calculate the size of the linked list. +Initialize a temporary pointer (temp) to the head of the linked list. +Calculate the size of the linked list using the size function. +Traverse the linked list again by moving the temp pointer to the middle node (size/2). +Return the middle node. +Complexity + +**Time complexity:** O(n) + +- n is the number of nodes in the linked list. The solution iterates through the linked list twice – once to calculate the size and once to reach the middle. + +**Space complexity:** O(1) +- as the solution uses a constant amount of extra space regardless of the input size. + + +### Code implementation + +### Python Solution + +```python +class Solution: + def middleNode(self, head: ListNode) -> ListNode: + if self.listSize(head) == 1: + return head + temp = head + for _ in range(self.listSize(head) // 2): + temp = temp.next + return temp + + def listSize(self, head: ListNode) -> int: + size = 0 + temp = head + while temp is not None: + size += 1 + temp = temp.next + return size + + +``` + +### C++ Solution + +```cpp +class Solution { +public: + ListNode* middleNode(ListNode* head) { + int i = 0; + ListNode* dummy = head; + while(dummy != NULL){ + dummy = dummy -> next; + i++; + } + int ans = i/2; + ListNode* temp = head; + int j = 0; + while(j < ans){ + temp = temp -> next; + j++; + } + return temp; + } +}; +``` + +### Java Solution + +```java +class Solution { + public static int size(ListNode head){ + int cnt=0; + while(head!=null){ + head = head.next; + cnt++; + } + return cnt; + } + public ListNode middleNode(ListNode head) { + + ListNode temp = head; + + int size = size(head); + + for(int i=0; i=0){ + ans[0]=aliceSizes[i]; + ans[1]=(bobSum-aliceSum+(2*aliceSizes[i]))/2; + } + else if(aliceSizes[i]==(bobSum-aliceSum+(2*aliceSizes[i]))/2){ + ans[0]=aliceSizes[i]; + ans[1]=aliceSizes[i]; + } + } + return ans; + } +} +``` + +- Time Complexity + The time complexity is $o(n)$. + +- Space Complexity + The space complexity is $O(1)$. diff --git a/solutions/lc-solutions/0800-0899/0890 - Find and Replace Pattern.md b/solutions/lc-solutions/0800-0899/0890 - Find and Replace Pattern.md new file mode 100644 index 0000000..da3ea25 --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0890 - Find and Replace Pattern.md @@ -0,0 +1,80 @@ +--- +id: find-and-replace-pattern +title: Find and Replace Pattern +sidebar_label: 890- Find and Replace Pattern +tags: + - Array + - String + - Two pointer +description: Given a list of strings words and a string pattern, return words that match pattern where each unique character in pattern maps uniquely to characters in the word. +sidebar_position: 0890 +--- + +## Problem Description + +Given a list of strings words and a string pattern, return a list of `words[i]` that match pattern. You may return the answer in any order. + +A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with `p(x)`, we get the desired word. + +Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter. + +### Example 1 + +- **Input:** `words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"` +- **Output:** `["mee","aqq"]` +- **Explanation:** `"mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. +"ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.` + +### Constraints + +- `1 <= pattern.length <= 20` +- `1 <= words.length <= 50` + +## Approach + +This solution uses a HashMap (hp1) to map characters from the pattern and each word to unique integers based on their first occurrence order. It constructs a transformed string (res) for the pattern by assigning unique integers to each character based on their first appearance. Then, it checks each word (str) against this transformed pattern (res). If a word matches the pattern transformation, it is added to the result list (al). + +#### Java + +```Java +class Solution { + public List findAndReplacePattern(String[] words, String pattern) { + List al = new ArrayList(); + int count1=0; + HashMap hp1 = new HashMap(); + String res=""; + for(int i=0;i= nums[j]`. + +Given an integer array `nums`, return `true` if the given array is monotonic, or `false` otherwise. + + +### Example + +**Example 1:** + + +``` +Input: nums = [1,2,2,3] +Output: true +``` +**Example 2:** +``` +Input: nums = [6,5,4,4] +Output: true +``` +### Constraints + +- `-10^5 <= nums[i] <= 10^5` + +## Solution Approach + +### Intuition: + +To efficiently determine the monotonic array +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + +class Solution { + isMonotonic(nums) { + const n = nums.length; + let increasing = true; + let decreasing = true; + for(let i = 0; i < n - 1; i++){ + if(nums[i] > nums[i+1]) increasing = false; + if(nums[i] < nums[i+1]) decreasing = false; + } + return increasing || decreasing; + } +} + + + ``` + + + + + ```typescript + class Solution { + isMonotonic(nums: number[]): boolean { + const n = nums.length; + let increasing = true; + let decreasing = true; + for(let i = 0; i < n - 1; i++){ + if(nums[i] > nums[i+1]) increasing = false; + if(nums[i] < nums[i+1]) decreasing = false; + } + return increasing || decreasing; + } +} + + + + + ``` + + + + + ```python + class Solution: + def isMonotonic(self, nums): + n = len(nums) + increasing = True + decreasing = True + for i in range(n - 1): + if nums[i] > nums[i+1]: + increasing = False + if nums[i] < nums[i+1]: + decreasing = False + return increasing or decreasing + + + + ``` + + + + + ```java + public class Solution { + public boolean isMonotonic(int[] nums) { + int n = nums.length; + boolean increasing = true; + boolean decreasing = true; + for(int i = 0; i < n - 1; i++){ + if(nums[i] > nums[i+1]) increasing = false; + if(nums[i] < nums[i+1]) decreasing = false; + } + return increasing || decreasing; + } +} + + + + ``` + + + + + ```cpp +class Solution { +public: + bool isMonotonic(vector& nums) { + int n = nums.size(); + bool increasing = true; + bool decreasing = true; + + for(int i=0; i nums[i+1]) increasing = false; + if(nums[i] < nums[i+1]) decreasing = false; + } + + return increasing || decreasing; + } +}; + +``` + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(n)$$ where n is the length of the input array nums. This is because the algorithm iterates through the array once, performing a constant amount of work for each element. +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/0800-0899/0899- Orderly-Queue.md b/solutions/lc-solutions/0800-0899/0899- Orderly-Queue.md new file mode 100644 index 0000000..9a0012f --- /dev/null +++ b/solutions/lc-solutions/0800-0899/0899- Orderly-Queue.md @@ -0,0 +1,81 @@ +--- +id: orderly-queue +title: Orderly Queue +sidebar_label: 899- Orderly Queue +tags: + - Math + - String + - Sorting +description: Given a string s and an integer k, return the lexicographically smallest string that can be formed by repeatedly moving one of the first k characters of s to the end of the string. +sidebar_position: 0899 +--- + +## Problem Description + +You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string. + +Return the lexicographically smallest string you could have after applying the mentioned step any number of moves. + +### Example 1 + +- **Input:** `s = "cba", k = 1` +- **Output:** `"acb"` +- **Explanation:** `In the first move, we move the 1st character 'c' to the end, obtaining the string "bac". +In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb".` + +### Constraints + +- `1 <= k <= s.length <= 1000` + +## Approach + +This solution first counts the frequency of each character in the string s. If `k > 1`, it simply returns the lexicographically smallest permutation by sorting the characters. If `k == 1`, it generates all possible rotations of the string and returns the lexicographically smallest one. + +#### Java + +```Java +class Solution { + public String orderlyQueue(String s, int k) { + int[] countChar = new int[26]; + int length = s.length(); + for(int i = 0 ; i < length ; ++i) { + countChar[s.charAt(i) - 'a']++; + } + if(k > 1) { + StringBuilder sb = new StringBuilder(); + for(int i = 0 ; i < 26 ; ++i) { + int appearance = countChar[i]; + char c = (char)('a' + i); + for(int r = 0 ; r < appearance ; ++r) { + sb.append(c); + } + } + return sb.toString(); + } + char startChar = 'a'; + for(int i = 0 ; i < 26 ; ++i) { + if(countChar[i] > 0) { + startChar = (char)('a' + i); + break; + } + } + List beginWithStartChar = new ArrayList<>(); + for(int i = 0 ; i < length ; ++i) { + if(s.charAt(i) == startChar) { + beginWithStartChar.add(s.substring(i) + s.substring(0, i)); + } + } + String min = beginWithStartChar.get(0); + for(String strBeginWithStartChar : beginWithStartChar) { + if(strBeginWithStartChar.compareTo(min) < 0) min = strBeginWithStartChar; + } + return min; + } +} +``` + +- Time Complexity + The time complexity is $o(n)$. + +- Space Complexity + The space complexity is $O(n)$. diff --git a/solutions/lc-solutions/0800-0899/_category_.json b/solutions/lc-solutions/0800-0899/_category_.json new file mode 100644 index 0000000..5169f78 --- /dev/null +++ b/solutions/lc-solutions/0800-0899/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "0800-0899", + "position": 10, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (0800 - 0899)" + } +} diff --git a/solutions/lc-solutions/0900-0999/0900-RLE-Iterator.md b/solutions/lc-solutions/0900-0999/0900-RLE-Iterator.md new file mode 100644 index 0000000..57f3ff4 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0900-RLE-Iterator.md @@ -0,0 +1,197 @@ +--- +id: RLE-Iterator +title: RLE Iterator +sidebar_label: RLE Iterator +tags: + - RLE + - Iterator + - Encoding + - Array + - Algorithm +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [RLE-Iterator](https://leetcode.com/problems/RLE-Iterator/description/) | [RLE-Iterator Solution on LeetCode](https://leetcode.com/problems/RLE-Iterator/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +We can use run-length encoding (i.e., RLE) to encode a sequence of integers. In a run-length encoded array of even length encoding (0-indexed), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. + +For example, the sequence `arr = [8,8,8,5,5]` can be encoded to be `encoding = [3,8,2,5]`. `encoding = [3,8,0,9,2,5]` and `encoding = [2,8,1,8,2,5]` are also valid RLE of `arr`. + +Given a run-length encoded array, design an iterator that iterates through it. + +Implement the `RLEIterator` class: + +- `RLEIterator(int[] encoded)` Initializes the object with the encoded array `encoded`. +- `int next(int n)` Exhausts the next `n` elements and returns the last element exhausted in this way. If there is no element left to exhaust, return `-1` instead. + +### Example 1: + +**Input**`["RLEIterator", "next", "next", "next", "next"] [[[3, 8, 0, 9, 2, 5]], [2], [1], [1], [2]]` +**Output**`[null, 8, 8, 5, -1]` + +### Constraints: + +- `2 <= encoding.length <= 1000` +- `encoding.length is even.` +- `0 <= encoding[i] <= 10^9` +- `1 <= n <= 10^9` +- At most `1000` calls will be made to `next`. + +## Approach + +To solve the problem, we can use a straightforward approach where we maintain a pointer to keep track of the current position in the encoded array. Each call to `next` will decrement the count of the current element by the specified `n`. If the count of the current element is exhausted, we move to the next element in the encoding. + +### Steps: +1. Initialize the class with the encoded array. +2. In the `next` method, decrement the count of the current element by `n`. +3. If the count is exhausted, move to the next element. +4. Continue the process until `n` is exhausted or the array is fully traversed. +5. Return the last element exhausted or `-1` if there are no more elements. + +## Solution + +### Python +```python +class RLEIterator: + + def __init__(self, encoding: List[int]): + self.encoding = encoding + self.index = 0 + + def next(self, n: int) -> int: + while self.index < len(self.encoding): + if self.encoding[self.index] >= n: + self.encoding[self.index] -= n + return self.encoding[self.index + 1] + else: + n -= self.encoding[self.index] + self.index += 2 + return -1 +``` + +### Java +```java +class RLEIterator { + private int[] encoding; + private int index; + + public RLEIterator(int[] encoding) { + this.encoding = encoding; + this.index = 0; + } + + public int next(int n) { + while (index < encoding.length) { + if (encoding[index] >= n) { + encoding[index] -= n; + return encoding[index + 1]; + } else { + n -= encoding[index]; + index += 2; + } + } + return -1; + } +} +``` + +### C++ +```cpp +class RLEIterator { +public: + vector encoding; + int index; + + RLEIterator(vector& encoding) { + this->encoding = encoding; + this->index = 0; + } + + int next(int n) { + while (index < encoding.size()) { + if (encoding[index] >= n) { + encoding[index] -= n; + return encoding[index + 1]; + } else { + n -= encoding[index]; + index += 2; + } + } + return -1; + } +}; +``` + +### C +```c +typedef struct { + int* encoding; + int length; + int index; +} RLEIterator; + +RLEIterator* rLEIteratorCreate(int* encoding, int encodingSize) { + RLEIterator* iter = (RLEIterator*)malloc(sizeof(RLEIterator)); + iter->encoding = encoding; + iter->length = encodingSize; + iter->index = 0; + return iter; +} + +int rLEIteratorNext(RLEIterator* obj, int n) { + while (obj->index < obj->length) { + if (obj->encoding[obj->index] >= n) { + obj->encoding[obj->index] -= n; + return obj->encoding[obj->index + 1]; + } else { + n -= obj->encoding[obj->index]; + obj->index += 2; + } + } + return -1; +} + +void rLEIteratorFree(RLEIterator* obj) { + free(obj); +} +``` + +### JavaScript +```javascript +class RLEIterator { + constructor(encoding) { + this.encoding = encoding; + this.index = 0; + } + + next(n) { + while (this.index < this.encoding.length) { + if (this.encoding[this.index] >= n) { + this.encoding[this.index] -= n; + return this.encoding[this.index + 1]; + } else { + n -= this.encoding[this.index]; + this.index += 2; + } + } + return -1; + } +} +``` + +## Step by Step Algorithm + +1. Initialize the iterator with the encoded array. +2. In the `next` method, check if the current element's count is greater than or equal to `n`. +3. If true, decrement the count by `n` and return the current element. +4. If false, subtract the current count from `n`, move to the next element, and repeat the process. +5. If the end of the array is reached and `n` is still greater than 0, return `-1`. + +## Conclusion + +This problem demonstrates how to implement an iterator for a run-length encoded array. The solution involves maintaining a pointer to the current position in the encoded array and handling the decrement of counts efficiently. This approach ensures that the `next` method runs in O(1) time for each call, making it suitable for scenarios where frequent queries are made. \ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0901-stock-spanner.md b/solutions/lc-solutions/0900-0999/0901-stock-spanner.md new file mode 100644 index 0000000..7889d6d --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0901-stock-spanner.md @@ -0,0 +1,193 @@ +--- +id: stock-spanner +title: Stock Spanner +sidebar_label: 0901 - Stock Spanner +tags: + - intermediate + - stack + - monotonic stack + - algorithms + - data structures +description: "This is a solution to the Stock Spanner on LeetCode." +--- + +## Problem Description + +Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day. + +The span of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day. + +**Example:** + +If the prices of the stock in the last four days is [7,2,1,2] and the price of the stock today is 2, then the span of today is 4 because starting from today, the price of the stock was less than or equal 2 for 4 consecutive days. + +Also, if the prices of the stock in the last four days is [7,34,1,2] and the price of the stock today is 8, then the span of today is 3 because starting from today, the price of the stock was less than or equal 8 for 3 consecutive days. + +Implement the `StockSpanner` class: + +- `StockSpanner()`: Initializes the object of the class. +- `int next(int price)`: Returns the span of the stock's price given that today's price is `price`. + +### Example + +**Example 1:** + +``` +Input +["StockSpanner", "next", "next", "next", "next", "next", "next", "next"] +[[], [100], [80], [60], [70], [60], [75], [85]] +Output +[null, 1, 1, 1, 2, 1, 4, 6] + +Explanation: +StockSpanner stockSpanner = new StockSpanner(); +stockSpanner.next(100); // return 1 +stockSpanner.next(80); // return 1 +stockSpanner.next(60); // return 1 +stockSpanner.next(70); // return 2 +stockSpanner.next(60); // return 1 +stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price. +stockSpanner.next(85); // return 6 +``` + +### Constraints + +- `1 <= price <= 10^5` +- At most `10^4` calls will be made to `next`. + +## Solution Approach + +### Intuition: + +To efficiently determine the span of stock prices, we can utilize a monotonic stack. The stack will help us keep track of the days with prices less than or equal to the current day's price. + +### Algorithm: + +1. Use a stack to store pairs of `(price, span)`. +2. For each incoming price, check if the stack's top has a price less than or equal to the current price. +3. If it does, pop the stack and add the span of the popped element to the current span. +4. Push the current price and span onto the stack. +5. Return the span of the current price. + +### Complexity: + +- Time Complexity: $O(N)$, where N is the number of days. +- Space Complexity: $O(N)$, for storing prices and spans in the stack. + +## Solution Implementation + +### Code (C++): + +```cpp +#include +using namespace std; + +class StockSpanner { +private: + stack> s; + +public: + StockSpanner() {} + + int next(int price) { + int span = 1; + while (!s.empty() && s.top().first <= price) { + span += s.top().second; + s.pop(); + } + s.push({price, span}); + return span; + } +}; +``` + +### Code (Python): + +```python +class StockSpanner: + def __init__(self): + self.stack = [] + + def next(self, price: int) -> int: + span = 1 + while self.stack and self.stack[-1][0] <= price: + span += self.stack.pop()[1] + self.stack.append((price, span)) + return span + +# Example usage: +stockSpanner = StockSpanner() +print(stockSpanner.next(100)) # Output: 1 +print(stockSpanner.next(80)) # Output: 1 +print(stockSpanner.next(60)) # Output: 1 +print(stockSpanner.next(70)) # Output: 2 +print(stockSpanner.next(60)) # Output: 1 +print(stockSpanner.next(75)) # Output: 4 +print(stockSpanner.next(85)) # Output: 6 +``` + +### Code (Java): + +```java +import java.util.Stack; + +class StockSpanner { + private Stack stack; + + public StockSpanner() { + stack = new Stack<>(); + } + + public int next(int price) { + int span = 1; + while (!stack.isEmpty() && stack.peek()[0] <= price) { + span += stack.pop()[1]; + } + stack.push(new int[]{price, span}); + return span; + } + + public static void main(String[] args) { + StockSpanner stockSpanner = new StockSpanner(); + System.out.println(stockSpanner.next(100)); // Output: 1 + System.out.println(stockSpanner.next(80)); // Output: 1 + System.out.println(stockSpanner.next(60)); // Output: 1 + System.out.println(stockSpanner.next(70)); // Output: 2 + System.out.println(stockSpanner.next(60)); // Output: 1 + System.out.println(stockSpanner.next(75)); // Output: 4 + System.out.println(stockSpanner.next(85)); // Output: 6 + } +} +``` + +### Code (JavaScript): + +```javascript +class StockSpanner { + constructor() { + this.stack = []; + } + + next(price) { + let span = 1; + while ( + this.stack.length > 0 && + this.stack[this.stack.length - 1][0] <= price + ) { + span += this.stack.pop()[1]; + } + this.stack.push([price, span]); + return span; + } +} + +// Example usage: +const stockSpanner = new StockSpanner(); +console.log(stockSpanner.next(100)); // Output: 1 +console.log(stockSpanner.next(80)); // Output: 1 +console.log(stockSpanner.next(60)); // Output: 1 +console.log(stockSpanner.next(70)); // Output: 2 +console.log(stockSpanner.next(60)); // Output: 1 +console.log(stockSpanner.next(75)); // Output: 4 +console.log(stockSpanner.next(85)); // Output: 6 +``` diff --git a/solutions/lc-solutions/0900-0999/0902-numbers-at-most-n-given-digit-set.md b/solutions/lc-solutions/0900-0999/0902-numbers-at-most-n-given-digit-set.md new file mode 100644 index 0000000..fe2e1e2 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0902-numbers-at-most-n-given-digit-set.md @@ -0,0 +1,369 @@ +--- +id: numbers-at-most-n-given-digit-set +title: Numbers At Most N Given Digit Set +sidebar_label: 0902 - Numbers At Most N Given Digit Set +tags: + - Dynamic Programming + - Recursion + - Math +description: "This is a solution to the Numbers At Most N Given Digit Set problem on LeetCode." +--- + +## Problem Description + +Given an array of digits which is sorted in **non-decreasing** order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`. + +Return the number of positive integers that can be generated that are less than or equal to a given integer `n`. + +### Examples + +**Example 1:** + +``` +Input: digits = ["1","3","5","7"], n = 100 +Output: 20 +Explanation: +The 20 numbers that can be written are: +1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. +``` +**Example 2:** + +``` +Input: digits = ["1","4","9"], n = 1000000000 +Output: 29523 +Explanation: +We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, +81 four digit numbers, 243 five digit numbers, 729 six digit numbers, +2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. +In total, this is 29523 integers that can be written using the digits array. +``` + +### Constraints + +- `1 <= digits.length <= 9` +- `digits[i].length == 1` +- `digits[i]` is a digit from `'1'` to `'9'`. +- All the values in digits are **unique**. +- digits is sorted in **non-decreasing** order. +- $1 \leq n \leq 10^9$ + +## Solution for Numbers At Most N Given Digit Set + +## Approach 1: Dynamic Programming + Counting +### Intuition + +First, call a positive integer `X` valid if `X <= N` and `X` only consists of digits from `D`. Our goal is to find the number of valid integers. + +Say `N` has `K` digits. If we write a valid number with `k` digits (`k < K`), then there are $(D.length)^k$ possible numbers we could write, since all of them will definitely be less than `N`. + +Now, say we are to write a valid `K` digit number from left to right. For example, `N = 2345`, `K = 4`, and `D = '1', '2', ..., '9'`. Let's consider what happens when we write the first digit. + +- If the first digit we write is less than the first digit of N, then we could write any numbers after, for a total of $(D.length)^{K-1}$ valid numbers from this one-digit prefix. In our example, if we start with `1`, we could write any of the numbers `1111` to `1999` from this prefix. + +- If the first digit we write is the same, then we require that the next digit we write is equal to or lower than the next digit in `N`. In our example (with `N = 2345`), if we start with `2`, the next digit we write must be `3` or less. + +- We can't write a larger digit, because if we started with eg. `3`, then even a number of `3000` is definitely larger than `N`. + +### Algorithm + +Let `dp[i]` be the number of ways to write a valid number if `N` became `N[i], N[i+1], ....` For example, if `N = 2345`, then `dp[0]` would be the number of valid numbers at most `2345`, `dp[1]` would be the ones at most `345`, `dp[2]` would be the ones at most `45`, and `dp[3]` would be the ones at most `5`. + +Then, by our reasoning above, `dp[i] = (number of d in D with d < S[i]) * ((D.length) ** (K-i-1))`, plus `dp[i+1]` if `S[i]` is in `D`. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int atMostNGivenDigitSet(vector& D, int N) { + string S = to_string(N); + int K = S.length(); + vector dp(K+1, 0); + dp[K] = 1; + + for (int i = K-1; i >= 0; --i) { + // compute dp[i] + int Si = S[i] - '0'; + for (const string& d : D) { + if (stoi(d) < Si) + dp[i] += pow(D.size(), K-i-1); + else if (stoi(d) == Si) + dp[i] += dp[i+1]; + } + } + + for (int i = 1; i < K; ++i) + dp[0] += pow(D.size(), i); + return dp[0]; + } +}; + +``` + + + + +```java +class Solution { + public int atMostNGivenDigitSet(String[] D, int N) { + String S = String.valueOf(N); + int K = S.length(); + int[] dp = new int[K+1]; + dp[K] = 1; + + for (int i = K-1; i >= 0; --i) { + // compute dp[i] + int Si = S.charAt(i) - '0'; + for (String d: D) { + if (Integer.valueOf(d) < Si) + dp[i] += Math.pow(D.length, K-i-1); + else if (Integer.valueOf(d) == Si) + dp[i] += dp[i+1]; + } + } + + for (int i = 1; i < K; ++i) + dp[0] += Math.pow(D.length, i); + return dp[0]; + } +} +``` + + + + + +```python +class Solution: + def atMostNGivenDigitSet(self, D, N): + S = str(N) + K = len(S) + dp = [0] * K + [1] + # dp[i] = total number of valid integers if N was "N[i:]" + + for i in xrange(K-1, -1, -1): + # Compute dp[i] + + for d in D: + if d < S[i]: + dp[i] += len(D) ** (K-i-1) + elif d == S[i]: + dp[i] += dp[i+1] + + return dp[0] + sum(len(D) ** i for i in xrange(1, K)) +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(logN)$ + +> **Reason**: and assuming `D.length` is constant. (We could make this better by pre-calculating the number of `d < S[i]` for all possible digits `S[i]`, but this isn't necessary.) + +#### Space Complexity: $O(logN)$ + +> **Reason**: the space used by `S` and `dp`. (Actually, we could store only the last 2 entries of `dp`, but this isn't necessary.) + +## Approach 2: Mathematical +### Intuition + +As in Approach 1, call a positive integer `X` valid if `X <= N` and `X` only consists of digits from `D`. + +Now let `B = D.length`. There is a bijection between valid integers and so called "bijective-base-`B`" numbers. For example, if `D = ['1', '3', '5', '7']`, then we could write the numbers `'1', '3', '5', '7', '11', '13', '15', '17', '31', ...` as (bijective-base-`B`) numbers `'1', '2', '3', '4', '11', '12', '13', '14', '21', ....` + +It is clear that both of these sequences are increasing, which means that the first sequence is a contiguous block of valid numbers, followed by invalid numbers. + +Our approach is to find the largest valid integer, and convert it into bijective-base-`B` from which it is easy to find its rank (position in the sequence.) Because of the bijection, the rank of this element must be the number of valid integers. + +Continuing our example, if `N = 64`, then the valid numbers are `'1', '3', ..., '55', '57'`, which can be written as bijective-base-4 numbers `'1', '2', ..., '33', '34'`. Converting this last entry `'34'` to decimal, the answer is `16` (3 * 4 + 4). + +### Algorithm + +Let's convert `N` into the largest possible valid integer `X`, convert `X` to bijective-base-B, then convert that result to a decimal answer. The last two conversions are relatively straightforward, so let's focus on the first part of the task. + +Let's try to write `X` one digit at a time. Let's walk through an example where `D = ['2', '4', '6', '8']`. There are some cases: + +- If the first digit of `N` is in `D`, we write that digit and continue. For example, if `N = 25123`, then we will write `2` and continue. + +- If the first digit of `N` is larger than `min(D)`, then we write the largest possible number from `D` less than that digit, and the rest of the numbers will be big. For example, if `N = 5123`, then we will write `4888` (`4` then `888`). + +- If the first digit of `N` is smaller than `min(D)`, then we must "subtract 1" (in terms of `X`'s bijective-base-B representation), and the rest of the numbers will be big. + + For example, if `N = 123, we will write `88`. If `N = 4123`, we will write `2888`. And if `N = 22123`, we will write `8888`. This is because "subtracting 1" from `'', '4', '22'` yields `'', '2', '8'` (can't go below 0). + +Actually, in our solution, it is easier to write in bijective-base-B, so instead of writing digits of `D`, we'll write the index of those digits (1-indexed). For example, `X = 24888` will be `A = [1, 2, 4, 4, 4]`. Afterwards, we convert this to decimal. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int atMostNGivenDigitSet(vector& D, int N) { + int B = D.size(); // bijective-base B + string s = to_string(N); + int K = s.length(); + vector A(K, 0); + int t = 0; + + for (char c : s) { + int c_index = 0; // Largest such that c >= D[c_index - 1] + bool match = false; + for (int i = 0; i < B; ++i) { + if (c >= D[i][0]) + c_index = i+1; + if (c == D[i][0]) + match = true; + } + + A[t++] = c_index; + if (match) continue; + + if (c_index == 0) { // subtract 1 + for (int j = t-1; j > 0; --j) { + if (A[j] > 0) break; + A[j] += B; + A[j-1]--; + } + } + + while (t < K) + A[t++] = B; + break; + } + + int ans = 0; + for (int x : A) + ans = ans * B + x; + return ans; + } +}; + +``` + + + + +```java +class Solution { + public int atMostNGivenDigitSet(String[] D, int N) { + int B = D.length; // bijective-base B + char[] ca = String.valueOf(N).toCharArray(); + int K = ca.length; + int[] A = new int[K]; + int t = 0; + + for (char c: ca) { + int c_index = 0; // Largest such that c >= D[c_index - 1] + boolean match = false; + for (int i = 0; i < B; ++i) { + if (c >= D[i].charAt(0)) + c_index = i+1; + if (c == D[i].charAt(0)) + match = true; + } + + A[t++] = c_index; + if (match) continue; + + if (c_index == 0) { // subtract 1 + for (int j = t-1; j > 0; --j) { + if (A[j] > 0) break; + A[j] += B; + A[j-1]--; + } + } + + while (t < K) + A[t++] = B; + break; + } + + int ans = 0; + for (int x: A) + ans = ans * B + x; + return ans; + } +} +``` + + + + + +```python +class Solution(object): + def atMostNGivenDigitSet(self, D, N): + B = len(D) # bijective-base B + S = str(N) + K = len(S) + A = [] # The largest valid number in bijective-base-B. + + for c in S: + if c in D: + A.append(D.index(c) + 1) + else: + i = bisect.bisect(D, c) + A.append(i) + # i = 1 + (largest index j with c >= D[j], or -1 if impossible) + if i == 0: + # subtract 1 + for j in xrange(len(A) - 1, 0, -1): + if A[j]: break + A[j] += B + A[j-1] -= 1 + + A.extend([B] * (K - len(A))) + break + + ans = 0 + for x in A: + ans = ans * B + x + return ans +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(logN)$ + +> **Reason**: and assuming `D.length` is constant. + + +#### Space Complexity: $O(logN)$ + +> **Reason**: the space used by `A`. + +## Video Solution + + + +## References + +- **LeetCode Problem**: [Numbers At Most N Given Digit Set](https://leetcode.com/problems/numbers-at-most-n-given-digit-set/description/) + +- **Solution Link**: [Numbers At Most N Given Digit Set](https://leetcode.com/problems/numbers-at-most-n-given-digit-set/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0903-Valid-Permutations-for-DI-Sequence.md b/solutions/lc-solutions/0900-0999/0903-Valid-Permutations-for-DI-Sequence.md new file mode 100644 index 0000000..bc4c505 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0903-Valid-Permutations-for-DI-Sequence.md @@ -0,0 +1,244 @@ +--- +id: Valid Permutations for DI Sequence +title: Valid Permutations for DI Sequence +sidebar_label: Valid-Permutations-for-DI-Sequence +tags: + - Permutations + - Algorithm + - Dynamic Programming +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Valid-Permutations-for-DI-Sequence](https://leetcode.com/problems/Valid-Permutations-for-DI-Sequence/description/) | [Valid-Permutations-for-DI-Sequence Solution on LeetCode](https://leetcode.com/problems/Valid-Permutations-for-DI-Sequence/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +You are given a string `s` of length `n` where `s[i]` is either: +- `'D'` means decreasing, or +- `'I'` means increasing. + +A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` is called a valid permutation if for all valid `i`: +- If `s[i] == 'D'`, then `perm[i] > perm[i + 1]`, and +- If `s[i] == 'I'`, then `perm[i] < perm[i + 1]`. + +Return the number of valid permutations `perm`. Since the answer may be large, return it modulo `10^9 + 7`. + +## Constraints + +- `n == s.length` +- `1 <= n <= 200` +- `s[i]` is either `'I'` or `'D'`. + +## Example + +## Example 1: +**Input:** `s = "DID"` +**Output:** `5` + +## Example 2: +**Input:** `s = "D"` +**Output:** `1` + +## Approach + +To solve this problem, we can use dynamic programming to count the number of valid permutations that satisfy the given constraints. We'll use a 2D DP array where `dp[i][j]` represents the number of valid permutations of length `i+1` ending with the integer `j`. + +The transitions are based on the character `'D'` or `'I'` in the input string `s`. + +## Step-by-Step Algorithm + +1. Initialize a DP array `dp` with dimensions `(n+1) x (n+1)` to store the number of valid permutations. +2. Set the base case: `dp[0][j] = 1` for all `j` from `0` to `n`. +3. Iterate through the string `s` and fill the DP array based on the transitions: + - If `s[i] == 'I'`, calculate the cumulative sum from the previous row for increasing sequences. + - If `s[i] == 'D'`, calculate the cumulative sum from the previous row for decreasing sequences. +4. Sum up all values in the last row of the DP array to get the result. +5. Return the result modulo `10^9 + 7`. + +## Solution + +### Python +```python +MOD = 10**9 + 7 + +def numPermsDISequence(s: str) -> int: + n = len(s) + dp = [[0] * (n + 1) for _ in range(n + 1)] + + for j in range(n + 1): + dp[0][j] = 1 + + for i in range(1, n + 1): + if s[i - 1] == 'I': + cum_sum = 0 + for j in range(n + 1): + cum_sum = (cum_sum + dp[i - 1][j]) % MOD + dp[i][j] = cum_sum + else: # s[i - 1] == 'D' + cum_sum = 0 + for j in range(n, -1, -1): + cum_sum = (cum_sum + dp[i - 1][j]) % MOD + dp[i][j] = cum_sum + + return sum(dp[n]) % MOD +``` + +### Java +```java +public class ValidPermutations { + public int numPermsDISequence(String s) { + int n = s.length(); + int MOD = 1000000007; + int[][] dp = new int[n + 1][n + 1]; + + for (int j = 0; j <= n; j++) { + dp[0][j] = 1; + } + + for (int i = 1; i <= n; i++) { + if (s.charAt(i - 1) == 'I') { + int cumSum = 0; + for (int j = 0; j <= n; j++) { + cumSum = (cumSum + dp[i - 1][j]) % MOD; + dp[i][j] = cumSum; + } + } else { + int cumSum = 0; + for (int j = n; j >= 0; j--) { + cumSum = (cumSum + dp[i - 1][j]) % MOD; + dp[i][j] = cumSum; + } + } + } + + int result = 0; + for (int j = 0; j <= n; j++) { + result = (result + dp[n][j]) % MOD; + } + + return result; + } +} +``` + +### C++ +```cpp +#include +#include +using namespace std; + +class Solution { +public: + int numPermsDISequence(string s) { + int n = s.length(); + int MOD = 1000000007; + vector> dp(n + 1, vector(n + 1, 0)); + + for (int j = 0; j <= n; j++) { + dp[0][j] = 1; + } + + for (int i = 1; i <= n; i++) { + if (s[i - 1] == 'I') { + int cumSum = 0; + for (int j = 0; j <= n; j++) { + cumSum = (cumSum + dp[i - 1][j]) % MOD; + dp[i][j] = cumSum; + } + } else { + int cumSum = 0; + for (int j = n; j >= 0; j--) { + cumSum = (cumSum + dp[i - 1][j]) % MOD; + dp[i][j] = cumSum; + } + } + } + + int result = 0; + for (int j = 0; j <= n; j++) { + result = (result + dp[n][j]) % MOD; + } + + return result; + } +}; +``` + +### C +```c +#include + +#define MOD 1000000007 + +int numPermsDISequence(char * s){ + int n = strlen(s); + int dp[n + 1][n + 1]; + + for (int j = 0; j <= n; j++) { + dp[0][j] = 1; + } + + for (int i = 1; i <= n; i++) { + if (s[i - 1] == 'I') { + int cumSum = 0; + for (int j = 0; j <= n; j++) { + cumSum = (cumSum + dp[i - 1][j]) % MOD; + dp[i][j] = cumSum; + } + } else { + int cumSum = 0; + for (int j = n; j >= 0; j--) { + cumSum = (cumSum + dp[i - 1][j]) % MOD; + dp[i][j] = cumSum; + } + } + } + + int result = 0; + for (int j = 0; j <= n; j++) { + result = (result + dp[n][j]) % MOD; + } + + return result; +} +``` + +### JavaScript +```javascript +var numPermsDISequence = function(s) { + const MOD = 10**9 + 7; + const n = s.length; + const dp = Array.from({length: n + 1}, () => Array(n + 1).fill(0)); + + for (let j = 0; j <= n; j++) { + dp[0][j] = 1; + } + + for (let i = 1; i <= n; i++) { + if (s[i - 1] === 'I') { + let cumSum = 0; + for (let j = 0; j <= n; j++) { + cumSum = (cumSum + dp[i - 1][j]) % MOD; + dp[i][j] = cumSum; + } + } else { + let cumSum = 0; + for (let j = n; j >= 0; j--) { + cumSum = (cumSum + dp[i - 1][j]) % MOD; + dp[i][j] = cumSum; + } + } + } + + return dp[n].reduce((acc, val) => (acc + val) % MOD, 0); +}; +``` + +## Conclusion + +This problem can be efficiently solved using dynamic programming by constructing a 2D DP array to keep track of valid permutations. The provided solutions in various programming languages demonstrate + + the approach and implementation details to achieve the desired result. The main challenge lies in understanding the transitions and correctly calculating cumulative sums based on the constraints imposed by the characters `'D'` and `'I'` in the input string. \ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0904-Fruits-Into-Baskets.md b/solutions/lc-solutions/0900-0999/0904-Fruits-Into-Baskets.md new file mode 100644 index 0000000..5549f96 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0904-Fruits-Into-Baskets.md @@ -0,0 +1,211 @@ +--- +id: Fruits-Into-Baskets +title: Fruits-Into-Baskets +sidebar_label: Fruits-Into-Baskets +tags: + - Array + - Sliding Window + - Two Baskets +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Fruits-Into-Baskets](https://leetcode.com/problems/fruit-into-baskets/description/) | [Fruits-Into-Baskets Solution on LeetCode](https://leetcode.com/problems/fruit-into-baskets/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the type of fruit the ith tree produces. + +You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: + +- You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold. +- Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. +- Once you reach a tree with fruit that cannot fit in your baskets, you must stop. + +Given the integer array `fruits`, return the maximum number of fruits you can pick. + +## Example 1 + +**Input:** `fruits = [1, 2, 1]` +**Output:** `3` +**Explanation:** `We can pick from all 3 trees.` + +## Example 2 + +**Input:** `fruits = [0, 1, 2, 2]` +**Output:** `3` +**Explanation:** `We can pick from trees [1, 2, 2]. If we had started at the first tree, we would only pick from trees [0, 1].` + +## Example 3 + +**Input:** `fruits = [1, 2, 3, 2, 2]` +**Output:** `4` +**Explanation:** `We can pick from trees [2, 3, 2, 2]. If we had started at the first tree, we would only pick from trees [1, 2].` + +## Constraints + +- `1 <= fruits.length <= 10^5` +- `0 <= fruits[i] < fruits.length` + +## Approach + +We can solve this problem using the sliding window technique. The idea is to maintain a window that contains at most two types of fruits. We move the right end of the window to the right, adding fruits to our baskets. If we encounter a third type of fruit, we move the left end of the window to the right until we have only two types of fruits again. + +## Solution + +### Python + +```python +def totalFruit(fruits): + basket = {} + left = 0 + max_fruits = 0 + + for right in range(len(fruits)): + basket[fruits[right]] = basket.get(fruits[right], 0) + 1 + + while len(basket) > 2: + basket[fruits[left]] -= 1 + if basket[fruits[left]] == 0: + del basket[fruits[left]] + left += 1 + + max_fruits = max(max_fruits, right - left + 1) + + return max_fruits +``` + +### Java + +```java +import java.util.HashMap; + +public class MaxFruitPicking { + public int totalFruit(int[] fruits) { + HashMap basket = new HashMap<>(); + int left = 0, maxFruits = 0; + + for (int right = 0; right < fruits.length; right++) { + basket.put(fruits[right], basket.getOrDefault(fruits[right], 0) + 1); + + while (basket.size() > 2) { + basket.put(fruits[left], basket.get(fruits[left]) - 1); + if (basket.get(fruits[left]) == 0) { + basket.remove(fruits[left]); + } + left++; + } + + maxFruits = Math.max(maxFruits, right - left + 1); + } + + return maxFruits; + } +} +``` + +### C++ + +```cpp +#include +#include +#include + +class Solution { +public: + int totalFruit(std::vector& fruits) { + std::unordered_map basket; + int left = 0, maxFruits = 0; + + for (int right = 0; right < fruits.size(); right++) { + basket[fruits[right]]++; + + while (basket.size() > 2) { + basket[fruits[left]]--; + if (basket[fruits[left]] == 0) { + basket.erase(fruits[left]); + } + left++; + } + + maxFruits = std::max(maxFruits, right - left + 1); + } + + return maxFruits; + } +}; +``` + +### C + +```c +#include +#include + +int totalFruit(int* fruits, int fruitsSize) { + int* basket = (int*)calloc(fruitsSize, sizeof(int)); + int left = 0, maxFruits = 0, basketCount = 0; + + for (int right = 0; right < fruitsSize; right++) { + if (basket[fruits[right]]++ == 0) { + basketCount++; + } + + while (basketCount > 2) { + if (--basket[fruits[left]] == 0) { + basketCount--; + } + left++; + } + + maxFruits = maxFruits > (right - left + 1) ? maxFruits : (right - left + 1); + } + + free(basket); + return maxFruits; +} +``` + +### JavaScript + +```javascript +var totalFruit = function(fruits) { + let basket = new Map(); + let left = 0; + let maxFruits = 0; + + for (let right = 0; right < fruits.length; right++) { + basket.set(fruits[right], (basket.get(fruits[right]) || 0) + 1); + + while (basket.size > 2) { + basket.set(fruits[left], basket.get(fruits[left]) - 1); + if (basket.get(fruits[left]) === 0) { + basket.delete(fruits[left]); + } + left++; + } + + maxFruits = Math.max(maxFruits, right - left + 1); + } + + return maxFruits; +}; +``` + +## Step-by-Step Algorithm + +1. Initialize a dictionary or hashmap to keep track of the count of each type of fruit in the current window. +2. Initialize two pointers, `left` and `right`, both set to the start of the array. +3. Initialize a variable `max_fruits` to store the maximum number of fruits collected. +4. Iterate through the array using the `right` pointer. +5. Add the fruit at the `right` pointer to the dictionary and update its count. +6. If the dictionary contains more than two types of fruits, move the `left` pointer to the right until only two types of fruits are in the dictionary. +7. Update `max_fruits` with the maximum value between `max_fruits` and the current window size (`right - left + 1`). +8. Continue iterating until the end of the array. +9. Return `max_fruits`. + +## Conclusion + +This problem can be efficiently solved using the sliding window technique. By maintaining a window that contains at most two types of fruits and adjusting the window size as needed, we can find the maximum number of fruits that can be collected. This approach ensures that the solution is optimal and runs in linear time. \ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0904-fruit-into-baskets.md b/solutions/lc-solutions/0900-0999/0904-fruit-into-baskets.md new file mode 100644 index 0000000..cfd6097 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0904-fruit-into-baskets.md @@ -0,0 +1,200 @@ +--- +id: Fruit-Into-Baskets +title: Fruit Into Baskets +sidebar_label: 0904 - Fruit Into Baskets +tags: + - intermediate + - Sliding Window + - Two Pointers + - Arrays + - Fruits + - Algorithms +--- + +## Problem Description + +You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces. + +You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: + +You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold. +Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. +Once you reach a tree with fruit that cannot fit in your baskets, you must stop. +Given the integer array fruits, return the maximum number of fruits you can pick. + +## Examples + +**Example 1:** + +``` +Input: fruits = [1,2,1] +Output: 3 +Explanation: We can pick from all 3 trees. +``` + +**Example 2:** + +``` +Input: fruits = [0,1,2,2] +Output: 3 +Explanation: We can pick from trees [1,2,2]. +If we had started at the first tree, we would only pick from trees [0,1]. +``` + +**Example 3:** + +``` +Input: fruits = [1,2,3,2,2] +Output: 4 +Explanation: We can pick from trees [2,3,2,2]. +If we had started at the first tree, we would only pick from trees [1,2]. +``` + +## Your Task + +You don't need to read input or print anything. Your task is to complete the function `totalFruit()` which takes an integer array `fruits` as input parameter and returns the maximum number of fruits you can pick. + +## Constraints + +``` +1 <= fruits.length <= 10^5 +0 <= fruits[i] <= fruits.length +``` + +## Solution Approach + +### Sliding Window Approach + +#### Intuition: + +We can use a sliding window approach to keep track of the two types of fruits. We expand the window by adding fruits to the baskets until we encounter a third type of fruit. At that point, we shrink the window from the left until we only have two types of fruits. + +#### Implementation: + +1. Use a dictionary to count the number of each type of fruit in the current window. +2. Use two pointers to represent the left and right boundaries of the window. +3. Expand the right pointer to include more fruits in the window. +4. When the window contains more than two types of fruits, move the left pointer to reduce the window size until only two types remain. +5. Keep track of the maximum window size encountered. + +#### Code (Python): + +```python +class Solution: + def totalFruit(self, fruits): + basket = {} + left = 0 + max_fruits = 0 + for right in range(len(fruits)): + basket[fruits[right]] = basket.get(fruits[right], 0) + 1 + while len(basket) > 2: + basket[fruits[left]] -= 1 + if basket[fruits[left]] == 0: + del basket[fruits[left]] + left += 1 + max_fruits = max(max_fruits, right - left + 1) + return max_fruits + +# Example usage: +solution = Solution() +print(solution.totalFruit([1,2,1])) # Output: 3 +``` + +#### Code (C++): + +```cpp +#include +#include +#include +using namespace std; + +class Solution { +public: + int totalFruit(vector& fruits) { + unordered_map basket; + int left = 0, max_fruits = 0; + for (int right = 0; right < fruits.size(); ++right) { + basket[fruits[right]]++; + while (basket.size() > 2) { + basket[fruits[left]]--; + if (basket[fruits[left]] == 0) { + basket.erase(fruits[left]); + } + left++; + } + max_fruits = max(max_fruits, right - left + 1); + } + return max_fruits; + } +}; + +// Example usage: +int main() { + Solution solution; + vector fruits = {1, 2, 1}; + int result = solution.totalFruit(fruits); // Output: 3 + return 0; +} +``` + +#### Code (Java): + +```java +import java.util.HashMap; +import java.util.Map; + +class Solution { + public int totalFruit(int[] fruits) { + Map basket = new HashMap<>(); + int left = 0, maxFruits = 0; + for (int right = 0; right < fruits.length; ++right) { + basket.put(fruits[right], basket.getOrDefault(fruits[right], 0) + 1); + while (basket.size() > 2) { + basket.put(fruits[left], basket.get(fruits[left]) - 1); + if (basket.get(fruits[left]) == 0) { + basket.remove(fruits[left]); + } + left++; + } + maxFruits = Math.max(maxFruits, right - left + 1); + } + return maxFruits; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + int[] fruits = {1, 2, 1}; + System.out.println(solution.totalFruit(fruits)); // Output: 3 + } +} +``` + +#### Code (JavaScript): + +```javascript +var totalFruit = function (fruits) { + let basket = new Map(); + let left = 0, + maxFruits = 0; + for (let right = 0; right < fruits.length; ++right) { + basket.set(fruits[right], (basket.get(fruits[right]) || 0) + 1); + while (basket.size > 2) { + basket.set(fruits[left], basket.get(fruits[left]) - 1); + if (basket.get(fruits[left]) === 0) { + basket.delete(fruits[left]); + } + left++; + } + maxFruits = Math.max(maxFruits, right - left + 1); + } + return maxFruits; +}; + +// Example usage: +console.log(totalFruit([1, 2, 1])); // Output: 3 +``` + +#### Complexity: + +- **Time Complexity:** $O(n)$, where $n$ is the length of the input array `fruits`. We traverse the array once with the two pointers. +- **Space Complexity:** $O(1)$, since the dictionary or map will hold at most three keys at any time. diff --git a/solutions/lc-solutions/0900-0999/0905-Sort-Array-By-Parity.md b/solutions/lc-solutions/0900-0999/0905-Sort-Array-By-Parity.md new file mode 100644 index 0000000..4278ec3 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0905-Sort-Array-By-Parity.md @@ -0,0 +1,188 @@ +--- +id: Sort-Array-By-Parity +title: Sort Array By Parity +sidebar_label: Sort Array By Parity +tags: + - Arrays + - Sorting +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :-------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------- | :--------------------------------------------------- | +| [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/description/) | [Sort Array By Parity Solution on LeetCode](https://leetcode.com/problems/sort-array-by-parity/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers. + +Return any array that satisfies this condition. + +### Example 1: + +**Input:** `nums = [3, 1, 2, 4]` +**Output:** `[2, 4, 3, 1]` +**Explanation:** The outputs `[4, 2, 3, 1]`, `[2, 4, 1, 3]`, and `[4, 2, 1, 3]` would also be accepted. + +### Example 2: + +**Input:** `nums = [0]` +**Output:** `[0]` + +## Constraints + +- `1 <= nums.length <= 5000` +- `0 <= nums[i] <= 5000` + +## Approach + +1. **Identify even and odd integers**: Iterate through the array and separate the even and odd integers. +2. **Rearrange the array**: Place all even integers at the beginning of the array followed by the odd integers. + +## Solution + +### Python + +```python +def sortArrayByParity(nums): + even = [x for x in nums if x % 2 == 0] + odd = [x for x in nums if x % 2 != 0] + return even + odd + +# Example usage +nums = [3, 1, 2, 4] +print(sortArrayByParity(nums)) # Output: [2, 4, 3, 1] +``` + +### Java + +```java +import java.util.*; + +public class EvenOddArray { + public static int[] sortArrayByParity(int[] nums) { + List even = new ArrayList<>(); + List odd = new ArrayList<>(); + + for (int num : nums) { + if (num % 2 == 0) { + even.add(num); + } else { + odd.add(num); + } + } + + even.addAll(odd); + return even.stream().mapToInt(i -> i).toArray(); + } + + public static void main(String[] args) { + int[] nums = {3, 1, 2, 4}; + System.out.println(Arrays.toString(sortArrayByParity(nums))); // Output: [2, 4, 3, 1] + } +} +``` + +### C++ + +```cpp +#include +#include + +std::vector sortArrayByParity(std::vector& nums) { + std::vector even, odd; + for (int num : nums) { + if (num % 2 == 0) { + even.push_back(num); + } else { + odd.push_back(num); + } + } + even.insert(even.end(), odd.begin(), odd.end()); + return even; +} + +int main() { + std::vector nums = {3, 1, 2, 4}; + std::vector result = sortArrayByParity(nums); + for (int num : result) { + std::cout << num << " "; + } + // Output: 2 4 3 1 +} +``` + +### C + +```c +#include +#include + +void sortArrayByParity(int* nums, int numsSize, int* returnSize) { + int* result = (int*)malloc(numsSize * sizeof(int)); + int evenIndex = 0, oddIndex = numsSize - 1; + + for (int i = 0; i < numsSize; ++i) { + if (nums[i] % 2 == 0) { + result[evenIndex++] = nums[i]; + } else { + result[oddIndex--] = nums[i]; + } + } + *returnSize = numsSize; + for (int i = 0; i < numsSize; ++i) { + nums[i] = result[i]; + } + free(result); +} + +int main() { + int nums[] = {3, 1, 2, 4}; + int numsSize = sizeof(nums) / sizeof(nums[0]); + int returnSize; + sortArrayByParity(nums, numsSize, &returnSize); + + for (int i = 0; i < numsSize; ++i) { + printf("%d ", nums[i]); + } + // Output: 2 4 3 1 + return 0; +} +``` + +### JavaScript + +```javascript +function sortArrayByParity(nums) { + let even = []; + let odd = []; + + for (let num of nums) { + if (num % 2 === 0) { + even.push(num); + } else { + odd.push(num); + } + } + + return [...even, ...odd]; +} + +// Example usage +let nums = [3, 1, 2, 4]; +console.log(sortArrayByParity(nums)); // Output: [2, 4, 3, 1] +``` + +## Step-by-Step Algorithm + +1. Initialize two empty lists/arrays: one for even integers and one for odd integers. +2. Iterate through the given array: + - If the current integer is even, add it to the even list/array. + - If the current integer is odd, add it to the odd list/array. +3. Concatenate the even list/array with the odd list/array. +4. Return the concatenated list/array. + +## Conclusion + +This problem can be solved efficiently by iterating through the array once and separating the integers into even and odd lists/arrays. The time complexity is O(n), where n is the length of the array, making this approach optimal for the given constraints. diff --git a/solutions/lc-solutions/0900-0999/0906-Super-Palindromes.md b/solutions/lc-solutions/0900-0999/0906-Super-Palindromes.md new file mode 100644 index 0000000..bdc4109 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0906-Super-Palindromes.md @@ -0,0 +1,248 @@ +--- +id: super-palindromes +title: Super Palindromes +sidebar_label: Super Palindromes +tags: + - Palindrome + - Math +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :-------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------- | :--------------------------------------------------- | +| [Super Palindromes](https://leetcode.com/problems/super-palindromes/description/) | [Super Palindromes Solution on LeetCode](https://leetcode.com/problems/super-palindromes/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome. + +Given two positive integers `left` and `right` represented as strings, return the number of super-palindromes integers in the inclusive range `[left, right]`. + +### Examples + +**Example 1:** + +**Input:** `left = "4" right = "1000"` +**Output:** `4` +**Explanation:** `4, 9, 121, and 484 are super-palindromes. Note that 676 is not a super-palindrome: 26 * 26 = 676, but 26 is not a palindrome.` + +**Example 2:** + +**Input:** `left = "1" right = "2"` +**Output:** `1` + +### Constraints + +- `1 <= left.length, right.length <= 18` +- `left` and `right` consist of only digits. +- `left` and `right` cannot have leading zeros. +- `left` and `right` represent integers in the range `[1, 10^18 - 1]`. +- `left` is less than or equal to `right`. + +## Approach + +To solve this problem, we need to: + +1. **Generate Palindromes:** Generate all palindromes that are within the possible square roots of the range `[left, right]`. +2. **Square Palindromes:** For each generated palindrome, compute its square and check if it is a palindrome. +3. **Count Super-Palindromes:** Count how many of these squared palindromes fall within the given range `[left, right]`. + +## Solution + +### Python + +```python +import math + +def is_palindrome(s): + return s == s[::-1] + +def super_palindromes(left, right): + left, right = int(left), int(right) + count = 0 + limit = int(math.sqrt(right)) + 1 + + for i in range(1, limit): + s = str(i) + pal = s + s[::-1] + num = int(pal) ** 2 + if num > right: + break + if num >= left and is_palindrome(str(num)): + count += 1 + + pal = s + s[-2::-1] + num = int(pal) ** 2 + if num > right: + break + if num >= left and is_palindrome(str(num)): + count += 1 + + return count +``` + +### Java + +```java +public class SuperPalindromes { + private static boolean isPalindrome(String s) { + int left = 0, right = s.length() - 1; + while (left < right) { + if (s.charAt(left) != s.charAt(right)) return false; + left++; + right--; + } + return true; + } + + public static int superPalindromes(String left, String right) { + long l = Long.parseLong(left), r = Long.parseLong(right); + int count = 0; + long limit = (long) Math.sqrt(r) + 1; + + for (long i = 1; i < limit; i++) { + String s = Long.toString(i); + String pal1 = s + new StringBuilder(s).reverse().toString(); + long num1 = Long.parseLong(pal1) * Long.parseLong(pal1); + if (num1 > r) break; + if (num1 >= l && isPalindrome(Long.toString(num1))) count++; + + String pal2 = s + new StringBuilder(s.substring(0, s.length() - 1)).reverse().toString(); + long num2 = Long.parseLong(pal2) * Long.parseLong(pal2); + if (num2 > r) break; + if (num2 >= l && isPalindrome(Long.toString(num2))) count++; + } + + return count; + } +} +``` + +### C++ + +```cpp +#include +#include +#include + +bool isPalindrome(const std::string& s) { + return std::equal(s.begin(), s.begin() + s.size() / 2, s.rbegin()); +} + +int superPalindromes(std::string left, std::string right) { + long long l = std::stoll(left), r = std::stoll(right); + int count = 0; + long long limit = static_cast(std::sqrt(r)) + 1; + + for (long long i = 1; i < limit; i++) { + std::string s = std::to_string(i); + std::string pal1 = s + std::string(s.rbegin(), s.rend()); + long long num1 = std::stoll(pal1) * std::stoll(pal1); + if (num1 > r) break; + if (num1 >= l && isPalindrome(std::to_string(num1))) count++; + + std::string pal2 = s + std::string(s.rbegin() + 1, s.rend()); + long long num2 = std::stoll(pal2) * std::stoll(pal2); + if (num2 > r) break; + if (num2 >= l && isPalindrome(std::to_string(num2))) count++; + } + + return count; +} +``` + +### C + +```c +#include +#include +#include +#include +#include + +bool isPalindrome(char* s) { + int len = strlen(s); + for (int i = 0; i < len / 2; i++) { + if (s[i] != s[len - i - 1]) return false; + } + return true; +} + +int superPalindromes(char* left, char* right) { + long long l = atoll(left), r = atoll(right); + int count = 0; + long long limit = (long long) sqrt(r) + 1; + + char s[20], pal[40]; + for (long long i = 1; i < limit; i++) { + sprintf(s, "%lld", i); + int len = strlen(s); + + // Palindrome of even length + snprintf(pal, 40, "%s%s", s, strrev(strdup(s))); + long long num1 = atoll(pal) * atoll(pal); + if (num1 > r) break; + if (num1 >= l && isPalindrome(ltoa(num1, pal, 10))) count++; + + // Palindrome of odd length + snprintf(pal, 40, "%s%s", s, strrev(strdup(s) + 1)); + long long num2 = atoll(pal) * atoll(pal); + if (num2 > r) break; + if (num2 >= l && isPalindrome(ltoa(num2, pal, 10))) count++; + } + + return count; +} +``` + +### JavaScript + +```javascript +function isPalindrome(s) { + return s === s.split("").reverse().join(""); +} + +function superPalindromes(left, right) { + let l = BigInt(left), + r = BigInt(right); + let count = 0; + let limit = BigInt(Math.sqrt(Number(r))) + BigInt(1); + + for (let i = BigInt(1); i < limit; i++) { + let s = i.toString(); + let pal1 = s + s.split("").reverse().join(""); + let num1 = BigInt(pal1) ** BigInt(2); + if (num1 > r) break; + if (num1 >= l && isPalindrome(num1.toString())) count++; + + let pal2 = s + s.slice(0, -1).split("").reverse().join(""); + let num2 = BigInt(pal2) ** BigInt(2); + if (num2 > r) break; + if (num2 >= l && isPalindrome(num2.toString())) count++; + } + + return count; +} +``` + +## Step-by-Step Algorithm + +1. **Generate Palindromes:** + - Iterate through possible values of `i` from 1 to the square root of the right boundary. + - Construct palindromes by concatenating `s` with its reverse and with its reverse minus the last character. +2. **Square Palindromes:** + + - Compute the square of each palindrome. + - Check if the squared value is within the range `[left, right]`. + +3. **Check for Super-Palindromes:** + + - Verify if the squared palindrome is also a palindrome. + +4. **Count and Return:** + - Count valid super-palindromes and return the count. + +## Conclusion + +The problem of finding super-palindromes can be efficiently solved by generating palindromes and checking their squares for the required properties. This approach ensures that we only work within the necessary range and use string manipulations to identify palindromic numbers, which is both effective and computationally feasible. diff --git a/solutions/lc-solutions/0900-0999/0907-sum-of-subarray-minimums.md b/solutions/lc-solutions/0900-0999/0907-sum-of-subarray-minimums.md new file mode 100644 index 0000000..755d6a3 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0907-sum-of-subarray-minimums.md @@ -0,0 +1,218 @@ +--- +id: Sum-of-Subarray-Minimums +title: Sum of Subarray Minimums +sidebar_label: 0907 - Sum of Subarray Minimums +tags: + - intermediate + - Arrays + - Stack + - Algorithms +--- + +## Problem Description + +Given an array of integers `arr`, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer modulo \(10^9 + 7\). + +### Examples + +**Example 1:** + +``` +Input: arr = [3,1,2,4] +Output: 17 +Explanation: +Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. +Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. +Sum is 17. +``` + +**Example 2:** + +``` +Input: arr = [11,81,94,43,3] +Output: 444 +``` + +## Constraints + +``` +1 <= arr.length <= 3 * 104 +1 <= arr[i] <= 3 * 104 +``` + +## Solution Approach + +### Intuition: + +We can solve this problem efficiently using a monotonic stack. The idea is to find the contribution of each element in the array as the minimum of various subarrays. By using a stack, we can determine the previous and next smaller elements for each element in the array. + +### Implementation: + +#### Code (C++): + +```cpp +#include +#include +using namespace std; + +class Solution { +public: + int sumSubarrayMins(vector& arr) { + const int MOD = 1e9 + 7; + int n = arr.size(); + vector left(n), right(n); + stack> s1, s2; + + for (int i = 0; i < n; ++i) { + int count = 1; + while (!s1.empty() && s1.top().first > arr[i]) { + count += s1.top().second; + s1.pop(); + } + s1.push({arr[i], count}); + left[i] = count; + } + + for (int i = n - 1; i >= 0; --i) { + int count = 1; + while (!s2.empty() && s2.top().first >= arr[i]) { + count += s2.top().second; + s2.pop(); + } + s2.push({arr[i], count}); + right[i] = count; + } + + long long result = 0; + for (int i = 0; i < n; ++i) { + result = (result + (long long)arr[i] * left[i] * right[i]) % MOD; + } + return result; + } +}; +``` + +#### Code (Python): + +```python +class Solution: + def sumSubarrayMins(self, arr): + MOD = 10**9 + 7 + n = len(arr) + left, right = [0] * n, [0] * n + s1, s2 = [], [] + + for i in range(n): + count = 1 + while s1 and s1[-1][0] > arr[i]: + count += s1.pop()[1] + s1.append((arr[i], count)) + left[i] = count + + for i in range(n-1, -1, -1): + count = 1 + while s2 and s2[-1][0] >= arr[i]: + count += s2.pop()[1] + s2.append((arr[i], count)) + right[i] = count + + result = 0 + for i in range(n): + result = (result + arr[i] * left[i] * right[i]) % MOD + + return result + +# Example usage: +solution = Solution() +print(solution.sumSubarrayMins([3, 1, 2, 4])) # Output: 17 +``` + +#### Code (Java): + +```java +import java.util.Stack; + +class Solution { + public int sumSubarrayMins(int[] arr) { + final int MOD = 1000000007; + int n = arr.length; + int[] left = new int[n]; + int[] right = new int[n]; + Stack s1 = new Stack<>(), s2 = new Stack<>(); + + for (int i = 0; i < n; ++i) { + int count = 1; + while (!s1.isEmpty() && s1.peek()[0] > arr[i]) { + count += s1.pop()[1]; + } + s1.push(new int[]{arr[i], count}); + left[i] = count; + } + + for (int i = n - 1; i >= 0; --i) { + int count = 1; + while (!s2.isEmpty() && s2.peek()[0] >= arr[i]) { + count += s2.pop()[1]; + } + s2.push(new int[]{arr[i], count}); + right[i] = count; + } + + long result = 0; + for (int i = 0; i < n; ++i) { + result = (result + (long)arr[i] * left[i] * right[i]) % MOD; + } + return (int)result; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.sumSubarrayMins(new int[]{3, 1, 2, 4})); // Output: 17 + } +} +``` + +#### Code (JavaScript): + +```javascript +var sumSubarrayMins = function (arr) { + const MOD = 1e9 + 7; + const n = arr.length; + const left = new Array(n).fill(0); + const right = new Array(n).fill(0); + const s1 = [], + s2 = []; + + for (let i = 0; i < n; ++i) { + let count = 1; + while (s1.length && s1[s1.length - 1][0] > arr[i]) { + count += s1.pop()[1]; + } + s1.push([arr[i], count]); + left[i] = count; + } + + for (let i = n - 1; i >= 0; --i) { + let count = 1; + while (s2.length && s2[s2.length - 1][0] >= arr[i]) { + count += s2.pop()[1]; + } + s2.push([arr[i], count]); + right[i] = count; + } + + let result = 0; + for (let i = 0; i < n; ++i) { + result = (result + arr[i] * left[i] * right[i]) % MOD; + } + return result; +}; + +// Example usage: +console.log(sumSubarrayMins([3, 1, 2, 4])); // Output: 17 +``` + +### Complexity: + +- **Time Complexity:** $O(n)$, where $n$ is the number of elements in the array. We traverse the array twice and use stack operations which are efficient. +- **Space Complexity:** $O(n)$, for the stack and auxiliary arrays. diff --git a/solutions/lc-solutions/0900-0999/0908-smallest-range-I.md b/solutions/lc-solutions/0900-0999/0908-smallest-range-I.md new file mode 100644 index 0000000..5f03557 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0908-smallest-range-I.md @@ -0,0 +1,174 @@ +--- +id: Smallest-Range-I +title: Smallest Range I +sidebar_label: 0908 - Smallest Range I +tags: + - easy + - Arrays + - Algorithms + - Math +--- + +## Problem Description + +You are given an integer array `nums` and an integer `k`. + +In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation at most once for each index `i`. + +The score of `nums` is the difference between the maximum and minimum elements in `nums`. + +Return the minimum score of `nums` after applying the mentioned operation at most once for each index in it. + +### Example 1: + +``` +Input: nums = [1], k = 0 +Output: 0 +Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0. +``` + +### Example 2: + +``` +Input: nums = [0,10], k = 2 +Output: 6 +Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6. +``` + +### Example 3: + +``` +Input: nums = [1,3,6], k = 3 +Output: 0 +Explanation: Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0. +``` + +### Constraints: + +``` +1 <= nums.length <= 10^4 +0 <= nums[i] <= 10^4 +0 <= k <= 10^4 +``` + +## Solution + +The solution involves the following steps: + +1. Calculate the minimum and maximum values of the array. +2. Consider the effect of adding or subtracting `k` from these values. +3. Calculate the new possible minimum and maximum values. +4. The minimum score will be the difference between these new possible maximum and minimum values. + +### Python Code + +```python +def minDifference(nums, k): + if len(nums) == 1: + return 0 + min_val, max_val = min(nums), max(nums) + return max(0, max_val - min_val - 2 * k) + +# Example usage: +nums1 = [1] +k1 = 0 +print(minDifference(nums1, k1)) # Output: 0 + +nums2 = [0, 10] +k2 = 2 +print(minDifference(nums2, k2)) # Output: 6 + +nums3 = [1, 3, 6] +k3 = 3 +print(minDifference(nums3, k3)) # Output: 0 +``` + +### C++ Code + +```cpp +#include +#include +using namespace std; + +class Solution { +public: + int minDifference(vector& nums, int k) { + if (nums.size() == 1) return 0; + int min_val = *min_element(nums.begin(), nums.end()); + int max_val = *max_element(nums.begin(), nums.end()); + return max(0, max_val - min_val - 2 * k); + } +}; + +// Example usage: +int main() { + Solution sol; + vector nums1 = {1}; + int k1 = 0; + cout << sol.minDifference(nums1, k1) << endl; // Output: 0 + + vector nums2 = {0, 10}; + int k2 = 2; + cout << sol.minDifference(nums2, k2) << endl; // Output: 6 + + vector nums3 = {1, 3, 6}; + int k3 = 3; + cout << sol.minDifference(nums3, k3) << endl; // Output: 0 + + return 0; +} +``` + +### Java Code + +```java +import java.util.Arrays; + +public class Solution { + public int minDifference(int[] nums, int k) { + if (nums.length == 1) return 0; + int minVal = Arrays.stream(nums).min().getAsInt(); + int maxVal = Arrays.stream(nums).max().getAsInt(); + return Math.max(0, maxVal - minVal - 2 * k); + } + + public static void main(String[] args) { + Solution sol = new Solution(); + int[] nums1 = {1}; + int k1 = 0; + System.out.println(sol.minDifference(nums1, k1)); // Output: 0 + + int[] nums2 = {0, 10}; + int k2 = 2; + System.out.println(sol.minDifference(nums2, k2)); // Output: 6 + + int[] nums3 = {1, 3, 6}; + int k3 = 3; + System.out.println(sol.minDifference(nums3, k3)); // Output: 0 + } +} +``` + +### JavaScript Code + +```javascript +function minDifference(nums, k) { + if (nums.length === 1) return 0; + const minVal = Math.min(...nums); + const maxVal = Math.max(...nums); + return Math.max(0, maxVal - minVal - 2 * k); +} + +// Example usage: +const nums1 = [1]; +const k1 = 0; +console.log(minDifference(nums1, k1)); // Output: 0 + +const nums2 = [0, 10]; +const k2 = 2; +console.log(minDifference(nums2, k2)); // Output: 6 + +const nums3 = [1, 3, 6]; +const k3 = 3; +console.log(minDifference(nums3, k3)); // Output: 0 +``` diff --git a/solutions/lc-solutions/0900-0999/0910-smallest-range-ii.md b/solutions/lc-solutions/0900-0999/0910-smallest-range-ii.md new file mode 100644 index 0000000..b0dcea3 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0910-smallest-range-ii.md @@ -0,0 +1,166 @@ +--- +id: smallest-range-ii +title: Smallest Range II +sidebar_label: 0910 - Smallest Range II +tags: + - Sorting + - Greedy + - Array +description: "This is a solution to the Smallest Range II problem on LeetCode." +--- + +## Problem Description + +You are given an integer array `nums` and an integer `k`. + +For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`. + +The score of `nums` is the difference between the maximum and minimum elements in nums. + +Return the minimum **score** of `nums` after changing the values at each index. + + +### Examples + +**Example 1:** + +``` +Input +Input: nums = [1], k = 0 +Output: 0 +Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0. +``` +**Example 2:** + +``` +Input: nums = [0,10], k = 2 +Output: 6 +Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6. +``` + +### Constraints + +- $1 \leq nums.length \leq 104$ +- $0 \leq nums[i] \leq 104$ +- $0 \leq k \leq 104$ + +## Solution for Smallest Range II + +## Approach: Linear Scan +### Intuition + +As in Smallest Range I, smaller `A[i]` will choose to increase their value ("go up"), and bigger `A[i]` will decrease their value ("go down"). + +### Algorithm + +We can formalize the above concept: if `A[i] < A[j]`, we don't need to consider when `A[i]` goes down while `A[j]` goes up. This is because the interval `(A[i] + K, A[j] - K)` is a subset of `(A[i] - K, A[j] + K)` (here, `(a, b)` for `a > b` denotes `(b, a)` instead.) + +That means that it is never worse to choose `(up, down)` instead of `(down, up)`. We can prove this claim that one interval is a subset of another, by showing both `A[i] + K` and `A[j] - K` are between `A[i] - K` and `A[j] + K`. + +For sorted `A`, say `A[i]` is the largest i that goes up. Then `A[0] + K`, `A[i] + K`, `A[i+1] - K`, `A[A.length - 1] - K` are the only relevant values for calculating the answer: every other value is between one of these extremal values. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int smallestRangeII(vector& A, int K) { + int N = A.size(); + sort(A.begin(), A.end()); + int ans = A[N-1] - A[0]; + + for (int i = 0; i < A.size() - 1; ++i) { + int a = A[i], b = A[i+1]; + int high = max(A[N-1] - K, a + K); + int low = min(A[0] + K, b - K); + ans = min(ans, high - low); + } + return ans; + } +}; + +``` + + + + +```java +class Solution { + public int smallestRangeII(int[] A, int K) { + int N = A.length; + Arrays.sort(A); + int ans = A[N-1] - A[0]; + + for (int i = 0; i < A.length - 1; ++i) { + int a = A[i], b = A[i+1]; + int high = Math.max(A[N-1] - K, a + K); + int low = Math.min(A[0] + K, b - K); + ans = Math.min(ans, high - low); + } + return ans; + } +} +``` + + + + + +```python +class Solution(object): + def smallestRangeII(self, A, K): + A.sort() + mi, ma = A[0], A[-1] + ans = ma - mi + for i in xrange(len(A) - 1): + a, b = A[i], A[i+1] + ans = min(ans, max(ma-K, a+K) - min(mi+K, b-K)) + return ans +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(NlogN)$ + +> **Reason**: where N is the length of the A. + +#### Space Complexity: $O(N)$ or $O(logN)$ + +> **Reason**: +> - The space complexity of the sorting algorithm depends on the implementation of each programming language. +> +> - For instance, the `list.sort()` function in Python is implemented with the Timsort algorithm whose space complexity is $O(N)$. +> +> - In Java, the `Arrays.sort()` is implemented as a variant of quicksort algorithm whose space complexity is $O(log⁑N)$. + + +## Video Solution + + + +## References + +- **LeetCode Problem**: [Smallest Range II](https://leetcode.com/problems/smallest-range-ii/description/) + +- **Solution Link**: [Smallest Range II](https://leetcode.com/problems/smallest-range-ii/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0912-sort-an-array.md b/solutions/lc-solutions/0900-0999/0912-sort-an-array.md new file mode 100644 index 0000000..ca1fcbe --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0912-sort-an-array.md @@ -0,0 +1,215 @@ +--- +id: Sort-an-Array +title: Sort an Array +sidebar_label: 0912 - Sort an Array +tags: + - medium + - Array + - Divide and Conquer + - Sorting +--- + +## Problem: Sort an Array of Integers + +### Description + +Given an array of integers `nums`, sort the array in ascending order and return it. + +You must solve the problem without using any built-in functions in `O(n log n)` time complexity and with the smallest space complexity possible. + +## Example 1 + +**Input**: nums = [5, 2, 3, 1] +**Output**: [1, 2, 3, 5] +**Explanation**: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5). + +## Example 2 + +**Input**: nums = [5, 1, 1, 2, 0, 0] +**Output**: [0, 0, 1, 1, 2, 5] +**Explanation**: Note that the values of nums are not necessarily unique. + +## Constraints + +- `1 <= nums.length <= 5 * 10^4` +- `-5 * 10^4 <= nums[i] <= 5 * 10^4` + +## Solution + +### Approach + +To achieve `O(n log n)` time complexity with the smallest space complexity possible, we can use the Merge Sort algorithm. Merge Sort is a divide-and-conquer algorithm that divides the array into halves, recursively sorts them, and then merges the sorted halves. + +### Implementation + +#### C++ + +```cpp +class Solution { +public: + void merge(vector& nums, int left, int mid, int right) { + int n1 = mid - left + 1; + int n2 = right - mid; + vector L(n1), R(n2); + + for (int i = 0; i < n1; i++) + L[i] = nums[left + i]; + for (int j = 0; j < n2; j++) + R[j] = nums[mid + 1 + j]; + + int i = 0, j = 0, k = left; + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { + nums[k] = L[i]; + i++; + } else { + nums[k] = R[j]; + j++; + } + k++; + } + + while (i < n1) { + nums[k] = L[i]; + i++; + k++; + } + + while (j < n2) { + nums[k] = R[j]; + j++; + k++; + } + } + + void mergeSort(vector& nums, int left, int right) { + if (left >= right) + return; + int mid = left + (right - left) / 2; + mergeSort(nums, left, mid); + mergeSort(nums, mid + 1, right); + merge(nums, left, mid, right); + } + + vector sortArray(vector& nums) { + mergeSort(nums, 0, nums.size() - 1); + return nums; + } +}; +``` + +#### Python + +```python +class Solution: + def merge(self, left, right): + sorted_list = [] + while left and right: + if left[0] < right[0]: + sorted_list.append(left.pop(0)) + else: + sorted_list.append(right.pop(0)) + sorted_list.extend(left if left else right) + return sorted_list + + def merge_sort(self, nums): + if len(nums) <= 1: + return nums + mid = len(nums) // 2 + left = self.merge_sort(nums[:mid]) + right = self.merge_sort(nums[mid:]) + return self.merge(left, right) + + def sortArray(self, nums): + return self.merge_sort(nums) +``` + +#### Java + +```java +class Solution { + public void merge(int[] nums, int left, int mid, int right) { + int n1 = mid - left + 1; + int n2 = right - mid; + int[] L = new int[n1]; + int[] R = new int[n2]; + + for (int i = 0; i < n1; ++i) + L[i] = nums[left + i]; + for (int j = 0; j < n2; ++j) + R[j] = nums[mid + 1 + j]; + + int i = 0, j = 0, k = left; + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { + nums[k] = L[i]; + i++; + } else { + nums[k] = R[j]; + j++; + } + k++; + } + + while (i < n1) { + nums[k] = L[i]; + i++; + k++; + } + + while (j < n2) { + nums[k] = R[j]; + j++; + k++; + } + } + + public void mergeSort(int[] nums, int left, int right) { + if (left < right) { + int mid = left + (right - left) / 2; + mergeSort(nums, left, mid); + mergeSort(nums, mid + 1, right); + merge(nums, left, mid, right); + } + } + + public int[] sortArray(int[] nums) { + mergeSort(nums, 0, nums.length - 1); + return nums; + } +} +``` + +#### JavaScript + +```javascript +var sortArray = function (nums) { + if (nums.length <= 1) { + return nums; + } + + const merge = (left, right) => { + let result = []; + while (left.length && right.length) { + if (left[0] < right[0]) { + result.push(left.shift()); + } else { + result.push(right.shift()); + } + } + return result.concat(left).concat(right); + }; + + const mergeSort = (nums) => { + if (nums.length <= 1) { + return nums; + } + const mid = Math.floor(nums.length / 2); + const left = mergeSort(nums.slice(0, mid)); + const right = mergeSort(nums.slice(mid)); + return merge(left, right); + }; + + return mergeSort(nums); +}; +``` diff --git a/solutions/lc-solutions/0900-0999/0913-cat-and-mouse.md b/solutions/lc-solutions/0900-0999/0913-cat-and-mouse.md new file mode 100644 index 0000000..a42b64b --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0913-cat-and-mouse.md @@ -0,0 +1,373 @@ +--- +id: cat-and-mouse +title: Cat and Mouse +sidebar_label: 0913 - Cat and Mouse +tags: + - Dynamic Programming + - Depth-First Search + - Memoization +description: "This is a solution to the Cat and Mouse problem on LeetCode." +--- + +## Problem Description + +A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns. + +The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph. + +The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node 0. + +During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`. + +Additionally, it is not allowed for the Cat to travel to the Hole (node `0`). + +Then, the game can end in three ways: + +- If ever the Cat occupies the same node as the Mouse, the Cat wins. +- If ever the Mouse reaches the Hole, the Mouse wins. +- If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw. + +Given a graph, and assuming both players play optimally, return + +- 1 if the mouse wins the game, +- 2 if the cat wins the game, or +- 0 if the game is a draw. + +### Examples + +**Example 1:** + +![image](https://assets.leetcode.com/uploads/2020/11/17/cat1.jpg) +``` +Input: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]] +Output: 0 +``` +**Example 2:** + +![image](https://assets.leetcode.com/uploads/2020/11/17/cat2.jpg) +``` +Input: graph = [[1,3],[0],[3],[0,2]] +Output: 1 +``` + +### Constraints + +- `3 <= graph.length <= 50` +- `1 <= graph[i].length < graph.length` +- `0 <= graph[i][j] < graph.length` +- `graph[i][j] != i` +- `graph[i]` is unique. +- The mouse and the cat can always move. + +## Solution for Cat and Mouse + +## Approach: Minimax / Percolate from Resolved States +### Intuition + +The state of the game can be represented as `(m, c, t)` where `m` is the location of the mouse, `c` is the location of the cat, and `t` is 1 if it is the mouse's move, else `2`. Let's call these states nodes. These states form a directed graph: the player whose turn it is has various moves which can be considered as outgoing edges from this node to other nodes. + +Some of these nodes are already resolved: if the mouse is at the hole `(m = 0)`, then the mouse wins; if the cat is where the mouse is `(c = m)`, then the cat wins. Let's say that nodes will either be colored MOUSE, CAT, or DRAW depending on which player is assured victory. + +As in a standard minimax algorithm, the Mouse player will prefer MOUSE nodes first, DRAW nodes second, and CAT nodes last, and the Cat player prefers these nodes in the opposite order. + +### Algorithm + +We will color each node marked DRAW according to the following rule. (We'll suppose the node has node.turn = Mouse: the other case is similar.) + +- ("Immediate coloring"): If there is a child that is colored $\small\text{MOUSE}$, then this node will also be colored $\small\text{MOUSE}$. + +- ("Eventual coloring"): If all children are colored $\small\text{CAT}$, then this node will also be colored $\small\text{CAT}$. + +We will repeatedly do this kind of coloring until no node satisfies the above conditions. To perform this coloring efficiently, we will use a queue and perform a bottom-up percolation: + +- Enqueue any node initially colored (because the Mouse is at the Hole, or the Cat is at the Mouse.) + +- For every node in the queue, for each parent of that node: + + - Do an immediate coloring of parent if you can. + + - If you can't, then decrement the side-count of the number of children marked $\small\text{DRAW}$. If it becomes zero, then do an "eventual coloring" of this parent. + + - All parents that were colored in this manner get enqueued to the queue. + +### Proof of Correctness + +Our proof is similar to a proof that minimax works. + +Say we cannot color any nodes any more, and say from any node colored $\small\text{CAT}$ or $\small\text{MOUSE}$ we need at most K moves to win. If say, some node marked $\small\text{DRAW}$ is actually a win for Mouse, it must have been with $>K$ moves. Then, a path along optimal play (that tries to prolong the loss as long as possible) must arrive at a node colored $\small\text{MOUSE}$ (as eventually the Mouse reaches the Hole.) Thus, there must have been some transition $\small\text{DRAW} \rightarrow \small\text{MOUSE}$ along this path. + +If this transition occurred at a `node` with `node.turn = Mouse`, then it breaks our immediate coloring rule. If it occured with `node.turn = Cat`, and all children of node have color $\small\text{MOUSE}$, then it breaks our eventual coloring rule. If some child has color $\small\text{CAT}$, then it breaks our immediate coloring rule. Thus, in this case node will have some child with $\small\text{DRAW}$, which breaks our optimal play assumption, as moving to this child ends the game in $>K$ moves, whereas moving to the colored neighbor ends the game in $\leq K$ moves. + +### Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +public: + int catMouseGame(std::vector>& graph) { + int N = graph.size(); + const int DRAW = 0, MOUSE = 1, CAT = 2; + + std::vector>> color(50, std::vector>(50, std::vector(3, DRAW))); + std::vector>> degree(50, std::vector>(50, std::vector(3, 0))); + + // degree[node] : the number of neutral children of this node + for (int m = 0; m < N; ++m) + for (int c = 0; c < N; ++c) { + degree[m][c][1] = graph[m].size(); + degree[m][c][2] = graph[c].size(); + for (int x : graph[c]) if (x == 0) { + degree[m][c][2]--; + break; + } + } + + // enqueued : all nodes that are colored + std::queue> queue; + for (int i = 0; i < N; ++i) + for (int t = 1; t <= 2; ++t) { + color[0][i][t] = MOUSE; + queue.push({0, i, t, MOUSE}); + if (i > 0) { + color[i][i][t] = CAT; + queue.push({i, i, t, CAT}); + } + } + + // percolate + while (!queue.empty()) { + // for nodes that are colored : + std::vector node = queue.front(); + queue.pop(); + int i = node[0], j = node[1], t = node[2], c = node[3]; + // for every parent of this node i, j, t : + for (std::vector parent : parents(graph, i, j, t)) { + int i2 = parent[0], j2 = parent[1], t2 = parent[2]; + // if this parent is not colored : + if (color[i2][j2][t2] == DRAW) { + // if the parent can make a winning move (ie. mouse to MOUSE), do so + if (t2 == c) { + color[i2][j2][t2] = c; + queue.push({i2, j2, t2, c}); + } else { + // else, this parent has degree[parent]--, and enqueue + // if all children of this parent are colored as losing moves + degree[i2][j2][t2]--; + if (degree[i2][j2][t2] == 0) { + color[i2][j2][t2] = 3 - t2; + queue.push({i2, j2, t2, 3 - t2}); + } + } + } + } + } + + return color[1][2][1]; + } + + // What nodes could play their turn to + // arrive at node (m, c, t) ? + std::vector> parents(std::vector>& graph, int m, int c, int t) { + std::vector> ans; + if (t == 2) { + for (int m2 : graph[m]) + ans.push_back({m2, c, 3-t}); + } else { + for (int c2 : graph[c]) if (c2 > 0) + ans.push_back({m, c2, 3-t}); + } + return ans; + } +}; + + +``` + + + + +```java +class Solution { + public int catMouseGame(int[][] graph) { + int N = graph.length; + final int DRAW = 0, MOUSE = 1, CAT = 2; + + int[][][] color = new int[50][50][3]; + int[][][] degree = new int[50][50][3]; + + // degree[node] : the number of neutral children of this node + for (int m = 0; m < N; ++m) + for (int c = 0; c < N; ++c) { + degree[m][c][1] = graph[m].length; + degree[m][c][2] = graph[c].length; + for (int x: graph[c]) if (x == 0) { + degree[m][c][2]--; + break; + } + } + + // enqueued : all nodes that are colored + Queue queue = new LinkedList(); + for (int i = 0; i < N; ++i) + for (int t = 1; t <= 2; ++t) { + color[0][i][t] = MOUSE; + queue.add(new int[]{0, i, t, MOUSE}); + if (i > 0) { + color[i][i][t] = CAT; + queue.add(new int[]{i, i, t, CAT}); + } + } + + // percolate + while (!queue.isEmpty()) { + // for nodes that are colored : + int[] node = queue.remove(); + int i = node[0], j = node[1], t = node[2], c = node[3]; + // for every parent of this node i, j, t : + for (int[] parent: parents(graph, i, j, t)) { + int i2 = parent[0], j2 = parent[1], t2 = parent[2]; + // if this parent is not colored : + if (color[i2][j2][t2] == DRAW) { + // if the parent can make a winning move (ie. mouse to MOUSE), do so + if (t2 == c) { + color[i2][j2][t2] = c; + queue.add(new int[]{i2, j2, t2, c}); + } else { + // else, this parent has degree[parent]--, and enqueue + // if all children of this parent are colored as losing moves + degree[i2][j2][t2]--; + if (degree[i2][j2][t2] == 0) { + color[i2][j2][t2] = 3 - t2; + queue.add(new int[]{i2, j2, t2, 3 - t2}); + } + } + } + } + } + + return color[1][2][1]; + } + + // What nodes could play their turn to + // arrive at node (m, c, t) ? + public List parents(int[][] graph, int m, int c, int t) { + List ans = new ArrayList(); + if (t == 2) { + for (int m2: graph[m]) + ans.add(new int[]{m2, c, 3-t}); + } else { + for (int c2: graph[c]) if (c2 > 0) + ans.add(new int[]{m, c2, 3-t}); + } + return ans; + } +} +``` + + + + + +```python +class Solution(object): + def catMouseGame(self, graph): + N = len(graph) + + # What nodes could play their turn to + # arrive at node (m, c, t) ? + def parents(m, c, t): + if t == 2: + for m2 in graph[m]: + yield m2, c, 3-t + else: + for c2 in graph[c]: + if c2: + yield m, c2, 3-t + + DRAW, MOUSE, CAT = 0, 1, 2 + color = collections.defaultdict(int) + + # degree[node] : the number of neutral children of this node + degree = {} + for m in xrange(N): + for c in xrange(N): + degree[m,c,1] = len(graph[m]) + degree[m,c,2] = len(graph[c]) - (0 in graph[c]) + + # enqueued : all nodes that are colored + queue = collections.deque([]) + for i in xrange(N): + for t in xrange(1, 3): + color[0, i, t] = MOUSE + queue.append((0, i, t, MOUSE)) + if i > 0: + color[i, i, t] = CAT + queue.append((i, i, t, CAT)) + + # percolate + while queue: + # for nodes that are colored : + i, j, t, c = queue.popleft() + # for every parent of this node i, j, t : + for i2, j2, t2 in parents(i, j, t): + # if this parent is not colored : + if color[i2, j2, t2] is DRAW: + # if the parent can make a winning move (ie. mouse to MOUSE), do so + if t2 == c: # winning move + color[i2, j2, t2] = c + queue.append((i2, j2, t2, c)) + # else, this parent has degree[parent]--, and enqueue if all children + # of this parent are colored as losing moves + else: + degree[i2, j2, t2] -= 1 + if degree[i2, j2, t2] == 0: + color[i2, j2, t2] = 3 - t2 + queue.append((i2, j2, t2, 3 - t2)) + + return color[1, 2, 1] +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(N^3)$ + +> **Reason**: where N is the number of nodes in the graph. There are $O(N^2)$ states, and each state has an outdegree of N, as there are at most N different moves. + +#### Space Complexity: $O(N^2)$ + +> **Reason**:due to the storage requirements of the color and degree arrays, which both have dimensions `[N][N][3]`. + + +## Video Solution + + + +## References + +- **LeetCode Problem**: [Cat and Mouse](https://leetcode.com/problems/cat-and-mouse/description/) + +- **Solution Link**: [Cat and Mouse](https://leetcode.com/problems/cat-and-mouse/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0914-x-of-a-kind-in-a-deck-of-cards.md b/solutions/lc-solutions/0900-0999/0914-x-of-a-kind-in-a-deck-of-cards.md new file mode 100644 index 0000000..032b526 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0914-x-of-a-kind-in-a-deck-of-cards.md @@ -0,0 +1,274 @@ +--- +id: x-of-a-kind-in-a-deck-of-cards +title: X of a Kind in a Deck of Cards +sidebar_label: 0914 - X of a Kind in a Deck of Cards +tags: + - Math + - Hash Table + - Array +description: "This is a solution to the X of a Kind in a Deck of Cards problem on LeetCode." +--- + +## Problem Description + +You are given an integer array deck where `deck[i]` represents the number written on the $i^th$ card. + +Partition the cards into **one or more groups** such that: + +- Each group has **exactly** `x` cards where `x > 1`, and +- All the cards in one group have the same integer written on them. + +Return `true` if such partition is possible, or `false` otherwise. + + +### Examples + +**Example 1:** + +``` +Input: deck = [1,2,3,4,4,3,2,1] +Output: true +Explanation: Possible partition [1,1],[2,2],[3,3],[4,4]. +``` +**Example 2:** + +``` +Input: deck = [1,1,1,2,2,2,3,3] +Output: false +Explanation: No possible partition. +``` + +### Constraints + +- $1 \leq deck.length \leq 10^4$ +- $0 \leq deck[i] < 10^4$ + +## Solution for X of a Kind in a Deck of Cards + +## Approach 1: Brute Force +### Intuition + +We can try every possible `X`. + +### Algorithm + +Since we divide the deck of `N` cards into say, `K` piles of `X` cards each, we must have `N % X == 0`. + +Then, say the deck has `C_i` copies of cards with number `i`. Each group with number `i` has `X` copies, so we must have `C_i % X == 0`. These are necessary and sufficient conditions. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + bool hasGroupsSizeX(vector& deck) { + int N = deck.size(); + vector count(10000, 0); + for (int c : deck) + count[c]++; + + vector values; + for (int i = 0; i < 10000; ++i) + if (count[i] > 0) + values.push_back(count[i]); + + for (int X = 2; X <= N; ++X) { + if (N % X == 0) { + bool valid = true; + for (int v : values) { + if (v % X != 0) { + valid = false; + break; + } + } + if (valid) + return true; + } + } + + return false; + } +}; + + +``` + + + + +```java +class Solution { + public boolean hasGroupsSizeX(int[] deck) { + int N = deck.length; + int[] count = new int[10000]; + for (int c: deck) + count[c]++; + + List values = new ArrayList(); + for (int i = 0; i < 10000; ++i) + if (count[i] > 0) + values.add(count[i]); + + search: for (int X = 2; X <= N; ++X) + if (N % X == 0) { + for (int v: values) + if (v % X != 0) + continue search; + return true; + } + + return false; + } +} +``` + + + + + +```python +class Solution(object): + def hasGroupsSizeX(self, deck): + count = collections.Counter(deck) + N = len(deck) + for X in xrange(2, N+1): + if N % X == 0: + if all(v % X == 0 for v in count.values()): + return True + return False +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(N^2log(logN))$ + +> **Reason**: where N is the number of cards. It is outside the scope of this article to prove that the number of divisors of N is bounded by $O(Nlog(⁑log⁑N))$. + +#### Space Complexity: $O(N)$ + +> **Reason**: The space needed to store the counts of each card type in the `values` list. + +## Approach 2: Greatest Common Divisor +### Intuition and Algorithm + +Again, say there are `C_i` cards of number `i`. These must be broken down into piles of `X` cards each, ie. `C_i % X == 0` for all `i`. + +Thus, `X` must divide the greatest common divisor of `C_i`. If this greatest common divisor `g` is greater than `1`, then `X = g` will satisfy. Otherwise, it won't. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + bool hasGroupsSizeX(vector& deck) { + vector count(10000, 0); + for (int c : deck) + count[c]++; + + int g = -1; + for (int i = 0; i < 10000; ++i) + if (count[i] > 0) { + if (g == -1) + g = count[i]; + else + g = gcd(g, count[i]); + } + + return g >= 2; + } + + int gcd(int x, int y) { + return x == 0 ? y : gcd(y % x, x); + } +}; + +``` + + + + +```java +class Solution { + public boolean hasGroupsSizeX(int[] deck) { + int[] count = new int[10000]; + for (int c: deck) + count[c]++; + + int g = -1; + for (int i = 0; i < 10000; ++i) + if (count[i] > 0) { + if (g == -1) + g = count[i]; + else + g = gcd(g, count[i]); + } + + return g >= 2; + } + + public int gcd(int x, int y) { + return x == 0 ? y : gcd(y%x, x); + } +} +``` + + + + + +```python +class Solution(object): + def hasGroupsSizeX(self, deck): + from fractions import gcd + vals = collections.Counter(deck).values() + return reduce(gcd, vals) >= 2 +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(Nlog^2(N))$ + +> **Reason**: where N is the number of votes. If there are $C_i$ cards with number i, then each gcd operation is naively $O(\log^2 C_i)$. Better bounds exist, but are outside the scope of this article to develop + +#### Space Complexity: $O(N)$ + +> **Reason**: The space needed to store the counts of each card type in the `values` list. + + + +## Video Solution + + + +## References + +- **LeetCode Problem**: [X of a Kind in a Deck of Cards](https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/description/) + +- **Solution Link**: [X of a Kind in a Deck of Cards](https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0915-partition-array-into-disjoint-intervals.md b/solutions/lc-solutions/0900-0999/0915-partition-array-into-disjoint-intervals.md new file mode 100644 index 0000000..f33413c --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0915-partition-array-into-disjoint-intervals.md @@ -0,0 +1,296 @@ +--- +id: partition-array-into-disjoint-intervals +title: Partition Array into Disjoint Intervals +sidebar_label: 915 - Partition Array into Disjoint Intervals +tags: + - Suffix Array + - Two Pointers + - Prefix Sum +description: "This is a solution to the Partition Array into Disjoint Intervals problem on LeetCode." +--- + +## Problem Description + +Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: + +- Every element in `left` is less than or equal to every element in `right`. +- `left` and `right` are non-empty. +- `left` has the smallest possible size. + +Return the length of `left` after such a partitioning. + +Test cases are generated such that partitioning exists. + +### Examples + +**Example 1:** + +``` +Input: nums = [5,0,3,8,6] +Output: 3 +Explanation: left = [5,0,3], right = [8,6] +``` +**Example 2:** + +``` +Input: nums = [1,1,1,0,6,12] +Output: 4 +Explanation: left = [1,1,1,0], right = [6,12] +``` + +### Constraints + +- $2 \leq nums.length \leq 10^5$ +- $0 \leq nums[i] \leq 10^6$ +- There is at least one valid answer for the given input. + +## Solution for Partition Array into Disjoint Intervals + +## Approach 1: Two Arrays +### Intuition + +Instead of checking whether `all(L <= R for L in left for R in right)` , for each index let's only check whether the **largest element to the left** of the current index (inclusive) is less than or equal to the **smallest element to the right** of the current index (`max(left) <= min(right)`). + +### Algorithm + +Let's try to find `max(left)` for subarrays `left = nums[:1], left = nums[:2], left = nums[:3], ...` etc. Specifically, `max_left[i]` will be the maximum of subarray `nums[:i+1]`. They are related to each other: `max(nums[:4]) = max(max(nums[:3]), nums[3])`, so `max_left[4] = max(max_left[3], nums[4])`. + +Similarly, `min(right)` for every possible right can be found in linear time. + +Now that we can query `max(left)` and `min(right)` in constant time by checking `max_left[i]` and `min_right[i]`, we just need to iterate over `max_left` and `min_right` to find the first index where `max_left[i-1]` is less than or equal to `min_right[i]`. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int partitionDisjoint(vector& nums) { + int N = nums.size(); + int maxLeft[N]; + int minRight[N]; + + maxLeft[0] = nums[0]; + minRight[N - 1] = nums[N - 1]; + + for (int i = 1; i < N; ++i) { + maxLeft[i] = max(maxLeft[i - 1], nums[i]); + } + + for (int i = N - 2; i >= 0; --i) { + minRight[i] = min(minRight[i + 1], nums[i]); + } + + for (int i = 1; i < N; ++i) { + if (maxLeft[i - 1] <= minRight[i]) { + return i; + } + } + // In case there is no solution, we'll return -1 + return -1; + } +}; +``` + + + + +```java +class Solution { + public int partitionDisjoint(int[] nums) { + int N = nums.length; + int[] maxLeft = new int[N]; + int[] minRight = new int[N]; + + maxLeft[0] = nums[0]; + minRight[N - 1] = nums[N - 1]; + + for (int i = 1; i < N; ++i) { + maxLeft[i] = Math.max(maxLeft[i - 1], nums[i]); + } + + for (int i = N - 2; i >= 0; --i) { + minRight[i] = Math.min(minRight[i + 1], nums[i]); + } + + for (int i = 1; i < N; ++i) { + if (maxLeft[i - 1] <= minRight[i]) { + return i; + } + } + // In case there is no solution, we'll return -1 + return -1; + } +} +``` + + + + + +```python +class Solution: + def partitionDisjoint(self, nums: List[int]) -> int: + N = len(nums) + max_left = [None] * N + min_right = [None] * N + + max_left[0] = nums[0] + min_right[-1] = nums[-1] + + for i in range(1, N): + max_left[i] = max(max_left[i - 1], nums[i]) + + for i in range(N - 2, -1, -1): + min_right[i] = min(min_right[i + 1], nums[i]) + + for i in range(1, N): + if max_left[i - 1] <= min_right[i]: + return i +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(N)$ + +> **Reason**: where N is the length of `nums`. We iterate over the input array three times and create two arrays with size N each. + +#### Space Complexity: $O(N)$ + +> **Reason**: We use two additional arrays of size N each. + +## Approach 2: One Array +### Intuition + +Notice, in the first approach, we iterated from `1` to `N` twice. Once to create `max_left` and once to find which index to split the array at. We can slightly optimize our approach by performing both of these steps in the same for loop. Doing so will allow us to replace the `max_left` array with a single variable that tracks the maximum value seen so far (`curr_max`). + +> How can we do this? Try to code it up yourself before looking at the solution below. + +### Algorithm + +1. Initialize a `min_right` array with the rightmost value equal to the rightmost value in nums. +2. Iterate over nums in reverse order and at each iteration update the current index of `min_right` with the minimum value seen so far. +3. Initialize `curr_max` as the leftmost value in nums. +4. Iterate over nums from left to right and at each iteration, update `curr_max` as the maximum value seen so far. When `curr_max` is less than or equal to the minimum value to the right, then the current index is where nums should be split. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int partitionDisjoint(vector& nums) { + int N = nums.size(); + int minRight[N]; + minRight[N - 1] = nums[N - 1]; + + for (int i = N - 2; i >= 0; --i) { + minRight[i] = min(minRight[i + 1], nums[i]); + } + + int currMax = nums[0]; + for (int i = 1; i < N; ++i) { + currMax = max(currMax, nums[i - 1]); + if (currMax <= minRight[i]) { + return i; + } + } + // In case there is no solution, we'll return -1 + return -1; + } +}; +``` + + + + +```java +class Solution { + public int partitionDisjoint(int[] nums) { + int N = nums.length; + int[] minRight = new int[N]; + minRight[N - 1] = nums[N - 1]; + + for (int i = N - 2; i >= 0; --i) { + minRight[i] = Math.min(minRight[i + 1], nums[i]); + } + + int currMax = nums[0]; + for (int i = 1; i < N; ++i) { + currMax = Math.max(currMax, nums[i - 1]); + if (currMax <= minRight[i]) { + return i; + } + } + // In case there is no solution, we'll return -1 + return -1; + } +} +``` + + + + + +```python +class Solution: + def partitionDisjoint(self, nums: List[int]) -> int: + N = len(nums) + min_right = [None] * N + min_right[-1] = nums[-1] + + for i in range(N - 2, -1, -1): + min_right[i] = min(min_right[i + 1], nums[i]) + + curr_max = nums[0] + for i in range(1, N): + curr_max = max(curr_max, nums[i - 1]) + if curr_max <= min_right[i]: + return i +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(N)$ + +> **Reason**: where N is the length of nums. We iterate over the input array two times (instead of three times as in the previous approach) and create only one array with size N (as opposed to two as before). + +#### Space Complexity: $O(N)$ + +> **Reason**: We use one additional array of size N. + + +## Video Solution + + + +## References + +- **LeetCode Problem**: [Partition Array into Disjoint Intervals](https://leetcode.com/problems/partition-array-into-disjoint-intervals/) + +- **Solution Link**: [Partition Array into Disjoint Intervals](https://leetcode.com/problems/partition-array-into-disjoint-intervals/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0916-word-subsets.md b/solutions/lc-solutions/0900-0999/0916-word-subsets.md new file mode 100644 index 0000000..19e27fd --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0916-word-subsets.md @@ -0,0 +1,205 @@ +--- +id: word-subsets +title: Word Subsets +sidebar_label: 0916 - Word Subsets +tags: + - String + - Array + - Hash Table +description: "This is a solution to the Word Subsets problem on LeetCode." +--- + +## Problem Description + +You are given two string arrays `words1` and `words2`. + +A string `b` is a **subset** of string `a` if every letter in `b` occurs in `a` including multiplicity. + +- For example, `"wrr"` is a subset of `"warrior"` but is not a subset of `"world"`. + +A string `a` from `words1` is **universal** if for every string `b` in `words2`, `b` is a subset of `a`. + +Return an array of all the **universal** strings in `words1`. You may return the answer in **any order**. + +### Examples + +**Example 1:** + +``` +Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"] +Output: ["facebook","google","leetcode"] +``` +**Example 2:** + +``` +Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["l","e"] +Output: ["apple","google","leetcode"] +``` + +### Constraints + +- $1 \leq words1.length, words2.length \leq 10^4$ +- $1 \leq words1[i].length, words2[i].length \leq 10$ +- `words1[i]` and `words2[i]` consist only of lowercase English letters. +- All the strings of `words1` are **unique**. + +## Solution for Word Subsets + +## Approach: Reduce to Single Word in B +### Intuition + +If b is a subset of a, then say a is a superset of b. Also, say $(word)N_{\text{"a"}}(\text{word})$ is the count of the number of $\text{"a"}$'s in the word. + +When we check whether a word `wordA` in `A` is a superset of `wordB`, we are individually checking the counts of letters: that for each $\text{letter}$, we have $N_{\text{letter}}(\text{wordA}) \geq N_{\text{letter}}(\text{wordB})$. + +Now, if we check whether a word `wordA` is a superset of all words $\text{wordB}_i$, we will check for each letter and each i, that $N_{\text{letter}}(\text{wordA}) \geq N_{\text{letter}}(\text{wordB}_i)$. This is the same as checking $N_{\text{letter}}(\text{wordA}) \geq \max\limits_i(N_{\text{letter}}(\text{wordB}_i))$. + +For example, when checking whether `"warrior"` is a superset of words B = `["wrr", "wa", "or"]`, we can combine these words in `B` to form a "maximum" word `"arrow"`, that has the maximum count of every letter in each word in `B`. + +### Algorithm + +Reduce `B` to a single word `bmax` as described above, then compare the counts of letters between words `a` in `A`, and `bmax`. + +### Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +public: + std::vector wordSubsets(std::vector& A, std::vector& B) { + std::vector bmax(26, 0); + for (const auto& b : B) { + std::unordered_map bCount = count(b); + for (int i = 0; i < 26; ++i) + bmax[i] = std::max(bmax[i], bCount[static_cast('a' + i)]); + } + + std::vector ans; + for (const auto& a : A) { + std::unordered_map aCount = count(a); + bool universal = true; + for (int i = 0; i < 26; ++i) { + if (aCount[static_cast('a' + i)] < bmax[i]) { + universal = false; + break; + } + } + if (universal) + ans.push_back(a); + } + + return ans; + } + +private: + std::unordered_map count(const std::string& S) { + std::unordered_map ans; + for (char c : S) + ans[c]++; + return ans; + } +}; + + +``` + + + + +```java +class Solution { + public List wordSubsets(String[] A, String[] B) { + int[] bmax = count(""); + for (String b: B) { + int[] bCount = count(b); + for (int i = 0; i < 26; ++i) + bmax[i] = Math.max(bmax[i], bCount[i]); + } + + List ans = new ArrayList(); + search: for (String a: A) { + int[] aCount = count(a); + for (int i = 0; i < 26; ++i) + if (aCount[i] < bmax[i]) + continue search; + ans.add(a); + } + + return ans; + } + + public int[] count(String S) { + int[] ans = new int[26]; + for (char c: S.toCharArray()) + ans[c - 'a']++; + return ans; + } +} +``` + + + + + +```python +class Solution(object): + def wordSubsets(self, A, B): + def count(word): + ans = [0] * 26 + for letter in word: + ans[ord(letter) - ord('a')] += 1 + return ans + + bmax = [0] * 26 + for b in B: + for i, c in enumerate(count(b)): + bmax[i] = max(bmax[i], c) + + ans = [] + for a in A: + if all(x >= y for x, y in zip(count(a), bmax)): + ans.append(a) + return ans +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(\mathcal{A}+\mathcal{B})$ + +> **Reason**: where $\mathcal{A}$ and $\mathcal{B}$ is the total amount of information in A and B respectively. + +#### Space Complexity: $O(A.length+B.length)$ + +## Video Solution + + + +## References + +- **LeetCode Problem**: [Word Subsets](https://leetcode.com/problems/word-subsets/description/) + +- **Solution Link**: [Word Subsets](https://leetcode.com/problems/word-subsets/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0917-reverse-only-letters.md b/solutions/lc-solutions/0900-0999/0917-reverse-only-letters.md new file mode 100644 index 0000000..360ba4e --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0917-reverse-only-letters.md @@ -0,0 +1,247 @@ +--- +id: reverse-only-letters +title: Reverse Only Letters +sidebar_label: 0917 - Reverse Only Letters +tags: + - Two Pointers + - String + - Stack +description: "This is a solution to the Reverse Only Letters problem on LeetCode." +--- + +## Problem Description + +Given a string `s`, reverse the string according to the following rules: + +- All the characters that are not English letters remain in the same position. +- All the English letters (lowercase or uppercase) should be reversed. + +Return `s` after reversing it. + +### Examples + +**Example 1:** + +``` +Input: s = "ab-cd" +Output: "dc-ba" +``` +**Example 2:** + +``` +Input: s = "a-bC-dEf-ghIj" +Output: "j-Ih-gfE-dCba" +``` + +### Constraints + +- $1 \leq s.length \leq 100$ +- `s` consists of characters with ASCII values in the range `[33, 122]`. +- `s` does not contain `'\"'` or `'\\'`. + +## Solution for Reverse Only Letters + +## Approach: Stack of Letters +### Intuition and Algorithm + +Collect the letters of `S` separately into a stack, so that popping the stack reverses the letters. (Alternatively, we could have collected the letters into an array and reversed the array.) + +Then, when writing the characters of `S`, any time we need a letter, we use the one we have prepared instead. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + string reverseOnlyLetters(string S) { + stack letters; + for (char c : S) + if (isalpha(c)) + letters.push(c); + + string ans; + for (char c : S) { + if (isalpha(c)) + ans += letters.top(), letters.pop(); + else + ans += c; + } + + return ans; + } +}; + +``` + + + + +```java +class Solution { + public String reverseOnlyLetters(String S) { + Stack letters = new Stack(); + for (char c: S.toCharArray()) + if (Character.isLetter(c)) + letters.push(c); + + StringBuilder ans = new StringBuilder(); + for (char c: S.toCharArray()) { + if (Character.isLetter(c)) + ans.append(letters.pop()); + else + ans.append(c); + } + + return ans.toString(); + } +} +``` + + + + + +```python +class Solution(object): + def reverseOnlyLetters(self, S): + letters = [c for c in S if c.isalpha()] + ans = [] + for c in S: + if c.isalpha(): + ans.append(letters.pop()) + else: + ans.append(c) + return "".join(ans) +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(N)$ + +> **Reason**: where `N` is the length of `S`. + +#### Space Complexity: $O(N)$ + +## Approach: Reverse Pointer +### Intuition + +Write the characters of `S` one by one. When we encounter a letter, we want to write the next letter that occurs if we iterated through the string backwards. + +So we do just that: keep track of a pointer `j` that iterates through the string backwards. When we need to write a letter, we use it. + +### Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +public: + std::string reverseOnlyLetters(std::string S) { + std::stringstream ans; + int j = S.length() - 1; + for (int i = 0; i < S.length(); ++i) { + if (std::isalpha(S[i])) { + while (!std::isalpha(S[j])) + j--; + ans << S[j--]; + } else { + ans << S[i]; + } + } + + return ans.str(); + } +}; + +``` + + + + +```java +class Solution { + public String reverseOnlyLetters(String S) { + StringBuilder ans = new StringBuilder(); + int j = S.length() - 1; + for (int i = 0; i < S.length(); ++i) { + if (Character.isLetter(S.charAt(i))) { + while (!Character.isLetter(S.charAt(j))) + j--; + ans.append(S.charAt(j--)); + } else { + ans.append(S.charAt(i)); + } + } + + return ans.toString(); + } +} +``` + + + + + +```python +class Solution(object): + def reverseOnlyLetters(self, S): + ans = [] + j = len(ans) - 1 + for i, x in enumerate(S): + if x.isalpha(): + while not S[j].isalpha(): + j -= 1 + ans.append(S[j]) + j -= 1 + else: + ans.append(x) + + return "".join(ans) +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(N)$ + +> **Reason**: where `N` is the length of `S`. + +#### Space Complexity: $O(N)$ + +## Video Solution + + + +## References + +- **LeetCode Problem**: [Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters/description/) + +- **Solution Link**: [Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0918-maximum-sum-circular-subarray.md b/solutions/lc-solutions/0900-0999/0918-maximum-sum-circular-subarray.md new file mode 100644 index 0000000..26b1b78 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0918-maximum-sum-circular-subarray.md @@ -0,0 +1,361 @@ +--- +id: maximum-sum-circular-subarray +title: Maximum Sum Circular Subarray +sidebar_label: 0918 - Maximum Sum Circular Subarray +tags: + - Dynamic Programming + - Divide and Conquer + - Array +description: "This is a solution to the Maximum Sum Circular Subarray problem on LeetCode." +--- + +## Problem Description + +Given a **circular integer array** nums of length `n`, return the maximum possible sum of a non-empty **subarray** of `nums`. + +A **circular array** means the end of the array connects to the beginning of the array. Formally, the next element of `nums[i]` is `nums[(i + 1) % n]` and the previous element of `nums[i]` is `nums[(i - 1 + n) % n]`. + +A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray `nums[i], nums[i + 1], ..., nums[j]`, there does not exist `i <= k1`, `k2 <= j` with `k1 % n == k2 % n`. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,-2,3,-2] +Output: 3 +Explanation: Subarray [3] has maximum sum 3. +``` +**Example 2:** + +``` +Input: nums = [5,-3,5] +Output: 10 +Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10. +``` + +### Constraints + +- `n == nums.length` +- $1 \leq n \leq 3 * 10^4$ +- $-3 * 10^4 \leq nums[i] \leq 3 * 10^4$ + +## Solution for Maximum Sum Circular Subarray + +## Approach 1: Enumerate prefix and suffix sums +### Intuition +As a circular array, the maximum subarray sum can be either the maximum "normal sum" which is the maximum sum of the ordinary array or a "special sum" which would involve elements that wrap around the array. The "special sum" would be the combination of a prefix sum and a suffix sum. A prefix is a subarray that starts at the first element of the array and a suffix is a subarray that ends at the final element of the array. The "special sum" would involve a prefix and suffix that do not overlap. + +The normal sum is the Maximum Subarray problem and can be solved with Kadane's algorithm. Please familiarize yourself with this solution if you haven't already. In this article, to save time, we will assume that users have already solved Maximum Subarray. + +We can calculate both the normal sum and the special sum and return the larger one. + +Assuming we already have the normal sum (it's just the solution to Maximum Subarray), let's focus on how to find the special sum. + +Assume the input array is called `nums` whose length is `n`. To calculate the special sum, we need to find the maximum sum of a prefix sum and a non-overlapping suffix sum of `nums`. Our idea is to enumerate a prefix with its sum and add the maximum suffix sum that starts after the prefix so that the prefix and suffix don't overlap. + +Imagine an array `suffixSum` where `suffixSum[i]` represents the suffix sum starting from index `i`, namely `suffixSum[i]` = `nums[i]` + `nums[i + 1]` + ... + `nums[n - 1]` (it's like a prefix sum, but backward). We can construct an array rightMax where `rightMax[i] = max(suffixSum[i], suffixSum[i + 1], ...suffixSum[n - 1])`. + +Namely, `rightMax[i]` is the largest suffix sum of `nums` that comes on or after `i`. + +With `rightMax`, we can then calculate the special sum by looking at all prefixes. We can easily accumulate the prefix while iterating over the input, and at each index `i`, we can check `rightMax[i + 1]` to find the maximum suffix that won't overlap with the current prefix. + +### Algorithm + +The algorithm works as follows: + +- Create an integer array rightMax of length n. + +- Set rightMax[n - 1] to nums[n - 1], set suffixSum to nums[n - 1]. + +- Iterate over i from n - 2 to 0 + + - Increase suffixSum by nums[i] + - Update rightMax[i] to max(rightMax[i + 1], suffixSum) +- Set maxSum and prefixSum to nums[0]. + +- Iterate over i from 0 to n - 2 + + - Increase prefixSum by nums[i] + - Update specialSum to max(specialSum, prefixSum + rightMax[i + 1]). +- Calculate the normal sum maxSum using Kadane's algorithm. + +- Return max(maxSum, specialSum) + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int maxSubarraySumCircular(vector& nums) { + const int n = nums.size(); + vector rightMax(n); + rightMax[n - 1] = nums[n - 1]; + int suffixSum = nums[n - 1]; + + for (int i = n - 2; i >= 0; --i) { + suffixSum += nums[i]; + rightMax[i] = max(rightMax[i + 1], suffixSum); + } + + int maxSum = nums[0]; + int specialSum = nums[0]; + int curMax = 0; + int prefixSum = 0; + for (int i = 0; i < n; ++i) { + // This is Kadane's algorithm. + curMax = max(curMax, 0) + nums[i]; + maxSum = max(maxSum, curMax); + + prefixSum += nums[i]; + if (i + 1 < n) { + specialSum = max(specialSum, prefixSum + rightMax[i + 1]); + } + } + + return max(maxSum, specialSum); + } +}; +``` + + + + +```java +class Solution { + public int maxSubarraySumCircular(int[] nums) { + final int n = nums.length; + final int[] rightMax = new int[n]; + rightMax[n - 1] = nums[n - 1]; + int suffixSum = nums[n - 1]; + + for (int i = n - 2; i >= 0; --i) { + suffixSum += nums[i]; + rightMax[i] = Math.max(rightMax[i + 1], suffixSum); + } + + int maxSum = nums[0]; + int specialSum = nums[0]; + int curMax = 0; + for (int i = 0, prefixSum = 0; i < n; ++i) { + // This is Kadane's algorithm. + curMax = Math.max(curMax, 0) + nums[i]; + maxSum = Math.max(maxSum, curMax); + + prefixSum += nums[i]; + if (i + 1 < n) { + specialSum = Math.max(specialSum, prefixSum + rightMax[i + 1]); + } + } + + return Math.max(maxSum, specialSum); + } +} +``` + + + + + +```python +class Solution: + def maxSubarraySumCircular(self, nums: List[int]) -> int: + n = len(nums) + right_max = [0] * n + right_max[-1] = nums[-1] + suffix_sum = nums[-1] + + for i in range(n-2, -1, -1): + suffix_sum += nums[i] + right_max[i] = max(right_max[i+1], suffix_sum) + + max_sum = nums[0] + special_sum = nums[0] + cur_max = 0 + for i in range(n): + # This is Kadane's algorithm. + cur_max = max(cur_max, 0) + nums[i] + max_sum = max(max_sum, cur_max) + + prefix_sum = sum(nums[:i+1]) + if i + 1 < n: + special_sum = max(special_sum, prefix_sum + right_max[i+1]) + + return max(max_sum, special_sum) +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(N)$ + +> **Reason**: The algorithm iterates over all elements in the array to calculate the `rightMax` array, and then to find the answer. These both take linear time. + +#### Space Complexity: $O(N)$ + +> **Reason**: This is the space to save the `rightMax` array. + +## Approach 2: Calculate the "Minimum Subarray" +### Intuition + +As mentioned before, we know that the maximum "normal sum" is the Maximum Subarray problem which can be found with Kadane's. As such, we can focus on finding the "special sum". + +Instead of thinking about the "special sum" as the sum of a prefix and a suffix, we can think about it as the sum of all elements, minus a subarray in the middle. In this case, we want to minimize this middle subarray's sum, which we can calculate using Kadane's algorithm as well. + +![image](https://assets.leetcode.com/static_assets/media/original_images/918/918_Maximum_Sum_Circular_Subarray.png) + +If we use Kadane's algorithm but use `min()` instead of `max()` to update the current subarray sum, it will give us the minimum subarray. Then, we can just subtract the minimum subarray from the total sum to find the "special sum". + +There is one case we need to consider however; what if the minimum subarray contains all elements, such as in the case where every element is negative? In that case, our "special sum" would represent an empty array, which is invalid because the problem explicitly states that we need a non-empty subarray. + +If we find that the minimum subarray is equal to the total sum, then we need to ignore the "special sum" and just return the "normal sum". + +### Algorithm + +- Calculate the maximum subarray `maxSum` using Kadane's algorithm. +- Calculate the minimum subarray `minSum` using Kadane's algorithm, by using `min()` instead of `max()`. +- Calculate the sum of all the elements in `nums`, totalSum +- If `minSum == totalSum` return `maxSum`, otherwise return `max(maxSum, totalSum - minSum)`. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int maxSubarraySumCircular(vector& nums) { + int curMax = 0; + int curMin = 0; + int maxSum = nums[0]; + int minSum = nums[0]; + int totalSum = 0; + + for (int num: nums) { + // Normal Kadane's + curMax = max(curMax, 0) + num; + maxSum = max(maxSum, curMax); + + // Kadane's but with min to find minimum subarray + curMin = min(curMin, 0) + num; + minSum = min(minSum, curMin); + + totalSum += num; + } + + if (totalSum == minSum) { + return maxSum; + } + + return max(maxSum, totalSum - minSum); + } +}; +``` + + + + +```java +class Solution { + public int maxSubarraySumCircular(int[] nums) { + int curMax = 0; + int curMin = 0; + int maxSum = nums[0]; + int minSum = nums[0]; + int totalSum = 0; + + for (int num: nums) { + // Normal Kadane's + curMax = Math.max(curMax, 0) + num; + maxSum = Math.max(maxSum, curMax); + + // Kadane's but with min to find minimum subarray + curMin = Math.min(curMin, 0) + num; + minSum = Math.min(minSum, curMin); + + totalSum += num; + } + + if (totalSum == minSum) { + return maxSum; + } + + return Math.max(maxSum, totalSum - minSum); + } +} +``` + + + + + +```python +class Solution: + def maxSubarraySumCircular(self, nums: List[int]) -> int: + cur_max = 0 + cur_min = 0 + max_sum = nums[0] + min_sum = nums[0] + total_sum = 0 + + for num in nums: + # Normal Kadane's + cur_max = max(cur_max, 0) + num + max_sum = max(max_sum, cur_max) + + # Kadane's but with min to find minimum subarray + cur_min = min(cur_min, 0) + num + min_sum = min(min_sum, cur_min) + + total_sum += num + + if total_sum == min_sum: + return max_sum + + return max(max_sum, total_sum - min_sum) +``` + + + +### Complexity Analysis + +#### Time Complexity: $O(N)$ + +> **Reason**: The algorithm iterates over all elements to calculate the `maxSum`, `minSum`, and `sum` which takes $O(N)$ time. + +#### Space Complexity: $O(1)$ + +> **Reason**: The algorithm doesn't use extra space other than several integer variables. + + +## Video Solution + + + +## References + +- **LeetCode Problem**: [Maximum Sum Circular Subarray](https://leetcode.com/problems/maximum-sum-circular-subarray/description/) + +- **Solution Link**: [Maximum Sum Circular Subarray](https://leetcode.com/problems/maximum-sum-circular-subarray/solutions/) + +--- + +

Authors:

+ +
+{['shreyash3087'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0920-Number-of-music-playlists.md b/solutions/lc-solutions/0900-0999/0920-Number-of-music-playlists.md new file mode 100644 index 0000000..ae44f33 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0920-Number-of-music-playlists.md @@ -0,0 +1,178 @@ +--- +id: Number of Music Playlists +title: Number of Music Playlists +sidebar_label: Number-of-music-playlists +tags: + - Dynamic Programming + - Combinatorics +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Number of Music Playlists](https://leetcode.com/problems/number-of-music-playlists) | [Number of Music Playlists Solution on LeetCode](https://leetcode.com/problems/Number-of-music-playlists/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +### Problem Description +Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: + +1. Every song is played at least once. +2. A song can only be played again only if `k` other songs have been played. + +Given `n`, `goal`, and `k`, return the number of possible playlists that you can create. Since the answer can be very large, return it modulo 10^9 + 7. + +#### Examples + +## Example 1: +**Input:**`n = 3, goal = 3, k = 1` +**Output:**`6` +**Explanation:** `There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1].` + +## Example 2: + +**Input:** `n = 2, goal = 3, k = 0` +**Output:** `6` +**Explanation:** `There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2].` + +## Example 3: + +**Input:** `n = 2, goal = 3, k = 1` +**Output:** `2` +**Explanation:** `There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].` + +### Constraints +- `0 <= k < n <= goal <= 100` + +### Approach +The problem can be approached using dynamic programming. We define `dp[i][j]` as the number of playlists of length `i` that contain exactly `j` different songs. + +**State Transition:** +- If we add a new song to the playlist, it must be one of the `n - j` songs that have not been used in the playlist yet. +- If we reuse an old song, it must be one of the `j - k` songs that are allowed to be reused. + +**Initialization:** +- `dp[0][0] = 1` as there's exactly one way to create an empty playlist. + +**Final Result:** +- The result is stored in `dp[goal][n]`. + +### Solution in Python +```python +class Solution: + def numMusicPlaylists(self, n: int, goal: int, k: int) -> int: + MOD = 10**9 + 7 + dp = [[0] * (n + 1) for _ in range(goal + 1)] + dp[0][0] = 1 + + for i in range(1, goal + 1): + for j in range(1, n + 1): + dp[i][j] = dp[i - 1][j - 1] * (n - j + 1) % MOD + if j > k: + dp[i][j] += dp[i - 1][j] * (j - k) % MOD + dp[i][j] %= MOD + + return dp[goal][n] +``` + +### Solution in Java +```java +class Solution { + public int numMusicPlaylists(int n, int goal, int k) { + int MOD = 1_000_000_007; + long[][] dp = new long[goal + 1][n + 1]; + dp[0][0] = 1; + + for (int i = 1; i <= goal; i++) { + for (int j = 1; j <= n; j++) { + dp[i][j] = dp[i - 1][j - 1] * (n - j + 1) % MOD; + if (j > k) { + dp[i][j] += dp[i - 1][j] * (j - k) % MOD; + } + dp[i][j] %= MOD; + } + } + + return (int) dp[goal][n]; + } +} +``` + +### Solution in C++ +```cpp +class Solution { +public: + int numMusicPlaylists(int n, int goal, int k) { + const int MOD = 1000000007; + vector> dp(goal + 1, vector(n + 1, 0)); + dp[0][0] = 1; + + for (int i = 1; i <= goal; i++) { + for (int j = 1; j <= n; j++) { + dp[i][j] = dp[i - 1][j - 1] * (n - j + 1) % MOD; + if (j > k) { + dp[i][j] = (dp[i][j] + dp[i - 1][j] * (j - k)) % MOD; + } + } + } + + return dp[goal][n]; + } +}; +``` + +### Solution in C +```c +int numMusicPlaylists(int n, int goal, int k) { + const int MOD = 1000000007; + long dp[101][101] = {0}; + dp[0][0] = 1; + + for (int i = 1; i <= goal; i++) { + for (int j = 1; j <= n; j++) { + dp[i][j] = dp[i - 1][j - 1] * (n - j + 1) % MOD; + if (j > k) { + dp[i][j] = (dp[i][j] + dp[i - 1][j] * (j - k)) % MOD; + } + } + } + + return dp[goal][n]; +} +``` + +### Solution in JavaScript +```javascript +var numMusicPlaylists = function(n, goal, k) { + const MOD = 1000000007; + const dp = Array.from({ length: goal + 1 }, () => Array(n + 1).fill(0)); + dp[0][0] = 1; + + for (let i = 1; i <= goal; i++) { + for (let j = 1; j <= n; j++) { + dp[i][j] = dp[i - 1][j - 1] * (n - j + 1) % MOD; + if (j > k) { + dp[i][j] = (dp[i][j] + dp[i - 1][j] * (j - k)) % MOD; + } + } + } + + return dp[goal][n]; +}; +``` + +### Step-by-Step Algorithm +1. **Initialize**: + - Define a 2D array `dp` where `dp[i][j]` represents the number of playlists of length `i` with exactly `j` different songs. + - Initialize `dp[0][0] = 1`. + +2. **State Transition**: + - For each playlist length `i` from 1 to `goal`: + - For each number of unique songs `j` from 1 to `n`: + - If adding a new song: Update `dp[i][j]` with `dp[i-1][j-1] * (n - j + 1) % MOD`. + - If reusing an old song: Update `dp[i][j]` with `dp[i-1][j] * (j - k) % MOD`. + +3. **Compute Final Result**: + - Return the value `dp[goal][n]`. + +### Conclusion +The dynamic programming approach efficiently calculates the number of valid playlists by building up from smaller subproblems. This approach ensures that all constraints are respected and provides a result in a feasible time complexity for the given constraints. \ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0921-minimum-add-to-make-parentheses-valid.md b/solutions/lc-solutions/0900-0999/0921-minimum-add-to-make-parentheses-valid.md new file mode 100644 index 0000000..3df28f9 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0921-minimum-add-to-make-parentheses-valid.md @@ -0,0 +1,131 @@ +--- +id: miminum-add-to-make-parentheses-valid +title: Minimum Add to Make Parentheses Valid +sidebar_label: 0921 - Minimum Add to Make Parentheses Valid +tags: + - Leetcode +--- + +## Problem Statement + +A parentheses string is valid if and only if: + +- It is the empty string, +- It can be written as AB (A concatenated with B), where A and B are valid strings, or +- It can be written as (A), where A is a valid string. + +You are given a parentheses string `s`. In one move, you can insert a parenthesis at any position of the string. + +For example, if `s = "()))"`, you can insert an opening parenthesis to be `"(()))"` or a closing parenthesis to be "`())))"`. +Return the minimum number of moves required to make `s` valid. + +## Examples + +### Example 1 + +**Input:** `s = "())"` +**Output:** `1` + +### Example 2 + +**Input:** `s = "((("` +**Output:** `3` + +## Constraints + +- $1 <= s.length <= 1000$ +- s[i] is either '(' or ')'. + +## Algorithm + +1. Initialize two counters, `open` and `close`, to keep track of the number of unmatched opening and closing parentheses. +2. Iterate through the string `s`. +3. For each character: + - If it is an opening parenthesis `'('`, increment the `open` counter. + - If it is a closing parenthesis `')'`: + - If the `open` counter is greater than 0, decrement the `open` counter (indicating a match with an opening parenthesis). + - Otherwise, increment the `close` counter (indicating an unmatched closing parenthesis). +4. The minimum number of moves required to make the string valid is the sum of `open` and `close`. + +## C++ Code + +```cpp +class Solution { +public: + int minAddToMakeValid(string s) { + int open = 0, close = 0; + for (char str : s) { + if (str == '(') { + open++; + } else if (open == 0) { + close++; + } else { + open--; + } + } + return open + close; + } +}; +``` + +## Python Code + +```python +class Solution: + def minAddToMakeValid(self, s: str) -> int: + open_count = 0 + close_count = 0 + + for char in s: + if char == '(': + open_count += 1 + elif open_count == 0: + close_count += 1 + else: + open_count -= 1 + + return open_count + close_count +``` + +## Java Code + +```java +class Solution { + public int minAddToMakeValid(String s) { + int open = 0, close = 0; + for (char c : s.toCharArray()) { + if (c == '(') { + open++; + } else if (open == 0) { + close++; + } else { + open--; + } + } + return open + close; + } +} +``` + +## JavaScript Code + +```javascript +/** + * @param {string} s + * @return {number} + */ +var minAddToMakeValid = function (s) { + let open = 0, + close = 0; + for (let char of s) { + if (char === "(") { + open++; + } else if (open === 0) { + close++; + } else { + open--; + } + } + return open + close; +}; +``` diff --git a/solutions/lc-solutions/0900-0999/0922-sort-array-by-parity-II.md b/solutions/lc-solutions/0900-0999/0922-sort-array-by-parity-II.md new file mode 100644 index 0000000..a8e05bf --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0922-sort-array-by-parity-II.md @@ -0,0 +1,162 @@ +--- +id: Sort-Array-by-Parity-II +title: Sort Array by Parity II +sidebar_label: 0922 - Sort Array by Parity II +tags: + - medium + - Arrays + - Sorting + - Two Pointers +--- + +## Problem Description + +Given an array of integers `nums`, half of the integers in `nums` are odd, and the other half are even. + +Sort the array so that whenever `nums[i]` is odd, `i` is odd, and whenever `nums[i]` is even, `i` is even. + +Return any answer array that satisfies this condition. + +## Examples + +**Example 1:** + +``` +Input: nums = [4,2,5,7] +Output: [4,5,2,7] +Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. +``` + +**Example 2:** + +``` +Input: nums = [2,3] +Output: [2,3] +``` + +## Constraints + +``` +2 <= nums.length <= 2 * 10^4 +nums.length is even. +Half of the integers in nums are even. +0 <= nums[i] <= 1000 +``` + +## Solution + +### Python + +```python +class Solution: + def sortArrayByParityII(self, nums: List[int]) -> List[int]: + even_index, odd_index = 0, 1 + while even_index < len(nums) and odd_index < len(nums): + if nums[even_index] % 2 == 0: + even_index += 2 + elif nums[odd_index] % 2 == 1: + odd_index += 2 + else: + nums[even_index], nums[odd_index] = nums[odd_index], nums[even_index] + even_index += 2 + odd_index += 2 + return nums + +# Example usage: +solution = Solution() +print(solution.sortArrayByParityII([4,2,5,7])) # Output: [4,5,2,7] +``` + +### C++ + +```cpp +#include +using namespace std; + +class Solution { +public: + vector sortArrayByParityII(vector& nums) { + int even_index = 0, odd_index = 1; + while (even_index < nums.size() && odd_index < nums.size()) { + if (nums[even_index] % 2 == 0) { + even_index += 2; + } else if (nums[odd_index] % 2 == 1) { + odd_index += 2; + } else { + swap(nums[even_index], nums[odd_index]); + even_index += 2; + odd_index += 2; + } + } + return nums; + } +}; + +// Example usage: +int main() { + Solution solution; + vector nums = {4, 2, 5, 7}; + vector result = solution.sortArrayByParityII(nums); // Output: [4, 5, 2, 7] + for (int num : result) { + cout << num << " "; + } + return 0; +} +``` + +### Java + +```java +class Solution { + public int[] sortArrayByParityII(int[] nums) { + int evenIndex = 0, oddIndex = 1; + while (evenIndex < nums.length && oddIndex < nums.length) { + if (nums[evenIndex] % 2 == 0) { + evenIndex += 2; + } else if (nums[oddIndex] % 2 == 1) { + oddIndex += 2; + } else { + int temp = nums[evenIndex]; + nums[evenIndex] = nums[oddIndex]; + nums[oddIndex] = temp; + evenIndex += 2; + oddIndex += 2; + } + } + return nums; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + int[] nums = {4, 2, 5, 7}; + int[] result = solution.sortArrayByParityII(nums); // Output: [4, 5, 2, 7] + for (int num : result) { + System.out.print(num + " "); + } + } +} +``` + +### JavaScript + +```javascript +var sortArrayByParityII = function (nums) { + let evenIndex = 0, + oddIndex = 1; + while (evenIndex < nums.length && oddIndex < nums.length) { + if (nums[evenIndex] % 2 === 0) { + evenIndex += 2; + } else if (nums[oddIndex] % 2 === 1) { + oddIndex += 2; + } else { + [nums[evenIndex], nums[oddIndex]] = [nums[oddIndex], nums[evenIndex]]; + evenIndex += 2; + oddIndex += 2; + } + } + return nums; +}; + +// Example usage: +console.log(sortArrayByParityII([4, 2, 5, 7])); // Output: [4, 5, 2, 7] +``` diff --git a/solutions/lc-solutions/0900-0999/0923-3sum-with-multiplicity.md b/solutions/lc-solutions/0900-0999/0923-3sum-with-multiplicity.md new file mode 100644 index 0000000..7cd01b0 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0923-3sum-with-multiplicity.md @@ -0,0 +1,149 @@ +--- +id: 3sum-with-multiplicity +title: 3Sum With Multiplicity +sidebar_label: 0923 - 3Sum With Multiplicity +tags: + - Leetcode +--- + +## Problem Statement + +Given an integer array `arr` and an integer `target`, return the number of tuples `(i, j, k)` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`. + +As the answer can be very large, return it modulo `10^9 + 7`. + +## Examples + +### Example 1 + +**Input:** `arr = [1,1,2,2,3,3,4,4,5,5]`, `target = 8` +**Output:** `20` +**Explanation:** +Enumerating by the values `(arr[i], arr[j], arr[k])`: + +- `(1, 2, 5)` occurs 8 times; +- `(1, 3, 4)` occurs 8 times; +- `(2, 2, 4)` occurs 2 times; +- `(2, 3, 3)` occurs 2 times. + +### Example 2 + +**Input:** `arr = [1,1,2,2,2,2]`, `target = 5` +**Output:** `12` +**Explanation:** +`arr[i] = 1`, `arr[j] = arr[k] = 2` occurs 12 times: + +- We choose one `1` from `[1,1]` in 2 ways, +- and two `2`s from `[2,2,2,2]` in 6 ways. + +### Example 3 + +**Input:** `arr = [2,1,3]`, `target = 6` +**Output:** `1` +**Explanation:** `(1, 2, 3)` occurred one time in the array so we return 1. + +## Constraints + +- $3 <= arr.length <= 3000$ +- $0 <= arr[i] <= 100$ +- $0 <= target <= 300$ + +## Algorithm + +1. Use a hashmap to keep track of the frequency of each sum of pairs `(arr[i] + arr[j])` as we iterate through the array. +2. For each element in the array, count the number of valid pairs that can form the target with the current element using the hashmap. +3. Iterate through the array and update the hashmap for the sums of pairs. +4. Keep track of the results and return it modulo `10^9 + 7`. + +## C++ Code + +```cpp +class Solution { +public: + int threeSumMulti(vector& arr, int target) { + int n = arr.size(); + const int mod = 1e9 + 7; + long ans = 0; + + unordered_map m; + for (int i = 0; i < n; ++i) { + ans = (ans + m[target - arr[i]]) % mod; + for (int j = 0; j < i; ++j) { + m[arr[i] + arr[j]]++; + } + } + + return ans; + } +}; +``` + +## Python Code + +```python +class Solution: + def threeSumMulti(self, arr: List[int], target: int) -> int: + from collections import defaultdict + + mod = 10**9 + 7 + count = defaultdict(int) + result = 0 + + for i, x in enumerate(arr): + result = (result + count[target - x]) % mod + for j in range(i): + count[arr[j] + x] += 1 + + return result +``` + +## Java Code + +```java +import java.util.HashMap; +import java.util.Map; + +class Solution { + public int threeSumMulti(int[] arr, int target) { + int n = arr.length; + int mod = 1000000007; + long result = 0; + + Map countMap = new HashMap<>(); + for (int i = 0; i < n; i++) { + result = (result + countMap.getOrDefault(target - arr[i], 0)) % mod; + for (int j = 0; j < i; j++) { + int sum = arr[i] + arr[j]; + countMap.put(sum, countMap.getOrDefault(sum, 0) + 1); + } + } + + return (int) result; + } +} +``` + +## JavaScript Code + +```javascript +/** + * @param {number[]} arr + * @param {number} target + * @return {number} + */ +var threeSumMulti = function (arr, target) { + const mod = 10 ** 9 + 7; + let count = new Map(); + let result = 0; + + for (let i = 0; i < arr.length; i++) { + result = (result + (count.get(target - arr[i]) || 0)) % mod; + for (let j = 0; j < i; j++) { + let sum = arr[i] + arr[j]; + count.set(sum, (count.get(sum) || 0) + 1); + } + } + + return result; +}; +``` diff --git a/solutions/lc-solutions/0900-0999/0925-long-pressed-name.md b/solutions/lc-solutions/0900-0999/0925-long-pressed-name.md new file mode 100644 index 0000000..d9d8f1b --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0925-long-pressed-name.md @@ -0,0 +1,147 @@ +--- +id: long-pressed-name +title: Long Pressed Name +sidebar_label: Long Pressed Name +tags: + - strings + - two-pointers +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Long Pressed Name](https://leetcode.com/problems/long-pressed-name/description/) | [Long Pressed Name Solution on LeetCode](https://leetcode.com/problems/Long-Pressed-Name/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description + +Your friend is typing his name into a keyboard. Sometimes, when typing a character `c`, the key might get long pressed, and the character will be typed 1 or more times. + +You examine the typed characters of the keyboard. Return `True` if it is possible that it was your friend's name, with some characters (possibly none) being long pressed. + +### Example 1 + +**Input:** `name = "alex" typed = "aaleex"` +**Output:** `true` + +**Explanation:** +`'a' and 'e' in 'alex' were long pressed.` + +### Example 2 + +**Input:** `name = "saeed" typed = "ssaaedd"` +**Output:** `false` + +**Explanation:** +`'e' must have been pressed twice, but it was not in the typed output.` + +### Constraints + +- `1 <= name.length, typed.length <= 1000` +- `name` and `typed` consist of only lowercase English letters. + +## Approach + +We can solve this problem using a two-pointer technique. We'll use two pointers to traverse both the `name` and `typed` strings. We'll compare characters at both pointers and handle long presses by ensuring the characters in `typed` match the corresponding characters in `name` in the correct order. + +## Solution + +### Python + +```python +def isLongPressedName(name: str, typed: str) -> bool: + i, j = 0, 0 + while j < len(typed): + if i < len(name) and name[i] == typed[j]: + i += 1 + elif j == 0 or typed[j] != typed[j - 1]: + return False + j += 1 + return i == len(name) +``` + +### Java + +```java +class Solution { + public boolean isLongPressedName(String name, String typed) { + int i = 0, j = 0; + while (j < typed.length()) { + if (i < name.length() && name.charAt(i) == typed.charAt(j)) { + i++; + } else if (j == 0 || typed.charAt(j) != typed.charAt(j - 1)) { + return false; + } + j++; + } + return i == name.length(); + } +} +``` + +### C++ + +```cpp +class Solution { +public: + bool isLongPressedName(string name, string typed) { + int i = 0, j = 0; + while (j < typed.length()) { + if (i < name.length() && name[i] == typed[j]) { + i++; + } else if (j == 0 || typed[j] != typed[j - 1]) { + return false; + } + j++; + } + return i == name.length(); + } +}; +``` + +### C + +```c +bool isLongPressedName(char * name, char * typed){ + int i = 0, j = 0; + while (typed[j] != '\0') { + if (name[i] != '\0' && name[i] == typed[j]) { + i++; + } else if (j == 0 || typed[j] != typed[j - 1]) { + return false; + } + j++; + } + return name[i] == '\0'; +} +``` + +### JavaScript + +```javascript +var isLongPressedName = function(name, typed) { + let i = 0, j = 0; + while (j < typed.length) { + if (i < name.length && name[i] === typed[j]) { + i++; + } else if (j === 0 || typed[j] !== typed[j - 1]) { + return false; + } + j++; + } + return i === name.length; +}; +``` + +## Step-by-Step Algorithm + +1. Initialize two pointers, `i` for `name` and `j` for `typed`, both set to 0. +2. Iterate through `typed` using pointer `j`. +3. If `name[i]` matches `typed[j]`, increment both `i` and `j`. +4. If `name[i]` does not match `typed[j]` and `typed[j]` is not a long press of `typed[j-1]`, return `False`. +5. Increment `j` in all cases. +6. After the loop, check if all characters in `name` were matched (`i == name.length`). Return `True` if they were, otherwise return `False`. + +## Conclusion + +This approach efficiently checks whether the `typed` string can be derived from the `name` string considering possible long presses. The two-pointer technique ensures that we traverse both strings in linear time, making the solution optimal and easy to understand. \ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0927-Three-Equal-Parts.md b/solutions/lc-solutions/0900-0999/0927-Three-Equal-Parts.md new file mode 100644 index 0000000..f395b53 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0927-Three-Equal-Parts.md @@ -0,0 +1,273 @@ +--- +id: Three-Equal-Parts +title: Three-Equal-Parts +sidebar_label: Three-Equal-Parts +tags: + - arrays + - binary + - partitioning +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Three-Equal-Parts](https://leetcode.com/problems/Three-Equal-Parts/description/) | [Three-Equal-Parts Solution on LeetCode](https://leetcode.com/problems/Three-Equal-Parts/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | +## Problem Description + +You are given an array `arr` which consists of only zeros and ones. Divide the array into three non-empty parts such that all of these parts represent the same binary value. + +If it is possible, return any `[i, j]` with `i + 1 < j`, such that: + +- `arr[0], arr[1], ..., arr[i]` is the first part, +- `arr[i + 1], arr[i + 2], ..., arr[j - 1]` is the second part, and +- `arr[j], arr[j + 1], ..., arr[arr.length - 1]` is the third part. + +All three parts should have equal binary values. If it is not possible, return `[-1, -1]`. + +Note that the entire part is used when considering what binary value it represents. For example, `[1,1,0]` represents 6 in decimal, not 3. Also, leading zeros are allowed, so `[0,1,1]` and `[1,1]` represent the same value. + +### Example 1 + +**Input:** `arr = [1,0,1,0,1]` +**Output:** `[0,3]` + +### Example 2 + +**Input:** `arr = [1,1,0,1,1]` +**Output:** `[-1,-1]` + +### Example 3 + +**Input:** `arr = [1,1,0,0,1]` +**Output:** `[0,2]` + +## Constraints + +- `3 <= arr.length <= 3 * 10^4` +- `arr[i]` is `0` or `1`. + +## Approach + +1. **Count the number of 1's in the array:** + - If the total number of 1's is not divisible by 3, return `[-1, -1]`. + - If the array is all zeros, return any valid split as `[0, n-1]` (since all parts will be 0). + +2. **Identify target 1's in each part:** + - The target number of 1's in each part is `total_ones // 3`. + +3. **Find the starting index of each part:** + - Locate the start of each part by finding the index where the 1's for each part begins. + +4. **Check for matching parts:** + - Ensure that the parts from the identified start indices match in terms of the sequence and trailing zeros. + +5. **Return the valid indices if parts match:** + - If valid, return the appropriate indices, otherwise return `[-1, -1]`. + +## Step-by-Step Algorithm + +1. Count the number of 1's in the array. If it's not divisible by 3, return `[-1, -1]`. +2. If the array is all zeros, return `[0, arr.length - 1]`. +3. Calculate the target number of 1's per part. +4. Identify the starting indices for each part by counting the 1's until reaching the target for each part. +5. Compare the parts to ensure they are identical. +6. Return the indices if parts are identical, otherwise return `[-1, -1]`. + +## Solution + +### Python +```python +def threeEqualParts(arr): + ones = sum(arr) + if ones % 3 != 0: + return [-1, -1] + if ones == 0: + return [0, len(arr) - 1] + + k = ones // 3 + ones_seen = 0 + first = second = third = -1 + + for i in range(len(arr)): + if arr[i] == 1: + if ones_seen == 0: + first = i + elif ones_seen == k: + second = i + elif ones_seen == 2 * k: + third = i + ones_seen += 1 + + length = len(arr) - third + if first + length <= second and second + length <= third: + if arr[first:first + length] == arr[second:second + length] == arr[third:]: + return [first + length - 1, second + length] + + return [-1, -1] +``` + +### Java +```java +public int[] threeEqualParts(int[] arr) { + int ones = 0; + for (int num : arr) { + if (num == 1) ones++; + } + if (ones % 3 != 0) return new int[] {-1, -1}; + if (ones == 0) return new int[] {0, arr.length - 1}; + + int k = ones / 3; + int first = -1, second = -1, third = -1; + int count = 0; + for (int i = 0; i < arr.length; i++) { + if (arr[i] == 1) { + if (count == 0) first = i; + else if (count == k) second = i; + else if (count == 2 * k) third = i; + count++; + } + } + + int len = arr.length - third; + if (first + len <= second && second + len <= third) { + for (int i = 0; i < len; i++) { + if (arr[first + i] != arr[second + i] || arr[first + i] != arr[third + i]) { + return new int[] {-1, -1}; + } + } + return new int[] {first + len - 1, second + len}; + } + return new int[] {-1, -1}; +} +``` + +### C++ +```cpp +#include +using namespace std; + +vector threeEqualParts(vector& arr) { + int ones = 0; + for (int num : arr) { + if (num == 1) ones++; + } + if (ones % 3 != 0) return {-1, -1}; + if (ones == 0) return {0, (int)arr.size() - 1}; + + int k = ones / 3; + int first = -1, second = -1, third = -1; + int count = 0; + for (int i = 0; i < arr.size(); i++) { + if (arr[i] == 1) { + if (count == 0) first = i; + else if (count == k) second = i; + else if (count == 2 * k) third = i; + count++; + } + } + + int len = arr.size() - third; + if (first + len <= second && second + len <= third) { + for (int i = 0; i < len; i++) { + if (arr[first + i] != arr[second + i] || arr[first + i] != arr[third + i]) { + return {-1, -1}; + } + } + return {first + len - 1, second + len}; + } + return {-1, -1}; +} +``` + +### C +```c +#include + +int* threeEqualParts(int* arr, int arrSize, int* returnSize) { + int ones = 0; + for (int i = 0; i < arrSize; i++) { + if (arr[i] == 1) ones++; + } + int* result = (int*)malloc(2 * sizeof(int)); + if (ones % 3 != 0) { + result[0] = -1; + result[1] = -1; + *returnSize = 2; + return result; + } + if (ones == 0) { + result[0] = 0; + result[1] = arrSize - 1; + *returnSize = 2; + return result; + } + + int k = ones / 3; + int first = -1, second = -1, third = -1; + int count = 0; + for (int i = 0; i < arrSize; i++) { + if (arr[i] == 1) { + if (count == 0) first = i; + else if (count == k) second = i; + else if (count == 2 * k) third = i; + count++; + } + } + + int len = arrSize - third; + if (first + len <= second && second + len <= third) { + for (int i = 0; i < len; i++) { + if (arr[first + i] != arr[second + i] || arr[first + i] != arr[third + i]) { + result[0] = -1; + result[1] = -1; + *returnSize = 2; + return result; + } + } + result[0] = first + len - 1; + result[1] = second + len; + *returnSize = 2; + return result; + } + result[0] = -1; + result[1] = -1; + *returnSize = 2; + return result; +} +``` + +### JavaScript +```javascript +var threeEqualParts = function(arr) { + const ones = arr.reduce((a, b) => a + b, 0); + if (ones % 3 !== 0) return [-1, -1]; + if (ones === 0) return [0, arr.length - 1]; + + const k = ones / 3; + let first = -1, second = -1, third = -1, count = 0; + for (let i = 0; i < arr.length; i++) { + if (arr[i] === 1) { + if (count === 0) first = i; + else if (count === k) second = i; + else if (count === 2 * k) third = i; + count++; + } + } + + const len = arr.length - third; + if (first + len <= second && second + len <= third) { + for (let i = 0; i < len; i++) { + if (arr[first + i] !== arr[second + i] || arr[first + i] !== arr[third + i]) { + return [-1, -1]; + } + } + return [first + len - 1, second + len]; + } + return [-1, -1]; +}; +``` + +## Conclusion + +This problem involves dividing an array of binary digits into three equal parts such that each part represents the same binary value. By counting the number of 1's and identifying the correct indices for each part, we can determine if such a division is possible and return the appropriate indices. The provided solutions in Python, Java, C++, C, and JavaScript offer various implementations of this approach. \ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0929-unique-email-addresses.md b/solutions/lc-solutions/0900-0999/0929-unique-email-addresses.md new file mode 100644 index 0000000..8b4329a --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0929-unique-email-addresses.md @@ -0,0 +1,166 @@ +--- +id: Unique-Email-Addresses +title: Unique Email Addresses +sidebar_label: 0929 - Unique Email Addresses +tags: + - medium + - Strings + - Hash Table +--- + +## Problem Description + +Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'. + +For example, in "alice@leetcode.com", "alice" is the local name, and "leetcode.com" is the domain name. If you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names. + +For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. If you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names. + +For example, "m.y+name@email.com" will be forwarded to "my@email.com". It is possible to use both of these rules at the same time. + +Given an array of strings emails where we send one email to each emails[i], return the number of different addresses that actually receive mails. + +## Examples + +**Example 1:** + +``` +Input: emails = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"] +Output: 2 +Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails. +``` + +**Example 2:** + +``` +Input: emails = ["a@leetcode.com","b@leetcode.com","c@leetcode.com"] +Output: 3 +``` + +## Constraints + +``` +1 <= emails.length <= 100 +1 <= emails[i].length <= 100 +emails[i] consist of lowercase English letters, '+', '.' and '@'. +Each emails[i] contains exactly one '@' character. +All local and domain names are non-empty. +Local names do not start with a '+' character. +Domain names end with the ".com" suffix. +``` + +## Solution + +### Python + +```python +class Solution: + def numUniqueEmails(self, emails: List[str]) -> int: + unique_emails = set() + for email in emails: + local, domain = email.split('@') + local = local.split('+')[0].replace('.', '') + unique_emails.add(local + '@' + domain) + return len(unique_emails) + +# Example usage: +solution = Solution() +print(solution.numUniqueEmails(["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"])) # Output: 2 +``` + +### C++ + +```cpp +#include +#include +#include +using namespace std; + +class Solution { +public: + int numUniqueEmails(vector& emails) { + unordered_set uniqueEmails; + for (const string& email : emails) { + string local; + string domain; + bool atFound = false; + bool plusFound = false; + for (char c : email) { + if (c == '@') { + atFound = true; + } + if (atFound) { + domain += c; + } else { + if (c == '+') { + plusFound = true; + } + if (!plusFound && c != '.') { + local += c; + } + } + } + uniqueEmails.insert(local + domain); + } + return uniqueEmails.size(); + } +}; + +// Example usage: +int main() { + Solution solution; + vector emails = {"test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"}; + int result = solution.numUniqueEmails(emails); // Output: 2 + cout << result << endl; + return 0; +} +``` + +### Java + +```java +import java.util.HashSet; +import java.util.Set; + +class Solution { + public int numUniqueEmails(String[] emails) { + Set uniqueEmails = new HashSet<>(); + for (String email : emails) { + String[] parts = email.split("@"); + String local = parts[0].split("\+")[0].replace(".", ""); + uniqueEmails.add(local + "@" + parts[1]); + } + return uniqueEmails.size(); + } + + public static void main(String[] args) { + Solution solution = new Solution(); + String[] emails = {"test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"}; + int result = solution.numUniqueEmails(emails); // Output: 2 + System.out.println(result); + } +} +``` + +### JavaScript + +```javascript +var numUniqueEmails = function (emails) { + let uniqueEmails = new Set(); + for (let email of emails) { + let [local, domain] = email.split("@"); + local = local.split("+")[0].replace(/\./g, ""); + uniqueEmails.add(local + "@" + domain); + } + return uniqueEmails.size; +}; + +// Example usage: +console.log( + numUniqueEmails([ + "test.email+alex@leetcode.com", + "test.e.mail+bob.cathy@leetcode.com", + "testemail+david@lee.tcode.com", + ]) +); // Output: 2 +``` diff --git a/solutions/lc-solutions/0900-0999/0930-binary-sub-arrays-with-sum.md b/solutions/lc-solutions/0900-0999/0930-binary-sub-arrays-with-sum.md new file mode 100644 index 0000000..6602361 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0930-binary-sub-arrays-with-sum.md @@ -0,0 +1,168 @@ +--- +id: binary-sub-arrays-with-sum +title: Binary Sub Arrays With Sum +sidebar_label: 0930- Binary Sub Arrays With Sum +tags: + - Leet code +description: "Solution to leetocde 930" +--- + +## Problem Statement + +Given a binary array `nums` and an integer `goal`, return the number of non-empty subarrays with a sum equal to `goal`. + +A subarray is a contiguous part of the array. + +### Example 1 + +**Input:** + +``` +nums = [1,0,1,0,1] +goal = 2 +``` + +**Output:** + +``` +4 +``` + +**Explanation:** +The 4 subarrays are bolded and underlined below: + +``` +[1,0,1,0,1] +[1,0,1,0,1] +[1,0,1,0,1] +[1,0,1,0,1] +``` + +### Example 2 + +**Input:** + +``` +nums = [0,0,0,0,0] +goal = 0 +``` + +**Output:** + +``` +15 +``` + +### Constraints + +- $1 <= nums.length <= 3 * 104$ +- $nums[i] is either 0 or 1.$ +- $0 <= goal <= nums.length$ + +### Algorithm + +1. **Define a helper function `atMost(nums, goal)`**: + + - Initialize `head`, `tail`, `total`, and `result` to 0. + - Iterate through the array using `head`: + - Add the value at `nums[head]` to `total`. + - While `total` is greater than `goal`: + - Subtract the value at `nums[tail]` from `total`. + - Increment `tail`. + - Add `head - tail + 1` to `result`. + - Return `result`. + +2. **Calculate the number of subarrays with sum exactly equal to `goal`**: + - Return `atMost(nums, goal) - atMost(nums, goal - 1)`. + +### Code Implementation + +### Python + +```python +class Solution: + def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: + return self.atMost(nums, goal) - self.atMost(nums, goal - 1) + + def atMost(self, nums: List[int], goal: int) -> int: + head, tail, total, result = 0, 0, 0, 0 + for head in range(len(nums)): + total += nums[head] + while total > goal and tail <= head: + total -= nums[tail] + tail += 1 + result += head - tail + 1 + return result +``` + +### C++ + +```cpp +class Solution { +public: + int numSubarraysWithSum(vector& nums, int goal) { + return atMost(nums, goal) - atMost(nums, goal - 1); + } + +private: + int atMost(vector& nums, int goal) { + int head = 0, tail = 0, total = 0, result = 0; + for (head = 0; head < nums.size(); ++head) { + total += nums[head]; + while (total > goal && tail <= head) { + total -= nums[tail]; + ++tail; + } + result += head - tail + 1; + } + return result; + } +}; +``` + +### Java + +```java +class Solution { + public int numSubarraysWithSum(int[] nums, int goal) { + return atMost(nums, goal) - atMost(nums, goal - 1); + } + + private int atMost(int[] nums, int goal) { + int head = 0, tail = 0, total = 0, result = 0; + for (head = 0; head < nums.length; ++head) { + total += nums[head]; + while (total > goal && tail <= head) { + total -= nums[tail]; + ++tail; + } + result += head - tail + 1; + } + return result; + } +} +``` + +### JavaScript + +```javascript +var numSubarraysWithSum = function (nums, goal) { + return atMost(nums, goal) - atMost(nums, goal - 1); +}; + +function atMost(nums, goal) { + let head = 0, + tail = 0, + total = 0, + result = 0; + for (head = 0; head < nums.length; ++head) { + total += nums[head]; + while (total > goal && tail <= head) { + total -= nums[tail]; + ++tail; + } + result += head - tail + 1; + } + return result; +} +``` diff --git a/solutions/lc-solutions/0900-0999/0931-minimum-falling-path-sum.md b/solutions/lc-solutions/0900-0999/0931-minimum-falling-path-sum.md new file mode 100644 index 0000000..a0dbae6 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0931-minimum-falling-path-sum.md @@ -0,0 +1,210 @@ +--- +id: minimum-falling-path-sum +title: Minimum Falling Path Sum +sidebar_label: 0931- Minimum Falling Path Sum +tags: + - Leet code +description: "Solution to leetocde 931" +--- + +## Problem Statement + +Given an \( n \times n \) array of integers `matrix`, return the minimum sum of any falling path through the matrix. + +A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position \((row, col)\) will be \((row + 1, col - 1)\), \((row + 1, col)\), or \((row + 1, col + 1)\). + +### Example 1 + +**Input:** + +``` +matrix = [[2, 1, 3], + [6, 5, 4], + [7, 8, 9]] +``` + +**Output:** + +``` +13 +``` + +**Explanation:** +There are two falling paths with a minimum sum as shown. + +### Example 2 + +**Input:** + +``` +matrix = [[-19, 57], + [-40, -5]] +``` + +**Output:** + +``` +-59 +``` + +**Explanation:** +The falling path with a minimum sum is shown. + +### Constraints + +- $n == matrix.length == matrix[i].length$ +- $1 <= n <= 100$ +- $-100 <= matrix[i][j] <= 100$ + +## Algorithm + +To solve this problem, we use dynamic programming. The idea is to keep a `dp` array where `dp[i][j]` represents the minimum sum of a falling path reaching the element at `matrix[i][j]`. + +1. **Initialize the DP table**: + + - Create a 2D list `dp` with the same dimensions as `matrix`. + - Initialize the first row of `dp` with the first row of `matrix` since the falling path can start from any element in the first row. + +2. **Fill the DP table**: + + - For each element `matrix[i][j]` in the subsequent rows: + - Calculate the minimum sum path to reach `matrix[i][j]` from the previous row: + - If `j > 0`, consider the element from the top-left diagonal `dp[i-1][j-1]`. + - Consider the element directly above `dp[i-1][j]`. + - If `j < n-1`, consider the element from the top-right diagonal `dp[i-1][j+1]`. + - Update `dp[i][j]` with the minimum of these values plus `matrix[i][j]`. + +3. **Find the minimum falling path sum**: + - The minimum sum of any falling path will be the minimum value in the last row of `dp`. + +### Pseudocode + +``` +function minFallingPathSum(matrix): + h = length of matrix + if h == 0: + return 0 + w = length of matrix[0] + dp = 2D list of size h x w initialized to infinity + dp[-1] = matrix[-1] + + for i from h-2 to 0: + for j from 0 to w-1: + dp[i][j] = matrix[i][j] + min( + dp[i+1][j], + dp[i+1][j-1] if j > 0 else infinity, + dp[i+1][j+1] if j < w-1 else infinity + ) + + return min(dp[0]) +``` + +## Python Code + +```python +from typing import List + +class Solution: + def minFallingPathSum(self, matrix: List[List[int]]) -> int: + h = len(matrix) + if h == 0: + return 0 + w = len(matrix) + dp = [[float('inf')] * w for _ in range(h)] + dp[-1] = matrix[-1] + + for i in range(h-2, -1, -1): + for j in range(w): + dp[i][j] = matrix[i][j] + min( + dp[i+1][j], + dp[i+1][j-1] if j > 0 else float("inf"), + dp[i+1][j+1] if j < w-1 else float("inf") + ) + return min(dp[0]) +``` + +## Java Code + +```java +class Solution { + public int minFallingPathSum(int[][] matrix) { + int h = matrix.length; + if (h == 0) { + return 0; + } + int w = matrix[0].length; + int[][] dp = new int[h][w]; + for (int j = 0; j < w; j++) { + dp[h-1][j] = matrix[h-1][j]; + } + + for (int i = h - 2; i >= 0; i--) { + for (int j = 0; j < w; j++) { + int down = dp[i+1][j]; + int downLeft = (j > 0) ? dp[i+1][j-1] : Integer.MAX_VALUE; + int downRight = (j < w-1) ? dp[i+1][j+1] : Integer.MAX_VALUE; + dp[i][j] = matrix[i][j] + Math.min(down, Math.min(downLeft, downRight)); + } + } + int minPathSum = Integer.MAX_VALUE; + for (int j = 0; j < w; j++) { + minPathSum = Math.min(minPathSum, dp[0][j]); + } + return minPathSum; + } +} +``` + +## C++ Code + +```cpp +class Solution { +public: + int minFallingPathSum(vector>& matrix) { + int h = matrix.size(); + if (h == 0) { + return 0; + } + int w = matrix[0].size(); + vector> dp(h, vector(w, INT_MAX)); + dp[h-1] = matrix[h-1]; + + for (int i = h - 2; i >= 0; --i) { + for (int j = 0; j < w; ++j) { + int down = dp[i+1][j]; + int downLeft = (j > 0) ? dp[i+1][j-1] : INT_MAX; + int downRight = (j < w-1) ? dp[i+1][j+1] : INT_MAX; + dp[i][j] = matrix[i][j] + min(down, min(downLeft, downRight)); + } + } + return *min_element(dp[0].begin(), dp[0].end()); + } +}; +``` + +## JavaScript Code + +```javascript +var minFallingPathSum = function (matrix) { + let h = matrix.length; + if (h === 0) { + return 0; + } + let w = matrix[0].length; + let dp = Array.from({ length: h }, () => Array(w).fill(Infinity)); + dp[h - 1] = [...matrix[h - 1]]; + + for (let i = h - 2; i >= 0; i--) { + for (let j = 0; j < w; j++) { + dp[i][j] = + matrix[i][j] + + Math.min( + dp[i + 1][j], + j > 0 ? dp[i + 1][j - 1] : Infinity, + j < w - 1 ? dp[i + 1][j + 1] : Infinity + ); + } + } + return Math.min(...dp[0]); +}; +``` diff --git a/solutions/lc-solutions/0900-0999/0932-beautiful-array.md b/solutions/lc-solutions/0900-0999/0932-beautiful-array.md new file mode 100644 index 0000000..88a5f47 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0932-beautiful-array.md @@ -0,0 +1,171 @@ +--- +id: beautiful-array +title: Beautiful Array +sidebar_label: 0932- Beautiful Array +tags: + - Leet code +description: "Solution to leetocde 932" +--- + +### Problem Statement + +An array `nums` of length `n` is beautiful if: + +1. `nums` is a permutation of the integers in the range `[1, n]`. +2. For every `0 <= i < j < n`, there is no index `k` such that `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`. + +Given the integer `n`, return any beautiful array `nums` of length `n`. There will be at least one valid answer for the given `n`. + +## Example 1: + +Input: `n = 4` +Output: `[2,1,4,3]` + +## Example 2: + +Input: `n = 5` +Output: `[3,1,2,5,4]` + +## Constraints: + +- $1 <= n <= 1000$ + +### Algorithm + +1. **Recursive Construction**: + + - Split the array into odd and even indexed numbers. + - Recursively apply the same splitting process to each half until each sub-array contains only one element. + - Combine the results from the recursive calls in an interleaved manner to ensure that no two adjacent numbers in the final array have a difference of 1. + +2. **Constructing the Beautiful Array**: + - Start with the array `[1, 2, ..., n]`. + - Use a helper function to recursively split the array into odd and even indexed parts. + - Combine the results by interleaving the results from the recursive calls. + +### Code Implementation + +### Python Implementation + +```python +class Solution: + def beautifulArray(self, n: int) -> List[int]: + if n == 1: + return [1] + + odds = self.beautifulArray((n + 1) // 2) # Recursively get beautiful array for odd indices + evens = self.beautifulArray(n // 2) # Recursively get beautiful array for even indices + + return [2 * x - 1 for x in odds] + [2 * x for x in evens] + +# Example usage: +solution = Solution() +print(solution.beautifulArray(5)) # Output: [1, 3, 2, 5, 4] +``` + +### Java + +```java +import java.util.*; + +class Solution { + public int[] beautifulArray(int n) { + if (n == 1) { + return new int[]{1}; + } + + int[] odds = beautifulArray((n + 1) / 2); // Recursively get beautiful array for odd indices + int[] evens = beautifulArray(n / 2); // Recursively get beautiful array for even indices + + int[] result = new int[n]; + int index = 0; + for (int odd : odds) { + result[index++] = 2 * odd - 1; + } + for (int even : evens) { + result[index++] = 2 * even; + } + + return result; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + int n = 5; + int[] beautifulArr = solution.beautifulArray(n); + System.out.println(Arrays.toString(beautifulArr)); // Output: [1, 3, 2, 5, 4] + } +} +``` + +### C++ + +```cpp +#include + +class Solution { +public: + vector beautifulArray(int n) { + if (n == 1) { + return {1}; + } + + vector odds = beautifulArray((n + 1) / 2); // Recursively get beautiful array for odd indices + vector evens = beautifulArray(n / 2); // Recursively get beautiful array for even indices + + vector result(n); + int index = 0; + for (int odd : odds) { + result[index++] = 2 * odd - 1; + } + for (int even : evens) { + result[index++] = 2 * even; + } + + return result; + } +}; + +// Example usage: +#include +using namespace std; + +int main() { + Solution solution; + int n = 5; + vector beautifulArr = solution.beautifulArray(n); + for (int num : beautifulArr) { + cout << num << " "; + } + cout << endl; // Output: 1 3 2 5 4 + return 0; +} +``` + +### JavaScript + +```javascript +var beautifulArray = function (n) { + if (n === 1) { + return [1]; + } + + let odds = beautifulArray(Math.ceil(n / 2)); // Recursively get beautiful array for odd indices + let evens = beautifulArray(Math.floor(n / 2)); // Recursively get beautiful array for even indices + + let result = []; + for (let odd of odds) { + result.push(2 * odd - 1); + } + for (let even of evens) { + result.push(2 * even); + } + + return result; +}; + +// Example usage: +let n = 5; +let beautifulArr = beautifulArray(n); +console.log(beautifulArr); // Output: [1, 3, 2, 5, 4] +``` diff --git a/solutions/lc-solutions/0900-0999/0933-number-of-recent-calls.md b/solutions/lc-solutions/0900-0999/0933-number-of-recent-calls.md new file mode 100644 index 0000000..6f9303e --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0933-number-of-recent-calls.md @@ -0,0 +1,135 @@ +--- +id: number-of-recent-calls +title: Number Of Recent Calls +sidebar_label: 0930- Number Of Recent Calls +tags: + - Leet code +description: "Solution to leetocde 933" +--- + +### Problem Statement + +You have a `RecentCounter` class which counts the number of recent requests within a certain time frame. + +Implement the `RecentCounter` class: + +- `RecentCounter()`: Initializes the counter with zero recent requests. +- `int ping(int t)`: Adds a new request at time `t`, where `t` represents some time in milliseconds, and returns the number of requests that have happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range `[t - 3000, t]`. + +It is guaranteed that every call to `ping` uses a strictly larger value of `t` than the previous call. + +### Example: + +```plaintext +Input +["RecentCounter", "ping", "ping", "ping", "ping"] +[[], [1], [100], [3001], [3002]] + +Output +[null, 1, 2, 3, 3] + +Explanation: +RecentCounter recentCounter = new RecentCounter(); +recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1 +recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2 +recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3 +recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3 +``` + +## Constraints: + +- $`1 <= t <= 10^9`$ +- $Each test case will call `ping` with strictly increasing values of `t`.$ +- $At most 10^4 calls will be made to `ping`.$ + +### Algorithm + +1. **Initialization**: Each implementation initializes a list (`records` in Python, `std::vector` in C++, `ArrayList` in Java, and array in JavaScript) to store timestamps and a `start` index to track the beginning of the valid range. + +2. **`ping` Method**: + - Appends the current timestamp to `records`. + - Checks and updates `start` to maintain the invariant that timestamps within the last 3000 milliseconds are within the range `[start, end]`. + - Returns the number of valid timestamps (from `start` to end of `records`). + +### Python Implementation + +```python +class RecentCounter: + def __init__(self): + self.records = [] + self.start = 0 + + def ping(self, t: int) -> int: + self.records.append(t) + while self.records[self.start] < t - 3000: + self.start += 1 + return len(self.records) - self.start +``` + +### C++ Implementation + +```cpp +#include + +class RecentCounter { +private: + std::vector records; + int start; +public: + RecentCounter() { + start = 0; + } + + int ping(int t) { + records.push_back(t); + while (records[start] < t - 3000) { + start++; + } + return records.size() - start; + } +}; +``` + +### Java Implementation + +```java +import java.util.ArrayList; +import java.util.List; + +class RecentCounter { + private List records; + private int start; + + public RecentCounter() { + records = new ArrayList<>(); + start = 0; + } + + public int ping(int t) { + records.add(t); + while (records.get(start) < t - 3000) { + start++; + } + return records.size() - start; + } +} +``` + +### JavaScript Implementation + +```javascript +class RecentCounter { + constructor() { + this.records = []; + this.start = 0; + } + + ping(t) { + this.records.push(t); + while (this.records[this.start] < t - 3000) { + this.start++; + } + return this.records.length - this.start; + } +} +``` diff --git a/solutions/lc-solutions/0900-0999/0941-valid-mountain-array.md b/solutions/lc-solutions/0900-0999/0941-valid-mountain-array.md new file mode 100644 index 0000000..0ab59da --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0941-valid-mountain-array.md @@ -0,0 +1,113 @@ +--- +id: valid-mountain-array +title: Valid Mountain Array +level: easy +sidebar_label: Valid Mountain Array +tags: + - Array +description: "This document provides a solution for the Valid Mountain Array problem." +--- + +## Problem Statement + +Given an array of integers `arr`, return `true` if and only if it is a valid mountain array. + +Recall that `arr` is a mountain array if and only if: + +- `arr.length >= 3` +- There exists some `i` with `0 < i < arr.length - 1` such that: + - `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` + - `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` + +**Example 1:** + +Input: `arr = [2, 1]` + +Output: `false` + +**Example 2:** + +Input: `arr = [3, 5, 5]` + +Output: `false` + +**Example 3:** + +Input: `arr = [0, 3, 2, 1]` + +Output: `true` + +**Constraints:** + +- `1 <= arr.length <= 10^4` +- `0 <= arr[i] <= 10^4` + +## Solutions + +### Approach + +To determine if the given array is a valid mountain array, follow these steps: + +1. **Initial Check**: Ensure the length of the array is at least 3. +2. **Increasing Phase**: Traverse the array from the start, checking if each element is less than the next one. +3. **Peak Check**: If the peak is at the beginning or end of the array, it's not a valid mountain. +4. **Decreasing Phase**: Continue traversing from the peak, checking if each element is greater than the next one. +5. **Final Check**: Ensure that the entire array was traversed. + +### Java + +```java +class Solution { + public boolean validMountainArray(int[] arr) { + int len = arr.length; + if (len < 3) { + return false; + } + + boolean flag = true; + for (int i = 0; i < len - 1; i++) { + if (arr[i] == arr[i + 1]) { + return false; + } + if (flag && arr[i + 1] < arr[i]) { + if (i == 0) return false; + flag = false; + } + if (!flag && arr[i] < arr[i + 1]) { + return false; + } + } + if (flag) { + return false; + } + return true; + } +} + +``` + +### Python + +```Python +class Solution: + def validMountainArray(self, arr: List[int]) -> bool: + length = len(arr) + if length < 3: + return False + + flag = True + for i in range(length - 1): + if arr[i] == arr[i + 1]: + return False + if flag and arr[i + 1] < arr[i]: + if i == 0: + return False + flag = False + if not flag and arr[i] < arr[i + 1]: + return False + + if flag: + return False + + return True +``` diff --git a/solutions/lc-solutions/0900-0999/0944-delete-columns-to-make-sorted.md b/solutions/lc-solutions/0900-0999/0944-delete-columns-to-make-sorted.md new file mode 100644 index 0000000..aa02e71 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0944-delete-columns-to-make-sorted.md @@ -0,0 +1,169 @@ +--- +id: Delete-Columns-to-Make-Sorted +title: Delete Columns to Make Sorted +sidebar_label: 0944 - Delete Columns to Make Sorted +tags: + - medium + - Arrays + - Strings + - Greedy +--- + +## Problem Description + +You are given an array of `n` strings `strs`, all of the same length. The strings can be arranged such that there is one on each line, making a grid. + +For example, `strs = ["abc", "bce", "cae"]` can be arranged as follows: + +``` +abc +bce +cae +``` + +You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted, while column 1 ('b', 'c', 'a') is not, so you would delete column 1. + +Return the number of columns that you will delete. + +## Examples + +**Example 1:** + +``` +Input: strs = ["cba","daf","ghi"] +Output: 1 +Explanation: The grid looks as follows: + cba + daf + ghi +Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. +``` + +**Example 2:** + +``` +Input: strs = ["a","b"] +Output: 0 +Explanation: The grid looks as follows: + a + b +Column 0 is the only column and is sorted, so you will not delete any columns. +``` + +**Example 3:** + +``` +Input: strs = ["zyx","wvu","tsr"] +Output: 3 +Explanation: The grid looks as follows: + zyx + wvu + tsr +All 3 columns are not sorted, so you will delete all 3. +``` + +## Constraints + +``` +n == strs.length +1 <= n <= 100 +1 <= strs[i].length <= 1000 +strs[i] consists of lowercase English letters. +``` + +## Solution + +### Python + +```python +class Solution: + def minDeletionSize(self, strs: List[str]) -> int: + count = 0 + for col in range(len(strs[0])): + for row in range(1, len(strs)): + if strs[row][col] < strs[row - 1][col]: + count += 1 + break + return count + +# Example usage: +solution = Solution() +print(solution.minDeletionSize(["cba","daf","ghi"])) # Output: 1 +``` + +### C++ + +```cpp +#include +#include +using namespace std; + +class Solution { +public: + int minDeletionSize(vector& strs) { + int count = 0; + for (int col = 0; col < strs[0].size(); ++col) { + for (int row = 1; row < strs.size(); ++row) { + if (strs[row][col] < strs[row - 1][col]) { + count += 1; + break; + } + } + } + return count; + } +}; + +// Example usage: +int main() { + Solution solution; + vector strs = {"cba","daf","ghi"}; + cout << solution.minDeletionSize(strs) << endl; // Output: 1 + return 0; +} +``` + +### Java + +```java +class Solution { + public int minDeletionSize(String[] strs) { + int count = 0; + for (int col = 0; col < strs[0].length(); ++col) { + for (int row = 1; row < strs.length; ++row) { + if (strs[row].charAt(col) < strs[row - 1].charAt(col)) { + count += 1; + break; + } + } + } + return count; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + String[] strs = {"cba", "daf", "ghi"}; + System.out.println(solution.minDeletionSize(strs)); // Output: 1 + } +} +``` + +### JavaScript + +```javascript +var minDeletionSize = function (strs) { + let count = 0; + for (let col = 0; col < strs[0].length; ++col) { + for (let row = 1; row < strs.length; ++row) { + if (strs[row][col] < strs[row - 1][col]) { + count += 1; + break; + } + } + } + return count; +}; + +// Example usage: +console.log(minDeletionSize(["cba", "daf", "ghi"])); // Output: 1 +``` diff --git a/solutions/lc-solutions/0900-0999/0945-minimum-increment-to-make-array-unique.md b/solutions/lc-solutions/0900-0999/0945-minimum-increment-to-make-array-unique.md new file mode 100644 index 0000000..1fa22ea --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0945-minimum-increment-to-make-array-unique.md @@ -0,0 +1,263 @@ +--- +id: minimum-increment-to-make-array-unique +title: Minimum Increment to Make Array Unique +sidebar_label: 945. Minimum Increment to Make Array Unique + +tags: +- Array +- Vector +- Map +- Unordered Map + +description: "This is a solution to the minimum increment to make a array unique problem on LeetCode." +--- + +## Problem Description +You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`. + +Return *the minimum number of moves to make every value in* `nums` **unique**. + +The test cases are generated so that the answer fits in a 32-bit integer. +### Examples + +**Example 1:** +``` +Input: nums = [1,2,2] +Output: 1 +Explanation: After 1 move, the array could be [1, 2, 3]. +``` + +**Example 2:** +``` +Input: nums = [3,2,1,2,1,7] +Output: 6 +Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7]. +It can be shown with 5 or less moves that it is impossible for the array to have all unique values. + +``` + + +### Constraints +- `1 <= nums.length <= 10^5` +- `0 <= nums[i] <= 10^5` + + +## Solution for Minimum Increment to Make Array Unique +### Approach +#### Brute Force +- **Iterate and Adjust**: For each element in the array, if there are duplicates, increment them one by one until they become unique. Count each increment as a move. + +- **Repeat**: Continue this process for each duplicate until all elements in the array are unique. + +**Implementation:** +```plaintext +1. Initialize a counter `moves` to 0. +2. Iterate through each element `num` in the array `nums`. + a. Use a hashmap to keep track of the frequency of each number. + b. If the number `num` appears more than once: + - Increment `num` until it becomes unique. + - Count each increment as a move (`moves++`). +3. Return the total number of moves required. +``` + +**Complexity:** +- Time Complexity: `O(n * k)`, where `n` is the number of elements in nums and `k` is the maximum number of increments needed to resolve duplicates. +- Space Complexity: `O(n)`, due to the hashmap storing frequencies. + +**Corner Cases:** +- Empty array: Return `0` since no moves are needed. +- Array with all unique elements: Return `0` as no adjustments are required. +- Arrays with varying frequencies and values: Handle each duplicate incrementally until all values are unique. + +#### Optimized Approach +- **Sort and Adjust**: Sort the array `nums`. Iterate through the sorted array and adjust each element to ensure uniqueness while keeping track of moves efficiently. +- **Greedy Adjustment**: As you iterate through the sorted array, if the current element is less than or equal to the previous element, adjust it to be one more than the previous element. + +**Implementation:** + +```plaintext +1. Sort the array `nums`. +2. Initialize a counter `moves` to 0. +3. Iterate through each element `num` in the sorted array `nums`: + a. If `num` is less than or equal to the previous element: + - Calculate the required increment to make `num` unique. + - Add this increment to `num`. + - Update `moves` by the calculated increment. + b. Update the previous element to the current `num`. +4. Return the total number of moves required. +``` + +**Complexity:** +- Time Complexity: `O(n log n)` due to sorting, where `n` is the number of elements in `nums`. Adjustments are made in linear time. +- Space Complexity: `O(1)` extra space if sorting in-place is allowed, otherwise `O(n)` for additional space for sorting. + +**Corner Cases:** +- Empty array: Return `0` since no moves are needed. +- Array with all unique elements: Return `0` as no adjustments are required. +- Arrays with varying frequencies and values: Efficiently handle adjustments in a sorted manner to minimize moves. + + + + + +#### Implementation + + ```jsx live + function Solution(arr) { + var minIncrementForUnique = function(nums) { + nums.sort((a, b) => a-b) + let moves = 0 + + for (let i = 1; i < nums.length; i++) { + if (nums[i] <= nums[i-1]) { + let increment = nums[i-1] - nums[i] + 1 + nums[i] += increment + moves += increment + } + } + + return moves + }; + const input = [3,2,1,2,1,7] + const originalInput = [...input] + const output = minIncrementForUnique(input) + return ( +
+

+ Input: + {JSON.stringify(originalInput)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + +#### Complexity Analysis + + - Time Complexity: $O(n)$ + - Space Complexity: $O(1)$ + + ## Code in Different Languages + + + + + + + ```javascript + var minIncrementForUnique = function(nums) { + nums.sort((a, b) => a - b); + let moves = 0; + for (let i = 1; i < nums.length; i++) { + if (nums[i] <= nums[i - 1]) { + let increment = nums[i - 1] - nums[i] + 1; + nums[i] += increment; + moves += increment; + } + } + return moves; + }; + ``` + + + + + + + ```typescript + function minIncrementForUnique(nums: number[]): number { + nums.sort((a, b) => a - b); + let moves = 0; + for (let i = 1; i < nums.length; i++) { + if (nums[i] <= nums[i - 1]) { + let increment = nums[i - 1] - nums[i] + 1; + nums[i] += increment; + moves += increment; + } + } + return moves; + } + ``` + + + + + + + ```python + + class Solution(object): + def minIncrementForUnique(self, nums): + nums.sort() + moves = 0 + for i in range(1, len(nums)): + if nums[i] <= nums[i - 1]: + increment = nums[i - 1] - nums[i] + 1 + nums[i] += increment + moves += increment + return moves + + ``` + + + + + + + ```java + import java.util.Arrays; + + class Solution { + public int minIncrementForUnique(int[] nums) { + Arrays.sort(nums); + int moves = 0; + for (int i = 1; i < nums.length; i++) { + if (nums[i] <= nums[i - 1]) { + int increment = nums[i - 1] - nums[i] + 1; + nums[i] += increment; + moves += increment; + } + } + return moves; + } + } + ``` + + + + + + + ```cpp + class Solution { + public: + int minIncrementForUnique(vector& nums) { + sort(nums.begin(), nums.end()); + int moves = 0; + for(int i=1;i + + +
+
+ +## References + +- **LeetCode Problem**: [Minimum Increment To Make Array Unique](https://leetcode.com/problems/minimum-increment-to-make-array-unique/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/minimum-increment-to-make-array-unique/solutions/) \ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0952-largest-component-size-by-common-factor.md b/solutions/lc-solutions/0900-0999/0952-largest-component-size-by-common-factor.md new file mode 100644 index 0000000..c611086 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0952-largest-component-size-by-common-factor.md @@ -0,0 +1,206 @@ +--- +id: largest-component-size-by-common-factor +title: Largest Component Size by Common Factor +sidebar_label: 0952 - Largest Component Size by Common Factor +tags: + - Array + - Hash Table + - Number Theory + - Math + - Union Find +description: "This is a solution to the Largest Component Size by Common Factor problem on LeetCode." +--- + +## Problem Description + +You are given an integer array of unique positive integers `A`. Consider the following graph: +* There are `A.length` nodes, labelled `A[0]` to `A[A.length - 1]`; +* There is an edge between `A[i]` and `A[j]` if and only if `A[i]` and `A[j]` share a common factor greater than `1`. + +Return the size of the largest connected component in the graph. + +### Examples + +**Example 1:** + +``` +Input: [4,6,15,35] +Output: 4 +``` +**Example 2:** + +``` +Input: [20,50,9,63] +Output: 2 +``` + +**Example 3:** + +``` +Input: [2,3,6,7,4,12,21,39] +Output: 8 +``` + +### Constraints +* `1 <= A.length <= 20000` +* `1 <= A[i] <= 100000` +* All the values of nums are **unique**. + +## Solution for largest-component-size-by-common-factor + +### Approach: Union each number with all of its factors + +#### Intuition: +The problem aims to find the largest connected component in an array where two elements are connected if they share a common factor greater than 1. + +1. **Union-Find Data Structure**: Disjoint Set Union helps in efficiently managing and merging sets. The key operations are Find (to find the representative of a set) and Union (to merge two sets). + +2. For each element in the array, find its factors and union the element with its factors. This way, all elements with common factors are connected. + +3. After processing all elements, count the size of each connected component and find the most frequent parent. + +### Code in Different Languages + +#### C++ + +```cpp +#include +#include +#include +#include +using namespace std; + +class DSU { +public: + DSU(int n): p_(n) { + for (int i = 0; i < n; ++i) + p_[i] = i; + } + + void Union(int x, int y) { + p_[Find(x)] = p_[Find(y)]; + } + + int Find(int x) { + if (p_[x] != x) p_[x] = Find(p_[x]); + return p_[x]; + } +private: + vector p_; +}; + +class Solution { +public: + int largestComponentSize(vector& A) { + int n = *max_element(begin(A), end(A)); + DSU dsu(n + 1); + for (int a : A) { + int t = sqrt(a); + for (int k = 2; k <= t; ++k) + if (a % k == 0) { + dsu.Union(a, k); + dsu.Union(a, a / k); + } + } + unordered_map c; + int ans = 1; + for (int a : A) + ans = max(ans, ++c[dsu.Find(a)]); + return ans; + } +}; +``` + +#### Java + +```java +class Solution { + private int[] uf; + + public int largestComponentSize(int[] A) { + if(A == null || A.length == 0) return 0; + int max = A[0]; + for(int i = 1; i < A.length; i++) max = Math.max(max, A[i]); + this.uf = new int[max + 1]; + for(int i = 0; i < uf.length; i++) this.uf[i] = i; + // For every number, find their factor and add to uf. + for(int i = 0; i < A.length; i++){ + for(int j = 2; j <= (int)Math.sqrt(A[i]); j++){ + if(A[i] % j == 0){ + union(A[i], j); + union(A[i], A[i] / j); + } + } + } + Map map = new HashMap<>(); + int res = 1; + for(int i = 0; i < A.length; i++){ + int root = find(A[i]); + int cur = map.containsKey(root) ? map.get(root): 0; + map.put(root, ++cur); + res = Math.max(res, cur); + } + return res; + } + + private void union(int i, int j){ + int p = find(i); + int q = find(j); + uf[p] = q; + } + + private int find(int j){ + if(uf[j] != j){ + uf[j] = find(uf[j]); + } + return uf[j]; + } +} +``` + +#### Python + +```python +from collections import defaultdict +import math + +class Solution: + def largestComponentSize(self, A): + p = list(range(max(A) + 1)) + + def find(x): + while p[x] != x: + p[x] = p[p[x]] + x = p[x] + return x + + def union(x, y): + p[find(x)] = find(y) + + for a in A: + for k in range(2, int(math.sqrt(a)) + 1): + if a % k == 0: + union(a, k) + union(a, a // k) + return max(collections.Counter(find(a) for a in A).values()) + +# Example usage: +solution = Solution() +print(solution.largestComponentSize([4,6,15,35])) # Output: 4 +print(solution.largestComponentSize([20,50,9,63])) # Output: 2 +print(solution.largestComponentSize([2,3,6,7,4,12,21,39])) # Output: 8 +``` + +### Complexity Analysis + +#### Time Complexity: $O(\sum \sqrt{A[i]})$ + +> **Reason**: For each element A[i], the algorithm checks up to $ \sqrt{A[i]} $ possible factors to perform union operations. + +#### Space Complexity: $O(max(A))$ + +> **Reason**: The Union-Find data structure requires space proportional to the maximum value in the array. + +## References + +- **LeetCode Problem**: [Largest Component Size by Common Factor](https://leetcode.com/problems/largest-component-size-by-common-factor/) diff --git a/solutions/lc-solutions/0900-0999/0953-verifying-an-alien-dictionary.md b/solutions/lc-solutions/0900-0999/0953-verifying-an-alien-dictionary.md new file mode 100644 index 0000000..c3f5d43 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0953-verifying-an-alien-dictionary.md @@ -0,0 +1,193 @@ +--- +id: Verifying-an-Alien-Dictionary +title: Verifying an Alien Dictionary +sidebar_label: 0953 - Verifying an Alien Dictionary +tags: + - medium + - Strings + - Hash Table +--- + +## Problem Description + +In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. + +Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language. + +## Examples + +**Example 1:** + +``` +Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" +Output: true +Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted. +``` + +**Example 2:** + +``` +Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" +Output: false +Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted. +``` + +**Example 3:** + +``` +Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" +Output: false +Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > 'βˆ…', where 'βˆ…' is defined as the blank character which is less than any other character (More info). +``` + +## Constraints + +``` +1 <= words.length <= 100 +1 <= words[i].length <= 20 +order.length == 26 +All characters in words[i] and order are English lowercase letters. +``` + +## Solution + +### Python + +```python +class Solution: + def isAlienSorted(self, words: List[str], order: str) -> bool: + order_index = {char: index for index, char in enumerate(order)} + + for i in range(len(words) - 1): + for j in range(len(words[i])): + if j >= len(words[i + 1]): + return False + if words[i][j] != words[i + 1][j]: + if order_index[words[i][j]] > order_index[words[i + 1][j]]: + return False + break + return True + +# Example usage: +solution = Solution() +print(solution.isAlienSorted(["hello","leetcode"], "hlabcdefgijkmnopqrstuvwxyz")) # Output: true +``` + +### C++ + +```cpp +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isAlienSorted(vector& words, string order) { + unordered_map order_index; + for (int i = 0; i < order.size(); ++i) { + order_index[order[i]] = i; + } + + for (int i = 0; i < words.size() - 1; ++i) { + if (!compare(words[i], words[i + 1], order_index)) { + return false; + } + } + return true; + } + +private: + bool compare(const string& word1, const string& word2, unordered_map& order_index) { + int len = min(word1.size(), word2.size()); + for (int i = 0; i < len; ++i) { + if (word1[i] != word2[i]) { + return order_index[word1[i]] < order_index[word2[i]]; + } + } + return word1.size() <= word2.size(); + } +}; + +// Example usage: +int main() { + Solution solution; + vector words = {"hello","leetcode"}; + string order = "hlabcdefgijkmnopqrstuvwxyz"; + bool result = solution.isAlienSorted(words, order); // Output: true + cout << result << endl; + return 0; +} +``` + +### Java + +```java +import java.util.HashMap; +import java.util.Map; + +class Solution { + public boolean isAlienSorted(String[] words, String order) { + Map orderIndex = new HashMap<>(); + for (int i = 0; i < order.length(); ++i) { + orderIndex.put(order.charAt(i), i); + } + + for (int i = 0; i < words.length - 1; ++i) { + if (!compare(words[i], words[i + 1], orderIndex)) { + return false; + } + } + return true; + } + + private boolean compare(String word1, String word2, Map orderIndex) { + int len = Math.min(word1.length(), word2.length()); + for (int i = 0; i < len; ++i) { + if (word1.charAt(i) != word2.charAt(i)) { + return orderIndex.get(word1.charAt(i)) < orderIndex.get(word2.charAt(i)); + } + } + return word1.length() <= word2.length; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + String[] words = {"hello","leetcode"}; + String order = "hlabcdefgijkmnopqrstuvwxyz"; + boolean result = solution.isAlienSorted(words, order); // Output: true + System.out.println(result); + } +} +``` + +### JavaScript + +```javascript +var isAlienSorted = function (words, order) { + const orderIndex = new Map(); + for (let i = 0; i < order.length; ++i) { + orderIndex.set(order[i], i); + } + + for (let i = 0; i < words.length - 1; ++i) { + if (!compare(words[i], words[i + 1], orderIndex)) { + return false; + } + } + return true; + + function compare(word1, word2, orderIndex) { + const len = Math.min(word1.length, word2.length); + for (let i = 0; i < len; ++i) { + if (word1[i] !== word2[i]) { + return orderIndex.get(word1[i]) < orderIndex.get(word2[i]); + } + } + return word1.length <= word2.length; + } +}; + +// Example usage: +console.log(isAlienSorted(["hello", "leetcode"], "hlabcdefgijkmnopqrstuvwxyz")); // Output: true +``` diff --git a/solutions/lc-solutions/0900-0999/0961-N-Repeated-Element-In-Size-2N-Array.md b/solutions/lc-solutions/0900-0999/0961-N-Repeated-Element-In-Size-2N-Array.md new file mode 100644 index 0000000..a9279df --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0961-N-Repeated-Element-In-Size-2N-Array.md @@ -0,0 +1,118 @@ +--- +id: n-repeated-element-in-size-2n-array +title: N-Repeated Element in Size 2N Array +sidebar_label: 961-N-Repeated-Element-in-Size-2N-Array +tags: + - Array + - Hash Table + - Counting +description: "Given an array of size 2N, find the element that is repeated N times." +--- + +## Problem + +You are given an integer array `nums` with a length of `2n`, where `n` is an integer greater than 1. The array contains `n + 1` unique elements, and exactly one of these elements is repeated `n` times. + +Return the element that is repeated `n` times. + +### Examples + +**Example 1:** + +**Input:** `nums = [1,2,3,3]` +**Output:** `3` + +**Example 2:** + +**Input:** `nums = [2,1,2,5,3,2]` +**Output:** `2` + +**Example 3:** + +**Input:** `nums = [5,1,5,2,5,3,5,4]` +**Output:** `5` + +### Constraints + +- `2 <= n <= 5000` +- `nums.length == 2 * n` +- `0 <= nums[i] <= 10^4` +- `nums` contains `n + 1` unique elements and one of them is repeated exactly `n` times. + +--- + +## Approach + +To solve this problem, we can use a hash table (dictionary) to count the occurrences of each element. The element that appears `n` times is the one we need to return. + +### Steps: + +1. Initialize an empty dictionary to count the frequency of each element. +2. Iterate through the array and update the count of each element in the dictionary. +3. Check if the count of any element reaches `n` and return that element. + +### Solution + +#### Java + +```java +class Solution { + public int repeatedNTimes(int[] nums) { + Map countMap = new HashMap<>(); + for (int num : nums) { + countMap.put(num, countMap.getOrDefault(num, 0) + 1); + if (countMap.get(num) == nums.length / 2) { + return num; + } + } + return -1; // Should never reach here + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + int repeatedNTimes(vector& nums) { + unordered_map countMap; + int n = nums.size() / 2; + for (int num : nums) { + countMap[num]++; + if (countMap[num] == n) { + return num; + } + } + return -1; // Should never reach here + } +}; +``` + +#### Python + +```python +class Solution: + def repeatedNTimes(self, nums: List[int]) -> int: + count = {} + n = len(nums) // 2 + for num in nums: + count[num] = count.get(num, 0) + 1 + if count[num] == n: + return num + return -1 # Should never reach here +``` + +### Complexity Analysis + +**Time Complexity:** O(n) + +> Reason: We iterate through the array once, and the operations we perform (insertion and lookup in a dictionary) are O(1) on average. + +**Space Complexity:** O(n) + +> Reason: We use a dictionary to store the frequency of each element, which in the worst case can contain `n + 1` unique elements. + +### References + +**LeetCode Problem:** [N-Repeated Element in Size 2N Array](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/) diff --git a/solutions/lc-solutions/0900-0999/0968-binary-tree-cameras.md b/solutions/lc-solutions/0900-0999/0968-binary-tree-cameras.md new file mode 100644 index 0000000..3b4147c --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0968-binary-tree-cameras.md @@ -0,0 +1,310 @@ +--- +id: binary-tree-cameras +title: Binary Tree Cameras +sidebar_label: 968. Binary Tree Cameras + +tags: +- Binary Tree +- Trees +- Binary Tree Cameras +- Leetcode + +description: "This is a solution to the Binary Tree Cameras problem on LeetCode." +--- + +## Problem Description +You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. +Return *the minimum number of cameras needed to monitor all nodes of the tree.* + +### Examples + +**Example 1:** + +![alt text](image.png) + +``` +Input: root = [0,0,null,0,0] +Output: 1 +Explanation: One camera is enough to monitor all nodes if placed as shown. +``` + +**Example 2:** + +![alt text](image-1.png) + +``` +Input: root = [0,0,null,0,null,0,null,null,0] +Output: 2 +Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement. +``` + + +### Constraints +- The number of nodes in the tree is in the range `[1, 1000]`. +- `Node.val == 0` + + +## Solution for Binary Tree Cameras +### Approach 1 +#### Brute Force +The brute force approach involves exploring all possible ways to place cameras and selecting the minimum configuration. This is impractical due to the exponential number of configurations. + + +**Steps:**: +- For each node, consider placing a camera at that node. +- Recursively determine the number of cameras needed for the left and right subtrees. +- Calculate the total number of cameras for each configuration and choose the minimum. + + +**Complexity:** +- Time Complexity: `O(2^n)` where `n` is the number of nodes in the tree. This is because each node has two possibilities: placing a camera or not. +- Space Complexity: `O(n)` due to the recursion stack. + +**Corner Cases:** +- An empty tree (should return 0). +- A single node tree (should return 1). +- A skewed tree where all nodes are in a single line (worst-case scenario for brute force). + +### Approach 2 +#### Optimized Approach +The optimized approach uses dynamic programming with a Depth-First Search (DFS) traversal. The idea is to use three states for each node: +- State 0: The node has no camera and is not monitored. +- State 1: The node is monitored but does not have a camera. +- State 2: The node has a camera. + +We then use these states to determine the minimum number of cameras needed. + +**Steps:** +- Define a recursive function `dfs(node)` that returns a tuple of three values representing the minimum cameras needed for states 0, 1, and 2. +- For each node, compute: + - State 0: The sum of the minimum cameras needed for state 1 of the left and right children. + - State 1: The minimum of state 2 (placing a camera) for either left or right child plus the minimum of states 0 or 1 for the other child. + - State 2: 1 (camera at this node) plus the minimum of states 0, 1, or 2 for both left and right children. +- The result for the root is the minimum of state 1 and state 2. + +**Implementation:** + +```python +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +def minCameraCover(root: TreeNode) -> int: + def dfs(node): + if not node: + return (0, 0, float('inf')) + + L = dfs(node.left) + R = dfs(node.right) + + d0 = L[1] + R[1] + d1 = min(L[2] + min(R[1], R[2]), R[2] + min(L[1], L[2])) + d2 = 1 + min(L) + min(R) + + return (d0, d1, d2) + + res = dfs(root) + return min(res[1], res[2]) +``` + +**Explanation:** +- **dfs(node)**: Returns a tuple (d0, d1, d2) for the given node. + - `d0`: Minimum cameras needed if the node is not monitored. + - `d1`: Minimum cameras needed if the node is monitored but has no camera. + - `d2`: Minimum cameras needed if the node has a camera. +- **Res**: For the root node, we return the minimum of `d1` and `d2`, ensuring all nodes are monitored. + +**Complexity:** +- Time Complexity: `O(n)` where `n` is the number of nodes. Each node is visited once +- Space Complexity: `O(h)` where `h` is the height of the tree due to the recursion stack. + +**Corner Cases:** +- An empty tree (should return 0). +- A single node tree (should return 1). +- A skewed tree where all nodes are in a single line. + + + + + ## Code in Different Languages + + + + + + + ```javascript + var minCameraCover = function(root) { + const NOT_NEEDED = 0; + const HAS_CAMERA = 1; + const NEEDS_CAMERA = 2; + + let cameras = 0; + + function dfs(node) { + if (!node) return NOT_NEEDED; + + const left = dfs(node.left); + const right = dfs(node.right); + + if (left === NEEDS_CAMERA || right === NEEDS_CAMERA) { + cameras++; + return HAS_CAMERA; + } + if (left === HAS_CAMERA || right === HAS_CAMERA) { + return NOT_NEEDED; + } + return NEEDS_CAMERA; + } + + return dfs(root) === NEEDS_CAMERA ? cameras + 1 : cameras; + }; + ``` + + + + + + + ```typescript + function minCameraCover(root: TreeNode | null): number { + const NOT_NEEDED = 0; + const HAS_CAMERA = 1; + const NEEDS_CAMERA = 2; + + let cameras = 0; + + function dfs(node: TreeNode | null): number { + if (!node) return NOT_NEEDED; + + const left = dfs(node.left); + const right = dfs(node.right); + + if (left === NEEDS_CAMERA || right === NEEDS_CAMERA) { + cameras++; + return HAS_CAMERA; + } + if (left === HAS_CAMERA || right === HAS_CAMERA) { + return NOT_NEEDED; + } + return NEEDS_CAMERA; + } + + return dfs(root) === NEEDS_CAMERA ? cameras + 1 : cameras; + }; + ``` + + + + + + + ```python + class Solution: + def minCameraCover(self, root: Optional[TreeNode]) -> int: + NOT_NEEDED = 0 + HAS_CAMERA = 1 + NEEDS_CAMERA = 2 + + cameras = 0 + + def dfs(node): + nonlocal cameras + if not node: + return NOT_NEEDED + + left = dfs(node.left) + right = dfs(node.right) + + if left == NEEDS_CAMERA or right == NEEDS_CAMERA: + cameras += 1 + return HAS_CAMERA + if left == HAS_CAMERA or right == HAS_CAMERA: + return NOT_NEEDED + return NEEDS_CAMERA + + return cameras + 1 if dfs(root) == NEEDS_CAMERA else cameras + ``` + + + + + + + ```java + class Solution { + private static final int NOT_NEEDED = 0; + private static final int HAS_CAMERA = 1; + private static final int NEEDS_CAMERA = 2; + + private int cameras = 0; + + public int minCameraCover(TreeNode root) { + return (dfs(root) == NEEDS_CAMERA ? 1 : 0) + cameras; + } + + private int dfs(TreeNode node) { + if (node == null) return NOT_NEEDED; + + int left = dfs(node.left); + int right = dfs(node.right); + + if (left == NEEDS_CAMERA || right == NEEDS_CAMERA) { + cameras++; + return HAS_CAMERA; + } + if (left == HAS_CAMERA || right == HAS_CAMERA) { + return NOT_NEEDED; + } + return NEEDS_CAMERA; + } + } + ``` + + + + + + + ```cpp + class Solution { + static const int NOT_NEEDED = 0; + static const int HAS_CAMERA = 1; + static const int NEEDS_CAMERA = 2; + + int cameras = 0; + + int dfs(TreeNode* node) { + if (!node) return NOT_NEEDED; + + int left = dfs(node->left); + int right = dfs(node->right); + + if (left == NEEDS_CAMERA || right == NEEDS_CAMERA) { + cameras++; + return HAS_CAMERA; + } + if (left == HAS_CAMERA || right == HAS_CAMERA) { + return NOT_NEEDED; + } + return NEEDS_CAMERA; + } + + public: + int minCameraCover(TreeNode* root) { + return (dfs(root) == NEEDS_CAMERA ? 1 : 0) + cameras; + } + }; + ``` + + + + + +## References + +- **LeetCode Problem**: [Binary Tree Cameras](https://leetcode.com/problems/binary-tree-cameras/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/binary-tree-cameras/solutions/) \ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0969-pancake-sorting.md b/solutions/lc-solutions/0900-0999/0969-pancake-sorting.md new file mode 100644 index 0000000..4f4fd03 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0969-pancake-sorting.md @@ -0,0 +1,178 @@ +--- +id: pancake-sorting +title: Pancake Sorting +sidebar_label: 969-Pancake Sorting +tags: + - Sorting + - Array + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Pancake Sorting problem on LeetCode." +sidebar_position: 13 +--- + +## Problem Description + +Given an array of integers `arr`, sort the array by performing a series of pancake flips. + +In one pancake flip, we do the following steps: +1. Choose an integer `k` where `1 <= k <= arr.length`. +2. Reverse the sub-array `arr[0...k-1]` (0-indexed). + +For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`. + +Return an array of the `k`-values corresponding to a sequence of pancake flips that sort `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct. + +### Examples + +**Example 1:** + +``` +Input: arr = [3,2,4,1] +Output: [4,2,4,3] +Explanation: +We perform 4 pancake flips, with k values 4, 2, 4, and 3. +Starting state: arr = [3, 2, 4, 1] +After 1st flip (k = 4): arr = [1, 4, 2, 3] +After 2nd flip (k = 2): arr = [4, 1, 2, 3] +After 3rd flip (k = 4): arr = [3, 2, 1, 4] +After 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted. +``` + +**Example 2:** + +``` +Input: arr = [1,2,3] +Output: [] +Explanation: The input is already sorted, so there is no need to flip anything. +Note that other answers, such as [3, 3], would also be accepted. +``` + +### Constraints + +- `1 <= arr.length <= 100` +- `1 <= arr[i] <= arr.length` +- All integers in `arr` are unique (i.e., `arr` is a permutation of the integers from 1 to `arr.length`). + +--- + +## Solution for Pancake Sorting Problem + +To solve this problem, we perform a series of pancake flips to sort the array in ascending order. A pancake flip reverses the sub-array from the start to a chosen index `k`. The goal is to bring the largest unsorted element to its correct position iteratively. + +### Approach + +1. **Identify Largest Element:** Find the largest unsorted element in the array. +2. **Bring to Front:** If this largest element is not already at the front, flip it to bring it to the front. +3. **Move to Correct Position:** Flip the entire sub-array up to the correct position of the largest element to place it at its sorted position. +4. **Repeat:** Repeat the above steps for the next largest unsorted elements, excluding the already sorted part of the array. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector pancakeSort(vector& arr) { + vector res; + int n = arr.size(); + for (int i = n; i > 1; --i) { + int maxIdx = max_element(arr.begin(), arr.begin() + i) - arr.begin(); + if (maxIdx == i - 1) continue; + if (maxIdx != 0) { + res.push_back(maxIdx + 1); + reverse(arr.begin(), arr.begin() + maxIdx + 1); + } + res.push_back(i); + reverse(arr.begin(), arr.begin() + i); + } + return res; + } +}; +``` + + + + + +```java +class Solution { + public List pancakeSort(int[] arr) { + List res = new ArrayList<>(); + int n = arr.length; + for (int i = n; i > 1; --i) { + int maxIdx = findMaxIndex(arr, i); + if (maxIdx == i - 1) continue; + if (maxIdx != 0) { + res.add(maxIdx + 1); + flip(arr, maxIdx + 1); + } + res.add(i); + flip(arr, i); + } + return res; + } + + private int findMaxIndex(int[] arr, int k) { + int maxIdx = 0; + for (int i = 1; i < k; i++) { + if (arr[i] > arr[maxIdx]) { + maxIdx = i; + } + } + return maxIdx; + } + + private void flip(int[] arr, int k) { + for (int i = 0, j = k - 1; i < j; i++, j--) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } +} +``` + + + + + +```python +class Solution: + def pancakeSort(self, arr: List[int]) -> List[int]: + res = [] + n = len(arr) + for i in range(n, 1, -1): + max_idx = arr.index(max(arr[:i])) + if max_idx == i - 1: + continue + if max_idx != 0: + res.append(max_idx + 1) + arr[:max_idx + 1] = arr[:max_idx + 1][::-1] + res.append(i) + arr[:i] = arr[:i][::-1] + return res +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(n^2)$, where `n` is the length of the array. Finding the maximum and flipping can each take up to `O(n)`, and we do this for each of the `n` elements. +- **Space Complexity**: $O(1)$, excluding the output list. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/0900-0999/0974-subarray-sums-divisible-by-k.md b/solutions/lc-solutions/0900-0999/0974-subarray-sums-divisible-by-k.md new file mode 100644 index 0000000..e6da9f8 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0974-subarray-sums-divisible-by-k.md @@ -0,0 +1,256 @@ +--- +id: subarray-sums-divisible-by-k +title: Subarray Sums Divisible by K +sidebar_label: 974. Subarray Sums Divisible by K + +tags: +- Array +- Sliding Window +- Hashmap + +description: "This is a solution to theSubarray Sums Divisible by K problem on LeetCode." +--- + +## Problem Description +Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k. + +A subarray is a contiguous part of an array. +### Examples + +**Example 1:** +``` +Input: nums = [4,5,0,-2,-3,1], k = 5 +Output: 7 +Explanation: There are 7 subarrays with a sum divisible by k = 5: +[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] +``` + +**Example 2:** +``` +Input: nums = [5], k = 9 +Output: 0 +``` + + +### Constraints +- `1 <= nums.length <= 3 * 10^4` +- `-10^4 <= nums[i] <= 10^4` +- `2 <= k <= 10^4` + +## Solution for Subarray Sums Divisible by K Problem +### Approach +#### Brute Force +- Generate All the Subarray and Check whether the which subarray sum is divisible by k. + +#### Optimized Approach +- The problem is to find the number of subarrays whose sum is divisible by a given integer k. The key insight is to use the concept of prefix sums and remainders: + +##### Prefix Sum and Remainders: +- Compute the prefix sum as you iterate through the array.Compute the remainder of the prefix sum divided by k. This remainder helps in identifying subarrays that are divisible by +k. + +##### Handling Negative Remainders: +- If the remainder is negative, adjust it by adding k to make it positive. This ensures consistent handling of remainders. +##### Using a HashMap: + +- Use a hash map (or dictionary) to count the frequency of each remainder. +- If the same remainder has been seen before, it means there are subarrays whose sum is divisible by k. +##### Counting Valid Subarrays: + +- For each prefix sum remainder, the count of valid subarrays is incremented by the frequency of the same remainder seen so far. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + var subarraysDivByK = function(nums, k) { + let sum = 0; + const mp = new Map(); + mp.set(0, 1); + let cnt = 0; + + for (let i = 0; i < nums.length; i++) { + sum += nums[i]; + sum = sum % k; + if (sum < 0) { + sum += k; + } + if (mp.has(sum)) { + cnt += mp.get(sum); + } + mp.set(sum, (mp.get(sum) || 0) + 1); + } + + return cnt; + }; + const input =[4,5,0,-2,-3,1] + const k = 5 + const output = subarraysDivByK(input , k) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(n) $ + - Space Complexity: $ O(k)$ + + ## Code in Different Languages + + + + ```javascript + var subarraysDivByK = function(nums, k) { + let sum = 0; + const mp = new Map(); + mp.set(0, 1); + let cnt = 0; + + for (let i = 0; i < nums.length; i++) { + sum += nums[i]; + sum = sum % k; + if (sum < 0) { + sum += k; + } + if (mp.has(sum)) { + cnt += mp.get(sum); + } + mp.set(sum, (mp.get(sum) || 0) + 1); + } + + return cnt; +}; + ``` + + + + + ```typescript + function subarraysDivByK(nums: number[], k: number): number { + let sum = 0; + const mp: Map = new Map(); + mp.set(0, 1); + let cnt = 0; + + for (let i = 0; i < nums.length; i++) { + sum += nums[i]; + sum = sum % k; + if (sum < 0) { + sum += k; + } + if (mp.has(sum)) { + cnt += mp.get(sum)!; + } + mp.set(sum, (mp.get(sum) || 0) + 1); + } + + return cnt; +} + + ``` + + + + ```python + from collections import defaultdict + +class Solution: + def subarraysDivByK(self, nums, k): + sum = 0 + mp = defaultdict(int) + mp[0] = 1 + cnt = 0 + + for num in nums: + sum += num + sum = sum % k + if sum < 0: + sum += k + cnt += mp[sum] + mp[sum] += 1 + + return cnt + + ``` + + + + + ```java + import java.util.HashMap; +import java.util.Map; + +class Solution { + public int subarraysDivByK(int[] nums, int k) { + int sum = 0; + Map mp = new HashMap<>(); + mp.put(0, 1); + int cnt = 0; + + for (int num : nums) { + sum += num; + sum = sum % k; + if (sum < 0) { + sum += k; + } + cnt += mp.getOrDefault(sum, 0); + mp.put(sum, mp.getOrDefault(sum, 0) + 1); + } + + return cnt; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + int subarraysDivByK(vector& nums, int k) { + int sum=0; + mapmp; + mp[0]=1; + int cnt=0; + for(int i=0;i + + +
+
+ +## References + +- **LeetCode Problem**: [Subarray Sums Divisible by K](https://leetcode.com/problems/subarray-product-less-than-k/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/subarray-sums-divisible-by-k/solutions) + diff --git a/solutions/lc-solutions/0900-0999/0976-largest-perimeter-triangle.md b/solutions/lc-solutions/0900-0999/0976-largest-perimeter-triangle.md new file mode 100644 index 0000000..03af9bc --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0976-largest-perimeter-triangle.md @@ -0,0 +1,133 @@ +--- +id: Largest-Perimeter-Triangle +title: Largest Perimeter Triangle +sidebar_label: 0976 - Largest Perimeter Triangle +tags: + - Array + - easy + - Math + - Greedy + - Sorting +--- + +## Problem Description + +Given an integer array `nums`, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0. + +### Examples + +**Example 1:** + +``` +Input: nums = [2,1,2] +Output: 5 +Explanation: You can form a triangle with three side lengths: 1, 2, and 2. +``` + +**Example 2:** + +``` +Input: nums = [1,2,1,10] +Output: 0 +Explanation: +You cannot use the side lengths 1, 1, and 2 to form a triangle. +You cannot use the side lengths 1, 1, and 10 to form a triangle. +You cannot use the side lengths 1, 2, and 10 to form a triangle. +As we cannot use any three side lengths to form a triangle of non-zero area, we return 0. +``` + +### Constraints + +``` +3 <= nums.length <= 10^4 +1 <= nums[i] <= 10^6 +``` + +## Solution + +### Python + +```python +def largestPerimeter(nums): + nums.sort(reverse=True) + for i in range(len(nums) - 2): + if nums[i] < nums[i + 1] + nums[i + 2]: + return nums[i] + nums[i + 1] + nums[i + 2] + return 0 + +# Example usage: +print(largestPerimeter([2, 1, 2])) # Output: 5 +print(largestPerimeter([1, 2, 1, 10])) # Output: 0 +``` + +### C++ + +```cpp +#include +#include +using namespace std; + +class Solution { +public: + int largestPerimeter(vector& nums) { + sort(nums.rbegin(), nums.rend()); + for (int i = 0; i < nums.size() - 2; ++i) { + if (nums[i] < nums[i + 1] + nums[i + 2]) { + return nums[i] + nums[i + 1] + nums[i + 2]; + } + } + return 0; + } +}; + +// Example usage: +// Solution sol; +// vector nums = {2, 1, 2}; +// cout << sol.largestPerimeter(nums); // Output: 5 +// nums = {1, 2, 1, 10}; +// cout << sol.largestPerimeter(nums); // Output: 0 +``` + +### Java + +```java +import java.util.Arrays; + +class Solution { + public int largestPerimeter(int[] nums) { + Arrays.sort(nums); + for (int i = nums.length - 3; i >= 0; --i) { + if (nums[i] + nums[i + 1] > nums[i + 2]) { + return nums[i] + nums[i + 1] + nums[i + 2]; + } + } + return 0; + } + + public static void main(String[] args) { + Solution sol = new Solution(); + int[] nums1 = {2, 1, 2}; + System.out.println(sol.largestPerimeter(nums1)); // Output: 5 + int[] nums2 = {1, 2, 1, 10}; + System.out.println(sol.largestPerimeter(nums2)); // Output: 0 + } +} +``` + +### JavaScript + +```javascript +var largestPerimeter = function (nums) { + nums.sort((a, b) => b - a); + for (let i = 0; i < nums.length - 2; i++) { + if (nums[i] < nums[i + 1] + nums[i + 2]) { + return nums[i] + nums[i + 1] + nums[i + 2]; + } + } + return 0; +}; + +// Example usage: +console.log(largestPerimeter([2, 1, 2])); // Output: 5 +console.log(largestPerimeter([1, 2, 1, 10])); // Output: 0 +``` diff --git a/solutions/lc-solutions/0900-0999/0977-sqaures-of-sorted-array.md b/solutions/lc-solutions/0900-0999/0977-sqaures-of-sorted-array.md new file mode 100644 index 0000000..f33a9be --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0977-sqaures-of-sorted-array.md @@ -0,0 +1,315 @@ +--- +id: squares-of-a-sorted-array +title: Squares of a sorted array +sidebar_label: 977. Squares of a Sorted Array + +tags: +- Array +- Vector + +description: "This is a solution to the squares of a sorted array problem on LeetCode." +--- + +## Problem Description +Given an integer array `nums` sorted in **non-decreasing** order, return an array of ***the squares of each number*** *sorted in non-decreasing order.* + +### Examples + +**Example 1:** +``` +Input: nums = [-4,-1,0,3,10] +Output: [0,1,9,16,100] +Explanation: After squaring, the array becomes [16,1,0,9,100]. +After sorting, it becomes [0,1,9,16,100]. +``` + +**Example 2:** +``` +Input: nums = [-7,-3,2,3,11] +Output: [4,9,9,49,121] + +``` + + +### Constraints +- `1 <= nums.length <= 10^4` +- `-10^4 <= nums[i] <= 10^4` +- `nums` is sorted in **non-decreasing** order. + +**Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach? + + +## Solution for Sqaures of a Sorted Array +### Approach +#### Brute Force +- **Square Each Element**: Iterate through the array and square each element. + +- **Sort the Resulting Array**: Sort the array of squares. + +**Implementation:** +```python +def sortedSquares(nums): + # Step 1: Square each element + squared_nums = [num ** 2 for num in nums] + + # Step 2: Sort the array of squares + squared_nums.sort() + + return squared_nums + +# Example usage +nums = [-4, -1, 0, 3, 10] +print(sortedSquares(nums)) # Output: [0, 1, 9, 16, 100] +``` + +**Complexity:** +- Time Complexity: `O(nlogn)` due to the sorting step, where `n` is the number of elements in `nums`. +- Space Complexity: `O(n)` for storing the sqaured numbers. + +**Corner Cases:** +- Empty array: Should return an empty array. +- All non-negative or all non-positive numbers: Should still work correctly without special handling. + +#### Optimized Approach +- **Two-pointer Technique**: Utilize two pointers, one at the beginning (`left`) and one at the end (`right`) of the array. +- **Compare and Insert**: Compare the absolute values of the elements pointed by `left` and `right`. Insert the square of the larger absolute value at the end of the result array and move the corresponding pointer inward. +- **Continue Until Pointers Meet**: Repeat the comparison and insertion until the pointers meet. + +**Implementation:** + +```python +def sortedSquares(nums): + n = nums.length + result = [0] * n + left, right = 0, n - 1 + position = n - 1 + + while left <= right: + if abs(nums[left]) > abs(nums[right]): + result[position] = nums[left] ** 2 + left += 1 + else: + result[position] = nums[right] ** 2 + right -= 1 + position -= 1 + + return result + +# Example usage +nums = [-4, -1, 0, 3, 10] +print(sortedSquares(nums)) # Output: [0, 1, 9, 16, 100] + +``` + +**Complexity:** +- Time Complexity: `O(n)` because we are traversing the array only once with the two-pointer technique. +- Space Complexity: `O(n)` for the result array. + +**Corner Cases:** +- Empty array: Should return an empty array. +- All non-negative or all non-positive numbers: Handled naturally by the two-pointer technique without special cases. +- Array with single element: Both approaches handle this case correctly. + + + + + +#### Implementation + + ```jsx live + function Solution(arr) { + var sortedSquares = function(nums) { + const result = new Array(nums.length) + let i = nums.length - 1 + let j = 0 + let k = nums.length - 1 + + while (i >= 0) { + if (Math.abs(nums[j]) > Math.abs(nums[k])) { + result[i] = nums[j] * nums[j]; + ++j; + } else { + result[i] = nums[k] * nums[k]; + --k; + } + --i; + } + return result + }; + const input = [-4,-1,0,3,10] + const originalInput = [...input] + const output = sortedSquares(input) + return ( +
+

+ Input: + {JSON.stringify(originalInput)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + +#### Complexity Analysis + + - Time Complexity: $O(n)$ + - Space Complexity: $O(n)$ + + ## Code in Different Languages + + + + + + + ```javascript + var sortedSquares = function(nums) { + const result = new Array(nums.length) + let i = nums.length - 1 + let j = 0 + let k = nums.length - 1 + + while (i >= 0) { + if (Math.abs(nums[j]) > Math.abs(nums[k])) { + result[i] = nums[j] * nums[j]; + j++; + } else { + result[i] = nums[k] * nums[k]; + k--; + } + i--; + } + return result; + }; + ``` + + + + + + + ```typescript + function sortedSquares(nums: number[]): number[] { + const result = new Array(nums.length); + let i = nums.length - 1; + let j = 0; + let k = nums.length - 1; + + while (i >= 0) { + if (Math.abs(nums[j]) > Math.abs(nums[k])) { + result[i] = nums[j] * nums[j]; + j++; + } else { + result[i] = nums[k] * nums[k]; + k--; + } + i--; + } + + return result; + } + ``` + + + + + + + ```python + + class Solution(object): + def sortedSquares(self, nums): + result = [0] * len(nums) + i = len(nums) - 1 + j = 0 + k = len(nums) - 1 + + while i >= 0: + if abs(nums[j]) > abs(nums[k]): + result[i] = nums[j] ** 2 + j += 1 + else: + result[i] = nums[k] ** 2 + k -= 1 + i -= 1 + + return result + + ``` + + + + + + + ```java + import java.util.Arrays; + + class Solution { + public int[] sortedSquares(int[] nums) { + int[] result = new int[nums.length]; + int i = nums.length - 1; + int j = 0; + int k = nums.length - 1; + + while (i >= 0) { + if (Math.abs(nums[j]) > Math.abs(nums[k])) { + result[i] = nums[j] * nums[j]; + j++; + } else { + result[i] = nums[k] * nums[k]; + k--; + } + i--; + } + + return result; + } + } + ``` + + + + + + + ```cpp + class Solution { + public: + int sortedSquares(vector& nums) { + vector result(nums.size()); + int i = nums.size()-1, j = 0, k = nums.size()-1; + while(i >= 0) + { + if(abs(nums[j]) > abs(nums[k])) + { + result[i] = nums[j] * nums[j]; + ++j; + } + else + { + result[i] = nums[k] * nums[k]; + --k; + } + --i; + } + return result; + } + }; + + ``` + + + + +
+
+ +## References + +- **LeetCode Problem**: [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/description) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/squares-of-a-sorted-array/solutions/) \ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0984-string-without-aaa-or-bbb.md b/solutions/lc-solutions/0900-0999/0984-string-without-aaa-or-bbb.md new file mode 100644 index 0000000..a2c0b32 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0984-string-without-aaa-or-bbb.md @@ -0,0 +1,177 @@ +--- +id: string-without-aaa-or-bbb +title: String Without AAA or BBB +sidebar_label: 984-String Without AAA or BBB +tags: + - Greedy + - String + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the String Without AAA or BBB problem on LeetCode." +sidebar_position: 3 +--- + +## Problem Description + +Given two integers `a` and `b`, return any string `s` such that: + +- `s` has length `a + b` and contains exactly `a` 'a' letters and exactly `b` 'b' letters. +- The substring 'aaa' does not occur in `s`. +- The substring 'bbb' does not occur in `s`. + +### Examples + +**Example 1:** + +``` +Input: a = 1, b = 2 +Output: "abb" +Explanation: "abb", "bab", and "bba" are all correct answers. +``` + +**Example 2:** + +``` +Input: a = 4, b = 1 +Output: "aabaa" +``` + +### Constraints + +- `0 <= a, b <= 100` +- It is guaranteed that such a string `s` exists for the given `a` and `b`. + +--- + +## Solution for String Without AAA or BBB Problem + +To solve this problem, we need to construct a string of length `a + b` containing exactly `a` 'a' letters and `b` 'b' letters. The key is to ensure that no substring 'aaa' or 'bbb' is formed. + +### Approach + +1. **Greedy Construction:** + - Start by determining the majority character (the one with the higher count). + - Add two of the majority character if more than one remains, followed by one of the minority character. + - If both characters have equal counts, alternate between the two to avoid 'aaa' or 'bbb'. + +2. **Ensure No Consecutive Repetitions:** + - Keep track of the previous two characters to ensure that adding another of the same character won't create three consecutive identical characters. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + string strWithout3a3b(int a, int b) { + string result; + while (a > 0 || b > 0) { + bool writeA = false; + int n = result.size(); + if (n >= 2 && result[n - 1] == result[n - 2]) { + if (result[n - 1] == 'b') { + writeA = true; + } + } else { + if (a >= b) { + writeA = true; + } + } + + if (writeA) { + result += 'a'; + --a; + } else { + result += 'b'; + --b; + } + } + return result; + } +}; +``` + + + + + +```java +class Solution { + public String strWithout3a3b(int a, int b) { + StringBuilder result = new StringBuilder(); + while (a > 0 || b > 0) { + boolean writeA = false; + int n = result.length(); + if (n >= 2 && result.charAt(n - 1) == result.charAt(n - 2)) { + if (result.charAt(n - 1) == 'b') { + writeA = true; + } + } else { + if (a >= b) { + writeA = true; + } + } + + if (writeA) { + result.append('a'); + --a; + } else { + result.append('b'); + --b; + } + } + return result.toString(); + } +} +``` + + + + + +```python +class Solution: + def strWithout3a3b(self, a: int, b: int) -> str: + result = [] + while a > 0 or b > 0: + writeA = False + if len(result) >= 2 and result[-1] == result[-2]: + if result[-1] == 'b': + writeA = True + else: + if a >= b: + writeA = True + + if writeA: + result.append('a') + a -= 1 + else: + result.append('b') + b -= 1 + + return ''.join(result) +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(a + b)$, where `a` and `b` are the counts of 'a' and 'b' respectively. We iterate through each character once. +- **Space Complexity**: $O(a + b)$, for storing the result string. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
+``` \ No newline at end of file diff --git a/solutions/lc-solutions/0900-0999/0987-vertical-order-traversal-of-a-binary-tree.md b/solutions/lc-solutions/0900-0999/0987-vertical-order-traversal-of-a-binary-tree.md new file mode 100644 index 0000000..d7eeb04 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0987-vertical-order-traversal-of-a-binary-tree.md @@ -0,0 +1,243 @@ +--- +id: vertical-order-traversal-binary-tree +title: Vertical Order Traversal of a Binary Tree +sidebar_label: 0987 - Vertical Order Traversal of a Binary Tree +tags: + - Binary Tree + - Vertical Order + - Trees + - Hard + - Leetcode +description: "This is a solution to the Vertical Order Traversal of a Binary Tree problem on LeetCode." +--- + +### Problem Description + +Given the `root` of a binary tree, calculate the vertical order traversal of the binary tree. + +For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`. + +The **vertical order traversal** of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. + +Return the *vertical order traversal* of the binary tree. + +### Examples + +**Example 1:** + +![input Tree](https://assets.leetcode.com/uploads/2021/01/29/vtree1.jpg) +``` +Input: root = [3,9,20,null,null,15,7] +Output: [[9],[3,15],[20],[7]] +Explanation: +Column -1: Only node 9 is in this column. +Column 0: Nodes 3 and 15 are in this column in that order from top to bottom. +Column 1: Only node 20 is in this column. +Column 2: Only node 7 is in this column. +``` + +## Example 2: + +![input Tree](https://assets.leetcode.com/uploads/2021/01/29/vtree2.jpg) +``` +Input: root = [1,2,3,4,5,6,7] +Output: [[4],[2],[1,5,6],[3],[7]] +Explanation: +Column -2: Only node 4 is in this column. +Column -1: Only node 2 is in this column. +Column 0: Nodes 1, 5, and 6 are in this column. + 1 is at the top, so it comes first. + 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6. +Column 1: Only node 3 is in this column. +Column 2: Only node 7 is in this column. +``` + +## Example 3: + +![input Tree](https://assets.leetcode.com/uploads/2021/01/29/vtree3.jpg) +``` +Input: root = [1,2,3,4,6,5,7] +Output: [[4],[2],[1,5,6],[3],[7]] +Explanation: +This case is the exact same as example 2, but with nodes 5 and 6 swapped. +Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values. +``` + +**Constraints:** + +- The number of nodes in the tree is in the range `[1, 1000]`. +- `0 <= Node.val <= 1000` + +### Solution for Vertical Order Traversal of a Binary Tree + +## Approach: + +- The approach involves performing a **breadth-first search** (BFS) traversal of the tree while keeping track of the positions `(row, col)` of each node. +- We use a dictionary to map column indices to lists of nodes and their respective rows. +- Finally, we sort these lists by row and node value and return the result in column order. + +## Steps: + +- Perform a *BFS traversal* of the tree. +- For each node, track its `(row, col)` position. +- Use a *dictionary* to store nodes by their column index. +- For nodes in the same column and row, *sort* them by their values. += Return the *vertical order traversal* from the leftmost to the rightmost column. + + +### Explanation + +- **BFS Traversal:** We use a queue to perform a level-order traversal while tracking each node's row and column. +- **Dictionary Storage:** Nodes are stored in a dictionary where keys are column indices, and values are lists of tuples containing `(row, value)` of the nodes. +- **Sorting:** For each column, nodes are sorted first by row and then by value. +- **Result Compilation:** The final result is compiled by traversing columns in sorted order and extracting node values. + +### Corner Cases: + +- A tree with only one node. +- A skewed tree (all nodes in a single line). + +## Code in Different Languages + +### Code(C++): + +```python + +from collections import defaultdict, deque + +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +def verticalTraversal(root: TreeNode): + nodes = defaultdict(list) + queue = deque([(root, 0, 0)]) + + while queue: + node, row, col = queue.popleft() + if node: + nodes[col].append((row, node.val)) + queue.append((node.left, row + 1, col - 1)) + queue.append((node.right, row + 1, col + 1)) + + result = [] + for col in sorted(nodes): + result.append([val for row, val in sorted(nodes[col])]) + return result +``` + +### Code(Java): + +``` +java +Copy code +import java.util.*; + +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int val) { this.val = val; } +} + +class Solution { + public List> verticalTraversal(TreeNode root) { + Map> nodes = new HashMap<>(); + Queue queue = new LinkedList<>(); + queue.offer(new int[]{root.val, 0, 0, System.identityHashCode(root)}); + + while (!queue.isEmpty()) { + int[] nodeData = queue.poll(); + int val = nodeData[0], row = nodeData[1], col = nodeData[2], hash = nodeData[3]; + TreeNode node = getNodeByHash(hash, root); + + if (!nodes.containsKey(col)) nodes.put(col, new ArrayList<>()); + nodes.get(col).add(new int[]{row, val}); + + if (node.left != null) + queue.offer(new int[]{node.left.val, row + 1, col - 1, System.identityHashCode(node.left)}); + if (node.right != null) + queue.offer(new int[]{node.right.val, row + 1, col + 1, System.identityHashCode(node.right)}); + } + + List> result = new ArrayList<>(); + for (int col : new TreeSet<>(nodes.keySet())) { + List nodeList = nodes.get(col); + nodeList.sort((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); + List colVals = new ArrayList<>(); + for (int[] node : nodeList) { + colVals.add(node[1]); + } + result.add(colVals); + } + return result; + } + + private TreeNode getNodeByHash(int hash, TreeNode root) { + if (System.identityHashCode(root) == hash) return root; + TreeNode node = null; + if (root.left != null) node = getNodeByHash(hash, root.left); + if (node == null && root.right != null) node = getNodeByHash(hash, root.right); + return node; + } +} +``` + +### Code(C++) + +``` +cpp +Copy code +#include +#include +#include +#include + +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + vector> verticalTraversal(TreeNode* root) { + map>> nodes; + queue>> q; + q.push({root, {0, 0}}); + + while (!q.empty()) { + auto p = q.front(); + q.pop(); + TreeNode* node = p.first; + int row = p.second.first, col = p.second.second; + nodes[col].push_back({row, node->val}); + + if (node->left) q.push({node->left, {row + 1, col - 1}}); + if (node->right) q.push({node->right, {row + 1, col + 1}}); + } + + vector> result; + for (auto& col : nodes) { + sort(col.second.begin(), col.second.end()); + vector colVals; + for (auto& node : col.second) { + colVals.push_back(node.second); + } + result.push_back(colVals); + } + return result; + } +}; +``` + +### Complexity: + +**Time Complexity**: $O(N.logN)$ where `N` is the number of nodes in the tree. Sorting nodes for each column contributes to the log factor. +**Space Complexity**: $O(N)$ due to the storage of node positions and the queue for BFS traversal. + diff --git a/solutions/lc-solutions/0900-0999/0989-add-to-array-form-of-integer.md b/solutions/lc-solutions/0900-0999/0989-add-to-array-form-of-integer.md new file mode 100644 index 0000000..d14ceed --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0989-add-to-array-form-of-integer.md @@ -0,0 +1,160 @@ +--- +id: Add-to-Array-Form-of-Integer +title: Add to Array-Form of Integer +sidebar_label: 0989 - Add to Array-Form of Integer +tags: + - easy + - array + - math +--- + +## Problem Description + +The array-form of an integer `num` is an array representing its digits in left to right order. + +For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the array-form of an integer, and an integer `k`, return the array-form of the integer `num + k`. + +## Example + +### Example 1: + +Input: `num = [1,2,0,0]`, `k = 34` +Output: `[1,2,3,4]` +Explanation: `1200 + 34 = 1234` + +### Example 2: + +Input: `num = [2,7,4]`, `k = 181` +Output: `[4,5,5]` +Explanation: `274 + 181 = 455` + +### Example 3: + +Input: `num = [2,1,5]`, `k = 806` +Output: `[1,0,2,1]` +Explanation: `215 + 806 = 1021` + +## Constraints: + +- `1 <= num.length <= 10^4` +- `0 <= num[i] <= 9` +- `num` does not contain any leading zeros except for the zero itself. +- `1 <= k <= 10^4` + +## Solution Approach + +### Python + +```python +def addToArrayForm(num, k): + num_str = ''.join(map(str, num)) + total = int(num_str) + k + return list(map(int, str(total))) + +# Example usage: +print(addToArrayForm([1, 2, 0, 0], 34)) # Output: [1, 2, 3, 4] +print(addToArrayForm([2, 7, 4], 181)) # Output: [4, 5, 5] +print(addToArrayForm([2, 1, 5], 806)) # Output: [1, 0, 2, 1] +``` + +### C++ + +```cpp +#include +#include +#include +using namespace std; + +class Solution { +public: + vector addToArrayForm(vector& num, int k) { + for (int i = num.size() - 1; i >= 0; --i) { + num[i] += k; + k = num[i] / 10; + num[i] %= 10; + } + while (k > 0) { + num.insert(num.begin(), k % 10); + k /= 10; + } + return num; + } +}; + +// Example usage: +int main() { + Solution solution; + vector num1 = {1, 2, 0, 0}; + vector result1 = solution.addToArrayForm(num1, 34); + for (int digit : result1) cout << digit; // Output: 1234 + cout << endl; + + vector num2 = {2, 7, 4}; + vector result2 = solution.addToArrayForm(num2, 181); + for (int digit : result2) cout << digit; // Output: 455 + cout << endl; + + vector num3 = {2, 1, 5}; + vector result3 = solution.addToArrayForm(num3, 806); + for (int digit : result3) cout << digit; // Output: 1021 + cout << endl; + + return 0; +} +``` + +### Java + +```java +import java.util.*; + +class Solution { + public List addToArrayForm(int[] num, int k) { + List result = new ArrayList<>(); + for (int i = num.length - 1; i >= 0; --i) { + k += num[i]; + result.add(k % 10); + k /= 10; + } + while (k > 0) { + result.add(k % 10); + k /= 10; + } + Collections.reverse(result); + return result; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + System.out.println(solution.addToArrayForm(new int[]{1, 2, 0, 0}, 34)); // Output: [1, 2, 3, 4] + System.out.println(solution.addToArrayForm(new int[]{2, 7, 4}, 181)); // Output: [4, 5, 5] + System.out.println(solution.addToArrayForm(new int[]{2, 1, 5}, 806)); // Output: [1, 0, 2, 1] + } +} +``` + +### JavaScript + +```javascript +var addToArrayForm = function (num, k) { + let carry = 0; + for (let i = num.length - 1; i >= 0; i--) { + let sum = num[i] + (k % 10) + carry; + num[i] = sum % 10; + carry = Math.floor(sum / 10); + k = Math.floor(k / 10); + } + while (k > 0 || carry > 0) { + let sum = (k % 10) + carry; + num.unshift(sum % 10); + carry = Math.floor(sum / 10); + k = Math.floor(k / 10); + } + return num; +}; + +// Example usage: +console.log(addToArrayForm([1, 2, 0, 0], 34)); // Output: [1, 2, 3, 4] +console.log(addToArrayForm([2, 7, 4], 181)); // Output: [4, 5, 5] +console.log(addToArrayForm([2, 1, 5], 806)); // Output: [1, 0, 2, 1] +``` diff --git a/solutions/lc-solutions/0900-0999/0994-rotting-oranges.md b/solutions/lc-solutions/0900-0999/0994-rotting-oranges.md new file mode 100644 index 0000000..27fea99 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0994-rotting-oranges.md @@ -0,0 +1,605 @@ +--- +id: rotting-oranges +title: Rotting Oranges +sidebar_label: 0994 - Rotting-Oranges +tags: + - Dfs + - Bfs + - Matrix + - JavaScript + - TypeScript +description: "This is a solution to the Two Sum problem on LeetCode." +--- + +In this page, we will solve the Rotting Oranges problem using two different approaches: Breadth First Search and Depth First Search technique. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +You are given an m x n grid where each cell can have one of three values: + +0 representing an empty cell, +1 representing a fresh orange, or +2 representing a rotten orange. +Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten. + +Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1. + +### Examples + +**Example 1:** + +```plaintext +Input: grid = [[2,1,1],[1,1,0],[0,1,1]] +Output: 4 +``` + +**Example 2:** + +```plaintext +Input: grid = [[2,1,1],[0,1,1],[1,0,1]] +Output: -1 +``` + +**Example 3:** + +```plaintext +Input: grid = [[0,2]] +Output: 0 +``` + +### Constraints + +- `m == grid.length` +- `n == grid[i].length` +- `1 <= m, n <= 10` +- grid[i][j] is 0, 1, or 2. + + + +--- + +## Solution for Rotting Oranges Problem + +### Intuition and Approach + +The idea is that for each rotten orange, we will find how many fresh oranges there are in its 4 directions. If we find any fresh orange we will make it into a rotten orange. One rotten orange can rotten up to 4 fresh oranges present in its 4 directions. For this problem, First we will be using the BFS ( Breadth-First Search ) technique and Then will be using the DFS ( Depth-First Search ) technique. + + + + +### Approach 1: Breadth First Search + +First of all we will create a Queue data structure to store coordinate of Rotten Oranges + + We will also have variables as: + +Total_oranges - It will store total number of oranges in the grid ( Rotten + Fresh ) +Count - It will store the total number of oranges rotten by us . +Total_time - total time taken to rotten. +-> After this, we will traverse the whole grid and count the total number of oranges in the grid and store it in Total_oranges. Then we will also push the rotten oranges in the Queue data structure as well. + +-> Now while our queue is not empty, we will pick up each Rotten Orange and check in all its 4 directions whether a Fresh orange is present or not. If it is present we will make it rotten and push it in our queue data structure and pop out the Rotten Orange which we took up as its work is done now. + +-> Also we will keep track of the count of rotten oranges we are getting. + +-> If we rotten some oranges, then obviously our queue will not be empty. In that case, we will increase our total time. This goes on until our queue becomes empty. + +-> After it becomes empty, We will check whether the total number of oranges initially is equal to the current count of oranges. If yes, we will return the total time taken, else will return -1 because some fresh oranges are still left and can’t be made rotten. + +#### Codes in Different Languages + + + + + ```javascript + function twoSum(nums, target) { + var orangesRotting = function(grid) { + let fresh = 0, + rott = 0, + m = grid.length, + n = grid[0].length; + const q = []; + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 2) { + q.push([i, j]); + } + + if (grid[i][j] === 1) fresh++; + } + } + + if (fresh === 0) return 0; + + console.log(fresh); + + const dr = [1, 0, -1, 0]; + const dc = [0, 1, 0, -1]; + let cnt = -1; + + while (q.length > 0) { + let size = q.length; + while (size--) { + const [x, y] = q.shift(); + for (let i = 0; i < 4; i++) { + const row = x + dr[i]; + const col = y + dc[i]; + + if ( + row >= 0 && + row < m && + col >= 0 && + col < n && + grid[row][col] === 1 + ) { + q.push([row, col]); + grid[row][col] = 2; + rott++; + } + } + } + cnt++; + } + + console.log(rott); + + return fresh === rott ? cnt : -1; + }; + ``` + + + + + ```typescript + function orangesRotting(grid: number[][]): number { + let fresh = 0, + rott = 0, + m = grid.length, + n = grid[0].length; + const q: [number, number][] = []; + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 2) { + q.push([i, j]); + } + + if (grid[i][j] === 1) fresh++; + } + } + + if (fresh === 0) return 0; + + let dr = [+1, 0, -1, 0]; + let dc = [0, +1, 0, -1]; + let cnt = -1; + + while (q.length > 0) { + let size = q.length; + while (size--) { + let [x, y] = q.shift()!; + for (let i = 0; i < 4; i++) { + let row = x + dr[i]; + let col = y + dc[i]; + + if ( + row >= 0 && + row < m && + col >= 0 && + col < n && + grid[row][col] === 1 + ) { + q.push([row, col]); + grid[row][col] = 2; + rott++; + } + } + } + cnt++; + } + + return fresh === rott ? cnt : -1; + }; + ``` + + + + + ```python + from collections import deque + + class Solution(object): + def orangesRotting(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + fresh = 0 + rott = 0 + m = len(grid) + n = len(grid[0]) + q = deque() + + for i in range(m): + for j in range(n): + if grid[i][j] == 2: + q.append((i, j)) + if grid[i][j] == 1: + fresh += 1 + + if fresh == 0: + return 0 + + dr = [1, 0, -1, 0] + dc = [0, 1, 0, -1] + cnt = -1 + + while q: + size = len(q) + while size > 0: + x, y = q.popleft() + + for i in range(4): + row = x + dr[i] + col = y + dc[i] + + if 0 <= row < m and 0 <= col < n and grid[row][col] == 1: + q.append((row, col)) + grid[row][col] = 2 + rott += 1 + size -= 1 + cnt += 1 + + return cnt if fresh == rott else -1 + + ``` + + + + + ```java + import java.util.LinkedList; + import java.util.Queue; + + class Solution { + public int orangesRotting(int[][] grid) { + int fresh = 0, rott = 0, m = grid.length, n = grid[0].length; + Queue q = new LinkedList<>(); + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 2) { + q.add(new int[]{i, j}); + } + + if (grid[i][j] == 1) fresh++; + } + } + + if (fresh == 0) return 0; + + int[] dr = {+1, 0, -1, 0}; + int[] dc = {0, +1, 0, -1}; + int cnt = -1; + + while (!q.isEmpty()) { + int size = q.size(); + while (size-- > 0) { + int[] curr = q.poll(); + int x = curr[0]; + int y = curr[1]; + + for (int i = 0; i < 4; i++) { + int row = x + dr[i]; + int col = y + dc[i]; + + if (row >= 0 && row < m && col >= 0 && col < n && grid[row][col] == 1) { + q.add(new int[]{row, col}); + grid[row][col] = 2; + rott++; + } + } + } + cnt++; + } + + return fresh == rott ? cnt : -1; + } + } + ``` + + + + + ```cpp + class Solution { + public: + int orangesRotting(vector>& grid) { + + int fresh=0, rott=0, m=grid.size(), n=grid[0].size(); + queue> q; + + for(int i=0 ; i=0 && row=0 && col + + +#### Complexity Analysis + +- Time Complexity: $$O(m*n)$$ +- Space Complexity: $$O(m*n)$$ +- Where `m` is the number of rows of the input matrix `grid`. +- Where `n` is the number of columns of the input matrix `grid`. + + + + + + +### Approach 2: Depth First Search + +In Depth-First Search (DFS) strategy to traverse the grid, starting from each initially rotten orange ('2') and propagating the rot to adjacent fresh oranges. +The algorithm marks each fresh orange it encounters with the time taken for rotting. After completing the DFS traversal for all initially rotten oranges, it checks for any remaining fresh oranges. If there are any, it returns -1 to signify that it's impossible to rot all oranges; otherwise, it returns the maximum time taken for rotting minus 2, as the initial time is set to 2. The underlying intuition involves simulating the rotting process by spreading the rot from initially rotten oranges to adjacent fresh ones, updating the time at each step until all reachable oranges are marked as rotten. + + + +#### Code in Different Languages + + + + + ```javascript + var orangesRotting = function(grid) { + function dfs(grid, i, j, time) { + const m = grid.length; + const n = grid[0].length; + // base case + if (i >= m || j >= n || i < 0 || j < 0 || grid[i][j] === 0 || + (grid[i][j] > 1 && grid[i][j] < time)) return; + + grid[i][j] = time; + dfs(grid, i + 1, j, time + 1); + dfs(grid, i - 1, j, time + 1); + dfs(grid, i, j + 1, time + 1); + dfs(grid, i, j - 1, time + 1); + } + + let time = 2; + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + if (grid[i][j] === 2) + dfs(grid, i, j, time); + } + } + + for (const row of grid) { + for (const cell of row) { + if (cell === 1) return -1; + time = Math.max(time, cell); + } + } + return time - 2; + }; + ``` + + + + + ```typescript + function orangesRotting(grid: number[][]): number { + function dfs(grid: number[][], i: number, j: number, time: number): void { + const m = grid.length; + const n = grid[0].length; + // base case + if (i >= m || j >= n || i < 0 || j < 0 || grid[i][j] === 0 || + (grid[i][j] > 1 && grid[i][j] < time)) return; + + grid[i][j] = time; + dfs(grid, i + 1, j, time + 1); + dfs(grid, i - 1, j, time + 1); + dfs(grid, i, j + 1, time + 1); + dfs(grid, i, j - 1, time + 1); + } + + let time = 2; + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + if (grid[i][j] === 2) + dfs(grid, i, j, time); + } + } + + for (const row of grid) { + for (const cell of row) { + if (cell === 1) return -1; + time = Math.max(time, cell); + } + } + return time - 2; + } + + ``` + + + + + ```python + class Solution(object): + def dfs(self, grid, i, j, time): + m = len(grid) + n = len(grid[0]) + # base case + if i >= m or j >= n or i < 0 or j < 0 or grid[i][j] == 0 or \ + (grid[i][j] > 1 and grid[i][j] < time): + return + + grid[i][j] = time + self.dfs(grid, i + 1, j, time + 1) + self.dfs(grid, i - 1, j, time + 1) + self.dfs(grid, i, j + 1, time + 1) + self.dfs(grid, i, j - 1, time + 1) + + def orangesRotting(self, grid): + + time = 2 + + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] == 2: + self.dfs(grid, i, j, time) + + for i in grid: + for j in i: + if j == 1: + return -1 + time = max(time, j) + return time - 2 + + ``` + + + + + ```java + class Solution { + public void dfs(int[][] grid, int i, int j, int time) { + int m = grid.length; + int n = grid[0].length; + // base case + if (i >= m || j >= n || i < 0 || j < 0 || grid[i][j] == 0 || + (grid[i][j] > 1 && grid[i][j] < time)) return; + + grid[i][j] = time; + dfs(grid, i + 1, j, time + 1); + dfs(grid, i - 1, j, time + 1); + dfs(grid, i, j + 1, time + 1); + dfs(grid, i, j - 1, time + 1); + } + + public int orangesRotting(int[][] grid) { + int time = 2; + + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + if (grid[i][j] == 2) + dfs(grid, i, j, time); + } + } + + for (int[] i : grid) { + for (int j : i) { + if (j == 1) return -1; + time = Math.max(time, j); + } + } + return time - 2; + } + } + ``` + + + + + ```cpp + class Solution { + public: + void dfs(vector> &grid, int i, int j, int time){ + int m = grid.size(); + int n = grid[0].size(); + // base case + if(i>=m || j>=n || i<0 || j<0 || grid[i][j]==0 || + (grid[i][j]>1 && grid[i][j]>& grid) { + int time=2; + + for(int i=0; i + + +#### Complexity Analysis + +- Time Complexity: $$O(m*n)$$ +- Space Complexity: $$O(m*n)$$ +- Where `m` is the number of rows of the input matrix `grid`. +- Where `n` is the number of columns of the input matrix `grid`. + + + + + + +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/rotting-oranges/description/) +- **Solution Link:** [Two Sum Solution on LeetCode](https://leetcode.com/problems/rotting-oranges/solutions/239659/dfs-bfs-clean-code/) diff --git a/solutions/lc-solutions/0900-0999/0997-find-the-town-judge.md b/solutions/lc-solutions/0900-0999/0997-find-the-town-judge.md new file mode 100644 index 0000000..d0b51d2 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/0997-find-the-town-judge.md @@ -0,0 +1,112 @@ +--- +id: find-the-town-judge +title: Find The Town Judge +sidebar_label: 0997 Find The Town Judge +tags: + - Array + - Hash Table + - Graph + - LeetCode + - C++ +description: "This is a solution to the Find The Town Judge problem on LeetCode." + +--- + +## Problem Description + +In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge. + +If the town judge exists, then: + +1. The town judge trusts nobody. +2. Everybody (except for the town judge) trusts the town judge. +3. There is exactly one person that satisfies properties 1 and 2. + +You are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi. If a trust relationship does not exist in trust array, then such a trust relationship does not exist. + +Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise. + + + +### Examples + +**Example 1:** + +``` + +Input: n = 2, trust = [[1,2]] +Output: 2 +``` + +**Example 2:** + +``` +Input: n = 3, trust = [[1,3],[2,3]] +Output: 3 +``` + +**Example 2:** + +``` +Input: n = 3, trust = [[1,3],[2,3],[3,1]] +Output: -1 +``` + +### Constraints + +- $1 \leq \text{n} \leq 1000$. +- $1 \leq \text{trust.length} \leq 10^4$. +- $\text{trust[i].length} == 2$. +- $\text{All the pairs of trust are unique}$. + + +### Approach + +To solve this problem(find the town judge) we simply have find that node which is not connected to anone but everyone is connected to it which means that node will be the town judge because according to the question the town judge trusts nobody but everybody (except for the town judge) trusts the town judge. + +#### Code in C++ + +```cpp +class Solution { +public: + int findJudge(int n, vector>& trust) { + vector> adj(n + 1); + vector> ad(n + 1); + for (int i = 0; i < trust.size(); i++) { + adj[t[i][0]].push_back(trust[i][1]); + ad[t[i][1]].push_back(trust[i][0]); + } + for (int i = 1; i <= n; i++) { + if (adj[i].size() == 0 && ad[i].size()==n-1) { + return i; + } + } + return -1; + } +}; +``` + +#### Code in Java + +```java +class Solution { + public int findJudge(int n, int[][] trust) { + int a[][] = new int[n][2]; + for(int i=0;i>& board) { + int x, y; + for (int i = 0; i < 8; i++) { + for (int j = 0; j < 8; j++) { + if (board[i][j] == 'R') { + x = i; + y = j; + break; + } + } + } + return capture(board, x, y, -1, 0) + capture(board, x, y, 1, 0) + + capture(board, x, y, 0, -1) + capture(board, x, y, 0, 1); + } + + int capture(vector>& board, int x, int y, int dx, int dy) { + while (x >= 0 && x < 8 && y >= 0 && y < 8) { + if (board[x][y] == 'B') return 0; + if (board[x][y] == 'p') return 1; + x += dx; + y += dy; + } + return 0; + } +}; +``` + +### Java + +```java +class Solution { + public int numRookCaptures(char[][] board) { + int x = -1, y = -1; + for (int i = 0; i < 8; i++) { + for (int j = 0; j < 8; j++) { + if (board[i][j] == 'R') { + x = i; + y = j; + break; + } + } + } + return capture(board, x, y, -1, 0) + capture(board, x, y, 1, 0) + + capture(board, x, y, 0, -1) + capture(board, x, y, 0, 1); + } + + private int capture(char[][] board, int x, int y, int dx, int dy) { + while (x >= 0 && x < 8 && y >= 0 && y < 8) { + if (board[x][y] == 'B') return 0; + if (board[x][y] == 'p') return 1; + x += dx; + y += dy; + } + return 0; + } +} +``` + +### JavaScript + +```javascript +var numRookCaptures = function (board) { + let x, y; + for (let i = 0; i < 8; i++) { + for (let j = 0; j < 8; j++) { + if (board[i][j] === "R") { + x = i; + y = j; + break; + } + } + } + + return ( + capture(board, x, y, -1, 0) + + capture(board, x, y, 1, 0) + + capture(board, x, y, 0, -1) + + capture(board, x, y, 0, 1) + ); +}; + +function capture(board, x, y, dx, dy) { + while (x >= 0 && x < 8 && y >= 0 && y < 8) { + if (board[x][y] === "B") return 0; + if (board[x][y] === "p") return 1; + x += dx; + y += dy; + } + return 0; +} +``` diff --git a/solutions/lc-solutions/0900-0999/970-powerful-integers.md b/solutions/lc-solutions/0900-0999/970-powerful-integers.md new file mode 100644 index 0000000..57eddc0 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/970-powerful-integers.md @@ -0,0 +1,146 @@ +--- +id: powerful-integers +title: Powerful Integers +sidebar_label: 970-Powerful Integers +tags: + - Math + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Powerful Integers problem on LeetCode." +sidebar_position: 12 +--- + +## Problem Description + +Given three integers `x`, `y`, and `bound`, return a list of all the powerful integers that have a value less than or equal to `bound`. + +An integer is powerful if it can be represented as `x^i + y^j` for some integers `i >= 0` and `j >= 0`. + +You may return the answer in any order. In your answer, each value should occur at most once. + +### Examples + +**Example 1:** + +``` +Input: x = 2, y = 3, bound = 10 +Output: [2,3,4,5,7,9,10] +Explanation: +2 = 2^0 + 3^0 +3 = 2^1 + 3^0 +4 = 2^0 + 3^1 +5 = 2^1 + 3^1 +7 = 2^2 + 3^1 +9 = 2^3 + 3^0 +10 = 2^0 + 3^2 +``` + +**Example 2:** + +``` +Input: x = 3, y = 5, bound = 15 +Output: [2,4,6,8,10,14] +``` + +### Constraints + +- `1 <= x, y <= 100` +- `0 <= bound <= 10^6` + +--- + +## Solution for Powerful Integers Problem + +To solve this problem, we need to find all unique integers that can be represented as `x^i + y^j` and are less than or equal to `bound`. We iterate over possible values of `i` and `j` while ensuring the results stay within the bounds. + +### Approach + +1. **Iterate Over Powers:** + - For `x`, calculate powers `x^i` starting from `i = 0` and stopping when `x^i > bound`. + - For each `x^i`, calculate powers `y^j` starting from `j = 0` and stopping when `y^j > bound`. + - If `x^i + y^j <= bound`, add it to the result set to ensure uniqueness. + +2. **Handling Edge Cases:** + - If `x == 1`, then `x^i` will always be `1` for all `i`, so the loop should run only once for `i = 0`. + - Similarly, if `y == 1`, then `y^j` will always be `1`. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector powerfulIntegers(int x, int y, int bound) { + set resultSet; + for (int i = 1; i < bound; i = (x == 1) ? bound : i * x) { + for (int j = 1; i + j <= bound; j = (y == 1) ? bound : j * y) { + resultSet.insert(i + j); + } + } + return vector(resultSet.begin(), resultSet.end()); + } +}; +``` + + + + + +```java +class Solution { + public List powerfulIntegers(int x, int y, int bound) { + Set resultSet = new HashSet<>(); + for (int i = 1; i < bound; i = (x == 1) ? bound + 1 : i * x) { + for (int j = 1; i + j <= bound; j = (y == 1) ? bound + 1 : j * y) { + resultSet.add(i + j); + } + } + return new ArrayList<>(resultSet); + } +} +``` + + + + + +```python +class Solution: + def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: + result_set = set() + i = 1 + while i < bound: + j = 1 + while i + j <= bound: + result_set.add(i + j) + if y == 1: + break + j *= y + if x == 1: + break + i *= x + return list(result_set) +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(log_x(text{bound})*log_y(text{bound}))$, since we iterate logarithmically based on the bound. +- **Space Complexity**: $O(k)$, where `k` is the number of unique powerful integers found. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/0900-0999/973-k-closest-points-to-origin.md b/solutions/lc-solutions/0900-0999/973-k-closest-points-to-origin.md new file mode 100644 index 0000000..9ee665d --- /dev/null +++ b/solutions/lc-solutions/0900-0999/973-k-closest-points-to-origin.md @@ -0,0 +1,230 @@ +--- +id: k-closest-points-to-origin +title: 973. K Closest Points to Origin +sidebar_label: 973. K Closest Points to Origin + +tags: +- Array +- Math +- Priority Queue + + +description: "This is a solution to the 973. K Closest Points to Origin + problem on LeetCode." +--- + +## Problem Description +Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). + +The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). + +You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). +### Examples +**Example 1:** + +``` +Input: points = [[1,3],[-2,2]], k = 1 +Output: [[-2,2]] +Explanation: +The distance between (1, 3) and the origin is sqrt(10). +The distance between (-2, 2) and the origin is sqrt(8). +Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. +We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. + +``` + +**Example 2:** +``` +Input: points = [[3,3],[5,-1],[-2,4]], k = 2 +Output: [[3,3],[-2,4]] +Explanation: The answer [[-2,4],[3,3]] would also be accepted. +``` + +### Constraints +- `1 <= k <= points.length <= 10^4` +- `-10^4 <= xi, yi <= 10^4` + +## Solution for973. K Closest Points to Origin + + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function kClosest(points, k) { + // Calculate the distance of each point from the origin + points.sort((a, b) => { + const distA = a[0] * a[0] + a[1] * a[1]; + const distB = b[0] * b[0] + b[1] * b[1]; + return distA - distB; + }); + + // Return the first k points + return points.slice(0, k); + } + + + const input = points = [[1,3],[-2,2]], k = 1 + const output = kClosest(input , k) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(nlogn) $ + - Space Complexity: $ O(n)$ + + ## Code in Different Languages + + + + ```javascript + function kClosest(points, k) { + const pq = new MinPriorityQueue({ priority: (point) => point[0] }); + + for (let i = 0; i < points.length; i++) { + const x = points[i][0]; + const y = points[i][1]; + const dist = x * x + y * y; + pq.enqueue([dist, i]); + } + + const ans = []; + for (let i = 0; i < k; i++) { + const [_, index] = pq.dequeue().element; + ans.push(points[index]); + } + + return ans; +} + + ``` + + + + + ```typescript + class Solution { + kClosest(points: number[][], k: number): number[][] { + let pq = new MinPriorityQueue<{ dist: number, index: number }>({ + priority: (point) => point.dist + }); + + for (let i = 0; i < points.length; i++) { + let x = points[i][0]; + let y = points[i][1]; + let z = x * x + y * y; + pq.enqueue({ dist: z, index: i }); + } + + let ans: number[][] = []; + while (k--) { + let { index } = pq.dequeue().element; + ans.push(points[index]); + } + return ans; + } +} + + ``` + + + + ```python + import heapq + +class Solution: + def kClosest(self, points, k): + pq = [] + for i, (x, y) in enumerate(points): + dist = x * x + y * y + heapq.heappush(pq, (dist, i)) + + ans = [] + for _ in range(k): + _, i = heapq.heappop(pq) + ans.append(points[i]) + return ans + + ``` + + + + + ```java + import java.util.PriorityQueue; + +class Solution { + public int[][] kClosest(int[][] points, int k) { + PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); + + for (int i = 0; i < points.length; i++) { + int x = points[i][0]; + int y = points[i][1]; + int z = x * x + y * y; + pq.offer(new int[] { z, i }); + } + + int[][] ans = new int[k][2]; + for (int i = 0; i < k; i++) { + int index = pq.poll()[1]; + ans[i] = points[index]; + } + return ans; + } +} + + ``` + + + + + ```cpp +class Solution { +public: + vector> kClosest(vector>& points, int k) { + vector>ans; + priority_queue , vector> , greater>>pq; + for(int i=0;i + + +
+
+ +## References + +- **LeetCode Problem**: [2348. Number of Zero-Filled Subarrays](https://leetcode.com/problems/k-closest-points-to-origin/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/k-closest-points-to-origin/description/) + diff --git a/solutions/lc-solutions/0900-0999/980 - Unique Paths III.md b/solutions/lc-solutions/0900-0999/980 - Unique Paths III.md new file mode 100644 index 0000000..4a448e6 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/980 - Unique Paths III.md @@ -0,0 +1,189 @@ +--- +id: unique-paths-iii +title: Unique Paths III +sidebar_label: Unique Paths III +tags: [Backtracking, DFS, Grid, C++, Python, Java] +description: Find the number of unique paths from the starting square to the ending square in a grid, walking over every non-obstacle square exactly once. +--- + +## Problem Statement + +### Problem Description + +You are given an `m x n` integer array `grid` where `grid[i][j]` could be: + +- `1` representing the starting square. There is exactly one starting square. +- `2` representing the ending square. There is exactly one ending square. +- `0` representing empty squares we can walk over. +- `-1` representing obstacles that we cannot walk over. + +Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once. + +### Example + +**Example 1:** +``` +Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]] +Output: 2 +``` +**Explanation:** We have the following two paths: + +(0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) +(0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) + + +**Example 2:** +``` +Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]] +Output: 4 +``` +**Explanation:** We have the following four paths: + +(0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) +(0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) +(0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) +(0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) + + +### Constraints + +- `m == grid.length` +- `n == grid[i].length` +- `1 <= m, n <= 20` +- `1 <= m * n <= 20` +- `-1 <= grid[i][j] <= 2` +- There is exactly one starting cell and one ending cell. + +## Solution + +### Intuition + +To solve this problem, we can use a backtracking approach with Depth-First Search (DFS). We will start from the starting square and try to explore all possible paths to the ending square while ensuring we visit every non-obstacle square exactly once. We will backtrack whenever we hit a dead end or revisit a square. + +### Time Complexity and Space Complexity Analysis + +- **Time Complexity**: $O(4^{m \times n})$, where $m \times n$ is the total number of cells. This is because, in the worst case, we might explore all possible paths. +- **Space Complexity**: $O(m \times n)$, for the recursion stack and the `visited` array. + +### Code + +#### C++ + +```cpp +class Solution { +public: + int uniquePathsIII(vector>& grid) { + int rows = grid.size(); + int cols = grid[0].size(); + int emptySquares = 1; // including the starting point + int startX, startY; + + for (int i = 0; i < rows; ++i) { + for (int j = 0; j < cols; ++j) { + if (grid[i][j] == 0) { + ++emptySquares; + } else if (grid[i][j] == 1) { + startX = i; + startY = j; + } + } + } + + return dfs(grid, startX, startY, emptySquares); + } + +private: + int dfs(vector>& grid, int x, int y, int emptySquares) { + if (x < 0 || x >= grid.size() || y < 0 || y >= grid[0].size() || grid[x][y] == -1) { + return 0; + } + if (grid[x][y] == 2) { + return emptySquares == 0 ? 1 : 0; + } + + grid[x][y] = -1; + int paths = dfs(grid, x + 1, y, emptySquares - 1) + + dfs(grid, x - 1, y, emptySquares - 1) + + dfs(grid, x, y + 1, emptySquares - 1) + + dfs(grid, x, y - 1, emptySquares - 1); + grid[x][y] = 0; + + return paths; + } +}; +``` + +#### Python +```python +class Solution: + def uniquePathsIII(self, grid: List[List[int]]) -> int: + rows, cols = len(grid), len(grid[0]) + empty_squares = 1 # including the starting point + start_x, start_y = 0, 0 + + for i in range(rows): + for j in range(cols): + if grid[i][j] == 0: + empty_squares += 1 + elif grid[i][j] == 1: + start_x, start_y = i, j + + def dfs(x, y, empty_squares): + if x < 0 or x >= rows or y < 0 or y >= cols or grid[x][y] == -1: + return 0 + if grid[x][y] == 2: + return 1 if empty_squares == 0 else 0 + + grid[x][y] = -1 + paths = (dfs(x + 1, y, empty_squares - 1) + + dfs(x - 1, y, empty_squares - 1) + + dfs(x, y + 1, empty_squares - 1) + + dfs(x, y - 1, empty_squares - 1)) + grid[x][y] = 0 + + return paths + + return dfs(start_x, start_y, empty_squares) +``` +#### Java +```java +class Solution { + public int uniquePathsIII(int[][] grid) { + int rows = grid.length; + int cols = grid[0].length; + int emptySquares = 1; // including the starting point + int startX = 0, startY = 0; + + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + if (grid[i][j] == 0) { + emptySquares++; + } else if (grid[i][j] == 1) { + startX = i; + startY = j; + } + } + } + + return dfs(grid, startX, startY, emptySquares); + } + + private int dfs(int[][] grid, int x, int y, int emptySquares) { + if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] == -1) { + return 0; + } + if (grid[x][y] == 2) { + return emptySquares == 0 ? 1 : 0; + } + + grid[x][y] = -1; + int paths = dfs(grid, x + 1, y, emptySquares - 1) + + dfs(grid, x - 1, y, emptySquares - 1) + + dfs(grid, x, y + 1, emptySquares - 1) + + dfs(grid, x, y - 1, emptySquares - 1); + grid[x][y] = 0; + + return paths; + } +} +``` diff --git a/solutions/lc-solutions/0900-0999/995-minimum-number-of-k-consecutive-bit-flips.md b/solutions/lc-solutions/0900-0999/995-minimum-number-of-k-consecutive-bit-flips.md new file mode 100644 index 0000000..42572bb --- /dev/null +++ b/solutions/lc-solutions/0900-0999/995-minimum-number-of-k-consecutive-bit-flips.md @@ -0,0 +1,117 @@ +--- +id: minimum-number-of-k-consecutive-bit-flips +title: Minimum Number of K Consecutive Bit Flips +sidebar_label: Minimum Number of K Consecutive Bit Flips +tags: + - Array + - Greedy + - Sliding Window +description: "This document provides a solution for the Minimum Number of K Consecutive Bit Flips problem." +--- + +## Problem Statement + +You are given a binary array `nums` and an integer `k`. + +A k-bit flip is choosing a subarray of length `k` from `nums` and simultaneously changing every `0` in the subarray to `1`, and every `1` in the subarray to `0`. + +Return the minimum number of k-bit flips required so that there is no `0` in the array. If it is not possible, return `-1`. + +A subarray is a contiguous part of an array. + +**Example 1:** + +Input: `nums = [0,1,0]`, `k = 1` + +Output: `2` + +Explanation: Flip `nums[0]`, then flip `nums[2]`. + +**Example 2:** + +Input: `nums = [1,1,0]`, `k = 2` + +Output: `-1` + +Explanation: No matter how we flip subarrays of size 2, we cannot make the array become `[1,1,1]`. + +**Example 3:** + +Input: `nums = [0,0,0,1,0,1,1,0]`, `k = 3` + +Output: `3` + +Explanation: +- Flip `nums[0],nums[1],nums[2]`: `nums` becomes `[1,1,1,1,0,1,1,0]` +- Flip `nums[4],nums[5],nums[6]`: `nums` becomes `[1,1,1,1,1,0,0,0]` +- Flip `nums[5],nums[6],nums[7]`: `nums` becomes `[1,1,1,1,1,1,1,1]` + +**Constraints:** + +- `1 <= nums.length <= 10^5` +- `1 <= k <= nums.length` + +## Solutions + +### Approach + +To solve this problem, we can use a greedy approach with a sliding window to keep track of the flips. The main idea is to flip the bits only when necessary and use an auxiliary array to record the effect of flips at each position. + +1. **Initialize Variables**: + - `flipped` to track the cumulative effect of flips. + - `res` to count the number of flips. + - `isFlipped` array to record the flips at each index. + +2. **Iterate through the Array**: + - For each element, check if the current position is affected by a previous flip by using the `isFlipped` array. + - If the current bit needs to be flipped (`flipped` == `nums[i]`), check if flipping is possible. + - Record the flip and update the counters. + +3. **Edge Cases**: + - If it's not possible to flip because the subarray exceeds the array bounds, return `-1`. + +### Java + +```java +class Solution { + public int minKBitFlips(int[] nums, int k) { + int n = nums.length, flipped = 0, res = 0; + int[] isFlipped = new int[n]; + + for (int i = 0; i < nums.length; ++i) { + if (i >= k) + flipped ^= isFlipped[i - k]; + if (flipped == nums[i]) { + if (i + k > nums.length) + return -1; + isFlipped[i] = 1; + flipped ^= 1; + res++; + } + } + return res; + } +} +``` + +### Python +```python +class Solution: + def minKBitFlips(self, nums: List[int], k: int) -> int: + n = len(nums) + flipped = 0 + res = 0 + is_flipped = [0] * n + + for i in range(n): + if i >= k: + flipped ^= is_flipped[i - k] + if flipped == nums[i]: + if i + k > n: + return -1 + is_flipped[i] = 1 + flipped ^= 1 + res += 1 + + return res +``` diff --git a/solutions/lc-solutions/0900-0999/_category_.json b/solutions/lc-solutions/0900-0999/_category_.json new file mode 100644 index 0000000..22a5f17 --- /dev/null +++ b/solutions/lc-solutions/0900-0999/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "0900-0999", + "position": 11, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (0900 - 0999)" + } +} diff --git a/solutions/lc-solutions/0900-0999/image-1.png b/solutions/lc-solutions/0900-0999/image-1.png new file mode 100644 index 0000000..332b74c Binary files /dev/null and b/solutions/lc-solutions/0900-0999/image-1.png differ diff --git a/solutions/lc-solutions/0900-0999/image.png b/solutions/lc-solutions/0900-0999/image.png new file mode 100644 index 0000000..8737d92 Binary files /dev/null and b/solutions/lc-solutions/0900-0999/image.png differ diff --git a/solutions/lc-solutions/1000-1099/1002-find-common-characters.md b/solutions/lc-solutions/1000-1099/1002-find-common-characters.md new file mode 100644 index 0000000..ad42dd7 --- /dev/null +++ b/solutions/lc-solutions/1000-1099/1002-find-common-characters.md @@ -0,0 +1,154 @@ +--- +id: find-common-characters +title: Find Common Characters +sidebar_label: Find Common Characters +tags: + - Hash Table + - String + - Java + - Python + - C++ +description: "This document provides solutions for the Find Common Characters problem on LeetCode." + +--- + +## Problem Statement + +Given a string array `words`, return an array of all characters that show up in all strings within the `words` (including duplicates). You may return the answer in any order. + +**Example 1:** + +Input: `words = ["bella","label","roller"]` + +Output: `["e","l","l"]` + +**Example 2:** + +Input: `words = ["cool","lock","cook"]` + +Output: `["c","o"]` + +**Constraints:** + +- `1 <= words.length <= 100` +- `1 <= words[i].length <= 100` +- `words[i]` consists of lowercase English letters. + +## Solutions + +### Approach + +To solve this problem, we need to find characters that appear in all strings within the `words` array. We can use a hash table to keep track of the minimum frequency of each character across all words. + +1. **Initialize the frequency map**: + - Use an array of size 26 to store the frequency of each character ('a' to 'z'). + +2. **Count the frequency of characters in each word**: + - For each word, count the frequency of each character and update the global minimum frequency. + +3. **Build the result list**: + - Collect characters that have a non-zero frequency in the global minimum frequency map. + +### Java + +```java +import java.util.ArrayList; +import java.util.List; + +class Solution { + public List commonChars(String[] words) { + int[] minFreq = new int[26]; + for (int i = 0; i < 26; i++) { + minFreq[i] = Integer.MAX_VALUE; + } + + for (String word : words) { + int[] charCount = new int[26]; + for (char c : word.toCharArray()) { + charCount[c - 'a']++; + } + for (int i = 0; i < 26; i++) { + minFreq[i] = Math.min(minFreq[i], charCount[i]); + } + } + + List result = new ArrayList<>(); + for (int i = 0; i < 26; i++) { + while (minFreq[i] > 0) { + result.add("" + (char) (i + 'a')); + minFreq[i]--; + } + } + return result; + } +} +``` + +### Python + +```python +from typing import List + +class Solution: + def commonChars(self, words: List[str]) -> List[str]: + min_freq = [float('inf')] * 26 + + for word in words: + char_count = [0] * 26 + for char in word: + char_count[ord(char) - ord('a')] += 1 + for i in range(26): + min_freq[i] = min(min_freq[i], char_count[i]) + + result = [] + for i in range(26): + result.extend([chr(i + ord('a'))] * min_freq[i]) + + return result +``` + +### C++ + +```cpp +#include +#include +#include +using namespace std; + +class Solution { +public: + vector commonChars(vector& words) { + vector minFreq(26, INT_MAX); + + for (const string& word : words) { + vector charCount(26, 0); + for (char c : word) { + charCount[c - 'a']++; + } + for (int i = 0; i < 26; i++) { + minFreq[i] = min(minFreq[i], charCount[i]); + } + } + + vector result; + for (int i = 0; i < 26; i++) { + for (int j = 0; j < minFreq[i]; j++) { + result.push_back(string(1, i + 'a')); + } + } + + return result; + } +}; +``` + +### Explanation + +- **Initialize Frequency Map**: + - We initialize an array `minFreq` of size 26 to `Integer.MAX_VALUE` or `float('inf')` to keep track of the minimum frequency of each character. +- **Count Frequency**: + - For each word, count the frequency of each character and update the `minFreq` array with the minimum frequency. +- **Build Result**: + - Iterate through the `minFreq` array and collect characters that have a non-zero frequency. + +This approach ensures that we find the common characters that appear in all words within the `words` array, considering the constraints and requirements of the problem. diff --git a/solutions/lc-solutions/1000-1099/1004-max-consecutive-ones-iii.md b/solutions/lc-solutions/1000-1099/1004-max-consecutive-ones-iii.md new file mode 100644 index 0000000..79505f4 --- /dev/null +++ b/solutions/lc-solutions/1000-1099/1004-max-consecutive-ones-iii.md @@ -0,0 +1,156 @@ +--- +id: max-consecutive-ones-iii +title: Max Consecutive Ones III +sidebar_label: Max Consecutive Ones III +tags: + - Array + - Sliding Window + - Java + - Python + - C++ +description: "This document provides solutions for the Max Consecutive Ones III problem on LeetCode." +--- + +## Problem Statement + +Given a binary array `nums` and an integer `k`, return the maximum number of consecutive `1`s in the array if you can flip at most `k` `0`s. + +**Example 1:** + +Input: `nums = [1,1,1,0,0,0,1,1,1,1,0]`, `k = 2` + +Output: `6` + +**Explanation**: [1,1,1,0,0,1,1,1,1,1,1] (flipping 0 and 0) + +**Example 2:** + +Input: `nums = [0,0,1,1,1,0,0]`, `k = 0` + +Output: `3` + +**Constraints:** + +- `1 <= nums.length <= 10^5` +- `nums[i]` is either `0` or `1`. +- `0 <= k <= nums.length` + +## Solutions + +### Approach + +To solve this problem, we can use the sliding window technique to maintain a window of the array that contains at most `k` zeros. Here's how to implement this: + +1. **Initialize pointers and counters**: + - Use two pointers (`left` and `right`) to define the current window. + - Use a counter to keep track of the number of zeros in the current window. + +2. **Expand the window**: + - Increment the `right` pointer to expand the window. + - If a zero is encountered, increment the zero counter. + +3. **Shrink the window if necessary**: + - If the zero counter exceeds `k`, increment the `left` pointer until the zero counter is `k` or less. + +4. **Track the maximum window size**: + - Update the maximum window size during each expansion. + +### Java + +```java +class Solution { + public int longestOnes(int[] nums, int k) { + int left = 0, right = 0; + int maxOnes = 0; + int zerosCount = 0; + + while (right < nums.length) { + if (nums[right] == 0) { + zerosCount++; + } + + while (zerosCount > k) { + if (nums[left] == 0) { + zerosCount--; + } + left++; + } + + maxOnes = Math.max(maxOnes, right - left + 1); + right++; + } + + return maxOnes; + } +} +``` + +### Python + +```python +from typing import List + +class Solution: + def longestOnes(self, nums: List[int], k: int) -> int: + left = 0 + zeros_count = 0 + max_ones = 0 + + for right in range(len(nums)): + if nums[right] == 0: + zeros_count += 1 + + while zeros_count > k: + if nums[left] == 0: + zeros_count -= 1 + left += 1 + + max_ones = max(max_ones, right - left + 1) + + return max_ones +``` + +### C++ + +```cpp +class Solution { +public: + int longestOnes(vector& nums, int k) { + int left = 0, right = 0; + int maxOnes = 0; + int zerosCount = 0; + + while (right < nums.size()) { + if (nums[right] == 0) { + zerosCount++; + } + + while (zerosCount > k) { + if (nums[left] == 0) { + zerosCount--; + } + left++; + } + + maxOnes = max(maxOnes, right - left + 1); + right++; + } + + return maxOnes; + } +}; +``` + +### Explanation + +- **Initialize Pointers and Counters**: + - We use `left` and `right` to define our sliding window. `zerosCount` keeps track of the number of zeros within the window. +- **Expand the Window**: + - We expand the window by moving the `right` pointer to the right. + - If we encounter a zero, we increment `zerosCount`. +- **Shrink the Window if Necessary**: + - If `zerosCount` exceeds `k`, we move the `left` pointer to the right until `zerosCount` is less than or equal to `k`. +- **Track the Maximum Window Size**: + - We update `maxOnes` to the maximum window size found during the process. + +This approach efficiently finds the maximum number of consecutive ones by maintaining a sliding window of valid subarrays, ensuring optimal performance for large input sizes. diff --git a/solutions/lc-solutions/1000-1099/1005-maximize-sum-of-array-after-k-negations.md b/solutions/lc-solutions/1000-1099/1005-maximize-sum-of-array-after-k-negations.md new file mode 100644 index 0000000..a44e2a0 --- /dev/null +++ b/solutions/lc-solutions/1000-1099/1005-maximize-sum-of-array-after-k-negations.md @@ -0,0 +1,161 @@ +--- +id: maximize-sum-of-array-after-k-negations +title: Maximize Sum of Array After K Negations +sidebar_label: 1005-Maximize Sum of Array After K Negations +tags: + - Array + - Greedy + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Maximize Sum After K Negations problem on LeetCode." +sidebar_position: 20 +--- + +## Problem Description + +Given an integer array `nums` and an integer `k`, modify the array in the following way: + +choose an index `i` and replace `nums[i]` with `-nums[i]`. You should apply this process exactly `k` times. You may choose the same index `i` multiple times. + +Return the largest possible sum of the array after modifying it in this way. + +### Examples + +**Example 1:** + +``` +Input: nums = [4,2,3], k = 1 +Output: 5 +Explanation: Choose index 1 and nums becomes [4,-2,3]. +``` + +**Example 2:** + +``` +Input: nums = [3,-1,0,2], k = 3 +Output: 6 +Explanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2]. +``` + +**Example 3:** + +``` +Input: nums = [2,-3,-1,5,-4], k = 2 +Output: 13 +Explanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4]. +``` + +### Constraints + +- `1 <= nums.length <= 10^4` +- `-100 <= nums[i] <= 100` +- `1 <= k <= 10^4` + +--- + +## Solution for Largest Sum After K Negations Problem + +To solve this problem, we should follow a greedy approach by repeatedly negating the smallest element in the array, as this will maximize the sum after `k` operations. + +### Approach + +1. **Sort the Array:** + - Sort the array to bring all the negative numbers to the front. + +2. **Negate the Minimum Element:** + - Iterate through the array and negate the smallest elements (negative numbers) first. + - If there are still operations left after negating all negative numbers, use the remaining operations on the smallest absolute value element. + +3. **Handle Remaining Operations:** + - If `k` is still greater than 0 after negating all negative numbers, continue to negate the smallest absolute value element until `k` becomes 0. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int largestSumAfterKNegations(vector& nums, int k) { + sort(nums.begin(), nums.end()); + for (int i = 0; i < nums.size() && k > 0; ++i) { + if (nums[i] < 0) { + nums[i] = -nums[i]; + --k; + } + } + if (k % 2 == 1) { + *min_element(nums.begin(), nums.end()) *= -1; + } + return accumulate(nums.begin(), nums.end(), 0); + } +}; +``` + + + + + +```java +class Solution { + public int largestSumAfterKNegations(int[] nums, int k) { + Arrays.sort(nums); + for (int i = 0; i < nums.length && k > 0; ++i) { + if (nums[i] < 0) { + nums[i] = -nums[i]; + --k; + } + } + int min = Arrays.stream(nums).min().getAsInt(); + if (k % 2 == 1) { + for (int i = 0; i < nums.length; ++i) { + if (nums[i] == min) { + nums[i] = -nums[i]; + break; + } + } + } + return Arrays.stream(nums).sum(); + } +} +``` + + + + + +```python +class Solution: + def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: + nums.sort() + for i in range(len(nums)): + if nums[i] < 0 and k > 0: + nums[i] = -nums[i] + k -= 1 + if k % 2 == 1: + nums[nums.index(min(nums))] *= -1 + return sum(nums) +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(n \log n)$, where `n` is the length of the array. This is due to the sorting step. +- **Space Complexity**: $O(1)$, as we are modifying the array in place. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
+``` diff --git a/solutions/lc-solutions/1000-1099/1008-Construct-Binary-Search-Tree-from-Preorder-Traversal.md b/solutions/lc-solutions/1000-1099/1008-Construct-Binary-Search-Tree-from-Preorder-Traversal.md new file mode 100644 index 0000000..70958ee --- /dev/null +++ b/solutions/lc-solutions/1000-1099/1008-Construct-Binary-Search-Tree-from-Preorder-Traversal.md @@ -0,0 +1,129 @@ +--- +id: construct-binary-search-tree-from-preorder-traversal +title: Construct Binary Search Tree from Preorder Traversal +level: medium +sidebar_label: Construct BST from Preorder +tags: + - Tree + - Depth-First Search (DFS) + - Binary Search Tree (BST) + - Java + - Python + - C++ +description: "This document provides solutions for the Construct Binary Search Tree from Preorder Traversal problem." +--- + +## Problem Statement + +Return the root node of a binary search tree that matches the given preorder traversal. + +(Recall that a binary search tree is a binary tree where for every node, any descendant of `node.left` has a value `< node.val`, and any descendant of `node.right` has a value `> node.val`. Also recall that a preorder traversal displays the value of the `node` first, then traverses `node.left`, then traverses `node.right`.) + +**Example 1:** + +Input: `preorder = [8,5,1,7,10,12]` + +Output: `TreeNode{val: 8, left: TreeNode{val: 5, left: TreeNode{val: 1, left: None, right: None}, right: TreeNode{val: 7, left: None, right: None}}, right: TreeNode{val: 10, left: None, right: TreeNode{val: 12, left: None, right: None}}}` + + + +**Constraints:** + +- `1 <= preorder.length <= 100` +- `1 <= preorder[i] <= 10^8` +- The values of `preorder` are distinct. + +## Solutions + +### Approach + +To construct the binary search tree from the given preorder traversal, we can use a recursive approach. Here's how we can achieve this: + +1. **Recursive Construction**: + - Use a recursive function to construct the binary search tree. + - Keep track of the current index in the `preorder` list. + - For each node, create a `TreeNode` with the current value. + - Recursively build the left subtree with values less than the current node's value. + - Recursively build the right subtree with values greater than the current node's value. + +### Java + +```java +class Solution { + int index = 0; + + public TreeNode bstFromPreorder(int[] preorder) { + return buildTree(preorder, Integer.MIN_VALUE, Integer.MAX_VALUE); + } + + private TreeNode buildTree(int[] preorder, int min, int max) { + if (index == preorder.length) + return null; + + int val = preorder[index]; + if (val < min || val > max) + return null; + + TreeNode node = new TreeNode(val); + index++; + + node.left = buildTree(preorder, min, val); + node.right = buildTree(preorder, val, max); + + return node; + } +} +``` + +### Python + +```python +class Solution: + def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]: + self.index = 0 + return self.buildTree(preorder, float('-inf'), float('inf')) + + def buildTree(self, preorder: List[int], min_val: int, max_val: int) -> Optional[TreeNode]: + if self.index == len(preorder): + return None + + val = preorder[self.index] + if val < min_val or val > max_val: + return None + + node = TreeNode(val) + self.index += 1 + + node.left = self.buildTree(preorder, min_val, val) + node.right = self.buildTree(preorder, val, max_val) + + return node +``` + +### C++ + +```cpp +class Solution { +public: + TreeNode* bstFromPreorder(vector& preorder) { + int index = 0; + return buildTree(preorder, index, INT_MIN, INT_MAX); + } + + TreeNode* buildTree(vector& preorder, int& index, int min_val, int max_val) { + if (index == preorder.size()) + return nullptr; + + int val = preorder[index]; + if (val < min_val || val > max_val) + return nullptr; + + TreeNode* node = new TreeNode(val); + index++; + + node->left = buildTree(preorder, index, min_val, val); + node->right = buildTree(preorder, index, val, max_val); + + return node; + } +}; diff --git a/solutions/lc-solutions/1000-1099/1009-complement-of-base-10-integer.md b/solutions/lc-solutions/1000-1099/1009-complement-of-base-10-integer.md new file mode 100644 index 0000000..f7d4d06 --- /dev/null +++ b/solutions/lc-solutions/1000-1099/1009-complement-of-base-10-integer.md @@ -0,0 +1,137 @@ +--- +id: complement-of-base-10-integer +title: Complement of Base 10 Integer +sidebar_label: 1009-Complement of Base 10 Integer +tags: + - Bit Manipulation + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Complement of Base 10 Integer problem on LeetCode." +sidebar_position: 15 +--- + +## Problem Description + +The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation. + +For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2. Given an integer `n`, return its complement. + +### Examples + +**Example 1:** + +``` +Input: n = 5 +Output: 2 +Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10. +``` + +**Example 2:** + +``` +Input: n = 7 +Output: 0 +Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10. +``` + +**Example 3:** + +``` +Input: n = 10 +Output: 5 +Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10. +``` + +### Constraints + +- `0 <= n < 10^9` + +--- + +## Solution for Complement of Integer Problem + +To solve this problem, we need to flip all bits of the binary representation of the given integer `n`. + +### Approach + +1. **Brute Force:** + - Convert the integer to its binary string representation. + - Flip each bit and convert the binary string back to an integer. + +2. **Optimized Approach:** + - Find the number of bits in the binary representation of `n`. + - Create a mask with the same number of bits set to 1. + - XOR `n` with the mask to get the complement. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int bitwiseComplement(int n) { + if (n == 0) return 1; + int mask = 1; + while (mask < n) { + mask = (mask << 1) | 1; + } + return n ^ mask; + } +}; +``` + + + + + +```java +class Solution { + public int bitwiseComplement(int n) { + if (n == 0) return 1; + int mask = 1; + while (mask < n) { + mask = (mask << 1) | 1; + } + return n ^ mask; + } +} +``` + + + + + +```python +class Solution: + def bitwiseComplement(self, n: int) -> int: + if n == 0: + return 1 + mask = 1 + while mask < n: + mask = (mask << 1) | 1 + return n ^ mask +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(log n)$, where `n` is the given integer. This is because we are iterating through the bits of `n`. +- **Space Complexity**: $O(1)$, as we are using a constant amount of extra space. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
+``` diff --git a/solutions/lc-solutions/1000-1099/1013-partition-array-into-three-parts-with-equal-sum.md b/solutions/lc-solutions/1000-1099/1013-partition-array-into-three-parts-with-equal-sum.md new file mode 100644 index 0000000..ec91514 --- /dev/null +++ b/solutions/lc-solutions/1000-1099/1013-partition-array-into-three-parts-with-equal-sum.md @@ -0,0 +1,136 @@ +--- +id: partition-array-into-three-parts-with-equal-sum +title: Partition Array Into Three Parts With Equal Sum +sidebar_label: Partition Array Equal Sum +tags: + - Array + - Two Pointers + - Java + - Python + - C++ +description: "This document provides solutions for the Partition Array Into Three Parts With Equal Sum problem." +--- + +## Problem Statement + +Given an array of integers `arr`, return `true` if we can partition the array into three non-empty parts with equal sums. + +Formally, we can partition the array if we can find indexes `i+1 < j` with `(arr[0] + arr[1] + ... + arr[i] == arr[i+1] + arr[i+2] + ... + arr[j-1] == arr[j] + arr[j+1] + ... + arr[arr.length-1])`. + +**Example 1:** + +Input: `arr = [0,2,1,-6,6,-7,9,1,2,0,1]` + +Output: `true` + +Explanation: The array can be partitioned as `[0,2,1]`, `[ -6,6,-7,9,1,2]`, `[0,1]` with equal sums of `[3,3,1]`. + +**Example 2:** + +Input: `arr = [0,2,1,-6,6,7,9,-1,2,0,1]` + +Output: `false` + +**Example 3:** + +Input: `arr = [3,3,6,5,-2,2,5,1,-9,4]` + +Output: `true` + +**Constraints:** + +- `3 <= arr.length <= 5 * 10^4` +- `-10^4 <= arr[i] <= 10^4` + +## Solutions + +### Approach + +To determine if we can partition the array into three parts with equal sums, we can use the following approach: + +1. **Calculate Total Sum**: + - Compute the total sum of the array elements. + +2. **Check Divisibility**: + - If the total sum is not divisible by 3, return `false` immediately since equal partitioning is not possible. + +3. **Partitioning**: + - Iterate through the array to find partitions where the cumulative sum equals `sum/3`. + - Count partitions until two partitions are found where the cumulative sum equals `sum/3`. + +### Java + +```java +class Solution { + public boolean canThreePartsEqualSum(int[] arr) { + int sum = 0; + for (int num : arr) { + sum += num; + } + if (sum % 3 != 0) { + return false; + } + + int target = sum / 3; + int currentSum = 0, partitions = 0; + + for (int num : arr) { + currentSum += num; + if (currentSum == target) { + partitions++; + currentSum = 0; + } + } + + return partitions >= 3; + } +} +``` + +### Python + +```python +class Solution: + def canThreePartsEqualSum(self, arr: List[int]) -> bool: + total_sum = sum(arr) + if total_sum % 3 != 0: + return False + + target = total_sum // 3 + current_sum, partitions = 0, 0 + + for num in arr: + current_sum += num + if current_sum == target: + partitions += 1 + current_sum = 0 + + return partitions >= 3 +``` + +### C++ + +```cpp +class Solution { +public: + bool canThreePartsEqualSum(vector& arr) { + int sum = accumulate(arr.begin(), arr.end(), 0); + if (sum % 3 != 0) { + return false; + } + + int target = sum / 3; + int currentSum = 0, partitions = 0; + + for (int num : arr) { + currentSum += num; + if (currentSum == target) { + partitions++; + currentSum = 0; + } + } + + return partitions >= 3; + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/1000-1099/1018-binary-prefix-divisible-by-5.md b/solutions/lc-solutions/1000-1099/1018-binary-prefix-divisible-by-5.md new file mode 100644 index 0000000..80468f9 --- /dev/null +++ b/solutions/lc-solutions/1000-1099/1018-binary-prefix-divisible-by-5.md @@ -0,0 +1,134 @@ +--- +id: binary-prefix-divisible-by-5 +title: Binary Prefix Divisible By 5 +sidebar_label: Binary Prefix Divisible By 5 +tags: + - Array + - Bit Manipulation + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Binary Prefix Divisible By 5 problem on LeetCode." +sidebar_position: 25 +--- + +## Problem Description + +You are given a binary array `nums` (0-indexed). + +We define `xi` as the number whose binary representation is the subarray `nums[0..i]` (from most-significant-bit to least-significant-bit). + +For example, if `nums = [1,0,1]`, then `x0 = 1`, `x1 = 2`, and `x2 = 5`. + +Return an array of booleans `answer` where `answer[i]` is true if `xi` is divisible by 5. + +### Examples + +**Example 1:** + +``` +Input: nums = [0,1,1] +Output: [true,false,false] +Explanation: The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. +Only the first number is divisible by 5, so answer[0] is true. +``` + +**Example 2:** + +``` +Input: nums = [1,1,1] +Output: [false,false,false] +``` + +### Constraints + +- `1 <= nums.length <= 10^5` +- `nums[i]` is either 0 or 1. + +--- + +## Solution for Binary Prefix Divisible By 5 Problem + +To solve this problem, we can take advantage of the fact that we only need to check divisibility by 5. As we iterate through the array, we can keep track of the current number modulo 5. This allows us to avoid handling potentially large integers. + +### Approach + +1. Initialize current to 0, which will store the current number modulo 5. +2. Iterate through each element in nums: + - Update current by shifting it left and adding the current element. + - Take current modulo 5 to keep it within manageable range. + - Append True to the result if current is 0, otherwise append False. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector prefixesDivBy5(vector& nums) { + vector result; + int current = 0; + for (int num : nums) { + current = (current * 2 + num) % 5; + result.push_back(current == 0); + } + return result; + } +}; +``` + + + + + +```java +class Solution { + public List prefixesDivBy5(int[] nums) { + List result = new ArrayList<>(); + int current = 0; + for (int num : nums) { + current = (current * 2 + num) % 5; + result.add(current == 0); + } + return result; + } +} +``` + + + + + +```python +class Solution: + def prefixesDivBy5(self, nums: List[int]) -> List[bool]: + result = [] + current = 0 + for num in nums: + current = (current * 2 + num) % 5 + result.append(current == 0) + return result +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(n)$, where `n` is the length of the array. We iterate through the array once. +- **Space Complexity**: $O(1)$, not including the space needed for the output array. We only use a constant amount of additional space. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
+``` \ No newline at end of file diff --git a/solutions/lc-solutions/1000-1099/1026-maximum-difference-between-node-and-ancestor.md b/solutions/lc-solutions/1000-1099/1026-maximum-difference-between-node-and-ancestor.md new file mode 100644 index 0000000..1333aa4 --- /dev/null +++ b/solutions/lc-solutions/1000-1099/1026-maximum-difference-between-node-and-ancestor.md @@ -0,0 +1,131 @@ +--- +id: maximum-difference-between-node-and-ancestor +title: Maximum Difference Between Node and Ancestor +sidebar_label: Maximum Difference Ancestor +tags: + - Tree + - Depth-First Search (DFS) + - Recursion + - Java + - Python + - C++ +description: "This document provides solutions for the Maximum Difference Between Node and Ancestor problem." +--- + +## Problem Statement + +Given the root of a binary tree, find the maximum value `V` for which there exist different nodes `A` and `B` where `V = |A.val - B.val|` and `A` is an ancestor of `B`. + +A node A is an ancestor of B if either: A is an ancestor of B or if the given B is an ancestor of A. + +**Example TreeNode root = + + # Example + + +Here's an example solution for LeetCode problem 1026, "Maximum Difference Between Node and Ancestor": + +### Problem Statement + +Given the root of a binary tree, find the maximum value `V` for which there exist different nodes `A` and `B` where `V = |A.val - B.val|` and `A` is an ancestor of `B`. + +A node A is an ancestor of B if there exists a path from A to B (including A and B themselves). + +### Example + +For example, consider the following binary tree: + +``` + 8 + / \ + 3 10 + / \ \ +1 6 14 + / \ / + 4 7 13 +``` + +The maximum difference between a node and its ancestor in this tree is `7`, which occurs between node `1` and node `8` (or node `10`). + +### Solutions + +#### Approach: Depth-First Search (DFS) + +To solve this problem, we can use a depth-first search (DFS) approach to track the minimum and maximum values encountered on the path from the root to each node. Here's how the solution can be implemented in Java, Python, and C++: + +### Java + +```java +class Solution { + int maxDifference = 0; + + public int maxAncestorDiff(TreeNode root) { + dfs(root, root.val, root.val); + return maxDifference; + } + + private void dfs(TreeNode node, int minAncestor, int maxAncestor) { + if (node == null) return; + + int currentDiff = Math.max(Math.abs(node.val - minAncestor), Math.abs(node.val - maxAncestor)); + maxDifference = Math.max(maxDifference, currentDiff); + + minAncestor = Math.min(minAncestor, node.val); + maxAncestor = Math.max(maxAncestor, node.val); + + dfs(node.left, minAncestor, maxAncestor); + dfs(node.right, minAncestor, maxAncestor); + } +} +``` + +### Python + +```python +class Solution: + def maxAncestorDiff(self, root: TreeNode) -> int: + self.max_diff = 0 + + def dfs(node, min_ancestor, max_ancestor): + if not node: + return + + current_diff = max(abs(node.val - min_ancestor), abs(node.val - max_ancestor)) + self.max_diff = max(self.max_diff, current_diff) + + min_ancestor = min(min_ancestor, node.val) + max_ancestor = max(max_ancestor, node.val) + + dfs(node.left, min_ancestor, max_ancestor) + dfs(node.right, min_ancestor, max_ancestor) + + dfs(root, root.val, root.val) + return self.max_diff +``` + +### C++ + +```cpp +class Solution { +public: + int maxDifference = 0; + + int maxAncestorDiff(TreeNode* root) { + dfs(root, root->val, root->val); + return maxDifference; + } + + void dfs(TreeNode* node, int minAncestor, int maxAncestor) { + if (!node) return; + + int currentDiff = max(abs(node->val - minAncestor), abs(node->val - maxAncestor)); + maxDifference = max(maxDifference, currentDiff); + + minAncestor = min(minAncestor, node->val); + maxAncestor = max(maxAncestor, node->val); + + dfs(node->left, minAncestor, maxAncestor); + dfs(node->right, minAncestor, maxAncestor); + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/1000-1099/1038-binary-search-tree-to-greater-sum-tree.md b/solutions/lc-solutions/1000-1099/1038-binary-search-tree-to-greater-sum-tree.md new file mode 100644 index 0000000..c40297f --- /dev/null +++ b/solutions/lc-solutions/1000-1099/1038-binary-search-tree-to-greater-sum-tree.md @@ -0,0 +1,338 @@ +--- +id: binary-search-tree-to-greater-sum-tree +title: Binary Search Tree to Greater Sum Tree +sidebar_label: 1038. Binary Search Tree to Greater Sum Tree +tags: +- Tree +- Depth-First Search +- Binary Tree +description: "This is a solution to the Binary Search Tree to Greater Sum Tree problem on LeetCode." +--- + +## Problem Description +Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. + +As a reminder, a binary search tree is a tree that satisfies these constraints: + +The left subtree of a node contains only nodes with keys less than the node's key. +The right subtree of a node contains only nodes with keys greater than the node's key. +Both the left and right subtrees must also be binary search trees. + +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2019/05/02/tree.png) +``` +Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] +Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] +``` + +**Example 2:** +``` +Input: root = [0,null,1] +Output: [1,null,1] +``` + +### Constraints +- `The number of nodes in the tree is in the range [1, 100].` +- `0 <= Node.val <= 100` +- `All the values in the tree are unique.` + +## Solution for Binary Search Tree to Greater Sum Tree + +1. **Reverse In-Order Traversal**: + - Perform a reverse in-order traversal (right-root-left) of the BST. This traversal order allows us to visit nodes in descending order of their values. + +2. **Accumulating Sum**: + - Maintain a running sum of all nodes visited so far. As we visit each node, we add its value to this running sum and update the node's value with this running sum. + +3. **Recursion**: + - Use recursion to traverse the tree and update the node values. + + + +#### Implementation + +```jsx live +function Solution() { +class TreeNode { + constructor(val = 0, left = null, right = null) { + this.val = val; + this.left = left; + this.right = right; + } +} + + var sum = 0; + + var solve = function(root) { + if (root === null) { + return null; + } + + solve(root.right); + + sum += root.val; + root.val = sum; + + solve(root.left); + + return root; + }; + + var bstToGst = function(root) { + sum = 0; // Reset sum for each call + return solve(root); + }; +function constructTreeFromArray(array) { + if (!array.length) return null; + + let root = new TreeNode(array[0]); + let queue = [root]; + let i = 1; + + while (i < array.length) { + let currentNode = queue.shift(); + + if (array[i] !== null) { + currentNode.left = new TreeNode(array[i]); + queue.push(currentNode.left); + } + i++; + + if (i < array.length && array[i] !== null) { + currentNode.right = new TreeNode(array[i]); + queue.push(currentNode.right); + } + i++; + } + return root; +} +const array = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] +const root = constructTreeFromArray(array) +const input = root +const output = bstToGst(root) + return ( +
+

+ Input: {JSON.stringify(array)} +

+

+ Output: {output.toString()} +

+
+ ); +} +``` + +### Code in Different Languages + + + + + ```javascript + /** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ + +var sum = 0; + +var solve = function(root) { + if (root === null) { + return null; + } + + solve(root.right); + + sum += root.val; + root.val = sum; + + solve(root.left); + + return root; +}; + +var bstToGst = function(root) { + sum = 0; // Reset sum for each call + return solve(root); +}; + +``` + + + + ```typescript + /** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +let sum = 0; + +const solve = (root: TreeNode | null): TreeNode | null => { + if (root === null) { + return null; + } + + solve(root.right); + + sum += root.val; + root.val = sum; + + solve(root.left); + + return root; +}; + +const bstToGst = (root: TreeNode | null): TreeNode | null => { + sum = 0; // Reset sum for each call + return solve(root); +}; + + ``` + + + + ```python + # Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def __init__(self): + self.sum = 0 + + def solve(self, root): + if not root: + return None + + self.solve(root.right) + + self.sum += root.val + root.val = self.sum + + self.solve(root.left) + + return root + + def bstToGst(self, root: TreeNode) -> TreeNode: + self.sum = 0 # Reset sum for each call + return self.solve(root) + + ``` + + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int sum = 0; + + private TreeNode solve(TreeNode root) { + if (root == null) { + return null; + } + + solve(root.right); + + sum += root.val; + root.val = sum; + + solve(root.left); + + return root; + } + + public TreeNode bstToGst(TreeNode root) { + return solve(root); + } +} + +``` + + + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int sum = 0; + + TreeNode* solve(TreeNode*& root) { + if (root == NULL) { + return 0; + } + + solve(root->right); + + sum += root->val; + root->val = sum; + solve(root->left); + + return root; + } + + TreeNode* bstToGst(TreeNode* root) { + return solve(root); + } +}; + +``` + + + +#### Complexity Analysis + ##### Time Complexity: $O(N)$ , because of tree traversal + + ##### Space Complexity: $O(1)$ +
+
+ +## References + +- **LeetCode Problem**: [Binary Search Tree to Greater Sum Tree](https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/description/) + diff --git a/solutions/lc-solutions/1000-1099/1051-height-checker.md b/solutions/lc-solutions/1000-1099/1051-height-checker.md new file mode 100644 index 0000000..e19000f --- /dev/null +++ b/solutions/lc-solutions/1000-1099/1051-height-checker.md @@ -0,0 +1,130 @@ +--- +id: height-checker +title: Height Checker +sidebar_label: 1051-height-checker +tags: +- Array +- Sorting +- Counting Sort +description: "Given an array heights, return the number of indices where heights[i] != expected[i]." +--- + +## Problem Description + +A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array `expected` where `expected[i]` is the expected height of the ith student in line. + +You are given an integer array `heights` representing the current order that the students are standing in. Each `heights[i]` is the height of the ith student in line (0-indexed). + +Return the number of indices where `heights[i]` != `expected[i]`. + +### Examples + +**Example 1:** +``` +Input: heights = [1,1,4,2,1,3] +Output: 3 +Explanation: +heights: [1,1,4,2,1,3] +expected: [1,1,1,2,3,4] +Indices 2, 4, and 5 do not match. +``` +**Example 2:** +``` +Input: heights = [5,1,2,3,4] +Output: 5 +Explanation: +heights: [5,1,2,3,4] +expected: [1,2,3,4,5] +All indices do not match. +``` +**Example 3:** +``` +Input: heights = [1,2,3,4,5] +Output: 0 +Explanation: +heights: [1,2,3,4,5] +expected: [1,2,3,4,5] +All indices match. +``` +### Constraints + +- `1 <= heights.length <= 100` +- `1 <= heights[i] <= 100` + +## Approach + +To determine the number of indices where the elements in the `heights` array do not match the elements in the `expected` array, we can follow these steps: + +1. Create a copy of the `heights` array and sort it to get the `expected` array. +2. Compare the `heights` array with the `expected` array and count the number of mismatched indices. + +### Solution + +#### Java Solution + +```java +import java.util.Arrays; + +class Solution { + public int heightChecker(int[] heights) { + int[] exp = new int[heights.length]; + int count = 0; + for(int i = 0; i < heights.length; i++) { + exp[i] = heights[i]; + } + Arrays.sort(exp); + for(int i = 0; i < heights.length; i++) { + if(heights[i] != exp[i]) { + count++; + } + } + return count; + } +} +``` + +#### C++ Solution + +```cpp +#include +#include + +class Solution { +public: + int heightChecker(std::vector& heights) { + std::vector exp = heights; + std::sort(exp.begin(), exp.end()); + int count = 0; + for (int i = 0; i < heights.size(); ++i) { + if (heights[i] != exp[i]) { + count++; + } + } + return count; + } +}; +``` + +#### Python Solution + +```python +class Solution: + def heightChecker(self, heights: List[int]) -> int: + exp = sorted(heights) + count = 0 + for i in range(len(heights)): + if heights[i] != exp[i]: + count += 1 + return count +``` + +### Complexity Analysis + +**Time Complexity:** O(n log n) +> The time complexity is dominated by the sorting step, which takes O(n log n) time. + +**Space Complexity:** O(n) +> We use additional space to store the sorted `expected` array. + +### References +**LeetCode Problem:** [Height Checker](https://leetcode.com/problems/height-checker/) diff --git a/solutions/lc-solutions/1000-1099/1052-grumpy-bookstore-owner.md b/solutions/lc-solutions/1000-1099/1052-grumpy-bookstore-owner.md new file mode 100644 index 0000000..a413c22 --- /dev/null +++ b/solutions/lc-solutions/1000-1099/1052-grumpy-bookstore-owner.md @@ -0,0 +1,134 @@ +--- +id: grumpy-bookstore-owner +title: Grumpy Bookstore Owner +level: medium +sidebar_label: Grumpy Bookstore Owner +tags: + - Array + - Sliding Window + - Greedy + - Java + - Python +description: "This document provides solutions for the Grumpy Bookstore Owner problem on LeetCode." +--- + +## Problem Statement + +There is a bookstore owner that has a store open for `n` minutes. Every minute, some number of customers enter the store. You are given an integer array `customers` of length `n` where `customers[i]` is the number of customers that enter the store at the start of the `i`th minute and all those customers leave after the end of that minute. + +On some minutes, the bookstore owner is grumpy. You are given a binary array `grumpy` where `grumpy[i]` is `1` if the bookstore owner is grumpy during the `i`th minute, and is `0` otherwise. + +When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied. + +The bookstore owner knows a secret technique to keep themselves not grumpy for `minutes` consecutive minutes, but can only use it once. + +Return the maximum number of customers that can be satisfied throughout the day. + +**Example 1:** + +Input: `customers = [1,0,1,2,1,1,7,5]`, `grumpy = [0,1,0,1,0,1,0,1]`, `minutes = 3` +Output: `16` + +Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. +The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16. + +**Example 2:** + +Input: `customers = [1]`, `grumpy = [0]`, `minutes = 1` +Output: `1` + +**Constraints:** + +- `n == customers.length == grumpy.length` +- `1 <= minutes <= n <= 2 * 10^4` +- `0 <= customers[i] <= 1000` +- `grumpy[i]` is either `0` or `1`. + +## Solutions + +### Intuition + +To maximize the number of satisfied customers, we need to: +1. Calculate the number of satisfied customers when the owner is not grumpy. +2. Use a sliding window to determine the best time to apply the secret technique to maximize the number of satisfied customers. + +### Approach + +1. **Initial Satisfaction Calculation:** + - Calculate the total number of customers satisfied when the owner is not grumpy. + - Use a variable `max_satisfied` to keep track of this initial number. + +2. **Sliding Window Technique:** + - Use a sliding window of size `minutes` to determine the best period to use the secret technique. + - Calculate the additional customers satisfied within this window. + - Update the maximum number of satisfied customers based on this calculation. + +### Implementation + +The provided code effectively implements the sliding window approach. Here's the breakdown: + +1. **Initial Satisfaction Calculation:** + - Traverse the `customers` array and add up customers where `grumpy[i]` is `0`. + +2. **Sliding Window:** + - Maintain a running sum of customers within the current window where `grumpy[i]` is `1`. + - Slide the window across the array and update the maximum satisfied customers. + +### Java + +```java +class Solution { + public int maxSatisfied(int[] customers, int[] grumpy, int minutes) { + int base = 0; + int currentWindow = 0; + int len = customers.length; + for(int i = 0; i < len; i++) { + if(grumpy[i] == 0) base += customers[i]; + else if(i < minutes) currentWindow += customers[i]; + } + int maxWindow = currentWindow; + for(int i = minutes; i < len; i++) { + currentWindow += (customers[i] * grumpy[i]); + currentWindow -= (customers[i - minutes] * grumpy[i - minutes]); + maxWindow = Math.max(currentWindow, maxWindow); + } + return maxWindow + base; + } +} + +``` + +### Python + +```Python +class Solution: + def maxSatisfied(self, customers, grumpy, minutes): + base = 0 + current_window = 0 + length = len(customers) + + for i in range(length): + if grumpy[i] == 0: + base += customers[i] + elif i < minutes: + current_window += customers[i] + + max_window = current_window + + for i in range(minutes, length): + current_window += customers[i] * grumpy[i] + current_window -= customers[i - minutes] * grumpy[i - minutes] + max_window = max(current_window, max_window) + + return max_window + base +``` + +###conclusion + +Complexity +Time Complexity: $O(n)$ +The algorithm iterates through the array twice (once for the initial satisfaction calculation and once for the sliding window), resulting in a linear time complexity. + +Space Complexity: $O(1)$ +The algorithm uses a constant amount of extra space for variables like satisfied, additional, and maxAdditional. + diff --git a/solutions/lc-solutions/1000-1099/_category_.json b/solutions/lc-solutions/1000-1099/_category_.json new file mode 100644 index 0000000..dbfd36f --- /dev/null +++ b/solutions/lc-solutions/1000-1099/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "1000-1099", + "position": 12, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (1000 - 1099)" + } +} diff --git a/solutions/lc-solutions/1100-1199/1100-find-k-length-substrings-with-no-repeated-characters.md b/solutions/lc-solutions/1100-1199/1100-find-k-length-substrings-with-no-repeated-characters.md new file mode 100644 index 0000000..e69de29 diff --git a/solutions/lc-solutions/1100-1199/1109-Corporate Flight Bookings.md b/solutions/lc-solutions/1100-1199/1109-Corporate Flight Bookings.md new file mode 100644 index 0000000..d7b8aff --- /dev/null +++ b/solutions/lc-solutions/1100-1199/1109-Corporate Flight Bookings.md @@ -0,0 +1,146 @@ +--- +id: corporate-flight-bookings +title: Corporate Flight Bookings +sidebar_label: Corporate Flight Bookings +tags: [Array, Prefix Sum, C++, Python, Java] +description: Solve the problem of calculating the total number of seats reserved for each flight using the booking intervals and prefix sum technique. +--- + +## Problem Statement + +### Problem Description + +There are `n` flights that are labeled from 1 to `n`. + +You are given an array of flight bookings `bookings`, where `bookings[i] = [firsti, lasti, seatsi]` represents a booking for flights `firsti` through `lasti` (inclusive) with `seatsi` seats reserved for each flight in the range. + +Return an array `answer` of length `n`, where `answer[i]` is the total number of seats reserved for flight `i`. + +### Example + +**Example 1:** + +``` +Input: bookings = [[1, 2, 10], [2, 3, 20], [2, 5, 25]], n = 5 +Output: [10, 55, 45, 25, 25] +``` +**Explanation:** +Flight labels: 1 2 3 4 5 +Booking 1 reserved: 10 10 +Booking 2 reserved: 20 20 +Booking 3 reserved: 25 25 25 25 +Total seats: 10 55 45 25 25 +Hence, answer = [10, 55, 45, 25, 25] + +**Example 2:** +``` +Input: bookings = [[1, 2, 10], [2, 2, 15]], n = 2 +Output: [10, 25] +``` +**Explanation:** +Flight labels: 1 2 +Booking 1 reserved: 10 10 +Booking 2 reserved: 15 +Total seats: 10 25 +Hence, answer = [10, 25] + + +### Constraints + +- 1 <= `n` <= 2 * 10^4 +- 1 <= `bookings.length` <= 2 * 10^4 +- `bookings[i].length` == 3 +- 1 <= `firsti` <= `lasti` <= `n` +- 1 <= `seatsi` <= 10^4 + +## Solution + +### Intuition + +To solve this problem efficiently, we use a difference array (also known as a prefix sum array). The idea is to use an auxiliary array to keep track of seat reservations in a way that allows us to compute the final seat count for each flight in a single pass. + +1. **Use a Difference Array**: + - Create an array `arr` of size `n+1` to track the seat changes. + - For each booking `[firsti, lasti, seatsi]`, increment `arr[firsti-1]` by `seatsi` and decrement `arr[lasti]` by `seatsi` (if `lasti < n`). + +2. **Compute the Prefix Sum**: + - Traverse the difference array to compute the prefix sum which gives the total number of seats reserved for each flight. + +### Time Complexity and Space Complexity Analysis + +- **Time Complexity**: + - The time complexity is $O(m + n)$, where `m` is the number of bookings and `n` is the number of flights. This is due to the single pass required for processing the bookings and computing the prefix sum. + +- **Space Complexity**: + - The space complexity is $O(n)$, which is required to store the difference array and the final answer array. + +### Code + +#### C++ + +```cpp +class Solution { +public: + vector corpFlightBookings(vector>& bookings, int n) { + vector arr(n + 1, 0); + for (const auto& booking : bookings) { + int start = booking[0] - 1; + int end = booking[1]; + int seats = booking[2]; + arr[start] += seats; + if (end < n) { + arr[end] -= seats; + } + } + + vector answer(n); + answer[0] = arr[0]; + for (int i = 1; i < n; ++i) { + answer[i] = answer[i - 1] + arr[i]; + } + return answer; + } +}; +``` +#### Python +```python +class Solution: + def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: + arr = [0] * (n + 1) + for start, end, seats in bookings: + arr[start - 1] += seats + if end < n: + arr[end] -= seats + + answer = [0] * n + answer[0] = arr[0] + for i in range(1, n): + answer[i] = answer[i - 1] + arr[i] + + return answer +``` +#### Java +```java +class Solution { + public int[] corpFlightBookings(int[][] bookings, int n) { + int[] arr = new int[n + 1]; + for (int[] booking : bookings) { + int start = booking[0] - 1; + int end = booking[1]; + int seats = booking[2]; + arr[start] += seats; + if (end < n) { + arr[end] -= seats; + } + } + + int[] answer = new int[n]; + answer[0] = arr[0]; + for (int i = 1; i < n; i++) { + answer[i] = answer[i - 1] + arr[i]; + } + + return answer; + } +} +``` diff --git a/solutions/lc-solutions/1100-1199/1110-Delete Nodes And Return Forest.md b/solutions/lc-solutions/1100-1199/1110-Delete Nodes And Return Forest.md new file mode 100644 index 0000000..02991f2 --- /dev/null +++ b/solutions/lc-solutions/1100-1199/1110-Delete Nodes And Return Forest.md @@ -0,0 +1,113 @@ +--- +id: delete-nodes-and-return-forest +title: Delete Nodes And Return Forest +sidebar_label: Delete Nodes And Return Forest +tags: [Binary Tree, Depth-First Search, C++, Python, Java] +description: Solve the problem of deleting nodes from a binary tree and returning the forest of remaining trees using depth-first search. +--- + +## Problem Statement + +### Problem Description + +Given the root of a binary tree, each node in the tree has a distinct value. + +After deleting all nodes with a value in `to_delete`, we are left with a forest (a disjoint union of trees). + +Return the roots of the trees in the remaining forest. You may return the result in any order. + +### Example + +**Example 1:** +``` +Input: root = [1, 2, 3, 4, 5, 6, 7], to_delete = [3, 5] +Output: [[1, 2, null, 4], [6], [7]] +``` + +### Constraints + +- The number of nodes in the given tree is at most 1000. +- Each node has a distinct value between 1 and 1000. +- `to_delete` contains distinct values between 1 and 1000. + +## Solution + +### Intuition + +The problem can be solved using a depth-first search (DFS) approach. The idea is to traverse the tree and, whenever a node needs to be deleted (i.e., its value is in the `to_delete` list), we handle its children by potentially adding them to the forest if they are not to be deleted. We maintain a set of nodes to be deleted for quick lookup and use a helper function to perform the DFS and manage the forest creation. + +### Time Complexity and Space Complexity Analysis + +- **Time Complexity**: + - The solution involves a single traversal of the tree, making the time complexity $O(n)$, where `n` is the number of nodes in the tree. + +- **Space Complexity**: + - The space complexity is $O(n)$ due to the recursive call stack and storage for the result list. + +### Code + +#### C++ + +```cpp +class Solution { +public: + vector delNodes(TreeNode* root, vector& to_delete) { + unordered_set to_delete_set(to_delete.begin(), to_delete.end()); + vector forest; + if (!to_delete_set.count(root->val)) { + forest.push_back(root); + } + dfs(root, to_delete_set, forest); + return forest; + } + +private: + TreeNode* dfs(TreeNode* node, unordered_set& to_delete_set, vector& forest) { + if (!node) return nullptr; + node->left = dfs(node->left, to_delete_set, forest); + node->right = dfs(node->right, to_delete_set, forest); + if (to_delete_set.count(node->val)) { + if (node->left) forest.push_back(node->left); + if (node->right) forest.push_back(node->right); + return nullptr; + } + return node; + } +}; +``` +#### Python +```python +class Solution: + def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: + seats = [0] * (n + 1) + for booking in bookings: + first, last, seats_count = booking + seats[first - 1] += seats_count + if last < n: + seats[last] -= seats_count + for i in range(1, n): + seats[i] += seats[i - 1] + return seats[:-1] + +``` +#### Java +```java +class Solution { + public int[] corpFlightBookings(int[][] bookings, int n) { + int[] seats = new int[n + 1]; + for (int[] booking : bookings) { + int first = booking[0]; + int last = booking[1]; + int seatsCount = booking[2]; + seats[first - 1] += seatsCount; + if (last < n) { + seats[last] -= seatsCount; + } + } + for (int i = 1; i < n; i++) { + seats[i] += seats[i - 1]; + } + return Arrays.copyOf(seats, n); + } +} +``` diff --git a/solutions/lc-solutions/1100-1199/1111-maximum-nesting-depth-of-two-valid-parantheses-strings.md b/solutions/lc-solutions/1100-1199/1111-maximum-nesting-depth-of-two-valid-parantheses-strings.md new file mode 100644 index 0000000..3e8306f --- /dev/null +++ b/solutions/lc-solutions/1100-1199/1111-maximum-nesting-depth-of-two-valid-parantheses-strings.md @@ -0,0 +1,149 @@ +--- +id: maximum-nesting-depth-of-two-valid-parentheses-strings +title: Maximun-Nesting-Depth-of-Two-Valid-Parentheses-Strings +sidebar_label: 1111 - Maximun-Nesting-Depth-of-Two-Valid-Parentheses-Strings +tags: + - Leetcode +--- + +## Problem Statement + +A string is a valid parentheses string (VPS) if and only if it consists of `(` and `)` characters only, and: + +- It is the empty string, or +- It can be written as AB (A concatenated with B), where A and B are VPS's, or +- It can be written as (A), where A is a VPS. + +We can similarly define the nesting depth `depth(S)` of any VPS `S` as follows: + +- `depth("") = 0` +- `depth(A + B) = max(depth(A), depth(B))`, where A and B are VPS's +- `depth("(" + A + ")") = 1 + depth(A)`, where A is a VPS. + +For example, `""`, `"()()"`, and `"()(()())"` are VPS's (with nesting depths 0, 1, and 2), and `")("` and `"(()"` are not VPS's. + +Given a VPS `seq`, split it into two disjoint subsequences `A` and `B`, such that `A` and `B` are VPS's (and `A.length + B.length = seq.length`). + +Now choose any such `A` and `B` such that `max(depth(A), depth(B))` is the minimum possible value. + +Return an answer array (of length `seq.length`) that encodes such a choice of `A` and `B`: `answer[i] = 0` if `seq[i]` is part of `A`, else `answer[i] = 1`. Note that even though multiple answers may exist, you may return any of them. + +## Examples + +### Example 1 + +**Input:** `seq = "(()())"` +**Output:** `[0, 1, 1, 1, 1, 0]` + +### Example 2 + +**Input:** `seq = "()(())()"` +**Output:** `[0, 0, 0, 1, 1, 0, 1, 1]` + +## Constraints + +- $1 <= seq.size <= 10000$ + +## Algorithm + +1. Initialize an empty stack to keep track of the depth. +2. Initialize the `answer` array with all zeros. +3. Iterate through each character in the `seq` string: + - If the character is `(`, check the current depth (based on the size of the stack): + - Assign the character to one of the subsequences (either `0` or `1`) in an alternating fashion to balance the depth between `A` and `B`. + - Push the current depth level onto the stack. + - If the character is `)`, pop from the stack and assign the closing parenthesis to the same subsequence as its matching opening parenthesis. +4. Return the `answer` array. + +## C++ Code + +```cpp +class Solution { +public: + vector maxDepthAfterSplit(string seq) { + int n = seq.size(); + vector answer(n, 0); + int depth = 0; + + for (int i = 0; i < n; ++i) { + if (seq[i] == '(') { + answer[i] = depth % 2; + depth++; + } else { + depth--; + answer[i] = depth % 2; + } + } + + return answer; + } +}; +``` + +## Python Code + +```python +class Solution: + def maxDepthAfterSplit(self, seq: str) -> List[int]: + depth = 0 + answer = [] + + for char in seq: + if char == '(': + answer.append(depth % 2) + depth += 1 + else: + depth -= 1 + answer.append(depth % 2) + + return answer +``` + +## Java Code + +```java +class Solution { + public int[] maxDepthAfterSplit(String seq) { + int n = seq.length(); + int[] answer = new int[n]; + int depth = 0; + + for (int i = 0; i < n; i++) { + if (seq.charAt(i) == '(') { + answer[i] = depth % 2; + depth++; + } else { + depth--; + answer[i] = depth % 2; + } + } + + return answer; + } +} +``` + +## JavaScript Code + +```javascript +/** + * @param {string} seq + * @return {number[]} + */ +var maxDepthAfterSplit = function (seq) { + const answer = []; + let depth = 0; + + for (let char of seq) { + if (char === "(") { + answer.push(depth % 2); + depth++; + } else { + depth--; + answer.push(depth % 2); + } + } + + return answer; +}; +``` diff --git a/solutions/lc-solutions/1100-1199/1115-print-foobar-alternately.md b/solutions/lc-solutions/1100-1199/1115-print-foobar-alternately.md new file mode 100644 index 0000000..4fa4f88 --- /dev/null +++ b/solutions/lc-solutions/1100-1199/1115-print-foobar-alternately.md @@ -0,0 +1,277 @@ +--- +id: print-foobar-alternately +title: Print FooBar Alternately +sidebar_label: 1115 - Print FooBar Alternately + - Leetcode +--- + +## Problem Statement + +Suppose you are given the following code: + +```class FooBar { + public void foo() { + for (int i = 0; i < n; i++) { + print("foo"); + } + } + + public void bar() { + for (int i = 0; i < n; i++) { + print("bar"); + } + } +} +``` + +The same instance of FooBar will be passed to two different threads: + +thread A will call foo(), while +thread B will call bar(). +Modify the given program to output "foobar" n times. + +### Example 1 + +**Input:** `n = 1` +**Output:** `"foobar"` +**Explanation:** There are two threads being fired asynchronously. One of them calls `foo()`, while the other calls `bar()`. "foobar" is being output 1 time. + +### Example 2 + +**Input:** `n = 2` +**Output:** `"foobarfoobar"` +**Explanation:** "foobar" is being output 2 times. + +### Constraints + +- $1 <= n <= 1000$ + +### Explanation + +1. **Initialization**: The `FooBar` class is initialized with a `Barrier` that ensures both threads synchronize at specific points. +2. **foo Method**: + - For each iteration, the `foo` method prints "foo". + - It then waits at the barrier until the `bar` method reaches the same point. +3. **bar Method**: + - For each iteration, the `bar` method waits at the barrier until the `foo` method has printed "foo". + - It then prints "bar". +4. **Thread Execution**: + - Two threads are created and started: one for `foo` and one for `bar`. + - The threads are joined to ensure they complete execution. + +This ensures that "foo" is always printed before "bar" in each iteration, resulting in the output "foobar" repeated `n` times. + +## Python Solution + +```python +from threading import Barrier + +class FooBar: + def __init__(self, n): + self.n = n + self.barrier = Barrier(2) + + def foo(self, printFoo): + for i in range(self.n): + printFoo() + self.barrier.wait() + + def bar(self, printBar): + for i in range(self.n): + self.barrier.wait() + printBar() + +# Helper functions to simulate the print +def printFoo(): + print("foo", end='') + +def printBar(): + print("bar", end='') + +# Example usage: +n = 2 +foo_bar = FooBar(n) + +from threading import Thread + +threadA = Thread(target=foo_bar.foo, args=(printFoo,)) +threadB = Thread(target=foo_bar.bar, args=(printBar,)) + +threadA.start() +threadB.start() + +threadA.join() +threadB.join() +``` + +Sure, here are the solutions for the problem in C++, Java, and JavaScript. + +### C++ Solution + +```cpp +#include +#include +#include +#include + +class FooBar { +private: + int n; + std::mutex mtx; + std::condition_variable cv; + bool foo_turn; + +public: + FooBar(int n) { + this->n = n; + foo_turn = true; + } + + void foo(std::function printFoo) { + for (int i = 0; i < n; i++) { + std::unique_lock lock(mtx); + cv.wait(lock, [this](){ return foo_turn; }); + printFoo(); + foo_turn = false; + cv.notify_one(); + } + } + + void bar(std::function printBar) { + for (int i = 0; i < n; i++) { + std::unique_lock lock(mtx); + cv.wait(lock, [this](){ return !foo_turn; }); + printBar(); + foo_turn = true; + cv.notify_one(); + } + } +}; + +void printFoo() { + std::cout << "foo"; +} + +void printBar() { + std::cout << "bar"; +} + +int main() { + int n = 2; + FooBar fooBar(n); + + std::thread threadA(&FooBar::foo, &fooBar, printFoo); + std::thread threadB(&FooBar::bar, &fooBar, printBar); + + threadA.join(); + threadB.join(); + + return 0; +} +``` + +### Java Solution + +```java +import java.util.concurrent.Semaphore; + +class FooBar { + private int n; + private Semaphore fooSemaphore = new Semaphore(1); + private Semaphore barSemaphore = new Semaphore(0); + + public FooBar(int n) { + this.n = n; + } + + public void foo(Runnable printFoo) throws InterruptedException { + for (int i = 0; i < n; i++) { + fooSemaphore.acquire(); + printFoo.run(); + barSemaphore.release(); + } + } + + public void bar(Runnable printBar) throws InterruptedException { + for (int i = 0; i < n; i++) { + barSemaphore.acquire(); + printBar.run(); + fooSemaphore.release(); + } + } + + public static void main(String[] args) throws InterruptedException { + int n = 2; + FooBar fooBar = new FooBar(n); + + Thread threadA = new Thread(() -> { + try { + fooBar.foo(() -> System.out.print("foo")); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + + Thread threadB = new Thread(() -> { + try { + fooBar.bar(() -> System.out.print("bar")); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + + threadA.start(); + threadB.start(); + + threadA.join(); + threadB.join(); + } +} +``` + +### JavaScript Solution + +```javascript +class FooBar { + constructor(n) { + this.n = n; + this.fooTurn = true; + this.lock = new Promise((resolve) => (this.resolveFoo = resolve)); + } + + async foo(printFoo) { + for (let i = 0; i < this.n; i++) { + await this.lock; + printFoo(); + this.fooTurn = false; + this.lock = new Promise((resolve) => (this.resolveBar = resolve)); + this.resolveBar(); + } + } + + async bar(printBar) { + for (let i = 0; i < this.n; i++) { + while (this.fooTurn) { + await new Promise((resolve) => setTimeout(resolve, 1)); + } + printBar(); + this.fooTurn = true; + this.lock = new Promise((resolve) => (this.resolveFoo = resolve)); + this.resolveFoo(); + } + } +} + +const n = 2; +const fooBar = new FooBar(n); + +function printFoo() { + process.stdout.write("foo"); +} + +function printBar() { + process.stdout.write("bar"); +} + +Promise.all([fooBar.foo(printFoo), fooBar.bar(printBar)]); +``` diff --git a/solutions/lc-solutions/1100-1199/1116-print-zero-even-odd.md b/solutions/lc-solutions/1100-1199/1116-print-zero-even-odd.md new file mode 100644 index 0000000..504dd09 --- /dev/null +++ b/solutions/lc-solutions/1100-1199/1116-print-zero-even-odd.md @@ -0,0 +1,313 @@ +--- +id: print-zero-even-odd +title: Print Zero Even Odd +sidebar_label: 1116 - Print Zero Even Odd + - Leetcode +--- + +## Problem Statement + +You have a function `printNumber` that can be called with an integer parameter and prints it to the console. You are given an instance of the class `ZeroEvenOdd` that has three functions: `zero`, `even`, and `odd`. The same instance of `ZeroEvenOdd` will be passed to three different threads: + +- Thread A: calls `zero()` that should only output 0's. +- Thread B: calls `even()` that should only output even numbers. +- Thread C: calls `odd()` that should only output odd numbers. + +Modify the given class to output the series "010203040506..." where the length of the series must be `2n`. + +## Examples + +### Example 1 + +- Input: `n = 2` +- Output: "0102" +- Explanation: There are three threads being fired asynchronously. One of them calls `zero()`, the other calls `even()`, and the last one calls `odd()`. "0102" is the correct output. + +### Example 2 + +- Input: `n = 5` +- Output: "0102030405" + +## Constraints + +- $1 <= n <= 1000$ + +## Algorithm + +1. Initialize three semaphores: one for zero, one for even, and one for odd. Initially, the zero semaphore is available, while the even and odd semaphores are not. +2. The `zero` method should: + - Print `0`. + - Alternate between enabling the odd and even semaphores. +3. The `even` method should: + - Wait until its semaphore is available. + - Print the next even number. + - Enable the zero semaphore. +4. The `odd` method should: + - Wait until its semaphore is available. + - Print the next odd number. + - Enable the zero semaphore. + +## Python Solution + +```python +from threading import Semaphore + +class ZeroEvenOdd: + def __init__(self, n): + self.n = n + self.zero_semaphore = Semaphore(1) + self.even_semaphore = Semaphore(0) + self.odd_semaphore = Semaphore(0) + self.current_number = 1 + + def zero(self, printNumber): + for _ in range(self.n): + self.zero_semaphore.acquire() + printNumber(0) + if self.current_number % 2 == 1: + self.odd_semaphore.release() + else: + self.even_semaphore.release() + + def even(self, printNumber): + for _ in range(1, self.n // 2 + 1): + self.even_semaphore.acquire() + printNumber(self.current_number) + self.current_number += 1 + self.zero_semaphore.release() + + def odd(self, printNumber): + for _ in range((self.n + 1) // 2): + self.odd_semaphore.acquire() + printNumber(self.current_number) + self.current_number += 1 + self.zero_semaphore.release() +``` + +## C++ Solution + +```cpp +#include +#include +#include + +class ZeroEvenOdd { +private: + int n; + int current_number; + std::binary_semaphore zero_semaphore{1}; + std::binary_semaphore even_semaphore{0}; + std::binary_semaphore odd_semaphore{0}; + +public: + ZeroEvenOdd(int n) : n(n), current_number(1) {} + + void zero(std::function printNumber) { + for (int i = 0; i < n; ++i) { + zero_semaphore.acquire(); + printNumber(0); + if (current_number % 2 == 1) { + odd_semaphore.release(); + } else { + even_semaphore.release(); + } + } + } + + void even(std::function printNumber) { + for (int i = 2; i <= n; i += 2) { + even_semaphore.acquire(); + printNumber(current_number++); + zero_semaphore.release(); + } + } + + void odd(std::function printNumber) { + for (int i = 1; i <= n; i += 2) { + odd_semaphore.acquire(); + printNumber(current_number++); + zero_semaphore.release(); + } + } +}; + +void printNumber(int number) { + std::cout << number; +} + +int main() { + int n = 5; + ZeroEvenOdd zeroEvenOdd(n); + + std::thread t1(&ZeroEvenOdd::zero, &zeroEvenOdd, printNumber); + std::thread t2(&ZeroEvenOdd::even, &zeroEvenOdd, printNumber); + std::thread t3(&ZeroEvenOdd::odd, &zeroEvenOdd, printNumber); + + t1.join(); + t2.join(); + t3.join(); + + return 0; +} +``` + +## Java Solution + +```java +import java.util.concurrent.Semaphore; + +class ZeroEvenOdd { + private int n; + private int currentNumber = 1; + private Semaphore zeroSemaphore = new Semaphore(1); + private Semaphore evenSemaphore = new Semaphore(0); + private Semaphore oddSemaphore = new Semaphore(0); + + public ZeroEvenOdd(int n) { + this.n = n; + } + + public void zero(IntConsumer printNumber) throws InterruptedException { + for (int i = 0; i < n; i++) { + zeroSemaphore.acquire(); + printNumber.accept(0); + if (currentNumber % 2 == 1) { + oddSemaphore.release(); + } else { + evenSemaphore.release(); + } + } + } + + public void even(IntConsumer printNumber) throws InterruptedException { + for (int i = 2; i <= n; i += 2) { + evenSemaphore.acquire(); + printNumber.accept(currentNumber++); + zeroSemaphore.release(); + } + } + + public void odd(IntConsumer printNumber) throws InterruptedException { + for (int i = 1; i <= n; i += 2) { + oddSemaphore.acquire(); + printNumber.accept(currentNumber++); + zeroSemaphore.release(); + } + } +} + +@FunctionalInterface +interface IntConsumer { + void accept(int value); +} + +public class Main { + public static void main(String[] args) throws InterruptedException { + int n = 5; + ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd(n); + + Thread t1 = new Thread(() -> { + try { + zeroEvenOdd.zero(value -> System.out.print(value)); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + + Thread t2 = new Thread(() -> { + try { + zeroEvenOdd.even(value -> System.out.print(value)); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + + Thread t3 = new Thread(() -> { + try { + zeroEvenOdd.odd(value -> System.out.print(value)); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + + t1.start(); + t2.start(); + t3.start(); + + t1.join(); + t2.join(); + t3.join(); + } +} +``` + +## JavaScript Solution + +```javascript +class ZeroEvenOdd { + constructor(n) { + this.n = n; + this.zeroTurn = true; + this.currentNumber = 1; + this.zeroSemaphore = new Promise((resolve) => (this.resolveZero = resolve)); + this.evenSemaphore = new Promise((resolve) => (this.resolveEven = resolve)); + this.oddSemaphore = new Promise((resolve) => (this.resolveOdd = resolve)); + } + + async zero(printNumber) { + for (let i = 0; i < this.n; i++) { + await this.zeroSemaphore; + printNumber(0); + this.zeroTurn = false; + if (this.currentNumber % 2 === 1) { + this.resolveOdd(); + this.oddSemaphore = new Promise( + (resolve) => (this.resolveOdd = resolve) + ); + } else { + this.resolveEven(); + this.evenSemaphore = new Promise( + (resolve) => (this.resolveEven = resolve) + ); + } + } + } + + async even(printNumber) { + for (let i = 2; i <= this.n; i += 2) { + await this.evenSemaphore; + printNumber(this.currentNumber++); + this.zeroTurn = true; + this.resolveZero(); + this.zeroSemaphore = new Promise( + (resolve) => (this.resolveZero = resolve) + ); + } + } + + async odd(printNumber) { + for (let i = 1; i <= this.n; i += 2) { + await this.oddSemaphore; + printNumber(this.currentNumber++); + this.zeroTurn = true; + this.resolveZero(); + this.zeroSemaphore = new Promise( + (resolve) => (this.resolveZero = resolve) + ); + } + } +} + +function printNumber(number) { + process.stdout.write(number.toString()); +} + +const n = 5; +const zeroEvenOdd = new ZeroEvenOdd(n); + +Promise.all([ + zeroEvenOdd.zero(printNumber), + zeroEvenOdd.even(printNumber), + zeroEvenOdd.odd(printNumber), +]); +``` diff --git a/solutions/lc-solutions/1100-1199/1117-buliding-h20.md b/solutions/lc-solutions/1100-1199/1117-buliding-h20.md new file mode 100644 index 0000000..da53e8c --- /dev/null +++ b/solutions/lc-solutions/1100-1199/1117-buliding-h20.md @@ -0,0 +1,222 @@ +--- +id: building-h20 +title: Building-H2o +sidebar_label: 1117 - Building-H2o + - Leetcode +--- + +## Problem Statement + +There are two kinds of threads: oxygen and hydrogen. Your goal is to group these threads to form water molecules. + +There is a barrier where each thread has to wait until a complete molecule can be formed. Hydrogen and oxygen threads will be given `releaseHydrogen` and `releaseOxygen` methods respectively, which will allow them to pass the barrier. These threads should pass the barrier in groups of three, and they must immediately bond with each other to form a water molecule. You must guarantee that all the threads from one molecule bond before any other threads from the next molecule do. + +## Examples + +### Example 1 + +- Input: `water = "HOH"` +- Output: "HHO" +- Explanation: "HOH" and "OHH" are also valid answers. + +### Example 2 + +- Input: `water = "OOHHHH"` +- Output: "HHOHHO" +- Explanation: "HOHHHO", "OHHHHO", "HHOHOH", "HOHHOH", "OHHHOH", "HHOOHH", "HOHOHH" and "OHHOHH" are also valid answers. + +## Constraints + +- $3 * n == water.length$ +- $1 <= n <= 20$ +- water[i] is either 'H' or 'O'. +- $There will be exactly 2 * n 'H' in water.$ +- There will be exactly n 'O' in water. + +## Algorithm + +1. Use semaphores to control the release of hydrogen and oxygen threads. +2. A barrier is used to ensure that the threads only proceed when the necessary number of hydrogen and oxygen threads have arrived. +3. Count the number of hydrogen and oxygen threads, ensuring that hydrogen threads only proceed when there are enough oxygen threads and vice versa. + +## Python Solution + +```python +from threading import Semaphore, Barrier + +class H2O: + def __init__(self): + self.h_semaphore = Semaphore(2) + self.o_semaphore = Semaphore(1) + self.barrier = Barrier(3) + + def hydrogen(self, releaseHydrogen: 'Callable[[], None]') -> None: + self.h_semaphore.acquire() + self.barrier.wait() + releaseHydrogen() + self.h_semaphore.release() + + def oxygen(self, releaseOxygen: 'Callable[[], None]') -> None: + self.o_semaphore.acquire() + self.barrier.wait() + releaseOxygen() + self.o_semaphore.release() +``` + +## C++ Solution + +```cpp +#include +#include +#include +#include +#include + +class H2O { +private: + std::mutex mtx; + std::condition_variable cv; + int hydrogenCount = 0; + int oxygenCount = 0; + +public: + H2O() {} + + void hydrogen(std::function releaseHydrogen) { + std::unique_lock lock(mtx); + cv.wait(lock, [this] { return hydrogenCount < 2; }); + hydrogenCount++; + releaseHydrogen(); + if (hydrogenCount == 2 && oxygenCount == 1) { + hydrogenCount = 0; + oxygenCount = 0; + cv.notify_all(); + } else { + cv.wait(lock, [this] { return hydrogenCount == 0; }); + } + } + + void oxygen(std::function releaseOxygen) { + std::unique_lock lock(mtx); + cv.wait(lock, [this] { return oxygenCount < 1; }); + oxygenCount++; + releaseOxygen(); + if (hydrogenCount == 2 && oxygenCount == 1) { + hydrogenCount = 0; + oxygenCount = 0; + cv.notify_all(); + } else { + cv.wait(lock, [this] { return oxygenCount == 0; }); + } + } +}; +``` + +## Java Solution + +```java +import java.util.concurrent.Semaphore; +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; + +class H2O { + private Semaphore hSemaphore = new Semaphore(2); + private Semaphore oSemaphore = new Semaphore(1); + private CyclicBarrier barrier = new CyclicBarrier(3); + + public H2O() {} + + public void hydrogen(Runnable releaseHydrogen) throws InterruptedException { + hSemaphore.acquire(); + try { + barrier.await(); + } catch (BrokenBarrierException e) { + e.printStackTrace(); + } + releaseHydrogen.run(); + hSemaphore.release(); + } + + public void oxygen(Runnable releaseOxygen) throws InterruptedException { + oSemaphore.acquire(); + try { + barrier.await(); + } catch (BrokenBarrierException e) { + e.printStackTrace(); + } + releaseOxygen.run(); + oSemaphore.release(); + } +} +``` + +## JavaScript Solution + +```javascript +class H2O { + constructor() { + this.hSemaphore = new Semaphore(2); + this.oSemaphore = new Semaphore(1); + this.barrier = new Barrier(3); + } + + async hydrogen(releaseHydrogen) { + await this.hSemaphore.acquire(); + await this.barrier.wait(); + releaseHydrogen(); + this.hSemaphore.release(); + } + + async oxygen(releaseOxygen) { + await this.oSemaphore.acquire(); + await this.barrier.wait(); + releaseOxygen(); + this.oSemaphore.release(); + } +} + +class Semaphore { + constructor(count) { + this.count = count; + this.queue = []; + } + + acquire() { + if (this.count > 0) { + this.count--; + return Promise.resolve(); + } else { + return new Promise((resolve) => this.queue.push(resolve)); + } + } + + release() { + if (this.queue.length > 0) { + const resolve = this.queue.shift(); + resolve(); + } else { + this.count++; + } + } +} + +class Barrier { + constructor(parties) { + this.parties = parties; + this.count = 0; + this.resolves = []; + } + + wait() { + this.count++; + if (this.count === this.parties) { + this.resolves.forEach((resolve) => resolve()); + this.resolves = []; + this.count = 0; + return Promise.resolve(); + } else { + return new Promise((resolve) => this.resolves.push(resolve)); + } + } +} +``` diff --git a/solutions/lc-solutions/1100-1199/1129-shortest-path-with-alternating-colors.md b/solutions/lc-solutions/1100-1199/1129-shortest-path-with-alternating-colors.md new file mode 100644 index 0000000..7b8e4a3 --- /dev/null +++ b/solutions/lc-solutions/1100-1199/1129-shortest-path-with-alternating-colors.md @@ -0,0 +1,211 @@ +--- +id: shortest-path-with-allternating-colors +title: Shortest-Path-With-Alternating-Colors +sidebar_label: 1129. Shortest-Path-With-Alternating-Colors +tags: +- Breadth-First Search +- Graph +description: "This is a solution to the Shortest-Path-With-Alternating-Colors problem on LeetCode." +--- + +## Problem Description +You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. + +You are given two arrays redEdges and blueEdges where: + +redEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai to node bi in the graph, and +blueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj to node vj in the graph. +Return an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist. +### Examples + +**Example 1:** +``` +Example 1: + +Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = [] +Output: [0,1,-1] +``` + +**Example 2:** +``` +Input: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]] +Output: [0,1,-1] +``` + +### Constraints +- `1 <= n <= 100` +- `0 <= redEdges.length, blueEdges.length <= 400` +- `redEdges[i].length == blueEdges[j].length == 2` +- `0 <= ai, bi, uj, vj < n` + + +## Solution for Shortest Path with Alternating Colors + +### Approach + + +#### Implementation +#### Code in Different Languages + + + + + ```java + + class Solution { + public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) { + List> l1 = new ArrayList<>(); + List> l2 = new ArrayList<>(); + int[] ans = new int[n]; + Arrays.fill(ans,-1); + for(int i = 0;i()); + l2.add(new ArrayList()); + } + for(int[] r : redEdges){ + l1.get(r[0]).add(r[1]); + } + for(int[] b : blueEdges){ + l2.get(b[0]).add(b[1]); + } + int f = 0; + Queue> q = new LinkedList<>(); + q.add(new Pair<>(0,0)); + q.add(new Pair<>(0,1)); + boolean[][] visited = new boolean[n][2]; + visited[0][1] = true; + visited[0][0] = true; + ans[0] = 0; + int level = 1; + while(!q.isEmpty()){ + int sz = q.size(); + System.out.println(sz); + while(sz-->0){ + Pair curr = q.poll(); + int value = curr.getKey(); + int color = curr.getValue(); + if(color==0){ + for(int i : l1.get(value)){ + if(!visited[i][0]){ + q.add(new Pair<>(i,1)); + if(ans[i]==-1)ans[i] = level; + visited[i][0] = true; + } + } + } + else{ + for(int i : l2.get(value)){ + if(!visited[i][1]){ + q.add(new Pair<>(i,0)); + if(ans[i]==-1) ans[i] = level; + visited[i][1] = true; + } + } + } + } + level++; + } + + return ans; + + } + } + ``` + + + + + ```python + + class Solution: + def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]: + lst=[-1]*n + grid=[[] for i in range(n)] + vr=[-1]*n + vb=[-1]*n + for i,j in redEdges: + grid[i].append((j,True)) + + for i,j in blueEdges: + grid[i].append((j,False)) + + queue=[(0,0,True),(0,0,False)] + vb[0]=1 + vr[0]=1 + while queue: + d,x,flg=queue.pop(0) + if lst[x]==-1: + lst[x]=d + for to,fg2 in grid[x]: + if flg!=fg2: + if (fg2==False and vb[to]==-1): + queue.append((d+1,to,fg2)) + vb[to]=1 + elif (fg2==True and vr[to]==-1): + queue.append((d+1,to,fg2)) + vr[to]=1 + return lst + + ``` + + + + + ```cpp + + class Solution { + public: + vector shortestAlternatingPaths(int n, vector>& redEdges, vector>& blueEdges) { + vector adjRed[n], adjBlue[n]; + for(auto it : redEdges){ + adjRed[it[0]].push_back(it[1]); + } + for(auto it : blueEdges){ + adjBlue[it[0]].push_back(it[1]); + } + set> vis; + vis.insert({0, -1}); + vector ans(n, -1); + queue>> q; // node length color + q.push({0, {0, -1}}); + while(!q.empty()){ + int node = q.front().first; + int length = q.front().second.first; + int color = q.front().second.second; + q.pop(); + if(ans[node] == -1){ + ans[node] = length; + } + //RED EDGE + if(color != 0){ + for(auto it : adjRed[node]){ + if(vis.find({it, 0}) == vis.end()){ + vis.insert({it, 0}); + q.push({it, {length + 1, 0}}); + } + } + } + //BLUE EDGE + if(color != 1){ + for(auto it : adjBlue[node]){ + if(vis.find({it, 1}) == vis.end()){ + vis.insert({it, 1}); + q.push({it, {length + 1, 1}}); + } + } + } + } + return ans; + } + }; + ``` + + + + + +## References + +- **LeetCode Problem:** [Shortest Path With Alternating Colors](https://leetcode.com/problems/shortest-path-with-alternating-colors/solutions/5371884/c-easy-solution/) +--- + diff --git a/solutions/lc-solutions/1100-1199/1143-longest-common-subsequence.md b/solutions/lc-solutions/1100-1199/1143-longest-common-subsequence.md new file mode 100644 index 0000000..7d75f18 --- /dev/null +++ b/solutions/lc-solutions/1100-1199/1143-longest-common-subsequence.md @@ -0,0 +1,169 @@ +--- +id: longest common subsequence +title: longest common subsequence +sidebar_label: 1143-longest common subsequence +tags: +- Recursion +- Dynamic Programming +- Java +- Cpp +- Python +description: "Given two strings , return the longest common subsequence ." +--- + +## Problem + +Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. + +A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. + +For example, "ace" is a subsequence of "abcde". +A common subsequence of two strings is a subsequence that is common to both strings. + +### Examples + +**Example 1:** + +**Input:** text1 = "abcde", text2 = "ace" +**Output:** 3 +**Explanation:** The longest common subsequence is "ace" and its length is 3. + +**Example 2:** + +**Input:** text1 = "abc", text2 = "abc" +**Output:** 3 +**Explanation:** The longest common subsequence is "abc" and its length is 3. + +### Constraints + +- `1 <= text1.length, text2.length <= 1000` + - `text1` and `text2` consist of only lowercase English characters. + + + +--- + +## Approach + +To count the length of the longest common subsequence , will make 2 pointers pointing at the end of the two texts then will compare the characters at that index whether it is same or not then if not equal then decrement both otherwise return the max when decrementing both the pointers one by one. + +### Steps: + +1. Create a 2D table dp of size (m+1) x (n+1), where m and n are the lengths of the two input strings. Initialize all elements in the table to -1, which will serve as a flag to indicate that no result has been stored yet. + +2. Fill the Memoization Table + +Iterate through the table and fill it with the results of subproblems. For each cell dp[i][j], consider the following cases: + +If i or j is 0, the longest common subsequence is 0 (since one of the strings is empty). +If the current characters at positions i-1 and j-1 in the two strings are the same, then the longest common subsequence is one more than the longest common subsequence of the substrings up to i-1 and j-1. +Otherwise, the longest common subsequence is the maximum of the longest common subsequences of the substrings up to i-1 and j, and the substrings up to i and j-1. +3. Read the Memoization Table + +The value at dp[m][n] represents the length of the longest common subsequence. You can use this value to construct the actual subsequence by tracing back the table from dp[m][n] to dp[0][0]. + +4. Construct the Longest Common Subsequence + +To construct the longest common subsequence, start from the bottom-right corner of the table and move diagonally up-left if the current characters match, or move up or left if they don’t. When you reach a cell with a value of -1, stop and backtrack to the previous cell. + +### Solution + +#### Java Solution + +```java +import java.util.Arrays; + +class Solution { + + static final int maximum = 1000; + + static int lcs(String X, String Y, int m, int n, int dp[][]) { + if (m == 0 || n == 0) { + return 0; + } + + if (dp[m - 1][n - 1] != -1) { + return dp[m - 1][n - 1]; + } + + if (X.charAt(m - 1) == Y.charAt(n - 1)) { + + dp[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp); + + return dp[m - 1][n - 1]; + } else { + + dp[m - 1][n - 1] = Math.max(lcs(X, Y, m, n - 1, dp), + lcs(X, Y, m - 1, n, dp)); + + return dp[m - 1][n - 1]; + } + } +} + +``` +### C++ Solution + +```cpp +#include +using namespace std; + +const int maximum = 1000; +int lcs(string X, string Y, int m, int n, int dp[][maximum]) +{ + if (m == 0 || n == 0) + return 0; + + if (dp[m - 1][n - 1] != -1) + return dp[m - 1][n - 1]; + + if (X[m - 1] == Y[n - 1]) { + + dp[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp); + + return dp[m - 1][n - 1]; + } + else { + + dp[m - 1][n - 1] = max(lcs(X, Y, m, n - 1, dp), + lcs(X, Y, m - 1, n, dp)); + + return dp[m - 1][n - 1]; + } +} +``` +### Python Solution + +```python +maximum = 1000 +def lcs(X, Y, m, n, dp): + + if (m == 0 or n == 0): + return 0 + + if (dp[m - 1][n - 1] != -1): + return dp[m - 1][n - 1] + + if (X[m - 1] == Y[n - 1]): + + dp[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp) + + return dp[m - 1][n - 1] + + else : + + dp[m - 1][n - 1] = max(lcs(X, Y, m, n - 1, dp), + lcs(X, Y, m - 1, n, dp)) + + return dp[m - 1][n - 1] +``` + +### Complexity Analysis +**Time Complexity:** O(m * n) +>where n and m are lengths of the first and second string respectively. + +**Space Complexity:** O(n*m) +>Reason: We are using the extra space in the form of dp array. + +### References +**LeetCode Problem:** Longest Common Subsequence \ No newline at end of file diff --git a/solutions/lc-solutions/1100-1199/1161-maximum-level-sum-of-a-binary-tree.md b/solutions/lc-solutions/1100-1199/1161-maximum-level-sum-of-a-binary-tree.md new file mode 100644 index 0000000..21e09c8 --- /dev/null +++ b/solutions/lc-solutions/1100-1199/1161-maximum-level-sum-of-a-binary-tree.md @@ -0,0 +1,385 @@ +--- +id: maximum-level-sum-of-a-binary-tree +title: Maximum Level Sum of a Binary Tree +sidebar_label: 1161. Maximum Level Sum of a Binary Tree +tags: +- Tree +- Breadth-First Search +- Binary Tree +description: "This is a solution to the Maximum Level Sum of a Binary Tree problem on LeetCode." +--- + +## Problem Description +Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. + +Return the smallest level x such that the sum of all the values of nodes at level x is maximal. +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2019/05/03/capture.JPG) +``` +Input: root = [1,7,0,7,-8,null,null] +Output: 2 +Explanation: +Level 1 sum = 1. +Level 2 sum = 7 + 0 = 7. +Level 3 sum = 7 + -8 = -1. +So we return the level with the maximum sum which is level 2. +``` + +**Example 2:** +``` +Input: root = [989,null,10250,98693,-89388,null,null,null,-32127] +Output: 2 +``` + +### Constraints +- `The number of nodes in the tree is in the range [1, 10^4]` +- `-10^5 <= Node.val <= 10^5` + +## Solution for Maximum Level Sum of a Binary + +### Approach +The problem is to find the level in a binary tree that has the maximum sum of node values. To solve this, we use a breadth-first search (BFS) approach, which is well-suited for level-order traversal of a tree. BFS allows us to process nodes level by level, making it easy to calculate the sum of values at each level. + +#### Initial Checks and Setup: + +- If the root is null, return -1 as there are no levels in the tree. +- Initialize a queue and add the root node to it. This queue will help us traverse the tree level by level. +- Initialize variables to keep track of the maximum sum (maxSum), the level with the maximum sum (ans), and the current level (level). Set maxSum to a very small value to ensure any level sum will be larger initially. +#### Level-Order Traversal Using BFS: + +- Use a while loop to process nodes until the queue is empty. +- Increment the level variable at the start of each iteration of the while loop to represent the current level. +- Determine the number of nodes at the current level (size), which is the current length of the queue. +- Initialize a temporary sum variable (tempSum) to zero for storing the sum of values at the current level. +#### Processing Each Level: + +- Use a for loop to iterate over all nodes at the current level. The loop runs size times. +- For each node, dequeue it from the queue, add its value to tempSum, and enqueue its left and right children (if they exist). +#### Update Maximum Sum and Level: + +- After processing all nodes at the current level, compare tempSum with maxSum. +- If tempSum is greater than maxSum, update maxSum to tempSum and set ans to the current level. +#### Return the Result: + +- Once all levels have been processed and the queue is empty, return ans, which holds the level number with the maximum sum. + + + +#### Implementation + +```jsx live +function Solution() { +class TreeNode { + constructor(val = 0, left = null, right = null) { + this.val = val; + this.left = left; + this.right = right; + } +} + +var maxLevelSum = function(root) { + if (!root) return -1; + + let ans = -1; + let level = 0; + let maxSum = Number.MIN_SAFE_INTEGER; + const queue = [root]; + + while (queue.length > 0) { + level++; + const size = queue.length; + let tempSum = 0; + for (let i = 0; i < size; i++) { + const curr = queue.shift(); + tempSum += curr.val; + if (curr.left) queue.push(curr.left); + if (curr.right) queue.push(curr.right); + } + if (tempSum > maxSum) { + ans = level; + maxSum = tempSum; + } + } + + return ans; +}; +function constructTreeFromArray(array) { + if (!array.length) return null; + + let root = new TreeNode(array[0]); + let queue = [root]; + let i = 1; + + while (i < array.length) { + let currentNode = queue.shift(); + + if (array[i] !== null) { + currentNode.left = new TreeNode(array[i]); + queue.push(currentNode.left); + } + i++; + + if (i < array.length && array[i] !== null) { + currentNode.right = new TreeNode(array[i]); + queue.push(currentNode.right); + } + i++; + } + return root; +} +const array = [1,7,0,7,-8,null,null] +const root = constructTreeFromArray(array) +const input = root +const output = maxLevelSum(root) + return ( +
+

+ Input: {JSON.stringify(array)} +

+

+ Output: {output.toString()} +

+
+ ); +} +``` + +### Code in Different Languages + + + + + ```javascript + var maxLevelSum = function(root) { + if (!root) return -1; + + let ans = -1; + let level = 0; + let maxSum = Number.MIN_SAFE_INTEGER; + const queue = [root]; + + while (queue.length > 0) { + level++; + const size = queue.length; + let tempSum = 0; + for (let i = 0; i < size; i++) { + const curr = queue.shift(); + tempSum += curr.val; + if (curr.left) queue.push(curr.left); + if (curr.right) queue.push(curr.right); + } + if (tempSum > maxSum) { + ans = level; + maxSum = tempSum; + } + } + + return ans; +}; +``` + + + + ```typescript + class TreeNode { + val: number; + left: TreeNode | null; + right: TreeNode | null; + constructor(val: number = 0, left: TreeNode | null = null, right: TreeNode | null = null) { + this.val = val; + this.left = left; + this.right = right; + } +} + +function maxLevelSum(root: TreeNode | null): number { + if (!root) return -1; + + let ans = -1; + let level = 0; + let maxSum = Number.MIN_SAFE_INTEGER; + const queue: TreeNode[] = [root]; + + while (queue.length > 0) { + level++; + const size = queue.length; + let tempSum = 0; + for (let i = 0; i < size; i++) { + const curr = queue.shift()!; + tempSum += curr.val; + if (curr.left) queue.push(curr.left); + if (curr.right) queue.push(curr.right); + } + if (tempSum > maxSum) { + ans = level; + maxSum = tempSum; + } + } + + return ans; +} + + ``` + + + + ```python + # Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def maxLevelSum(self, root: TreeNode) -> int: + if not root: + return -1 + + from collections import deque + + ans = -1 + level = 0 + max_sum = float('-inf') + queue = deque([root]) + + while queue: + level += 1 + size = len(queue) + temp_sum = 0 + for _ in range(size): + curr = queue.popleft() + temp_sum += curr.val + if curr.left: + queue.append(curr.left) + if curr.right: + queue.append(curr.right) + if temp_sum > max_sum: + ans = level + max_sum = temp_sum + + return ans + + ``` + + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +import java.util.*; + +class Solution { + public int maxLevelSum(TreeNode root) { + if (root == null) return -1; + + int ans = -1; + int level = 0; + int maxSum = Integer.MIN_VALUE; + Queue queue = new LinkedList<>(); + queue.add(root); + + while (!queue.isEmpty()) { + level++; + int size = queue.size(); + int tempSum = 0; + for (int i = 0; i < size; i++) { + TreeNode curr = queue.poll(); + tempSum += curr.val; + if (curr.left != null) queue.add(curr.left); + if (curr.right != null) queue.add(curr.right); + } + if (tempSum > maxSum) { + ans = level; + maxSum = tempSum; + } + } + + return ans; + } +} + +``` + + + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxLevelSum(TreeNode* root) { + int ans=-1; + int level=0; + int sum=INT_MIN; + queue q; + if(!root) return ans; + + q.push(root); + + while(!q.empty()){ + + level++; + int size = q.size(); + int temp=0; + while(size--){ + TreeNode *curr = q.front(); + q.pop(); + temp+=curr->val; + + if(curr->left) q.push(curr->left); + if(curr->right) q.push(curr->right); + + } + if(temp>sum) + { + ans=level; + sum=temp; + } + } + + return ans; + } +}; +``` + + + +#### Complexity Analysis + ##### Time Complexity: $O(N)$ , because of tree traversal + + ##### Space Complexity: $O(1)$ +
+
+ +## References + +- **LeetCode Problem**: [Maximum Level Sum of a Binary Tree](https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/description/) + diff --git a/solutions/lc-solutions/1100-1199/1190-reverse-substrings-between-each-pair-of-parentheses.md b/solutions/lc-solutions/1100-1199/1190-reverse-substrings-between-each-pair-of-parentheses.md new file mode 100644 index 0000000..04e7cab --- /dev/null +++ b/solutions/lc-solutions/1100-1199/1190-reverse-substrings-between-each-pair-of-parentheses.md @@ -0,0 +1,201 @@ +--- +id: reverse-substrings-between-each-pair-of-parentheses +title: 1190. Reverse Substrings Between Each Pair of Parentheses +sidebar_label: 1190. Reverse Substrings Between Each Pair of Parentheses +tags: +- String +- Stack + +description: "This is a solution to the 1190. Reverse Substrings Between Each Pair of Parentheses problem on LeetCode." +--- + +## Problem Description +You are given a string s that consists of lower case English letters and brackets. + +Reverse the strings in each pair of matching parentheses, starting from the innermost one. + +Your result should not contain any brackets. + + ### Examples +**Example 1:** +``` +Input: s = "(u(love)i)" +Output: "iloveu" +Explanation: The substring "love" is reversed first, then the whole string is reversed. +``` + +### Constraints +- `1 <= s.length <= 2000` +- `s only contains lower case English characters and parentheses.` +- `It is guaranteed that all parentheses are balanced.` +## Solution for 1190. Reverse Substrings Between Each Pair of Parentheses + + + + + #### Implementation + ```jsx live + function Solution(arr) { + var reverseParentheses = function(s) { + let st = []; + let arr = s.split(''); + + for (let i = 0; i < arr.length; i++) { + if (arr[i] === '(') { + st.push(i); + } else if (arr[i] === ')') { + let top = st.pop(); + reverse(arr, top + 1, i - 1); + } + } + + let ans = ''; + for (let c of arr) { + if (/[a-z]/.test(c)) { + ans += c; + } + } + return ans; + }; + + function reverse(arr, left, right) { + while (left < right) { + let temp = arr[left]; + arr[left] = arr[right]; + arr[right] = temp; + left++; + right--; + } + } + + const input = "(u(love)i)" + const output = reverseParentheses(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n^2) $ + - Space Complexity: $ O(n)$ + + ## Code in Different Languages + + + + ```python + class Solution: + def reverseParentheses(self, s: str) -> str: + st = [] + s = list(s) + + for i in range(len(s)): + if s[i] == '(': + st.append(i) + elif s[i] == ')': + top = st.pop() + s[top + 1:i] = s[top + 1:i][::-1] + + return ''.join(c for c in s if c.isalpha()) + + ``` + + + + + ```java + import java.util.Stack; + +public class Solution { + public String reverseParentheses(String s) { + Stack st = new Stack<>(); + char[] charArray = s.toCharArray(); + + for (int i = 0; i < charArray.length; i++) { + if (charArray[i] == '(') { + st.push(i); + } else if (charArray[i] == ')') { + int top = st.pop(); + reverse(charArray, top + 1, i - 1); + } + } + + StringBuilder ans = new StringBuilder(); + for (char c : charArray) { + if (Character.isLetter(c)) { + ans.append(c); + } + } + return ans.toString(); + } + + private void reverse(char[] array, int left, int right) { + while (left < right) { + char temp = array[left]; + array[left] = array[right]; + array[right] = temp; + left++; + right--; + } + } +} + + ``` + + + + + + ```cpp + class Solution { +public: + string reverseParentheses(string s) { + stackst; + for(int i=0;i='a' && s[i]<='z') + { + ans+=s[i]; + } + } + return ans; + } +}; +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [ 1190. Reverse Substrings Between Each Pair of Parentheses](https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/) + diff --git a/solutions/lc-solutions/1100-1199/_category_.json b/solutions/lc-solutions/1100-1199/_category_.json new file mode 100644 index 0000000..3f7e61c --- /dev/null +++ b/solutions/lc-solutions/1100-1199/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "1100-1199", + "position": 13, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (1100 - 1199)" + } +} diff --git a/solutions/lc-solutions/1200-1299/1200-minimum-absolute-difference.md b/solutions/lc-solutions/1200-1299/1200-minimum-absolute-difference.md new file mode 100644 index 0000000..7d08842 --- /dev/null +++ b/solutions/lc-solutions/1200-1299/1200-minimum-absolute-difference.md @@ -0,0 +1,122 @@ +--- +id: minimum-absolute-difference +title: Minimum Absolute Difference +sidebar_label: 1200. Minimum Absolute Difference +tags: +- Array +- Sorting +description: "Solution to Leetcode 1200. Minimum Absolute Difference" +--- + +## Problem Description + +Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. + +Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows + +a, b are from arr +a < b +b - a equals to the minimum absolute difference of any two elements in arr + +### Examples + +**Example 1:** + +``` +Input: arr = [4,2,1,3] +Output: [[1,2],[2,3],[3,4]] +Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. +``` + +**Example 2:** + +``` +Input: arr = [1,3,6,10,15] +Output: [[1,3]] + +``` + + + +### Constraints +- `2 <= arr.length <= 10^5` +- `-10^6 <= arr[i] <= 10^6` + +### Approach +Counting Sort + +We can use counting sort to reduce the time complexity of sorting used in above appraoch. The counting sort method can be applied here becase the range of elements are small enough to be fitted into an array. + +But we cannot directly apply counting sort becase the range also includes negative elements and thus we must remap the range from [a...b] to [0...(b-a)] = [0...R]. This can be done by simply subtracting minimum element each element of input array. + +Then, since each element is distinct, we can simply use boolean array seen to keep track of each element present in the range [0...R]. Now, we can use this as a sorted array and compare between adjacent element, i.e, previous element which was present in seen and current element present in seen. The rest of the logic of updating MAB or resetting ans if smaller difference if found is the same as above. We just need to take care that we reset the shift while pushing elements into final ans. + +### Complexity + +Time complexity: $O(N + R)$ +Space complexity: $O(R)$ + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp +class Solution { +public: + vector> minimumAbsDifference(vector& A) { + auto [mn, mx] = minmax_element(begin(A), end(A)); // returns iterator to min and max element in A + int R = *mx - *mn + 1, shift = -*mn, minDiff = INT_MAX, curDiff, prevElement = -R; + vector> ans; + vector seen(R); // used to denote if i is present or not over the remapped range [0, R] + for(auto c : A) seen[c + shift] = true; // mark each element of A as seen after applying shift + for(int i = 0; i < R; i++) + if(seen[i]) { + int a = prevElement - shift, b = i - shift; // remove the applied shift while pushing into ans array + curDiff = b - a; + if(curDiff == minDiff) ans.push_back({a, b}); + else if(curDiff < minDiff) { + minDiff = curDiff; + ans = {{a, b}}; + } + prevElement = i; // update previous element so we only compare adjacent elements of sorted A + } + + return ans; + } +}; + ``` + +#### PYTHON + +```python +class Solution: + def minimumAbsDifference(self, A): + mn, mx = min(A), max(A) + R, shift, min_diff, prev_element = mx-mn+1, -mn, 10**10, -10**10 + ans, seen = [], [False]*R + for c in A: + seen[c + shift] = True + for i in range(R): + if seen[i]: + a, b = prev_element - shift, i - shift + cur_diff = b-a + if cur_diff == min_diff: ans.append([a, b]) + elif cur_diff < min_diff: + min_diff, ans = cur_diff, [[a, b]] + prev_element = i + return ans +``` + + + +### Complexity Analysis + +- Time Complexity: $O(N+R)$ + +- Space Complexity: $O(R)$ + +### References + +- **LeetCode Problem**: Minimum Absolute Difference \ No newline at end of file diff --git a/solutions/lc-solutions/1200-1299/1201-ugly-number-III.md b/solutions/lc-solutions/1200-1299/1201-ugly-number-III.md new file mode 100644 index 0000000..b2f5e22 --- /dev/null +++ b/solutions/lc-solutions/1200-1299/1201-ugly-number-III.md @@ -0,0 +1,147 @@ +--- +id: ugly-number-III +title: Ugly Number III +sidebar_label: 1201. Ugly Number III +tags: +- Math +- Binary Search +- Combinatorics +- Number Theory +description: "Solution to Leetcode 1201. Ugly Number III" +--- + +## Problem Description + +An ugly number is a positive integer that is divisible by a, b, or c. + +Given four integers n, a, b, and c, return the nth ugly number. + +### Examples + +**Example 1:** + +``` +Input: n = 3, a = 2, b = 3, c = 5 +Output: 4 +Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4. +``` + +**Example 2:** + +``` +Input: n = 4, a = 2, b = 3, c = 4 +Output: 6 +Explanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6. + +``` + + + +### Constraints +- `1 <= n, a, b, c <= 10^9` +- `1 <= a * b * c <= 10^18` + +### Approach +The idea is, we search for the smallest K such that the number of numbers divisible by a or b or c in [1, K] is exactly N. + +We know the number of numbers divisible by x in [1, K] is K div x (or K // x, in Python). +The number of numbers divisible by a or b or c in [1, K]: += #(divisible by a) + #(divisible by b) + #(divisible by c) - #(divisible by a, b) - #(divisible by (b, c)) - #(divisible by a, c) + #(divisible by a, b, c) += (K//a + K// b + K//c) - (K//lcm(a,b) + K//lcm(b, c) + K//lcm(c, a)) + K//lcm(a, b, c) + +where lcm is lowest common multiplier of the inside numeric arguments. + +Time Complexity: Note that the time complexity of computing lcm or gcd is O(log N). Thus, the overall time complexity is O((logN)^2) + +### Complexity + +Time complexity: $O((logN)^2)$ +Space complexity: $O(1)$ + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp +typedef long long ll; +#define MAX_ANS 2e9 + +class Solution { +public: + int nthUglyNumber(int n, int a, int b, int c) { + int left = 0, right = MAX_ANS, result = 0; + while (left <= right) { + int mid = left + (right - left) / 2; + if (count(mid, a, b, c) >= n) { + result = mid; + right = mid - 1; + } else { + left = mid + 1; + } + } + return result; + } + int count(ll num, ll a, ll b, ll c) { + return (int)(num / a + num / b + num / c + - num / lcm(a, b) + - num / lcm(b, c) + - num / lcm(a, c) + + num / (lcm(a, lcm(b, c)))); + } + ll gcd(ll a, ll b) { + if (a == 0) return b; + return gcd(b % a, a); + } + ll lcm(ll a, ll b) { + return a * b / gcd(a, b); + } +}; + ``` + +#### PYTHON + +```python + def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int: + def lcm(a, b): + prod = a*b + if a < b: + a, b = b, a + while b > 0: + a = a % b + a, b = b, a + return prod//a + def count(k): + #how many numbers divisible by a or b or c in [1, k] + na = k // a + nb = k // b + nc = k // c + nab = k // lcm(a, b) + nac = k // lcm(a, c) + nbc = k // lcm(b, c) + nabc = k // lcm(lcm(a, b), c) + return na + nb + nc - nab - nac - nbc + nabc + l, r = 0, 2*10**9 + while l <= r: + mid = l + (r - l)//2 + if count(mid) >= n: + if count(mid) == n and (mid % a == 0 or mid % b == 0 or mid % c == 0): + return mid + r = mid - 1 + else: + l = mid + 1 + return l +``` + + + +### Complexity Analysis + +- Time Complexity: $O((logN)^2)$ + +- Space Complexity: $O(1)$ + +### References + +- **LeetCode Problem**: Ugly Number III \ No newline at end of file diff --git a/solutions/lc-solutions/1200-1299/1207-unique-number-of-occurrences.md b/solutions/lc-solutions/1200-1299/1207-unique-number-of-occurrences.md new file mode 100644 index 0000000..ddeb9b5 --- /dev/null +++ b/solutions/lc-solutions/1200-1299/1207-unique-number-of-occurrences.md @@ -0,0 +1,116 @@ +--- +id: unique-number-of-occurrences +title: Unique Number of Occurrences +sidebar_label: 1207. Unique Number of Occurrences +tags: +- Array +- Hash Table +description: "Solution to Leetcode 1207. Unique Number of Occurrences" +--- + +## Problem Description + +Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise. + +### Examples + +**Example 1:** + +``` +Input: arr = [1,2,2,1,1,3] +Output: true +Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. +``` + +**Example 2:** + +``` +Input: arr = [1,2] +Output: false +``` + + + +### Constraints +- `1 <= arr.length <= 1000` +- `-1000 <= arr[i] <= 1000` + +### Approach +1. Sort the input array arr to group identical elements together. +2. Traverse the sorted array, counting occurrences of each element. +3. Store the counts in a separate vector v. +4. Sort the vector v to make it easier to check for duplicates. +5. Iterate through v and check if adjacent elements are equal. If so, return false. +6. If the loop completes, it means all counts are unique, and the function returns true. + +### Complexity + +Time complexity: $O(n)$ +Space complexity: $O(n)$ + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp +class Solution { +public: + bool uniqueOccurrences(vector& arr) { + unordered_mapfreq; + for(auto x: arr){ + freq[x]++; + } + unordered_sets; + for(auto x: freq){ + s.insert(x.second); + } + return freq.size()==s.size(); + } +}; + ``` + +#### JAVA + +```JAVA +class Solution { + public boolean uniqueOccurrences(int[] arr) { + Map freq = new HashMap<>(); + for (int x : arr) { + freq.put(x, freq.getOrDefault(x, 0) + 1); + } + + Set s = new HashSet<>(); + for (int x : freq.values()) { + s.add(x); + } + + return freq.size() == s.size(); + } +} +``` + +#### PYTHON + +```python +class Solution: + def uniqueOccurrences(self, arr: List[int]) -> bool: + freq = {} + for x in arr: + freq[x] = freq.get(x, 0) + 1 + + return len(freq) == len(set(freq.values())) +``` + + + +### Complexity Analysis + +- Time Complexity: $O(n)$ + +- Space Complexity: $O(n)$ + +### References + +- **LeetCode Problem**: Unique Number of Occurrences \ No newline at end of file diff --git a/solutions/lc-solutions/1200-1299/1209-remove-all-adjacent-duplicates-in-string-II.md b/solutions/lc-solutions/1200-1299/1209-remove-all-adjacent-duplicates-in-string-II.md new file mode 100644 index 0000000..6c1ca8b --- /dev/null +++ b/solutions/lc-solutions/1200-1299/1209-remove-all-adjacent-duplicates-in-string-II.md @@ -0,0 +1,119 @@ +--- +id: remove-all-adjacent-duplicates-in-string-II +title: Remove All Adjacent Duplicates in String II +sidebar_label: 1209. Remove All Adjacent Duplicates in String II +tags: + - String + - Stack +description: "Solution to Leetcode 1209. Remove All Adjacent Duplicates in String II" +--- + +## Problem Description + +You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together. + +We repeatedly make k duplicate removals on s until we no longer can. + +Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique. + +### Examples + +**Example 1:** + +``` +Input: s = "abcd", k = 2 +Output: "abcd" +Explanation: There's nothing to delete. +``` + +**Example 2:** + +``` +Input: s = "deeedbbcccbdaa", k = 3 +Output: "aa" +Explanation: +First delete "eee" and "ccc", get "ddbbbdaa" +Then delete "bbb", get "dddaa" +Finally delete "ddd", get "aa" +``` + +### Constraints + +- `1 <= s.length <= 10^5` +- `2 <= k <= 10^4` + +### Approach + +1. Save the character c and its count to the stack. +2. If the next character c is same as the last one, increment the count. +3. Otherwise push a pair (c, 1) into the stack. +4. I used a dummy element ('#', 0) to avoid empty stack. + +### Complexity + +Time complexity: $O(n)$ +Space complexity: $O(n)$ + +### Solution + +#### Code in Different Languages + +#### C++ + +```cpp + string removeDuplicates(string s, int k) { + vector> stack = {{0, '#'}}; + for (char c: s) { + if (stack.back().second != c) { + stack.push_back({1, c}); + } else if (++stack.back().first == k) + stack.pop_back(); + } + string res; + for (auto & p : stack) { + res.append(p.first, p.second); + } + return res; + } +``` + +#### JAVA + +```java + public String removeDuplicates(String s, int k) { + int[] count = new int[s.length()]; + StringBuilder sb = new StringBuilder(); + for(char c : s.toCharArray()) { + sb.append(c); + int last = sb.length()-1; + count[last] = 1 + (last > 0 && sb.charAt(last) == sb.charAt(last-1) ? count[last-1] : 0); + if(count[last] >= k) sb.delete(sb.length()-k, sb.length()); + } + return sb.toString(); + } +``` + +#### PYTHON + +```python + def removeDuplicates(self, s, k): + stack = [['#', 0]] + for c in s: + if stack[-1][0] == c: + stack[-1][1] += 1 + if stack[-1][1] == k: + stack.pop() + else: + stack.append([c, 1]) + return ''.join(c * k for c, k in stack) +``` + +### Complexity Analysis + +- Time Complexity: $O(n)$ + +- Space Complexity: $O(n)$ + +### References + +- **LeetCode Problem**: Remove All Adjacent Duplicates in String II diff --git a/solutions/lc-solutions/1200-1299/1221-split-a-string-in-balanced-strings.md b/solutions/lc-solutions/1200-1299/1221-split-a-string-in-balanced-strings.md new file mode 100644 index 0000000..0dc4c63 --- /dev/null +++ b/solutions/lc-solutions/1200-1299/1221-split-a-string-in-balanced-strings.md @@ -0,0 +1,167 @@ +--- +id: split-a-string-in-balanced-strings +title: Split a String in balanced Strings +sidebar_label: 1221. Split a String in Balanced Strings +tags: +- String +- Greedy +- Counting +description: "Solution to Leetcode 1221. Split a String in Balanced Strings" +--- + +## Problem Description + +**Balanced** strings are those that have an equal quantity of `'L'` and `'R'` characters. + +Given a balanced **string** `s`, split it into some number of substrings such that: + +- Each substring is balanced. + +Return the **maximum** number of balanced strings you can obtain. + +### Examples + +**Example 1:** + +``` +Input: s = "RLRRLLRLRL" +Output: 4 +Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'. +``` + +**Example 2:** + +``` +Input: s = "RLRRRLLRLL" +Output: 2 +Explanation: s can be split into "RL", "RRRLLRLL", each substring contains same number of 'L' and 'R'. +Note that s cannot be split into "RL", "RR", "RL", "LR", "LL", because the 2nd and 5th substrings are not balanced. + +``` + +**Example 3:** + +``` +Input: s = "LLLLRRRR" +Output: 1 +Explanation: s can be split into "LLLLRRRR". + + +``` + + + +### Constraints +- `2 <= s.length <= 1000` +- `s[i] is either 'L' or 'R'.` +- `s is a balanced string.` + +### Approach + +The provided code solves the problem of splitting a string into the maximum number of balanced substrings. A balanced substring is defined as a substring that has an equal number of 'L' and 'R' characters. Here's a step-by-step approach to how the code works: + +### Steps: + +1. **Initialize Counters**: + - `count` is initialized to 0 and will be used to count the number of balanced substrings. + - `ch` is initialized to 0 and will be used to keep track of the balance between 'R' and 'L' characters. + +2. **Iterate Through the String**: + - The code loops through each character of the input string `s` using a `for` loop. + +3. **Update Balance Counter**: + - Inside the loop, for each character: + - If the character is 'R', increment the `ch` counter. + - If the character is 'L', decrement the `ch` counter. + - This way, `ch` keeps track of the balance: + - Positive values of `ch` indicate more 'R's than 'L's. + - Negative values of `ch` indicate more 'L's than 'R's. + - A `ch` value of 0 indicates an equal number of 'R' and 'L' characters up to that point. + +4. **Check for Balanced Substring**: + - After updating `ch`, the code checks if `ch` is 0. + - If `ch` is 0, it means that the substring from the last balanced point (or from the start if it's the first balanced substring) to the current position is balanced. + - Increment the `count` counter each time a balanced substring is found. + +5. **Return the Result**: + - After the loop completes, `count` will hold the total number of balanced substrings in the input string `s`. + - The function returns the value of `count`. + +### Example Walkthrough +Let's consider the string `s = "RLRRLLRLRL"`: + +- Initialize: `count = 0`, `ch = 0` +- Loop through each character: + - 'R' -> `ch = 1` + - 'L' -> `ch = 0` (balanced substring found, `count = 1`) + - 'R' -> `ch = 1` + - 'R' -> `ch = 2` + - 'L' -> `ch = 1` + - 'L' -> `ch = 0` (balanced substring found, `count = 2`) + - 'R' -> `ch = 1` + - 'L' -> `ch = 0` (balanced substring found, `count = 3`) + - 'R' -> `ch = 1` + - 'L' -> `ch = 0` (balanced substring found, `count = 4`) + +The final `count` is 4, which is the number of balanced substrings in the input string. + + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp +class Solution { +public: + int balancedStringSplit(string s) { + int count = 0; + int ch = 0; + for (char c : s) { + if (c == 'R') { + ch++; + } else { + ch--; + } + if (ch == 0) { + count++; + } + } + return count; + } +}; + + ``` + +#### PYTHON + +```python + def balancedStringSplit(s: str) -> int: + count = 0 + ch = 0 + for char in s: + if char == 'R': + ch += 1 + else: + ch -= 1 + if ch == 0: + count += 1 + return count + +``` + + + +### Complexity Analysis + +- **Time Complexity**: O(n) + - The algorithm iterates through each character in the input string exactly once, resulting in a linear time complexity relative to the length of the string \( n \). + +- **Space Complexity**: O(1) + - The algorithm uses a fixed amount of extra space (for the `count` and `ch` variables), regardless of the input size, resulting in constant space complexity. + + +### References + +- **LeetCode Problem**: Split a String in balanced Strings diff --git a/solutions/lc-solutions/1200-1299/1232-check-if-it-is-a-straight-line.md b/solutions/lc-solutions/1200-1299/1232-check-if-it-is-a-straight-line.md new file mode 100644 index 0000000..dfefde5 --- /dev/null +++ b/solutions/lc-solutions/1200-1299/1232-check-if-it-is-a-straight-line.md @@ -0,0 +1,189 @@ +--- +id: check-if-it-is-a-straight-line +title: 1232. Check If It Is a Straight Line +sidebar_label: 1232. Check If It Is a Straight Line +tags: +- Array +- Maths +- Geometry + +description: "This is a solution to the Check If It Is a Straight Line problem on LeetCode." +--- + +## Problem Description +You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. + +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2019/10/15/untitled-diagram-2.jpg) +``` +Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] +Output: true +``` + +**Example 2:** +![image](https://assets.leetcode.com/uploads/2019/10/09/untitled-diagram-1.jpg) +``` +Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] +Output: false +``` + + +### Constraints +- `2 <= coordinates.length <= 1000` +- `coordinates[i].length == 2` +- `-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4` +- `coordinates contains no duplicate point.` + +## Solution for 1232. Check If It Is a Straight Line Problem +### Approach +1. **Calculate the Initial Slope**: + - Compute the difference in the `y` values (`diff_y`) and the difference in the `x` values (`diff_x`) between the first two points. + +2. **Iterate through the Points**: + - For each subsequent point, compute the product of the initial slope differences with the current point's differences. + - If at any point the calculated products do not match, the points do not lie on a straight line. + +3. **Return the Result**: + - If all points satisfy the condition, return `true`. Otherwise, return `false`. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function checkStraightLine(coordinates) { + const diff_y = (coordinates[1][1] - coordinates[0][1]); + const diff_x = (coordinates[1][0] - coordinates[0][0]); + for (let i = 2; i < coordinates.length; i++) { + if (diff_y * (coordinates[i][0] - coordinates[i-1][0]) !== diff_x * (coordinates[i][1] - coordinates[i-1][1])) { + return false; + } + } + return true; + } + const input = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] + const output = checkStraightLine(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(N) $ + - Space Complexity: $ O(1)$ + + ## Code in Different Languages + + + + ```javascript + function checkStraightLine(coordinates) { + const diff_y = (coordinates[1][1] - coordinates[0][1]); + const diff_x = (coordinates[1][0] - coordinates[0][0]); + for (let i = 2; i < coordinates.length; i++) { + if (diff_y * (coordinates[i][0] - coordinates[i-1][0]) !== diff_x * (coordinates[i][1] - coordinates[i-1][1])) { + return false; + } + } + return true; + } + ``` + + + + + ```typescript + class Solution { + checkStraightLine(coordinates: number[][]): boolean { + const diff_y = (coordinates[1][1] - coordinates[0][1]); + const diff_x = (coordinates[1][0] - coordinates[0][0]); + for (let i = 2; i < coordinates.length; i++) { + if (diff_y * (coordinates[i][0] - coordinates[i-1][0]) !== diff_x * (coordinates[i][1] - coordinates[i-1][1])) { + return false; + } + } + return true; + } +} + + ``` + + + + ```python + class Solution: + def checkStraightLine(self, coordinates: List[List[int]]) -> bool: + diff_y = (coordinates[1][1] - coordinates[0][1]) + diff_x = (coordinates[1][0] - coordinates[0][0]) + for i in range(2, len(coordinates)): + if diff_y * (coordinates[i][0] - coordinates[i-1][0]) != diff_x * (coordinates[i][1] - coordinates[i-1][1]): + return False + return True + + ``` + + + + + ```java + + import java.util.List; + +class Solution { + public boolean checkStraightLine(List coordinates) { + int diff_y = (coordinates.get(1)[1] - coordinates.get(0)[1]); + int diff_x = (coordinates.get(1)[0] - coordinates.get(0)[0]); + for (int i = 2; i < coordinates.size(); i++) { + if (diff_y * (coordinates.get(i)[0] - coordinates.get(i-1)[0]) != diff_x * (coordinates.get(i)[1] - coordinates.get(i-1)[1])) { + return false; + } + } + return true; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + bool checkStraightLine(vector>& coordinates) { + int diff_y = (coordinates[1][1] - coordinates[0][1]); + int diff_x = (coordinates[1][0] - coordinates[0][0]); + for(int i=2; i + + +
+
+ +## References + +- **LeetCode Problem**: [ Check If It Is a Straight Line](https://leetcode.com/problems/check-if-it-is-a-straight-line/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/check-if-it-is-a-straight-line/) + diff --git a/solutions/lc-solutions/1200-1299/1248-count-number-of-nice-subarrays.md b/solutions/lc-solutions/1200-1299/1248-count-number-of-nice-subarrays.md new file mode 100644 index 0000000..769bb86 --- /dev/null +++ b/solutions/lc-solutions/1200-1299/1248-count-number-of-nice-subarrays.md @@ -0,0 +1,284 @@ +--- +id: count-number-of-nice-subarrays +title: 1248. Count Number of Nice Subarrays +sidebar_label: 1248. Count Number of Nice Subarrays +tags: +- Array +- Hash Table +- Counting + +description: "This is a solution to the Count Number of Nice Subarrays problem on LeetCode." +--- + +## Problem Description +Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it. + +Return the number of nice sub-arrays. + +### Examples + +**Example 1:** +``` +Input: nums = [1,1,2,1,1], k = 3 +Output: 2 +Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1]. +``` + +**Example 2:** + +``` +Input: nums = [2,4,6], k = 1 +Output: 0 +Explanation: There are no odd numbers in the array. +``` + + +### Constraints +- `1 <= nums.length <= 50000` +- `1 <= nums[i] <= 10^5` +- `1 <= k <= nums.length` + +## Solution for 1781. Sum of Beauty of All Substrings Problem +### Approach + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function numberOfSubarrays(nums, k) { + let i = 0, j = 0, t = 0, odd = 0, total = 0; + const n = nums.length; + + while (j < n) { + if (nums[j] % 2 === 1) { + odd++; + } + + while (i <= j && odd > k) { + if (nums[i] % 2 === 1) { + odd--; + } + i++; + } + + if (odd === k) { + t = i; + while (t <= j && nums[t] % 2 === 0) { + t++; + } + total += (t - i + 1); + } + j++; + } + return total; + } + const input = [1,1,2,1,1] + const k = 3 + const output = numberOfSubarrays(input ,k) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(N) $ + - Space Complexity: $ O(1)$ + + ## Code in Different Languages + + + + ```javascript + numberOfSubarrays(nums, k) { + let i = 0, j = 0, t = 0, odd = 0, total = 0; + const n = nums.length; + + while (j < n) { + if (nums[j] % 2 === 1) { + odd++; + } + + while (i <= j && odd > k) { + if (nums[i] % 2 === 1) { + odd--; + } + i++; + } + + if (odd === k) { + t = i; + while (t <= j && nums[t] % 2 === 0) { + t++; + } + total += (t - i + 1); + } + j++; + } + return total; + } + ``` + + + + + ```typescript + class Solution { + numberOfSubarrays(nums: number[], k: number): number { + let i = 0, j = 0, t = 0, odd = 0, total = 0; + const n = nums.length; + + while (j < n) { + if (nums[j] % 2 === 1) { + odd++; + } + + while (i <= j && odd > k) { + if (nums[i] % 2 === 1) { + odd--; + } + i++; + } + + if (odd === k) { + t = i; + while (t <= j && nums[t] % 2 === 0) { + t++; + } + total += (t - i + 1); + } + j++; + } + return total; + } +} + + ``` + + + + ```python + class Solution: + def numberOfSubarrays(self, nums: List[int], k: int) -> int: + i = 0 + j = 0 + t = 0 + odd = 0 + total = 0 + n = len(nums) + + while j < n: + if nums[j] % 2 == 1: + odd += 1 + + while i <= j and odd > k: + if nums[i] % 2 == 1: + odd -= 1 + i += 1 + + if odd == k: + t = i + while t <= j and nums[t] % 2 == 0: + t += 1 + total += (t - i + 1) + j += 1 + + return total + + ``` + + + + + ```java + public class Solution { + public int numberOfSubarrays(int[] nums, int k) { + int i = 0, j = 0, t = 0, odd = 0, total = 0; + int n = nums.length; + + while (j < n) { + if (nums[j] % 2 == 1) { + odd++; + } + + while (i <= j && odd > k) { + if (nums[i] % 2 == 1) { + odd--; + } + i++; + } + + if (odd == k) { + t = i; + while (t <= j && nums[t] % 2 == 0) { + t++; + } + total += (t - i + 1); + } + j++; + } + return total; + } +} + + ``` + + + + + ```cpp +class Solution { +public: + int numberOfSubarrays(vector& nums, int k) { + int i = 0, j = 0, t = 0, odd = 0, total = 0; + int n = nums.size(); + + while (j < n) { + if (nums[j] % 2 == 1) { + odd++; + } + + while (i <= j && odd > k) { + if (nums[i] % 2 == 1) { + odd--; + } + i++; + } + + if (odd == k) { + t = i; + while (t <= j && nums[t] % 2 == 0) { + t++; + } + total += (t - i + 1); + } + j++; + } + return total; + } +}; + + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [ Count Number of Nice Subarrays](https://leetcode.com/problems/count-number-of-nice-subarrays/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/count-number-of-nice-subarrays/description/) + diff --git a/solutions/lc-solutions/1200-1299/1288-remove-covered-intervals.md b/solutions/lc-solutions/1200-1299/1288-remove-covered-intervals.md new file mode 100644 index 0000000..4e18614 --- /dev/null +++ b/solutions/lc-solutions/1200-1299/1288-remove-covered-intervals.md @@ -0,0 +1,144 @@ +--- +id: remove-covered-intervals +title: 1288. Remove Covered Intervals +sidebar_label: 1288. Remove Covered Intervals +tags: +- Array +- Intervals + +description: "This is a solution to the 1288. Remove Covered Intervals problem on LeetCode." +--- + +## Problem Description +Given an array intervals where intervals[i] = [li, ri] represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list. + +`The interval `[a, b)` is covered by the interval `[c, d) `if and only if c <= a and b <= d.` + +Return the number of remaining intervals. + ### Examples +**Example 1:** +``` +Input: intervals = [[1,4],[3,6],[2,8]] +Output: 2 +Explanation: Interval [3,6] is covered by [2,8], therefore it is removed. +``` + +### Constraints +- `1 <= intervals.length <= 10^3` +## Solution for 1288. Remove Covered Intervals + + + + + #### Implementation + ```jsx live + function Solution(arr) { + var removeCoveredIntervals = function(intervals) { + let cnt = 0; + for (let i = 0; i < intervals.length; i++) { + for (let j = 0; j < intervals.length; j++) { + if (i !== j && intervals[j][0] <= intervals[i][0] && intervals[i][1] <= intervals[j][1]) { + cnt++; + break; + } + } + } + return intervals.length - cnt; +}; + + const input = [[1,4],[3,6],[2,8]] + const output = removeCoveredIntervals(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n^2) $ + - Space Complexity: $ O(1)$ + + ## Code in Different Languages + + + + ```python + class Solution: + def removeCoveredIntervals(self, intervals): + cnt = 0 + for i in range(len(intervals)): + for j in range(len(intervals)): + if i != j and intervals[j][0] <= intervals[i][0] and intervals[i][1] <= intervals[j][1]: + cnt += 1 + break + return len(intervals) - cnt + + ``` + + + + + ```java +import java.util.List; + +public class Solution { + public int removeCoveredIntervals(List> intervals) { + int cnt = 0; + for (int i = 0; i < intervals.size(); i++) { + for (int j = 0; j < intervals.size(); j++) { + if (i != j && intervals.get(j).get(0) <= intervals.get(i).get(0) && intervals.get(i).get(1) <= intervals.get(j).get(1)) { + cnt++; + break; + } + } + } + return intervals.size() - cnt; + } +} + + ``` + + + + + + ```cpp + class Solution { +public: + int removeCoveredIntervals(vector>& intervals) { + int cnt=0; + for(int i=0;i + + +
+
+ +## References + +- **LeetCode Problem**: [1288. Remove Covered Intervals](https://leetcode.com/problems/remove-covered-intervals/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/remove-covered-intervals/) + diff --git a/solutions/lc-solutions/1200-1299/1295-Find-Numbers-With-Even-Number-Of-Digits.md b/solutions/lc-solutions/1200-1299/1295-Find-Numbers-With-Even-Number-Of-Digits.md new file mode 100644 index 0000000..d0799dd --- /dev/null +++ b/solutions/lc-solutions/1200-1299/1295-Find-Numbers-With-Even-Number-Of-Digits.md @@ -0,0 +1,187 @@ +--- +id: find-numbers-with-even-number-of-digits +title: Find Numbers with Even Number of Digits +sidebar_label: 1295-Find-Numbers-With-Even-Number-Of-Digits +tags: + - Array +--- + +## Problem Description +Given an array `nums` of integers, return how many of them contain an even number of digits. + + +### Example + +**Example 1:** + + +``` +Input: nums = [12,345,2,6,7896] +Output: 2 +Explanation: +12 contains 2 digits (even number of digits). +345 contains 3 digits (odd number of digits). +2 contains 1 digit (odd number of digits). +6 contains 1 digit (odd number of digits). +7896 contains 4 digits (even number of digits). +Therefore only 12 and 7896 contain an even number of digits. +``` +**Example 2:** +``` +Input: nums = [555,901,482,1771] +Output: 1 +Explanation: +Only 1771 contains an even number of digits. +``` +### Constraints + +- `1 <= nums[i] <= 10^5` + +## Solution Approach + +### Intuition: + +To efficiently determine Find Numbers with Even Number of Digits +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + +class Solution { + findNumbers(nums) { + let rem = 0, cnt1 = 0, cnt2 = 0; + const n = nums.length; + for(let i=0; i0){ + rem = num%10; + cnt1++; + num=Math.floor(num/10); + } + if(cnt1%2==0) cnt2++; + } + return cnt2; + } +} + + + + + ``` + + + + + ```typescript + class Solution { + findNumbers(nums: number[]): number { + let rem = 0, cnt1 = 0, cnt2 = 0; + const n = nums.length; + for(let i=0; i0){ + rem = num%10; + cnt1++; + num=Math.floor(num/10); + } + if(cnt1%2==0) cnt2++; + } + return cnt2; + } +} + + + + ``` + + + + + ```python + class Solution: + def findNumbers(self, nums: List[int]) -> int: + rem = 0 + cnt1 = 0 + cnt2 = 0 + n = len(nums) + for i in range(n): + cnt1 = 0 + num = nums[i] + while num>0: + rem = num%10 + cnt1+=1 + num=num//10 + if cnt1%2==0: + cnt2+=1 + return cnt2 + + + + + ``` + + + + + ```java + public class Solution { + public int findNumbers(int[] nums) { + int rem = 0, cnt1 = 0, cnt2 = 0; + int n = nums.length; + for(int i=0; i0){ + rem = num%10; + cnt1++; + num=num/10; + } + if(cnt1%2==0) cnt2++; + } + return cnt2; + } +} + + + + ``` + + + + + ```cpp +class Solution { +public: + int findNumbers(vector& nums) { + int rem = 0, cnt1 = 0, cnt2 = 0; + int n = nums.size(); + for(int i=0; i0){ + rem = nums[i]%10; + cnt1++; + nums[i]/=10; + + } + if(cnt1%2==0) cnt2++; + } + + return cnt2; + } +}; +``` + + + +#### Complexity Analysis + +- Time Complexity: $$O(n*m)$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(n*m)$$ where n is the length of the input array nums and m is the maximum number of digits in an element of the array. This is because the function iterates over each element in the array (O(n*m)) and for each element, it performs a while loop that iterates up to the number of digits in the element (O(m)). +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/1200-1299/_category_.json b/solutions/lc-solutions/1200-1299/_category_.json new file mode 100644 index 0000000..aae4acf --- /dev/null +++ b/solutions/lc-solutions/1200-1299/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "1200-1299", + "position": 14, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (1200 - 1299)" + } +} diff --git a/solutions/lc-solutions/1300-1399/1302-Deepest-Leaves-Sum.md b/solutions/lc-solutions/1300-1399/1302-Deepest-Leaves-Sum.md new file mode 100644 index 0000000..f1b7419 --- /dev/null +++ b/solutions/lc-solutions/1300-1399/1302-Deepest-Leaves-Sum.md @@ -0,0 +1,155 @@ +--- +id: Deepest-Leaves-Sum. +title: Deepest Leaves Sum. +sidebar_label: 1302-Deepest-Leaves-Sum +tags: + - Tree + - DFS + - BFS +description: "This is a solution to the Deepest Leaves Sum problem on LeetCode." +--- + +## Problem Description + +Given the root of a binary tree, return the sum of values of its deepest leaves. + +### Examples + +**Example 1:** + +``` +Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] +Output: 15 +``` +**Example 2:** + +``` +Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] +Output: 19 +``` + +### Constraints + +- The number of nodes in the tree is in the range `[1, 104]`. +- `1 <= Node.val <= 100` + + +## Deepest Leaves Sum + + +### Code in Different Languages + + +```cpp +class Solution { +public: + int deepestLeavesSum(TreeNode* root) { + + queueque; + int ans=0; + que.push(root); + //we push root of every level in queue and while pushing we calculate the sum and store that sum in ans varible when we at last we return ans varibale + que.push(NULL); + int sum =root->val; + ans=sum; + sum=0; + while(!que.empty()){ + if(que.front()==NULL && que.size()==1){ + break; + //condition for break the loop + } + TreeNode* temp =que.front(); + if(temp==NULL){ + ans=sum; + sum=0; + que.push(NULL); + //if we see null means one level is completed we store the sum in ans and empty the sum + } + else{ + if(temp->left!=NULL){ + que.push(temp->left); + //pushing next level in queue + + sum+=temp->left->val; + // adding the value in the sum + } + if(temp->right!=NULL){ + que.push(temp->right); + sum+=temp->right->val; + } + + } + + que.pop(); + } + + return ans; + } +}; + +``` + + +```java +class Solution { + public int deepestLeavesSum(TreeNode root) { + int level=getHeight(root); + return helper(root,level); + } + public int getHeight(TreeNode root) { + if (root == null) + return 0; + else { + int leftHeight = getHeight(root.left); + int rightHeight = getHeight(root.right); + + return Math.max(leftHeight, rightHeight) + 1; + } + } + public int helper(TreeNode root,int level){ + if(root==null){ + return 0; + } + if(level==1){ + return root.val; + } + return helper(root.left,level-1)+helper(root.right,level-1); + } +} +``` + + + +```python +class Solution: + def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: + deepestLevel = 0 + currSum = 0 + def dfs(root,level): + nonlocal deepestLevel,currSum + if not root: + return + if level==deepestLevel: + currSum+=root.val + elif level>deepestLevel: + deepestLevel = level + currSum = root.val + dfs(root.left,level+1) + dfs(root.right,level+1) + dfs(root,0) + return currSum +``` + + +### Complexity Analysis + +#### Time complexity: O(n) + +#### Space complexity: O(n) + + +## References + +- **LeetCode Problem**: [Deepest Leaves Sum](https://leetcode.com/problems/smallest-range-ii/description/](https://leetcode.com/problems/deepest-leaves-sum/description/) + +- **Solution Link**: [Deepest Leaves Sum](https://leetcode.com/problems/smallest-range-ii/solutions/](https://leetcode.com/problems/deepest-leaves-sum/solutions/5397378/dfs-solution-python/) diff --git a/solutions/lc-solutions/1300-1399/1305- All-Elements-In-Two-Binary-Search-Trees.md b/solutions/lc-solutions/1300-1399/1305- All-Elements-In-Two-Binary-Search-Trees.md new file mode 100644 index 0000000..3dfafa5 --- /dev/null +++ b/solutions/lc-solutions/1300-1399/1305- All-Elements-In-Two-Binary-Search-Trees.md @@ -0,0 +1,164 @@ +--- +id: all-elements-in-two-binary-search-trees +title: All Elements in Two Binary Search Trees +sidebar_label: 1305- All Elements in Two Binary Search Trees +tags: + - Tree + - DFS + - BFS + - Sorting + - Binary Tree +description: "This is a solution to the All Elements in Two Binary Search Trees." +--- + +## Problem Description + +Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order. + +### Examples + +**Example 1:** + +``` +Input: root1 = [2,1,4], root2 = [1,0,3] +Output: [0,1,1,2,3,4] +``` +**Example 2:** + +``` +Input: root1 = [1,null,8], root2 = [8,1] +Output: [1,1,8,8] +``` + +### Constraints + +- The number of nodes in each tree is in the range `[0, 5000]`. +- `-105 <= Node.val <= 105` + + +## All Elements in Two Binary Search Trees + + +### Code in Different Languages + + +```cpp + +class Solution { + +public: + vector getAllElements(TreeNode* a, TreeNode* b) { + vector A,B; + Inorder(a,A); + Inorder(b,B); + + return Merge(A,B); + } + +private: + + vector Merge(vectorA,vectorB) + { + int a=A.size(), b=B.size(); + vector V (a+b); + + int i=0,j=0,k=0; + while(i
& v) + { + if(!a) return ; + + Inorder(a->left,v); + v.push_back(a->val); + Inorder(a->right,v); + } +}; + +``` + + +```java +class Solution { + private List l = new ArrayList<>(); + private void inorder_r1(TreeNode root1){ + if (root1==null) { + return; + } + + l.add(root1.val); + inorder_r1(root1.left); + inorder_r1(root1.right); + } + private void inorder_r2(TreeNode root2){ + if (root2==null) { + return; + } + + l.add(root2.val); + inorder_r2(root2.left); + inorder_r2(root2.right); + } + public List getAllElements(TreeNode root1, TreeNode root2) { + if (root1 != null) { + inorder_r1(root1); + } + if (root2!=null) { + inorder_r1(root2); + } + + Collections.sort(l); + return l; + } +} +``` + + + +```python +class Solution(object): + def inorder(self,root,res): + if not root: + return + self.inorder(root.left,res) + res.append(root.val) + self.inorder(root.right,res) + + def getAllElements(self, root1, root2): + res1 = [] + res2 = [] + + self.inorder(root1,res1) + self.inorder(root2,res2) + + ans = [] + while len(res1) > 0 and len(res2) > 0: + if res1[0] >= res2[0]: + ans.append(res2.pop(0)) + else: + ans.append(res1.pop(0)) + ans += res1 if len(res1) > 0 else res2 + return ans +``` + + +### Complexity Analysis + +#### Time complexity: O(n) + +#### Space complexity: O(n) + + +## References + +- **LeetCode Problem**: [All Elements in Two Binary Search Trees]([https://leetcode.com/problems/smallest-range-ii/description/](https://leetcode.com/problems/deepest-leaves-sum/description/](https://leetcode.com/problems/all-elements-in-two-binary-search-trees/description/)) + +- **Solution Link**: [All Elements in Two Binary Search Trees]([https://leetcode.com/problems/smallest-range-ii/solutions/](https://leetcode.com/problems/deepest-leaves-sum/solutions/5397378/dfs-solution-python/](https://leetcode.com/problems/all-elements-in-two-binary-search-trees/solutions/5136840/one-pass-extremely-detailed-explanation/)) diff --git a/solutions/lc-solutions/1300-1399/1310-xor-queries-of-a-subarray.md b/solutions/lc-solutions/1300-1399/1310-xor-queries-of-a-subarray.md new file mode 100644 index 0000000..c6c928b --- /dev/null +++ b/solutions/lc-solutions/1300-1399/1310-xor-queries-of-a-subarray.md @@ -0,0 +1,125 @@ +--- +id: xor-queries-of-a-subarray +title: XOR Queries Of A Subarray +sidebar_label: 1310 XOR Queries Of A Subarray +tags: [Array, Bit Manipulation, Prefix Sum] +description: "This is the solution for XOR Queries Of A Subarray in leetcode." +--- + +### Examples + +**Example 1:** + +``` +Input: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]] +Output: [2,7,14,8] +``` + +**Example 2:** + +``` +Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]] +Output: [8,0,4,4] +``` + +**Example 3:** + +``` +Input: arr = [1], queries = [[0,0]] +Output: [1] +``` + +### Constraints +- `1 <= arr.length, queries.length <= 3 * 10^4` +- `1 <= arr[i] <= 10^9` +- `queries[i].length == 2` +- `0 <= lefti <= righti < arr.length` + +## Solution + + + + + +```python +from typing import List + +class Solution: + def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: + n = len(queries) + ans = [] + m = len(arr) + prefixXor = [0] * (m + 1) + for i in range(m): + prefixXor[i + 1] = prefixXor[i] ^ arr[i] + for query in queries: + left = query[0] + right = query[1] + ans.append(prefixXor[right + 1] ^ prefixXor[left]) + return ans +``` + + + + + + +```java +class Solution { + public int[] xorQueries(int[] arr, int[][] queries) { + for (int i = 1; i < arr.length; i++) { + arr[i] = arr[i - 1] ^ arr[i]; + } + int[] xor = new int[queries.length]; + for (int i = 0; i < queries.length; i++) { + int l = queries[i][0]; + int r = queries[i][1]; + if (l > 0) { + xor[i] = arr[r] ^ arr[l - 1]; + } else { + xor[i] = arr[r]; + } + } + return xor; + } +} +``` + + + + + +```cpp +#include + +class Solution { +public: + std::vector xorQueries(std::vector& arr, std::vector>& queries) { + std::vector preXor(arr.size() + 1); + int currXor = 0; + preXor[0] = 0; + for (int i = 0; i < arr.size(); i++) { + currXor ^= arr[i]; + preXor[i + 1] = currXor; + } + + std::vector ans(queries.size()); + for (int i = 0; i < queries.size(); i++) { + int l = queries[i][0]; + int r = queries[i][1]; + ans[i] = preXor[l] ^ preXor[r + 1]; + } + + return ans; + } +}; +``` + + + +--- + +## References + +- **LeetCode Problem:** [XOR Queries Of A Subarray](https://leetcode.com/problems/xor-queries-of-a-subarray/description/) +- **Solution Link:** [Leetcode Solution](https://leetcode.com/problems/xor-queries-of-a-subarray/solutions/3530554/beats-94-easy-to-understand-c-code/) diff --git a/solutions/lc-solutions/1300-1399/1323-Maximum-69-Number.md b/solutions/lc-solutions/1300-1399/1323-Maximum-69-Number.md new file mode 100644 index 0000000..6de8470 --- /dev/null +++ b/solutions/lc-solutions/1300-1399/1323-Maximum-69-Number.md @@ -0,0 +1,65 @@ +--- +id: maximum-69-number +title: Maximum 69 Number +sidebar_label: 1323-Maximum-69-Number +tags: + - Math + - Greedy +--- + +## Problem Description +You are given a positive integer `num` consisting only of digits `6` and `9`. + +Return the maximum number you can get by changing at most one digit (`6` becomes `9`, and `9` becomes `6`). + + +### Example + +**Example 1:** + + +``` +Input: num = 9669 +Output: 9969 +Explanation: +Changing the first digit results in 6669. +Changing the second digit results in 9969. +Changing the third digit results in 9699. +Changing the fourth digit results in 9666. +The maximum number is 9969. +``` +**Example 2:** +``` +Input: num = 9996 +Output: 9999 +Explanation: Changing the last digit 6 to 9 results in the maximum number. +``` +### Constraints + +- `1 <= num <= 104` + +## Solution Approach + +### Intuition: + +To efficiently determine the maximum number + + +## Solution Implementation + +### Code (C++): +```cpp +class Solution { +public: + int maximum69Number (int num) { + string str = to_string(num); + for(int i = 0; i < str.size(); i++){ + if(str[i] == '6'){ + str[i] = '9'; + break; + } + } + return stoi(str); + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/1300-1399/1342-Number-Of-Steps-To-Reduce-A-Number-To-Zero.md b/solutions/lc-solutions/1300-1399/1342-Number-Of-Steps-To-Reduce-A-Number-To-Zero.md new file mode 100644 index 0000000..2c1d8a1 --- /dev/null +++ b/solutions/lc-solutions/1300-1399/1342-Number-Of-Steps-To-Reduce-A-Number-To-Zero.md @@ -0,0 +1,171 @@ +--- +id: number-of-steps-to-reduce-a-number-to-zero +title: Number of Steps to Reduce a Number to Zero +sidebar_label: 1342-Number-Of-Steps-To-Reduce-A-Number-To-Zero +tags: + - Math + - Bit MManupulation +--- + +## Problem Description +Given an integer `num`, return the number of steps to reduce it to zero. + +In one step, if the current number is even, you have to divide it by `2`, otherwise, you have to subtract `1` from it. + + +### Example + +**Example 1:** + + +``` +Input: num = 14 +Output: 6 +Explanation: +Step 1) 14 is even; divide by 2 and obtain 7. +Step 2) 7 is odd; subtract 1 and obtain 6. +Step 3) 6 is even; divide by 2 and obtain 3. +Step 4) 3 is odd; subtract 1 and obtain 2. +Step 5) 2 is even; divide by 2 and obtain 1. +Step 6) 1 is odd; subtract 1 and obtain 0. +``` +**Example 2:** +``` +Input: num = 8 +Output: 4 +Explanation: +Step 1) 8 is even; divide by 2 and obtain 4. +Step 2) 4 is even; divide by 2 and obtain 2. +Step 3) 2 is even; divide by 2 and obtain 1. +Step 4) 1 is odd; subtract 1 and obtain 0. +``` +### Constraints + +- `0 <= num <= 106` + +## Solution Approach + +### Intuition: + +To efficiently determine the Number of Steps to Reduce a Number to Zero +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + +class Solution { + numberOfSteps(num) { + let cnt = 0; + while (num > 0) { + if (num % 2 === 0) { + num /= 2; + cnt++; + } else { + num -= 1; + cnt++; + } + } + return cnt; + } +} + + ``` + + + + + ```typescript + class Solution { + numberOfSteps(num: number): number { + let cnt = 0; + while (num > 0) { + if (num % 2 === 0) { + num /= 2; + cnt++; + } else { + num -= 1; + cnt++; + } + } + return cnt; + } +} + + ``` + + + + + ```python + class Solution: + def numberOfSteps(self, num: int) -> int: + cnt = 0 + while num > 0: + if num % 2 == 0: + num //= 2 + cnt += 1 + else: + num -= 1 + cnt += 1 + return cnt + + + ``` + + + + + ```java + public class Solution { + public int numberOfSteps(int num) { + int cnt = 0; + while (num > 0) { + if (num % 2 == 0) { + num /= 2; + cnt++; + } else { + num -= 1; + cnt++; + } + } + return cnt; + } +} + + ``` + + + + + ```cpp +class Solution { +public: + int numberOfSteps(int num) { + int cnt = 0; + while(num>0){ + if(num%2==0){ + num/=2; + cnt++; + } + else{ + num-=1; + cnt++; + } + } + return cnt; + } +}; +``` + + + +#### Complexity Analysis + +- Time Complexity: $$O(log(n))$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(log(n))$$ where n is the input number num. This is because in each iteration of the while loop, the value of num is halved (or decreased by 1), which effectively reduces the number of bits required to represent num by 1. Since the loop runs until num becomes 0, the number of iterations is proportional to the number of bits in the binary representation of num, which is roughly log2(n). +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/1300-1399/1346-Check-If-N-And-It's-Double-Exists.md b/solutions/lc-solutions/1300-1399/1346-Check-If-N-And-It's-Double-Exists.md new file mode 100644 index 0000000..a56b714 --- /dev/null +++ b/solutions/lc-solutions/1300-1399/1346-Check-If-N-And-It's-Double-Exists.md @@ -0,0 +1,66 @@ +--- +id: check-if-n-and-it's-double-exist +title: Check If N And Its Double Exist +sidebar_label: 1346-Check-If-N-And-Its-Double-Exist +tags: + - Araay + - Hash Table + - Two Pointer + - Binary Search + - Sorting +--- + +## Problem Description +Given an array `arr` of integers, check if there exist two indices `i` and `j` such that : + +`i != j` +`0 <= i, j < arr.length` +`arr[i] == 2 * arr[j]` + + +### Example + +**Example 1:** + + +``` +Input: arr = [10,2,5,3] +Output: true +Explanation: For i = 0 and j = 2, +arr[i] == 10 == 2 * 5 == 2 * arr[j] +``` +**Example 2:** +``` +Input: arr = [3,1,7,11] +Output: false +Explanation: There is no i and j that satisfy the conditions. + +``` +### Constraints + +- `-103 <= arr[i] <= 103` + +## Solution Approach + +### Intuition: + +To efficiently determine the n and if it's double exists or not. + + +## Solution Implementation + +### Code (C++): +```cpp +class Solution { +public: + bool checkIfExist(vector& arr) { + for(int i=0; i + + + ```javascript + +class Solution { + countNegatives(grid) { + let m = grid.length; + let n = grid[0].length; + let cnt = 0; + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] < 0) cnt++; + } + } + return cnt; + } +} + + ``` + + + + + ```typescript + class Solution { + countNegatives(grid: number[][]): number { + let m = grid.length; + let n = grid[0].length; + let cnt = 0; + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] < 0) cnt++; + } + } + return cnt; + } +} + + + + ``` + + + + + ```python + class Solution: + def countNegatives(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + cnt = 0 + for i in range(m): + for j in range(n): + if grid[i][j] < 0: + cnt += 1 + return cnt + + + + ``` + + + + + ```java + public class Solution { + public int countNegatives(int[][] grid) { + int m = grid.length; + int n = grid[0].length; + int cnt = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] < 0) cnt++; + } + } + return cnt; + } +} + + + ``` + + + + + ```cpp +class Solution { +public: + int countNegatives(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + int cnt = 0; + for(int i=0; i + + +#### Complexity Analysis + +- Time Complexity: $$O(m*n)$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(log(n))$$ where m and n are the number of rows and columns in the grid, respectively. This is because the algorithm iterates over each element in the grid once. +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/1300-1399/1365-How-Many-Numbers-Are-Smaller-Than-The-Current-Number.md b/solutions/lc-solutions/1300-1399/1365-How-Many-Numbers-Are-Smaller-Than-The-Current-Number.md new file mode 100644 index 0000000..7f87157 --- /dev/null +++ b/solutions/lc-solutions/1300-1399/1365-How-Many-Numbers-Are-Smaller-Than-The-Current-Number.md @@ -0,0 +1,181 @@ +--- +id: how-many-numbers-are-smaller-than-the-current-number +title: How Many Numbers Are Smaller Than the Current Number +sidebar_label: 1365-How-Many-Numbers-Are-Smaller-Than-The-Current-Number +tags: + - Array + - Hash Table + - Sorting + - Counting + +description: The problem no. is 1365. The Problem is How Many Numbers Are Smaller Than the Current Number +--- + +## Problem Description +Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid `j's` such that `j != i` and `nums[j] < nums[i]`. + +Return the answer in an array. + + +### Example + +**Example 1:** + + +``` +Input: nums = [8,1,2,2,3] +Output: [4,0,1,1,3] +Explanation: +For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). +For nums[1]=1 does not exist any smaller number than it. +For nums[2]=2 there exist one smaller number than it (1). +For nums[3]=2 there exist one smaller number than it (1). +For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2). +``` +**Example 2:** +``` +Input: nums = [6,5,4,8] +Output: [2,1,0,3] +``` +### Constraints + +- `2 <= nums.length <= 500` + +## Solution Approach + +### Intuition: + +To efficiently determine the Numbers Are Smaller Than the Current Number +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + +class Solution { + smallerNumbersThanCurrent(nums) { + let n = nums.length; + let ans = new Array(n); + for (let i = 0; i < n; i++) { + let cnt = 0; + for (let j = 0; j < n; j++) { + if (nums[i] > nums[j]) { + cnt++; + } + } + ans[i] = cnt; + } + return ans; + } +} + + + ``` + + + + + ```typescript + class Solution { + smallerNumbersThanCurrent(nums: number[]): number[] { + let n = nums.length; + let ans: number[] = new Array(n); + for (let i = 0; i < n; i++) { + let cnt = 0; + for (let j = 0; j < n; j++) { + if (nums[i] > nums[j]) { + cnt++; + } + } + ans[i] = cnt; + } + return ans; + } +} + + + + + ``` + + + + + ```python + class Solution: + def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: + n = len(nums) + ans = [0] * n + for i in range(n): + cnt = 0 + for j in range(n): + if nums[i] > nums[j]: + cnt += 1 + ans[i] = cnt + return ans + + + + + ``` + + + + + ```java + public class Solution { + public int[] smallerNumbersThanCurrent(int[] nums) { + int n = nums.length; + int[] ans = new int[n]; + for (int i = 0; i < n; i++) { + int cnt = 0; + for (int j = 0; j < n; j++) { + if (nums[i] > nums[j]) { + cnt++; + } + } + ans[i] = cnt; + } + return ans; + } +} + + + + ``` + + + + + ```cpp +class Solution { +public: + vector smallerNumbersThanCurrent(vector& nums) { + int n = nums.size(); + vector ans(n); + for(int i=0; inums[j]){ + cnt++; + } + } + ans[i]=cnt; + } + return ans; + } +}; + +``` + + + +#### Complexity Analysis + +- Time Complexity: $$O(n^2)$$ +- Space Complexity: $$O(n)$$ +- The time complexity is $$O(log(n))$$ where n is the length of the input array nums. This is because the algorithm uses a nested loop structure, where each element in the array is compared to every other element. +- The space complexity is $$O(n)$$ where n is the length of the input array nums. This is because the algorithm creates a new array ans of the same length as the input array to store the results. diff --git a/solutions/lc-solutions/1300-1399/1389-Create-Target-Array-in-given-order.md b/solutions/lc-solutions/1300-1399/1389-Create-Target-Array-in-given-order.md new file mode 100644 index 0000000..a0b498b --- /dev/null +++ b/solutions/lc-solutions/1300-1399/1389-Create-Target-Array-in-given-order.md @@ -0,0 +1,134 @@ +--- +id: create-target-array-in-given-order +title: Create Target Array in Given Order +sidebar_label: 1389 Create Target Array in Given Order +tags: +- Array +- Simulation +description: "This is the solution for create target array in given order in leetcode." +--- + +## Problem + +Given two arrays of integers `nums` and `index`, your task is to create a target array under the following rules: + +1. Initially, the target array is empty. +2. From left to right, read `nums[i]` and `index[i]`, then insert at index `index[i]` the value `nums[i]` in the target array. +3. Repeat the previous step until there are no elements to read in `nums` and `index`. +4. Return the target array. + +It is guaranteed that the insertion operations will be valid. + +### Examples + +**Example 1:** + +``` +Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] +Output: [0,4,1,3,2] +Explanation: +nums index target +0 0 [0] +1 1 [0,1] +2 2 [0,1,2] +3 2 [0,1,3,2] +4 1 [0,4,1,3,2] +``` + +**Example 2:** + +``` +Input: nums = [1,2,3,4,0], index = [0,1,2,3,0] +Output: [0,1,2,3,4] +Explanation: +nums index target +1 0 [1] +2 1 [1,2] +3 2 [1,2,3] +4 3 [1,2,3,4] +0 0 [0,1,2,3,4] +``` + +**Example 3:** + +``` +Input: nums = [1], index = [0] +Output: [1] +``` + +**Expected Time Complexity:** $O(N)$ +**Expected Auxiliary Space:** $O(N)$ + +### Constraints +- `1 <= nums.length, index.length <= 100` +- `nums.length == index.length` +- `0 <= nums[i] <= 100` +- `0 <= index[i] <= i` + +## Solution + +### Approach + +The approach for solving the problem of creating a target array from given `nums` and `index` arrays involves iterating through the `index` array and inserting elements from the `nums` array into a target array at positions specified by the `index` values. Specifically, we start with an empty target array. For each element in the `index` array, we use the corresponding element in the `nums` array and insert it at the position specified by the `index` value. This insertion shifts the existing elements in the target array to the right to accommodate the new element. This process is repeated for all elements in the `index` array until the target array is fully constructed. This approach ensures that the elements are placed in the correct positions according to the given indices, resulting in the desired target array. This method is implemented using a loop to iterate over the `index` array and the `insert` method to place the elements from the `nums` array at the appropriate positions in the target array. + +### Implementation + + + + + ```cpp + class Solution { + public: + std::vector createTargetArray(std::vector& nums, std::vector& index) { + std::vector target; + for (size_t i = 0; i < index.size(); ++i) { + target.insert(target.begin() + index[i], nums[i]); + } + return target; + } + }; + ``` + + + + + + ```python + class Solution: + def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: + target = [] + for i in range(len(index)): + target.insert(index[i], nums[i]) + return target + ``` + + + + + + + ```java + class Solution { + public int[] createTargetArray(int[] nums, int[] index) { + List target = new ArrayList<>(); + for (int i = 0; i < index.length; i++) { + target.add(index[i], nums[i]); + } + int[] result = new int[target.size()]; + for (int i = 0; i < target.size(); i++) { + result[i] = target.get(i); + } + return result; + } + } + ``` + + + + +--- + +## References + +- **LeetCode Problem:** [Create Target Array in Given Order](https://leetcode.com/problems/create-target-array-in-the-given-order/description/) +- **Solution Link:** [Leetcode Solution](https://leetcode.com/problems/create-target-array-in-the-given-order/post-solution/?submissionId=1271296265) \ No newline at end of file diff --git a/solutions/lc-solutions/1300-1399/_category_.json b/solutions/lc-solutions/1300-1399/_category_.json new file mode 100644 index 0000000..ca6a490 --- /dev/null +++ b/solutions/lc-solutions/1300-1399/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "1300-1399", + "position": 15, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (1300 - 1399)" + } +} diff --git a/solutions/lc-solutions/1300-1399/get-watched-videos-by-your-friends.md b/solutions/lc-solutions/1300-1399/get-watched-videos-by-your-friends.md new file mode 100644 index 0000000..9c9d777 --- /dev/null +++ b/solutions/lc-solutions/1300-1399/get-watched-videos-by-your-friends.md @@ -0,0 +1,200 @@ +--- +id: get-watched-videos-by-your-friends +title: Get Watched Videos by Your Friends +sidebar_label: Get Watched Videos by Your Friends +tags: [Graph, BFS, C++, Python, Java] +description: Find the list of videos watched by friends up to a certain level, ordered by their frequencies. +--- + +## Problem Statement + +### Problem Description + +There are `n` people, each person has a unique id between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with id `i`. + +Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level `k` of videos are all watched videos by people with the shortest path exactly equal to `k` with you. Given your `id` and the `level` of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency, order them alphabetically from least to greatest. + +### Example + +**Example 1:** + +``` +Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1 +Output: ["B","C"] +``` +**Explanation:** +You have id = 0 (green color in the figure) and your friends are (yellow color in the figure): +Person with id = 1 -> watchedVideos = ["C"] +Person with id = 2 -> watchedVideos = ["B","C"] +The frequencies of watchedVideos by your friends are: +B -> 1 +C -> 2 + + +### Constraints + +- `n == watchedVideos.length == friends.length` +- `2 <= n <= 100` +- `1 <= watchedVideos[i].length <= 100` +- `1 <= watchedVideos[i][j].length <= 8` +- `0 <= friends[i].length < n` +- `0 <= friends[i][j] < n` +- `0 <= id < n` +- `1 <= level < n` +- If `friends[i]` contains `j`, then `friends[j]` contains `i` + +## Solution + +### Intuition + +To solve this problem, we use a Breadth-First Search (BFS) approach to explore all friends up to the specified level. We start from the given `id` and use a queue to perform BFS. At each level, we gather the videos watched by the friends and keep track of the frequencies. We then sort the videos by frequency and alphabetically for those with the same frequency. + +### Time Complexity and Space Complexity Analysis + +- **Time Complexity**: The time complexity is $O(n \cdot m \cdot \log m)$, where `n` is the number of people and `m` is the maximum number of videos watched by any person. This is due to the BFS traversal and the sorting of the video frequencies. +- **Space Complexity**: The space complexity is $O(n \cdot m)$ due to the space needed for the BFS queue and the frequency map. + +### Code + +#### Python +```python +from collections import deque, Counter + +class Solution: + def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]: + video_frequency = Counter() + visited = [False] * len(friends) + q = deque([id]) + visited[id] = True + current_level = 0 + + while q: + size = len(q) + if current_level == level: + break + for _ in range(size): + person = q.popleft() + for friend in friends[person]: + if not visited[friend]: + visited[friend] = True + q.append(friend) + current_level += 1 + + while q: + person = q.popleft() + video_frequency.update(watchedVideos[person]) + + return sorted(video_frequency.keys(), key=lambda x: (video_frequency[x], x)) +``` + +#### C++ + +```cpp +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector watchedVideosByFriends(vector>& watchedVideos, vector>& friends, int id, int level) { + vector result; + unordered_map videoFrequency; + vector visited(friends.size(), false); + queue q; + q.push(id); + visited[id] = true; + int currentLevel = 0; + + while (!q.empty()) { + int size = q.size(); + if (currentLevel == level) break; + + while (size--) { + int person = q.front(); + q.pop(); + for (int friendId : friends[person]) { + if (!visited[friendId]) { + visited[friendId] = true; + q.push(friendId); + } + } + } + currentLevel++; + } + + while (!q.empty()) { + int person = q.front(); + q.pop(); + for (const string& video : watchedVideos[person]) { + videoFrequency[video]++; + } + } + + vector> videoList(videoFrequency.begin(), videoFrequency.end()); + sort(videoList.begin(), videoList.end(), [](const pair& a, const pair& b) { + if (a.second == b.second) return a.first < b.first; + return a.second < b.second; + }); + + for (const auto& [video, freq] : videoList) { + result.push_back(video); + } + + return result; + } +}; +``` +#### Java +```java +import java.util.*; + +class Solution { + public List watchedVideosByFriends(List> watchedVideos, List> friends, int id, int level) { + Map videoFrequency = new HashMap<>(); + boolean[] visited = new boolean[friends.size()]; + Queue queue = new LinkedList<>(); + queue.add(id); + visited[id] = true; + int currentLevel = 0; + + while (!queue.isEmpty()) { + int size = queue.size(); + if (currentLevel == level) break; + + for (int i = 0; i < size; i++) { + int person = queue.poll(); + for (int friend : friends.get(person)) { + if (!visited[friend]) { + visited[friend] = true; + queue.add(friend); + } + } + } + currentLevel++; + } + + while (!queue.isEmpty()) { + int person = queue.poll(); + for (String video : watchedVideos.get(person)) { + videoFrequency.put(video, videoFrequency.getOrDefault(video, 0) + 1); + } + } + + List> videoList = new ArrayList<>(videoFrequency.entrySet()); + videoList.sort((a, b) -> { + if (a.getValue().equals(b.getValue())) return a.getKey().compareTo(b.getKey()); + return Integer.compare(a.getValue(), b.getValue()); + }); + + List result = new ArrayList<>(); + for (Map.Entry entry : videoList) { + result.add(entry.getKey()); + } + + return result; + } +} +``` diff --git a/solutions/lc-solutions/1400-1499/1402-Reducing-Dishes.md b/solutions/lc-solutions/1400-1499/1402-Reducing-Dishes.md new file mode 100644 index 0000000..8941565 --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1402-Reducing-Dishes.md @@ -0,0 +1,149 @@ +--- +id: reducing-dishes +title: Reducing Dishes +sidebar_label: 1402-Reducing-Dishes +tags: + - Arrays + - Dynamic Programming + - Sorting + - C++ + - Java + - Python +description: "This document provides a solution to the Reducing Dishes problem, where we need to maximize the sum of the satisfaction of dishes." +--- + +## Problem + +A chef has collected data on the satisfaction level of his `n` dishes. Chef can cook any dish in 1 unit of time. Each dish takes `1` unit of time to cook. + +The chef has a choice to skip or cook the dish. He wants to maximize the sum of the satisfaction he gets from all the dishes he decides to cook. The satisfaction of a dish is defined as the sum of its satisfaction times its cooking time. + +Return the maximum sum of satisfaction the chef can obtain. + +### Examples + +**Example 1:** + +Input: satisfaction = [-1,-8,0,5,-9] +Output: 14 +Explanation: After removing the negative dishes, the remaining dishes are [0, 5]. + The optimal solution is to cook dish 0 at time 1 (0 * 1 = 0) and cook dish 5 at time 2 (5 * 2 = 10). + The total satisfaction is 0 + 10 + 5 = 14. + +**Example 2:** + +Input: satisfaction = [4,3,2] +Output: 20 +Explanation: The optimal solution is to cook all dishes in order. + The total satisfaction is 4 * 1 + 3 * 2 + 2 * 3 = 20. + +**Example 3:** + +Input: satisfaction = [-1,-4,-5] +Output: 0 +Explanation: The chef does not cook any dishes since all the satisfaction levels are negative. + +### Constraints + +- `n == satisfaction.length` +- `1 <= n <= 500` +- `-10^3 <= satisfaction[i] <= 10^3` + +### Approach + +To maximize the sum of satisfaction, we can sort the satisfaction array in ascending order. We will then iterate from the end of the sorted list towards the beginning, keeping a running total of the current satisfaction sum. We add to our result only if the current total is positive. + +The detailed steps are: + +1. Sort the satisfaction array. +2. Initialize `total` and `current` sums to 0. +3. Traverse the array from the end to the beginning, updating `current` sum and checking if adding the current element increases the `total`. +4. Return the maximum `total`. + +### Solution + +#### Code in Different Languages + +### C++ Solution +```cpp +#include +#include +#include + +using namespace std; + +int maxSatisfaction(vector& satisfaction) { + sort(satisfaction.begin(), satisfaction.end()); + int total = 0, current = 0; + for (int i = satisfaction.size() - 1; i >= 0; --i) { + current += satisfaction[i]; + if (current > 0) { + total += current; + } else { + break; + } + } + return total; +} + +int main() { + vector satisfaction = {-1, -8, 0, 5, -9}; + cout << maxSatisfaction(satisfaction) << endl; // Output: 14 +} +``` +### Java Solution +```java +import java.util.Arrays; + +public class ReducingDishes { + public static int maxSatisfaction(int[] satisfaction) { + Arrays.sort(satisfaction); + int total = 0, current = 0; + for (int i = satisfaction.length - 1; i >= 0; --i) { + current += satisfaction[i]; + if (current > 0) { + total += current; + } else { + break; + } + } + return total; + } + + public static void main(String[] args) { + int[] satisfaction = {-1, -8, 0, 5, -9}; + System.out.println(maxSatisfaction(satisfaction)); // Output: 14 + } +} +``` +### Python Solution + +```python +def maxSatisfaction(satisfaction): + satisfaction.sort() + total, current = 0, 0 + for i in range(len(satisfaction) - 1, -1, -1): + current += satisfaction[i] + if current > 0: + total += current + else: + break + return total + +# Test +satisfaction = [-1, -8, 0, 5, -9] +print(maxSatisfaction(satisfaction)) # Output: 14 +``` +### Complexity Analysis +**Time Complexity:** O(n log n) + +>Reason: Sorting the array takes O(n log n) time, and traversing the array takes O(n) time. + +**Space Complexity:** O(1) + +>Reason: We use a constant amount of extra space. + +This solution sorts the satisfaction array and then iterates through it in reverse to calculate the maximum sum of satisfaction. The time complexity is dominated by the sorting step, and the space complexity is constant. + +### References +**LeetCode Problem:** Reducing Dishes \ No newline at end of file diff --git a/solutions/lc-solutions/1400-1499/1405-longest-happy-string.md b/solutions/lc-solutions/1400-1499/1405-longest-happy-string.md new file mode 100644 index 0000000..e85f44b --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1405-longest-happy-string.md @@ -0,0 +1,148 @@ +--- +id: longest-happy-string +title: Longest Happy String +sidebar_label: 1405 - Longest Happy String +tags: + - String + - Greedy + - Heap +description: "This is a solution to the Longest Happy String problem on LeetCode." +--- + +## Problem Description + +A string s is called happy if it satisfies the following conditions: + +- s only contains the letters `'a'`, `'b'`, and `'c'`. +- s does not contain any of `"aaa"`, `"bbb"`, or `"ccc"` as a substring. +- s contains at most `a` occurrences of the letter `'a'`. +- s contains at most `b` occurrences of the letter `'b'`. +- s contains at most `c` occurrences of the letter `'c'`. +Given three integers `a`, `b`, and `c`, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string "". + +A substring is a contiguous sequence of characters within a string. + +### Examples + +**Example 1:** + +``` +Input: a = 1, b = 1, c = 7 +Output: "ccaccbcc" +Explanation: "ccbccacc" would also be a correct answer. +``` +**Example 2:** +``` +Input: a = 7, b = 1, c = 0 +Output: "aabaa" +Explanation: It is the only correct answer in this case. +``` +### Constraints + +- `0 <= a, b, c <= 100` +- `a + b + c > 0` + +## Solution for Longest Happy String + +### Approach + +this is almost identical to `984. String Without AAA or BBB`. We just need to ignore the smallest count in each round. Aassuming `a >= b >= c`: always try to add `'aa'`. If `a - 2 >= b`, add `'b'` (if not, the next round will add 'bb'). Repeat recursivelly for the remaining counts. + +In other words, we are greedily use two characters from the largest pile. We cusion these two characters with a character from the medium pile. For `[11,5,3]`, as an example, we first generate 'aabaabaab', and our piles become `[5,2,3]`. At this time, c becomes the medium pile, and we generate `'..aac'` `([3,2,2])`. After we add one more `'..aa'`, c becomes the largest pile and we pull two characters from it `'..cc' ``([1,2,0])`. We add the rest `'..bba'`, and the resulting string is `'aabaabaabaacaaccbba'`. + +This algorithm can be esilly proved to be correct by a contradiction (and counter-examples). + +## Code in Different Languages + + + + + +```cpp +string longestDiverseString(int a, int b, int c, char aa = 'a', char bb = 'b', char cc = 'c') { + if (a < b) + return longestDiverseString(b, a, c, bb, aa, cc); + if (b < c) + return longestDiverseString(a, c, b, aa, cc, bb); + if (b == 0) + return string(min(2, a), aa); + auto use_a = min(2, a), use_b = a - use_a >= b ? 1 : 0; + return string(use_a, aa) + string(use_b, bb) + + longestDiverseString(a - use_a, b - use_b, c, aa, bb, cc); +} +``` + + + +```java +String generate(int a, int b, int c, String aa, String bb, String cc) { + if (a < b) + return generate(b, a, c, bb, aa, cc); + if (b < c) + return generate(a, c, b, aa, cc, bb); + if (b == 0) + return aa.repeat(Math.min(2, a)); + int use_a = Math.min(2, a), use_b = a - use_a >= b ? 1 : 0; + return aa.repeat(use_a) + bb.repeat(use_b) + + generate(a - use_a, b - use_b, c, aa, bb, cc); +} +public String longestDiverseString(int a, int b, int c) { + return generate(a, b, c, "a", "b", "c"); +} +``` + + + + + +```python +from collections import Counter +class Solution: + def longestDiverseString(self, a: int, b: int, c: int) -> str: + result = [] # list of characters forming the happy string + remaining = Counter({'a':a,'b':b,'c':c,}) # freq dict of remaining characters + + # In each loop we update remaining and recompute + (fence, _), (wedge, _) = remaining.most_common(2) # initial group + while remaining[fence] > 0 and remaining[wedge] > 0: # loop till no new groups could be formed + # add first fence + result.append(fence) + remaining[fence] -= 1 + + # (Optional) add second fence, if it wouldn't form triplet with first fence and last wedge + if len(result) >= 2 and result[-2] == fence: + pass + elif remaining[fence] > 0: # add second fence if any remaining + result.append(fence) + remaining[fence] -= 1 + + # add wedge + result.append(wedge) + remaining[wedge] -= 1 + + # recompute the fence and wedge char for next group + (fence, _), (wedge, _) = remaining.most_common(2) + + # has remaining characters not consumed by loop, can append two maximum fences + if remaining[fence] > 0: + result.append(fence) + remaining[fence] -= 1 + if remaining[fence] > 0: + result.append(fence) + + return ''.join(result) +``` + + + +## Complexity Analysis + +### Time Complexity: $O(a+b+c)$ + +### Space Complexity: $O(a+b+c)$ + +## References + +- **LeetCode Problem**: [Longest Happy String](https://leetcode.com/problems/longest-happy-string/description/) + +- **Solution Link**: [Longest Happy String](https://leetcode.com/problems/longest-happy-string/solutions/) \ No newline at end of file diff --git a/solutions/lc-solutions/1400-1499/1406-Stone-Game-III.md b/solutions/lc-solutions/1400-1499/1406-Stone-Game-III.md new file mode 100644 index 0000000..fad1e5a --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1406-Stone-Game-III.md @@ -0,0 +1,159 @@ +--- +id: stone-game-III +title: Stone Game III +sidebar_label: 1406. Stone Game III + +tags: +- Array +- Math +- Dynammic Programming +- Game Theory + +description: "This is a solution to the Stone Game III problem on LeetCode." +--- + +## Problem Description +Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. + +Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take `1`, `2`,or `3` stones from the first remaining stones in the row. + +The score of each player is the sum of the values of the stones taken. The score of each player is `0` initially. + +The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. + +Assume Alice and Bob play optimally. + +Return `"Alice"` if `Alice` will win, `"Bob"` if `Bob` will win, or `"Tie"` if they will end the game with the same score. +### Examples + +**Example 1:** +``` +Input: stoneValue = [1,2,3,7] +Output: "Bob" +Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. + +``` + +**Example 2:** + +``` +Input: stoneValue = [1,2,3,-9] +Output: "Alice" +Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. +If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose. +If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose. +Remember that both play optimally so here Alice will choose the scenario that makes her win. +``` + + +### Constraints +- `1 <= stoneValue.length <= 5 * 10^4` +- `-1000 <= stoneValue[i] <= 1000` + +## Solution for Stone Game III Problem +### Approach +The problem is typical of dynamic programming. Let `dp[i]` denote the maximum score one can get if he/she takes stones first at the position i. We only need to compare `dp[0]*2` with the total sum of stone values to determine the game result. + +#### Steps to Solve +**Step1**. Calculate the suffix sum of stone values. +**Step2**. For `i = n-1, n-2, …, 0`, calculate `dp[i]`. We need to enumerate three possible scenarios which correspond to taking `1`, `2`, `3 `stones at this round. + +**state transition**: `dp[i] = max(dp[i], suffixSum[i]-suffixSum[k+1] + suffixSum[k+1] - dp[k+1]) = max(dp[i], suffixSum[i] - dp[k+1])`,for k = i, i+1, i+2, where `(suffixSum[k+1] - dp[k+1])` means the score one can get when he/she takes stones secondly at the position k+1. +**Step3**. Compare `suffixSum[0]` with `dp[0]*2`. (Alice score: `dp[0]`, Bob score: `suffixSum[0]-dp[0])` + + ## Code in Different Languages + + + + ```python + class Solution(object): + def stoneGameIII(self, stoneValue): + """ + :type stoneValue: List[int] + :rtype: str + """ + n = len(stoneValue) + suffixSum = [0 for _ in range(n+1)] + dp = [0 for _ in range(n+1)] + for i in range(n-1, -1, -1): + suffixSum[i] = suffixSum[i+1] + stoneValue[i] + for i in range(n-1, -1, -1): + dp[i] = stoneValue[i] + suffixSum[i+1] - dp[i+1] + for k in range(i+1, min(n, i+3)): + dp[i] = max(dp[i], suffixSum[i] - dp[k+1]) + if dp[0]*2 == suffixSum[0]: + return "Tie" + elif dp[0]*2 > suffixSum[0]: + return "Alice" + else: + return "Bob" + + ``` + + + + + ```java + class Solution { + public String stoneGameIII(int[] stoneValue) { + int n = stoneValue.length; + int[] suffixSum = new int[n+1]; + int[] dp = new int[n+1]; + suffixSum[n] = 0; + dp[n] = 0; + for (int i = n - 1; i >= 0; i--) + suffixSum[i] = suffixSum[i + 1] + stoneValue[i]; + for (int i = n-1; i >= 0; i--) { + dp[i] = stoneValue[i] + suffixSum[i+1] - dp[i+1]; + for (int k = i+1; k < i+3 && k < n; k++) { + dp[i] = Math.max(dp[i], suffixSum[i]-dp[k+1]); + } + } + if (dp[0]*2 == suffixSum[0]) + return "Tie"; + else if (dp[0]*2 > suffixSum[0]) + return "Alice"; + else + return "Bob"; + } +} + ``` + + + + + ```cpp + + class Solution { +public: + string stoneGameIII(vector& stoneValue) { + int n = stoneValue.size(); + vector suffixSum(n+1, 0); + vector dp(n+1, 0); + for (int i = n - 1; i >= 0; i--) + suffixSum[i] = suffixSum[i + 1] + stoneValue[i]; + for (int i = n-1; i >= 0; i--) { + dp[i] = stoneValue[i] + suffixSum[i+1] - dp[i+1]; + for (int k = i+1; k < i+3 && k < n; k++) { + dp[i] = max(dp[i], suffixSum[i]-dp[k+1]); + } + } + if (dp[0]*2 == suffixSum[0]) + return "Tie"; + else if (dp[0]*2 > suffixSum[0]) + return "Alice"; + else + return "Bob"; + } +}; +``` + + + + +## References + +- **LeetCode Problem**: [1406. Stone Game III](https://leetcode.com/problems/stone-game-iii/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/stone-game-iii/solutions/) + diff --git a/solutions/lc-solutions/1400-1499/1407-Top-Travellers.md b/solutions/lc-solutions/1400-1499/1407-Top-Travellers.md new file mode 100644 index 0000000..a2f1bb6 --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1407-Top-Travellers.md @@ -0,0 +1,131 @@ +--- +id: top-travellers +title: Top Travellers +level: easy +sidebar_label: 1407-Top Travellers +tags: + - Sql + - Pandas + - Database +description: "This document provides solutions for the Kids With the Top Travellers problem." +--- + +## Problem Statement + +**Table**: Users + ++---------------+---------+ +| Column Name | Type | ++---------------+---------+ +| id | int | +| name | varchar | ++---------------+---------+ +id is the column with unique values for this table. +name is the name of the user. + +**Table**: Rides + ++---------------+---------+ +| Column Name | Type | ++---------------+---------+ +| id | int | +| user_id | int | +| distance | int | ++---------------+---------+ +id is the column with unique values for this table. +user_id is the id of the user who traveled the distance "distance". + +Write a solution to report the distance traveled by each user. + +Return the result table ordered by `travelled_distance` in descending order, if two or more users traveled the same distance, order them by their `name` in ascending order. + +The result format is in the following example. + +**Example 1:** + +``` +Input: +Users table: ++------+-----------+ +| id | name | ++------+-----------+ +| 1 | Alice | +| 2 | Bob | +| 3 | Alex | +| 4 | Donald | +| 7 | Lee | +| 13 | Jonathan | +| 19 | Elvis | ++------+-----------+ +Rides table: ++------+----------+----------+ +| id | user_id | distance | ++------+----------+----------+ +| 1 | 1 | 120 | +| 2 | 2 | 317 | +| 3 | 3 | 222 | +| 4 | 7 | 100 | +| 5 | 13 | 312 | +| 6 | 19 | 50 | +| 7 | 7 | 120 | +| 8 | 19 | 400 | +| 9 | 7 | 230 | ++------+----------+----------+ +Output: ++----------+--------------------+ +| name | travelled_distance | ++----------+--------------------+ +| Elvis | 450 | +| Lee | 450 | +| Bob | 317 | +| Jonathan | 312 | +| Alex | 222 | +| Alice | 120 | +| Donald | 0 | ++----------+--------------------+ +Explanation: +Elvis and Lee traveled 450 miles, Elvis is the top traveler as his name is alphabetically smaller than Lee. +Bob, Jonathan, Alex, and Alice have only one ride and we just order them by the total distances of the ride. +Donald did not have any rides, the distance traveled by him is 0. + +``` + + + +## Solutions + +### Approach + +we will apply left join on id = user_Id and then group by userId and it will sum will add all the grouped distance and return it and if the value is null then ifull will return 0 and atlast we will order them. + +### Sql + +```Sql + +SELECT u.name, IFNULL(SUM(r.distance), 0) AS travelled_distance +FROM Users u +LEFT JOIN Rides r +ON u.id = r.user_id +GROUP BY r.user_id +ORDER BY travelled_distance DESC, u.name ASC; + +``` + +### Pandas + +```Pandas +import pandas as pd + +def top_travellers(users: pd.DataFrame, rides: pd.DataFrame) -> pd.DataFrame: + + df = rides.groupby( ['user_id'])['distance'].sum().reset_index(name='travelled_distance' ) + + df = pd.merge( users, df, how='left', left_on='id', right_on='user_id') + + df['travelled_distance'] = df['travelled_distance'].fillna(0) + + df.sort_values( by=['travelled_distance','name'], ascending=[False,True], inplace=True ) + + return df[['name','travelled_distance']] + +``` diff --git a/solutions/lc-solutions/1400-1499/1408-String-Matching-in-an-Array.md b/solutions/lc-solutions/1400-1499/1408-String-Matching-in-an-Array.md new file mode 100644 index 0000000..f22540b --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1408-String-Matching-in-an-Array.md @@ -0,0 +1,127 @@ +--- +id: string-matching-in-an-array +title: String Matching in an Array +sidebar_label: 1408 - String Matching in an Array +tags: + - Array + - String + - String Matching +description: "This is a solution to the String Matching in an Array problem on LeetCode." +--- + +## Problem Description + +Given an array of string `words`, return all strings in words that is a substring of another word. You can return the answer in any order. + +A substring is a contiguous sequence of characters within a string + +### Examples + +**Example 1:** + +``` +Input: words = ["mass","as","hero","superhero"] +Output: ["as","hero"] +Explanation: "as" is substring of "mass" and "hero" is substring of "superhero". +["hero","as"] is also a valid answer. +``` +**Example 2:** +``` +Input: words = ["leetcode","et","code"] +Output: ["et","code"] +Explanation: "et", "code" are substring of "leetcode". + +``` +### Constraints + +- `1 <= words.length <= 100` +- `1 <= words[i].length <= 30` + + +## Solution for String Matching in an Array + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector stringMatching(vector& words) { + vector ans; + for(auto i:words) + { + for(auto j: words) + { + if(i==j) continue; + if(j.find(i)!=-1) + { + ans.push_back(i); + break; + } + } + } + return ans; + } +}; +``` + + + +```java +class Solution { + public List stringMatching(String[] words) { + String str = String.join(" ", words); + List res = new ArrayList<>(); + for(int i = 0; i < words.length; i++){ + if(str.indexOf(words[i]) != str.lastIndexOf(words[i])){ + res.add(words[i]); + } + } + return res; + } +} +``` + + + + + +```python +class Solution: + def stringMatching(self, words: List[str]) -> List[str]: + def add(word: str): + node = trie + for c in word: + node = node.setdefault(c, {}) + + def get(word: str) -> bool: + node = trie + for c in word: + if (node := node.get(c)) is None: return False + return True + + words.sort(key=len, reverse=True) + trie, result = {}, [] + for word in words: + if get(word): result.append(word) + for i in range(len(word)): + add(word[i:]) + return result +``` + + + +## Complexity Analysis + +### Time Complexity: $O(NlogN + N * S^2)$ + +### Space Complexity: $O(N * S^2)$ + +## References + +- **LeetCode Problem**: [String Matching in an Array](https://leetcode.com/problems/string-matching-in-an-array/description/) + +- **Solution Link**: [String Matching in an Array](https://leetcode.com/problems/string-matching-in-an-array/solutions/) \ No newline at end of file diff --git a/solutions/lc-solutions/1400-1499/1409-Queries-on-a-Permutation-With-Key.md b/solutions/lc-solutions/1400-1499/1409-Queries-on-a-Permutation-With-Key.md new file mode 100644 index 0000000..aaeba48 --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1409-Queries-on-a-Permutation-With-Key.md @@ -0,0 +1,232 @@ +--- +id: queries-on-a-permutation-with-key +title: Queries on a Permutation With Key +sidebar_label: 1409 - Queries on a Permutation With Key +tags: + - Array + - Binary Indexed Tree + - Simulation +description: "This is a solution to the Queries on a Permutation With Key problem on LeetCode." +--- + +## Problem Description + +Given the array queries of positive integers between 1 and m, you have to process all `queries[i] ``(from i=0 to i=queries.length-1)` according to the following rules: + +- In the beginning, you have the permutation `P=[1,2,3,...,m]`. +- For the current i, find the position of `queries[i]` in the permutation `P (indexing from 0)` and then move this at the beginning of the permutation P. Notice that the position of `queries[i]` in P is the result for `queries[i]`. +Return an array containing the result for the given queries. + +### Examples + +**Example 1:** + +``` +Output: [2,1,2,1] +Explanation: The queries are processed as follow: +For i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. +For i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. +For i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. +For i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. +Therefore, the array containing the result is [2,1,2,1]. + +``` +**Example 2:** +``` +Input: queries = [4,1,2,2], m = 4 +Output: [3,1,2,0] + +``` +### Constraints + +- `1 <= m <= 10^3` +- `1 <= queries.length <= m` +- `1 <= queries[i] <= m` + +## Solution for Queries on a Permutation With Key + +### Approach + +1. Push_front : takes $O(n)$ +2. Find the index of a number :$ O(1)$ if use hashmap +3. Update the index’s of the rest of the elements from index 1 : takes $O(n)$ + +We can keep the elements in a sorted manner using a treeset/set. +However finding the position of element by looking at the number of elements `< or > element[I] `would take $O(n)$ which brings the time complexity to $O(n^2)$ + +An efficient Data structure that can find the number of elements `< or > an element[I]` is Fenwick tree. + +I use fenwick tree to solve the problem. +The idea is instead of pushing the element to the front i.e assigning an index 0 for every query. +I assign -1 for the first query, -2 for the second query, -3 for the third … +By doing so we can observe that range of index’`s = [-m,m]` +However we know that array index cannot be negative, Hence i encode it such that +-m = 0 +-m+1 = 1 +-m+2 = 2 +. +. +. +m=2m. +Basically right shifting the range to start from 0. +By doing so our new range is `[0,2m]` + +Operations we perform: +We initialize our Fenwick tree of size 2m +Set all the values from `[1…m]` i.e `[m..2m] to 1` +For every query +we find its postion by finding the number of set elements `<` the given query. +we set it's postion to 0 in fenwick tree +set its new to `-1,-2,-3` i.e `(m,m-1,m-2)` + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + void update(vector& tree,int i,int val) { + while(i& tree,int i) { + int s = 0; + while(i>0) { + s+=tree[i]; + i-=(i&(-i)); + } + return s; + } + + vector processQueries(vector& queries, int m) { + vector res,tree((2*m)+1,0); + unordered_map hmap; + for(int i=1;i<=m;++i) { + hmap[i] = i+m; + update(tree,i+m,1); + } + + for(int querie : queries) { + res.push_back(getSum(tree,hmap[querie])-1); + update(tree,hmap[querie],-1); + update(tree,m,1); + hmap[querie] = m; + m--; + } + return res; + } +}; +``` + + + +```java +class Solution { + public int[] processQueries(int[] queries, int m) { + int n = queries.length; + BIT bit = new BIT(n+m+1); + Map map = new HashMap<>(); + for (int i = 1; i <= m; i++) { + bit.add(n+i, 1); + map.put(i, n+i); + } + + int[] res = new int[n]; + for (int i = 0; i < n; i++) { + int index = map.remove(queries[i]); + res[i] = bit.prefixSum(index-1); + + int new_index = n - i; + bit.add(index, -1); + bit.add(new_index, 1); + map.put(queries[i], new_index); + } + return res; + } + + class BIT { + int[] a; + + public BIT(int n) { + a = new int[n]; + } + + public void add(int index, int delta) { + index++; + while (index < a.length) { + a[index] += delta; + index += index & (-index); + } + } + + public int prefixSum(int index) { + index++; + int res = 0; + while (index > 0) { + res += a[index]; + index -= index & (-index); + } + return res; + } + } +} +``` + + + + + +```python +class Solution: + def processQueries(self, queries: List[int], m: int) -> List[int]: + + tree = [0] * ((2*m) + 1) + res = [] + + def update(i,val): + while i0: + s+=tree[i] + i-=(i&(-i)) + return s + + hmap = collections.defaultdict(int) + + for i in range(1,m+1): + hmap[i] = i+m + update(i+m,1) + + for i in queries: + res.append(prefixSum(hmap[i])-1) + update(hmap[i],-1) + update(m,1) + hmap[i] = m + m-=1 + + return res +``` + + + +## Complexity Analysis + +### Time Complexity: $O(nlogn)$ + +### Space Complexity: $O(2m)$ + +## References + +- **LeetCode Problem**: [Queries on a Permutation With Key](https://leetcode.com/problems/queries-on-a-permutation-with-key/description/) + +- **Solution Link**: [Queries on a Permutation With Key](https://leetcode.com/problems/queries-on-a-permutation-with-key/solutions/) \ No newline at end of file diff --git a/solutions/lc-solutions/1400-1499/1410-HTML-Entity-Parser.md b/solutions/lc-solutions/1400-1499/1410-HTML-Entity-Parser.md new file mode 100644 index 0000000..b3e03d1 --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1410-HTML-Entity-Parser.md @@ -0,0 +1,141 @@ +--- +id: html-entity-parser +title: HTML Entity Parser +sidebar_label: 1410 - HTML Entity Parser +tags: + - Hash Table + - String +description: "This is a solution to the HTML Entity Parser problem on LeetCode." +--- + +## Problem Description + +HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself. + +The special characters and their entities for HTML are: + +- Quotation Mark: the entity is `"`; and symbol character is` "`. +- Single Quote Mark: the entity is `&apos`; and symbol character is `'`. +- Ampersand: the entity is `&`; and symbol character is `&`. +- Greater Than Sign: the entity is `>`; and symbol character is `>`. +- Less Than Sign: the entity is `<`; and symbol character is `<`. +- Slash: the entity is `&frasl`; and symbol character is `/`. +Given the input text string to the HTML parser, you have to implement the entity parser. + +Return the text after replacing the entities by the special characters. + +### Examples + +**Example 1:** + +``` +Input: text = "& is an HTML entity but &ambassador; is not." +Output: "& is an HTML entity but &ambassador; is not." +Explanation: The parser will replace the & entity by & + +``` +**Example 2:** +``` +Input: text = "and I quote: "..."" +Output: "and I quote: \"...\"" + +``` +### Constraints + +- `1 <= text.length <= 10^5` +- The string may contain any possible characters out of all the 256 ASCII characters. + +## Solution for HTML Entity Parser + +### Approach + +We can use two-pointers approach and re-use the input string to store the output: + +- Copy the current character `text[p] = text[i]` +- Track the starting position of `'&'` +- When we see `';'`, check for the special character. +For a match, decrease the slow pointer p, and copy the corresponding symbol. +For true $O(n)$ solution, we need to use Trie to do the matching. I feel lazy today so I just broke special characters by size to minimize checks. + +## Code in Different Languages + + + + + +```cpp +string entityParser(string text) { + vector> encoded[8] = {{}, {}, {}, {}, {{">", '>'}, {"<", '<'}}, + {{"&", '&'}}, {{""", '"'}, {"'", '\''}}, {{"⁄", '/'}}}; + int st = 0, p = 0; + for (auto i = 0; i < text.size(); ++i, ++p) { + text[p] = text[i]; + if (text[p] == '&') + st = p; + if (text[p] == ';') { + auto sz = p - st + 1; + if (sz >= 4 && sz <= 7) + for (auto &[enc, dec] : encoded[sz]) { + if (text.compare(st, sz, enc) == 0) { + p = st; + text[p] = dec; + break; + } + } + st = p + 1; + } + } + text.resize(p); + return text; +} +``` + + + +```java +public String entityParser(String text) { + if (text == null || text.length() == 0) { + return ""; + } + Map map = + Map.of(""", "\"", "'", "'", + ">", ">", + "<", "<", "⁄", "/"); + for (String key : map.keySet()) { + text = text.replaceAll(key, map.get(key)); + } + return text.replaceAll("&", "&"); // "&" must be put in last; + } +``` + + + + + +```python +class Solution: + def entityParser(self, text: str) -> str: + + html_symbol = [ '"', ''', '>', '<', '⁄', '&'] + formal_symbol = [ '"', "'", '>', '<', '/', '&'] + + for html_sym, formal_sym in zip(html_symbol, formal_symbol): + text = text.replace( html_sym , formal_sym ) + + return text + +``` + + + +## Complexity Analysis + +### Time Complexity: $O(n)$ + +### Space Complexity: $O(1)$ + +## References + +- **LeetCode Problem**: [HTML Entity Parser](https://leetcode.com/problems/html-entity-parser/description/) + +- **Solution Link**: [HTML Entity Parser](https://leetcode.com/problems/html-entity-parser/solutions/) \ No newline at end of file diff --git a/solutions/lc-solutions/1400-1499/1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons.md b/solutions/lc-solutions/1400-1499/1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons.md new file mode 100644 index 0000000..a63b687 --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons.md @@ -0,0 +1,63 @@ +--- +id: build-array-where-you-can-find-the-maximum-exactly-k-comparisons +title: 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons +sidebar_label: 1420-build-array-where-you-can-find-the-maximum-exactly-k-comparisons +description: "This document provides solutions for leetcode problem 1420." +--- + +## Intuition +The problem involves finding the number of ways to create an array of length n with elements from 1 to m such that the sum of the elements is equal to k. This can be approached as a dynamic programming problem where you consider each position in the array and each possible value for that position. The intuition here is to use recursion with memoization to keep track of the number of ways to achieve the desired sum while exploring different choices. + +## Approach +We define a function `solve` that takes several parameters: + +1. If `searchCost` exceeds k, we return 0 as it's not a valid way to achieve the desired sum. +2. If we have reached the end of the array (n == index), we check if `searchCost` is equal to k. If it is, we return 1 (valid way), otherwise, we return 0 (not a valid way). +3. We check if we have already computed the result for the current state (index, searchCost, maxi) in the dp table. If yes, we return the memoized result. +4. We initialize `temp` to 0, which will be used to accumulate the number of valid ways. +5. We loop through all possible values from 1 to m for the current position. +6. If the current value is greater than `maxi`, we recursively call `solve` with `index + 1`, `searchCost + 1`, and the new maximum value `i`. +7. If the current value is not greater than `maxi`, we call `solve` with `index + 1`, `searchCost`, and the current maximum value `maxi`. +8. We accumulate the results in `temp`. + +## Complexity +Time complexity: The time complexity depends on the number of subproblems, which is O(n * k * m^2) in the worst case. + +Space complexity: The space complexity is determined by the size of the dp table, which is O(n * k * m) to store intermediate results. + +```cpp +class Solution { +public: + int mod = 1e9 + 7; + int solve(int index, int searchCost, int maxi, int n, int m, int k, vector>> &dp) + { + if (searchCost > k) + return 0; + + if (n == index) + { + if (searchCost == k) + return 1; + return 0; + } + if (dp[index][searchCost][maxi] != -1) + return dp[index][searchCost][maxi]; + + int temp = 0; + for (int i = 1; i <= m; i++) + { + if (i > maxi) + temp = (temp + solve(index + 1, searchCost + 1, i, n, m, k, dp)) % mod; + else + temp = (temp + solve(index + 1, searchCost, maxi, n, m, k, dp)) % mod; + } + return dp[index][searchCost][maxi] = temp; + } + + int numOfArrays(int n, int m, int k) + { + vector>> dp(n + 1, vector>(k + 1, vector(m + 1, -1))); + return solve(0, 0, 0, n, m, k, dp); + } +}; +``` diff --git a/solutions/lc-solutions/1400-1499/1421 - npv-queries.md b/solutions/lc-solutions/1400-1499/1421 - npv-queries.md new file mode 100644 index 0000000..cf06164 --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1421 - npv-queries.md @@ -0,0 +1,80 @@ +--- +id: npv-queries +title: 1421. NPV Queries +sidebar_label: 1421 - npv-queries +description: "This is a solution to LeetCode problems 1421." +--- + +SQL Schema +Table: NPV + ++---------------+---------+ +| Column Name | Type | ++---------------+---------+ +| id | int | +| year | int | +| npv | int | ++---------------+---------+ +(id, year) is the primary key of this table. +The table contains information about the id and the year of each inventory and the corresponding net present value. + + +Table: Queries + ++---------------+---------+ +| Column Name | Type | ++---------------+---------+ +| id | int | +| year | int | ++---------------+---------+ +(id, year) is the primary key of this table. +The table contains information about the id and the year of each inventory query. + + +Write an SQL query to find the npv of each query in the queries table. + +Return the result table in any order. + +The query result format is as follows: + +NPV table: ++------+--------+--------+ +| id | year | npv | ++------+--------+--------+ +| 1 | 2018 | 100 | +| 7 | 2020 | 30 | +| 13 | 2019 | 40 | +| 1 | 2019 | 113 | +| 2 | 2008 | 121 | +| 3 | 2009 | 12 | +| 11 | 2020 | 99 | +| 7 | 2019 | 0 | ++------+--------+--------+ + +Queries table: ++------+--------+ +| id | year | ++------+--------+ +| 1 | 2019 | +| 2 | 2008 | +| 3 | 2009 | +| 7 | 2018 | +| 7 | 2019 | +| 7 | 2020 | +| 13 | 2019 | ++------+--------+ + +Result table: ++------+--------+--------+ +| id | year | npv | ++------+--------+--------+ +| 1 | 2019 | 113 | +| 2 | 2008 | 121 | +| 3 | 2009 | 12 | +| 7 | 2018 | 0 | +| 7 | 2019 | 0 | +| 7 | 2020 | 30 | +| 13 | 2019 | 40 | ++------+--------+--------+ + +The npv value of (7, 2018) is not present in the NPV table, so we consider it as 0. The npv values of all other queries can be found in the NPV table. diff --git a/solutions/lc-solutions/1400-1499/1424-diagonal-traverse-ii.md b/solutions/lc-solutions/1400-1499/1424-diagonal-traverse-ii.md new file mode 100644 index 0000000..d3ef313 --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1424-diagonal-traverse-ii.md @@ -0,0 +1,338 @@ +--- +id: diagonal-traverse-ii +title: Diagonal Traverse II +sidebar_label: 1424. Diagonal Traverse II + +tags: +- Array +- Sorting +- Heap (Priority Queue) + +description: "This is a solution to the Diagonal Traverse II problem on LeetCode." +--- + +## Problem Description +Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images. +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2020/04/08/sample_1_1784.png) +``` +Input: nums = [[1,2,3],[4,5,6],[7,8,9]] +Output: [1,4,2,7,5,3,8,6,9] +``` + +**Example 2:** +![image](https://assets.leetcode.com/uploads/2020/04/08/sample_2_1784.png) +``` +Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]] +Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16] +``` + + +### Constraints +- `1 <= nums.length <= 10^5` +- `1 <= nums[i].length <= 10^5` +- `1 <= sum(nums[i].length) <= 10^5` +- `1 <= nums[i][j] <= 10^5` + +## Solution for Diagonal Traverse II Problem +### Approach +The problem requires traversing the 2D list in a diagonal manner. Diagonal order means we visit all elements of each diagonal, starting from the top-left element `(0, 0)`. The diagonals can be visualized as lines of elements where the sum of the row index and column index is constant. + +#### Steps to Solve +1. **Initialize a Queue and Visited Matrix**: + - Use a queue to facilitate breadth-first traversal starting from the top-left element. + - Use a `visited` matrix to keep track of visited elements to avoid processing the same element multiple times. + +2. **Determine Dimensions**: + - Determine the maximum number of columns (`n`) by iterating through each row of the input list. + - The number of rows (`m`) is simply the length of the input list. + +3. **Breadth-First Traversal**: + - Start from `(0, 0)`, mark it as visited, and add it to the queue. + - While the queue is not empty, perform the following steps: + - Dequeue the front element (current position). + - Add the value at the current position to the result list. + - Check and enqueue the element directly below the current position if it exists and has not been visited. + - Check and enqueue the element to the right of the current position if it exists and has not been visited. + +4. **Return the Result**: + - After processing all elements in the queue, the result list will contain the elements in diagonal order. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function findDiagonalOrder(nums) { + let ans = []; + let q = []; + let vis = nums.map(row => row.map(() => false)); + + let m = nums.length; + let n = 0; + for (let i = 0; i < m; i++) { + if (nums[i].length > n) { + n = nums[i].length; + } + } + + q.push([0, 0]); + vis[0][0] = true; + + while (q.length > 0) { + let [row, col] = q.shift(); + ans.push(nums[row][col]); + + if (row + 1 < m && col < nums[row + 1].length && !vis[row + 1][col]) { + q.push([row + 1, col]); + vis[row + 1][col] = true; + } + if (row < m && col + 1 < nums[row].length && !vis[row][col + 1]) { + q.push([row, col + 1]); + vis[row][col + 1] = true; + } + } + + return ans; + } + const input = [[1,2,3],[4,5,6],[7,8,9]] + const output = findDiagonalOrder(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(m*n) $ + - Space Complexity: $ O(m*n)$ + + ## Code in Different Languages + + + + ```javascript + findDiagonalOrder(nums) { + let ans = []; + let q = []; + let vis = nums.map(row => row.map(() => false)); + + let m = nums.length; + let n = 0; + for (let i = 0; i < m; i++) { + if (nums[i].length > n) { + n = nums[i].length; + } + } + + q.push([0, 0]); + vis[0][0] = true; + + while (q.length > 0) { + let [row, col] = q.shift(); + ans.push(nums[row][col]); + + if (row + 1 < m && col < nums[row + 1].length && !vis[row + 1][col]) { + q.push([row + 1, col]); + vis[row + 1][col] = true; + } + if (row < m && col + 1 < nums[row].length && !vis[row][col + 1]) { + q.push([row, col + 1]); + vis[row][col + 1] = true; + } + } + + return ans; + } + ``` + + + + + ```typescript + class Solution { + findDiagonalOrder(nums: number[][]): number[] { + let ans: number[] = []; + let q: [number, number][] = []; + let vis: boolean[][] = nums.map(row => row.map(() => false)); + + let m = nums.length; + let n = 0; + for (let i = 0; i < m; i++) { + if (nums[i].length > n) { + n = nums[i].length; + } + } + + q.push([0, 0]); + vis[0][0] = true; + + while (q.length > 0) { + let [row, col] = q.shift(); + ans.push(nums[row][col]); + + if (row + 1 < m && col < nums[row + 1].length && !vis[row + 1][col]) { + q.push([row + 1, col]); + vis[row + 1][col] = true; + } + if (row < m && col + 1 < nums[row].length && !vis[row][col + 1]) { + q.push([row, col + 1]); + vis[row][col + 1] = true; + } + } + + return ans; + } +} + + ``` + + + + ```python + from collections import deque + +class Solution: + def findDiagonalOrder(self, nums): + ans = [] + q = deque() + vis = [[False] * len(row) for row in nums] + + m = len(nums) + n = 0 + for i in range(m): + if len(nums[i]) > n: + n = len(nums[i]) + + q.append((0, 0)) + vis[0][0] = True + + while q: + row, col = q.popleft() + ans.append(nums[row][col]) + + if row + 1 < m and col < len(nums[row + 1]) and not vis[row + 1][col]: + q.append((row + 1, col)) + vis[row + 1][col] = True + if row < m and col + 1 < len(nums[row]) and not vis[row][col + 1]: + q.append((row, col + 1)) + vis[row][col + 1] = True + + return ans + + ``` + + + + + ```java + import java.util.*; + +class Solution { + public List findDiagonalOrder(List> nums) { + List ans = new ArrayList<>(); + Queue q = new LinkedList<>(); + boolean[][] vis = new boolean[nums.size()][]; + + int m = nums.size(); + int n = 0; + for (int i = 0; i < m; i++) { + if (nums.get(i).size() > n) { + n = nums.get(i).size(); + } + vis[i] = new boolean[nums.get(i).size()]; + } + + q.offer(new int[]{0, 0}); + vis[0][0] = true; + + while (!q.isEmpty()) { + int[] el = q.poll(); + int row = el[0]; + int col = el[1]; + ans.add(nums.get(row).get(col)); + + if (row + 1 < m && col < nums.get(row + 1).size() && !vis[row + 1][col]) { + q.offer(new int[]{row + 1, col}); + vis[row + 1][col] = true; + } + if (row < m && col + 1 < nums.get(row).size() && !vis[row][col + 1]) { + q.offer(new int[]{row, col + 1}); + vis[row][col + 1] = true; + } + } + + return ans; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + vector findDiagonalOrder(vector>& nums) { + + vector ans; + queue> q; + vector> vis = nums; + + int m = nums.size(); + int n = 0; + for(int i=0 ; in){ + n = nums[i].size(); + } + } + + q.push({0,0}); + vis[0][0] = -1; + + while(!q.empty()){ + auto el = q.front(); + int row = el.first; + int col = el.second; + q.pop(); + ans.push_back(nums[row][col]); + + if(row+1 + + +
+
+ +## References + +- **LeetCode Problem**: [1424. Diagonal Traverse II](https://leetcode.com/problems/diagonal-traverse-ii/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/diagonal-traverse-ii/solutions) + diff --git a/solutions/lc-solutions/1400-1499/1431-kids-with-the-greatest-number-of-candies.md b/solutions/lc-solutions/1400-1499/1431-kids-with-the-greatest-number-of-candies.md new file mode 100644 index 0000000..90856de --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1431-kids-with-the-greatest-number-of-candies.md @@ -0,0 +1,101 @@ +--- +id: kids-with-the-greatest-number-of-candies +title: Kids With the Greatest Number of Candies +level: easy +sidebar_label: Kids With the Greatest Number of Candies +tags: + - Array + - Greedy + - Java +description: "This document provides solutions for the Kids With the Greatest Number of Candies problem." +--- + +## Problem Statement + +There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the ith kid has, and an integer `extraCandies`, denoting the number of extra candies that you have. + +Return a boolean array `result` of length `n`, where `result[i]` is `true` if, after giving the ith kid all the `extraCandies`, they will have the greatest number of candies among all the kids, or `false` otherwise. + +**Example 1:** + +Input: `candies = [2,3,5,1,3]`, `extraCandies = 3` + +Output: `[true,true,true,false,true]` + +Explanation: If you give all `extraCandies` to: +- Kid 1, they will have `2 + 3 = 5` candies, which is the greatest among the kids. +- Kid 2, they will have `3 + 3 = 6` candies, which is the greatest among the kids. +- Kid 3, they will have `5 + 3 = 8` candies, which is the greatest among the kids. +- Kid 4, they will have `1 + 3 = 4` candies, which is not the greatest among the kids. +- Kid 5, they will have `3 + 3 = 6` candies, which is the greatest among the kids. + +**Example 2:** + +Input: `candies = [4,2,1,1,2]`, `extraCandies = 1` + +Output: `[true,false,false,false,false]` + +Explanation: There is only `1` extra candy. +Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy. + +**Example 3:** + +Input: `candies = [12,1,12]`, `extraCandies = 10` + +Output: `[true,false,true]` + +**Constraints:** + +- `n == candies.length` +- `2 <= n <= 100` +- `1 <= candies[i] <= 100` +- `1 <= extraCandies <= 50` + +## Solutions + +### Approach + +To determine if each kid can have the greatest number of candies after receiving `extraCandies`, follow these steps: + +1. **Find the Maximum Candies:** + - Traverse through the `candies` array to find the maximum number of candies any kid currently has. + +2. **Check Each Kid's Condition:** + - Iterate through the `candies` array again. + - For each kid, check if adding `extraCandies` to their current candies makes their total candies equal to or greater than the maximum number found. + - Store `true` if the condition is met, otherwise store `false`. + +### Java + +```java + +class Solution { + public List kidsWithCandies(int[] candies, int extraCandies) { + int maxCandies = 0; + for (int candy : candies) { + maxCandies = Math.max(maxCandies, candy); + } + + List result = new ArrayList<>(); + for (int candy : candies) { + result.add(candy + extraCandies >= maxCandies); + } + + return result; + } + +} +``` + +### Python +```Python +class Solution: + def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: + maxCandies = max(candies) + result = [] + + for candy in candies: + result.append(candy + extraCandies >= maxCandies) + + return result +``` diff --git a/solutions/lc-solutions/1400-1499/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.md b/solutions/lc-solutions/1400-1499/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.md new file mode 100644 index 0000000..3b2a36d --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.md @@ -0,0 +1,142 @@ +--- +id: longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit +title: Longest Continuous Subarray with Absolute Diff Less Than or Equal to Limit +level: hard +sidebar_label: Longest Continuous Subarray with Absolute Diff Less Than or Equal to Limit +tags: + - Array + - Sliding Window + - Deque + - Java +description: "This document provides solutions for the Longest Continuous Subarray with Absolute Diff Less Than or Equal to Limit problem." +--- + +## Problem Statement + +Given an array of integers `nums` and an integer `limit`, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to `limit`. + +**Example 1:** + +Input: `nums = [8,2,4,7]`, `limit = 4` + +Output: `2` + +Explanation: All subarrays are: +- `[8]` with maximum absolute diff `|8-8| = 0 <= 4`. +- `[8,2]` with maximum absolute diff `|8-2| = 6 > 4`. +- `[8,2,4]` with maximum absolute diff `|8-2| = 6 > 4`. +- `[8,2,4,7]` with maximum absolute diff `|8-2| = 6 > 4`. +- `[2]` with maximum absolute diff `|2-2| = 0 <= 4`. +- `[2,4]` with maximum absolute diff `|2-4| = 2 <= 4`. +- `[2,4,7]` with maximum absolute diff `|2-7| = 5 > 4`. +- `[4]` with maximum absolute diff `|4-4| = 0 <= 4`. +- `[4,7]` with maximum absolute diff `|4-7| = 3 <= 4`. +- `[7]` with maximum absolute diff `|7-7| = 0 <= 4`. + +Therefore, the size of the longest subarray is 2. + +**Example 2:** + +Input: `nums = [10,1,2,4,7,2]`, `limit = 5` + +Output: `4` + +Explanation: The subarray `[2,4,7,2]` is the longest since the maximum absolute diff is `|2-7| = 5 <= 5`. + +**Example 3:** + +Input: `nums = [4,2,2,2,4,4,2,2]`, `limit = 0` + +Output: `3` + +**Constraints:** + +- `1 <= nums.length <= 10^5` +- `1 <= nums[i] <= 10^9` +- `0 <= limit <= 10^9` + +## Solutions + +### Approach + +To determine the length of the longest subarray where the absolute difference between any two elements is less than or equal to `limit`, follow these steps: + +1. **Sliding Window with Deque:** + - Use two deques to maintain the maximum and minimum values in the current window. + - Slide the window across the array and adjust the window size to ensure the absolute difference condition is met. + +### Java + +```java + + +class Solution { + public int longestSubarray(int[] nums, int limit) { + LinkedList increase = new LinkedList<>(); + LinkedList decrease = new LinkedList<>(); + + int max = 0; + int left = 0; + + for (int i = 0; i < nums.length; i++) { + int n = nums[i]; + + while (!increase.isEmpty() && n < increase.getLast()) { + increase.removeLast(); + } + increase.add(n); + + while (!decrease.isEmpty() && n > decrease.getLast()) { + decrease.removeLast(); + } + decrease.add(n); + + while (decrease.getFirst() - increase.getFirst() > limit) { + if (nums[left] == decrease.getFirst()) { + decrease.removeFirst(); + } + if (nums[left] == increase.getFirst()) { + increase.removeFirst(); + } + left++; + } + + int size = i - left + 1; + max = Math.max(max, size); + } + + return max; + } +} +``` +### Python +```Python +class Solution: + def longestSubarray(self, nums: List[int], limit: int) -> int: + increase = deque() + decrease = deque() + max_length = 0 + left = 0 + + for i in range(len(nums)): + n = nums[i] + + while increase and n < increase[-1]: + increase.pop() + increase.append(n) + + while decrease and n > decrease[-1]: + decrease.pop() + decrease.append(n) + + while decrease[0] - increase[0] > limit: + if nums[left] == decrease[0]: + decrease.popleft() + if nums[left] == increase[0]: + increase.popleft() + left += 1 + + max_length = max(max_length, i - left + 1) + + return max_length +``` diff --git a/solutions/lc-solutions/1400-1499/1443-minimum-time-to-collect-all-apples-in-a-tree.md b/solutions/lc-solutions/1400-1499/1443-minimum-time-to-collect-all-apples-in-a-tree.md new file mode 100644 index 0000000..e85ac05 --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1443-minimum-time-to-collect-all-apples-in-a-tree.md @@ -0,0 +1,279 @@ +--- +id: minimum-time-to-collect-all-apples-in-a-tree +title: Minimum Time to Collect All Apples in a Tree +sidebar_label: 1443. Minimum Time to Collect All Apples in a Tree + +tags: +- Hash Table +- Tree +- Depth-First Search +- Breadth-First Search + +description: "This is a solution to the Minimum Time to Collect All Apples in a Tree problem on LeetCode." +--- + +## Problem Description +Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex. + +The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple. +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_2.png) +``` +Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false] +Output: 6 +Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. +``` + +**Example 2:** +![image](https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_2.png) +``` +Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false] +Output: 8 +Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. +``` + + +### Constraints +- `1 <= n <= 10^5` +- `edges.length == n - 1` +- `edges[i].length == 2` +- `0 <= ai < bi <= n - 1` +- `hasApple.length == n` + +## Solution for Diagonal Traverse II Problem +### Approach +The problem can be solved using Depth-First Search (DFS). The main idea is to traverse the tree, and whenever an apple is found in a subtree, add the cost of traveling to and from that subtree to the total time. If a subtree does not contain any apples, it can be skipped. + +#### Steps to Solve +1. **Construct the Adjacency List**: + - Create an adjacency list to represent the tree from the given edges. + +2. **Depth-First Search (DFS)**: + - Perform a DFS starting from the root node (0). + - For each node, recursively calculate the total travel cost for its children. + - If a child node has an apple, include the travel cost of going to the child and returning to the current node (cost of 2). + - Mark the current node as having an apple if any of its children have apples, ensuring that the parent nodes consider the travel costs for collecting apples from their subtrees. + +3. **Return the Result**: + - The DFS function returns the total travel cost required to collect all apples and return to the root node. + + + + #### Implementation + ```jsx live + function Solution(arr) { + function dfs(adj, hasApple, node, parent) { + let distance = 0; + for (let i of adj[node]) { + if (i !== parent) { + let temp = dfs(adj, hasApple, i, node); + if (hasApple[i]) { + distance += (2 + temp); + hasApple[node] = true; + } + } + } + return distance; + } + + function minTime(n, edges, hasApple) { + let adj = Array.from({ length: n }, () => []); + for (let [u, v] of edges) { + adj[u].push(v); + adj[v].push(u); + } + return dfs(adj, hasApple, 0, 0); + } + const input = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false] + const output = minTime(input , edges , hasApple) + return ( +
+

+ Input: + {JSON.stringify(input)} + edges: + {JSON.stringify(edges)} + hasApple: + {JSON.stringify(hasApple)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(m*n) $ + - Space Complexity: $ O(m*n)$ + + ## Code in Different Languages + + + + ```javascript + class Solution { + dfs(adj, hasApple, node, parent) { + let distance = 0; + for (let i of adj[node]) { + if (i !== parent) { + let temp = this.dfs(adj, hasApple, i, node); + if (hasApple[i]) { + distance += (2 + temp); + hasApple[node] = true; + } + } + } + return distance; + } + + minTime(n, edges, hasApple) { + let adj = Array.from({ length: n }, () => []); + for (let [u, v] of edges) { + adj[u].push(v); + adj[v].push(u); + } + return this.dfs(adj, hasApple, 0, 0); + } +} + + ``` + + + + + ```typescript + class Solution { + private dfs(adj: number[][], hasApple: boolean[], node: number, parent: number): number { + let distance = 0; + for (let i of adj[node]) { + if (i !== parent) { + let temp = this.dfs(adj, hasApple, i, node); + if (hasApple[i]) { + distance += (2 + temp); + hasApple[node] = true; + } + } + } + return distance; + } + + minTime(n: number, edges: number[][], hasApple: boolean[]): number { + let adj: number[][] = Array.from({ length: n }, () => []); + for (let [u, v] of edges) { + adj[u].push(v); + adj[v].push(u); + } + return this.dfs(adj, hasApple, 0, 0); + } +} + + ``` + + + + ```python + class Solution: + def dfs(self, adj, hasApple, node, parent): + distance = 0 + for i in adj[node]: + if i != parent: + temp = self.dfs(adj, hasApple, i, node) + if hasApple[i]: + distance += 2 + temp + hasApple[node] = True + return distance + + def minTime(self, n, edges, hasApple): + adj = [[] for _ in range(n)] + for u, v in edges: + adj[u].append(v) + adj[v].append(u) + return self.dfs(adj, hasApple, 0, 0) + + ``` + + + + + ```java + import java.util.*; + +class Solution { + public int dfs(List[] adj, List hasApple, int node, int parent) { + int distance = 0; + for (int i : adj[node]) { + if (i != parent) { + int temp = dfs(adj, hasApple, i, node); + if (hasApple.get(i)) { + distance += 2 + temp; + hasApple.set(node, true); + } + } + } + return distance; + } + + public int minTime(int n, List> edges, List hasApple) { + List[] adj = new ArrayList[n]; + for (int i = 0; i < n; i++) { + adj[i] = new ArrayList<>(); + } + for (List edge : edges) { + int u = edge.get(0); + int v = edge.get(1); + adj[u].add(v); + adj[v].add(u); + } + return dfs(adj, hasApple, 0, 0); + } +} + + ``` + + + + + ```cpp +class Solution { +public: + int dfs(vector adj[], vector &hasApple, int node, int parent) { + int distance = 0; + for(auto i:adj[node]) { + if(i!=parent) { + int temp=dfs(adj, hasApple, i, node); + if(hasApple[i]) { + distance+=(2+temp); + hasApple[node]=true; + } + } + } + return distance; + } + + int minTime(int n, vector>& edges, vector& hasApple) { + vector adj[n]; + for(int i=0;i + + +
+
+ +## References + +- **LeetCode Problem**: [Minimum Time to Collect All Apples in a Tree](https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/description/) + diff --git a/solutions/lc-solutions/1400-1499/1450-Number-Of-Students-Doing-Homework-At-A-Given-Time.md b/solutions/lc-solutions/1400-1499/1450-Number-Of-Students-Doing-Homework-At-A-Given-Time.md new file mode 100644 index 0000000..c13723c --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1450-Number-Of-Students-Doing-Homework-At-A-Given-Time.md @@ -0,0 +1,168 @@ +--- +id: number-of-students-doing-homework-at-a-given-time +title: Number of Students Doing Homework at a Given Time +sidebar_label: 1450-Number-Of-Students-Doing-Homework-At-A-Given-Time +tags: + - Array + +definition: This is problem no. 1450 on leetcode. the problem is finding the Number of Students Doing Homework at a Given Time +--- + +## Problem Description +Given two integer arrays `startTime` and `endTime` and given an integer `queryTime`. + +The `ith` student started doing their homework at the time `startTime[i]` and finished it at time `endTime[i]`. + +Return the number of students doing their homework at time `queryTime`. More formally, return the number of students where `queryTime` lays in the interval `[startTime[i], endTime[i]]` inclusive. + + +### Example + +**Example 1:** +``` +Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4 +Output: 1 +Explanation: We have 3 students where: +The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4. +The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4. +The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4. +``` +**Example 2:** +``` +Input: startTime = [4], endTime = [4], queryTime = 4 +Output: 1 +Explanation: The only student was doing their homework at the queryTime. +``` +### Constraints + +- `1 <= startTime[i] <= endTime[i] <= 1000` + +## Solution Approach + +### Intuition: + +To efficiently determine the Number of Students Doing Homework at a Given Time +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + +class Solution { + busyStudent(startTime, endTime, queryTime) { + let n = endTime.length; + let cnt = 0; + for (let i = 0; i < n; i++) { + if (startTime[i] <= queryTime && queryTime <= endTime[i]) { + cnt++; + } else if (startTime[i] === queryTime || endTime[i] === queryTime) { + cnt++; + } + } + return cnt; + } +} + + + ``` + + + + + ```typescript + +class Solution { + busyStudent(startTime: number[], endTime: number[], queryTime: number): number { + let n = endTime.length; + let cnt = 0; + for (let i = 0; i < n; i++) { + if (startTime[i] <= queryTime && queryTime <= endTime[i]) { + cnt++; + } else if (startTime[i] === queryTime || endTime[i] === queryTime) { + cnt++; + } + } + return cnt; + } +} + + + + + + ``` + + + + + ```python +class Solution: + def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int: + n = len(endTime) + cnt = 0 + for i in range(n): + if startTime[i] <= queryTime <= endTime[i]: + cnt += 1 + elif startTime[i] == queryTime or endTime[i] == queryTime: + cnt += 1 + return cnt + + + + + ``` + + + + + ```java +public class Solution { + public int busyStudent(int[] startTime, int[] endTime, int queryTime) { + int n = endTime.length; + int cnt = 0; + for (int i = 0; i < n; i++) { + if (startTime[i] <= queryTime && queryTime <= endTime[i]) { + cnt++; + } else if (startTime[i] == queryTime || endTime[i] == queryTime) { + cnt++; + } + } + return cnt; + } +} + + + + ``` + + + + + ```cpp + + class Solution { + public: + int busyStudent(vector& startTime, vector& endTime, int queryTime) { + int n = endTime.size(); + int cnt = 0; + for(int i=0; i + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(n)$$ where n is the length of the input arrays startTime and endTime. This is because the algorithm iterates over the arrays once, performing a constant amount of work for each element. +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/1400-1499/1480-running-sum-of-1d-array.md b/solutions/lc-solutions/1400-1499/1480-running-sum-of-1d-array.md new file mode 100644 index 0000000..9e8de7a --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1480-running-sum-of-1d-array.md @@ -0,0 +1,111 @@ +--- +id: running-sum-of-1d-array +title: Running Sum of 1d Array +sidebar_label: 1480-Running Sum of 1d Array +tags: + - Array + - Prefix sum + +description: "This is a solution to the Running Sum of 1d Array in leetcode" +--- + +## Problem Description + +Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). +Return the running sum of nums. + + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,3,4] +Output: [1,3,6,10] +Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. +``` +**Example 2:** +``` +Input: nums = [1,1,1,1,1] +Output: [1,2,3,4,5] +Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]. + ``` +## Complexity Analysis + +*** Time Complexity:** $O(n)$ + +*** Space Complexity:** $O(n)$ + +### Constraints + +- ` 1<= nums.length <= 1000` +- `10^6 <= nums[i] <= 10^6` + + + +### Solution +## Approach +The approach involves creating a result array of the same length as the input array, initialized to 1. We maintain a cumulative sum variable (sum1) that starts at 0. As we iterate through the input array, we update each element of the result array to be the current element plus the cumulative sum, then update the cumulative sum by adding the current element. This process ensures that each element in the result array represents the running sum of the input array up to that point. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + std::vector runningSum(std::vector& nums) { + std::vector res(nums.size(), 1); + int sum1 = 0; + for (int i = 0; i < nums.size(); ++i) { + res[i] = nums[i] + sum1; + sum1 += nums[i]; + } + return res; + } +}; + +``` + + + + +```java +class Solution { + public int[] runningSum(int[] nums) { + int[] res = new int[nums.length]; + int sum1 = 0; + for (int i = 0; i < nums.length; i++) { + res[i] = nums[i] + sum1; + sum1 += nums[i]; + } + return res; + } +} + +``` + + + + +```python +class Solution: + def runningSum(self, nums: List[int]) -> List[int]: + res=[1]*(len(nums)) + sum1=0 + for i in range(len(nums)): + res[i]=nums[i]+sum1 + sum1+=nums[i] + return res + +``` + + + +## References + +- **LeetCode Problem**: [Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array/description/) + +- **Solution Link**: [Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array/post-solution/?submissionId=1192409834) diff --git a/solutions/lc-solutions/1400-1499/1483 - Kth Ancestor of a Tree Node.md b/solutions/lc-solutions/1400-1499/1483 - Kth Ancestor of a Tree Node.md new file mode 100644 index 0000000..03ac7f8 --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1483 - Kth Ancestor of a Tree Node.md @@ -0,0 +1,151 @@ +--- +id: kth-ancestor-of-a-tree node +title: Kth Ancestor of a Tree Node +sidebar_label: 1483 Kth Ancestor of a Tree Node +tags: +- Java +- Binary Search +- Dynamic Programming +- Tree +- Depth-First Search +- Breadth-First Search +- Design +description: "This document provides a solution where we Find the kth ancestor of a given node." +--- + +## Problem + +You are given a tree with $n$ nodes numbered from $0$ to $n - 1$ in the form of a parent array parent where $parent[i]$ is the parent of $i^{\text{th}}$ node. The root of the tree is node $0$. Find the $k^{\text{th}}$ ancestor of a given node. + +The $k^{\text{th}}$ ancestor of a tree node is the $k^{\text{th}}$ node in the path from that node to the root node. + +Implement the $TreeAncestor$ class: + +- $TreeAncestor(int n, int[] parent)$ Initializes the object with the number of nodes in the tree and the parent array. + +- $int getKthAncestor(int node, int k)$ return the $k^{\text{th}}$ ancestor of the given node node. If there is no such ancestor, return $-1$. + +### Examples + +**Example 1:** + +![image](https://github.com/vivekvardhan2810/codeharborhub.github.io/assets/91594529/c96383bd-e0bb-494d-8112-226686ab1832) + +**Input:** ["TreeAncestor", "getKthAncestor", "getKthAncestor", "getKthAncestor"] +[[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]] + +**Output:** [null, 1, 0, -1] + +**Explanation:** + +TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]); + +treeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3 + +treeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5 + +treeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor + +### Constraints + +- $1 <= k <= n <= 5 * 10^4$ +- $parent.length == n$ +- $parent[0] == -1$ +- $0 <= parent[i] < n$ for all $0 < i < n$ +- $0 <= node < n$ +- There will be at most $5 * 10^4$ queries. +--- + +## Approach + +To solve the problem, we need to understand the nature of the allowed moves: + +1. **Binary Lifting Setup**: + + - Calculate the maximum power of 2 needed, which is $\log_2(n)$. This represents the maximum number of jumps we need to consider. + + - Create a 2D array **'dp'** where **'dp[i][j]'** represents the $2^j$-th ancestor of node i. + +2. **Preprocessing**: + + - Initialize **'dp[i][0]'** with the parent of node i. + + - Fill in the rest of the **'dp'** table using dynamic programming. For each power j, compute **'dp[i][j]'** using **'dp[i][j-1]'**. Specifically, **'dp[i][j]'** is $2^j$-th ancestor of node i, which is the $2^j-1$-th ancestor of node i. + +3. **Query Processing**: + + - For each query to find the π‘˜-th ancestor of a node, use the binary representation of π‘˜. For each bit that is set in π‘˜, jump accordingly using the **'dp'** table. + + - If at any point the ancestor becomes $'-1'$, return $'-1'$. + +## Solution for Kth Ancestor of a Tree Node + +- The goal is to find the $k^{\text{th}}$ ancestor of a node efficiently. A naive approach would involve iterating up the tree one node at a time, which would be too slow for large values of k. Instead, we use a technique called "binary lifting". + +- Binary lifting allows us to jump in powers of two, which significantly speeds up the process. By preprocessing the tree, we can answer each query in logarithmic time. + +#### Code in Java + +```java +import java.util.*; + +class TreeAncestor { + private int[][] dp; + private int maxPower; + + public TreeAncestor(int n, int[] parent) { + maxPower = (int) (Math.log(n) / Math.log(2)) + 1; + dp = new int[n][maxPower]; + + for (int i = 0; i < n; i++) { + dp[i][0] = parent[i]; + } + + for (int j = 1; j < maxPower; j++) { + for (int i = 0; i < n; i++) { + int midAncestor = dp[i][j - 1]; + if (midAncestor != -1) { + dp[i][j] = dp[midAncestor][j - 1]; + } else { + dp[i][j] = -1; + } + } + } + } + + public int getKthAncestor(int node, int k) { + for (int j = 0; j < maxPower; j++) { + if ((k & (1 << j)) > 0) { + node = dp[node][j]; + if (node == -1) { + return -1; + } + } + } + return node; + } + + public static void main(String[] args) { + TreeAncestor treeAncestor = new TreeAncestor(7, new int[]{-1, 0, 0, 1, 1, 2, 2}); + System.out.println(treeAncestor.getKthAncestor(3, 1)); // returns 1 + System.out.println(treeAncestor.getKthAncestor(5, 2)); // returns 0 + System.out.println(treeAncestor.getKthAncestor(6, 3)); // returns -1 + } +} +``` + +### Complexity Analysis + +#### Time Complexity: $O(n log n)$ + +> **Reason**: Initializing the dp array requires iterating through all nodes for each power of 2 up to log𝑛, where as coming to query it involves checking up to log 𝑛 bits in the binary representation of π‘˜ and making jumps accordingly. + +#### Space Complexity: $O(log n)$ + +> **Reason**: The space complexity is $O(log n)$, The **'dp'** table requires 𝑛 Γ— log𝑛, where 𝑛 is the number of nodes and log𝑛 is the maximum power of 2 we consider. + +# References + +- **LeetCode Problem:** [Kth Ancestor of a Tree Node](https://leetcode.com/problems/kth-ancestor-of-a-tree-node/description/) +- **Solution Link:** [Kth Ancestor of a Tree Node Solution on LeetCode](https://leetcode.com/problems/kth-ancestor-of-a-tree-node/solutions/) +- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/vivekvardhan43862/) diff --git a/solutions/lc-solutions/1400-1499/1497-check-if-array-pairs-are-divisible-by-k.md b/solutions/lc-solutions/1400-1499/1497-check-if-array-pairs-are-divisible-by-k.md new file mode 100644 index 0000000..a7eabc4 --- /dev/null +++ b/solutions/lc-solutions/1400-1499/1497-check-if-array-pairs-are-divisible-by-k.md @@ -0,0 +1,262 @@ +--- +id: check-if-array-pairs-are-divisible-by-k +title: Check If Array Pairs Are Divisible by k +sidebar_label: 1497. Check If Array Pairs Are Divisible by k + +tags: +- Array +- Sliding Window +- Hashmap + +description: "This is a solution to the Check If Array Pairs Are Divisible by k problem on LeetCode." +--- + +## Problem Description +Given an array of integers arr of even length n and an integer k. +We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k. +Return true If you can find a way to do that or false otherwise. + +### Examples + +**Example 1:** +``` +Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5 +Output: true +Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10). +``` + +**Example 2:** +``` +Input: arr = [1,2,3,4,5,6], k = 7 +Output: true +Explanation: Pairs are (1,6),(2,5) and(3,4). +``` + +**Example 3:** +``` +Input: arr = [1,2,3,4,5,6], k = 10 +Output: false +Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10. +``` +### Constraints +- `arr.length == n` +- `1 <= n <= 10^5` +- n is even. +- `-10^9 <= arr[i] <= 10^9` +- `1 <= k <= 10^5` + +## Solution for Subarray Sums Divisible by K Problem +### Approach +#### Calculate Remainders: + +- For each number in the array, calculate its remainder when divided by k. +- Adjust the remainder to be non-negative using the formula ((num % k) + k) % k. +#### Count Remainders: + +- Use a hash map (or dictionary) to count the frequency of each remainder. +#### Check Pairs: + +- For each unique remainder, check if there exists a complement remainder such that their sums are divisible by k. + +#### Special Cases: +- If the remainder is 0, there must be an even number of such elements because each must pair with another 0 to be divisible by k. +- For other remainders, ensure that the count of the remainder is equal to the count of its complement (k - remainder). +#### Return the Result: +- If all conditions are satisfied, return true. Otherwise, return false. + + + + #### Implementation + ```jsx live + function Solution(arr) { + var canArrange = function(arr, k) { + const mp = new Map(); + for (let num of arr) { + let remainder = ((num % k) + k) % k; + mp.set(remainder, (mp.get(remainder) || 0) + 1); + } + + for (let [remainder, count] of mp.entries()) { + if (remainder === 0) { + if (count % 2 !== 0) return false; + } else { + let complement = k - remainder; + if (mp.get(remainder) !== mp.get(complement)) { + return false; + } + } + } + return true; + }; + + const input = [1,2,3,4,5,10,6,7,8,9] + const k = 5 + const output = canArrange(input , k) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(n) $ + - Space Complexity: $ O(k)$ + + ## Code in Different Languages + + + + ```javascript + var canArrange = function(arr, k) { + const mp = new Map(); + for (let num of arr) { + let remainder = ((num % k) + k) % k; + mp.set(remainder, (mp.get(remainder) || 0) + 1); + } + + for (let [remainder, count] of mp.entries()) { + if (remainder === 0) { + if (count % 2 !== 0) return false; + } else { + let complement = k - remainder; + if (mp.get(remainder) !== mp.get(complement)) { + return false; + } + } + } + return true; +}; + + ``` + + + + + ```typescript + function canArrange(arr: number[], k: number): boolean { + const mp: Map = new Map(); + for (let num of arr) { + let remainder = ((num % k) + k) % k; + mp.set(remainder, (mp.get(remainder) || 0) + 1); + } + + for (let [remainder, count] of mp.entries()) { + if (remainder === 0) { + if (count % 2 !== 0) return false; + } else { + let complement = k - remainder; + if (mp.get(remainder) !== mp.get(complement)) { + return false; + } + } + } + return true; +} + + ``` + + + + ```python + from collections import defaultdict + +class Solution: + def canArrange(self, arr, k): + mp = defaultdict(int) + for num in arr: + remainder = ((num % k) + k) % k + mp[remainder] += 1 + + for remainder, count in mp.items(): + if remainder == 0: + if count % 2 != 0: + return False + else: + complement = k - remainder + if mp[remainder] != mp[complement]: + return False + return True + + ``` + + + + + ```java + import java.util.HashMap; +import java.util.Map; + +class Solution { + public boolean canArrange(int[] arr, int k) { + Map mp = new HashMap<>(); + for (int num : arr) { + int remainder = ((num % k) + k) % k; + mp.put(remainder, mp.getOrDefault(remainder, 0) + 1); + } + + for (Map.Entry entry : mp.entrySet()) { + int remainder = entry.getKey(); + int count = entry.getValue(); + if (remainder == 0) { + if (count % 2 != 0) return false; + } else { + int complement = k - remainder; + if (!mp.get(remainder).equals(mp.get(complement))) { + return false; + } + } + } + return true; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + bool canArrange(vector& arr, int k) { + map mp; + for (auto num : arr) { + int remainder = ((num % k) + k) % k; + mp[remainder]++; + } + + for (auto [remainder, count] : mp) { + if (remainder == 0) { + if (count % 2 != 0) return false; + } else { + int complement = k - remainder; + if (mp[remainder] != mp[complement]) { + return false; + } + } + } + return true; + } +}; +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Check If Array Pairs Are Divisible by k](https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/solutions) + diff --git a/solutions/lc-solutions/1400-1499/_category_.json b/solutions/lc-solutions/1400-1499/_category_.json new file mode 100644 index 0000000..732bded --- /dev/null +++ b/solutions/lc-solutions/1400-1499/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "1400-1499", + "position": 16, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (1400 - 1499)" + } +} diff --git a/solutions/lc-solutions/1500-1599/0671-secong-min-node-in-binary-tree.md b/solutions/lc-solutions/1500-1599/0671-secong-min-node-in-binary-tree.md new file mode 100644 index 0000000..0e3f538 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/0671-secong-min-node-in-binary-tree.md @@ -0,0 +1,208 @@ +--- +id: secong-min-node-in-binary-tree +title: Second Minimum Node in Binary Tree +sidebar_label: 671-Second Minimum Node in Binary Tree +tags: [Leet code] +description: "Solution to leetocde 671" +--- + +## Problem Statement + +Given a non-empty special binary tree consisting of nodes with non-negative values, where each node in this tree has exactly two or zero sub-nodes. If a node has two sub-nodes, then the node's value is the smaller value among its two sub-nodes. More formally, the property `root.val = min(root.left.val, root.right.val)` always holds. + +Given such a binary tree, you need to output the second minimum value in the set made of all the node values in the whole tree. + +If no such second minimum value exists, output -1 instead. + +## Examples + +### Example 1 + +**Input:** `root = [2,2,5,null,null,5,7]` +**Output:** `5` +**Explanation:** The smallest value is 2, the second smallest value is 5. + +### Example 2 + +**Input:** `root = [2,2,2]` +**Output:** `-1` +**Explanation:** The smallest value is 2, but there isn't any second smallest value. + +## Constraints + +- $The number of nodes in the tree is in the range [1, 25].$ +- $1<= Node.val <= 231 - 1$ +- $root.val == min(root.left.val, root.right.val) for each internal node of the tree.$ + +## Python Code + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right + +import sys + +class Solution: + def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int: + if not root: + return -1 + + smallest = root.val + secondSmallest = sys.maxsize + stack = [root] + + while stack: + node = stack.pop() + if node.left: + if node.left.val != smallest: + secondSmallest = min(secondSmallest, node.left.val) + stack.append(node.left) + + if node.right: + if node.right.val != smallest: + secondSmallest = min(secondSmallest, node.right.val) + stack.append(node.right) + + return secondSmallest if secondSmallest != sys.maxsize else -1 +``` + +## C++ Code + +```cpp +#include +#include +#include + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + int findSecondMinimumValue(TreeNode* root) { + if (!root) return -1; + + int smallest = root->val; + long secondSmallest = LONG_MAX; + std::stack stack; + stack.push(root); + + while (!stack.empty()) { + TreeNode* node = stack.top(); + stack.pop(); + + if (node->left) { + if (node->left->val != smallest) { + secondSmallest = std::min(secondSmallest, (long)node->left->val); + } + stack.push(node->left); + } + + if (node->right) { + if (node->right->val != smallest) { + secondSmallest = std::min(secondSmallest, (long)node->right->val); + } + stack.push(node->right); + } + } + + return secondSmallest == LONG_MAX ? -1 : (int)secondSmallest; + } +}; +``` + +## Java Code + +```java +import java.util.Stack; + +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +class Solution { + public int findSecondMinimumValue(TreeNode root) { + if (root == null) return -1; + + int smallest = root.val; + long secondSmallest = Long.MAX_VALUE; + Stack stack = new Stack<>(); + stack.push(root); + + while (!stack.isEmpty()) { + TreeNode node = stack.pop(); + + if (node.left != null) { + if (node.left.val != smallest) { + secondSmallest = Math.min(secondSmallest, node.left.val); + } + stack.push(node.left); + } + + if (node.right != null) { + if (node.right.val != smallest) { + secondSmallest = Math.min(secondSmallest, node.right.val); + } + stack.push(node.right); + } + } + + return secondSmallest == Long.MAX_VALUE ? -1 : (int) secondSmallest; + } +} +``` + +## JavaScript Code + +```javascript +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ + +/** + * @param {TreeNode} root + * @return {number} + */ +var findSecondMinimumValue = function (root) { + if (!root) return -1; + + let smallest = root.val; + let secondSmallest = Number.MAX_SAFE_INTEGER; + let stack = [root]; + + while (stack.length) { + let node = stack.pop(); + + if (node.left) { + if (node.left.val !== smallest) { + secondSmallest = Math.min(secondSmallest, node.left.val); + } + stack.push(node.left); + } + + if (node.right) { + if (node.right.val !== smallest) { + secondSmallest = Math.min(secondSmallest, node.right.val); + } + stack.push(node.right); + } + } + + return secondSmallest === Number.MAX_SAFE_INTEGER ? -1 : secondSmallest; +}; +``` diff --git a/solutions/lc-solutions/1500-1599/1503-Last Moment Before All Ants Fall Out of a Plank.md b/solutions/lc-solutions/1500-1599/1503-Last Moment Before All Ants Fall Out of a Plank.md new file mode 100644 index 0000000..c9b8f35 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1503-Last Moment Before All Ants Fall Out of a Plank.md @@ -0,0 +1,351 @@ +--- + +id: last-moment-before-all-ants-fall-out-of-a-plank +title: Last Moment Before All Ants Fall Out of a Plank +sidebar_label: 1503-Last-Moment-Before-All-Ants-Fall-Out-Of-A-Plank +tags: + - Simulation + - LeetCode + - Python + - JavaScript + - TypeScript + - Java + - C++ +description: "This is a solution to the Last Moment Before All Ants Fall Out of a Plank problem on LeetCode." + +--- + +In this page, we will solve the Last Moment Before All Ants Fall Out of a Plank problem using different approaches: a simple maximum calculation for left and right ants. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +We have a wooden plank of the length `n` units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the others move to the right. + +When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. + +When an ant reaches one end of the plank at a time `t`, it falls out of the plank immediately. + +Given an integer `n` and two integer arrays `left` and `right`, the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank. + +### Examples + +**Example 1:** + +```plaintext +Input: n = 4, left = [4,3], right = [0,1] +Output: 4 +Explanation: +- The ant at index 0 is named A and going to the right. +- The ant at index 1 is named B and going to the right. +- The ant at index 3 is named C and going to the left. +- The ant at index 4 is named D and going to the left. +The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank). +``` + +**Example 2:** + +```plaintext +Input: n = 7, left = [], right = [0,1,2,3,4,5,6,7] +Output: 7 +Explanation: All ants are going to the right, the ant at index 0 needs 7 seconds to fall. +``` + +**Example 3:** + +```plaintext +Input: n = 7, left = [0,1,2,3,4,5,6,7], right = [] +Output: 7 +Explanation: All ants are going to the left, the ant at index 7 needs 7 seconds to fall. +``` + +### Constraints + +- $1 <= n <= 10^4$ +- $0 <= left.length <= n + 1$ +- $0 <= left[i] <= n$ +- $0 <= right.length <= n + 1$ +- $0 <= right[i] <= n$ +- $1 <= left.length + right.length <= n + 1$ +- All values of `left` and `right` are unique, and each value can appear only in one of the two arrays. + +--- + +## Solution for Last Moment Before All Ants Fall Out of a Plank + +### Intuition and Approach + +The key insight is that we can ignore the direction changes of ants when they meet. The last ant to fall off will be either the furthest ant moving to the left or the furthest ant moving to the right. Therefore, we need to find the maximum distance any ant has to travel to fall off the plank. + + + + +### Approach 1: Maximum Calculation + +We calculate the maximum distance for the ants moving to the left and to the right and return the larger of the two. + +#### Implementation + +```jsx live +function lastMomentBeforeAllAntsFallOut() { + const n = 4; + const left = [4, 3]; + const right = [0, 1]; + + const getLastMoment = function(n, left, right) { + const maxLeft = left.length > 0 ? Math.max(...left) : 0; + const maxRight = right.length > 0 ? n - Math.min(...right) : 0; + return Math.max(maxLeft, maxRight); + }; + + const result = getLastMoment(n, left, right); + return ( +
+

+ Input: n = {n}, left = {JSON.stringify(left)}, right = {JSON.stringify(right)} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function getLastMoment(n, left, right) { + const maxLeft = left.length > 0 ? Math.max(...left) : 0; + const maxRight = right.length > 0 ? n - Math.min(...right) : 0; + return Math.max(maxLeft, maxRight); + } + ``` + + + + + ```typescript + function getLastMoment(n: number, left: number[], right: number[]): number { + const maxLeft = left.length > 0 ? Math.max(...left) : 0; + const maxRight = right.length > 0 ? n - Math.min(...right) : 0; + return Math.max(maxLeft, maxRight); + } + ``` + + + + + ```python + class Solution: + def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int: + max_left = max(left) if left else 0 + max_right = n - min(right) if right else 0 + return max(max_left, max_right) + ``` + + + + + ```java + class Solution { + public int getLastMoment(int n, int[] left, int[] right) { + int maxLeft = left.length > 0 ? Arrays.stream(left).max().getAsInt() : 0; + int maxRight = right.length > 0 ? n - Arrays.stream(right).min().getAsInt() : 0; + return Math.max(maxLeft, maxRight); + } + } + ``` + + + + + ```cpp + class Solution { + public: + int getLastMoment(int n, vector& left, vector& right) { + int maxLeft = left.empty() ? 0 : *max_element(left.begin(), left.end()); + int maxRight = right.empty() ? 0 : n - *min_element(right.begin(), right.end()); + return max(maxLeft, maxRight); + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(L + R)$$, where `L` is the length of the `left` array and `R` is the length of the `right` array. +- Space Complexity: $$O(1)$$, as we are only using a few extra variables. + +
+ + + +### Approach 2: Simulation + +We can simulate the movement of ants on the plank to observe their behavior and determine the last moment before all ants fall off. + +#### Implementation + +```jsx live +function lastMomentBeforeAllAntsFallOut() { + const n = 4; + const left = [4, 3]; + const right = [0, 1]; + + const getLastMoment = function(n, left, right) { + const positions = Array(n + 1).fill(0); + for (let pos of left) positions[pos] = 1; + for (let pos of right) positions[pos] = 2; + + let lastMoment = 0; + for (let i = 0; i <= n; i++) { + if (positions[i] === 1) lastMoment = Math.max(lastMoment, i); + if (positions[i] === 2) lastMoment = Math.max(lastMoment, n - i); + } + return lastMoment; + }; + + const result = getLastMoment(n, left, right); + return ( +
+

+ Input: n = {n}, left = {JSON.stringify(left)}, right = {JSON.stringify(right)} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function get + +LastMoment(n, left, right) { + const positions = Array(n + 1).fill(0); + for (let pos of left) positions[pos] = 1; + for (let pos of right) positions[pos] = 2; + + let lastMoment = 0; + for (let i = 0; i <= n; i++) { + if (positions[i] === 1) lastMoment = Math.max(lastMoment, i); + if (positions[i] === 2) lastMoment = Math.max(lastMoment, n - i); + } + return lastMoment; + } + ``` + + + + + ```typescript + function getLastMoment(n: number, left: number[], right: number[]): number { + const positions = Array(n + 1).fill(0); + for (let pos of left) positions[pos] = 1; + for (let pos of right) positions[pos] = 2; + + let lastMoment = 0; + for (let i = 0; i <= n; i++) { + if (positions[i] === 1) lastMoment = Math.max(lastMoment, i); + if (positions[i] === 2) lastMoment = Math.max(lastMoment, n - i); + } + return lastMoment; + } + ``` + + + + + ```python + class Solution: + def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int: + positions = [0] * (n + 1) + for pos in left: + positions[pos] = 1 + for pos in right: + positions[pos] = 2 + + last_moment = 0 + for i in range(n + 1): + if positions[i] == 1: + last_moment = max(last_moment, i) + if positions[i] == 2: + last_moment = max(last_moment, n - i) + return last_moment + ``` + + + + + ```java + class Solution { + public int getLastMoment(int n, int[] left, int[] right) { + int[] positions = new int[n + 1]; + for (int pos : left) positions[pos] = 1; + for (int pos : right) positions[pos] = 2; + + int lastMoment = 0; + for (int i = 0; i <= n; i++) { + if (positions[i] == 1) lastMoment = Math.max(lastMoment, i); + if (positions[i] == 2) lastMoment = Math.max(lastMoment, n - i); + } + return lastMoment; + } + } + ``` + + + + + ```cpp + class Solution { + public: + int getLastMoment(int n, vector& left, vector& right) { + vector positions(n + 1, 0); + for (int pos : left) positions[pos] = 1; + for (int pos : right) positions[pos] = 2; + + int lastMoment = 0; + for (int i = 0; i <= n; i++) { + if (positions[i] == 1) lastMoment = max(lastMoment, i); + if (positions[i] == 2) lastMoment = max(lastMoment, n - i); + } + return lastMoment; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(L + R)$$, where `L` is the length of the `left` array and `R` is the length of the `right` array. +- Space Complexity: $$O(N)$$, where `N` is the length of the plank. + +
+
+ +:::tip + +By using a simple maximum calculation approach or a simulation approach, we can efficiently solve the Last Moment Before All Ants Fall Out of a Plank problem. The choice of implementation language depends on the specific requirements and constraints of the problem. + +::: + +## References + +- **LeetCode Problem:** [Last Moment Before All Ants Fall Out of a Plank](https://leetcode.com/problems/last-moment-before-all-ants-fall-out-of-a-plank/) +- **Solution Link:** [Last Moment Before All Ants Fall Out of a Plank Solution on LeetCode](https://leetcode.com/problems/last-moment-before-all-ants-fall-out-of-a-plank/solution/) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + diff --git a/solutions/lc-solutions/1500-1599/1506-Find-Root-Of-N-Ary-Tree.md b/solutions/lc-solutions/1500-1599/1506-Find-Root-Of-N-Ary-Tree.md new file mode 100644 index 0000000..17a54f9 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1506-Find-Root-Of-N-Ary-Tree.md @@ -0,0 +1,520 @@ +--- + +id: find-root-of-n-ary-tree +title: Find Root of N-Ary Tree +sidebar_label: 1506-Find-Root-Of-N-Ary-Tree +tags: + - Tree + - LeetCode + - Python + - JavaScript + - TypeScript + - Java + - C++ +description: "This is a solution to the Find Root of N-Ary Tree problem on LeetCode." + +--- + +In this page, we will solve the Find Root of N-Ary Tree problem using different approaches: counting the degree of each node and a hash set approach. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +You are given all the nodes of an `N`-ary tree as an array of `Node` objects, where each node has a unique value. + +Return the root of the `N`-ary tree. + +Each `Node` object has the following properties: + +- `int val`: the value of the node. +- `List children`: the list of children of the node. + +### Examples + +**Example 1:** + +```plaintext +Input: +Input: [1, null, 3, 2, 4, null, 5, 6] +Output: 1 +Explanation: The root of the tree is 1. +``` + +**Example 2:** + +```plaintext +Input: +Input: [1, null, 2, 3, 4, 5, null, null, 6, 7, null, 8, null, 9, 10, null, null, 11, null, 12, null, 13, null, null, 14] +Output: 1 +Explanation: The root of the tree is 1. +``` + +### Constraints + +- The total number of nodes is between `[1, 5 * 10^4]`. + +--- + +## Solution for Find Root of N-Ary Tree + +### Intuition and Approach + +To find the root of an N-ary tree, we can use the following approaches: + +1. **Counting the Degree**: In this approach, we count the in-degrees (number of times a node appears as a child) of all nodes. The node with an in-degree of zero is the root. +2. **Hash Set**: We use a hash set to keep track of all nodes and another hash set for all children nodes. The difference between these sets will give us the root node. + + + + +### Approach 1: Counting the Degree + +#### Implementation + +```jsx live +function findRootOfNAryTree() { + class Node { + constructor(val) { + this.val = val; + this.children = []; + } + } + + const nodes = [ + new Node(1), + new Node(2), + new Node(3), + new Node(4), + new Node(5), + new Node(6) + ]; + + nodes[0].children = [nodes[1], nodes[2], nodes[3]]; + nodes[1].children = [nodes[4], nodes[5]]; + + const findRoot = function(treeNodes) { + const inDegree = new Map(); + for (const node of treeNodes) { + if (!inDegree.has(node)) { + inDegree.set(node, 0); + } + for (const child of node.children) { + inDegree.set(child, (inDegree.get(child) || 0) + 1); + } + } + for (const [node, degree] of inDegree) { + if (degree === 0) return node; + } + return null; + }; + + const root = findRoot(nodes); + return ( +
+

+ Input: {JSON.stringify(nodes.map(node => node.val))} +

+

+ Output: {root ? root.val : null} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function findRoot(treeNodes) { + const inDegree = new Map(); + for (const node of treeNodes) { + if (!inDegree.has(node)) { + inDegree.set(node, 0); + } + for (const child of node.children) { + inDegree.set(child, (inDegree.get(child) || 0) + 1); + } + } + for (const [node, degree] of inDegree) { + if (degree === 0) return node; + } + return null; + } + ``` + + + + + ```typescript + function findRoot(treeNodes: Node[]): Node | null { + const inDegree = new Map(); + for (const node of treeNodes) { + if (!inDegree.has(node)) { + inDegree.set(node, 0); + } + for (const child of node.children) { + inDegree.set(child, (inDegree.get(child) || 0) + 1); + } + } + for (const [node, degree] of inDegree) { + if (degree === 0) return node; + } + return null; + } + ``` + + + + + ```python + class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children if children is not None else [] + + class Solution: + def findRoot(self, tree: List['Node']) -> 'Node': + in_degree = {node: 0 for node in tree} + for node in tree: + for child in node.children: + in_degree[child] += 1 + for node, degree in in_degree.items(): + if degree == 0: + return node + return None + ``` + + + + + ```java + import java.util.*; + + class Node { + public int val; + public List children; + + public Node() {} + + public Node(int val) { + this.val = val; + } + + public Node(int val, List children) { + this.val = val; + this.children = children; + } + } + + class Solution { + public Node findRoot(List tree) { + Map inDegree = new HashMap<>(); + for (Node node : tree) { + inDegree.putIfAbsent(node, 0); + for (Node child : node.children) { + inDegree.put(child, inDegree.getOrDefault(child, 0) + 1); + } + } + for (Map.Entry entry : inDegree.entrySet()) { + if (entry.getValue() == 0) { + return entry.getKey(); + } + } + return null; + } + } + ``` + + + + + ```cpp + #include + #include + + using namespace std; + + class Node { + public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } + }; + + class Solution { + public: + Node* findRoot(vector tree) { + unordered_map inDegree; + for (Node* node : tree) { + if (inDegree.find(node) == inDegree.end()) { + inDegree[node] = 0; + } + for (Node* child : node->children) { + inDegree[child]++; + } + } + for (auto& entry : inDegree) { + if (entry.second == 0) { + return entry.first; + } + } + return nullptr; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(N)$$, where `N` is the number of nodes in the tree. +- Space Complexity: $$O(N)$$, for storing the in-degree map. + +
+ + + +### Approach 2: Hash Set + +#### Implementation + +```jsx live +function findRootOfNAryTree() { + class Node { + constructor(val) { + this.val = val; + this.children = []; + } + } + + const nodes = [ + new Node(1), + new Node(2), + new Node(3), + new Node(4), + new Node(5), + new Node(6) + ]; + + nodes[0].children = [nodes[1], nodes[2], nodes[3]]; + nodes[1].children = [nodes[4], nodes[5]]; + + const findRoot = function(treeNodes) { + const allNodes = new Set(treeNodes); + const childrenNodes = new Set(); + for (const node of treeNodes) { + for (const child of node.children) { + childrenNodes.add(child); + } + } + for (const node of treeNodes) { + if (!childrenNodes.has(node)) { + return node; + } + } + return null; + }; + + const root = findRoot(nodes); + return ( +
+

+ Input: {JSON.stringify(nodes.map(node => node.val))} +

+

+ Output: {root ? root.val : null} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function findRoot(treeNodes) { + const allNodes = new Set(treeNodes); + const childrenNodes = new Set(); + for (const node of treeNodes) { + for (const child of node.children) { + childrenNodes.add(child); + } + } + for (const node of treeNodes) { + if (!childrenNodes.has(node)) { + return node; + } + } + return null; + } + ``` + + + + + ```typescript + function findRoot(treeNodes: Node[]): Node | null { + const allNodes = new Set(treeNodes); + const childrenNodes = new Set(); + for (const node of treeNodes) { + for (const child of node.children) { + childrenNodes.add(child); + } + } + for (const node of treeNodes) { + if (!childrenNodes.has(node)) { + return node; + } + } + return null; + } + ``` + + + + + ```python + class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children if children is not None else [] + + class Solution: + def findRoot(self, tree: List['Node']) -> 'Node': + all_nodes = set(tree) + children_nodes = set() + for node in tree: + for child in node.children: + children_nodes.add(child) + for node in tree: + if node not in children_nodes: + return node + return None + ``` + + + + + ```java + import java.util.*; + + class Node { + public int val; + public List children; + + public Node() {} + + public Node(int val) { + this.val = val; + } + + public Node(int val, List children) { + this.val = val; + this.children = children; + } + } + + class Solution { + public Node findRoot(List tree) { + Set allNodes = new HashSet<>(tree); + Set childrenNodes = new HashSet<>(); + for (Node node : tree) { + for (Node child : node.children) { + childrenNodes.add(child); + } + } + for (Node node : tree) { + if (!childrenNodes.contains(node)) { + return node; + } + } + return null; + } + } + ``` + + + + + ```cpp + #include + #include + + using namespace std; + + class Node { + public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } + }; + + class Solution { + public: + Node* findRoot(vector tree) { + unordered_set allNodes(tree.begin(), tree.end()); + unordered_set childrenNodes; + for (Node* node : tree) { + for (Node* child : node->children) { + childrenNodes.insert(child); + } + } + for (Node* node : tree) { + if (childrenNodes.find(node) == childrenNodes.end()) { + return node; + } + } + return nullptr; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(N)$$, where `N` is the number of nodes in the tree. +- Space Complexity: $$O(N)$$, for storing the sets of all nodes and children nodes. + +
+
+ +:::tip Note + +By using both counting the degree and hash set approaches, we can efficiently find the root of an N-ary tree. The choice between the two approaches depends on the specific requirements and constraints of the problem. + +::: + +## References + +- **LeetCode Problem:** [Find Root of N-Ary Tree](https://leetcode.com/problems/find-root-of-n-ary-tree/) +- **Solution Link:** [Find Root of N-Ary Tree Solution on LeetCode](https://leetcode.com/problems/find-root-of-n-ary-tree/solution/) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + diff --git a/solutions/lc-solutions/1500-1599/1508-Range Sum of Sorted Subarray Sums.md b/solutions/lc-solutions/1500-1599/1508-Range Sum of Sorted Subarray Sums.md new file mode 100644 index 0000000..6a3b9d1 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1508-Range Sum of Sorted Subarray Sums.md @@ -0,0 +1,1035 @@ +--- + +id: range-sum-of-sorted-subarray-sums +title: Range Sum of Sorted Subarray Sums +sidebar_label: 1508-Range-Sum-Of-Sorted-Subarray-Sums +tags: + - Array + - Prefix Sum + - Sorting + - LeetCode + - Python + - JavaScript + - TypeScript + - Java + - C++ +description: "This is a solution to the Range Sum of Sorted Subarray Sums problem on LeetCode." + +--- + +In this page, we will solve the Range Sum of Sorted Subarray Sums problem using different approaches: calculating all subarray sums and sorting them, and using a min-heap for efficiency. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +You are given the array `nums` consisting of `n` positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of $n * (n + 1) / 2$ numbers. + +Return the sum of the numbers from index `left` to index `right` (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo $(10^9 + 7)$. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [1,2,3,4], n = 4, left = 1, right = 5 +Output: 13 +Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index left = 1 to right = 5 is 1 + 2 + 3 + 3 + 4 = 13. +``` + +**Example 2:** + +```plaintext +Input: nums = [1,2,3,4], n = 4, left = 3, right = 4 +Output: 6 +Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index left = 3 to right = 4 is 3 + 3 = 6. +``` + +**Example 3:** + +```plaintext +Input: nums = [1,2,3,4], n = 4, left = 1, right = 10 +Output: 50 +``` + +### Constraints + +- $n == nums.length$ +- $1 <= nums.length <= 1000$ +- $1 <= nums[i] <= 100$ +- $1 <= left <= right <= n * (n + 1) / 2$ + +--- +## Explanation +There are three main approaches discussed: + +1. **Naive Approach**: + - Calculate all possible subarray sums and store them in a list. + - Sort the list of subarray sums. + - Calculate the sum of the range of sorted subarray sums from `left` to `right`. + +2. **Min-Heap Approach**: + - Use a min-heap to store the subarray sums dynamically. + - Extract the minimum elements from the heap for the required range and sum them up. + +3. **Fenwick Tree Approach**: + - Use a Fenwick Tree to manage prefix sums. + - Calculate subarray sums based on prefix sums. + - Sort the subarray sums and sum the elements in the required range. + + +## Solution for Range Sum of Sorted Subarray Sums + +### Intuition and Approach + +To solve the problem, we can use two approaches: + +1. **Brute Force Approach**: Calculate all subarray sums, sort them, and then find the sum of the specified range. +2. **Optimized Approach Using Min-Heap**: Use a min-heap to keep track of the smallest sums and avoid sorting the entire list of subarray sums. + + + + +### Approach 1: Brute Force + +#### Implementation + +```jsx live +function rangeSumNaive() { + function rangeSum(nums, n, left, right) { + const MOD = 1e9 + 7; + const allSums = []; + + for (let i = 0; i < n; i++) { + let sum = 0; + for (let j = i; j < n; j++) { + sum += nums[j]; + allSums.push(sum); + } + } + + allSums.sort((a, b) => a - b); + + let result = 0; + for (let i = left - 1; i < right; i++) { + result = (result + allSums[i]) % MOD; + } + + return result; + } + + const nums = [1, 2, 3, 4]; + const n = 4, left = 1, right = 5; + const result = rangeSum(nums, n, left, right); + + return ( +
+

+ Input: {JSON.stringify(nums)} +

+

+ Output: {result} +

+
+ ); +} + +``` + +#### Code in Different Languages + + + + + ```javascript + function rangeSumOfSortedSubarraySums(nums, n, left, right) { + const MOD = 1e9 + 7; + const subarraySums = []; + + for (let i = 0; i < n; i++) { + let sum = 0; + for (let j = i; j < n; j++) { + sum += nums[j]; + subarraySums.push(sum); + } + } + + subarraySums.sort((a, b) => a - b); + + let result = 0; + for (let i = left - 1; i < right; i++) { + result = (result + subarraySums[i]) % MOD; + } + + return result; + } + ``` + + + + + ```typescript + function rangeSumOfSortedSubarraySums(nums: number[], n: number, left: number, right: number): number { + const MOD = 1e9 + 7; + const subarraySums: number[] = []; + + for (let i = 0; i < n; i++) { + let sum = 0; + for (let j = i; j < n; j++) { + sum += nums[j]; + subarraySums.push(sum); + } + } + + subarraySums.sort((a, b) => a - b); + + let result = 0; + for (let i = left - 1; i < right; i++) { + result = (result + subarraySums[i]) % MOD; + } + + return result; + } + ``` + + + + + ```python + from typing import List + + class Solution: + def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int: + MOD = 10**9 + 7 + subarray_sums = [] + + for i in range(n): + sum = 0 + for j in range(i, n): + sum += nums[j] + subarray_sums.append(sum) + + subarray_sums.sort() + + result = 0 + for i in range(left - 1, right): + result = (result + subarray_sums[i]) % MOD + + return result + + ``` + + + + + ```java + import java.util.*; + + class Solution { + public int rangeSum(int[] nums, int n, int left, int right) { + final int MOD = 1000000007; + List subarraySums = new ArrayList<>(); + + for (int i = 0; i < n; i++) { + int sum = 0; + for (int j = i; j < n; j++) { + sum += nums[j]; + subarraySums.add(sum); + } + } + + Collections.sort(subarraySums); + + int result = 0; + for (int i = left - 1; i < right; i++) { + result = (result + subarraySums.get(i)) % MOD; + } + + return result; + } + + } + ``` + + + + + ```cpp + #include + #include + + using namespace std; + + class Solution { + public: + int rangeSum(vector& nums, int n, int left, int right) { + const int MOD = 1e9 + 7; + vector subarraySums; + + for (int i = 0; i < n; ++i) { + int sum = 0; + for (int j = i; j < n; ++j) { + sum += nums[j]; + subarraySums.push_back(sum); + } + } + + sort(subarraySums.begin(), subarray + +Sums.end()); + + int result = 0; + for (int i = left - 1; i < right; ++i) { + result = (result + subarraySums[i]) % MOD; + } + + return result; + } + }; + + + ``` + + + + +
+ + + +### Approach 2: Min-Heap + +#### Explanation + +The min-heap approach can optimize the time complexity. Instead of calculating all subarray sums and sorting them, we use a min-heap to keep track of the smallest sums. + +#### Implementation + +```jsx live +function rangeSumMinHeap() { + function rangeSum(nums, n, left, right) { + const MOD = 1e9 + 7; + const minHeap = []; + + for (let i = 0; i < n; ++i) { + let sum = 0; + for (let j = i; j < n; ++j) { + sum += nums[j]; + minHeap.push(sum); + } + } + + minHeap.sort((a, b) => a - b); + + let result = 0; + for (let i = 0; i < right; ++i) { + const minSum = minHeap[i]; + if (i >= left - 1) { + result = (result + minSum) % MOD; + } + } + + return result; + } + + const nums = [1, 2, 3, 4]; + const n = 4, left = 1, right = 5; + const result = rangeSum(nums, n, left, right); + + return ( +
+

+ Input: {JSON.stringify(nums)} +

+

+ Output: {result} +

+
+ ); +} +``` + + + + ```javascript + class MinHeap { + constructor() { + this.heap = []; + } + + insert(val) { + this.heap.push(val); + this.bubbleUp(); + } + + bubbleUp() { + let index = this.heap.length - 1; + const current = this.heap[index]; + + while (index > 0) { + const parentIndex = Math.floor((index - 1) / 2); + const parent = this.heap[parentIndex]; + if (current >= parent) break; + this.heap[index] = parent; + index = parentIndex; + } + + this.heap[index] = current; + } + + extractMin() { + const min = this.heap[0]; + const end = this.heap.pop(); + if (this.heap.length > 0) { + this.heap[0] = end; + this.sinkDown(0); + } + return min; + } + + sinkDown(index) { + const length = this.heap.length; + const element = this.heap[index]; + while (true) { + let leftChildIndex = 2 * index + 1; + let rightChildIndex = 2 * index + 2; + let leftChild, rightChild; + let swap = null; + + if (leftChildIndex < length) { + leftChild = this.heap[leftChildIndex]; + if (leftChild < element) swap = leftChildIndex; + } + + if (rightChildIndex < length) { + rightChild = this.heap[rightChildIndex]; + if ( + (swap === null && rightChild < element) || + (swap !== null && rightChild < leftChild) + ) { + swap = rightChildIndex; + } + } + + if (swap === null) break; + this.heap[index] = this.heap[swap]; + index = swap; + } + + this.heap[index] = element; + } + } + + function rangeSumOfSortedSubarraySums(nums, n, left, right) { + const MOD = 1e9 + 7; + const heap = new MinHeap(); + + for (let i = 0; i < n; i++) { + let sum = 0; + for (let j = i; j < n; j++) { + sum += nums[j]; + heap.insert(sum); + } + } + + let result = 0; + for (let i = 0; i < right; i++) { + let minSum = heap.extractMin(); + if (i >= left - 1) { + result = (result + minSum) % MOD; + } + } + + return result; + } + + + ``` + + + + + ```typescript + class MinHeap { + heap: number[]; + + constructor() { + this.heap = []; + } + + insert(val: number): void { + this.heap.push(val); + this.bubbleUp(); + } + + bubbleUp(): void { + let index = this.heap.length - 1; + const current = this.heap[index]; + + while (index > 0) { + const parentIndex = Math.floor((index - 1) / 2); + const parent = this.heap[parentIndex]; + if (current >= parent) break; + this.heap[index] = parent; + index = parentIndex; + } + + this.heap[index] = current; + } + + extractMin(): number { + const min = this.heap[0]; + const end = this.heap.pop(); + if (this.heap.length > 0) { + this.heap[0] = end!; + this.sinkDown(0); + } + return min; + } + + sinkDown(index: number): void { + const length = this.heap.length; + const element = this.heap[index]; + while (true) { + let leftChildIndex = 2 * index + 1; + let rightChildIndex = 2 * index + 2; + let leftChild, rightChild; + let swap = null; + + if (leftChildIndex < length) { + leftChild = this.heap[leftChildIndex]; + if (leftChild < element) swap = leftChildIndex; + } + + if (rightChildIndex < length) { + rightChild = this.heap[rightChildIndex]; + if ( + (swap === null && rightChild < element) || + (swap !== null && rightChild < leftChild) + ) { + swap = rightChildIndex; + } + } + + if (swap === null) break; + this.heap[index] = this.heap[swap]; + index = swap; + } + + this.heap[index] = element; + } + } + + function rangeSumOfSortedSubarraySums(nums: number[], n: number, left: number, right: number): number { + const MOD = 1e9 + 7; + const heap = new MinHeap(); + + for (let i = 0; i < n; i++) { + let sum = 0; + for (let j = i; j < n; j++) { + sum += nums[j]; + heap.insert(sum); + } + } + + let result = 0; + for (let i = 0; i < right; i++) { + let minSum = heap.extractMin(); + if (i >= left - 1) { + result = (result + minSum) % MOD; + } + } + + return result; + } + + + ``` + + + + + ```python + import heapq + from typing import List + + class Solution: + def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int: + MOD = 10**9 + 7 + min_heap = [] + + for i in range(n): + sum = 0 + for j in range(i, n): + sum += nums[j] + heapq.heappush(min_heap, sum) + + result = 0 + for i in range(right): + min_sum = heapq.heappop(min_heap) + if i >= left - 1: + result = (result + min_sum) % MOD + + return result + + ``` + + + + + ```java + import java.util.PriorityQueue; + + class Solution { + public int rangeSum(int[] nums, int n, int left, int right) { + final int MOD = 1000000007; + PriorityQueue minHeap = new PriorityQueue<>(); + + for (int i = 0; i < n; i++) { + int sum = 0; + for (int j = i; j < n; j++) { + sum += nums[j]; + minHeap.offer(sum); + } + } + + int result = 0; + for (int i = 0; i < right; i++) { + int minSum = minHeap.poll(); + if (i >= left - 1) { + result = (result + minSum) % MOD; + } + } + + return result; + } + + + } + ``` + + + + + ```cpp + #include + #include + + using namespace std; + + class Solution { + public: + int rangeSum(vector& nums + +, int n, int left, int right) { + const int MOD = 1e9 + 7; + priority_queue, greater> minHeap; + + for (int i = 0; i < n; ++i) { + int sum = 0; + for (int j = i; j < n; ++j) { + sum += nums[j]; + minHeap.push(sum); + } + } + + int result = 0; + for (int i = 0; i < right; ++i) { + int minSum = minHeap.top(); + minHeap.pop(); + if (i >= left - 1) { + result = (result + minSum) % MOD; + } + } + + return result; + } + }; + + + ``` + + + + +
+ + + +### Approach 3: Fenwick Tree + +#### Explanation + +Using a Fenwick Tree (or Binary Indexed Tree) can efficiently manage the prefix sums and query the range sum. + +#### Implementation + +```jsx live +function rangeSumFenwickTree() { + class FenwickTree { + constructor(size) { + this.size = size; + this.tree = Array(size + 1).fill(0); + } + + update(index, value) { + while (index <= this.size) { + this.tree[index] += value; + index += index & -index; + } + } + + query(index) { + let sum = 0; + while (index > 0) { + sum += this.tree[index]; + index -= index & -index; + } + return sum; + } + } + + function rangeSumOfSortedSubarraySums(nums, n, left, right) { + const MOD = 1e9 + 7; + let prefixSum = Array(n + 1).fill(0); + let allSums = []; + + for (let i = 0; i < n; i++) { + prefixSum[i + 1] = prefixSum[i] + nums[i]; + } + + for (let i = 0; i <= n; i++) { + for (let j = i + 1; j <= n; j++) { + allSums.push(prefixSum[j] - prefixSum[i]); + } + } + + allSums.sort((a, b) => a - b); + let result = 0; + + for (let i = left - 1; i < right; i++) { + result = (result + allSums[i]) % MOD; + } + + return result; + } + + const nums = [1, 2, 3, 4]; + const n = 4, left = 1, right = 5; + const result = rangeSumOfSortedSubarraySums(nums, n, left, right); + + return ( +
+

+ Input: {JSON.stringify(nums)} +

+

+ Output: {result} +

+
+ ); +} + +``` + + + + + ```javascript + class FenwickTree { + constructor(size) { + this.size = size; + this.tree = Array(size + 1).fill(0); + } + + update(index, value) { + while (index <= this.size) { + this.tree[index] += value; + index += index & -index; + } + } + + query(index) { + let sum = 0; + while (index > 0) { + sum += this.tree[index]; + index -= index & -index; + } + return sum; + } + } + + function rangeSumOfSortedSubarraySums(nums, n, left, right) { + const MOD = 1e9 + 7; + let prefixSum = Array(n + 1).fill(0); + let allSums = []; + + for (let i = 0; i < n; i++) { + prefixSum[i + 1] = prefixSum[i] + nums[i]; + } + + for (let i = 0; i <= n; i++) { + for (let j = i + 1; j <= n; j++) { + allSums.push(prefixSum[j] - prefixSum[i]); + } + } + + allSums.sort((a, b) => a - b); + let result = 0; + + for (let i = left - 1; i < right; i++) { + result = (result + allSums[i]) % MOD; + } + + return result; + } + + ``` + + + + + ```typescript + class FenwickTree { + size: number; + tree: number[]; + + constructor(size: number) { + this.size = size; + this.tree = Array(size + 1).fill(0); + } + + update(index: number, value: number): void { + while (index <= this.size) { + this.tree[index] += value; + index += index & -index; + } + } + + query(index: number): number { + let sum = 0; + while (index > 0) { + sum += this.tree[index]; + index -= index & -index; + } + return sum; + } + } + + function rangeSumOfSortedSubarraySums(nums: number[], n: number, left: number, right: number): number { + const MOD = 1e9 + 7; + let prefixSum = Array(n + 1).fill(0); + let allSums: number[] = []; + + for (let i = 0; i < n; i++) { + prefixSum[i + 1] = prefixSum[i] + nums[i]; + } + + for (let i = 0; i <= n; i++) { + for (let j = i + 1; j <= n; j++) { + allSums.push(prefixSum[j] - prefixSum[i]); + } + } + + allSums.sort((a, b) => a - b); + let result = 0; + + for (let i = left - 1; i < right; i++) { + result = (result + allSums[i]) % MOD; + } + + return result; + } + + ``` + + + + + ```python + class FenwickTree: + def __init__(self, size: int): + self.size = size + self.tree = [0] * (size + 1) + + def update(self, index: int, value: int): + while index <= self.size: + self.tree[index] += value + index += index & -index + + def query(self, index: int) -> int: + sum = 0 + while index > 0: + sum += self.tree[index] + index -= index & -index + return sum + + def rangeSumOfSortedSubarraySums(nums, n, left, right): + MOD = 10**9 + 7 + prefix_sum = [0] * (n + 1) + all_sums = [] + + for i in range(n): + prefix_sum[i + 1] = prefix_sum[i] + nums[i] + + for i in range(n + 1): + for j in range(i + 1, n + 1): + all_sums.append(prefix_sum[j] - prefix_sum[i]) + + all_sums.sort() + result = 0 + + for i in range(left - 1, right): + result = (result + all_sums[i]) % MOD + + return result + + + ``` + + + + + ```java + import java.util.Arrays; + + class FenwickTree { + private int[] tree; + private int size; + + public FenwickTree(int size) { + this.size = size; + this.tree = new int[size + 1]; + } + + public void update(int index, int value) { + while (index <= size) { + tree[index] += value; + index += index & -index; + } + } + + public int query(int index) { + int sum = 0; + while (index > 0) { + sum += tree[index]; + index -= index & -index; + } + return sum; + } + } + + class Solution { + public int rangeSum(int[] nums, int n, int left, int right) { + final int MOD = 1000000007; + int[] prefixSum = new int[n + 1]; + int[] allSums = new int[n * (n + 1) / 2]; + int k = 0; + + for (int i = 0; i < n; i++) { + prefixSum[i + 1] = prefixSum[i] + nums[i]; + } + + for (int i = 0; i <= n; i++) { + for (int j = i + 1; j <= n; j++) { + allSums[k++] = prefixSum[j] - prefixSum[i]; + } + } + + Arrays.sort(allSums); + int result = 0; + + for (int i = left - 1; i < right; i++) { + result = (result + allSums[i]) % MOD; + } + + return result; + } + + + } + ``` + + + + + ```cpp + #include + #include + + using namespace std; + + class FenwickTree { + public: + FenwickTree(int size) : tree(size + 1, 0), size(size) {} + + void update(int index, int value) { + while (index <= size) { + tree[index] += value; + index += index & -index; + } + } + + + + int query(int index) const { + int sum = 0; + while (index > 0) { + sum += tree[index]; + index -= index & -index; + } + return sum; + } + + private: + vector tree; + int size; + }; + + class Solution { + public: + int rangeSum(vector& nums, int n, int left, int right) { + const int MOD = 1e9 + 7; + vector prefixSum(n + 1, 0); + vector allSums(n * (n + 1) / 2); + int k = 0; + + for (int i = 0; i < n; ++i) { + prefixSum[i + 1] = prefixSum[i] + nums[i]; + } + + for (int i = 0; i <= n; ++i) { + for (int j = i + 1; j <= n; ++j) { + allSums[k++] = prefixSum[j] - prefixSum[i]; + } + } + + sort(allSums.begin(), allSums.end()); + int result = 0; + + for (int i = left - 1; i < right; ++i) { + result = (result + allSums[i]) % MOD; + } + + return result; + } + }; + + + ``` + + + + +
+
+ + +:::tip +Each approach has its own time and space complexity considerations. The naive approach is simple but may be inefficient for large inputs. The min-heap approach optimizes the process of finding the smallest subarray sums. The Fenwick Tree approach efficiently manages prefix sums but requires understanding of Fenwick Tree operations. +::: + +## References + +- **LeetCode Problem:** [Range Sum of Sorted Subarray Sums](https://leetcode.com/problems/range-sum-of-sorted-subarray-sums/description/) +- **Solution Link:** [Range Sum of Sorted Subarray Sums Solution on LeetCode](https://leetcode.com/problems/range-sum-of-sorted-subarray-sums/solution/) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + diff --git a/solutions/lc-solutions/1500-1599/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves.md b/solutions/lc-solutions/1500-1599/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves.md new file mode 100644 index 0000000..bf9e776 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1509-minimum-difference-between-largest-and-smallest-value-in-three-moves.md @@ -0,0 +1,149 @@ +--- +id: minimum-difference-between-largest-and-smallest-value-in-three-moves +title: Minimum Difference Between Largest And Smallest in Three Moves +sidebar_label: 1509-Minimum Difference Between Largest And Smallest in Three Moves +tags: + - Leet code +description: "Solution to leetocde 1509" +--- + +## Problem Statement + +You are given an integer array `nums`. + +In one move, you can choose one element of `nums` and change it to any value. + +Return the minimum difference between the largest and smallest value of `nums` after performing at most three moves. + +## Examples + +### Example 1 + +**Input:** `nums = [5,3,2,4]` +**Output:** `0` +**Explanation:** + +1. Change 2 to 3: `nums` becomes `[5,3,3,4]`. +2. Change 4 to 3: `nums` becomes `[5,3,3,3]`. +3. Change 5 to 3: `nums` becomes `[3,3,3,3]`. + After 3 moves, the difference between the minimum and maximum is `3 - 3 = 0`. + +### Example 2 + +**Input:** `nums = [1,5,0,10,14]` +**Output:** `1` +**Explanation:** + +1. Change 5 to 0: `nums` becomes `[1,0,0,10,14]`. +2. Change 10 to 0: `nums` becomes `[1,0,0,0,14]`. +3. Change 14 to 1: `nums` becomes `[1,0,0,0,1]`. + After 3 moves, the difference between the minimum and maximum is `1 - 0 = 1`. + +### Example 3 + +**Input:** `nums = [3,100,20]` +**Output:** `0` +**Explanation:** + +1. Change 100 to 7: `nums` becomes `[3,7,20]`. +2. Change 20 to 7: `nums` becomes `[3,7,7]`. +3. Change 3 to 7: `nums` becomes `[7,7,7]`. + After 3 moves, the difference between the minimum and maximum is `7 - 7 = 0`. + +## Constraints + +- $1 <= nums.length <= 105$ +- $-109 <= nums[i] <= 109$ + +## Algorithm + +1. If the length of `nums` is less than or equal to 4, return 0 because we can change all elements to be the same. +2. Sort the array `nums`. +3. Consider the 4 smallest and 4 largest elements from the sorted array: + - The potential moves would be: + - Remove the 3 largest elements and keep the smallest 1. + - Remove the 2 largest elements and the smallest 1, keeping the next smallest 2. + - Remove the 1 largest element and the smallest 2, keeping the next smallest 3. + - Remove the 3 smallest elements and keep the largest 1. +4. Return the minimum difference among these potential moves. + +## C++ Code + +```cpp +#include +#include + +using namespace std; + +class Solution { +public: + int minDifference(vector& nums) { + int n = nums.size(); + if (n <= 4) return 0; + + sort(nums.begin(), nums.end()); + + int result = INT_MAX; + for (int i = 0; i <= 3; ++i) { + result = min(result, nums[n - 4 + i] - nums[i]); + } + return result; + } +}; +``` + +## Python Code + +```python +class Solution: + def minDifference(self, nums: List[int]) -> int: + n = len(nums) + if n <= 4: + return 0 + + nums.sort() + + return min(nums[-4 + i] - nums[i] for i in range(4)) +``` + +## Java Code + +```java +import java.util.Arrays; + +class Solution { + public int minDifference(int[] nums) { + int n = nums.length; + if (n <= 4) return 0; + + Arrays.sort(nums); + + int result = Integer.MAX_VALUE; + for (int i = 0; i <= 3; ++i) { + result = Math.min(result, nums[n - 4 + i] - nums[i]); + } + return result; + } +} +``` + +## JavaScript Code + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var minDifference = function (nums) { + const n = nums.length; + if (n <= 4) return 0; + + nums.sort((a, b) => a - b); + + let result = Infinity; + for (let i = 0; i <= 3; ++i) { + result = Math.min(result, nums[n - 4 + i] - nums[i]); + } + return result; +}; +``` diff --git a/solutions/lc-solutions/1500-1599/1512-number-of-good-pairs.md b/solutions/lc-solutions/1500-1599/1512-number-of-good-pairs.md new file mode 100644 index 0000000..65aa0b2 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1512-number-of-good-pairs.md @@ -0,0 +1,230 @@ +--- +id: number-of-good-pairs +title: 1512 Number of Good Pairs +sidebar_label: 1512-number-of-good-paris +tags: +- Array +- Hash Table +- Counting + +description: "This is a solution to the Number of Good Pairs problem on LeetCode." +--- + +## Problem Description +Given an array of integers `nums`, return the number of **good pairs**. + +A pair `(i, j)` is called good if `nums[i] == nums[j]` and `i < j`. + +### Examples + +**Example 1:** +``` +Input: nums = [1,2,3,1,1,3] +Output: 4 +Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. +``` + +**Example 2:** + +``` +Input: nums = [1,1,1,1] +Output: 6 +Explination: Each pair in the array are good. +``` + +**Example 3:** + +``` +Input: nums = [1,2,3] +Output: 0 +``` + + +### Constraints +- `1 <= nums.length <= 100` +- `1 <= nums[i] <= 100` +## Solution for 1512. Number of Good Pairs Problem +### Approach + +#### Use a Hash Map to Track Frequencies: + +- Use a hash map (or dictionary) to keep track of the frequency of each element in the array as you iterate through it. +- For each element, before incrementing its frequency in the hash map, add the current frequency of that element to the count of good pairs. This is because each occurrence of an element forms good pairs with all previous occurrences of the same element. + +#### Iterate Through the Array: + +- As you iterate through the array, update the count of good pairs based on the frequency of the current element in the hash map. +- Update the frequency of the current element in the hash map. + +#### Return the Total Count of Good Pairs: + +- After processing all elements, the count of good pairs will be stored in a variable. + +#### Steps to Solve the Problem + +#### 1. Initialize Variables: + +- Create a hash map to store the frequency of each element. +- Initialize a variable to count the number of good pairs. + +#### 2. Iterate Through the Array: + +- For each element in the array, do the following: +- Check the current frequency of the element in the hash map. +- Add the current frequency to the count of good pairs. +- Increment the frequency of the element in the hash map. + +#### 3. Return the Result: + +- After the loop, the count variable will hold the number of good pairs. + + + + + #### Implementation + ```jsx live + function numIdenticalPairs(nums) { + const countMap = new Map(); + let goodPairs = 0; + + nums.forEach((num) => { + if (countMap.has(num)) { + goodPairs += countMap.get(num); + } + countMap.set(num, (countMap.get(num) || 0) + 1); + }); + + return goodPairs; + } + + const input = nums; + const output = numIdenticalPairs(input); + + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(N^2) $ + - Space Complexity: $ O(N)$ + + ## Code in Different Languages + + + + ```javascript + var numIdenticalPairs = function(nums) { + const countMap = new Map(); + let goodPairs = 0; + + nums.forEach((num) => { + if (countMap.has(num)) { + goodPairs += countMap.get(num); + } + countMap.set(num, (countMap.get(num) || 0) + 1); + }); + + return goodPairs; +}; + ``` + + + + + ```typescript + class Solution { + function numIdenticalPairs(nums: number[]): number { + const countMap = new Map(); + let goodPairs = 0; + + nums.forEach((num) => { + if (countMap.has(num)) { + goodPairs += countMap.get(num) as number; + } + countMap.set(num, (countMap.get(num) || 0) + 1); + }); + + return goodPairs; +} +} + + ``` + + + + ```python + class Solution: + def numIdenticalPairs(self, nums: List[int]) -> int: + count_map = {} + good_pairs = 0 + + for num in nums: + if num in count_map: + good_pairs += count_map[num] + count_map[num] = count_map.get(num, 0) + 1 + + return good_pairs + + ``` + + + + ```java + import java.util.HashMap; + +class Solution { + public int numIdenticalPairs(int[] nums) { + int[] count = new int[101]; + int goodPairs = 0; + + for (int num : nums) { + goodPairs += count[num]; + count[num]++; + } + + return goodPairs; + } +} + + ``` + + + + ```cpp + +class Solution { +public: + int numIdenticalPairs(std::vector& nums) { + std::unordered_map countMap; + int goodPairs = 0; + + for (int num : nums) { + goodPairs += countMap[num]++; + } + + return goodPairs; + } +}; + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Number of Good Pairs](https://leetcode.com/problems/number-of-good-pairs/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/number-of-good-pairs/description/) + diff --git a/solutions/lc-solutions/1500-1599/1514-path-with-maximum-probability.md b/solutions/lc-solutions/1500-1599/1514-path-with-maximum-probability.md new file mode 100644 index 0000000..70f102d --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1514-path-with-maximum-probability.md @@ -0,0 +1,354 @@ +--- +id: path-with-maximum-probability +title: Path with Maximum Probability +sidebar_label: 1514 - Path with Maximum Probability +tags: +- Array +- Graph +- Heap (Priority Queue) +- Shortest Path +description: "This is a solution to the Path with Maximum Probability problem on LeetCode." +--- + +## Problem Description +You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where `edges[i] = [a, b]` is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. + +Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. + +If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5. + +### Examples +**Example 1:** +![image](https://assets.leetcode.com/uploads/2019/09/20/1558_ex1.png) +``` +Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 +Output: 0.25000 +Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25. + +``` + +**Example 2:** +![image](https://assets.leetcode.com/uploads/2019/09/20/1558_ex2.png) + +``` +Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2 +Output: 0.30000 +``` + +### Constraints +- `2 <= n <= 10^4` +- `0 <= start, end < n` +- `start != end` +- `0 <= a, b < n` +- `a != b` +- `0 <= succProb.length == edges.length <= 2*10^4` +- `0 <= succProb[i] <= 1` +- `There is at most one edge between every two nodes.` +## Solution for Path with Maximum Probability Problem +### Approach +#### Main Intuition +The main intuition behind this code is similar to Dijkstra's algorithm for finding the shortest path, but instead of minimizing distances, it maximizes probabilities. The idea is to iteratively explore the most probable paths using a priority queue to always expand the most promising node (the node with the highest probability of being part of the maximum probability path to the end node). + +#### Graph Representation: + +- The graph is represented using an adjacency list. Each node has a list of pairs, where each pair consists of an adjacent node and the probability of successfully traversing the edge to that node. +#### Input Parsing: + +- The number of nodes (n) and the edges along with their respective probabilities (edges and succProb) are given as input. +- The start and end nodes are also provided. +#### Building the Graph: + +- A vector of vectors of pairs (adj) is created to store the adjacency list. +- For each edge, two entries are added to the adjacency list to ensure the graph is undirected. Each entry contains the adjacent node and the probability of traversing that edge. +#### Probability Initialization: + +- A prob vector is initialized to store the maximum probability of reaching each node from the start node. It is initialized to 0.0 for all nodes. +- The probability of reaching the start node from itself is set to 1.0 (prob[start] = 1.0). +#### Priority Queue for Processing Nodes: + +- A priority queue (pq) is used to process nodes. This queue helps in processing nodes in the order of their probabilities (although the current implementation uses a max-heap for integer priorities, which is not correct and should use a min-heap for probabilities). +#### Dijkstra-like Algorithm: + +- The algorithm processes nodes from the priority queue. For each node, it checks all its adjacent nodes. +- For each adjacent node, it calculates the probability of reaching it through the current node (prob[node] * probab). +- If this new probability is higher than the currently known probability for the adjacent node, it updates the probability and pushes the adjacent node into the priority queue. +#### Result: + +- After processing all reachable nodes, the maximum probability to reach the end node is found in prob[end]. + + + + #### Implementation + ```jsx live + function Solution(arr) { + var maxProbability = function(n, edges, succProb, start, end) { + const p = Array(n).fill(0); + const graph = p.reduce((m, _, i) => m.set(i, []), new Map()); + edges.forEach(([u, v], i) => { + graph.get(u).push([v, succProb[i]]); + graph.get(v).push([u, succProb[i]]); + }); + + const queue = [[start, 1]]; + p[start] = 1; + + for (let [node, currP] of queue) { + for (let [adj, nextP] of graph.get(node)) { + if (currP * nextP > p[adj]) { + p[adj] = currP * nextP; + queue.push([adj, p[adj]]); + } + } + } + + return p[end]; + }; + const input = [[0,1],[1,2],[0,2]] + const n = 3 + const succProb = [0.5,0.5,0.2] + const start=0; + const end =2 + const output = maxProbability(n, input , succProb,start , end) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(edges*log(n)) $ + - Space Complexity: $ O(n)$ + + ## Code in Different Languages + + + + ```javascript + function maxProbability(n, edges, succProb, start, end) { + let adj = Array.from({ length: n }, () => []); + + for (let i = 0; i < edges.length; i++) { + adj[edges[i][0]].push([edges[i][1], succProb[i]]); + adj[edges[i][1]].push([edges[i][0], succProb[i]]); + } + + let prob = new Array(n).fill(0.0); + let pq = new MaxPriorityQueue({ priority: x => x[1] }); + + prob[start] = 1.0; + pq.enqueue([start, 1.0]); + + while (!pq.isEmpty()) { + let [node, nodeProb] = pq.dequeue().element; + + for (let [adjNode, probab] of adj[node]) { + if (prob[node] * probab > prob[adjNode]) { + prob[adjNode] = prob[node] * probab; + pq.enqueue([adjNode, prob[adjNode]]); + } + } + } + + return prob[end]; +} + + ``` + + + + + ```typescript + class Solution { + maxProbability(n: number, edges: number[][], succProb: number[], start: number, end: number): number { + let adj: Array<[number, number][]> = Array.from({ length: n }, () => []); + + for (let i = 0; i < edges.length; i++) { + adj[edges[i][0]].push([edges[i][1], succProb[i]]); + adj[edges[i][1]].push([edges[i][0], succProb[i]]); + } + + let prob: number[] = new Array(n).fill(0.0); + let pq = new MaxPriorityQueue({ priority: (x: [number, number]) => x[1] }); + + prob[start] = 1.0; + pq.enqueue([start, 1.0]); + + while (!pq.isEmpty()) { + let [node, nodeProb] = pq.dequeue().element; + + for (let [adjNode, probab] of adj[node]) { + if (prob[node] * probab > prob[adjNode]) { + prob[adjNode] = prob[node] * probab; + pq.enqueue([adjNode, prob[adjNode]]); + } + } + } + + return prob[end]; + } +} + + ``` + + + + ```python + import heapq +from typing import List + +class Solution: + def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: + adj = [[] for _ in range(n)] + + for i in range(len(edges)): + adj[edges[i][0]].append((edges[i][1], succProb[i])) + adj[edges[i][1]].append((edges[i][0], succProb[i])) + + prob = [0.0] * n + pq = [] + + prob[start] = 1.0 + heapq.heappush(pq, (-1.0, start)) + + while pq: + nodeProb, node = heapq.heappop(pq) + nodeProb = -nodeProb + + for adjNode, probab in adj[node]: + if prob[node] * probab > prob[adjNode]: + prob[adjNode] = prob[node] * probab + heapq.heappush(pq, (-prob[adjNode], adjNode)) + + return prob[end] + + ``` + + + + + ```java + import java.util.*; + +class Solution { + public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) { + List>[] adj = new ArrayList[n]; + for (int i = 0; i < n; i++) { + adj[i] = new ArrayList<>(); + } + + for (int i = 0; i < edges.length; i++) { + adj[edges[i][0]].add(new Pair<>(edges[i][1], succProb[i])); + adj[edges[i][1]].add(new Pair<>(edges[i][0], succProb[i])); + } + + double[] prob = new double[n]; + PriorityQueue> pq = new PriorityQueue<>((a, b) -> Double.compare(b.getValue(), a.getValue())); + + prob[start] = 1.0; + pq.add(new Pair<>(start, 1.0)); + + while (!pq.isEmpty()) { + Pair nodePair = pq.poll(); + int node = nodePair.getKey(); + double nodeProb = nodePair.getValue(); + + for (Pair it : adj[node]) { + int adjNode = it.getKey(); + double probab = it.getValue(); + + if (prob[node] * probab > prob[adjNode]) { + prob[adjNode] = prob[node] * probab; + pq.add(new Pair<>(adjNode, prob[adjNode])); + } + } + } + + return prob[end]; + } + + static class Pair { + private final K key; + private final V value; + + public Pair(K key, V value) { + this.key = key; + this.value = value; + } + + public K getKey() { + return key; + } + + public V getValue() { + return value; + } + } +} + + ``` + + + + + ```cpp + class Solution { +public: + double maxProbability(int n, vector>& edges, vector& succProb, int start, int end) { + vector>adj[n]; + + for(int i=0;iprob(n,0.0); + priority_queue pq; + + prob[start]=1.0; + + pq.push(start); + + while(!pq.empty()) + { + int node= pq.top(); + pq.pop(); + + for(auto it: adj[node]) + { + int adjNode=it.first; + double probab=it.second; + + if(prob[node]*probab>prob[adjNode] ) + { + pq.push(adjNode); + prob[adjNode]=prob[node]*probab; + } + } + } + + return prob[end]; + } +}; +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Path with Maximum Probability](https://leetcode.com/problems/path-with-maximum-probability) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/path-with-maximum-probability/solutions) + diff --git a/solutions/lc-solutions/1500-1599/1518-Water-Bottles.md b/solutions/lc-solutions/1500-1599/1518-Water-Bottles.md new file mode 100644 index 0000000..07935cb --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1518-Water-Bottles.md @@ -0,0 +1,315 @@ +--- + +id: water-bottles +title: Water Bottles Solution +sidebar_label: 1518-Water-Bottles +tags: + - Greedy + - Simulation + - LeetCode + - Python + - Java + - C++ + - JavaScript +description: "This is a solution to the Water Bottles problem on LeetCode." + +--- + +In this page, we will solve the Water Bottles problem using different approaches: iterative simulation and a more optimized approach. We will provide the implementation of the solution in Python, Java, C++, JavaScript, and more. + +## Problem Description + +There are `numBottles` water bottles that are initially full of water. You can exchange `numExchange` empty water bottles from the market with one full water bottle. + +The operation of drinking a full water bottle turns it into an empty bottle. + +Given the two integers `numBottles` and `numExchange`, return the maximum number of water bottles you can drink. + +### Examples + +**Example 1:** + +```plaintext +Input: numBottles = 9, numExchange = 3 +Output: 13 +Explanation: You can exchange 3 empty bottles to get 1 full water bottle. +Number of water bottles you can drink: 9 + 3 + 1 = 13. +``` + +**Example 2:** + +```plaintext +Input: numBottles = 15, numExchange = 4 +Output: 19 +Explanation: You can exchange 4 empty bottles to get 1 full water bottle. +Number of water bottles you can drink: 15 + 3 + 1 = 19. +``` + +### Constraints + +- $1 <= numBottles <= 100$ +- $2 <= numExchange <= 100$ + +--- + +## Solution for Water Bottles Problem + +### Intuition and Approach + +The problem can be solved by simulating the process of drinking water bottles and exchanging empty ones for full ones until no more exchanges can be made. + + + + +### Approach 1: Iterative Simulation + +We iteratively drink the water bottles and exchange the empty ones until no more exchanges are possible. + +#### Implementation + +```jsx live +function maxBottles() { + const numBottles = 9; + const numExchange = 3; + + const maxWaterBottles = function(numBottles, numExchange) { + let totalDrank = numBottles; + let emptyBottles = numBottles; + + while (emptyBottles >= numExchange) { + const newBottles = Math.floor(emptyBottles / numExchange); + totalDrank += newBottles; + emptyBottles = emptyBottles % numExchange + newBottles; + } + + return totalDrank; + }; + + const result = maxWaterBottles(numBottles, numExchange); + return ( +
+

+ Input: numBottles = {numBottles}, numExchange = {numExchange} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function maxWaterBottles(numBottles, numExchange) { + let totalDrank = numBottles; + let emptyBottles = numBottles; + + while (emptyBottles >= numExchange) { + const newBottles = Math.floor(emptyBottles / numExchange); + totalDrank += newBottles; + emptyBottles = emptyBottles % numExchange + newBottles; + } + + return totalDrank; + } + ``` + + + + + ```typescript + function maxWaterBottles(numBottles: number, numExchange: number): number { + let totalDrank: number = numBottles; + let emptyBottles: number = numBottles; + + while (emptyBottles >= numExchange) { + const newBottles: number = Math.floor(emptyBottles / numExchange); + totalDrank += newBottles; + emptyBottles = emptyBottles % numExchange + newBottles; + } + + return totalDrank; + } + ``` + + + + + ```python + class Solution: + def numWaterBottles(self, numBottles: int, numExchange: int) -> int: + total_drank = numBottles + empty_bottles = numBottles + + while empty_bottles >= numExchange: + new_bottles = empty_bottles // numExchange + total_drank += new_bottles + empty_bottles = empty_bottles % numExchange + new_bottles + + return total_drank + ``` + + + + + ```java + class Solution { + public int numWaterBottles(int numBottles, int numExchange) { + int totalDrank = numBottles; + int emptyBottles = numBottles; + + while (emptyBottles >= numExchange) { + int newBottles = emptyBottles / numExchange; + totalDrank += newBottles; + emptyBottles = emptyBottles % numExchange + newBottles; + } + + return totalDrank; + } + } + ``` + + + + + ```cpp + class Solution { + public: + int numWaterBottles(int numBottles, int numExchange) { + int totalDrank = numBottles; + int emptyBottles = numBottles; + + while (emptyBottles >= numExchange) { + int newBottles = emptyBottles / numExchange; + totalDrank += newBottles; + emptyBottles = emptyBottles % numExchange + newBottles; + } + + return totalDrank; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(\log n)$$, where `n` is the initial number of bottles, due to the iterative division. +- Space Complexity: $$O(1)$$, as we are using a constant amount of extra space. + +
+ + + +### Approach 2: Optimized Approach + +We can derive a mathematical formula to calculate the total number of water bottles drank based on the initial number of bottles and the exchange rate. + +#### Implementation + +```jsx live +function maxBottles() { + const numBottles = 9; + const numExchange = 3; + + const maxWaterBottles = function(numBottles, numExchange) { + return numBottles + Math.floor((numBottles - 1) / (numExchange - 1)); + }; + + const result = maxWaterBottles(numBottles, numExchange); + return ( +
+

+ Input: numBottles = {numBottles}, numExchange = {numExchange} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function maxWaterBottles(numBottles, numExchange) { + return numBottles + Math.floor((numBottles - 1) / (numExchange - 1)); + } + ``` + + + + + ```typescript + function maxWaterBottles(numBottles: number, numExchange: number): number { + return numBottles + Math.floor((numBottles - 1) / (numExchange - 1)); + } + ``` + + + + + ```python + class Solution: + def numWaterBottles(self, numBottles: int, numExchange: int) -> int: + return numBottles + (numBottles - 1) // (numExchange - 1) + ``` + + + + + ```java + class Solution { + public int numWaterBottles(int numBottles, int numExchange) { + return numBottles + (num + +Bottles - 1) / (numExchange - 1); + } + } + ``` + + + + + ```cpp + class Solution { + public: + int numWaterBottles(int numBottles, int numExchange) { + return numBottles + (numBottles - 1) / (numExchange - 1); + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(1)$$, as we directly calculate the result using a formula. +- Space Complexity: $$O(1)$$, as we are using a constant amount of extra space. + +
+
+ +:::tip Note + +By using both iterative simulation and an optimized mathematical approach, we can efficiently solve the Water Bottles problem. The choice between the two approaches depends on the specific requirements and constraints of the problem. + +::: + +## References + +- **LeetCode Problem:** [Water Bottles](https://leetcode.com/problems/water-bottles/) +- **Solution Link:** [Water Bottles Solution on LeetCode](https://leetcode.com/problems/water-bottles/solution/) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + diff --git a/solutions/lc-solutions/1500-1599/1523-count-odd-numbers-in-an-interval-range.md b/solutions/lc-solutions/1500-1599/1523-count-odd-numbers-in-an-interval-range.md new file mode 100644 index 0000000..cd45e02 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1523-count-odd-numbers-in-an-interval-range.md @@ -0,0 +1,185 @@ +--- +id: count-odd-numbers-in-range +title: Count Odd Numbers in an Interval Range +sidebar_label: 1523-Count Odd Numbers in an Interval Range +tags: + - Brute Force + - Mathematics + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Count Odd Numbers in an Interval Range problem on LeetCode." +sidebar_position: 3 +--- + +## Problem Description + +Given two non-negative integers `low` and `high`. Return the count of odd numbers between `low` and `high` (inclusive). + +### Examples + +**Example 1:** + +``` +Input: low = 3, high = 7 +Output: 3 +Explanation: The odd numbers between 3 and 7 are [3,5,7]. +``` + +**Example 2:** + +``` +Input: low = 8, high = 10 +Output: 1 +Explanation: The odd numbers between 8 and 10 are [9]. +``` + +### Constraints + +- `0 <= low <= high <= 10^9` + +--- + +## Solution for Counting Odd Numbers in an Interval Range + +### Brute Force Approach + +The brute force approach involves iterating through each number between `low` and `high` and counting how many of these numbers are odd. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int countOdds(int low, int high) { + int count = 0; + for (int i = low; i <= high; ++i) { + if (i % 2 != 0) { + count++; + } + } + return count; + } +}; +``` + + + + + +```java +class Solution { + public int countOdds(int low, int high) { + int count = 0; + for (int i = low; i <= high; ++i) { + if (i % 2 != 0) { + count++; + } + } + return count; + } +} +``` + + + + + +```python +class Solution: + def countOdds(self, low: int, high: int) -> int: + count = 0 + for i in range(low, high + 1): + if i % 2 != 0: + count += 1 + return count +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(n)$, where $n$ is the number of integers between `low` and `high`. This is because we iterate through each number in the range. +- **Space Complexity**: $O(1)$. We use a constant amount of extra space for the counter variable. + + +### Optimized Approach + +A more efficient approach involves using simple arithmetic to calculate the count of odd numbers. If `low` and `high` are both even, we can count how many odd numbers are in the range by the formula: + +- If both `low` and `high` are even, the number of odd numbers is $(\frac{high - low}{2})$ +- If both `low` and `high` are odd, the number of odd numbers is $(\frac{high - low}{2} + 1)$ +- Otherwise, the number of odd numbers is $(\frac{high - low + 1}{2})$ + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int countOdds(int low, int high) { + if (low % 2 == 0) low++; + if (high % 2 == 0) high--; + if (low > high) return 0; + return (high - low) / 2 + 1; + } +}; +``` + + + + + +```java +class Solution { + public int countOdds(int low, int high) { + if (low % 2 == 0) low++; + if (high % 2 == 0) high--; + if (low > high) return 0; + return (high - low) / 2 + 1; + } +} +``` + + + + + +```python +class Solution: + def countOdds(self, low: int, high: int) -> int: + if low % 2 == 0: + low += 1 + if high % 2 == 0: + high -= 1 + if low > high: + return 0 + return (high - low) // 2 + 1 +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(1)$, as it involves simple arithmetic operations. +- **Space Complexity**: $O(1)$, as we use a constant amount of extra space. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/1500-1599/1528-Shuffle-String.md b/solutions/lc-solutions/1500-1599/1528-Shuffle-String.md new file mode 100644 index 0000000..893c4fb --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1528-Shuffle-String.md @@ -0,0 +1,332 @@ +--- + +id: shuffle-string +title: Shuffle String Solution +sidebar_label: 1528-Shuffle-String +tags: + - Array + - String + - LeetCode + - JavaScript + - TypeScript + - Python + - Java + - C++ +description: "This is a solution to the Shuffle String problem on LeetCode." + +--- + +In this page, we will solve the Shuffle String problem using different approaches: simple iteration and an optimized version using map. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +You are given a string `s` and an integer array `indices` of the same length. The string `s` will be shuffled such that the character at the `i`th position moves to `indices[i]` in the shuffled string. + +Return the shuffled string. + +### Examples + +**Example 1:** + +```plaintext +Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3] +Output: "leetcode" +Explanation: As shown, "codeleet" becomes "leetcode" after shuffling. +``` + +**Example 2:** + +```plaintext +Input: s = "abc", indices = [0,1,2] +Output: "abc" +Explanation: After shuffling, each character remains in its position. +``` + +### Constraints + +- `s.length == indices.length == n` +- `1 <= n <= 100` +- `s` consists of only lowercase English letters. +- `0 <= indices[i] < n` +- All values of `indices` are unique. + +--- + +## Solution for Shuffle String Problem + +### Intuition and Approach + +The problem can be solved by creating a new array for the shuffled string, placing each character at the position specified by the `indices` array. We will demonstrate a simple iteration approach and an optimized version using map. + + + + +### Approach 1: Simple Iteration + +We iterate through the string and place each character at the position specified by the `indices` array. + +#### Implementation + +```jsx live +function shuffleString() { + const s = "codeleet"; + const indices = [4, 5, 6, 7, 0, 2, 1, 3]; + + const restoreString = function(s, indices) { + let shuffled = new Array(s.length); + for (let i = 0; i < s.length; i++) { + shuffled[indices[i]] = s[i]; + } + return shuffled.join(''); + }; + + const result = restoreString(s, indices); + return ( +
+

+ Input: s = "{s}", indices = {JSON.stringify(indices)} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function restoreString(s, indices) { + let shuffled = new Array(s.length); + for (let i = 0; i < s.length; i++) { + shuffled[indices[i]] = s[i]; + } + return shuffled.join(''); + } + ``` + + + + + ```typescript + function restoreString(s: string, indices: number[]): string { + let shuffled: string[] = new Array(s.length); + for (let i = 0; i < s.length; i++) { + shuffled[indices[i]] = s[i]; + } + return shuffled.join(''); + } + ``` + + + + + ```python + class Solution: + def restoreString(self, s: str, indices: List[int]) -> str: + shuffled = [''] * len(s) + for i, index in enumerate(indices): + shuffled[index] = s[i] + return ''.join(shuffled) + ``` + + + + + ```java + class Solution { + public String restoreString(String s, int[] indices) { + char[] shuffled = new char[s.length()]; + for (int i = 0; i < s.length(); i++) { + shuffled[indices[i]] = s.charAt(i); + } + return new String(shuffled); + } + } + ``` + + + + + ```cpp + class Solution { + public: + string restoreString(string s, vector& indices) { + string shuffled(s.length(), ' '); + for (int i = 0; i < s.length(); i++) { + shuffled[indices[i]] = s[i]; + } + return shuffled; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$, where `n` is the length of the string. +- Space Complexity: $$O(n)$$, as we are using an additional array to store the shuffled string. + +
+ + + +### Approach 2: Using Map + +We can use a map to store the characters with their respective indices and then reconstruct the shuffled string. + +#### Implementation + +```jsx live +function shuffleString() { + const s = "codeleet"; + const indices = [4, 5, 6, 7, 0, 2, 1, 3]; + + const restoreString = function(s, indices) { + let map = new Map(); + for (let i = 0; i < s.length; i++) { + map.set(indices[i], s[i]); + } + let shuffled = ''; + for (let i = 0; i < s.length; i++) { + shuffled += map.get(i); + } + return shuffled; + }; + + const result = restoreString(s, indices); + return ( +
+

+ Input: s = "{s}", indices = {JSON.stringify(indices)} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function restoreString(s, indices) { + let map = new Map(); + for (let i = 0; i < s.length; i++) { + map.set(indices[i], s[i]); + } + let shuffled = ''; + for (let i = 0; i < s.length; i++) { + shuffled += map.get(i); + } + return shuffled; + } + ``` + + + + + ```typescript + function restoreString(s: string, indices: number[]): string { + let map: Map = new Map(); + for (let i = 0; i < s.length; i++) { + map.set(indices[i], s[i]); + } + let shuffled: string = ''; + for (let i = 0; i < s.length; i++) { + shuffled += map.get(i); + } + return shuffled; + } + ``` + + + + + ```python + class Solution: + def restoreString(self, s: str, indices: List[int]) -> str: + map = {indices[i]: s[i] for i in range(len(s))} + shuffled = ''.join(map[i] for i in range(len(s))) + return shuffled + ``` + + + + + ```java + import java.util.HashMap; + import java.util.Map; + + class Solution { + public String restoreString(String s, int[] indices) { + Map map = new HashMap<>(); + for (int i = 0; i < s.length(); i++) { + map.put(indices[i], s.charAt(i)); + } + StringBuilder shuffled = new StringBuilder(); + for (int i = 0; i < s.length(); i++) { + shuffled.append(map.get(i)); + } + return shuffled.toString(); + } + } + ``` + + + + + ```cpp + #include + #include + + class Solution { + public: + string restoreString(string s, vector& indices) { + unordered_map map; + for (int i = 0; i < s.length(); i++) { + map[indices[i]] = s[i]; + } + string shuffled(s.length(), ' '); + for (int i = 0; i < s.length(); i++) { + shuffled[i] = map[i]; + } + return shuffled; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$, where `n` is the length of the string. +- Space Complexity: $$O(n)$$, as we are using a map to store the characters. + +
+
+ +:::tip Note + +By using both simple iteration and map-based approaches, we can efficiently solve the Shuffle String problem. The choice between the two approaches depends on the specific requirements and constraints of the problem. + +::: + +## References + +- **LeetCode Problem:** [Shuffle String](https://leetcode.com/problems/shuffle-string/) +- **Solution Link:** [Shuffle String Solution on LeetCode](https://leetcode.com/problems/shuffle-string/solution/) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + + diff --git a/solutions/lc-solutions/1500-1599/1529-minimum-suffix-flips.md b/solutions/lc-solutions/1500-1599/1529-minimum-suffix-flips.md new file mode 100644 index 0000000..f421de8 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1529-minimum-suffix-flips.md @@ -0,0 +1,146 @@ +--- +id: minimum-suffix-flips +title: Minimum Suffix Flips +sidebar_label: 1529-Minimum Suffix Flips +tags: + - Greedy + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Minimum Suffix Flips problem on LeetCode." +sidebar_position: 2 +--- + +## Problem Description + +You are given a 0-indexed binary string `target` of length `n`. You have another binary string `s` of length `n` that is initially set to all zeros. You want to make `s` equal to `target`. + +In one operation, you can pick an index `i` where `0 <= i < n` and flip all bits in the inclusive range `[i, n - 1]`. Flip means changing '0' to '1' and '1' to '0'. + +Return the minimum number of operations needed to make `s` equal to `target`. + +### Examples + +**Example 1:** + +``` +Input: target = "10111" +Output: 3 +Explanation: Initially, s = "00000". +Choose index i = 2: "00000" -> "00111" +Choose index i = 0: "00111" -> "11000" +Choose index i = 1: "11000" -> "10111" +We need at least 3 flip operations to form target. +``` + +**Example 2:** + +``` +Input: target = "101" +Output: 3 +Explanation: Initially, s = "000". +Choose index i = 0: "000" -> "111" +Choose index i = 1: "111" -> "100" +Choose index i = 2: "100" -> "101" +We need at least 3 flip operations to form target. +``` + +**Example 3:** + +``` +Input: target = "00000" +Output: 0 +Explanation: We do not need any operations since the initial s already equals target. +``` + +### Constraints + +- `n == target.length` +- `1 <= n <= 10^5` +- `target[i]` is either '0' or '1'. + +--- + +## Solution for Minimum Number of Flips to Make Binary String Equal Problem + +### Approach: Greedy + +To solve the problem, we can use a greedy approach. We need to count how many times the value changes from '0' to '1' or from '1' to '0' in the target string. This count will give us the minimum number of flips required. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int minFlips(string target) { + int flips = 0; + char current = '0'; + for (char c : target) { + if (c != current) { + flips++; + current = c; + } + } + return flips; + } +}; +``` + + + + + +```java +class Solution { + public int minFlips(String target) { + int flips = 0; + char current = '0'; + for (char c : target.toCharArray()) { + if (c != current) { + flips++; + current = c; + } + } + return flips; + } +} +``` + + + + + +```python +class Solution: + def minFlips(self, target: str) -> int: + flips = 0 + current = '0' + for c in target: + if c != current: + flips += 1 + current = c + return flips +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(n)$, where $n$ is the length of the target string. We traverse the target string once. +- **Space Complexity**: $O(1)$. We use a constant amount of extra space for variables. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/1500-1599/1534-Count-good-triplets.md b/solutions/lc-solutions/1500-1599/1534-Count-good-triplets.md new file mode 100644 index 0000000..4d8109d --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1534-Count-good-triplets.md @@ -0,0 +1,404 @@ +--- +id: count-good-triplets +title: Count Good Triplets Solution +sidebar_label: 1534-Count-Good-Triplets +tags: + - Count Good Triplets + - Array + - Brute Force + - Optimization + - LeetCode + - Python + - JavaScript +description: "This is a solution to the Count Good Triplets problem on LeetCode." +--- + +In this page, we will solve the Count Good Triplets problem using multiple approaches: brute-force and optimization. We will provide the implementation of the solution in Python, JavaScript, TypeScript, Java, and C++. + +## Problem Description + +Given an array of integers `arr`, and three integers `a`, `b`, and `c`. You need to find the number of good triplets. + +A triplet $(arr[i], arr[j], arr[k])$ is good if the following conditions are true: + +- $0 <= i < j < k < arr.length$ +- $|arr[i] - arr[j]| <= a$ +- $|arr[j] - arr[k]| <= b$ +- $|arr[i] - arr[k]| <= c$ + +Where $|x|$ denotes the absolute value of `x`. + +Return the number of good triplets. + +### Examples + +**Example 1:** + +```plaintext +Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3 +Output: 4 +Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)]. +``` + +**Example 2:** + +```plaintext +Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1 +Output: 0 +Explanation: No triplet satisfies all conditions. +``` + +### Constraints + +- $3 <= arr.length <= 100$ +- $0 <= arr[i] <= 1000$ +- $0 <= a, b, c <= 1000$ + +--- + +## Solution for Count Good Triplets Problem + +### Intuition and Approach + +The problem can be solved using different approaches. We will start with a brute-force approach and then look at an optimized approach using early exits to reduce unnecessary comparisons. + + + + +### Approach 1: Brute Force + +We iterate through all possible triplets `(i, j, k)` where `0 <= i < j < k < arr.length` and check if they satisfy the conditions `|arr[i] - arr[j]| <= a`, `|arr[j] - arr[k]| <= b`, and `|arr[i] - arr[k]| <= c`. If they do, we count it as a good triplet. + +#### Implementation +```jsx live +function countGoodTriplets() { + const arr = [3, 0, 1, 1, 9, 7]; + const a = 7; + const b = 2; + const c = 3; + + const countGoodTriplets = function(arr, a, b, c) { + let count = 0; + for (let i = 0; i < arr.length - 2; i++) { + for (let j = i + 1; j < arr.length - 1; j++) { + if (Math.abs(arr[i] - arr[j]) > a) continue; + for (let k = j + 1; k < arr.length; k++) { + if (Math.abs(arr[j] - arr[k]) <= b && Math.abs(arr[i] - arr[k]) <= c) { + count++; + } + } + } + } + return count; + }; + + const result = countGoodTriplets(arr, a, b, c); + return ( +
+

+ Input: arr = {JSON.stringify(arr)}, a = {a}, b = {b}, c = {c} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function countGoodTriplets(arr, a, b, c) { + let count = 0; + for (let i = 0; i < arr.length - 2; i++) { + for (let j = i + 1; j < arr.length - 1; j++) { + for (let k = j + 1; k < arr.length; k++) { + if (Math.abs(arr[i] - arr[j]) <= a && + Math.abs(arr[j] - arr[k]) <= b && + Math.abs(arr[i] - arr[k]) <= c) { + count++; + } + } + } + } + return count; + } + ``` + + + + + ```typescript + function countGoodTriplets(arr: number[], a: number, b: number, c: number): number { + let count = 0; + for (let i = 0; i < arr.length - 2; i++) { + for (let j = i + 1; j < arr.length - 1; j++) { + for (let k = j + 1; k < arr.length; k++) { + if (Math.abs(arr[i] - arr[j]) <= a && + Math.abs(arr[j] - arr[k]) <= b && + Math.abs(arr[i] - arr[k]) <= c) { + count++; + } + } + } + } + return count; + } + ``` + + + + + ```python + class Solution: + def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int: + count = 0 + for i in range(len(arr) - 2): + for j in range(i + 1, len(arr) - 1): + for k in range(j + 1, len(arr)): + if abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c: + count += 1 + return count + ``` + + + + + ```java + class Solution { + public int countGoodTriplets(int[] arr, int a, int b, int c) { + int count = 0; + for (int i = 0; i < arr.length - 2; i++) { + for (int j = i + 1; j < arr.length - 1; j++) { + for (int k = j + 1; k < arr.length; k++) { + if (Math.abs(arr[i] - arr[j]) <= a && + Math.abs(arr[j] - arr[k]) <= b && + Math.abs(arr[i] - arr[k]) <= c) { + count++; + } + } + } + } + return count; + } + } + ``` + + + + + ```cpp + class Solution { + public: + int countGoodTriplets(vector& arr, int a, int b, int c) { + int count = 0; + for (int i = 0; i < arr.size() - 2; i++) { + for (int j = i + 1; j < arr.size() - 1; j++) { + for (int k = j + 1; k < arr.size(); k++) { + if (abs(arr[i] - arr[j]) <= a && + abs(arr[j] - arr[k]) <= b && + abs(arr[i] - arr[k]) <= c) { + count++; + } + } + } + } + return count; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n^3)$$ +- Space Complexity: $$O(1)$$ +- Where `n` is the length of the array `arr`. +- The time complexity is determined by the three nested loops iterating through the array. +- The space complexity is constant as no additional space is required beyond a few variables. + +
+ + +### Approach 2: Optimized Brute Force + +To optimize the brute force solution, we can use early exits to avoid unnecessary comparisons. Specifically, if a pair does not satisfy one of the conditions, we can skip further comparisons for that triplet. + +#### Implementation + +```jsx live +function countGoodTriplets() { + const arr = [3, 0, 1, 1, 9, 7]; + const a = 7; + const b = 2; + const c = 3; + const countGoodTripletsOptimized = function(arr, a, b, c) { + let count = 0; + for (let i = 0; i < arr.length - 2; i++) { + for (let j = i + 1; j < arr.length - 1; j++) { + if (Math.abs(arr[i] - arr[j]) > a) continue; + for (let k = j + 1; k < arr.length; k++) { + if (Math.abs(arr[j] - arr[k]) <= b && Math.abs(arr[i] - arr[k]) <= c) { + count++; + } + } + } + } + return count; + }; + + const resultOptimized = countGoodTripletsOptimized(arr, a, b, c); + + return ( +
+

+ Input: arr = {JSON.stringify(arr)}, a = {a}, b = {b}, c = {c} +

+

+ Output: {resultOptimized} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function countGoodTriplets(arr, a, b, c) { + let count = 0; + for (let i = 0; i < arr.length - 2; i++) { + for (let j = i + 1; j < arr.length - 1; j++) { + if (Math.abs(arr[i] - arr[j]) > a) continue; + for (let k = j + 1; k < arr.length; k++) { + if (Math.abs(arr[j] - arr[k]) <= b && + Math.abs(arr[i] - arr[k]) <= c) { + count++; + } + } + } + } + return count; + } + ``` + + + + + ```typescript + function countGoodTriplets(arr: number[], a: number, b: number, c: number): number { + let count = 0; + for (let i = 0; i < arr.length - 2; i++) { + for (let j = i + 1; j < arr.length - 1; j++) { + if (Math.abs(arr[i] - arr[j]) > a) continue; + for (let k = j + 1; k < arr.length; k++) { + if (Math.abs(arr[j] - arr[k]) <= b && + Math.abs(arr[i] - arr[k]) <= c) { + count++; + } + } + } + } + return count; + } + ``` + + + + + ```python + class Solution: + def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int: + count = 0 + for i in range(len(arr) - 2): + for j in range(i + 1, len(arr) - 1): + if abs(arr[i] - arr[j]) > a: + continue + for k in range(j + 1, len(arr)): + if abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c: + count += 1 + return count + ``` + + + + + ```java + class Solution { + public int countGoodTriplets(int[] arr, int a, int b, int c) { + int count = 0; + for (int i = 0; i < arr.length - 2; i++) { + for (int j = i + 1; j < arr.length - 1; j++) { + if (Math.abs(arr[i] - arr[j]) > a) continue; + for (int k = j + 1; k < arr.length; k++) { + if (Math.abs(arr[j] - arr[k]) <= b && + Math.abs(arr[i] - arr[k]) <= c) { + count++; + } + } + } + } + return count; + } + } + ``` + + + + + ```cpp + class Solution { + public: + int countGoodTriplets(vector& arr, int a, int b, int c) { + int count = 0; + for (int i = 0; i < arr.size() - 2; i++) { + for (int j = i + 1; j < arr.size() - 1; j++) { + if (abs(arr[i] - arr[j]) > a) continue; + for (int k = j + 1; k < arr.size(); k++) { + if (abs(arr[j] - arr[k]) <= b && + abs(arr[i] - arr[k]) <= c) { + count++; + } + } + } + } + return count; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n^3)$$ +- Space Complexity: $$O(1)$$ +- Where `n` is the length of the array `arr`. +- The time complexity remains cubic but the constant factor is reduced due to early exits. + +
+
+ +:::tip Note + +By using these approaches, we can efficiently solve the Count Good Triplets problem for the given constraints. + +::: +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/count-good-triplets/) +- **Solution Link:** [Count Good Triplets Solution on LeetCode](https://leetcode.com/problems/count-good-triplets/discuss/762344/Brute-Force-O(n3)-with-JavaC%2B%2B) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + + + diff --git a/solutions/lc-solutions/1500-1599/1539-kth-missing-number.md b/solutions/lc-solutions/1500-1599/1539-kth-missing-number.md new file mode 100644 index 0000000..eb6764e --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1539-kth-missing-number.md @@ -0,0 +1,416 @@ +--- + +id: kth-missing-positive-number +title: Kth Missing Positive Number Solution +sidebar_label: 1539-Kth-Missing-Positive-Number +tags: + - Array + - Binary Search + - LeetCode + - JavaScript + - TypeScript + - Python + - Java + - C++ +description: "This is a solution to the Kth Missing Positive Number problem on LeetCode." +--- + +In this page, we will solve the Kth Missing Positive Number problem using different approaches: linear search and binary search. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +Given an array `arr` of positive integers sorted in a strictly increasing order, and an integer `k`. + +Return the `k`th positive integer that is missing from this array. + +### Examples + +**Example 1:** + +```plaintext +Input: arr = [2,3,4,7,11], k = 5 +Output: 9 +Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9. +``` + +**Example 2:** + +```plaintext +Input: arr = [1,2,3,4], k = 2 +Output: 6 +Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6. +``` + +### Constraints + +- `1 <= arr.length <= 1000` +- `1 <= arr[i] <= 1000` +- `1 <= k <= 1000` +- `arr[i] < arr[j]` for `1 <= i < j <= arr.length` + +--- + +## Solution for Kth Missing Positive Number Problem + +### Intuition and Approach + +The problem can be solved using linear search or binary search. Linear search is straightforward, while binary search is more efficient. + + + + +### Approach 1: Linear Search + +We iterate through the positive integers, checking if they are present in the array. If a number is missing, we decrement `k`. When `k` reaches 0, we have found the `k`th missing positive integer. + +#### Implementation + +```jsx live +function kthMissingPositiveNumber() { + const arr = [2, 3, 4, 7, 11]; + const k = 5; + + const findKthPositive = function(arr, k) { + let missingCount = 0; + let current = 1; + + while (missingCount < k) { + if (!arr.includes(current)) { + missingCount++; + } + if (missingCount < k) { + current++; + } + } + + return current; + }; + + const result = findKthPositive(arr, k); + return ( +
+

+ Input: arr = {JSON.stringify(arr)}, k = {k} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function findKthPositive(arr, k) { + let missingCount = 0; + let current = 1; + + while (missingCount < k) { + if (!arr.includes(current)) { + missingCount++; + } + if (missingCount < k) { + current++; + } + } + + return current; + } + ``` + + + + + ```typescript + function findKthPositive(arr: number[], k: number): number { + let missingCount = 0; + let current = 1; + + while (missingCount < k) { + if (!arr.includes(current)) { + missingCount++; + } + if (missingCount < k) { + current++; + } + } + + return current; + } + ``` + + + + + ```python + class Solution: + def findKthPositive(self, arr: List[int], k: int) -> int: + missing_count = 0 + current = 1 + + while missing_count < k: + if current not in arr: + missing_count += 1 + if missing_count < k: + current += 1 + + return current + ``` + + + + + ```java + class Solution { + public int findKthPositive(int[] arr, int k) { + int missingCount = 0; + int current = 1; + + while (missingCount < k) { + boolean found = false; + for (int num : arr) { + if (num == current) { + found = true; + break; + } + } + if (!found) { + missingCount++; + } + if (missingCount < k) { + current++; + } + } + + return current; + } + } + ``` + + + + + ```cpp + class Solution { + public: + int findKthPositive(vector& arr, int k) { + int missingCount = 0; + int current = 1; + + while (missingCount < k) { + if (find(arr.begin(), arr.end(), current) == arr.end()) { + missingCount++; + } + if (missingCount < k) { + current++; + } + } + + return current; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n \times m)$$, where `n` is the length of the array and `m` is the `k`th missing positive number. +- Space Complexity: $$O(1)$$, as no additional space is used. +- The time complexity is high due to the nested loops in `arr.includes()`. + +
+ + +### Approach 2: Binary Search + +We can optimize the solution using binary search by calculating the number of missing elements at each index and adjusting our search range accordingly. + +#### Implementation + +```jsx live +function kthMissingPositiveNumber() { + const arr = [2, 3, 4, 7, 11]; + const k = 5; + + const findKthPositive = function(arr, k) { + let left = 0; + let right = arr.length; + + while (left < right) { + const mid = Math.floor((left + right) / 2); + const missing = arr[mid] - mid - 1; + + if (missing < k) { + left = mid + 1; + } else { + right = mid; + } + } + + return left + k; + }; + + const result = findKthPositive(arr, k); + return ( +
+

+ Input: arr = {JSON.stringify(arr)}, k = {k} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function findKthPositive(arr, k) { + let left = 0; + let right = arr.length; + + while (left < right) { + const mid = Math.floor((left + right) / 2); + const missing = arr[mid] - mid - 1; + + if (missing < k) { + left = mid + 1; + } else { + right = mid; + } + } + + return left + k; + } + ``` + + + + + ```typescript + function findKthPositive(arr: number[], k: number): number { + let left = 0; + let right = arr.length; + + while (left < right) { + const mid = Math.floor((left + right) / 2); + const missing = arr[mid] - mid - 1; + + if (missing < k) { + left = mid + 1; + } else { + right = mid; + } + } + + return left + k; + } + ``` + + + + + ```python + class Solution: + def findKthPositive(self, arr: List[int], k: int) -> int: + left, right = 0, len(arr) + + while left < right: + mid = (left + right) // 2 + missing = arr[mid] - mid - 1 + + if missing < k: + left = mid + 1 + else: + right = mid + + return left + k + ``` + + + + + + + ```java + class Solution { + public int findKthPositive(int[] arr, int k) { + int left = 0, right = arr.length; + + while (left < right) { + int mid = (left + right) / 2; + int missing = arr[mid] - mid - 1; + + if (missing < k) { + left = mid + 1; + } else { + right = mid; + } + } + + return left + k; + } + } + ``` + + + + + ```cpp + class Solution { + public: + int findKthPositive(vector& arr, int k) { + int left = 0, right = arr.size(); + + while (left < right) { + int mid = (left + right) / 2; + int missing = arr[mid] - mid - 1; + + if (missing < k) { + left = mid + 1; + } else { + right = mid; + } + } + + return left + k; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(\log n)$$, where `n` is the length of the array. +- Space Complexity: $$O(1)$$, as no additional space is used. +- The binary search significantly reduces the time complexity compared to the linear search approach. + +
+
+ +:::tip Note + +By using both linear search and binary search approaches, we can efficiently solve the Kth Missing Positive Number problem. The binary search approach is more efficient, especially for larger inputs. + +::: +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/kth-missing-positive-number/) +- **Solution Link:** [Kth Missing Positive Number Solution on LeetCode](https://leetcode.com/problems/kth-missing-positive-number/solutions/5016750/easy-binary-search-solution-in-c-100-beats-full-expanation-with-example/) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + +--- diff --git a/solutions/lc-solutions/1500-1599/1544-make-the-string-great.md b/solutions/lc-solutions/1500-1599/1544-make-the-string-great.md new file mode 100644 index 0000000..7ce07f9 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1544-make-the-string-great.md @@ -0,0 +1,172 @@ +--- +id: make-the-string-great +title: Make The String Great (Leetcode) +sidebar_label: 1544-MakeTheStringGreat +description: Given a string s of lower and upper case English letters. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Make The String Great](https://leetcode.com/problems/make-the-string-great/description/) | [Make The String Great Solution on LeetCode](https://leetcode.com/problems/make-the-string-great/solutions) | [Aaradhya Singh ](https://leetcode.com/u/keira_09/) | + + +## Problem Description + +Given a string $s$ of lower and upper case English letters. + +A good string is a string which doesn't have two adjacent characters $s[i]$ and $s[i + 1]$ where: + +- $0 <= i <= s.length - 2$ +- s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa. + +To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good. + +Return the string after making it good. The answer is guaranteed to be unique under the given constraints. + +Notice that an empty string is also good. + +### Examples + +#### Example 1 + +- **Input:** s = "leEeetcode" +- **Output:** "leetcode" +- **Explanation:** In the first step, either you choose $i = 1$ or $i = 2$, both will result $"leEeetcode"$ to be reduced to $"leetcode"$. + + +#### Example 2 + +- **Input:** s = "abBAcC" +- **Output:** "" +- **Explanation:** We have many possible scenarios, and all lead to the same answer. For example:
+"abBAcC" --> "aAcC" --> "cC" --> "" +"abBAcC" --> "abBA" --> "aA" --> "" + +#### Example 2 + +- **Input:** s = "s" +- **Output:** "s" + + +### Constraints + + +- $1 <= s.length <= 100$ +- s contains only lower and upper case English letters. + + + +### Intuition + +The code aims to remove adjacent pairs of characters in the input string s where one character is the uppercase version of the other (e.g., 'a' and 'A'). It initializes an empty string result and iterates through s. If result is empty, it adds the current character. Otherwise, it checks if the current character and the last character of result form such a pair. If they do, it removes the last character from result; otherwise, it appends the current character to result. This approach efficiently creates a "good" string with no adjacent pairs of uppercase-lowercase characters, providing the desired output. + +### Approach + +1. **Initialize an Empty String:** + + - Initialize an empty string result to store the characters after processing. + +2. **Iterate Through the Input String:** + + - Iterate through each character in the input string s using a for loop. + +3. **Check for Empty String:** + + - If result is empty, add the current character to result. + +4. **Check for Adjacent Pairs:** + + - If result is not empty, check if the current character and the last character of result form an adjacent pair where one character is the uppercase version of the other (e.g., 'a' and 'A'). + - If such a pair is found, remove the last character from result using result.erase(result.size() - 1). + - If no adjacent pair is found, append the current character to result. + +5. **Return the Resulting String:** + + - After processing all characters in s, return the final value of result, which represents the "good" string without adjacent pairs of uppercase-lowercase characters. + +### Solution Code + +#### Python + +```py +class Solution: + def makeGood(self, s: str) -> str: + result = [] + + for char in s: + if not result: + result.append(char) + else: + if result[-1].lower() == char.lower() and (result[-1] != char): + result.pop() + else: + result.append(char) + + return ''.join(result) +``` + +#### Java + +```java +class Solution { + public String makeGood(String s) { + StringBuilder result = new StringBuilder(); + + for (char c : s.toCharArray()) { + if (result.length() == 0) { + result.append(c); + } else { + char lastChar = result.charAt(result.length() - 1); + if (Character.toLowerCase(c) == Character.toLowerCase(lastChar) + && c != lastChar + 32 && c != lastChar - 32) { + result.deleteCharAt(result.length() - 1); + } else { + result.append(c); + } + } + } + + return result.toString(); + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + string makeGood(std::string s) { + string result ; + for (int i=0 ; i< s.length() ; i++) + { + if (result.empty()) + { + result += s[i]; + } + + else + { + if (!result.empty() && (s[i] == result.back() - 32 || s[i] == result.back() + 32)) + { + result.erase(result.size() - 1); + } + + else if (!result.empty()) + { + result += s[i] ; + } + } + } + + return result; + + } +}; +``` + +### Conclusion + +The code efficiently creates a "good" string by removing adjacent pairs of characters where one is the uppercase version of the other. It uses a StringBuilder to store and manipulate the characters, iterating through the input string and checking for adjacent pairs. If such a pair is found, the last character is removed from the StringBuilder; otherwise, the current character is appended. This approach ensures that the resulting string has no adjacent pairs of uppercase-lowercase characters, adhering to the desired output. The time complexity of this approach is $O(n)$, where $n$ is the length of the input string, as each character is processed once. The space complexity is also $O(n)$ due to the storage of the StringBuilder. diff --git a/solutions/lc-solutions/1500-1599/1547-Minimum-cost-to-cut-a-stick.md b/solutions/lc-solutions/1500-1599/1547-Minimum-cost-to-cut-a-stick.md new file mode 100644 index 0000000..db31253 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1547-Minimum-cost-to-cut-a-stick.md @@ -0,0 +1,112 @@ +--- +id: minimum-cost-to-cut-a-stick +title: Minimum Cost to Cut a Stick +sidebar_label: 1547 - Minimum Cost to Cut a Stick +tags: [Dynamic Programming, Array, C++] +description: Solve the problem of finding the minimum cost to cut a stick into smaller pieces at specified positions, using dynamic programming. +--- + +## Problem Statement + +### Problem Description + +Given a wooden stick of length `n` units. The stick is labeled from 0 to `n`. For example, a stick of length 6 is labeled as follows: +``` +0 - 1 - 2 - 3 - 4 - 5 - 6 +``` + +- Given an integer array `cuts` where `cuts[i]` denotes a position you should perform a cut at. + +- You should perform the cuts in order, but you can change the order of the cuts as you wish. + +- The cost of one cut is the length of the stick to be cut. The total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e., the sum of their lengths is the length of the stick before the cut). + +- Return the minimum total cost of the cuts. + +### Example + +**Example 1:** +``` +Input: +n = 7, cuts = [1, 3, 4, 5] + +Output: +16 +``` + +**Explanation:** + +- Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario: + +- The first cut is done to a rod of length 7 so the cost is 7. + +- The second cut is done to a rod of length 6 (i.e., the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. + +- The total cost is 7 + 6 + 4 + 3 = 20. + +- Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16). + + +### Constraints + +- 2 <= `n` <= 10^6 +- 1 <= `cuts.length` <= min(`n` - 1, 100) +- 1 <= `cuts[i]` <= `n` - 1 +- All the integers in the `cuts` array are distinct. + +## Solution + +### Intuition + +- Sort the cuts in ascending order. +- Use dynamic programming to minimize the cost of cuts. +- Define `dp[i][j]` as the minimum cost to cut the stick between cuts[i-1] and cuts[j-1]. +- Use a bottom-up approach to solve the subproblems and combine them to get the final result. + +### Time Complexity and Space Complexity Analysis + +- **Initialization**: + - Sorting the cuts array takes $O(m log m)$ time, where m is the number of cuts. + - Initializing the `dp` array takes $O(m^3)$ time. + - Overall initialization time complexity is $O(m log m + m^2)$. + +- **DP Table Calculation**: + - Filling the `dp` table involves iterating over all possible subintervals and calculating the minimum cost for each subinterval using nested loops. + - This takes $O(m^3)$ time in the worst case. + +- **Overall Time Complexity**: + - The overall time complexity is $O(m^3)$. + +- **Space Complexity**: + - The `dp` table requires $O(m^2)$ space. + - The space complexity is $O(m^2)$. + +### Code + +#### C++ + +```cpp +class Solution { +public: + int minCost(int n, std::vector& cuts) { + std::sort(cuts.begin(), cuts.end()); + int m = cuts.size(); + std::vector> dp(m + 2, std::vector(m + 2, 0)); + + for (int l = 2; l <= m + 1; l++) { + for (int i = 0; i + l <= m + 1; i++) { + int j = i + l; + dp[i][j] = INT_MAX; + for (int k = i + 1; k < j; k++) { + dp[i][j] = std::min(dp[i][j], dp[i][k] + dp[k][j]); + } + int left = (i == 0) ? 0 : cuts[i - 1]; + int right = (j == m + 1) ? n : cuts[j - 1]; + dp[i][j] += right - left; + } + } + + return dp[0][m + 1]; + } +}; +``` diff --git a/solutions/lc-solutions/1500-1599/1550-Three-Consecutive-Odds b/solutions/lc-solutions/1500-1599/1550-Three-Consecutive-Odds new file mode 100644 index 0000000..13142d0 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1550-Three-Consecutive-Odds @@ -0,0 +1,60 @@ +--- +id: three-consecutive-odds +title: Three Consecutive Odds +sidebar_label: 1550-Three-Consecutive-Odds +tags: + - Array + +--- + +## Problem Description + +Given an integer array `arr`, return `true` if there are three consecutive odd numbers in the array. Otherwise, return `false`. + + +### Example + +**Example 1:** + +``` +Input: arr = [2,6,4,1] +Output: false +Explanation: There are no three consecutive odds. +``` + +**Example 2:** +``` +Input: arr = [1,2,34,3,4,5,7,23,12] +Output: true +Explanation: [5,7,23] are three consecutive odds. +``` + +### Constraints + +- `1 <= arr.length <= 1000` + +## Solution Approach + +### Intuition: + +To efficiently determine the three consecutive odds + + +## Solution Implementation + +### Code (C++): + +```cpp +class Solution { +public: + bool threeConsecutiveOdds(vector& arr) { + int n = arr.size(); + for(int i=0; i& arr) { + int count = 0; // Initialize count to keep track of consecutive odd numbers + + for (int num : arr) { // Iterate through each element in the array + if (num % 2 != 0) { // Check if the current element is odd + count++; // Increment the count if it's odd + if (count == 3) { // If we have found three consecutive odds, return true + return true; + } + } else { // If the element is even, reset the count to 0 + count = 0; + } + } + + return false; // If we finish the loop without finding three consecutive odds, return false + + } +}; + ``` + +#### JAVA + +```java +class Solution { + public boolean threeConsecutiveOdds(int[] arr) { + int count = 0; // Initialize count to keep track of consecutive odd numbers + + for (int i = 0; i < arr.length; i++) { // Iterate through each element in the array + if (arr[i] % 2 != 0) { // Check if the current element is odd + count++; // Increment the count if it's odd + if (count == 3) { // If we have found three consecutive odds, return true + return true; + } + } else { // If the element is even, reset the count to 0 + count = 0; + } + } + + return false; // If we finish the loop without finding three consecutive odds, return false + } +} +``` + +#### PYTHON + +```python +class Solution(object): + def threeConsecutiveOdds(self, arr): + count = 0 # Initialize count to keep track of consecutive odd numbers + + for num in arr: # Iterate through each element in the array + if num % 2 != 0: # Check if the current element is odd + count += 1 # Increment the count if it's odd + if count == 3: # If we have found three consecutive odds, return true + return True + else: # If the element is even, reset the count to 0 + count = 0 + + return False # If we finish the loop without finding three consecutive odds, return false + +``` + + + +### Complexity Analysis + +- Time Complexity: $O(n)$ + +- Space Complexity: $O(1)$ + +### References + +- **LeetCode Problem**: Three Consecutive Odds \ No newline at end of file diff --git a/solutions/lc-solutions/1500-1599/1552-magnetic-force-between-two-balls.md b/solutions/lc-solutions/1500-1599/1552-magnetic-force-between-two-balls.md new file mode 100644 index 0000000..ed1dd1f --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1552-magnetic-force-between-two-balls.md @@ -0,0 +1,328 @@ +--- +id: magnetic-force-between-two-balls +title: Magnetic Force Between Two Balls +sidebar_label: 1552. Magnetic Force Between Two Balls + + +tags: +- Array +- Binary Search +- Sorting +description: "This is a solution to the Magnetic Force Between Two Balls problem on LeetCode." +--- + +## Problem Description +In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum. + +Rick stated that magnetic force between two different balls at positions x and y is |x - y|. + +Given the integer array position and the integer m. Return the required force. +### Examples +**Example 1:** +![image](https://assets.leetcode.com/uploads/2020/08/11/q3v1.jpg) +``` +Input: position = [1,2,3,4,7], m = 3 +Output: 3 +Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3. +``` + +### Constraints +- `n == position.length` +- `2 <= n <= 10^5` +- `1 <= position[i] <= 10^9` +- `All integers in position are distinct.` +- `2 <= m <= position.length` + +## Solution for Min Cost to Connect All Points +### Approach +To solve this problem, we can utilize a binary search algorithm combined with a greedy approach. The goal is to determine the largest minimum distance possible between any two balls. Here's the step-by-step approach: + +1. **Sorting**: First, sort the positions array. This will help in easily calculating the distance between consecutive positions. +2. **Binary Search Setup**: + - Initialize the search range for the possible distances. The lower bound (`low`) is set to 1 (the smallest possible distance) and the upper bound (`high`) is set to the difference between the maximum and minimum positions (the largest possible distance). +3. **Binary Search Execution**: + - While `low` is less than or equal to `high`, calculate the middle value (`mid`) of the current search range. + - Use a helper function `possible` to check if it is possible to place all `m` balls such that the minimum distance between any two balls is at least `mid`. + - This is done by placing the first ball at the first position and then trying to place each subsequent ball at the next position that is at least `mid` distance away from the last placed ball. + - If it is possible to place all `m` balls in this manner, it means `mid` is a valid candidate for the largest minimum distance, so we update the result and try for a larger distance by setting `low` to `mid + 1`. + - If it is not possible, it means `mid` is too large, so we try a smaller distance by setting `high` to `mid - 1`. +4. **Result**: The largest valid `mid` found during the binary search is the answer. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function possible(position, m, mid) { + let prev = position[0]; + let cnt = 1; + + for (let i = 1; i < position.length; i++) { + if (Math.abs(position[i] - prev) >= mid) { + cnt++; + prev = position[i]; + } + if (cnt >= m) return true; + } + + return false; + } + + function maxDistance(position, m) { + position.sort((a, b) => a - b); + let low = 1; + let high = position[position.length - 1] - position[0]; + let maxi = 0; + + while (low <= high) { + let mid = Math.floor(low + (high - low) / 2); + if (possible(position, m, mid)) { + maxi = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + + return maxi; + } + const input = [1,2,3,4,7], m = 3 + const output = maxDistance(input , m) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(nlog(n)) $ + - Space Complexity: $ O(1)$ + + ## Code in Different Languages + + + + ```javascript + class Solution { + possible(position, m, mid) { + let prev = position[0]; + let cnt = 1; + + for (let i = 1; i < position.length; i++) { + if (Math.abs(position[i] - prev) >= mid) { + cnt++; + prev = position[i]; + } + if (cnt >= m) return true; + } + + return false; + } + + maxDistance(position, m) { + position.sort((a, b) => a - b); + let low = 1; + let high = position[position.length - 1] - position[0]; + let maxi = 0; + + while (low <= high) { + let mid = Math.floor(low + (high - low) / 2); + if (this.possible(position, m, mid)) { + maxi = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + + return maxi; + } +} + + ``` + + + + + ```typescript + class Solution { + possible(position: number[], m: number, mid: number): boolean { + let prev = position[0]; + let cnt = 1; + + for (let i = 1; i < position.length; i++) { + if (Math.abs(position[i] - prev) >= mid) { + cnt++; + prev = position[i]; + } + if (cnt >= m) return true; + } + + return false; + } + + maxDistance(position: number[], m: number): number { + position.sort((a, b) => a - b); + let low = 1; + let high = position[position.length - 1] - position[0]; + let maxi = 0; + + while (low <= high) { + let mid = Math.floor(low + (high - low) / 2); + if (this.possible(position, m, mid)) { + maxi = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + + return maxi; + } +} + + ``` + + + + ```python + class Solution: + def possible(self, position, m, mid): + prev = position[0] + cnt = 1 + + for i in range(1, len(position)): + if abs(position[i] - prev) >= mid: + cnt += 1 + prev = position[i] + if cnt >= m: + return True + + return False + + def maxDistance(self, position, m): + position.sort() + low, high = 1, position[-1] - position[0] + maxi = 0 + + while low <= high: + mid = (low + high) // 2 + if self.possible(position, m, mid): + maxi = mid + low = mid + 1 + else: + high = mid - 1 + + return maxi + + ``` + + + + + ```java + import java.util.Arrays; + +public class Solution { + public boolean possible(int[] position, int m, int mid) { + int prev = position[0]; + int cnt = 1; + + for (int i = 1; i < position.length; i++) { + if (Math.abs(position[i] - prev) >= mid) { + cnt++; + prev = position[i]; + } + if (cnt >= m) return true; + } + + return false; + } + + public int maxDistance(int[] position, int m) { + Arrays.sort(position); + int low = 1; + int high = position[position.length - 1] - position[0]; + int maxi = 0; + + while (low <= high) { + int mid = low + (high - low) / 2; + if (possible(position, m, mid)) { + maxi = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + + return maxi; + } +} + + ``` + + + + + + ```cpp + class Solution { +public: + bool possible(vector& position, int m, int mid) { + int prev = position[0]; + int cnt = 1; + + for (int i = 1; i < position.size(); i++) { + if (abs(position[i] - prev) >= mid) { + cnt++; + prev = position[i]; + } + if (cnt >= m) return true; + } + + return false; + } + + int maxDistance(vector& position, int m) { + sort(position.begin(), position.end()); + int low = 1; + int high = position.back() - position[0]; + int maxi = 0; + + while (low <= high) { + int mid = low + (high - low) / 2; + if (possible(position, m, mid)) { + maxi = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + + return maxi; + } +}; + +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [ Magnetic Force Between Two Balls](https://leetcode.com/problems/magnetic-force-between-two-balls/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/magnetic-force-between-two-balls/description/) + diff --git a/solutions/lc-solutions/1500-1599/1566-Detect-Pattern-of-Length-M-Repeated-K-or-More-Times.md b/solutions/lc-solutions/1500-1599/1566-Detect-Pattern-of-Length-M-Repeated-K-or-More-Times.md new file mode 100644 index 0000000..927796c --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1566-Detect-Pattern-of-Length-M-Repeated-K-or-More-Times.md @@ -0,0 +1,412 @@ +--- +id: detect-pattern +title: Detect Pattern Solution +sidebar_label: 1566-Detect Pattern of Length M Repeated K or More Times +tags: + - Detect Pattern + - String + - LeetCode + - Python + - JavaScript + - TypeScript + - Java + - C++ +description: "This is a solution to the Detect Pattern problem on LeetCode." +--- + +In this page, we will solve the Detect Pattern problem using multiple approaches. We will provide the implementation of the solution in Python, JavaScript, TypeScript, Java, and C++. + +## Problem Description + +Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times. + +A pattern is a subarray (consecutive elements) that occurs `k` or more times within the array `arr`. + +The pattern can be of any length and must not overlap. + +### Examples + +**Example 1:** + +```plaintext +Input: arr = [1,2,4,4,4,4], m = 1, k = 3 +Output: true +Explanation: The repeated pattern is [4]. + +``` + +**Example 2:** + +```plaintext +Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2 +Output: true +Explanation: The repeated pattern is [1,2]. +``` + +**Example 3:** + +```plaintext +Input: arr = [1,2,1,2,1,3], m = 2, k = 3 +Output: false +Explanation: There is no such pattern. +``` + +**Example 4:** + +```plaintext +Input: arr = [1,2,3,1,2], m = 2, k = 2 +Output: false +Explanation: There is no such pattern. +``` + +### Constraints + +- $2 <= arr.length <= 100$ +- $1 <= arr[i] <= 100$ +- $1 <= m <= 100$ +- $2 <= k <= 100$ + +--- + +## Solution for Detect Pattern Problem + +### Intuition and Approach + +We can solve this problem using a sliding window approach. We iterate through the array and check if there is a pattern of length `m` that repeats `k` or more times. + + + + +### Approach: Sliding Window + +In this approach, we use a sliding window of length `m` to check for repeated patterns. + +#### Implementation +```jsx live +function detectPattern() { + const arr = [1, 2, 4, 4, 4, 4]; + const m = 1; + const k = 3; + + const containsPattern = function(arr, m, k) { + const n = arr.length; + for (let i = 0; i <= n - m * k; i++) { + let pattern = arr.slice(i, i + m); + let count = 1; + for (let j = i + m; j < n; j += m) { + if (arr.slice(j, j + m).toString() === pattern.toString()) { + count++; + if (count >= k) return true; + } else { + break; + } + } + } + return false; + }; + + const result = containsPattern(arr, m, k); + return ( +
+

+ Input: arr = {JSON.stringify(arr)}, m = {m}, k = {k} +

+

+ Output: {result ? "true" : "false"} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function containsPattern(arr, m, k) { + const n = arr.length; + for (let i = 0; i <= n - m * k; i++) { + let pattern = arr.slice(i, i + m); + let count = 1; + for (let j = i + m; j < n; j += m) { + if (arr.slice(j, j + m).toString() === pattern.toString()) { + count++; + if (count >= k) return true; + } else { + break; + } + } + } + return false; + } + ``` + + + + + ```typescript + function containsPattern(arr: number[], m: number, k: number): boolean { + const n = arr.length; + for (let i = 0; i <= n - m * k; i++) { + let pattern = arr.slice(i, i + m); + let count = 1; + for (let j = i + m; j < n; j += m) { + if (arr.slice(j, j + m).toString() === pattern.toString()) { + count++; + if (count >= k) return true; + } else { + break; + } + } + } + return false; + } + ``` + + + + + ```python + class Solution: + def containsPattern(self, arr: List[int], m: int, k: int) -> bool: + n = len(arr) + for i in range(n - m * k + 1): + pattern = arr[i:i + m] + count = 1 + for j in range(i + m, n, m): + if arr[j:j + m] == pattern: + count += 1 + if count >= k: + return True + else: + break + return False + ``` + + + + + ```java + class Solution { + public boolean containsPattern(int[] arr, int m, int k) { + int n = arr.length; + for (int i = 0; i <= n - m * k; i++) { + int[] pattern = Arrays.copyOfRange(arr, i, i + m); + int count = 1; + for (int j = i + m; j < n; j += m) { + int[] subArray = Arrays.copyOfRange(arr, j, j + m); + if (Arrays.equals(pattern, subArray)) { + count++; + if (count >= k) return true; + } else { + break; + } + } + } + return false; + } + } + ``` + + + + + ```cpp + class Solution { + public: + bool containsPattern(vector& arr, int m, int k) { + int n = arr.size(); + for (int i + + = 0; i <= n - m * k; i++) { + vector pattern(arr.begin() + i, arr.begin() + i + m); + int count = 1; + for (int j = i + m; j < n; j += m) { + vector subArray(arr.begin() + j, arr.begin() + j + m); + if (pattern == subArray) { + count++; + if (count >= k) return true; + } else { + break; + } + } + } + return false; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n \cdot m)$$ +- Space Complexity: $$O(1)$$ +- Where `n` is the length of the array `arr` and `m` is the length of the pattern. +- We iterate through the array once and compare patterns of length `m`. +- The space complexity is constant as we use only a few variables irrespective of the size of the input. + +
+ + +### Approach: Hash Map + +In this approach, we use a hash map to store the occurrence of patterns. + +#### Implementation + +```jsx live +function detectPattern() { + const arr = [1, 2, 4, 4, 4, 4]; + const m = 1; + const k = 3; + + const containsPattern = function(arr, m, k) { + const patternMap = new Map(); + for (let i = 0; i <= arr.length - m * k; i++) { + let pattern = arr.slice(i, i + m).toString(); + if (!patternMap.has(pattern)) { + patternMap.set(pattern, 1); + } else { + patternMap.set(pattern, patternMap.get(pattern) + 1); + } + if (patternMap.get(pattern) >= k) return true; + } + return false; + }; + + const result = containsPattern(arr, m, k); + return ( +
+

+ Input: arr = {JSON.stringify(arr)}, m = {m}, k = {k} +

+

+ Output: {result ? "true" : "false"} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function containsPattern(arr, m, k) { + const patternMap = new Map(); + for (let i = 0; i <= arr.length - m * k; i++) { + let pattern = arr.slice(i, i + m).toString(); + if (!patternMap.has(pattern)) { + patternMap.set(pattern, 1); + } else { + patternMap.set(pattern, patternMap.get(pattern) + 1); + } + if (patternMap.get(pattern) >= k) return true; + } + return false; + } + ``` + + + + + ```typescript + function containsPattern(arr: number[], m: number, k: number): boolean { + const patternMap = new Map(); + for (let i = 0; i <= arr.length - m * k; i++) { + let pattern = arr.slice(i, i + m).toString(); + if (!patternMap.has(pattern)) { + patternMap.set(pattern, 1); + } else { + patternMap.set(pattern, patternMap.get(pattern) + 1); + } + if (patternMap.get(pattern) >= k) return true; + } + return false; + } + ``` + + + + + ```python + class Solution: + def containsPattern(self, arr: List[int], m: int, k: int) -> bool: + pattern_map = {} + for i in range(len(arr) - m * k + 1): + pattern = tuple(arr[i:i + m]) + pattern_map[pattern] = pattern_map.get(pattern, 0) + 1 + if pattern_map[pattern] >= k: + return True + return False + ``` + + + + + ```java + class Solution { + public boolean containsPattern(int[] arr, int m, int k) { + Map patternMap = new HashMap<>(); + for (int i = 0; i <= arr.length - m * k; i++) { + String pattern = Arrays.toString(Arrays.copyOfRange(arr, i, i + m)); + patternMap.put(pattern, patternMap.getOrDefault(pattern, 0) + 1); + if (patternMap.get(pattern) >= k) return true; + } + return false; + } + } + ``` + + + + + ```cpp + class Solution { + public: + bool containsPattern(vector& arr, int m, int k) { + unordered_map patternMap; + for (int i = 0; i <= arr.size() - m * k; i++) { + string pattern = ""; + for (int j = i; j < i + m; j++) { + pattern += to_string(arr[j]) + ","; + } + patternMap[pattern]++; + if (patternMap[pattern] >= k) return true; + } + return false; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n \cdot m)$$ +- Space Complexity: $$O(n \cdot m)$$ +- Where `n` is the length of the array `arr` and `m` is the length of the pattern. +- We iterate through the array once and store patterns in the hash map. +- The space complexity is proportional to the number of distinct patterns. + +
+
+ +:::tip Note + +By using these approaches, we can efficiently solve the Detect Pattern problem for the given constraints. + +::: +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/) +- **Solution Link:** [Detect Pattern Solution on LeetCode](https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/812851/JavaPythonC%2B%2B-Simple-Solution) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + diff --git a/solutions/lc-solutions/1500-1599/1567-maximum-length-of-subarray-with-positive-product.md b/solutions/lc-solutions/1500-1599/1567-maximum-length-of-subarray-with-positive-product.md new file mode 100644 index 0000000..07e0199 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1567-maximum-length-of-subarray-with-positive-product.md @@ -0,0 +1,246 @@ +--- +id: maximum-length-of-subarray-with-positive-product +title: 1567. Maximum Length of Subarray With Positive Product +sidebar_label: 1567. Maximum Length of Subarray With Positive Product +tags: + - Array + - Greedy + - Dynamic Programming +description: "This is a solution to the 1567. Maximum Length of Subarray With Positive Product problem on LeetCode." +--- + +## Problem Description + +Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive. + +A subarray of an array is a consecutive sequence of zero or more values taken out of that array. + +Return the maximum length of a subarray with positive product. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,-2,-3,4] +Output: 4 +Explanation: The array nums already has a positive product of 24. +``` + +**Example 2:** + +``` +Input: nums = [0,1,-2,-3,-4] +Output: 3 +Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6. +Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive. +``` + +### Constraints + +- `2 <= nums.length <= 10^5` + +## Solution for \1567. Maximum Length of Subarray With Positive Product Problem +### Steps +1. Initialize three variables: `maxLen`, `posLen`, and `negLen` to 0. + - `maxLen` will store the length of the longest subarray with a positive product. + - `posLen` will store the length of the current subarray with a positive product. + - `negLen` will store the length of the current subarray with a negative product. + +2. Iterate through each element `num` in the array `nums`: + - If `num` is greater than 0, it means the product of the current subarray remains positive: + - Increment `posLen` by 1. + - If `negLen` is greater than 0, increment `negLen` by 1, otherwise set `negLen` to 0. + - If `num` is less than 0, it means the product of the current subarray becomes negative: + - Swap the values of `posLen` and `negLen` (while adding 1 to `negLen`). + - If `posLen` was zero, set it to 0 after the swap. + - If `num` is equal to 0, it means the product of the subarray is reset: + - Set both `posLen` and `negLen` to 0. + - Update `maxLen` with the maximum value between `maxLen` and `posLen`. + +3. After iterating through all the elements, `maxLen` will contain the length of the longest subarray with a positive product. + + + +### Approach + + + + #### Implementation + ```jsx live + function Solution(arr) { + + function getMaxLen(nums) { + let maxLen = 0; + let posLen = 0; + let negLen = 0; + + for (let num of nums) { + if (num > 0) { + posLen++; + negLen = (negLen > 0) ? negLen + 1 : 0; + } else if (num < 0) { + let temp = posLen; + posLen = (negLen > 0) ? negLen + 1 : 0; + negLen = temp + 1; + } else { + posLen = 0; + negLen = 0; + } + maxLen = Math.max(maxLen, posLen); + } + + return maxLen; +} + + const input = [0,1,-2,-3,-4] + const output = getMaxLen(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n) $ + - Space Complexity: $ O(1)$ + + ## Code in Different Languages + + + + ```javascriptfunction getMaxLen(nums) { + let maxLen = 0; + let posLen = 0; + let negLen = 0; + + for (let num of nums) { + if (num > 0) { + posLen++; + negLen = (negLen > 0) ? negLen + 1 : 0; + } else if (num < 0) { + let temp = posLen; + posLen = (negLen > 0) ? negLen + 1 : 0; + negLen = temp + 1; + } else { + posLen = 0; + negLen = 0; + } + maxLen = Math.max(maxLen, posLen); + } + + return maxLen; +} + + ``` + + + + + ```python + class Solution: + def getMaxLen(self, nums): + maxLen = 0 + posLen = 0 + negLen = 0 + + for num in nums: + if num > 0: + posLen += 1 + negLen = negLen + 1 if negLen > 0 else 0 + elif num < 0: + temp = posLen + posLen = negLen + 1 if negLen > 0 else 0 + negLen = temp + 1 + else: + posLen = 0 + negLen = 0 + maxLen = max(maxLen, posLen) + + return maxLen + + ``` + + + + + ```java + import java.util.List; + +public class Solution { + public int getMaxLen(List nums) { + int maxLen = 0; + int posLen = 0; + int negLen = 0; + + for (int num : nums) { + if (num > 0) { + posLen++; + negLen = (negLen > 0) ? negLen + 1 : 0; + } else if (num < 0) { + int temp = posLen; + posLen = (negLen > 0) ? negLen + 1 : 0; + negLen = temp + 1; + } else { + posLen = 0; + negLen = 0; + } + maxLen = Math.max(maxLen, posLen); + } + + return maxLen; + } +} + + ``` + + + + ```cpp + class Solution { +public: + int getMaxLen(vector& nums) { + int maxLen = 0; + int posLen = 0; + int negLen = 0; + + for (int num : nums) { + if (num > 0) { + posLen++; + negLen = (negLen > 0) ? negLen + 1 : 0; + } else if (num < 0) { + int temp = posLen; + posLen = (negLen > 0) ? negLen + 1 : 0; + negLen = temp + 1; + } else { + posLen = 0; + negLen = 0; + } + maxLen = max(maxLen, posLen); + } + + return maxLen; + } +}; + +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [1567. Maximum Length of Subarray With Positive Product](https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/solutions) diff --git a/solutions/lc-solutions/1500-1599/1572-Matrix Diagonal Sum.md b/solutions/lc-solutions/1500-1599/1572-Matrix Diagonal Sum.md new file mode 100644 index 0000000..8e95091 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1572-Matrix Diagonal Sum.md @@ -0,0 +1,364 @@ +--- +id: matrix-diagonal-sum +title: Matrix Diagonal Sum Solution +sidebar_label: 1572-Matrix-Diagonal-Sum +tags: + - Matrix Diagonal Sum + - Array + - LeetCode + - Python + - JavaScript + - TypeScript + - Java + - C++ +description: "This is a solution to the Matrix Diagonal Sum problem on LeetCode." +--- + +In this page, we will solve the Matrix Diagonal Sum problem using multiple approaches. We will provide the implementation of the solution in Python, JavaScript, TypeScript, Java, and C++. + +## Problem Description + +Given a square matrix `mat`, return the sum of the matrix diagonals. + +Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. + +### Examples + +**Example 1:** + +```plaintext +Input: mat = [[1,2,3], + [4,5,6], + [7,8,9]] +Output: 25 +Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 +``` + +**Example 2:** + +```plaintext +Input: mat = [[1,1,1,1], + [1,1,1,1], + [1,1,1,1], + [1,1,1,1]] +Output: 8 +Explanation: Diagonals sum: 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 8 +``` + +### Constraints + +- $n == mat.length == mat[i].length$ +- $1 <= n <= 100$ +- $1 <= mat[i][j] <= 100$ + +--- + +## Solution for Matrix Diagonal Sum Problem + +### Intuition and Approach + +We can solve this problem by iterating over the matrix and summing up the elements on both diagonals. + + + + +### Approach: Iterative + +In this approach, we iterate through the matrix and add elements from the primary diagonal and the secondary diagonal. + +#### Implementation +```jsx live +function matrixDiagonalSum() { + const mat = [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9] + ]; + + const diagonalSum = function(mat) { + let sum = 0; + const n = mat.length; + for (let i = 0; i < n; i++) { + sum += mat[i][i]; // Primary diagonal + if (i !== n - 1 - i) { // Exclude middle element for odd-sized matrix + sum += mat[i][n - 1 - i]; // Secondary diagonal + } + } + return sum; + }; + + const result = diagonalSum(mat); + return ( +
+

+ Input: mat = {JSON.stringify(mat)} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function diagonalSum(mat) { + let sum = 0; + const n = mat.length; + for (let i = 0; i < n; i++) { + sum += mat[i][i]; // Primary diagonal + if (i !== n - 1 - i) { // Exclude middle element for odd-sized matrix + sum += mat[i][n - 1 - i]; // Secondary diagonal + } + } + return sum; + } + ``` + + + + + ```typescript + function diagonalSum(mat: number[][]): number { + let sum = 0; + const n = mat.length; + for (let i = 0; i < n; i++) { + sum += mat[i][i]; // Primary diagonal + if (i !== n - 1 - i) { // Exclude middle element for odd-sized matrix + sum += mat[i][n - 1 - i]; // Secondary diagonal + } + } + return sum; + } + ``` + + + + + ```python + class Solution: + def diagonalSum(self, mat: List[List[int]]) -> int: + diagonal_sum = 0 + n = len(mat) + for i in range(n): + diagonal_sum += mat[i][i] # Primary diagonal + if i != n - 1 - i: # Exclude middle element for odd-sized matrix + diagonal_sum += mat[i][n - 1 - i] # Secondary diagonal + return diagonal_sum + ``` + + + + + ```java + class Solution { + public int diagonalSum(int[][] mat) { + int sum = 0; + int n = mat.length; + for (int i = 0; i < n; i++) { + sum += mat[i][i]; // Primary diagonal + if (i != n - 1 - i) { // Exclude middle element for odd-sized matrix + sum += mat[i][n - 1 - i]; // Secondary diagonal + } + } + return sum; + } + } + ``` + + + + + ```cpp + class Solution { + public: + int diagonalSum(vector>& mat) { + int sum = 0; + int n = mat.size(); + for (int i = 0; i < n; i++) { + sum += mat[i][i]; // Primary diagonal + if (i != n - 1 - i) { // Exclude middle element for odd-sized matrix + sum += mat[i][n - 1 - i]; // Secondary diagonal + } + } + return sum; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(1)$$ +- Where `n` is the size of the square matrix `mat`. +- The time complexity is linear because we iterate through the matrix only once. +- The space complexity is constant as we use only a few variables irrespective of the size of the input. + +
+ + +### Approach: Optimized + +In this approach, we optimize the previous solution by iterating only once through the matrix. We use two pointers to traverse both diagonals simultaneously. + +#### Implementation + +```jsx live +function matrixDiagonalSum() { + const mat = [ + + + [1, 2, 3], + [4, 5, 6], + [7, 8, 9] + ]; + + const diagonalSum = function(mat) { + let sum = 0; + const n = mat.length; + for (let i = 0, j = n - 1; i < n; i++, j--) { + sum += mat[i][i]; // Primary diagonal + if (i !== j) { // Exclude middle element for odd-sized matrix + sum += mat[i][j]; // Secondary diagonal + } + } + return sum; + }; + + const result = diagonalSum(mat); + return ( +
+

+ Input: mat = {JSON.stringify(mat)} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function diagonalSum(mat) { + let sum = 0; + const n = mat.length; + for (let i = 0, j = n - 1; i < n; i++, j--) { + sum += mat[i][i]; // Primary diagonal + if (i !== j) { // Exclude middle element for odd-sized matrix + sum += mat[i][j]; // Secondary diagonal + } + } + return sum; + } + ``` + + + + + ```typescript + function diagonalSum(mat: number[][]): number { + let sum = 0; + const n = mat.length; + for (let i = 0, j = n - 1; i < n; i++, j--) { + sum += mat[i][i]; // Primary diagonal + if (i !== j) { // Exclude middle element for odd-sized matrix + sum += mat[i][j]; // Secondary diagonal + } + } + return sum; + } + ``` + + + + + ```python + class Solution: + def diagonalSum(self, mat: List[List[int]]) -> int: + diagonal_sum = 0 + n = len(mat) + for i in range(n): + diagonal_sum += mat[i][i] # Primary diagonal + if i != n - 1 - i: # Exclude middle element for odd-sized matrix + diagonal_sum += mat[i][n - 1 - i] # Secondary diagonal + return diagonal_sum + ``` + + + + + ```java + class Solution { + public int diagonalSum(int[][] mat) { + int sum = 0; + int n = mat.length; + for (int i = 0, j = n - 1; i < n; i++, j--) { + sum += mat[i][i]; // Primary diagonal + if (i != j) { // Exclude middle element for odd-sized matrix + sum += mat[i][j]; // Secondary diagonal + } + } + return sum; + } + } + ``` + + + + + ```cpp + class Solution { + public: + int diagonalSum(vector>& mat) { + int sum = 0; + int n = mat.size(); + for (int i = 0, j = n - 1; i < n; i++, j--) { + sum += mat[i][i]; // Primary diagonal + if (i != j) { // Exclude middle element for odd-sized matrix + sum += mat[i][j]; // Secondary diagonal + } + } + return sum; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(1)$$ +- Where `n` is the size of the square matrix `mat`. +- The time complexity is linear because we iterate through the matrix only once. +- The space complexity is constant as we use only a few variables irrespective of the size of the input. + +
+
+ +:::tip Note + +By using these approaches, we can efficiently solve the Matrix Diagonal Sum problem for the given constraints. + +::: +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/matrix-diagonal-sum/) +- **Solution Link:** [Matrix Diagonal Sum Solution on LeetCode](https://leetcode.com/problems/matrix-diagonal-sum/discuss/809393/Python-3-O(n)-solution-explained) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + diff --git a/solutions/lc-solutions/1500-1599/1576-Replace-All- to-Avoid-Consecutive-Repeating-Characters.md b/solutions/lc-solutions/1500-1599/1576-Replace-All- to-Avoid-Consecutive-Repeating-Characters.md new file mode 100644 index 0000000..d60ab96 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1576-Replace-All- to-Avoid-Consecutive-Repeating-Characters.md @@ -0,0 +1,449 @@ +--- +id: replace-all-s-to-avoid-consecutive-repeating-characters +title: Replace All ?'s to Avoid Consecutive Repeating Characters Solution +sidebar_label: 1576-Replace-All-Question-Marks-to-avoid-consecutive-repeating-characters +tags: + - String + - Greedy + - LeetCode + - Python + - JavaScript + - TypeScript + - Java + - C++ +description: "This is a solution to the Replace All ?'s to Avoid Consecutive Repeating Characters problem on LeetCode." +--- + +In this page, we will solve the Replace All ?'s to Avoid Consecutive Repeating Characters problem using multiple approaches: greedy and character replacement. We will provide the implementation of the solution in Python, JavaScript, TypeScript, Java, and C++. + +## Problem Description + +Given a string `s` containing only lowercase English letters and the '?' character, convert all the '?' characters into lowercase letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non-'?' characters. + +Return the final string after replacing all the '?' characters. + +It is guaranteed that there are no consecutive repeating characters in the given string except for '?'. + +A string `a` is considered lexicographically smaller than a string `b` if in the first position where `a` and `b` differ, string `a` has a character strictly smaller than the corresponding character in `b`. For example, `"abcc"` is lexicographically smaller than `"abcd"` because the first position they differ is at the fourth character, and 'c' is smaller than 'd'. + +### Examples + +**Example 1:** + +```plaintext +Input: s = "?zs" +Output: "azs" +Explanation: There are 25 possible characters for each position. The first position is '?', so we replace it with 'a'. The second position is 'z', so we keep it as is. The third position is 's', so we keep it as is. +``` + +**Example 2:** + +```plaintext +Input: s = "ubv?w" +Output: "ubvaw" +Explanation: The first position is 'u', so we keep it as is. The second position is 'b', so we keep it as is. The third position is 'v', so we keep it as is. The fourth position is '?', so we replace it with 'a'. The fifth position is 'w', so we keep it as is. +``` + +**Example 3:** + +```plaintext +Input: s = "j?qg??b" +Output: "jaqgacb" +``` + +**Example 4:** + +```plaintext +Input: s = "??yw?ipkj?" +Output: "abywaipkja" +``` + +### Constraints + +- $1 <= s.length <= 100$ +- `s` consists only of lowercase English letters and the '?' character. + +--- + +## Solution for Replace All ?'s to Avoid Consecutive Repeating Characters + +### Intuition and Approach + +The problem can be solved using different approaches. We will start with a greedy approach and then look at a character replacement approach. + + + + +### Approach 1: Greedy + +We iterate through the string and whenever we encounter a '?', we replace it with the smallest character that is different from its neighboring characters. + +#### Implementation +```jsx live +function modifyString() { + const s = "?zs"; + + const modifyString = function(s) { + s = s.split(''); + const n = s.length; + for (let i = 0; i < n; i++) { + if (s[i] === '?') { + let prev = i === 0 ? null : s[i - 1]; + let next = i === n - 1 ? null : s[i + 1]; + let candidate = 'a'; + while (candidate === prev || candidate === next) { + candidate = String.fromCharCode(candidate.charCodeAt(0) + 1); + } + s[i] = candidate; + } + } + return s.join(''); + }; + + const result = modifyString(s); + return ( +
+

+ Input: s = {JSON.stringify(s)} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function modifyString(s) { + s = s.split(''); + const n = s.length; + for (let i = 0; i < n; i++) { + if (s[i] === '?') { + let prev = i === 0 ? null : s[i - 1]; + let next = i === n - 1 ? null : s[i + 1]; + let candidate = 'a'; + while (candidate === prev || candidate === next) { + candidate = String.fromCharCode(candidate.charCodeAt(0) + 1); + } + s[i] = candidate; + } + } + return s.join(''); + } + ``` + + + + + ```typescript + function modifyString(s: string): string { + s = s.split(''); + const n = s.length; + for (let i = 0; i < n; i++) { + if (s[i] === '?') { + let prev = i === 0 ? null : s[i - 1]; + let next = i === n - 1 ? null : s[i + 1]; + let candidate = 'a'; + while (candidate === prev || candidate === next) { + candidate = String.fromCharCode(candidate.charCodeAt(0) + 1); + } + s[i] = candidate; + } + } + return s.join(''); + } + ``` + + + + + ```python + class Solution: + def modifyString(self, s: str) -> str: + s = list(s) + n = len(s) + for i in range(n): + if s[i] == '?': + prev = s[i - 1] if i > 0 else None + next = s[i + 1] if i < n - 1 else None + candidate = 'a' + while candidate == prev or candidate == next: + candidate = chr(ord(candidate) + 1) + s[i] = candidate + return ''.join(s) + ``` + + + + + ```java + class Solution { + public String modifyString(String s) { + char[] chars = s.toCharArray(); + int n = chars.length; + for (int i = 0; i < n; i++) { + if (chars[i] == '?') { + char prev = i == 0 ? 0 : chars[i - 1]; + char next = + + i == n - 1 ? 0 : chars[i + 1]; + char candidate = 'a'; + while (candidate == prev || candidate == next) { + candidate++; + } + chars[i] = candidate; + } + } + return new String(chars); + } + } + ``` + + + + + ```cpp + class Solution { + public: + string modifyString(string s) { + for (int i = 0; i < s.length(); ++i) { + if (s[i] == '?') { + char prev = i == 0 ? 0 : s[i - 1]; + char next = i == s.length() - 1 ? 0 : s[i + 1]; + char candidate = 'a'; + while (candidate == prev || candidate == next) { + candidate++; + } + s[i] = candidate; + } + } + return s; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(n)$$ +- Where `n` is the length of the string `s`. +- The time complexity is linear because we iterate through the string only once. +- The space complexity is also linear because we use an array to store the modified string. + +
+ + +### Approach 2: Character Replacement + +In this approach, we replace the '?' characters from left to right with characters based on the previous character and the next character. We maintain a variable to keep track of the previous character and update it while traversing the string. + +#### Implementation + +```jsx live +function modifyString() { + const s = "?zs"; + + const modifyString = function(s) { + let prev = ''; + const n = s.length; + const result = []; + for (let i = 0; i < n; i++) { + if (s[i] === '?') { + let next = i === n - 1 ? '' : s[i + 1]; + let candidate = 'a'; + while (candidate === prev || candidate === next) { + candidate = String.fromCharCode(candidate.charCodeAt(0) + 1); + } + result.push(candidate); + prev = candidate; + } else { + result.push(s[i]); + prev = s[i]; + } + } + return result.join(''); + }; + + const result = modifyString(s); + return ( +
+

+ Input: s = {JSON.stringify(s)} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function modifyString(s) { + let prev = ''; + const n = s.length; + const result = []; + for (let i = 0; i < n; i++) { + if (s[i] === '?') { + let next = i === n - 1 ? '' : s[i + 1]; + let candidate = 'a'; + while (candidate === prev || candidate === next) { + candidate = String.fromCharCode(candidate.charCodeAt(0) + 1); + } + result.push(candidate); + prev = candidate; + } else { + result.push(s[i]); + prev = s[i]; + } + } + return result.join(''); + } + ``` + + + + + ```typescript + function modifyString(s: string): string { + let prev = ''; + const n = s.length; + const result = []; + for (let i = 0; i < n; i++) { + if (s[i] === '?') { + let next = i === n - 1 ? '' : s[i + 1]; + let candidate = 'a'; + while (candidate === prev || candidate === next) { + candidate = String.fromCharCode(candidate.charCodeAt(0) + 1); + } + result.push(candidate); + prev = candidate; + } else { + result.push(s[i]); + prev = s[i]; + } + } + return result.join(''); + } + ``` + + + + + ```python + class Solution: + def modifyString(self, s: str) -> str: + prev = '' + result = [] + for char in s: + if char == '?': + next_char = s[s.index(char) + 1] if '?' in s[s.index(char) + 1:] else '' + candidate = 'a' + while candidate == prev or candidate == next_char: + candidate = chr(ord(candidate) + 1) + result.append(candidate) + prev = candidate + else: + result.append(char) + prev = char + return ''.join(result) + ``` + + + + + ```java + class Solution { + public String modifyString(String s) { + char prev = 0; + StringBuilder result = new StringBuilder(); + for (int i = 0; i < s.length(); i++) { + char current = s.charAt(i); + if (current == '?') { + char next = i == s.length() - 1 ? 0 : s.charAt(i + 1); + char candidate = 'a'; + while (candidate == prev || candidate == next) { + candidate++; + } + result.append(candidate); + prev = candidate; + } else { + result.append(current); + prev = current; + } + } + return result.toString(); + } + } + ``` + + + + + ```cpp + class Solution { + public: + string modifyString(string s) { + char prev = 0; + string result; + for (char current : s) { + if (current == '?') { + char next = s.empty() ? 0 : s[0]; + char candidate = 'a'; + while (candidate == prev || candidate == next) { + candidate++; + } + result += candidate; + prev = candidate; + } else { + result += current; + prev = current; + } + } + return result; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(n)$$ +- Where `n` is the length of the string `s`. +- The time complexity is linear because we iterate through the string only once. +- The space complexity is also linear because we use an array to store the modified + + string. + +
+
+ +:::tip Note + +By using these approaches, we can efficiently solve the Replace All ?'s to Avoid Consecutive Repeating Characters problem for the given constraints. + +::: +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/) +- **Solution Link:** [Replace All ?'s to Avoid Consecutive Repeating Characters Solution on LeetCode](https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/806961/JavaPython-3-Replace-?-with-other-than-adjacent-letters.-Clean-code) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + + diff --git a/solutions/lc-solutions/1500-1599/1584-min-cost-to-connect-all-points.md b/solutions/lc-solutions/1500-1599/1584-min-cost-to-connect-all-points.md new file mode 100644 index 0000000..58a7ef5 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1584-min-cost-to-connect-all-points.md @@ -0,0 +1,376 @@ +--- +id: min-cost-to-connect-all-points +title: Min Cost to Connect All Points +sidebar_label: 1584 - Min Cost to Connect All Points +tags: +- Array +- Union Find +- Graph +- Minimum Spanning Tree +description: "This is a solution to the Min Cost to Connect All Points problem on LeetCode." +--- + +## Problem Description +You are given an array points representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi].` + +The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: `|xi - xj| + |yi - yj|`, where |val| denotes the absolute value of val. + +Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points. + +### Examples +**Example 1:** +![image](https://assets.leetcode.com/uploads/2020/08/26/d.png) +``` +Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]] +Output: 20 +Explanation: +![image](https://assets.leetcode.com/uploads/2020/08/26/c.png) +We can connect the points as shown above to get the minimum cost of 20. +Notice that there is a unique path between every pair of points. + +``` + +### Constraints +- `1 <= points.length <= 1000` +- `-10^6 <= xi, yi <= 10^6` +- `All pairs (xi, yi) are distinct.` + +## Solution for Min Cost to Connect All Points +### Approach +#### Prim's algorithm: + +- Prim's algorithm is an algorithm for solving the optimization problem of finding the minimum spanning tree in a weighted connected graph within graph theory. A minimum spanning tree is a subset of the edges of the graph that forms a tree containing all vertices while minimizing the total weight of those edges. + +#### Overview of the Algorithm: + +- Calculate the distances between each pair of points and use Prim's algorithm to form the minimum spanning tree. +- Start from an initial point, mark it as visited, and select the point with the smallest distance among the unvisited points. +- Calculate the distances from the selected point to the unvisited points and store them in a cache. +- Add the minimum cost edge to the priority queue using the distances from the cache. +- Repeat the above steps until all points are visited, and calculate the minimum cost. +#### Specific Steps: + +#### Initial State: + +- n: Number of points +- min_cost: Minimum cost (initially 0) and return value +- visited: A list to indicate if each point is visited (initially all False) +- pq: Priority queue (initially (0, 0) indicating starting from point 0 with cost 0) +- cache: Dictionary for caching distances (initially empty) +#### Each Step: + +- Pop cost and point from pq (start from the initial point). +- If the point is already visited, skip this point. +- Otherwise, mark this point as visited and add the current cost to the minimum cost. +- Calculate distances from this point to all unvisited points and store them in the cache. Update the cache if the new distance is smaller. +- Add the point with the smallest distance among the unvisited points to the priority queue using distances from the cache. +- Repeat steps 3 to 5 until all points are visited. +- Return the final minimum cost. + + + + + + #### Implementation + ```jsx live + function Solution(arr) { + var minCostConnectPoints = function(points) { + let cost = 0; + const n = points.length; + const dist = Array(n).fill(Infinity); + dist[0] = 0; + let next = 0; + + for (let step = 1; step < n; step++) { + let min = Infinity; + let point = -1; + for (let i = 1; i < n; i++) { + if (dist[i] > 0) { + dist[i] = Math.min(dist[i], Math.abs(points[i][0] - points[next][0]) + Math.abs(points[i][1] - points[next][1])); + if (dist[i] < min) { + min = dist[i]; + point = i; + } + } + } + cost += min; + dist[point] = 0; + next = point; + } + + return cost; + }; + const input = [[0,0],[2,2],[3,10],[5,2],[7,0]] + const output =minCostConnectPoints(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n^2 * log(n)) $ + - Space Complexity: $ O(n)$ + + ## Code in Different Languages + + + + ```javascript + manhattDist(v1, v2) { + return Math.abs(v1[0] - v2[0]) + Math.abs(v1[1] - v2[1]); + } + + minCostConnectPoints(points) { + const n = points.length; + const adj = Array.from({ length: n }, () => []); + + for (let i = 0; i < n; i++) { + for (let j = i + 1; j < n; j++) { + const dist = this.manhattDist(points[i], points[j]); + adj[i].push([j, dist]); + adj[j].push([i, dist]); + } + } + + const pq = new MinPriorityQueue({ priority: x => x[0] }); + const vis = Array(n).fill(false); + pq.enqueue([0, 0]); + let cost = 0; + + while (!pq.isEmpty()) { + const [topEdgwWt, currNode] = pq.dequeue().element; + + if (vis[currNode]) continue; + vis[currNode] = true; + cost += topEdgwWt; + + for (const [adjPoint, edWt] of adj[currNode]) { + if (!vis[adjPoint]) { + pq.enqueue([edWt, adjPoint]); + } + } + } + + return cost; + } + ``` + + + + + ```typescript + class Solution { + manhattDist(v1: number[], v2: number[]): number { + return Math.abs(v1[0] - v2[0]) + Math.abs(v1[1] - v2[1]); + } + + minCostConnectPoints(points: number[][]): number { + const n = points.length; + const adj: [number, number][][] = Array.from({ length: n }, () => []); + + for (let i = 0; i < n; i++) { + for (let j = i + 1; j < n; j++) { + const dist = this.manhattDist(points[i], points[j]); + adj[i].push([j, dist]); + adj[j].push([i, dist]); + } + } + + const pq = new MinPriorityQueue({ priority: (x: [number, number]) => x[0] }); + const vis = Array(n).fill(false); + pq.enqueue([0, 0]); + let cost = 0; + + while (!pq.isEmpty()) { + const [topEdgwWt, currNode] = pq.dequeue().element; + + if (vis[currNode]) continue; + vis[currNode] = true; + cost += topEdgwWt; + + for (const [adjPoint, edWt] of adj[currNode]) { + if (!vis[adjPoint]) { + pq.enqueue([edWt, adjPoint]); + } + } + } + + return cost; + } +} + + ``` + + + + ```python + import heapq + +class Solution: + def manhattDist(self, v1, v2): + return abs(v1[0] - v2[0]) + abs(v1[1] - v2[1]) + + def minCostConnectPoints(self, points): + n = len(points) + adj = [[] for _ in range(n)] + + for i in range(n): + for j in range(i + 1, n): + dist = self.manhattDist(points[i], points[j]) + adj[i].append((j, dist)) + adj[j].append((i, dist)) + + pq = [(0, 0)] # (distance, point) + vis = [False] * n + cost = 0 + + while pq: + topEdgwWt, currNode = heapq.heappop(pq) + + if vis[currNode]: + continue + vis[currNode] = True + cost += topEdgwWt + + for adjPoint, edWt in adj[currNode]: + if not vis[adjPoint]: + heapq.heappush(pq, (edWt, adjPoint)) + + return cost + + ``` + + + + + ```java + import java.util.*; + +class Solution { + private int manhattDist(int[] v1, int[] v2) { + return Math.abs(v1[0] - v2[0]) + Math.abs(v1[1] - v2[1]); + } + + public int minCostConnectPoints(int[][] points) { + int n = points.length; + List> adj = new ArrayList<>(); + + for (int i = 0; i < n; i++) { + adj.add(new ArrayList<>()); + } + + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + int dist = manhattDist(points[i], points[j]); + adj.get(i).add(new int[]{j, dist}); + adj.get(j).add(new int[]{i, dist}); + } + } + + PriorityQueue pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); + boolean[] vis = new boolean[n]; + pq.add(new int[]{0, 0}); // {distance, point} + int cost = 0; + + while (!pq.isEmpty()) { + int[] curr = pq.poll(); + int topEdgwWt = curr[0]; + int currNode = curr[1]; + + if (vis[currNode]) continue; + vis[currNode] = true; + cost += topEdgwWt; + + for (int[] neighbor : adj.get(currNode)) { + int adjPoint = neighbor[0]; + int edWt = neighbor[1]; + if (!vis[adjPoint]) { + pq.add(new int[]{edWt, adjPoint}); + } + } + } + + return cost; + } +} + + ``` + + + + + + ```cpp + class Solution { +public: + int manhattDist(vector&v1 , vector&v2) + { + return abs(abs(v1[0]-v2[0]) + abs(v1[1]-v2[1])); + } + int minCostConnectPoints(vector>& points) { + int n = points.size(); + vector> adj[n]; //{point , cost or Manhattan dist} + + //we have to make a adjacency list fom every point to every other point + for(int i=0; i , vector> , greater> > pq; + // {distance , point} + vector vis(n,0); + pq.push({0,0}); //starting from 0 as source + int Cost=0; + while(!pq.empty()) + { + auto it = pq.top(); + pq.pop(); + int CurrNode = it.second ; + int topEdgwWt = it.first; + + if(vis[CurrNode]==1) continue; + + vis[CurrNode]=1; + + Cost+=topEdgwWt; + for(auto it: adj[CurrNode]) + { + int adjPoint=it.first; + int edWt=it.second; + if(!vis[adjPoint]) + { + pq.push({edWt , adjPoint}); + } + } + } + return Cost; + } +}; +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [ Min Cost to Connect All Points](https://leetcode.com/problems/min-cost-to-connect-all-points/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/min-cost-to-connect-all-points/description/) + diff --git a/solutions/lc-solutions/1500-1599/1588-Sum of All Odd Length Subarrays.md b/solutions/lc-solutions/1500-1599/1588-Sum of All Odd Length Subarrays.md new file mode 100644 index 0000000..09c724e --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1588-Sum of All Odd Length Subarrays.md @@ -0,0 +1,388 @@ +--- +id: sum-of-all-odd-length-subarrays +title: Sum of All Odd Length Subarrays Solution +sidebar_label: 1588-Sum-of-All-Odd-Length-Subarrays +tags: + - Array + - Prefix Sum + - LeetCode + - Python + - JavaScript + - TypeScript + - Java + - C++ +description: "This is a solution to the Sum of All Odd Length Subarrays problem on LeetCode." +--- + +In this page, we will solve the Sum of All Odd Length Subarrays problem using multiple approaches: brute-force and prefix sum optimization. We will provide the implementation of the solution in Python, JavaScript, TypeScript, Java, and C++. + +## Problem Description + +Given an array of positive integers `arr`, calculate the sum of all possible odd-length subarrays. + +A subarray is a contiguous subsequence of the array. + +Return the sum of all odd-length subarrays of `arr`. + +### Examples + +**Example 1:** + +```plaintext +Input: arr = [1,4,2,5,3] +Output: 58 +Explanation: The odd-length subarrays of `arr` and their sums are: +- [1] => 1 +- [4] => 4 +- [2] => 2 +- [5] => 5 +- [3] => 3 +- [1,4,2] => 7 +- [4,2,5] => 11 +- [2,5,3] => 10 +- [1,4,2,5,3] => 15 +If we sum everything, we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58. +``` + +**Example 2:** + +```plaintext +Input: arr = [1,2] +Output: 3 +Explanation: There are only 2 elements. So, only subarrays of length 1 and 2 will be considered. The sum of them is 1 + 2 = 3. +``` + +**Example 3:** + +```plaintext +Input: arr = [10,11,12] +Output: 66 +``` + +### Constraints + +- $1 <= arr.length <= 100$ +- $1 <= arr[i] <= 1000$ + +--- + +## Solution for Sum of All Odd Length Subarrays + +### Intuition and Approach + +The problem can be solved using different approaches. We will start with a brute-force approach and then look at an optimized approach using prefix sums. + + + + +### Approach 1: Brute Force + +We iterate through all possible subarrays of odd lengths and calculate their sums. + +#### Implementation +```jsx live +function sumOfOddLengthSubarrays() { + const arr = [1, 4, 2, 5, 3]; + + const sumOddLengthSubarrays = function(arr) { + let result = 0; + for (let i = 0; i < arr.length; i++) { + for (let j = i; j < arr.length; j += 2) { + for (let k = i; k <= j; k++) { + result += arr[k]; + } + } + } + return result; + }; + + const result = sumOddLengthSubarrays(arr); + return ( +
+

+ Input: arr = {JSON.stringify(arr)} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function sumOddLengthSubarrays(arr) { + let result = 0; + for (let i = 0; i < arr.length; i++) { + for (let j = i; j < arr.length; j += 2) { + for (let k = i; k <= j; k++) { + result += arr[k]; + } + } + } + return result; + } + ``` + + + + + ```typescript + function sumOddLengthSubarrays(arr: number[]): number { + let result = 0; + for (let i = 0; i < arr.length; i++) { + for (let j = i; j < arr.length; j += 2) { + for (let k = i; k <= j; k++) { + result += arr[k]; + } + } + } + return result; + } + ``` + + + + + ```python + class Solution: + def sumOddLengthSubarrays(self, arr: List[int]) -> int: + result = 0 + for i in range(len(arr)): + for j in range(i, len(arr), 2): + result += sum(arr[i:j+1]) + return result + ``` + + + + + ```java + class Solution { + public int sumOddLengthSubarrays(int[] arr) { + int result = 0; + for (int i = 0; i < arr.length; i++) { + for (int j = i; j < arr.length; j += 2) { + for (int k = i; k <= j; k++) { + result += arr[k]; + } + } + } + return result; + } + } + ``` + + + + + ```cpp + class Solution { + public: + int sumOddLengthSubarrays(vector& arr) { + int result = 0; + for (int i = 0; i < arr.size(); i++) { + for (int j = i; j < arr.size(); j += 2) { + for (int k = i; k <= j; k++) { + result += arr[k]; + } + } + } + return result; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n^3)$$ +- Space Complexity: $$O(1)$$ +- Where `n` is the length of the array `arr`. +- The time complexity is cubic due to three nested loops iterating through the array. +- The space complexity is constant as no additional space is required beyond a few variables. + +
+ + +### Approach 2: Prefix Sum + +We can optimize the brute-force solution by precomputing prefix sums. This allows us to calculate the sum of any subarray in constant time. + +#### Implementation + +```jsx live +function sumOfOddLengthSubarrays() { + const arr = [1, 4, 2, 5, 3]; + + const sumOddLengthSubarrays = function(arr) { + const prefixSum = [0]; + for (let num of arr) { + prefixSum.push(prefixSum[prefixSum.length - 1] + num); + } + + let result = 0; + for (let i = 0; i < arr.length; i++) { + for (let j = i; j < arr.length; j += 2) { + result += prefixSum[j + 1] - prefixSum[i]; + } + } + + return result; + }; + + const result = sumOddLengthSubarrays(arr); + return ( +
+

+ Input: arr = {JSON.stringify(arr)} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Codes in Different Languages + + + + + ```javascript + function sumOddLengthSubarrays(arr) { + const prefixSum = [0]; + for (let num of arr) { + prefixSum.push(prefixSum[prefixSum.length - 1] + num); + } + + let result = 0; + for (let i = 0; i < arr.length; i++) { + for (let j = i; j < arr.length; j += 2) { + result += prefixSum[j + 1] - prefixSum[i]; + } + } + + return result; + } + ``` + + + + + ```typescript + function sumOddLengthSubarrays(arr: number[]): number { + const prefixSum = [0]; + for (let num of arr) { + prefixSum.push(prefixSum[prefixSum.length - 1] + num); + } + + let result = 0; + for (let i = 0; i < arr.length; i++) { + for (let j = i; j < arr.length; j += 2) { + result += prefixSum[j + 1] - prefixSum[i]; + } + } + + return result; + } + ``` + + + + + ```python + class Solution: + def sumOddLengthSubarrays(self, arr: List[int]) -> int: + prefix_sum = [0] + for num in arr: + prefix_sum.append(prefix_sum[-1] + num) + + result = 0 + for i in range(len(arr)): + for j in range(i, len(arr), 2): + result += prefix_sum[j + 1] - prefix_sum[i] + + return result + ``` + + + + + ```java + class Solution { + public int sumOddLengthSubarrays(int[] arr) { + int[] prefixSum = new int[arr.length + 1]; + for (int i = 0; i < arr.length; i++) { + prefixSum[i + 1] = prefixSum[i] + arr[i]; + } + + int result = 0; + for (int i = 0; i < arr.length; i++) { + for (int j = i; j < arr.length; j += 2) { + result += prefixSum[j + 1] - prefixSum[i]; + } + } + + return result; + } + } + ``` + + + + + ```cpp + class Solution { + public: + int sumOddLengthSubarrays(vector& arr) { + vector prefixSum(arr.size() + 1, 0); + for (int i = 0; i < arr.size(); i++) { + prefixSum[i + 1] = prefixSum[i] + arr[i]; + } + + int result = 0; + for (int i = 0; i < arr.size(); i++) { + for (int j = i; j < arr.size(); j += 2) { + result += prefixSum[j + 1] - prefixSum[i]; + } + } + + return result; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n^2)$$ +- Space Complexity: $$O(n)$$ +- Where `n` is the length of the array `arr`. +- The time complexity is quadratic due to two nested loops iterating through the array. +- The space complexity is linear as we use extra space to store prefix sums. + +
+
+ +:::tip Note + +By using these approaches, we can efficiently solve the Sum of All Odd Length Subarrays problem for the given constraints. + +::: +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/sum-of-all-odd-length-subarrays/) +- **Solution Link:** [Sum of All Odd Length Subarrays Solution on LeetCode](https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/851730/Brute-Force-and-Prefix-Sum-Solutions-in-Python-Java-JavaScript-C%2B%2B) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + diff --git a/solutions/lc-solutions/1500-1599/1590-Make-Sum-Divisible-By-P.md b/solutions/lc-solutions/1500-1599/1590-Make-Sum-Divisible-By-P.md new file mode 100644 index 0000000..68048f8 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1590-Make-Sum-Divisible-By-P.md @@ -0,0 +1,479 @@ +--- + +id: make-sum-divisible-by-p +title: Make Sum Divisible by P +sidebar_label: 1590-Make-Sum-Divisible-By-P +tags: + - Array + - Hash Table + - Prefix Sum + - LeetCode + - Python + - JavaScript + - TypeScript + - Java + - C++ +description: "This is a solution to the Make Sum Divisible by P problem on LeetCode." + +--- + +In this page, we will solve the Make Sum Divisible by P problem using different approaches. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +Given an array of positive integers `nums`, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by `p`. It is guaranteed that there is an answer. If this is not possible, return -1. + +### Examples + +**Example 1:** + +```plaintext +Input: nums = [3,1,4,2], p = 6 +Output: 1 +Explanation: The sum of the array is 10, and the sum modulo 6 is 4. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6. +``` + +**Example 2:** + +```plaintext +Input: nums = [6,3,5,2], p = 9 +Output: 2 +Explanation: The sum of the array is 16, and the sum modulo 9 is 7. We can remove the subarray [5,2], and the sum of the remaining elements is 9, which is divisible by 9. +``` + +### Constraints + +- $1 \leq nums.length \leq 10^5$ +- $1 \leq nums[i] \leq 10^9$ +- $1 \leq p \leq 10^9$ + +--- + +## Solution for Make Sum Divisible by P + +### Intuition and Approach + +To solve the problem, we need to remove the smallest subarray such that the sum of the remaining elements is divisible by `p`. One efficient way to approach this is by using the prefix sum and a hash map. + + + + +### Approach 1: Prefix Sum and HashMap + +We calculate the prefix sum and use a hash map to store the remainder when each prefix sum is divided by `p`. This allows us to quickly find the smallest subarray whose removal makes the remaining sum divisible by `p`. + +#### Implementation + +```jsx live +function makeSumDivisibleByP() { + const nums = [3, 1, 4, 2]; + const p = 6; + + const minSubarray = function(nums, p) { + const totalSum = nums.reduce((acc, num) => acc + num, 0); + const remainder = totalSum % p; + if (remainder === 0) return 0; + + const prefixSum = new Map(); + prefixSum.set(0, -1); + + let currentSum = 0; + let minLength = Infinity; + + for (let i = 0; i < nums.length; i++) { + currentSum += nums[i]; + const currentRemainder = currentSum % p; + + const targetRemainder = (currentRemainder - remainder + p) % p; + if (prefixSum.has(targetRemainder)) { + minLength = Math.min(minLength, i - prefixSum.get(targetRemainder)); + } + + prefixSum.set(currentRemainder, i); + } + + return minLength === Infinity ? -1 : minLength; + }; + + const result = minSubarray(nums, p); + return ( +
+

+ Input: nums = {JSON.stringify(nums)}, p = {p} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function minSubarray(nums, p) { + const totalSum = nums.reduce((acc, num) => acc + num, 0); + const remainder = totalSum % p; + if (remainder === 0) return 0; + + const prefixSum = new Map(); + prefixSum.set(0, -1); + + let currentSum = 0; + let minLength = Infinity; + + for (let i = 0; i < nums.length; i++) { + currentSum += nums[i]; + const currentRemainder = currentSum % p; + + const targetRemainder = (currentRemainder - remainder + p) % p; + if (prefixSum.has(targetRemainder)) { + minLength = Math.min(minLength, i - prefixSum.get(targetRemainder)); + } + + prefixSum.set(currentRemainder, i); + } + + return minLength === Infinity ? -1 : minLength; + } + ``` + + + + + ```typescript + function minSubarray(nums: number[], p: number): number { + const totalSum = nums.reduce((acc, num) => acc + num, 0); + const remainder = totalSum % p; + if (remainder === 0) return 0; + + const prefixSum = new Map(); + prefixSum.set(0, -1); + + let currentSum = 0; + let minLength = Infinity; + + for (let i = 0; i < nums.length; i++) { + currentSum += nums[i]; + const currentRemainder = currentSum % p; + + const targetRemainder = (currentRemainder - remainder + p) % p; + if (prefixSum.has(targetRemainder)) { + minLength = Math.min(minLength, i - prefixSum.get(targetRemainder)!); + } + + prefixSum.set(currentRemainder, i); + } + + return minLength === Infinity ? -1 : minLength; + } + ``` + + + + + ```python + class Solution: + def minSubarray(self, nums: List[int], p: int) -> int: + total_sum = sum(nums) + remainder = total_sum % p + if remainder == 0: + return 0 + + prefix_sum = {0: -1} + current_sum = 0 + min_length = float('inf') + + for i, num in enumerate(nums): + current_sum += num + current_remainder = current_sum % p + + target_remainder = (current_remainder - remainder + p) % p + if target_remainder in prefix_sum: + min_length = min(min_length, i - prefix_sum[target_remainder]) + + prefix_sum[current_remainder] = i + + return min_length if min_length != float('inf') else -1 + ``` + + + + + ```java + import java.util.HashMap; + import java.util.Map; + + class Solution { + public int minSubarray(int[] nums, int p) { + int totalSum = 0; + for (int num : nums) { + totalSum += num; + } + int remainder = totalSum % p; + if (remainder == 0) { + return 0; + } + + Map prefixSum = new HashMap<>(); + prefixSum.put(0, -1); + + int currentSum = 0; + int minLength = Integer.MAX_VALUE; + + for (int i = 0; i < nums.length; i++) { + currentSum += nums[i]; + int currentRemainder = currentSum % p; + + int targetRemainder = (currentRemainder - remainder + p) % p; + if (prefixSum.containsKey(targetRemainder)) { + minLength = Math.min(minLength, i - prefixSum.get(targetRemainder)); + } + + prefixSum.put(currentRemainder, i); + } + + return minLength == Integer.MAX_VALUE ? -1 : minLength; + } + } + ``` + + + + + ```cpp + #include + #include + #include + #include + + class Solution { + public: + int minSubarray(std::vector& nums, int p) { + int totalSum = std::accumulate(nums.begin(), nums.end(), 0); + int remainder = totalSum % p; + if (remainder == 0) return 0; + + std::unordered_map prefixSum; + prefixSum[0] = -1; + + int currentSum = 0; + int minLength = INT_MAX; + + for (int i = 0; i < nums.size(); ++i) { + currentSum += nums[i]; + int currentRemainder = currentSum %``` + p; + + int targetRemainder = (currentRemainder - remainder + p) % p; + if (prefixSum.count(targetRemainder)) { + minLength = std::min(minLength, i - prefixSum[targetRemainder]); + } + + prefixSum[currentRemainder] = i; + } + + return minLength == INT_MAX ? -1 : minLength; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$, where $$n$$ is the length of the `nums` array. +- Space Complexity: $$O(n)$$, for storing the prefix sum and remainder in the hash map. + +
+ + + +### Approach 2: Brute Force + +Although less efficient than the prefix sum approach, we can solve the problem using a brute force approach. We iterate through all possible subarrays and check if removing them would make the sum divisible by `p`. + +#### Implementation + +```jsx live +function makeSumDivisibleByP() { + const nums = [6,3,5,2]; + const p = 9; + + const minSubarray = function(nums, p) { + const n = nums.length; + let minLength = Infinity; + + for (let i = 0; i < n; i++) { + let sum = 0; + for (let j = i; j < n; j++) { + sum += nums[j]; + if ((sum % p === 0) && ((j - i + 1) < minLength)) { + minLength = j - i + 1; + } + } + } + + return minLength === Infinity ? -1 : minLength; + }; + + const result = minSubarray(nums, p); + return ( +
+

+ Input: nums = {JSON.stringify(nums)}, p = {p} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function minSubarray(nums, p) { + const n = nums.length; + let minLength = Infinity; + + for (let i = 0; i < n; i++) { + let sum = 0; + for (let j = i; j < n; j++) { + sum += nums[j]; + if ((sum % p === 0) && ((j - i + 1) < minLength)) { + minLength = j - i + 1; + } + } + } + + return minLength === Infinity ? -1 : minLength; + } + ``` + + + + + ```typescript + function minSubarray(nums: number[], p: number): number { + const n = nums.length; + let minLength = Infinity; + + for (let i = 0; i < n; i++) { + let sum = 0; + for (let j = i; j < n; j++) { + sum += nums[j]; + if ((sum % p === 0) && ((j - i + 1) < minLength)) { + minLength = j - i + 1; + } + } + } + + return minLength === Infinity ? -1 : minLength; + } + ``` + + + + + ```python + class Solution: + def minSubarray(self, nums: List[int], p: int) -> int: + n = len(nums) + min_length = float('inf') + + for i in range(n): + sum = 0 + for j in range(i, n): + sum += nums[j] + if sum % p == 0 and j - i + 1 < min_length: + min_length = j - i + 1 + + return min_length if min_length != float('inf') else -1 + ``` + + + + + ```java + class Solution { + public int minSubarray(int[] nums, int p) { + int n = nums.length; + int minLength = Integer.MAX_VALUE; + + for (int i = 0; i < n; i++) { + int sum = 0; + for (int j = i; j < n; j++) { + sum += nums[j]; + if (sum % p == 0 && (j - i + 1) < minLength) { + minLength = j - i + 1; + } + } + } + + return minLength == Integer.MAX_VALUE ? -1 : minLength; + } + } + ``` + + + + + ```cpp + #include + #include + + class Solution { + public: + int minSubarray(std::vector& nums, int p) { + int n = nums.size(); + int minLength = INT_MAX; + + for (int i = 0; i < n; i++) { + int sum = 0; + for (int j = i; j < n; j++) { + sum += nums[j]; + if (sum % p == 0 && (j - i + 1) < minLength) { + minLength = j - i + 1; + } + } + } + + return minLength == INT_MAX ? -1 : minLength; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n^2)$$, where $$n$$ is the length of the `nums` array, due to the nested loops. +- Space Complexity: $$O(1)$$, as no extra space is used except for a few variables. + +
+
+ +:::tip + +By using either the prefix sum and hash map approach or the brute force approach, we can efficiently solve the Make Sum Divisible by P problem. The choice of implementation language depends on the specific requirements and constraints of the problem. + +::: + +## References + +- **LeetCode Problem:** [Make Sum Divisible by P](https://leetcode.com/problems/make-sum-divisible-by-p/) +- **Solution Link:** [Make Sum Divisible by P Solution on LeetCode](https://leetcode.com/problems/make-sum-divisible-by-p/solution/) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + + \ No newline at end of file diff --git a/solutions/lc-solutions/1500-1599/1592-Rearrange-Spaces-between-words.md b/solutions/lc-solutions/1500-1599/1592-Rearrange-Spaces-between-words.md new file mode 100644 index 0000000..ea70368 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1592-Rearrange-Spaces-between-words.md @@ -0,0 +1,702 @@ +--- + +id: rearrange-spaces-between-words +title: Rearrange Spaces Between Words +sidebar_label: 1592-Rearrange-Spaces-Between-Words +tags: + - String + - LeetCode + - Python + - JavaScript + - TypeScript + - Java + - C++ +description: "This is a solution to the Rearrange Spaces Between Words problem on LeetCode." + +--- + +In this page, we will solve the Rearrange Spaces Between Words problem using different approaches. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` contains at least one word. + +Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot distribute all the spaces equally, place the extra spaces at the end, including between the last word and the end of the string. + +### Examples + +**Example 1:** + +```plaintext +Input: text = " this is a sentence " +Output: "this is a sentence" +``` + +**Example 2:** + +```plaintext +Input: text = " practice makes perfect" +Output: "practice makes perfect " +``` + +### Constraints + +- $1 <= text.length <= 100$ +- `text` consists of lowercase English letters and spaces. +- `text` contains at least one word. + +--- + +## Solution for Rearrange Spaces Between Words + +### Intuition and Approach + +To solve this problem, we can follow these steps: + +1. Count the total number of spaces in the input string. +2. Split the input string into words. +3. Calculate the number of spaces that should be placed between words and the number of remaining spaces. +4. Construct the result string by joining the words with the calculated spaces and appending the remaining spaces at the end if needed. + + + + +### Approach 1: Splitting and Joining + +We first split the text into words and count the spaces. Then, we calculate the spaces to distribute between words and the remaining spaces. Finally, we join the words with the calculated spaces and add the remaining spaces at the end if necessary. + +#### Implementation + +```jsx live +function rearrangeSpacesBetweenWords() { + const text = " this is a sentence "; + + const rearrangeSpaces = function(text) { + const totalSpaces = text.split('').filter(c => c === ' ').length; + const words = text.trim().split(/\s+/); + const numWords = words.length; + + if (numWords === 1) { + return words[0] + ' '.repeat(totalSpaces); + } + + const spacesBetweenWords = Math.floor(totalSpaces / (numWords - 1)); + const remainingSpaces = totalSpaces % (numWords - 1); + + return words.join(' '.repeat(spacesBetweenWords)) + ' '.repeat(remainingSpaces); + }; + + const result = rearrangeSpaces(text); + return ( +
+

+ Input: text = "{text}" +

+

+ Output: "{result}" +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function rearrangeSpaces(text) { + const totalSpaces = text.split('').filter(c => c === ' ').length; + const words = text.trim().split(/\s+/); + const numWords = words.length; + + if (numWords === 1) { + return words[0] + ' '.repeat(totalSpaces); + } + + const spacesBetweenWords = Math.floor(totalSpaces / (numWords - 1)); + const remainingSpaces = totalSpaces % (numWords - 1); + + return words.join(' '.repeat(spacesBetweenWords)) + ' '.repeat(remainingSpaces); + } + ``` + + + + + ```typescript + function rearrangeSpaces(text: string): string { + const totalSpaces = text.split('').filter(c => c === ' ').length; + const words = text.trim().split(/\s+/); + const numWords = words.length; + + if (numWords === 1) { + return words[0] + ' '.repeat(totalSpaces); + } + + const spacesBetweenWords = Math.floor(totalSpaces / (numWords - 1)); + const remainingSpaces = totalSpaces % (numWords - 1); + + return words.join(' '.repeat(spacesBetweenWords)) + ' '.repeat(remainingSpaces); + } + ``` + + + + + ```python + class Solution: + def rearrangeSpaces(self, text: str) -> str: + total_spaces = text.count(' ') + words = text.split() + num_words = len(words) + + if num_words == 1: + return words[0] + ' ' * total_spaces + + spaces_between_words = total_spaces // (num_words - 1) + remaining_spaces = total_spaces % (num_words - 1) + + return (' ' * spaces_between_words).join(words) + ' ' * remaining_spaces + ``` + + + + + ```java + class Solution { + public String rearrangeSpaces(String text) { + int totalSpaces = 0; + for (char c : text.toCharArray()) { + if (c == ' ') { + totalSpaces++; + } + } + + String[] words = text.trim().split("\\s+"); + int numWords = words.length; + + if (numWords == 1) { + return words[0] + " ".repeat(totalSpaces); + } + + int spacesBetweenWords = totalSpaces / (numWords - 1); + int remainingSpaces = totalSpaces % (numWords - 1); + + return String.join(" ".repeat(spacesBetweenWords), words) + " ".repeat(remainingSpaces); + } + } + ``` + + + + + ```cpp + #include + #include + #include + #include + + class Solution { + public: + std::string rearrangeSpaces(std::string text) { + int totalSpaces = std::count(text.begin(), text.end(), ' '); + std::istringstream iss(text); + std::vector words; + std::string word; + while (iss >> word) { + words.push_back(word); + } + int numWords = words.size(); + + if (numWords == 1) { + return words[0] + std::string(totalSpaces, ' '); + } + + int spacesBetweenWords = totalSpaces / (numWords - 1); + int remainingSpaces = totalSpaces % (numWords - 1); + + std::string result; + for (int i = 0; i < numWords - 1; ++i) { + result += words[i] + std::string(spacesBetweenWords, ' '); + } + result += words[numWords - 1] + std::string(remainingSpaces, ' '); + return result; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ where n is the length of the input string. +- Space Complexity: $$O(n)$$ for storing the words and the result string. + +
+ + + +### Approach 2: Regex Splitting + +In this approach, we use regular expressions to split the text into words and spaces. This can sometimes provide a more straightforward way to handle the spaces and words. + +#### Implementation + +```jsx live +function rearrangeSpacesBetweenWords() { + const text = " practice makes perfect"; + + const rearrangeSpaces = function(text) { + const words = text.match(/\b\w+\b/g); + const totalSpaces = text.length - words.reduce((acc, word) => acc + word.length, 0); + const numWords = words.length; + + if (numWords === 1) { + return words[0] + ' '.repeat(totalSpaces); + } + + const spacesBetweenWords = Math.floor(totalSpaces / (numWords - 1)); + const remainingSpaces = totalSpaces % (numWords - 1); + + return words.join(' '.repeat(spacesBetweenWords)) + ' '.repeat(remainingSpaces); + }; + + const result = rearrangeSpaces(text); + return ( +
+

+ Input: text = "{text}" +

+

+ Output: "{result}" +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function rearrangeSpaces(text) { + const words = text.match(/\b\w+\b/g); + const totalSpaces = text.length - words.reduce((acc, word) => acc + word.length, 0); + const numWords = words.length; + + if (numWords === 1) { + return words[0] + ' '.repeat(totalSpaces); + } + + const spacesBetweenWords = Math.floor(totalSpaces / (numWords - 1)); + const remainingSpaces = totalSpaces % (numWords - 1); + + return words.join(' '.repeat(spacesBetweenWords)) + ' '.repeat(remainingSpaces); + } + ``` + + + + + ```typescript + function rearrangeSpaces(text: string): string { + const words = text.match(/\b\w+\b/g); + const totalSpaces = text.length - words.reduce((acc, word) => acc + word.length, 0); + const numWords = words.length; + + if (numWords === 1) { + return words[0] + ' '.repeat(totalSpaces); + } + + const spacesBetweenWords = Math.floor(totalSpaces / (numWords - 1)); + const remainingSpaces = totalSpaces % (numWords - 1); + + return words.join(' '.repeat(spacesBetweenWords)) + ' '.repeat(remainingSpaces); + } + ``` + + + + + ```python + class Solution: + def rearrangeSpaces(self, text: str) -> str: + words = re.findall(r'\b\w+\b', text) + total_spaces = len(text) - sum(len(word) for word in words) + num_words = len(words) + + if num_words == 1: + return words[0] + ' ' * total_spaces + + spaces_between_words = total_spaces // (num_words - 1) + remaining_spaces = total_spaces % (num_words - 1) + + return (' ' * spaces_between_words).join(words) + ' ' * remaining_spaces + ``` + + + + + ```java + class Solution { + public String rearrangeSpaces(String text) { + List words = new ArrayList<>(); + Matcher m = Pattern.compile("\\b\\w+\\b").matcher(text); + while (m.find()) { + words.add(m.group()); + } + int totalSpaces = text.length() - words.stream().mapToInt(String::length).sum(); + int numWords = words.size(); + + if (numWords == 1) { + return words.get(0) + " ".repeat(totalSpaces); + } + + int spacesBetweenWords = totalSpaces / (numWords - 1); + int remainingSpaces = totalSpaces % (numWords - 1); + + return String.join(" ".repeat(spacesBetweenWords), words) + " ".repeat(remainingSpaces); + } + } + ``` + + + + + ```cpp + #include + #include + #include + #include + #include + + class Solution { + public: + std::string rearrangeSpaces(std::string text) { + std::regex word_regex("\\b\\w+\\b"); + auto words_begin = std::sregex_iterator(text.begin(), text.end(), word_regex); + auto words_end = std::sregex_iterator(); + + std::vector words; + for (std::sregex_iterator i = words_begin; i != words_end; ++i) { + words.push_back((*i).str()); + } + + int totalSpaces = text.length() - std::accumulate(words.begin(), words.end(), 0, [](int sum, const std::string& word) { return sum + word.length(); }); + int numWords = words.size(); + + if (numWords == 1) { + return words[0] + std::string(totalSpaces, ' '); + } + + int spacesBetweenWords = totalSpaces / (numWords - 1); + int remainingSpaces = totalSpaces % (numWords - 1); + + std::string result; + for (int i = 0; i < numWords - 1; ++i) { + result += words[i] + std::string(spacesBetweenWords, ' '); + } + result += words[numWords - 1] + std::string(remainingSpaces, ' '); + return result; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ where n is the length of the input string. +- Space Complexity: $$O(n)$$ for storing the words and the result string. + +
+ + + +### Approach 3: Counting and Constructing + +In this approach, we manually count the spaces and words, then construct the result string by iterating through the words and adding spaces as needed. + +#### Implementation + +```jsx live +function rearrangeSpacesBetweenWords() { + const text = " hello"; + + const rearrangeSpaces = function(text) { + let totalSpaces = 0; + let words = []; + let word = ''; + + for (let char of text) { + if (char === ' ') { + if (word) { + words.push(word); + word = ''; + } + totalSpaces++; + } else { + word += char; + } + } + if (word) { + words.push(word); + } + + const numWords = words.length; + + if (numWords === 1) { + return words[0] + ' '.repeat(totalSpaces); + } + + const spacesBetweenWords = Math.floor(totalSpaces / (numWords - 1)); + const remainingSpaces = totalSpaces % (numWords - 1); + + return words.join(' '.repeat(spacesBetweenWords)) + ' '.repeat(remainingSpaces); + }; + + const result = rearrangeSpaces(text); + return ( +
+

+ Input: text = "{text}" +

+

+ Output: "{result}" +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function rearrangeSpaces(text) { + let totalSpaces = 0; + let words = []; + let word = ''; + + for (let char of text) { + if (char === ' ') { + if (word) { + words.push(word); + word = ''; + } + totalSpaces++; + } else { + word += char; + } + } + if (word) { + words.push(word); + } + + const numWords = words.length; + + if (numWords === 1) { + return words[0] + ' '.repeat(totalSpaces); + } + + const spacesBetweenWords = Math.floor(totalSpaces / (numWords - 1)); + const remainingSpaces = totalSpaces % (numWords - 1); + + return words.join(' '.repeat(spacesBetweenWords)) + ' '.repeat(remainingSpaces); + } + ``` + + + + + ```typescript + function rearrangeSpaces(text: string): string { + let totalSpaces = 0; + let words: string[] = []; + let word = ''; + + for (let char of text) { + if (char === ' ') { + if (word) { + words.push(word); + word = ''; + } + totalSpaces++; + } else { + word += char; + } + } + if (word) { + words.push(word); + } + + const numWords = words.length; + + if (numWords === 1) { + return words[0] + ' '.repeat(totalSpaces); + } + + const spacesBetweenWords = Math.floor(totalSpaces / (numWords - 1)); + const remainingSpaces = totalSpaces % (numWords - 1); + + return words.join(' '.repeat(spacesBetweenWords)) + ' '.repeat(remainingSpaces); + } + ``` + + + + + ```python + class Solution: + def rearrangeSpaces(self, text: str) -> str: + total_spaces = 0 + words = [] + word = '' + + for char in text: + if char == ' ': + if word: + words.append(word) + word = '' + total_spaces += 1 + else: + word += char + if word: + words.append(word) + + num_words = len(words) + + if num_words == 1: + return words[0] + ' ' * total_spaces + + spaces_between_words = total_spaces // (num_words - 1) + remaining_spaces = total_spaces % (num_words - 1) + + return (' ' * spaces_between_words).join(words) + ' ' + + * remaining_spaces + ``` + + + + + ```java + class Solution { + public String rearrangeSpaces(String text) { + int totalSpaces = 0; + List words = new ArrayList<>(); + StringBuilder word = new StringBuilder(); + + for (char c : text.toCharArray()) { + if (c == ' ') { + if (word.length() > 0) { + words.add(word.toString()); + word = new StringBuilder(); + } + totalSpaces++; + } else { + word.append(c); + } + } + if (word.length() > 0) { + words.add(word.toString()); + } + + int numWords = words.size(); + + if (numWords == 1) { + return words.get(0) + " ".repeat(totalSpaces); + } + + int spacesBetweenWords = totalSpaces / (numWords - 1); + int remainingSpaces = totalSpaces % (numWords - 1); + + return String.join(" ".repeat(spacesBetweenWords), words) + " ".repeat(remainingSpaces); + } + } + ``` + + + + + ```cpp + #include + #include + #include + + class Solution { + public: + std::string rearrangeSpaces(std::string text) { + int totalSpaces = 0; + std::vector words; + std::string word; + + for (char c : text) { + if (c == ' ') { + if (!word.empty()) { + words.push_back(word); + word.clear(); + } + totalSpaces++; + } else { + word += c; + } + } + if (!word.empty()) { + words.push_back(word); + } + + int numWords = words.size(); + + if (numWords == 1) { + return words[0] + std::string(totalSpaces, ' '); + } + + int spacesBetweenWords = totalSpaces / (numWords - 1); + int remainingSpaces = totalSpaces % (numWords - 1); + + std::string result; + for (int i = 0; i < numWords - 1; ++i) { + result += words[i] + std::string(spacesBetweenWords, ' '); + } + result += words[numWords - 1] + std::string(remainingSpaces, ' '); + return result; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ where n is the length of the input string. +- Space Complexity: $$O(n)$$ for storing the words and the result string. + +
+ +
+ +--- + +:::tip + +By using the above approach, we can efficiently solve the Rearrange Spaces Between Words problem. The choice of implementation language depends on the specific requirements and constraints of the problem. + +::: + +## References + +- **LeetCode Problem:** [Rearrange Spaces Between Words](https://leetcode.com/problems/rearrange-spaces-between-words/description/) +- **Solution Link:** [Rearrange Spaces Between Words Solution on LeetCode](https://leetcode.com/problems/rearrange-spaces-between-words/solution/) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) diff --git a/solutions/lc-solutions/1500-1599/1593-split-a-string-into-the-max-number-of-unique-substrings.md b/solutions/lc-solutions/1500-1599/1593-split-a-string-into-the-max-number-of-unique-substrings.md new file mode 100644 index 0000000..715eb02 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1593-split-a-string-into-the-max-number-of-unique-substrings.md @@ -0,0 +1,264 @@ +--- + +id: split-a-string-into-the-max-number-of-unique-substrings +title: Split a String Into the Max Number of Unique Substrings +sidebar_label: 1593-Split-a-String-Into-the-Max-Number-of-Unique-Substrings +tags: + - String + - Backtracking + - Dynamic Programming + - LeetCode + - Python + - JavaScript + - TypeScript + - Java + - C++ +description: "This is a solution to the Split a String Into the Max Number of Unique Substrings problem on LeetCode." + +--- + +In this page, we will solve the Split a String Into the Max Number of Unique Substrings problem using different approaches. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +Given a string `s`, return the maximum number of unique substrings that the given string can be split into. + +### Examples + +**Example 1:** + +```plaintext +Input: s = "ababccc" +Output: 5 +Explanation: One way to split s into the maximum number of unique substrings is ["a", "b", "ab", "c", "cc"]. +``` + +**Example 2:** + +```plaintext +Input: s = "aba" +Output: 2 +Explanation: One way to split s into the maximum number of unique substrings is ["a", "ba"]. +``` + +### Constraints + +- $1 <= s.length <= 16$ +- `s` contains only lower case English letters. + +--- + +## Solution for Split a String Into the Max Number of Unique Substrings + +### Intuition and Approach + +To solve this problem, we need to explore all possible ways to split the string into unique substrings. This can be effectively done using a backtracking approach. We will also consider a dynamic programming approach to enhance our solution. + + + + +### Approach 1: Backtracking + +We use a backtracking approach to explore all possible splits. We maintain a set to keep track of unique substrings and try to split the string at every possible position recursively. + +#### Implementation + +```jsx live +function splitStringIntoMaxUniqueSubstrings() { + const s = "ababccc"; + + const maxUniqueSplit = function(s) { + const set = new Set(); + + function backtrack(start) { + if (start === s.length) return set.size; + + let maxCount = 0; + for (let end = start + 1; end <= s.length; end++) { + const substring = s.substring(start, end); + if (!set.has(substring)) { + set.add(substring); + maxCount = Math.max(maxCount, backtrack(end)); + set.delete(substring); + } + } + return maxCount; + } + + return backtrack(0); + }; + + const result = maxUniqueSplit(s); + return ( +
+

+ Input: s = "{s}" +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function maxUniqueSplit(s) { + const set = new Set(); + + function backtrack(start) { + if (start === s.length) return set.size; + + let maxCount = 0; + for (let end = start + 1; end <= s.length; end++) { + const substring = s.substring(start, end); + if (!set.has(substring)) { + set.add(substring); + maxCount = Math.max(maxCount, backtrack(end)); + set.delete(substring); + } + } + return maxCount; + } + + return backtrack(0); + } + ``` + + + + + ```typescript + function maxUniqueSplit(s: string): number { + const set = new Set(); + + function backtrack(start: number): number { + if (start === s.length) return set.size; + + let maxCount = 0; + for (let end = start + 1; end <= s.length; end++) { + const substring = s.substring(start, end); + if (!set.has(substring)) { + set.add(substring); + maxCount = Math.max(maxCount, backtrack(end)); + set.delete(substring); + } + } + return maxCount; + } + + return backtrack(0); + } + ``` + + + + + ```python + class Solution: + def maxUniqueSplit(self, s: str) -> int: + def backtrack(start, seen): + if start == len(s): + return len(seen) + + max_count = 0 + for end in range(start + 1, len(s) + 1): + substring = s[start:end] + if substring not in seen: + seen.add(substring) + max_count = max(max_count, backtrack(end, seen)) + seen.remove(substring) + return max_count + + return backtrack(0, set()) + ``` + + + + + ```java + import java.util.HashSet; + import java.util.Set; + + class Solution { + public int maxUniqueSplit(String s) { + return backtrack(s, 0, new HashSet<>()); + } + + private int backtrack(String s, int start, Set seen) { + if (start == s.length()) return seen.size(); + + int maxCount = 0; + for (int end = start + 1; end <= s.length(); end++) { + String substring = s.substring(start, end); + if (!seen.contains(substring)) { + seen.add(substring); + maxCount = Math.max(maxCount, backtrack(s, end, seen)); + seen.remove(substring); + } + } + return maxCount; + } + } + ``` + + + + + ```cpp + #include + #include + + class Solution { + public: + int maxUniqueSplit(std::string s) { + return backtrack(s, 0, std::unordered_set()); + } + + private: + int backtrack(const std::string& s, int start, std::unordered_set seen) { + if (start == s.size()) return seen.size(); + + int maxCount = 0; + for (int end = start + 1; end <= s.size(); ++end) { + std::string substring = s.substr(start, end - start); + if (seen.find(substring) == seen.end()) { + seen.insert(substring); + maxCount = std::max(maxCount, backtrack(s, end, seen)); + seen.erase(substring); + } + } + return maxCount; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(2^n)$$ due to the exponential number of ways to split the string. +- Space Complexity: $$O(n)$$ for the recursion stack and the set to store unique substrings. + +
+ +
+ +:::tip + +By using different approaches like backtracking and dynamic programming, we can solve the Split a String Into the Max Number of Unique Substrings problem efficiently. The choice of implementation language and approach depends on the specific requirements and constraints of the problem. + +::: + +## References + +- **LeetCode Problem:** [Split a String Into the Max Number of Unique Substrings](https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/) +- **Solution Link:** [Split a String Into the Max Number of Unique Substrings Solution on LeetCode](https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/solution/) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + diff --git a/solutions/lc-solutions/1500-1599/1594-Maximum Non Negative Product in a Matrix.md b/solutions/lc-solutions/1500-1599/1594-Maximum Non Negative Product in a Matrix.md new file mode 100644 index 0000000..207e07e --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1594-Maximum Non Negative Product in a Matrix.md @@ -0,0 +1,632 @@ +--- + +id: maximum-non-negative-product-in-a-matrix +title: Maximum Non Negative Product in a Matrix +sidebar_label: 1594-Maximum-Non-Negative-Product-in-a-Matrix +tags: + - Matrix + - Dynamic Programming + - LeetCode + - Python + - JavaScript + - TypeScript + - Java + - C++ +description: "This is a solution to the Maximum Non Negative Product in a Matrix problem on LeetCode." + +--- + +In this page, we will solve the Maximum Non Negative Product in a Matrix problem using different approaches. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +You are given an `m x n` matrix `grid`. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix. + +Among all possible paths starting from the top-left corner $(0, 0)$ and ending in the bottom-right corner $(m - 1, n - 1)$, find the path with the `maximum non-negative product`. The product of a path is the product of all integers in the grid cells visited along the path. + +Return the maximum non-negative product modulo $10^9 + 7$. If the maximum product is negative, return -1. + +### Examples + +**Example 1:** + +```plaintext +Input: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]] +Output: -1 +Explanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. +``` + +**Example 2:** + +```plaintext +Input: grid = [[1,-2,1],[1,-2,1],[3,-4,1]] +Output: 8 +Explanation: Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8). +``` + +**Example 3:** + +```plaintext +Input: grid = [[1,3],[0,-4]] +Output: 0 +Explanation: Maximum non-negative product is shown (1 * 0 * -4 = 0). +``` + +### Constraints + +- $m == grid.length$ +- $n == grid[i].length$ +- $1 <= m, n <= 15$ +- $-4 <= grid[i][j] <= 4$ + +--- + +## Solution for Maximum Non Negative Product in a Matrix + +### Intuition and Approach + +To solve this problem, we can use Dynamic Programming (DP). We'll maintain two DP arrays `maxDP` and `minDP`, where: +- `maxDP[i][j]` will store the maximum product to reach cell `(i, j)`. +- `minDP[i][j]` will store the minimum product to reach cell `(i, j)`. + +At each cell `(i, j)`, we will consider the values from the cell above `(i-1, j)` and from the cell to the left `(i, j-1)`. This helps in managing both positive and negative products. + + + + +### Approach 1: Dynamic Programming + +#### Implementation + +```jsx live +function maximumNonNegativeProductInMatrix() { + const grid = [[1,-2,1],[1,-2,1],[3,-4,1]]; + + const maxProductPath = function(grid) { + const MOD = 1e9 + 7; + const m = grid.length, n = grid[0].length; + const maxDP = Array.from({length: m}, () => Array(n).fill(0)); + const minDP = Array.from({length: m}, () => Array(n).fill(0)); + + maxDP[0][0] = minDP[0][0] = grid[0][0]; + + for (let i = 1; i < m; ++i) { + maxDP[i][0] = minDP[i][0] = maxDP[i - 1][0] * grid[i][0]; + } + + for (let j = 1; j < n; ++j) { + maxDP[0][j] = minDP[0][j] = maxDP[0][j - 1] * grid[0][j]; + } + + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + if (grid[i][j] >= 0) { + maxDP[i][j] = Math.max(maxDP[i - 1][j], maxDP[i][j - 1]) * grid[i][j]; + minDP[i][j] = Math.min(minDP[i - 1][j], minDP[i][j - 1]) * grid[i][j]; + } else { + maxDP[i][j] = Math.min(minDP[i - 1][j], minDP[i][j - 1]) * grid[i][j]; + minDP[i][j] = Math.max(maxDP[i - 1][j], maxDP[i][j - 1]) * grid[i][j]; + } + } + } + + const result = maxDP[m - 1][n - 1]; + return result < 0 ? -1 : result % MOD; + }; + + const result = maxProductPath(grid); + return ( +
+

+ Input: grid = {JSON.stringify(grid)} +

+

+ Output: {result} +

+
+ ); +} +``` + +#### Code in Different Languages + + + + + ```javascript + function maxProductPath(grid) { + const MOD = 1e9 + 7; + const m = grid.length, n = grid[0].length; + const maxDP = Array.from({length: m}, () => Array(n).fill(0)); + const minDP = Array.from({length: m}, () => Array(n).fill(0)); + + maxDP[0][0] = minDP[0][0] = grid[0][0]; + + for (let i = 1; i < m; ++i) { + maxDP[i][0] = minDP[i][0] = maxDP[i - 1][0] * grid[i][0]; + } + + for (let j = 1; j < n; ++j) { + maxDP[0][j] = minDP[0][j] = maxDP[0][j - 1] * grid[0][j]; + } + + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + if (grid[i][j] >= 0) { + maxDP[i][j] = Math.max(maxDP[i - 1][j], maxDP[i][j - 1]) * grid[i][j]; + minDP[i][j] = Math.min(minDP[i - 1][j], minDP[i][j - 1]) * grid[i][j]; + } else { + maxDP[i][j] = Math.min(minDP[i - 1][j], minDP[i][j - 1]) * grid[i][j]; + minDP[i][j] = Math.max(maxDP[i - 1][j], maxDP[i][j - 1]) * grid[i][j]; + } + } + } + + const result = maxDP[m - 1][n - 1]; + return result < 0 ? -1 : result % MOD; + } + ``` + + + + + ```typescript + function maxProductPath(grid: number[][]): number { + const MOD = 1e9 + 7; + const m = grid.length, n = grid[0].length; + const maxDP = Array.from({length: m}, () => Array(n).fill(0)); + const minDP = Array.from({length: m}, () => Array(n).fill(0)); + + maxDP[0][0] = minDP[0][0] = grid[0][0]; + + for (let i = 1; i < m; ++i) { + maxDP[i][0] = minDP[i][0] = maxDP[i - 1][0] * grid[i][0]; + } + + for (let j = 1; j < n; ++j) { + maxDP[0][j] = minDP[0][j] = maxDP[0][j - 1] * grid[0][j]; + } + + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + if (grid[i][j] >= 0) { + maxDP[i][j] = Math.max(maxDP[i - 1][j], maxDP[i][j - 1]) * grid[i][j]; + minDP[i][ + +j] = Math.min(minDP[i - 1][j], minDP[i][j - 1]) * grid[i][j]; + } else { + maxDP[i][j] = Math.min(minDP[i - 1][j], minDP[i][j - 1]) * grid[i][j]; + minDP[i][j] = Math.max(maxDP[i - 1][j], maxDP[i][j - 1]) * grid[i][j]; + } + } + } + + const result = maxDP[m - 1][n - 1]; + return result < 0 ? -1 : result % MOD; + } + ``` + + + + + ```python + class Solution: + def maxProductPath(self, grid: List[List[int]]) -> int: + MOD = 10**9 + 7 + m, n = len(grid), len(grid[0]) + maxDP = [[0] * n for _ in range(m)] + minDP = [[0] * n for _ in range(m)] + + maxDP[0][0] = minDP[0][0] = grid[0][0] + + for i in range(1, m): + maxDP[i][0] = minDP[i][0] = maxDP[i-1][0] * grid[i][0] + + for j in range(1, n): + maxDP[0][j] = minDP[0][j] = maxDP[0][j-1] * grid[0][j] + + for i in range(1, m): + for j in range(1, n): + if grid[i][j] >= 0: + maxDP[i][j] = max(maxDP[i-1][j], maxDP[i][j-1]) * grid[i][j] + minDP[i][j] = min(minDP[i-1][j], minDP[i][j-1]) * grid[i][j] + else: + maxDP[i][j] = min(minDP[i-1][j], minDP[i][j-1]) * grid[i][j] + minDP[i][j] = max(maxDP[i-1][j], maxDP[i][j-1]) * grid[i][j] + + result = maxDP[m-1][n-1] + return -1 if result < 0 else result % MOD + ``` + + + + + ```java + import java.util.Arrays; + + class Solution { + public int maxProductPath(int[][] grid) { + int MOD = (int) 1e9 + 7; + int m = grid.length, n = grid[0].length; + long[][] maxDP = new long[m][n]; + long[][] minDP = new long[m][n]; + + maxDP[0][0] = minDP[0][0] = grid[0][0]; + + for (int i = 1; i < m; ++i) { + maxDP[i][0] = minDP[i][0] = maxDP[i - 1][0] * grid[i][0]; + } + + for (int j = 1; j < n; ++j) { + maxDP[0][j] = minDP[0][j] = maxDP[0][j - 1] * grid[0][j]; + } + + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (grid[i][j] >= 0) { + maxDP[i][j] = Math.max(maxDP[i - 1][j], maxDP[i][j - 1]) * grid[i][j]; + minDP[i][j] = Math.min(minDP[i - 1][j], minDP[i][j - 1]) * grid[i][j]; + } else { + maxDP[i][j] = Math.min(minDP[i - 1][j], minDP[i][j - 1]) * grid[i][j]; + minDP[i][j] = Math.max(maxDP[i - 1][j], maxDP[i][j - 1]) * grid[i][j]; + } + } + } + + long result = maxDP[m - 1][n - 1]; + return result < 0 ? -1 : (int) (result % MOD); + } + } + ``` + + + + + ```cpp + #include + #include + + class Solution { + public: + int maxProductPath(std::vector>& grid) { + int MOD = 1e9 + 7; + int m = grid.size(), n = grid[0].size(); + std::vector> maxDP(m, std::vector(n, 0)); + std::vector> minDP(m, std::vector(n, 0)); + + maxDP[0][0] = minDP[0][0] = grid[0][0]; + + for (int i = 1; i < m; ++i) { + maxDP[i][0] = minDP[i][0] = maxDP[i - 1][0] * grid[i][0]; + } + + for (int j = 1; j < n; ++j) { + maxDP[0][j] = minDP[0][j] = maxDP[0][j - 1] * grid[0][j]; + } + + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (grid[i][j] >= 0) { + maxDP[i][j] = std::max(maxDP[i - 1][j], maxDP[i][j - 1]) * grid[i][j]; + minDP[i][j] = std::min(minDP[i - 1][j], minDP[i][j - 1]) * grid[i][j]; + } else { + maxDP[i][j] = std::min(minDP[i - 1][j], minDP[i][j - 1]) * grid[i][j]; + minDP[i][j] = std::max(maxDP[i - 1][j], maxDP[i][j - 1]) * grid[i][j]; + } + } + } + + long long result = maxDP[m - 1][n - 1]; + return result < 0 ? -1 : result % MOD; + } + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(m \times n)$$ since we process each cell once. +- Space Complexity: $$O(m \times n)$$ for storing the DP arrays. + +
+ + + +### Approach 2: Memoization + +We can use memoization to store the results of subproblems and avoid redundant calculations. + +#### Implementation + +```jsx live + +function maximumNonNegativeProductInMatrix() { + const grid = [[1, -2, 1], [1, -2, 1], [3, -4, 1]]; + + const maxProductPath = function (grid) { + const MOD = 1e9 + 7; + const m = grid.length, n = grid[0].length; + const memo = Array.from({ length: m }, () => Array(n).fill(undefined)); + + const solve = (i, j) => { + if (grid[i][j] === 0) return [0, 0]; + if (i === 0 && j === 0) return [grid[i][j], grid[i][j]]; + if (memo[i][j] !== undefined) return memo[i][j]; + + let maxProduct = -Infinity; + let minProduct = Infinity; + + if (i > 0) { + const [maxUp, minUp] = solve(i - 1, j); + maxProduct = Math.max(maxProduct, maxUp * grid[i][j], minUp * grid[i][j]); + minProduct = Math.min(minProduct, maxUp * grid[i][j], minUp * grid[i][j]); + } + if (j > 0) { + const [maxLeft, minLeft] = solve(i, j - 1); + maxProduct = Math.max(maxProduct, maxLeft * grid[i][j], minLeft * grid[i][j]); + minProduct = Math.min(minProduct, maxLeft * grid[i][j], minLeft * grid[i][j]); + } + + memo[i][j] = [maxProduct, minProduct]; + return memo[i][j]; + }; + + const result = solve(m - 1, n - 1)[0]; + return result < 0 ? -1 : result % MOD; + }; + + const result = maxProductPath(grid); + return ( +
+

+ Input: grid = {JSON.stringify(grid)} +

+

+ Output: {result} +

+
+ ); +} + +``` + +#### Code in Different Languages + + + + + ```javascript + const maxProductPath = function (grid) { + const MOD = 1e9 + 7; + const m = grid.length, n = grid[0].length; + const memo = Array.from({ length: m }, () => Array(n).fill(undefined)); + + const solve = (i, j) => { + if (grid[i][j] === 0) return [0, 0]; + if (i === 0 && j === 0) return [grid[i][j], grid[i][j]]; + if (memo[i][j] !== undefined) return memo[i][j]; + + let maxProduct = -Infinity; + let minProduct = Infinity; + + if (i > 0) { + const [maxUp, minUp] = solve(i - 1, j); + maxProduct = Math.max(maxProduct, maxUp * grid[i][j], minUp * grid[i][j]); + minProduct = Math.min(minProduct, maxUp * grid[i][j], minUp * grid[i][j]); + } + if (j > 0) { + const [maxLeft, minLeft] = solve(i, j - 1); + maxProduct = Math.max(maxProduct, maxLeft * grid[i][j], minLeft * grid[i][j]); + minProduct = Math.min(minProduct, maxLeft * grid[i][j], minLeft * grid[i][j]); + } + + memo[i][j] = [maxProduct, minProduct]; + return memo[i][j]; + }; + + const result = solve(m - 1, n - 1)[0]; + return result < 0 ? -1 : result % MOD; + } + ``` + + + + + ```typescript + const maxProductPath = function (grid: number[][]): number { + const MOD = 1e9 + 7; + const m = grid.length, n = grid[0].length; + const memo: number[][] = Array.from({ length: m }, () => Array(n).fill(undefined)); + + const solve = (i: number, j: number): [number, number] => { + if (grid[i][j] === 0) return [0, 0]; + if (i === 0 && j === 0) return [grid[i][j], grid[i][j]]; + if (memo[i][j] !== undefined) return memo[i][j]; + + let maxProduct = -Infinity; + let minProduct = Infinity; + + if (i > 0) { + const [maxUp, minUp] = solve(i - 1, j); + maxProduct = Math.max(maxProduct, maxUp * grid[i][j], minUp * grid[i][j]); + minProduct = Math.min(minProduct, maxUp * grid[i][j], minUp * grid[i][j]); + } + if (j > 0) { + const [maxLeft, minLeft] = solve(i, j - 1); + maxProduct = Math.max(maxProduct, maxLeft * grid[i][j], minLeft * grid[i][j]); + minProduct = Math.min(minProduct, maxLeft * grid[i][j], minLeft * grid[i][j]); + } + + memo[i][j] = [maxProduct, minProduct]; + return memo[i][j]; + }; + + const result = solve(m - 1, n - 1)[0]; + return result < 0 ? -1 : result % MOD; +}; + + ``` + + + + + ```python + MOD = 1e9 + 7 + + +def max_product_path(grid): + m, n = len(grid), len(grid[0]) + memo = [[None] * n for _ in range(m)] + + def solve(i, j): + if grid[i][j] == 0: + return 0, 0 + if i == 0 and j == 0: + return grid[i][j], grid[i][j] + if memo[i][j] is not None: + return memo[i][j] + + max_product = -float("inf") + min_product = float("inf") + + if i > 0: + max_up, min_up = solve(i - 1, j) + max_product = max(max_product, max_up * grid[i][j], min_up * grid[i][j]) + min_product = min(min_product, max_up * grid[i][j], min_up * grid[i][j]) + + if j > 0: + max_left, min_left = solve(i, j - 1) + max_product = max(max_product, max_left * grid[i][j], min_left * grid[i][j]) + min_product = min(min_product, max_left * grid[i][j], min_left * grid[i][j]) + + memo[i][j] = max_product, min_product + return memo[i][j] + + result, _ = solve(m - 1, n - 1) + return result % MOD if result > 0 else -1 + + + ``` + + + + + ```java +class Solution { + public static int maxProductPath(int[][] grid) { + int MOD = 1000000007; + int m = grid.length, n = grid[0].length; + int[][] memo = new int[m][n]; + for (int i = 0; i < m; i++) { + Arrays.fill(memo[i], -1); + } + + return solve(grid, memo, m - 1, n - 1); + } + + private static int solve(int[][] grid, int[][] memo, int i, int j) { + if (grid[i][j] == 0) { + return 0; + } + if (i == 0 && j == 0) { + return grid[i][j]; + } + if (memo[i][j] != -1) { + return memo[i][j]; + } + + int maxProduct = -Integer.MAX_VALUE; + int minProduct = Integer.MAX_VALUE; + + if (i > 0) { + int upProduct = solve(grid, memo, i - 1, j); + maxProduct = Math.max(maxProduct, upProduct * grid[i][j]); + minProduct = Math.min(minProduct, upProduct * grid[i][j]); + } + if (j > 0) { + int leftProduct = solve(grid, memo, i, j - 1); + maxProduct = Math.max(maxProduct, leftProduct * grid[i][j]); + minProduct = Math.min(minProduct, leftProduct * grid[i][j]); + } + + memo[i][j] = Math.max(maxProduct, minProduct) % MOD; + return memo[i][j]; + } +} + + ``` + + + + + ```cpp + #include + #include + #include + +const int MOD = 1e9 + 7; + +int solve(vector>& grid, vector>& memo, int i, int j) { + if (grid[i][j] == 0) { + return 0; + } + if (i == 0 && j == 0) { + return grid[i][j]; + } + if (memo[i][j] != -1) { + return memo[i][j]; + } + + int maxProduct = numeric_limits::min(); + int minProduct = numeric_limits::max(); + + if (i > 0) { + int upProduct = solve(grid, memo, i - 1, j); + maxProduct = max(maxProduct, upProduct * grid[i][j]); + minProduct = min(minProduct, upProduct * grid[i][j]); + } + if (j > 0) { + int leftProduct = solve(grid, memo, i, j - 1); + maxProduct = max(maxProduct, leftProduct * grid[i][j]); + minProduct = min(minProduct, leftProduct * grid[i][j]); + } + + memo[i][j] = max(maxProduct, minProduct) % MOD; + return memo[i][j]; +} + +int maxProductPath(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector> memo(m, vector(n, -1)); + + return solve(grid, memo, m - 1, n - 1); +} + + + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $$O(m \times n)$$ since we process each cell once. +- Space Complexity: $$O(m \times n)$$ for storing the memoization results. + +
+
+ +:::tip + +By using either the Tabulation approach or the Memoization approach, we can efficiently solve the Maximum Non Negative Product in a Matrix. The choice of implementation language depends on the specific requirements and constraints of the problem. + +::: + +## References + +- **LeetCode Problem:** [Maximum Non Negative Product in a Matrix](https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/description/) +- **Solution Link:** [Maximum Non Negative Product in a Matrix Solution on LeetCode](https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/solution/) +- **Authors LeetCode Profile:** [Manish Kumar Gupta](https://leetcode.com/_manishh12/) + diff --git a/solutions/lc-solutions/1500-1599/1595 - Minimum Cost to Connect Two Groups of Points.md b/solutions/lc-solutions/1500-1599/1595 - Minimum Cost to Connect Two Groups of Points.md new file mode 100644 index 0000000..7da9c51 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1595 - Minimum Cost to Connect Two Groups of Points.md @@ -0,0 +1,173 @@ +--- +id: Minimum Cost to Connect Two Groups of Points +title: Minimum Cost to Connect Two Groups of Points +sidebar_label: 1595 Minimum Cost to Connect Two Groups of Points +tags: +- Dynamic Programming +- Bit Manipulation +- Java +- Bitmask +- Matrix +- Array +description: "This document provides a solution where we return the minimum cost to connect the two groups." +--- +## Problem + +You are given two groups of points where the first group has $size1$ points, the second group has $size2$ points, and $size1 >= size2$. + +The cost of the connection between any two points are given in an $size1$ x $size2$ matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group. + +### Examples + +**Example 1:** + +![image](https://github.com/CodeHarborHub/codeharborhub.github.io/assets/91594529/bb9cc0a0-5c28-444d-a0cb-d0753998c6c0) + +**Input:** cost = [[15, 96], [36, 2]] + +**Output:** 17 + +**Explanation:** The optimal way of connecting the groups is: + +1--A + +2--B + +This results in a total cost of 17. + +**Example 2:** + +![image](https://github.com/CodeHarborHub/codeharborhub.github.io/assets/91594529/d956087d-3ffc-4a13-9144-83bf585bee88) + +**Input:** cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]] + +**Output:** 4 + +**Explanation:** The optimal way of connecting the groups is: + +1--A + +2--B + +2--C + +3--A + +This results in a total cost of 4. + +**Example 3:** + +**Input:** cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]] + +**Output:** 10 + +### Constraints + +- $size1 == cost.length$ +- $size2 == cost[i].length$ +- $1 <= size1,size2 <= 12$ +- $size1 >= size2$ +- $0 <= cost[i][j] <= 100$ + +--- +## Approach +There are four approaches discussed that helps to obtain the solution: + +1. **Define the Problem**: + - We are given two groups of points with a cost matrix representing the connection cost between each pair of points from the two groups. + + - We need to ensure that every point in both groups is connected to at least one point in the other group. + +2. **Dynamic Programming with Memoization**: + - Use dynamic programming (DP) with memoization to avoid redundant calculations. + + - Define a recursive function **'dfs(cost, i, mask, memo)'** where: + - **i** is the current index in the first group. + - Mask is a bitmask representing the subset of points in the second group that have been connected. + - memo is a memoization table to store intermediate results. + +3. **Recursive Strategy**: + - For each point in the first group, attempt to connect it to every point in the second group, updating the bitmask accordingly. + + - Once all points in the first group are processed, ensure that all points in the second group are connected by calculating the minimum additional cost for any remaining points. + + - Use memoization to store and reuse results of subproblems to improve efficiency. + +4. **Base and Transition**: + - **Base Case:** If all points in the first group are processed (i == $size1$), calculate the cost to connect any remaining points in the second group that have not been connected. + + - **Transition:** For each point in the second group, update the bitmask and recursively calculate the minimum cost. + +## Solution for Minimum Cost to Connect Two Groups of Points + +This problem can be solved using dynamic programming. The problem requires connecting two groups of points such that each point in the first group is connected to at least one point in the second group and vice versa, with the goal of minimizing the total connection cost. This problem can be approached as a minimum cost bipartite matching problem with additional constraints. + +#### Code in Java + + ```java + import java.util.*; + import java.util.Arrays; + + class Solution { + public int connectTwoGroups(List> cost) { + int size1 = cost.size(); + int size2 = cost.get(0).size(); + + // Memoization table + int[][] memo = new int[size1][1 << size2]; + for (int i = 0; i < size1; i++) { + Arrays.fill(memo[i], -1); + } + + return dfs(cost, 0, 0, memo); + } + + private int dfs(List> cost, int i, int mask, int[][] memo) { + int size1 = cost.size(); + int size2 = cost.get(0).size(); + + if (i == size1) { + int remainingCost = 0; + for (int j = 0; j < size2; j++) { + if ((mask & (1 << j)) == 0) { + int minCost = Integer.MAX_VALUE; + for (int k = 0; k < size1; k++) { + minCost = Math.min(minCost, cost.get(k).get(j)); + } + remainingCost += minCost; + } + } + return remainingCost; + } + + if (memo[i][mask] != -1) { + return memo[i][mask]; + } + + int minCost = Integer.MAX_VALUE; + for (int j = 0; j < size2; j++) { + minCost = Math.min(minCost, cost.get(i).get(j) + dfs(cost, i + 1, mask | (1 << j), memo)); + } + + memo[i][mask] = minCost; + return minCost; + } +} + +``` + +### Complexity Analysis + +#### Time Complexity: O($size1$ Γ— $2^size2$ x $size2$) + +> **Reason**: There are $'size 1'$ points in the first group, and each point can potentially connect to any subset of the $'size2'$ points in the second group, leading to $'2^size2'$ possible states for the bitmask. For each state, we iterate over all points in the second group, hence the additional factor of $'size2'$ + +#### Space Complexity: O($size1$ Γ— $2^size2$) + +> **Reason**: Additional space is used for the recursion stack, which is O($size1$). + +# References + +- **LeetCode Problem:** [Minimum Cost to Connect Two Groups of Points](https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points/description/) +- **Solution Link:** [Minimum Cost to Connect Two Groups of Points Solution on LeetCode](https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points/solutions/) +- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/vivekvardhan43862/) diff --git a/solutions/lc-solutions/1500-1599/1598-crawler-log-folder.md b/solutions/lc-solutions/1500-1599/1598-crawler-log-folder.md new file mode 100644 index 0000000..e61f67b --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1598-crawler-log-folder.md @@ -0,0 +1,183 @@ +--- +id: crawler-log-folder +title: 1598. Crawler Log Folder +sidebar_label: 1598. Crawler Log Folder +tags: +- Array +- Union Find +- Graph +- Minimum Spanning Tree +description: "This is a solution to the 1598. Crawler Log Folder problem on LeetCode." +--- + +## Problem Description +The Leetcode file system keeps a log each time some user performs a change folder operation. + +The operations are described below: + +"../" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder). +"./" : Remain in the same folder. +"x/" : Move to the child folder named x (This folder is guaranteed to always exist). +You are given a list of strings logs where logs[i] is the operation performed by the user at the ith step. + +The file system starts in the main folder, then the operations in logs are performed. + +Return the minimum number of operations needed to go back to the main folder after the change folder operations. +### Examples +**Example 1:** +![image](https://assets.leetcode.com/uploads/2020/09/09/sample_11_1957.png) +``` +Input: logs = ["d1/","d2/","../","d21/","./"] +Output: 2 +Explanation: Use this change folder operation "../" 2 times and go back to the main folder. +``` + +### Constraints +- `1 <= logs.length <= 10^3` +- `2 <= logs[i].length <= 10` +- `logs[i] contains lowercase English letters, digits, '.', and '/'.` +- `logs[i] follows the format described in the statement.` +- `Folder names consist of lowercase English letters and digits.` + +## Solution for 1598. Crawler Log Folder + + + + + #### Implementation + ```jsx live + function Solution(arr) { + var minOperations = function(logs) { + let cnt = 0; + for (let log of logs) { + if (log === "../") { + if (cnt > 0) { + cnt--; + } + } else if (log !== "./") { + cnt++; + } + } + return cnt; + }; + + const input = logs = ["d1/","d2/","../","d21/","./"] + const output = minOperations(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n) $ + - Space Complexity: $ O(1)$ + + ## Code in Different Languages + + + + ```typescript + function minOperations(logs: string[]): number { + let cnt = 0; + for (let log of logs) { + if (log === "../") { + if (cnt > 0) { + cnt--; + } + } else if (log !== "./") { + cnt++; + } + } + return cnt; +} + + ``` + + + + ```python + from typing import List + +class Solution: + def minOperations(self, logs: List[str]) -> int: + cnt = 0 + for log in logs: + if log == "../": + if cnt > 0: + cnt -= 1 + elif log != "./": + cnt += 1 + return cnt + + ``` + + + + + ```java + import java.util.List; + +public class Solution { + public int minOperations(List logs) { + int cnt = 0; + for (String log : logs) { + if (log.equals("../")) { + if (cnt > 0) { + cnt--; + } + } else if (!log.equals("./")) { + cnt++; + } + } + return cnt; + } +} + + ``` + + + + + + ```cpp + class Solution { +public: + int minOperations(vector& logs) { + int cnt=0; + for (int i = 0; i < logs.size(); i++) { + if (logs[i] == "../") { + if(cnt) + cnt--; + else continue; + } else if (logs[i] == "./") { + continue; + } else{ + cnt++; + } + } + return cnt; + } +}; +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [ 1598. Crawler Log Folder](https://leetcode.com/problems/crawler-log-folder/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/crawler-log-folder/description/) + diff --git a/solutions/lc-solutions/1500-1599/1796-second-largest-digit-in-a-string.md b/solutions/lc-solutions/1500-1599/1796-second-largest-digit-in-a-string.md new file mode 100644 index 0000000..b38558c --- /dev/null +++ b/solutions/lc-solutions/1500-1599/1796-second-largest-digit-in-a-string.md @@ -0,0 +1,124 @@ +--- +id: second-largest-digit-in-a-string +title: Second Largest Digit in a String +sidebar_label: 1796-Second Largest Digit in a String +tags: + - Leet code +description: "Solution to leetocde 1796" +--- + +## Problem Statement + +Given an alphanumeric string `s`, return the second largest numerical digit that appears in `s`, or -1 if it does not exist. + +An alphanumeric string is a string consisting of lowercase English letters and digits. + +## Examples + +### Example 1 + +**Input:** `s = "dfa12321afd"` +**Output:** `2` +**Explanation:** The digits that appear in `s` are [1, 2, 3]. The second largest digit is 2. + +### Example 2 + +**Input:** `s = "abc1111"` +**Output:** `-1` +**Explanation:** The digits that appear in `s` are [1]. There is no second largest digit. + +## Constraints + +- $1 <= s.length <= 500$ +- s consists of only lowercase English letters and/or digits. + +## Algorithm + +1. Extract all unique digits from the string. +2. If the count of unique digits is less than 2, return -1. +3. Convert the digits to integers and sort them in descending order. +4. Return the second largest digit. + +## Python Code + +```python +class Solution: + def secondHighest(self, s: str) -> int: + digits = {char for char in s if char.isdigit()} + if len(digits) < 2: + return -1 + sorted_digits = sorted(map(int, digits), reverse=True) + return sorted_digits[1] +``` + +## C++ Code + +```cpp +#include +#include +#include + +class Solution { +public: + int secondHighest(std::string s) { + std::set digits; + for (char ch : s) { + if (isdigit(ch)) { + digits.insert(ch); + } + } + if (digits.size() < 2) { + return -1; + } + auto it = digits.rbegin(); + std::advance(it, 1); + return *it - '0'; + } +}; +``` + +## Java Code + +```java +import java.util.Set; +import java.util.TreeSet; + +class Solution { + public int secondHighest(String s) { + Set digits = new TreeSet<>(); + for (char ch : s.toCharArray()) { + if (Character.isDigit(ch)) { + digits.add(ch); + } + } + if (digits.size() < 2) { + return -1; + } + return Character.getNumericValue(((TreeSet) digits).lower(((TreeSet) digits).last())); + } +} +``` + +## JavaScript Code + +```javascript +/** + * @param {string} s + * @return {number} + */ +var secondHighest = function (s) { + let digits = new Set(); + for (let char of s) { + if (/\d/.test(char)) { + digits.add(char); + } + } + if (digits.size < 2) { + return -1; + } + let sortedDigits = Array.from(digits) + .map(Number) + .sort((a, b) => b - a); + return sortedDigits[1]; +}; +``` diff --git a/solutions/lc-solutions/1500-1599/Find-Kth-Bit-in-Nth-Binary-String.md b/solutions/lc-solutions/1500-1599/Find-Kth-Bit-in-Nth-Binary-String.md new file mode 100644 index 0000000..98deb8f --- /dev/null +++ b/solutions/lc-solutions/1500-1599/Find-Kth-Bit-in-Nth-Binary-String.md @@ -0,0 +1,95 @@ +--- +id: find-kth-bit-in-nth-binary-string +title: Find Kth Bit in Nth Binary String +sidebar_label: 1545 - Find Kth Bit in Nth Binary String +tags: [Binary String, Kth Bit, Inversion, C++] +description: Given two positive integers n and k, return the kth bit in the nth binary string generated by specific rules. +--- + +## Find Kth Bit in Nth Binary String + +### Problem Statement +Given two positive integers `n` and `k`, the binary string `S_n` is formed as follows: + +- `S1 = "0"` +- `S_i = S_(i - 1) + "1" + reverse(invert(S_(i - 1)))` for `i > 1` + +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). + +For example, the first four strings in the above sequence are: + +- `S1 = "0"` +- `S2 = "011"` +- `S3 = "0111001"` +- `S4 = "011100110110001"` + +Return the `k`th bit in `S_n`. It is guaranteed that `k` is valid for the given `n`. + +### Example 1: +**Input:** `n = 3, k = 1` +**Output:** `"0"` +**Explanation:** `S3` is `"0111001"`. The 1st bit is `"0"`. + +### Example 2: +**Input:** `n = 4, k = 11` +**Output:** `"1"` +**Explanation:** `S4` is `"011100110110001"`. The 11th bit is `"1"`. + +### Constraints + +- `1 <= n <= 20` +- `1 <= k <= 2^n - 1` +### Intuition + +The goal of the solution is to find the `k`th bit in the `n`th binary string `S_n` generated by specific rules. Here's the step-by-step intuition behind the algorithm: + +1. **Base Case**: The base case `S1` is initialized as "0". +2. **Building Subsequent Strings**: For each subsequent `S_i` where `i > 1`, the string is constructed by concatenating `S_(i-1)`, "1", and the inverted and reversed `S_(i-1)`. +3. **String Inversion and Reversal**: For constructing the inverted and reversed part, iterate through `S_(i-1)` from end to start, inverting each bit (0 becomes 1 and 1 becomes 0). +4. **Store Intermediate Strings**: Use a hash map (`mp`) to store each `S_i` to avoid recomputation and facilitate quick access. +5. **Access the k-th Bit**: After constructing `S_n`, access the `k-1` index of the string to get the `k`th bit. + +### Time Complexity + +The time complexity of the algorithm is $O(2^n)$, where $n$ is the input integer: + +- **Constructing Strings**: Each `S_i` is twice the length of `S_(i-1)`, leading to exponential growth. The length of `S_n` is $2^n - 1$. +- **Inversion and Reversal**: Inverting and reversing the previous string takes linear time with respect to its length, leading to exponential time overall due to the doubling size at each step. + +### Space Complexity + +The space complexity of the algorithm is $O(2^n)$ in the worst case: + +- **Storage in Hash Map**: The hash map stores each intermediate string `S_i`. The total storage needed is the sum of the lengths of all strings up to `S_n`, which is dominated by the length of `S_n`. +- **Final String Storage**: The final string `S_n` has length $2^n - 1$, contributing to the space complexity. + +Overall, both the time and space complexity are exponential in `n`. + +### Code +#### C++ +```cpp +class Solution { +public: + char findKthBit(int n, int k) { + + unordered_mapmp; + mp[1]="0"; + for(int i=2;i<=n;i++) + { + + int j=mp[i-1].length()-1; + string s1=""; + while(j>=0){ + if(mp[i-1][j--]=='0') + s1+='1'; + else s1+='0'; + } + + mp[i]+=mp[i-1]+"1"+s1; + } + + string ans=mp[n]; + return ans[k-1]; + } +}; +``` diff --git a/solutions/lc-solutions/1500-1599/Maximum-Number-of-Non-Overlapping-Subarrays-With-Sum-Equals-Target.md b/solutions/lc-solutions/1500-1599/Maximum-Number-of-Non-Overlapping-Subarrays-With-Sum-Equals-Target.md new file mode 100644 index 0000000..b59b322 --- /dev/null +++ b/solutions/lc-solutions/1500-1599/Maximum-Number-of-Non-Overlapping-Subarrays-With-Sum-Equals-Target.md @@ -0,0 +1,86 @@ +--- +id: maximum-number-of-non-overlapping-subarrays-with-sum-equals-target +title: Maximum Number of Non-Overlapping Subarrays With Sum Equals Target +sidebar_label: 1546 - Maximum Number of Non-Overlapping Subarrays With Sum Equals Target +tags: [Subarrays, Array, Target, Sum, C++] +description: Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target. +--- + +## Maximum Number of Non-Overlapping Subarrays With Sum Equals Target + +### Problem Statement +Given an array `nums` and an integer `target`, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to `target`. + +### Example 1: +**Input:** nums = [1, 1, 1, 1, 1], target = 2 +**Output:** 2 +**Explanation:** There are 2 non-overlapping subarrays [1, 1, 1, 1, 1] with sum equal to `target` (2). + +### Example 2: +**Input:** nums = [-1, 3, 5, 1, 4, 2, -9], target = 6 +**Output:** 2 +**Explanation:** There are 3 subarrays with sum equal to 6 ([5, 1], [4, 2], [3, 5, 1, 4, 2, -9]) but only the first 2 are non-overlapping. + +### Constraints + +- `1 <= nums.length <= 10^5` +- `-10^4 <= nums[i] <= 10^4` +- `0 <= target <= 10^6` + +### Intuition + +The goal of the solution is to find the maximum number of non-overlapping subarrays such that the sum of values in each subarray is equal to a given target. Here's the step-by-step intuition behind the algorithm: + +1. **Prefix Sum and Hash Map**: The algorithm uses a prefix sum approach where it maintains a running sum (`sum`) of the elements as it iterates through the array. It also uses a hash map (`mp`) to store the index of each prefix sum encountered. + +2. **Check for Target Sum**: At each index `i`, the algorithm checks if there exists a previous prefix sum that when subtracted from the current prefix sum results in the target. This is achieved by checking if `sum - target` exists in the hash map. + +3. **Update Answer and Maintain Non-Overlapping Property**: If such a prefix sum is found and the subarray formed by this prefix sum is non-overlapping with previous subarrays (ensured by checking if the stored index is greater than or equal to `pre`), then it increments the answer count (`ans`) and updates the `pre` index to the current index `i`. + +4. **Update Hash Map**: Finally, it updates the hash map with the current prefix sum and its index. + +### Time Complexity + +The time complexity of the algorithm is $O(n)$, where $n$ is the length of the input array `nums`. This is because: + +- **Single Pass Through Array**: The algorithm iterates through the array once. Each element is processed exactly one time in a single loop from start to finish. +- **Constant-Time Operations**: During each iteration, the algorithm performs operations such as updating the running sum, checking if a key exists in the hash map, and updating the hash map. These operations (lookup and insertion in the hash map) are average $O(1)$ operations. + +Combining these factors, the overall time complexity is $O(n)$. + +### Space Complexity + +The space complexity of the algorithm is $O(n)$ in the worst case. This is because: + +- **Hash Map Storage**: The algorithm uses a hash map to store prefix sums and their corresponding indices. In the worst case, where all elements in the array are unique and result in different prefix sums, the hash map could store up to $n$ entries (one for each element in the array). +- **Additional Variables**: The algorithm uses a few additional variables (`pre`, `ans`, and `sum`), but these use constant space, $O(1)$, and do not depend on the input size. + +Thus, the dominating factor for space complexity is the hash map, leading to an overall space complexity of $O(n)$. + +### Code + +#### C++ +``` +class Solution { +public: + int maxNonOverlapping(vector& nums, int target) { + unordered_map mp; // Hash map to store prefix sums and their indices + int n = nums.size(); + mp[0] = -1; // Initialize with prefix sum 0 at index -1 + int pre = -1; // Variable to track the end index of the last added subarray + int ans = 0; // Variable to count the number of valid subarrays + int sum = 0; // Variable to store the running sum (prefix sum) + + for (int i = 0; i < n; i++) { + sum += nums[i]; // Update the running sum + // Check if there exists a prefix sum that forms a subarray with the target sum + if (mp.find(sum - target) != mp.end() && mp[sum - target] >= pre) { + ans++; // Increment the count of valid subarrays + pre = i; // Update the end index of the last added subarray + } + mp[sum] = i; // Store the current prefix sum with its index in the hash map + } + return ans; // Return the count of non-overlapping subarrays with sum equal to target + } +}; +``` diff --git a/solutions/lc-solutions/1500-1599/_category_.json b/solutions/lc-solutions/1500-1599/_category_.json new file mode 100644 index 0000000..aa726fa --- /dev/null +++ b/solutions/lc-solutions/1500-1599/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "1500-1599", + "position": 17, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (1500 - 1599)" + } +} diff --git a/solutions/lc-solutions/1600-1699/1608-special-array-with-x-elements-greater-than-or-equal-x.md b/solutions/lc-solutions/1600-1699/1608-special-array-with-x-elements-greater-than-or-equal-x.md new file mode 100644 index 0000000..6c6c094 --- /dev/null +++ b/solutions/lc-solutions/1600-1699/1608-special-array-with-x-elements-greater-than-or-equal-x.md @@ -0,0 +1,127 @@ +--- +id: special-array-with-x-elements-greater-than-or-equal-x +title: Special Array with X Elements Greater Than or Equal X +level: medium +sidebar_label: Special Array with X Elements Greater Than or Equal X +tags: + - Array + - Sorting + - Counting + - Java +description: "This document provides solutions for the Special Array with X Elements Greater Than or Equal X problem." +--- + +## Problem Statement + +You are given an array `nums` of non-negative integers. `nums` is considered special if there exists a number `x` such that there are exactly `x` numbers in `nums` that are greater than or equal to `x`. + +Notice that `x` does not have to be an element in `nums`. + +Return `x` if the array is special, otherwise, return `-1`. It can be proven that if `nums` is special, the value for `x` is unique. + +**Example 1:** + +Input: `nums = [3,5]` + +Output: `2` + +Explanation: There are 2 values (3 and 5) that are greater than or equal to 2. + +**Example 2:** + +Input: `nums = [0,0]` + +Output: `-1` + +Explanation: No numbers fit the criteria for `x`. +- If `x = 0`, there should be 0 numbers >= `x`, but there are 2. +- If `x = 1`, there should be 1 number >= `x`, but there are 0. +- If `x = 2`, there should be 2 numbers >= `x`, but there are 0. +- `x` cannot be greater since there are only 2 numbers in `nums`. + +**Example 3:** + +Input: `nums = [0,4,3,0,4]` + +Output: `3` + +Explanation: There are 3 values that are greater than or equal to 3. + +**Constraints:** + +- `1 <= nums.length <= 100` +- `0 <= nums[i] <= 1000` + +## Solutions + +### Intuition + +To solve this problem, we need to determine if there exists a number `x` such that there are exactly `x` elements in the array that are greater than or equal to `x`. We can achieve this by counting the number of elements for each possible value and checking if the condition holds. + +### Approach + +1. **Counting Frequencies:** + - Create an array `intArr` to count the occurrences of each element in `nums`. + +2. **Cumulative Sum:** + - Calculate the cumulative sum from the highest value to the lowest to determine how many elements are greater than or equal to each possible value. + +3. **Check Condition:** + - Iterate through the possible values and check if there exists a value `x` where the number of elements greater than or equal to `x` is exactly `x`. + +### Java + +```java +class Solution { + public int specialArray(int[] nums) { + int val = 0; + int len = nums.length; + int[] intArr = new int[1001]; + + for(int i = 0; i < len; i++) { + intArr[nums[i]]++; + } + + for(int i = 1000; i >= 0; i--) { + intArr[i] += val; + val = intArr[i]; + } + + val = -1; + for(int i = 0; i < 1000; i++) { + if(intArr[i] == i) { + val = i; + } + } + + return val; + } + +} +``` + +### Python + +```Python +class Solution: + def specialArray(self, nums: List[int]) -> int: + n = len(nums) + intArr = [0] * 1001 + + for num in nums: + if num <= 1000: + intArr[num] += 1 + + val = 0 + for i in range(1000, -1, -1): + intArr[i] += val + val = intArr[i] + + val = -1 + for i in range(1001): + if intArr[i] == i: + val = i + break + + return val +``` diff --git a/solutions/lc-solutions/1600-1699/1609-Even-Odd-Tree.md b/solutions/lc-solutions/1600-1699/1609-Even-Odd-Tree.md new file mode 100644 index 0000000..354b4d7 --- /dev/null +++ b/solutions/lc-solutions/1600-1699/1609-Even-Odd-Tree.md @@ -0,0 +1,211 @@ +--- +id: even-odd-tree +title: Even Odd Tree (LeetCode) +sidebar_label: 1609-EvenOddTree +tags: + - Tree + - Breadth-First Search + - Level Order Traversal +description: Determine if a binary tree is an "even-odd" tree, where the level of nodes alternates between odd and even values. +sidebar_position: 1609 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Even Odd Tree](https://leetcode.com/problems/even-odd-tree/) | [Even Odd Tree Solution on LeetCode](https://leetcode.com/problems/even-odd-tree/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +A binary tree is named "even-odd" if it satisfies the following conditions: + +1. The root has an odd value. +2. Each level has nodes with values that alternate between odd and even. +3. For each level, nodes with odd values come first, followed by nodes with even values. + +Given the root of a binary tree, return `true` if the binary tree is "even-odd", otherwise return `false`. + +### Example 1 + +- **Input:** `root = [1,10,4,3,null,7,9,12,8,6,null,null,2]` +- **Output:** `true` +- **Explanation:** The values of each level are: + - Level 0: [1] + - Level 1: [10, 4] + - Level 2: [3, 7, 9, 12] + - Level 3: [8, 6, 2] + The tree satisfies all the conditions for an "even-odd" tree. + +### Example 2 + +- **Input:** `root = [5,4,2,3,3,7]` +- **Output:** `false` +- **Explanation:** The values of the levels are: + - Level 0: [5] + - Level 1: [4, 2] + - Level 2: [3, 3, 7] + Node values in the second level are not in strictly increasing order. + +### Constraints + +- The number of nodes in the tree is in the range `[1, 10^5]`. +- `1 <= Node.val <= 10^6` + +## Approach + +To determine if a binary tree is an "even-odd" tree, we can use a breadth-first search (BFS) approach to traverse the tree level by level. Here's the approach: + +1. **Breadth-First Search (BFS)**: + - Use a queue to perform level-order traversal. + - For each level, check if the values alternate between odd and even, maintaining strict ordering. + +2. **Validation**: + - For each node at an even level (`level % 2 == 0`), values should be strictly increasing and odd. + - For each node at an odd level (`level % 2 != 0`), values should be strictly decreasing and even. + +3. **Edge Cases**: + - Handle single node trees appropriately. + +### Solution Code + +#### Python + +```python +from collections import deque +import math + +class Solution: + def isEvenOddTree(self, root: TreeNode) -> bool: + if not root: + return False + + queue = deque([root]) + level = 0 + + while queue: + size = len(queue) + prev_val = -math.inf if level % 2 == 0 else math.inf + + for _ in range(size): + node = queue.popleft() + + if level % 2 == 0: + if node.val % 2 == 0 or node.val <= prev_val: + return False + else: + if node.val % 2 != 0 or node.val >= prev_val: + return False + + prev_val = node.val + + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + + level += 1 + + return True +``` + +#### java +```java +import java.util.LinkedList; +import java.util.Queue; + +class Solution { + public boolean isEvenOddTree(TreeNode root) { + if (root == null) return false; + + Queue queue = new LinkedList<>(); + queue.offer(root); + int level = 0; + + while (!queue.isEmpty()) { + int size = queue.size(); + int prevVal = (level % 2 == 0) ? Integer.MIN_VALUE : Integer.MAX_VALUE; + + for (int i = 0; i < size; i++) { + TreeNode node = queue.poll(); + + if (level % 2 == 0) { + if (node.val % 2 == 0 || node.val <= prevVal) { + return false; + } + } else { + if (node.val % 2 != 0 || node.val >= prevVal) { + return false; + } + } + + prevVal = node.val; + + if (node.left != null) { + queue.offer(node.left); + } + if (node.right != null) { + queue.offer(node.right); + } + } + + level++; + } + + return true; + } +} +``` + +#### C++ +```c++ +#include +#include +using namespace std; + +class Solution { +public: + bool isEvenOddTree(TreeNode* root) { + if (!root) return false; + + queue q; + q.push(root); + int level = 0; + + while (!q.empty()) { + int size = q.size(); + int prevVal = (level % 2 == 0) ? numeric_limits::min() : numeric_limits::max(); + + for (int i = 0; i < size; ++i) { + TreeNode* node = q.front(); + q.pop(); + + if (level % 2 == 0) { + if (node->val % 2 == 0 || node->val <= prevVal) { + return false; + } + } else { + if (node->val % 2 != 0 || node->val >= prevVal) { + return false; + } + } + + prevVal = node->val; + + if (node->left) q.push(node->left); + if (node->right) q.push(node->right); + } + + ++level; + } + + return true; + } +}; +``` + +#### Conclusion +The above solutions use BFS to validate if a given binary tree is an "even-odd" tree based on the +defined rules. Each solution ensures that nodes at even and odd levels have values that strictly +alternate in the required manner. Adjustments for different languages and edge cases are handled to +ensure robustness across different inputs. \ No newline at end of file diff --git a/solutions/lc-solutions/1600-1699/1622- Fancy Sequence.md b/solutions/lc-solutions/1600-1699/1622- Fancy Sequence.md new file mode 100644 index 0000000..f7042c0 --- /dev/null +++ b/solutions/lc-solutions/1600-1699/1622- Fancy Sequence.md @@ -0,0 +1,167 @@ +--- +id: fancy-sequence +title: Fancy Sequence +sidebar_label: 1622 Fancy Sequence +tags: +- Math +- Design +- Segment Tree +description: "This document provides a solution where we need to Write an API that generates fancy sequences using the append, addAll, and multAll operations. " +--- + +## Problem + +Write an API that generates fancy sequences using the $append$, $addAll$, and $multAll$ operations. + +Implement the $Fancy$ class: + +- Fancy() Initializes the object with an empty sequence. + +- void append(val) Appends an integer val to the end of the sequence. + +- void addAll(inc) Increments all existing values in the sequence by an integer inc. + +- void multAll(m) Multiplies all existing values in the sequence by an integer m. + +- int getIndex(idx) Gets the current value at index $idx$ (0-indexed) of the sequence **modulo** $10^9$ + $7$. If the index is greater or equal than the length of the sequence, return $-1$. + +### Examples + +**Example 1:** + +``` +Input: "["Fancy", "append", "addAll", "append", "multAll", "getIndex", "addAll", "append", "multAll", "getIndex", "getIndex", "getIndex"] +[[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]" + +Output: "[null, null, null, null, null, 10, null, null, null, 26, 34, 20]" + +Explanation: + +Fancy fancy = new Fancy(); +fancy.append(2); // fancy sequence: [2] +fancy.addAll(3); // fancy sequence: [2+3] -> [5] +fancy.append(7); // fancy sequence: [5, 7] +fancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14] +fancy.getIndex(0); // return 10 +fancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17] +fancy.append(10); // fancy sequence: [13, 17, 10] +fancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20] +fancy.getIndex(0); // return 26 +fancy.getIndex(1); // return 34 +fancy.getIndex(2); // return 20 +``` + +### Constraints + +- `1 <= val, inc, m <= 100` +- `0 <= idx <= 10^5` +- At most $10^5$ calls total will be made to $append$, $addAll$, $multAll$, and $getIndex$. + +--- + +## Approach + +To solve the problem, we need to understand the nature of the allowed moves: + +1. **Using Lazy Operations**: + + - Instead of updating the entire sequence for $addAll$ and $multAll$, we maintain cumulative addition and multiplication factors. This way, we can defer the actual updates to when we need to access a particular element. + +2. **Tracking Inverse Operations**: + + - When appending a new value, we need to account for the current cumulative operations, so we store values in a form that can be easily adjusted when retrieving them. + +3. **Efficient Index Retrieval**: + + - By maintaining cumulative operations and only applying them when accessing an index, we ensure that our operations are efficient and avoid unnecessary updates to the sequence. + +## Solution for Fancy Sequence + +The problem involves three types of operations on a sequence of numbers: appending a value, adding a value to all elements, and multiplying all elements by a value. A naive approach would directly modify the sequence for each operation, but this would be inefficient given the constraints. Instead, we can use lazy propagation-like techniques to efficiently handle the operations. + +#### Code in Java + +```java +import java.util.ArrayList; +import java.util.List; + +class Fancy { + private static final int MOD = 1000000007; + private List sequence; + private long add; + private long mult; + + public Fancy() { + sequence = new ArrayList<>(); + add = 0; + mult = 1; + } + + public void append(int val) { + // Apply the inverse of the current add and mult to keep the value as its original form + long adjustedVal = ((val - add) * modInverse(mult, MOD)) % MOD; + if (adjustedVal < 0) adjustedVal += MOD; + sequence.add(adjustedVal); + } + + public void addAll(int inc) { + add = (add + inc) % MOD; + } + + public void multAll(int m) { + add = (add * m) % MOD; + mult = (mult * m) % MOD; + } + + public int getIndex(int idx) { + if (idx >= sequence.size()) return -1; + long result = (sequence.get(idx) * mult + add) % MOD; + return (int) result; + } + + // Function to compute the modular inverse using Fermat's Little Theorem + private long modInverse(long a, int mod) { + return power(a, mod - 2, mod); + } + + // Function to compute (x^y) % mod + private long power(long x, int y, int mod) { + if (y == 0) return 1; + long p = power(x, y / 2, mod) % mod; + p = (p * p) % mod; + return (y % 2 == 0) ? p : (x * p) % mod; + } + + public static void main(String[] args) { + Fancy fancy = new Fancy(); + fancy.append(2); + fancy.addAll(3); + fancy.append(7); + fancy.multAll(2); + System.out.println(fancy.getIndex(0)); + fancy.addAll(3); + fancy.append(10); + fancy.multAll(2); + System.out.println(fancy.getIndex(0)); + System.out.println(fancy.getIndex(1)); + System.out.println(fancy.getIndex(2)); + } +} + +``` + +### Complexity Analysis + +#### Time Complexity: $O(1)$ + +> **Reason**: Time Complexity is $O(1)$, because append involves adding an element to the list, Whereas addAll only updates a cumulative variable, multAll updates cumulative variables and lastly getIndex, it basically involves getIndex calculating the result using the cumulative variables. + +#### Space Complexity: $O(n)$ + +> **Reason**: $O(n)$, where n is the number of elements in the sequence, as we store each element. + +# References + +- **LeetCode Problem:** [Fancy Sequence](https://leetcode.com/problems/fancy-sequence/description/) +- **Solution Link:** [Fancy Sequence Solution on LeetCode](https://leetcode.com/problems/fancy-sequence/solutions/) +- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/vivekvardhan43862/) diff --git a/solutions/lc-solutions/1600-1699/1631-path-with-minimum-effort.md b/solutions/lc-solutions/1600-1699/1631-path-with-minimum-effort.md new file mode 100644 index 0000000..9a79ccd --- /dev/null +++ b/solutions/lc-solutions/1600-1699/1631-path-with-minimum-effort.md @@ -0,0 +1,352 @@ +--- +id: path-with-minimum-effort +title: Path With Minimum Effort +sidebar_label: 1631 - Path With Minimum Effort +tags: +- Array +- Binary Search +- Depth-First Search +- Breadth-First Search +- Union Find +- Heap (Priority Queue) +- Matrix + +description: "This is a solution to the Path With Minimum Effort problem on LeetCode." +--- + +## Problem Description +You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where `heights[row][col]` represents the height of cell (row, col). You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1) (i.e., 0-indexed)`. You can move up, down, left, or right, and you wish to find a route that requires the minimum effort. + +A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. + +Return the minimum effort required to travel from the top-left cell to the bottom-right cell. + + +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2020/10/04/ex1.png) + +``` +Input: heights = [[1,2,2],[3,8,2],[5,3,5]] +Output: 2 +Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells. +This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3. + +``` + +**Example 2:** +![image](https://assets.leetcode.com/uploads/2020/10/04/ex2.png) + +``` +Input: heights = [[1,2,3],[3,8,4],[5,3,5]] +Output: 1 +Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5]. +``` + +**Example 3:** +![image](https://assets.leetcode.com/uploads/2020/10/04/ex3.png) +``` +Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]] +Output: 0 +Explanation: This route does not require any effort. +``` + +### Constraints +- `rows == heights.length` +- `columns == heights[i].length` +- `1 <= rows, columns <= 100` +- `1 <= heights[i][j] <= 10^6` + +## Solution for Path With Minimum Effort Problem +### Approach +#### Dijkstra's Algorithm: +- A classic algorithm for finding the shortest path in a weighted graph, adapted for this problem. + +#### Steps +##### Initialize Priority Queue: +- The algorithm starts at the top-left corner (the source). The priority queue is initialized to store the effort needed to reach each cell from the source. The effort for the source itself is zero. +##### Distance Matrix: +- A 2D array keeps track of the minimum effort required to reach each cell. Initially, this is set to infinity for all cells except the source. + +##### Iterate and Update Distances: +- The algorithm pops the cell with the smallest effort from the priority queue and explores its neighbors. The effort required to reach a neighbor is updated if a smaller effort is found. +##### Early Exit: +- The algorithm stops when it reaches the bottom-right corner, returning the effort required to get there. + + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function minimumEffortPath(heights) { + const rows = heights.length, cols = heights[0].length; + const dist = Array.from(Array(rows), () => Array(cols).fill(Infinity)); + const minHeap = [[0, 0, 0]]; // [effort, x, y] + + dist[0][0] = 0; + const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]; + + while (minHeap.length > 0) { + const [effort, x, y] = minHeap.shift(); + + if (effort > dist[x][y]) continue; + + if (x === rows - 1 && y === cols - 1) return effort; + + for (const [dx, dy] of directions) { + const nx = x + dx, ny = y + dy; + if (nx >= 0 && nx < rows && ny >= 0 && ny < cols) { + const newEffort = Math.max(effort, Math.abs(heights[x][y] - heights[nx][ny])); + if (newEffort < dist[nx][ny]) { + dist[nx][ny] = newEffort; + minHeap.push([newEffort, nx, ny]); + minHeap.sort((a, b) => a[0] - b[0]); + } + } + } + } + return -1; + } + const input = [[1,2,2],[3,8,2],[5,3,5]] + const output = minimumEffortPath(input) ; + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(M*N log(M*N)) $ where M and N are the dimensions of the grid. This is primarily due to the operations on the priority queue. + - Space Complexity: $ O(M*N) $ $O(M*N)$, needed for the distance matrix and the priority queue. + + ## Code in Different Languages + + + + ```javascript + function minimumEffortPath(heights) { + const rows = heights.length, cols = heights[0].length; + const dist = Array.from(Array(rows), () => Array(cols).fill(Infinity)); + const minHeap = [[0, 0, 0]]; // [effort, x, y] + + dist[0][0] = 0; + const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]; + + while (minHeap.length > 0) { + const [effort, x, y] = minHeap.shift(); + + if (effort > dist[x][y]) continue; + + if (x === rows - 1 && y === cols - 1) return effort; + + for (const [dx, dy] of directions) { + const nx = x + dx, ny = y + dy; + if (nx >= 0 && nx < rows && ny >= 0 && ny < cols) { + const newEffort = Math.max(effort, Math.abs(heights[x][y] - heights[nx][ny])); + if (newEffort < dist[nx][ny]) { + dist[nx][ny] = newEffort; + minHeap.push([newEffort, nx, ny]); + minHeap.sort((a, b) => a[0] - b[0]); + } + } + } + } + return -1; + } + ``` + + + + + ```typescript + class Solution { + minimumEffortPath(heights: number[][]): number { + const pq = new MinPriorityQueue<{priority: number, element: [number, [number, number]]}>({ priority: x => x.priority }); + const n = heights.length; + const m = heights[0].length; + const dist = Array.from({ length: n }, () => Array(m).fill(Infinity)); + dist[0][0] = 0; + pq.enqueue({priority: 0, element: [0, [0, 0]]}); + + const delRow = [-1, 0, 1, 0]; + const delCol = [0, 1, 0, -1]; + + while (!pq.isEmpty()) { + const {element: [diff, [row, col]]} = pq.dequeue(); + + if (row === n - 1 && col === m - 1) return diff; + + for (let i = 0; i < 4; i++) { + const newRow = row + delRow[i]; + const newCol = col + delCol[i]; + + if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < m) { + const newEffort = Math.max(Math.abs(heights[row][col] - heights[newRow][newCol]), diff); + if (newEffort < dist[newRow][newCol]) { + dist[newRow][newCol] = newEffort; + pq.enqueue({priority: newEffort, element: [newEffort, [newRow, newCol]]}); + } + } + } + } + return 0; + } +} + + ``` + + + + ```python + import heapq + +class Solution: + def minimumEffortPath(self, heights: List[List[int]]) -> int: + n, m = len(heights), len(heights[0]) + dist = [[float('inf')] * m for _ in range(n)] + dist[0][0] = 0 + pq = [(0, 0, 0)] + + delRow = [-1, 0, 1, 0] + delCol = [0, 1, 0, -1] + + while pq: + diff, row, col = heapq.heappop(pq) + + if row == n - 1 and col == m - 1: + return diff + + for i in range(4): + newRow, newCol = row + delRow[i], col + delCol[i] + + if 0 <= newRow < n and 0 <= newCol < m: + newEffort = max(abs(heights[row][col] - heights[newRow][newCol]), diff) + if newEffort < dist[newRow][newCol]: + dist[newRow][newCol] = newEffort + heapq.heappush(pq, (newEffort, newRow, newCol)) + return 0 + + ``` + + + + + ```java + import java.util.*; + +class Solution { + public int minimumEffortPath(int[][] heights) { + PriorityQueue pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); + int n = heights.length; + int m = heights[0].length; + int[][] dist = new int[n][m]; + for (int[] row : dist) Arrays.fill(row, Integer.MAX_VALUE); + dist[0][0] = 0; + pq.offer(new int[]{0, 0, 0}); + + int[] delRow = {-1, 0, 1, 0}; + int[] delCol = {0, 1, 0, -1}; + + while (!pq.isEmpty()) { + int[] curr = pq.poll(); + int diff = curr[0]; + int row = curr[1]; + int col = curr[2]; + + if (row == n - 1 && col == m - 1) return diff; + + for (int i = 0; i < 4; i++) { + int newRow = row + delRow[i]; + int newCol = col + delCol[i]; + + if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < m) { + int newEffort = Math.max(Math.abs(heights[row][col] - heights[newRow][newCol]), diff); + if (newEffort < dist[newRow][newCol]) { + dist[newRow][newCol] = newEffort; + pq.offer(new int[]{newEffort, newRow, newCol}); + } + } + } + } + return 0; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + int minimumEffortPath(vector>& heights) { + priority_queue>, + vector>>, + greater>>>pq; + + int n = heights.size(); + int m = heights[0].size(); + + vector> dist(n, vector(m, 1e9)); + dist[0][0] = 0; + // {diff{row,col}} + pq.push({0, {0, 0}}); + + int delRow[] = {-1, 0, 1, 0}; + int delCol[] = {0, 1, 0, -1}; + + while (!pq.empty()) { + auto it = pq.top(); + pq.pop(); + + int diff = it.first; + int row = it.second.first; + int col = it.second.second; + + if (row == n - 1 && col == m - 1) + return diff; + + for (int i = 0; i < 4; i++) { + int newRow = row + delRow[i]; + int newCol = col + delCol[i]; + + if (newRow >= 0 & newRow < n && newCol >= 0 && newCol < m) { + int newEffort = max( + abs(heights[row][col] - heights[newRow][newCol]), diff); + ; + if (newEffort < dist[newRow][newCol]) { + dist[newRow][newCol] = newEffort; + pq.push({newEffort, {newRow, newCol}}); + } + } + } + } + return 0; + } +}; + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Path With Minimum Effort](https://leetcode.com/problems/path-with-minimum-effort/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/path-with-minimum-effort/solutions) + diff --git a/solutions/lc-solutions/1600-1699/1646-get-maximum-in-generated-array.md b/solutions/lc-solutions/1600-1699/1646-get-maximum-in-generated-array.md new file mode 100644 index 0000000..4c07a66 --- /dev/null +++ b/solutions/lc-solutions/1600-1699/1646-get-maximum-in-generated-array.md @@ -0,0 +1,180 @@ +--- +id: get-maximum-in-generated-array +title: Get Maximum in Generated Array +sidebar_label: 1646-Get Maximum in Generated Array +tags: + - Brute Force + - Dynamic Programming + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Get Maximum in Generated Array problem on LeetCode." +sidebar_position: 2 +--- + +## Problem Description + +You are given an integer `n`. A 0-indexed integer array `nums` of length `n + 1` is generated in the following way: + +- `nums[0] = 0` +- `nums[1] = 1` +- `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n` +- `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n` + +Return the maximum integer in the array `nums`. + +### Examples + +**Example 1:** + +``` +Input: n = 7 +Output: 3 +Explanation: According to the given rules: + nums[0] = 0 + nums[1] = 1 + nums[(1 * 2) = 2] = nums[1] = 1 + nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2 + nums[(2 * 2) = 4] = nums[2] = 1 + nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3 + nums[(3 * 2) = 6] = nums[3] = 2 + nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3 +Hence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3. +``` + +**Example 2:** + +``` +Input: n = 2 +Output: 1 +Explanation: According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1. +``` + +**Example 3:** + +``` +Input: n = 3 +Output: 2 +Explanation: According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2. +``` + +### Constraints + +- `0 <= n <= 100` + +--- + +## Solution for Get Maximum in Generated Array Problem + +### Approach: Dynamic Programming + +The problem can be solved efficiently using a dynamic programming approach. We generate the array according to the given rules and keep track of the maximum value. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int getMaximumGenerated(int n) { + if (n == 0) return 0; + if (n == 1) return 1; + + vector nums(n + 1); + nums[0] = 0; + nums[1] = 1; + int maxVal = 1; + + for (int i = 2; i <= n; ++i) { + if (i % 2 == 0) { + nums[i] = nums[i / 2]; + } else { + nums[i] = nums[i / 2] + nums[i / 2 + 1]; + } + maxVal = max(maxVal, nums[i]); + } + + return maxVal; + } +}; +``` + + + + + +```java +class Solution { + public int getMaximumGenerated(int n) { + if (n == 0) return 0; + if (n == 1) return 1; + + int[] nums = new int[n + 1]; + nums[0] = 0; + nums[1] = 1; + int maxVal = 1; + + for (int i = 2; i <= n; ++i) { + if (i % 2 == 0) { + nums[i] = nums[i / 2]; + } else { + nums[i] = nums[i / 2] + nums[i / 2 + 1]; + } + maxVal = Math.max(maxVal, nums[i]); + } + + return maxVal; + } +} +``` + + + + + +```python +class Solution: + def getMaximumGenerated(self, n: int) -> int: + if n == 0: + return 0 + if n == 1: + return 1 + + nums = [0] * (n + 1) + nums[0] = 0 + nums[1] = 1 + max_val = 1 + + for i in range(2, n + 1): + if i % 2 == 0: + nums[i] = nums[i // 2] + else: + nums[i] = nums[i // 2] + nums[i // 2 + 1] + max_val = max(max_val, nums[i]) + + return max_val +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(n)$ + - We iterate through the array once to fill in the values. +- **Space Complexity**: $O(n)$ + - We use additional space to store the array `nums` of length `n + 1`. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/1600-1699/1652-defuse-the-bomb.md b/solutions/lc-solutions/1600-1699/1652-defuse-the-bomb.md new file mode 100644 index 0000000..c5e17d7 --- /dev/null +++ b/solutions/lc-solutions/1600-1699/1652-defuse-the-bomb.md @@ -0,0 +1,294 @@ +--- +id: defuse-the-bomb +title: Defuse the Bomb Solution +sidebar_label: 1652-Defuse the Bomb +tags: + - Circular Array + - Sliding Window + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Defuse the Bomb problem on LeetCode." +sidebar_position: 2 +--- + +In this tutorial, we will solve the Defuse the Bomb problem using a circular array and sliding window approach. We will provide the implementation of the solution in C++, Java, and Python. + +## Problem Description + +You have a bomb to defuse, and your informer will provide you with a circular array `code` of length `n` and a key `k`. To decrypt the code, you must replace every number as follows: + +- If `k > 0`, replace the `i-th` number with the sum of the next `k` numbers. +- If `k < 0`, replace the `i-th` number with the sum of the previous `k` numbers. +- If `k == 0`, replace the `i-th` number with 0. + +As `code` is circular, the next element of `code[n-1]` is `code[0]`, and the previous element of `code[0]` is `code[n-1]`. + +### Examples + +**Example 1:** + +``` +Input: code = [5,7,1,4], k = 3 +Output: [12,10,16,13] +Explanation: Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around. +``` + +**Example 2:** + +``` +Input: code = [1,2,3,4], k = 0 +Output: [0,0,0,0] +Explanation: When k is zero, the numbers are replaced by 0. +``` + +**Example 3:** + +``` +Input: code = [2,4,9,3], k = -2 +Output: [12,5,6,13] +Explanation: The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of the previous numbers. +``` + +### Constraints + +- `n == code.length` +- `1 <= n <= 100` +- `1 <= code[i] <= 100` +- `-(n - 1) <= k <= n - 1` + +--- + +## Solution for Defuse the Bomb Problem + +### Intuition and Approach + +The problem can be solved using a sliding window approach to handle the circular nature of the array. Depending on the value of `k`, we sum the appropriate elements and use modular arithmetic to handle the circular behavior. + + + + +### Approach 1: Brute Force (Naive) + +The brute force approach involves iterating through each element and calculating the sum of the next or previous `k` elements based on the value of `k`. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector decrypt(vector& code, int k) { + int n = code.size(); + vector result(n, 0); + + if (k == 0) return result; + + for (int i = 0; i < n; ++i) { + int sum = 0; + for (int j = 1; j <= abs(k); ++j) { + if (k > 0) { + sum += code[(i + j) % n]; + } else { + sum += code[(i - j + n) % n]; + } + } + result[i] = sum; + } + + return result; + } +}; +``` + + + + + +```java +class Solution { + public int[] decrypt(int[] code, int k) { + int n = code.length; + int[] result = new int[n]; + + if (k == 0) return result; + + for (int i = 0; i < n; ++i) { + int sum = 0; + for (int j = 1; j <= Math.abs(k); ++j) { + if (k > 0) { + sum += code[(i + j) % n]; + } else { + sum += code[(i - j + n) % n]; + } + } + result[i] = sum; + } + + return result; + } +} +``` + + + + + +```python +class Solution: + def decrypt(self, code: List[int], k: int) -> List[int]: + n = len(code) + result = [0] * n + + if k == 0: + return result + + for i in range(n): + sum_val = 0 + for j in range(1, abs(k) + 1): + if k > 0: + sum_val += code[(i + j) % n] + else: + sum_val += code[(i - j + n) % n] + result[i] = sum_val + + return result +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n \cdot |k|)$ due to nested loops. +- Space Complexity: $O(n)$ for the result array. +- Where `n` is the length of the code array. +- The time complexity is $O(n \cdot |k|)$ because we iterate through each element and calculate the sum of `k` elements. +- The space complexity is $O(n)$ because we store the result in a new array. + + + + +### Approach 2: Sliding Window (Optimized) + +The sliding window approach uses a more efficient way to calculate the sum by maintaining a running sum and updating it as the window slides over the array. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector decrypt(vector& code, int k) { + int n = code.size(); + vector result(n, 0); + + if (k == 0) return result; + + int start = k > 0 ? 1 : k; + int end = k > 0 ? k : -1; + + int sum = 0; + for (int i = start; i != end + 1; ++i) { + sum += code[(i + n) % n]; + } + + for (int i = 0; i < n; ++i) { + result[i] = sum; + sum -= code[(start + i + n) % n]; + sum += code[(end + 1 + i + n) % n]; + } + + return result; + } +}; +``` + + + + + +```java +class Solution { + public int[] decrypt(int[] code, int k) { + int n = code.length; + int[] result = new int[n]; + + if (k == 0) return result; + + int start = k > 0 ? 1 : k; + int end = k > 0 ? k : -1; + + int sum = 0; + for (int i = start; i != end + 1; ++i) { + sum += code[(i + n) % n]; + } + + for (int i = 0; i < n; ++i) { + result[i] = sum; + sum -= code[(start + i + n) % n]; + sum += code[(end + 1 + i + n) % n]; + } + + return result; + } +} +``` + + + + + +```python +class Solution: + def decrypt(self, code: List[int], k: int) -> List[int]: + n = len(code) + result = [0] * n + + if k == 0: + return result + + start, end = (1, k) if k > 0 else (k, -1) + + sum_val = sum(code[i % n] for i in range(start, end + 1)) + + for i in range(n): + result[i] = sum_val + sum_val -= code[(start + i) % n] + sum_val += code[(end + 1 + i) % n] + + return result +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ due to the sliding window. +- Space Complexity: $O(n)$ for the result array. +- Where `n` is the length of the code array. +- The time complexity is $O(n + +)$ because we iterate through each element once with a running sum. +- The space complexity is $O(n)$ because we store the result in a new array. + + + + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/1600-1699/1662-check-if-two-string-arrays-are-equivalent.md b/solutions/lc-solutions/1600-1699/1662-check-if-two-string-arrays-are-equivalent.md new file mode 100644 index 0000000..5ab19cd --- /dev/null +++ b/solutions/lc-solutions/1600-1699/1662-check-if-two-string-arrays-are-equivalent.md @@ -0,0 +1,117 @@ +--- +id: check-if-two-string-arrays-are-equivalent +title: Check If Two String Arrays are Equivalent +sidebar_label: 1662-Check If Two String Arrays are Equivalent +tags: + - Array + +description: "This is a solution to the Check If Two String Arrays are Equivalent in a string in leetcode" +--- + +## Problem Description + +Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. + +A string is represented by an array if the array elements concatenated in order forms the string. + + + +### Examples + +**Example 1:** + +``` +Input: word1 = ["ab", "c"], word2 = ["a", "bc"] +Output: true +Explanation: +word1 represents string "ab" + "c" -> "abc" +word2 represents string "a" + "bc" -> "abc" +The strings are the same, so return true. +``` +**Example 2:** +``` +Input: word1 = ["a", "cb"], word2 = ["ab", "c"] +Output: false + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(word1.length+word2.length)$ + +*** Space Complexity:** $O(1)$ + +### Constraints + +- `1 <= word1.length, word2.length <= 103` +- `1 <= word1[i].length, word2[i].length <= 103` +- `1 <= sum(word1[i].length), sum(word2[i].length) <= 103` + + + +### Solution +## Approach + +To determine if two arrays of strings are equivalent by concatenating their elements, the approach involves combining the elements of each array into single strings and then comparing these resulting strings. Specifically, for each input array, iterate through its elements and concatenate them into one continuous string. Once both arrays are fully concatenated, compare the two resulting strings for equality. If they are identical, the function returns true; otherwise, it returns false. This method ensures that the order and content of the strings are preserved and accurately compared. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + bool arrayStringsAreEqual(std::vector& word1, std::vector& word2) { + std::string s1 = ""; + std::string s2 = ""; + for(const std::string& ch1 : word1) { + s1 += ch1; + } + for(const std::string& ch2 : word2) { + s2 += ch2; + } + return s1 == s2; + } +}; + + +``` + + + + +```java +class Solution { + public boolean arrayStringsAreEqual(String[] word1, String[] word2) { + String s1=""; + String s2=""; + for(String ch1:word1) + s1+=ch1; + for(String ch2:word2) + s2+=ch2; + return s1.equals(s2); + } +} + +``` + + + + +```python +class Solution: + def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: + s1 = "".join(word1) + s2 = "".join(word2) + return s1 == s2 + +``` + + + +## References + +- **LeetCode Problem**: [Check If Two String Arrays are Equivalent](https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/description/) + +- **Solution Link**: [Check If Two String Arrays are Equivalent](https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/post-solution/?submissionId=1234733608) diff --git a/solutions/lc-solutions/1600-1699/1670-design-front-middle-back-queue.md b/solutions/lc-solutions/1600-1699/1670-design-front-middle-back-queue.md new file mode 100644 index 0000000..7039ce0 --- /dev/null +++ b/solutions/lc-solutions/1600-1699/1670-design-front-middle-back-queue.md @@ -0,0 +1,481 @@ +--- +id: design-front-middle-back-queue +title: Design Front Middle Back Queue +sidebar_label: 1670.Design Front Middle Back Queue + +tags: +- Array +- Linked List +- Design +- Queue +- Data Stream + +description: "This is a solution to theDesign Front Middle Back Queue problem on LeetCode." +--- + +## Problem Description +Design a queue that supports push and pop operations in the front, middle, and back. + +Implement the FrontMiddleBack class: + +- FrontMiddleBack() Initializes the queue. +- void pushFront(int val) Adds val to the front of the queue. +- void pushMiddle(int val) Adds val to the middle of the queue. +- void pushBack(int val) Adds val to the back of the queue. +- int popFront() Removes the front element of the queue and returns it. If the queue is empty, return -1. +- int popMiddle() Removes the middle element of the queue and returns it. If the queue is empty, return -1. +- int popBack() Removes the back element of the queue and returns it. If the queue is empty, return -1. +- Notice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example: + +- Pushing 6 into the middle of [1, 2, 3, 4, 5] results in [1, 2, 6, 3, 4, 5]. +- Popping the middle from [1, 2, 3, 4, 5, 6] returns 3 and results in [1, 2, 4, 5, 6]. + +### Examples +**Example 1:** +``` +Input: +["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", "popFront", "popMiddle", "popMiddle", "popBack", "popFront"] +[[], [1], [2], [3], [4], [], [], [], [], []] +Output: +[null, null, null, null, null, 1, 3, 4, 2, -1] + +Explanation: +FrontMiddleBackQueue q = new FrontMiddleBackQueue(); +q.pushFront(1); // [1] +q.pushBack(2); // [1, 2] +q.pushMiddle(3); // [1, 3, 2] +q.pushMiddle(4); // [1, 4, 3, 2] +q.popFront(); // return 1 -> [4, 3, 2] +q.popMiddle(); // return 3 -> [4, 2] +q.popMiddle(); // return 4 -> [2] +q.popBack(); // return 2 -> [] +q.popFront(); // return -1 -> [] (The queue is empty) + +``` + +### Constraints +- `1 <= val <= 10^9` +- At most 1000 calls will be made to pushFront, pushMiddle, pushBack, popFront, popMiddle, and popBack. +## Solution for Design Front Middle Back Queue +### Approach +#### Data Structure + +- **Deque (Double-ended Queue):** A deque is used to store the elements. It allows for efficient addition and removal of elements from both the front and the back. This is crucial for implementing the required operations efficiently. + +#### Operations + +1. **Initialization:** + - The constructor initializes an empty deque. + +2. **Push Operations:** + - **pushFront(int val):** + - Adds `val` to the front of the deque. + - This is done using the `push_front` method in C++ or the equivalent method in other languages (e.g., `unshift` in JavaScript, `appendleft` in Python, `addFirst` in Java). + - **pushMiddle(int val):** + - Adds `val` to the middle of the deque. + - The middle index is calculated as `size / 2`. If the size is even, it places the element just before the second half; if odd, it places it in the middle. + - Inserting at this position can be done using the `insert` method in most languages. + - **pushBack(int val):** + - Adds `val` to the back of the deque. + - This is done using the `push_back` method in C++ or the equivalent method in other languages (e.g., `push` in JavaScript, `append` in Python, `addLast` in Java). + +3. **Pop Operations:** + - **popFront():** + - Removes and returns the element from the front of the deque. + - If the deque is empty, it returns `-1`. + - This is done using the `pop_front` method in C++ or the equivalent method in other languages (e.g., `shift` in JavaScript, `popleft` in Python, `removeFirst` in Java). + - **popMiddle():** + - Removes and returns the middle element of the deque. + - The middle index is calculated as `(size - 1) / 2`. This ensures the correct middle element is chosen whether the size is odd or even. + - If the deque is empty, it returns `-1`. + - The element at this index is removed using the `erase` method in C++ or the equivalent method in other languages (e.g., `splice` in JavaScript, direct indexing in Python, manual traversal in Java). + - **popBack():** + - Removes and returns the element from the back of the deque. + - If the deque is empty, it returns `-1`. + - This is done using the `pop_back` method in C++ or the equivalent method in other languages (e.g., `pop` in JavaScript, `pop` in Python, `removeLast` in Java). + +## Intuition + +The main intuition behind using a deque is that it provides efficient O(1) time complexity for adding and removing elements from both ends. For the middle operations, although inserting and removing from the middle of a deque is generally O(n) due to shifting elements, the deque allows straightforward and flexible indexing which simplifies implementation. + + + + + + #### Implementation + ```jsx live + function Solution(arr) { + var FrontMiddleBackQueue = function() { + this.queue = []; + }; + + /** + * @param {number} val + * @return {void} + */ + FrontMiddleBackQueue.prototype.pushFront = function(val) { + this.queue.unshift(val); + }; + + /** + * @param {number} val + * @return {void} + */ + FrontMiddleBackQueue.prototype.pushMiddle = function(val) { + let middle = Math.floor(this.queue.length / 2); + this.queue.splice(middle, 0, val) + }; + + /** + * @param {number} val + * @return {void} + */ + FrontMiddleBackQueue.prototype.pushBack = function(val) { + this.queue.push(val); + }; + + /** + * @return {number} + */ + FrontMiddleBackQueue.prototype.popFront = function() { + if(!this.queue.length) return -1; + return this.queue.shift(); + }; + + /** + * @return {number} + */ + FrontMiddleBackQueue.prototype.popMiddle = function() { + if(!this.queue.length) return -1; + let middle = Math.floor(this.queue.length / 2); + if(this.queue.length % 2 == 0) middle--; + return this.queue.splice(middle, 1); + }; + + /** + * @return {number} + */ + FrontMiddleBackQueue.prototype.popBack = function() { + if(!this.queue.length) return -1; + return this.queue.pop(); + }; + + /** + * Your FrontMiddleBackQueue object will be instantiated and called as such: + * var obj = new FrontMiddleBackQueue() + * obj.pushFront(val) + * obj.pushMiddle(val) + * obj.pushBack(val) + * var param_4 = obj.popFront() + * var param_5 = obj.popMiddle() + * var param_6 = obj.popBack() + */ + const input = "["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", "popFront", "popMiddle", "popMiddle", "popBack", "popFront"] + [[], [1], [2], [3], [4], [], [], [], [], []]" + const output =[null, null, null, null, null, 1, 3, 4, 2, -1] + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(1) $ + - Space Complexity: $ O(n)$ , where n is the total number we are inserting + + ## Code in Different Languages + + + + ```javascript + var FrontMiddleBackQueue = function() { + this.queue = []; +}; + +/** + * @param {number} val + * @return {void} + */ +FrontMiddleBackQueue.prototype.pushFront = function(val) { + this.queue.unshift(val); +}; + +/** + * @param {number} val + * @return {void} + */ +FrontMiddleBackQueue.prototype.pushMiddle = function(val) { + let middle = Math.floor(this.queue.length / 2); + this.queue.splice(middle, 0, val) +}; + +/** + * @param {number} val + * @return {void} + */ +FrontMiddleBackQueue.prototype.pushBack = function(val) { + this.queue.push(val); +}; + +/** + * @return {number} + */ +FrontMiddleBackQueue.prototype.popFront = function() { + if(!this.queue.length) return -1; + return this.queue.shift(); +}; + +/** + * @return {number} + */ +FrontMiddleBackQueue.prototype.popMiddle = function() { + if(!this.queue.length) return -1; + let middle = Math.floor(this.queue.length / 2); + if(this.queue.length % 2 == 0) middle--; + return this.queue.splice(middle, 1); +}; + +/** + * @return {number} + */ +FrontMiddleBackQueue.prototype.popBack = function() { + if(!this.queue.length) return -1; + return this.queue.pop(); +}; + +/** + * Your FrontMiddleBackQueue object will be instantiated and called as such: + * var obj = new FrontMiddleBackQueue() + * obj.pushFront(val) + * obj.pushMiddle(val) + * obj.pushBack(val) + * var param_4 = obj.popFront() + * var param_5 = obj.popMiddle() + * var param_6 = obj.popBack() + */ + ``` + + + + + ```typescript + class FrontMiddleBackQueue { + private dq: number[]; + + constructor() { + this.dq = []; + } + + pushFront(val: number): void { + this.dq.unshift(val); + } + + pushMiddle(val: number): void { + const size = this.dq.length; + this.dq.splice(Math.floor(size / 2), 0, val); + } + + pushBack(val: number): void { + this.dq.push(val); + } + + popFront(): number { + if (this.dq.length === 0) return -1; + return this.dq.shift()!; + } + + popMiddle(): number { + if (this.dq.length === 0) return -1; + const size = this.dq.length; + const middleIndex = Math.floor((size - 1) / 2); + return this.dq.splice(middleIndex, 1)[0]; + } + + popBack(): number { + if (this.dq.length === 0) return -1; + return this.dq.pop()!; + } +} + + ``` + + + + ```python + from collections import deque + +class FrontMiddleBackQueue: + def __init__(self): + self.dq = deque() + + def pushFront(self, val: int) -> None: + self.dq.appendleft(val) + + def pushMiddle(self, val: int) -> None: + size = len(self.dq) + self.dq.insert(size // 2, val) + + def pushBack(self, val: int) -> None: + self.dq.append(val) + + def popFront(self) -> int: + if not self.dq: + return -1 + return self.dq.popleft() + + def popMiddle(self) -> int: + if not self.dq: + return -1 + size = len(self.dq) + middleIndex = (size - 1) // 2 + return self.dq.pop(middleIndex) + + def popBack(self) -> int: + if not self.dq: + return -1 + return self.dq.pop() + + ``` + + + + + ```java + import java.util.Deque; +import java.util.LinkedList; + +class FrontMiddleBackQueue { + private Deque dq; + + public FrontMiddleBackQueue() { + dq = new LinkedList<>(); + } + + public void pushFront(int val) { + dq.addFirst(val); + } + + public void pushMiddle(int val) { + int size = dq.size(); + int middleIndex = size / 2; + if (middleIndex == size) { + dq.add(val); + } else { + Deque temp = new LinkedList<>(); + for (int i = 0; i < middleIndex; i++) { + temp.add(dq.removeFirst()); + } + dq.addFirst(val); + while (!temp.isEmpty()) { + dq.addFirst(temp.removeLast()); + } + } + } + + public void pushBack(int val) { + dq.addLast(val); + } + + public int popFront() { + if (dq.isEmpty()) return -1; + return dq.removeFirst(); + } + + public int popMiddle() { + if (dq.isEmpty()) return -1; + int size = dq.size(); + int middleIndex = (size - 1) / 2; + Deque temp = new LinkedList<>(); + for (int i = 0; i < middleIndex; i++) { + temp.add(dq.removeFirst()); + } + int middle = dq.removeFirst(); + while (!temp.isEmpty()) { + dq.addFirst(temp.removeLast()); + } + return middle; + } + + public int popBack() { + if (dq.isEmpty()) return -1; + return dq.removeLast(); + } +} + + ``` + + + + + + ```cpp + class FrontMiddleBackQueue { +public: + deque dq; + FrontMiddleBackQueue() { + + } + + void pushFront(int val) { + dq.push_front(val); + } + + void pushMiddle(int val) { + int size = dq.size(); + dq.insert(dq.begin()+size/2,val); + } + + void pushBack(int val) { + dq.push_back(val); + } + + int popFront() { + if (dq.empty()) return -1; + int x = dq.front(); + dq.pop_front(); + return x; + } + + int popMiddle() { + if (dq.empty()) return -1; + + int size = dq.size(); + int middleIndex = (size - 1) / 2; + int element = dq[middleIndex]; + + dq.erase(dq.begin() + middleIndex); + + return element; + } + + + int popBack() { + if (dq.empty()) return -1; + int x = dq.back(); + dq.pop_back(); + return x; + } +}; + +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Design Front Middle Back Queue](https://leetcode.com/problems/design-front-middle-back-queue/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/design-front-middle-back-queue/solution) + diff --git a/solutions/lc-solutions/1600-1699/1678-goal-parser-interpretation.md b/solutions/lc-solutions/1600-1699/1678-goal-parser-interpretation.md new file mode 100644 index 0000000..eab6a19 --- /dev/null +++ b/solutions/lc-solutions/1600-1699/1678-goal-parser-interpretation.md @@ -0,0 +1,120 @@ +--- +id: goal-parser-interpretation +title: Goal Parser Interpretation +sidebar_label: 1678-Goal Parser Interpretation +tags: + - String + +description: "This is a solution to the goal parser interpretation in leetcode" +--- + +## Problem Description + +You own a Goal Parser that can interpret a string command. The command consists of an alphabet of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", "()" as the string "o", and "(al)" as the string "al". The interpreted strings are then concatenated in the original order. + +Given the string command, return the Goal Parser's interpretation of command. + + + + +### Examples + +**Example 1:** + +``` +Input: command = "G()(al)" +Output: "Goal" +Explanation: The Goal Parser interprets the command as follows: +G -> G +() -> o +(al) -> al +The final concatenated result is "Goal". +``` +**Example 2:** +``` +Input: command = "G()()()()(al)" +Output: "Gooooal" + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(1)$ + +*** Space Complexity:** $O(1)$ + +### Constraints + +- `1 <= command.length <= 100` +- `command` consists of `"G"`, `"()"`, and/or `"(al)"` in some order. + + + +### Solution +## Approach +To interpret the given command string, the approach involves replacing specific substrings within the command to their corresponding interpreted values. The command may contain the substrings "()" and "(al)", which need to be replaced with "o" and "al", respectively. The process can be efficiently achieved using the replace`method available in most programming languages, which allows us to replace all occurrences of a substring with another substring. + +Here's the step-by-step approach: + +1. Identify Substrings: Determine the specific substrings in the command that need to be replaced. In this case, "()" should be replaced with "o", and "(al)" should be replaced with "al". +2. Replace Substrings: Use the replace method to perform the replacements. First, replace all occurrences of "()" with "o". Then, replace all occurrences of "(al)" with "al". +3. Return the Result: After performing the replacements, the resulting string is the interpreted command. + +This approach ensures that the command string is correctly transformed in a single pass through each replace operation, making it efficient and straightforward to implement. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + std::string interpret(std::string command) { + size_t pos; + while ((pos = command.find("()")) != std::string::npos) { + command.replace(pos, 2, "o"); + } + while ((pos = command.find("(al)")) != std::string::npos) { + command.replace(pos, 4, "al"); + } + return command; + } +}; + + +``` + + + + +```java +class Solution { + public String interpret(String command) { + command=command.replace("()","o").replace("(al)","al"); + return command; + + } +} + +``` + + + + +```python +class Solution: + def interpret(self, command: str) -> str: + command = command.replace("()", "o").replace("(al)", "al") + return command + + +``` + + + +## References + +- **LeetCode Problem**: [Goal Parser Interpretation](https://leetcode.com/problems/goal-parser-interpretation/) + +- **Solution Link**: [Goal Parser Interpretation](https://leetcode.com/problems/goal-parser-interpretation/post-solution/?submissionId=1224590230) diff --git a/solutions/lc-solutions/1600-1699/1679-max-number-of-k-sum-pairs.md b/solutions/lc-solutions/1600-1699/1679-max-number-of-k-sum-pairs.md new file mode 100644 index 0000000..3937c1f --- /dev/null +++ b/solutions/lc-solutions/1600-1699/1679-max-number-of-k-sum-pairs.md @@ -0,0 +1,157 @@ +--- +id: max-number-of-k-sum-pairs +title: Max Number of K-Sum Pairs (Leetcode) +sidebar_label: 0082-MaxNumberofK-SumPairs +description: You are given an integer array nums and an integer k.In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.Return the maximum number of operations you can perform on the array. +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Max Number of K-Sum Pairs](https://leetcode.com/problems/max-number-of-k-sum-pairs/description/) | [Max Number of K-Sum Pairs Solution on LeetCode](https://leetcode.com/problems/max-number-of-k-sum-pairs/solutions) | [Aaradhya Singh ](https://leetcode.com/u/keira_09/) | + + +## Problem Description + +You are given an integer array nums and an integer $k$. + +In one operation, you can pick two numbers from the array whose sum equals $k$ and remove them from the array. + +Return the maximum number of operations you can perform on the array. + +### Examples + +#### Example 1 + +- **Input:** $nums = [1,2,3,4], k = 5$ +- **Output:** $2$ +- **Explanation:** Starting with nums = $[1,2,3,4]$: +- Remove numbers $1$ and $4$, then nums = $[2,3]$ +- Remove numbers $2$ and $3$, then nums = $[]$ +There are no more pairs that sum up to $5$, hence a total of $2$ operations. + + +#### Example 2 + +- **Input:** $nums = [3,1,3,4,3], k = 6$ +- **Output:** $1$ +- **Explanation:** Starting with nums = $[3,1,3,4,3]$: +- Remove the first two $3$'s, then nums = $[1,4,3]$ +There are no more pairs that sum up to $6$, hence a total of $1$ operation. + +### Constraints + +- $1 <= nums.length <= 105$ +- $1 <= nums[i] <= 109$ +- $1 <= k <= 109$ + + +### Intuition + +The code finds the maximum number of pairs in nums that sum to $k$ by first sorting the array and then using the two-pointer technique. Pointers start and end check pairs: if their sum equals $k$, the count is incremented and both pointers move inward. If the sum is greater than $k$, end moves left; if less, start moves right. This approach efficiently identifies pairs with a sum of $k$ in $O(nlog⁑n)$ time due to sorting and $O(n)$ time for the two-pointer traversal. + +### Approach + +1. **Sorting the Array:** + + - The first step is to sort the given array nums using std::sort. This step ensures that elements are in ascending order, which is crucial for the two-pointer technique. + +2. **Initializing Pointers and Count:** + + - Initialize three variables: count to keep track of the number of valid pairs, start pointing to the beginning of the sorted array, and end pointing to the end of the array. + +3. **Two-Pointer Technique:** + + - Use the two-pointer technique within a while loop until start is less than end. + - Check if the sum of elements at nums[start] and nums[end] equals the target value k. + - If it does, increment count and move both pointers inward (start++ and end--). + - If the sum is greater than k, decrement end to reduce the sum. + - If the sum is less than k, increment start to increase the sum. + +4. **Return Count:** + + - After the while loop, return the final value of count, which represents the maximum number of pairs in nums that sum to k. + +### Solution Code + +#### Python + +```py +class Solution: + def maxOperations(self, nums: List[int], k: int) -> int: + nums.sort() # Sort the array in ascending order + count = 0 + start, end = 0, len(nums) - 1 # Initialize two pointers + + while start < end: + if nums[start] + nums[end] == k: + count += 1 + start += 1 + end -= 1 + elif nums[start] + nums[end] > k: + end -= 1 + else: + start += 1 + + return count +``` + +#### Java + +```java +import java.util.Arrays; + +class Solution { + public int maxOperations(int[] nums, int k) { + Arrays.sort(nums); // Sort the array in ascending order + int count = 0; + int start = 0, end = nums.length - 1; // Initialize two pointers + + while (start < end) { + if (nums[start] + nums[end] == k) { + count++; + start++; + end--; + } else if (nums[start] + nums[end] > k) { + end--; + } else { + start++; + } + } + + return count; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + int maxOperations(vector& nums, int k) { + std::sort(nums.begin() , nums.end()); + int count = 0; + int start = 0; + int end = nums.size() - 1; + + while (start < end){ + if (nums[start] + nums[end] == k){ + count ++; + end--; + start++; + } + else if (nums[start] + nums[end] > k){ + end--; + } + else{start++;} + } + return count; + } +}; +``` + +### Conclusion + +The code effectively calculates the maximum number of pairs in an array nums that sum up to the given value $k$ using the two-pointer technique. It first sorts the array in ascending order, which enables efficient pair finding. The two pointers start and end traverse the sorted array, checking pairs. If the sum of elements at these pointers equals $k$, a valid pair is found, and both pointers move inward. If the sum is greater than $k$, end moves left to reduce the sum; if less, start moves right to increase the sum. This approach optimally identifies pairs with a sum of $k$, with a time complexity of $O(n log n)$ due to sorting and $O(n)$ for the two-pointer traversal, making it efficient for large arrays. diff --git a/solutions/lc-solutions/1600-1699/1688-Count-Of-Matches-in-Tournament.md b/solutions/lc-solutions/1600-1699/1688-Count-Of-Matches-in-Tournament.md new file mode 100644 index 0000000..b2ce105 --- /dev/null +++ b/solutions/lc-solutions/1600-1699/1688-Count-Of-Matches-in-Tournament.md @@ -0,0 +1,126 @@ +--- +id: count-of-matches-in-tournament +title: Count of Matches in Tournament +sidebar_label: 1688-Count-of-Matches-in-Tournament +tags: +- Simulation +- Tournament +description: "Given the number of teams in a tournament, calculate the number of matches played until a winner is decided." +--- + +## Problem + +You are given an integer `n`, the number of teams in a tournament. In each match, a team wins and the other team is eliminated. The tournament continues until there is one team left. Your task is to return the number of matches played in the tournament until a winner is decided. + +### Examples + +**Example 1:** + +**Input:** `n = 7` +**Output:** `6` +**Explanation:** +- 1st round: 7 teams are divided into 3 matches with 1 team automatically advancing (3 + 1 = 4). +- 2nd round: 4 teams are divided into 2 matches (2 + 1 = 3). +- 3rd round: 3 teams are divided into 1 match with 1 team automatically advancing (1 + 1 = 2). +- 4th round: 2 teams are divided into 1 match, resulting in a single winner (1 + 0 = 1). +- Total matches: 3 + 2 + 1 = 6. + +**Example 2:** + +**Input:** `n = 14` +**Output:** `13` +**Explanation:** +- 1st round: 14 teams are divided into 7 matches (7 + 0 = 7). +- 2nd round: 7 teams are divided into 3 matches with 1 team automatically advancing (3 + 1 = 4). +- 3rd round: 4 teams are divided into 2 matches (2 + 1 = 3). +- 4th round: 3 teams are divided into 1 match with 1 team automatically advancing (1 + 1 = 2). +- 5th round: 2 teams are divided into 1 match, resulting in a single winner (1 + 0 = 1). +- Total matches: 7 + 3 + 2 + 1 = 13. + +### Constraints + +- `1 <= n <= 200` + +--- + +## Approach + +To solve this problem, we can use a straightforward simulation approach by counting the number of matches played in each round until one team remains. The key observation is that in each match, one team is eliminated, so the number of matches in each round is equal to the number of teams divided by 2. + +### Steps: + +1. Initialize a counter for the number of matches to 0. +2. While the number of teams is greater than 1: + 1. If the number of teams is even, half of them play matches, and the other half is eliminated. + 2. If the number of teams is odd, one team automatically advances, and the rest play matches. + 3. Add the number of matches in this round to the counter. +3. Return the counter as the total number of matches played. + +### Solution + +#### Java + +```java +class Solution { + public int numberOfMatches(int n) { + int matches = 0; + while (n > 1) { + if (n % 2 == 0) { + matches += n / 2; + n = n / 2; + } else { + matches += (n - 1) / 2; + n = (n - 1) / 2 + 1; + } + } + return matches; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + int numberOfMatches(int n) { + int matches = 0; + while (n > 1) { + if (n % 2 == 0) { + matches += n / 2; + n = n / 2; + } else { + matches += (n - 1) / 2; + n = (n - 1) / 2 + 1; + } + } + return matches; + } +}; +``` + +#### Python + +```python +class Solution: + def numberOfMatches(self, n: int) -> int: + matches = 0 + while n > 1: + if n % 2 == 0: + matches += n // 2 + n = n // 2 + else: + matches += (n - 1) // 2 + n = (n - 1) // 2 + 1 + return matches +``` + +### Complexity Analysis +**Time Complexity:** O(log n) +>Reason: The number of teams is halved in each round, leading to a logarithmic time complexity. + +**Space Complexity:** O(1) +>Reason: The space complexity is constant as we only use a few variables. + +### References +**LeetCode Problem:** Count of Matches in Tournament diff --git a/solutions/lc-solutions/1600-1699/_category_.json b/solutions/lc-solutions/1600-1699/_category_.json new file mode 100644 index 0000000..3c480dd --- /dev/null +++ b/solutions/lc-solutions/1600-1699/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "1600-1699", + "position": 18, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (1600 - 1699)" + } +} diff --git a/solutions/lc-solutions/1700-1799/1701-Average-Waiting-Time.md b/solutions/lc-solutions/1700-1799/1701-Average-Waiting-Time.md new file mode 100644 index 0000000..daafe0c --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1701-Average-Waiting-Time.md @@ -0,0 +1,113 @@ +--- +id: average-waiting-time +title: Average Waiting Time +sidebar_label: 1701. Average Waiting Time +tags: [Array, Simulation, C++, Python, Java] +description: "This is a solution to the Average Waiting Time problem on LeetCode." +--- + +## Problem Description + +There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]`: + +- `arrival[i]` is the arrival time of the ith customer. The arrival times are sorted in non-decreasing order. +- `timei` is the time needed to prepare the order of the ith customer. + +When a customer arrives, they give the chef their order, and the chef starts preparing it once they are idle. The customer waits until the chef finishes preparing their order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input. + +Return the average waiting time of all customers. Solutions within `10^-5` from the actual answer are considered accepted. + +### Examples + +**Example 1:** + +``` +Input: customers = [[1,2],[2,5],[4,3]] +Output: 5.00000 +Explanation: +1) The first customer arrives at time 1, the chef takes their order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. +2) The second customer arrives at time 2, the chef takes their order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. +3) The third customer arrives at time 4, the chef takes their order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. +So the average waiting time = (2 + 6 + 7) / 3 = 5. +``` + +**Example 2:** + +``` +Input: customers = [[5,2],[5,4],[10,3],[20,1]] +Output: 3.25000 +Explanation: +1) The first customer arrives at time 5, the chef takes their order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. +2) The second customer arrives at time 5, the chef takes their order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. +3) The third customer arrives at time 10, the chef takes their order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. +4) The fourth customer arrives at time 20, the chef takes their order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. +So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. +``` + +### Constraints + +- `1 <= customers.length <= 10^5` +- `1 <= arrival[i], time[i] <= 10^4` +- `arrival[i] <= arrival[i + 1]` + +## Solution for 1701. Average Waiting Time + +### Approach + +`cur` means the current time. For each customer arriving at `t` with their order needing `d`, +we start preparing their order at `max(cur, t)`, we finish their order at `max(cur, t) + d`, +and they wait for `max(cur, t) + d - t`. + +We need to sum up the waiting time and also update the `cur` time after serving each customer. + +### Code in Different Languages + + + + + ```python + def averageWaitingTime(self, A): + wait = cur = 0. + for t, d in A: + cur = max(cur, t) + d + wait += cur - t + return wait / len(A) + ``` + + + + ```java + public double averageWaitingTime(int[][] A) { + double wait = 0, cur = 0; + for (int[] a: A) { + cur = Math.max(cur, 1.0 * a[0]) + a[1]; + wait += cur - a[0]; + } + return 1.0 * wait / A.length; + } + ``` + + + + ```cpp + double averageWaitingTime(vector>& A) { + double wait = 0, cur = 0; + for (auto& a: A) { + cur = max(cur, 1.0 * a[0]) + a[1]; + wait += cur - a[0]; + } + return 1.0 * wait / A.size(); + } + ``` + + + +### Complexity Analysis + +- Time Complexity: $ O(N) $ +- Space Complexity: $ O(1)$ + +## References + +- **LeetCode Problem**: [Average Waiting Time](https://leetcode.com/problems/average-waiting-time/description/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/average-waiting-time/solutions/) diff --git a/solutions/lc-solutions/1700-1799/1702-Maximum-Binary-String-After-Change.md b/solutions/lc-solutions/1700-1799/1702-Maximum-Binary-String-After-Change.md new file mode 100644 index 0000000..4f07ff4 --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1702-Maximum-Binary-String-After-Change.md @@ -0,0 +1,129 @@ +--- +id: maximum-binary-string-after-change +title: Maximum Binary String After Change +sidebar_label: 1702. Maximum Binary String After Change +tags: +- String +- Greedy +- C++ +- Python +- Java +description: "This is a solution to the Maximum Binary String After Change problem on LeetCode." +--- + +## Problem Description +You are given a binary string `binary` consisting of only `0's` or `1's`. You can apply each of the following operations any number of times: + +1. If the number contains the substring `"00"`, you can replace it with `"10"`. For example, `"00010" -> "10010"`. +2. If the number contains the substring `"10"`, you can replace it with `"01"`. For example, `"00010" -> "00001"`. + +Return the maximum binary string you can obtain after any number of operations. Binary string `x` is greater than binary string `y` if `x`'s decimal representation is greater than `y`'s decimal representation. + +### Examples + +**Example 1:** +``` +Input: binary = "000110" +Output: "111011" +Explanation: A valid transformation sequence can be: +"000110" -> "000101" +"000101" -> "100101" +"100101" -> "110101" +"110101" -> "110011" +"110011" -> "111011" +``` + +**Example 2:** +``` +Input: binary = "01" +Output: "01" +Explanation: "01" cannot be transformed any further. +``` + +### Constraints +- `1 <= binary.length <= 10^5` +- `binary` consists of '0' and '1'. + +## Solution for 1702. Maximum Binary String After Change + +### Approach +- Divide the string into two parts: leading ones and the rest. +- For the rest part, we can always use `"10" -> "01"` to put all ones to the end of the string and hence move all zeros ahead of these ones. +- For all the zeros, apply `"00" -> "10"` from left to right, till only one `"0"` remains; it is the maximum. + +## Code in Different Languages + + + + ```python + class Solution: + def maximumBinaryString(self, binary: str) -> str: + leading_ones = binary.find('0') + if leading_ones < 0: + return binary + n = len(binary) + zeros = binary.count('0') + rest_ones = n - leading_ones - zeros + return '1' * (leading_ones + zeros - 1) + '0' + '1' * rest_ones + ``` + + + + + ```java + public class Solution { + public String maximumBinaryString(String binary) { + int leadingOnes = binary.indexOf("0"); + if (leadingOnes < 0) { + return binary; + } + int zeros = 0, restOnes = 0; + for (int i = leadingOnes; i < binary.length(); ++i) { + char c = binary.charAt(i); + if (c == '0') { + ++zeros; + } else { + ++restOnes; + } + } + return "1".repeat(leadingOnes + zeros - 1) + "0" + "1".repeat(restOnes); + } + } + ``` + + + + + ```cpp + class Solution { + public: + string maximumBinaryString(string s) { + // support variables + int zeros = 0, i = 0, len = s.size(); + // moving the pointer after the first leading 1s + while (s[i] == '1') i++; + // counting the 0s + for (int j = i; j < len; j++) zeros += s[j] == '0'; + // edge case: not enough 0s to make any move convenient + if (zeros < 2) return s; + // turning all the zeros but one into 1s + while (--zeros) s[i++] = '1'; + s[i++] = '0'; + // setting all the remaining original 1s to the end + while (i < len) s[i++] = '1'; + return s; + } + }; + ``` + + + +#### Complexity Analysis + +- Time Complexity: $O(N)$ +- Space Complexity: $O(N)$ + +## References + +- **LeetCode Problem**: [Maximum Binary String After Change](https://leetcode.com/problems/maximum-binary-string-after-change/description/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/maximum-binary-string-after-change/solutions/) diff --git a/solutions/lc-solutions/1700-1799/1703-minimum-adjacent-swaps-for-k-consecutive-ones.md b/solutions/lc-solutions/1700-1799/1703-minimum-adjacent-swaps-for-k-consecutive-ones.md new file mode 100644 index 0000000..8af9c96 --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1703-minimum-adjacent-swaps-for-k-consecutive-ones.md @@ -0,0 +1,135 @@ +--- +id: minimum-adjacent-swaps-for-k-consecutive-ones +title: Minimum Adjacent Swaps for K Consecutive Ones +sidebar_label: 1703. Minimum Adjacent Swaps for K Consecutive Ones +tags: +- Array +- Greedy +- Sliding Window +- PrefixSum +- Python +- Java + +description: "This is a solution to the Minimum Adjacent Swaps for K Consecutive Ones problem on LeetCode." +--- + +## Problem Description +You are given an integer array `nums` and an integer `k`. `nums` comprises only `0`'s and `1`'s. In one move, you can choose two adjacent indices and swap their values. + +Return the minimum number of moves required so that `nums` has k consecutive `1`'s. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,0,0,1,0,1], k = 2 +Output: 1 +Explanation: In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's. +``` + +**Example 2:** + +``` +Input: nums = [1,0,0,0,0,0,1,1], k = 3 +Output: 5 +Explanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1]. +``` + +### Constraints +- `1 <= nums.length <= 10^5` +- `1 <= k <= sum(nums)` + +## Solution for 1703. Minimum Adjacent Swaps for K Consecutive Ones + +### Approach +Take `[1,0,0,1,1,0,0,1,0,0,1], k=4` for example. + +Idea: + +1. Find the indices of all `1`s. + - `[0,3,4,7,10]` +2. Calculate the total number of swaps with a sliding window of length `k`. + - Window 1: `[0,3,4,7]` and window 2: `[3,4,7,10]` (e.g., `k=4`). +3. Notice that aggregating all `1`s to the median `1` will lead to the minimum distance. + - 1st window: 3 and 4 are both medians; choose the larger one. + - 2nd window: 4 and 7 are both medians; choose the larger one. +4. For each valid index, aggregate all `k/2` left `1`s and `(k-1)/2` right `1`s. + - Aggregate `1` at `0, 3, and 7` to `1` at `4` for the first window (e.g., `[0,3,4,7]` to `[2,3,4,5]`). + - Aggregate `1` at `3, 4, and 10` to `1` at `7` for the second window (e.g., `[3,4,7,10]` to `[5,6,7,8]`). +5. Use the prefix sum to speed up the calculation for the total number of swaps. + - `[0,0,3,7,14,24]` + +## Code in Different Languages + + + + + ```python + def minMoves(self, A, k): + A = [i for i, a in enumerate(A) if a] + n = len(A) + B = [0] * (n + 1) + res = float('inf') + for i in range(n): + B[i + 1] = B[i] + A[i] + for i in range(len(A) - k + 1): + res = min(res, B[i + k] - B[k // 2 + i] - B[(k + 1) // 2 + i] + B[i]) + res -= (k // 2) * ((k + 1) // 2) + return res + ``` + + + + + + ```java + public int minMoves(int[] nums, int k) { + ArrayList A = new ArrayList(), B = new ArrayList(); + for (int i = 0; i < nums.length; ++i) + if (nums[i] == 1) + A.add((long)i); + long res = Long.MAX_VALUE; + B.add(0L); + for (int i = 0; i < A.size(); ++i) + B.add(B.get(i) + A.get(i)); + for (int i = 0; i < A.size() - k + 1; ++i) + res = Math.min(res, B.get(i + k) - B.get(k / 2 + i) - B.get((k + 1) / 2 + i) + B.get(i)); + res -= (k / 2) * ((k + 1) / 2); + return (int)res; + } + ``` + + + + + + ```cpp + int minMoves(vector& nums, int k) { + vector A, B(1); + for (int i = 0; i < nums.size(); ++i) + if (nums[i]) + A.push_back(i); + long n = A.size(), res = 2e9; + for (int i = 0; i < n; ++i) + B.push_back(B[i] + A[i]); + for (int i = 0; i < n - k + 1; ++i) + res = min(res, B[i + k] - B[k / 2 + i] - B[(k + 1) / 2 + i] + B[i]); + res -= (k / 2) * ((k + 1) / 2); + return res; + } + ``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(N)$ +- Space Complexity: $O(N)$ + +## References + +- **LeetCode Problem:** [Minimum Adjacent Swaps for K Consecutive Ones](https://leetcode.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones/description/) +- **Solution Link:** [LeetCode Solution](https://leetcode.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones/solutions/) +Feel free to adjust any parts of this if you need further customization! diff --git a/solutions/lc-solutions/1700-1799/1704-Determine-if-String-Halves-Are-Alike.md b/solutions/lc-solutions/1700-1799/1704-Determine-if-String-Halves-Are-Alike.md new file mode 100644 index 0000000..62adb8e --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1704-Determine-if-String-Halves-Are-Alike.md @@ -0,0 +1,156 @@ +--- +id: determine-if-string-halves-are-alike +title: Determine if String Halves Are Alike +sidebar_label: 1704. Determine if String Halves Are Alike +tags: +- String +- Counting +- Python +- Java +description: "This is a solution to the Determine if String Halves Are Alike problem on LeetCode." +--- + +## Problem Description + +You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. + +Two strings are alike if they have the same number of vowels `('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')`. Notice that `s` contains uppercase and lowercase letters. + +Return true if a and b are alike. Otherwise, return false. + +### Examples + +**Example 1:** + +``` +Input: s = "book" +Output: true +Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike. +``` + +**Example 2:** + +``` +Input: s = "textbook" +Output: false +Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. +Notice that the vowel o is counted twice. +``` + +### Constraints + +- `2 <= s.length <= 1000` +- `s.length is even` + +## Solution for 1704. Determine if String Halves Are Alike + +### Approach + +1. Define a helper function `count_vowels` to count the number of vowels in a given string. +2. Compute the length of the input string and find the midpoint. +3. Split the string into two halves: the first half `(first_half)` and the second half `(second_half)`. +4. Use the `count_vowels` function to count the vowels in both halves. +5. Compare the counts of vowels in both halves. If they are equal, return `True`; otherwise, return `False`. + +## Code in Different Languages + + + + + + ```python + class Solution: + def halvesAreAlike(self, s: str) -> bool: + def count_vowels(string): + vowels = set('aeiouAEIOU') + return sum(1 for char in string if char in vowels) + + length = len(s) + mid_point = length // 2 + + first_half = s[:mid_point] + second_half = s[mid_point:] + + return count_vowels(first_half) == count_vowels(second_half) + ``` + + + + + + ```java + import java.util.HashSet; + import java.util.Set; + + public class Solution { + public boolean halvesAreAlike(String s) { + Set vowels = new HashSet<>(); + vowels.add('a'); vowels.add('e'); vowels.add('i'); vowels.add('o'); vowels.add('u'); + vowels.add('A'); vowels.add('E'); vowels.add('I'); vowels.add('O'); vowels.add('U'); + + int length = s.length(); + int midPoint = length / 2; + + String firstHalf = s.substring(0, midPoint); + String secondHalf = s.substring(midPoint); + + return countVowels(firstHalf, vowels) == countVowels(secondHalf, vowels); + } + + private int countVowels(String str, Set vowels) { + int count = 0; + for (char c : str.toCharArray()) { + if (vowels.contains(c)) { + count++; + } + } + return count; + } + } + ``` + + + + + + ```cpp + #include + using namespace std; + + class Solution { + public: + bool halvesAreAlike(string s) { + auto countVowels = [](const string& str) { + unordered_set vowels{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; + int count = 0; + for (char c : str) { + if (vowels.count(c) > 0) { + count++; + } + } + return count; + }; + + int length = s.length(); + int midPoint = length / 2; + + string firstHalf = s.substr(0, midPoint); + string secondHalf = s.substr(midPoint); + + return countVowels(firstHalf) == countVowels(secondHalf); + } + }; + ``` + + + + +## Complexity Analysis + +- **Time Complexity:** $O(N)$ +- **Space Complexity:** $O(1)$ + +## References + +- **LeetCode Problem:** [Determine if String Halves Are Alike](https://leetcode.com/problems/determine-if-string-halves-are-alike/description/) +- **Solution Link:** [LeetCode Solution](https://leetcode.com/problems/determine-if-string-halves-are-alike/solutions/) diff --git a/solutions/lc-solutions/1700-1799/1705-Maximum-Number-of-Eaten-Apples.md b/solutions/lc-solutions/1700-1799/1705-Maximum-Number-of-Eaten-Apples.md new file mode 100644 index 0000000..9a67bf1 --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1705-Maximum-Number-of-Eaten-Apples.md @@ -0,0 +1,185 @@ +--- +id: maximum-number-of-eaten-apples +title: Maximum Number of Eaten Apples +sidebar_label: 1705. Maximum Number of Eaten Apples +tags: [Array, Simulation, C++, Python, Java] +description: "This is a solution to the Maximum Number of Eaten Apples problem on LeetCode." +--- + +## Problem Description + +There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`. + +You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days. + +Given two integer arrays days and apples of length `n`, return the maximum number of apples you can eat. + +### Examples + +**Example 1:** + +``` +Input: apples = [1,2,3,5,2], days = [3,2,1,4,2] +Output: 7 +Explanation: You can eat 7 apples: +- On the first day, you eat an apple that grew on the first day. +- On the second day, you eat an apple that grew on the second day. +- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. +- On the fourth to the seventh days, you eat apples that grew on the fourth day. + +``` + +**Example 2:** + +``` +Input: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2] +Output: 5 +Explanation: You can eat 5 apples: +- On the first to the third day you eat apples that grew on the first day. +- Do nothing on the fouth and fifth days. +- On the sixth and seventh days you eat apples that grew on the sixth day. + +``` + +### Constraints + +- `n == apples.length == days.length` +- `1 <= n <= 2 * 10^4` +- `0 <= apples[i], days[i] <= 2 * 10^4` + +## Solution for 1705. Maximum Number of Eaten Apples + + +### Approach + +The first thing to ask your mind is how to eat more & more apples? What is the best strategy for doing it? +Your mind will tell if we eat apples that get rotten fast and eat them as early as possible. It will be the best strategy for sure. + +Now see the constraints: We can't implement $O(N^2)$ as this will give time limit exceeded. +We need some data structure to maintain the above possibility and do the work in atmax $O(NLogN)$. +We have min-heap for it. + +Now keep building min heap ( We can use priority queue in C++ for the same purpose) and keep eating the maximum no of apples + +### Code in Different Languages + + + + + ```python + from heapq import heappush, heappop +class Solution: + def eatenApples(self, A: List[int], D: List[int]) -> int: + ans, i, N = 0, 0, len(A) + h = [] + while i < N or h: + # only push to heap when you have a valid i, and the apple has atleast one day to stay fresh. + if i 0: + heappush(h, [i+D[i], A[i]]) + # remove the rotten apples batches and the batches with no apples left (which might have got consumed). + while h and (h[0][0] <= i or h[0][1] <= 0): + heappop(h) + # only if there is batch in heap after removing all the rotten ones, you can eat. else wait for the subsequent days for new apple batch by incrementing i. + if h: + h[0][1]-=1 + ans+=1 + i+=1 + return ans + ``` + + + + ```java + class Solution { + public int eatenApples(int[] apples, int[] days) { + PriorityQueue appleStorage = new PriorityQueue<>((a, b) -> a[0] - b[0]); + int appleCount = 0; + + for(int i = 0; i < apples.length || !appleStorage.isEmpty(); i++) { + if(i < apples.length) { + appleStorage.add(new int[]{ i + days[i], apples[i] }); + } + + while(!appleStorage.isEmpty() && (appleStorage.peek()[0] <= i || appleStorage.peek()[1] <= 0)) { + appleStorage.poll(); + } + + if(!appleStorage.isEmpty()) { + appleCount++; + appleStorage.peek()[1]--; + } + } + + return appleCount; + } +} + ``` + + + + ```cpp + typedef pair pii; +class Solution { +public: + int eatenApples(vector& apples, vector& days) { + //Make a priority queue --> pq (pair - {rotten day , no of apples} ) and sort according to increasing rotten day + priority_queue, greater >pq; + int n = apples.size(); + int eatenApples = 0; + //Process apples which are not processed or until we still have good apples in the queue + for(int i = 0; i= pq.top().first) + pq.pop(); + + //If we have good apples then we have to eat it to keep the dr away + if(!pq.empty()) + { + auto p = pq.top(); + pq.pop(); + + // Not reached the nth day yet (Note : we are trying to eat atmost 1 apple a day here) + if(i < n ) + { + eatenApples ++ ; //eat the good apple + p.second--; //one apple consumed + // If still good apples remains push it in our good apple queue + if(p.second > 0) + pq.push(p); + } + else + { + // Note - we are eating in the greedy fashion so as to consume max no of apples, i.e first eating those + // apples which get rotten earlier + // Add minimum of days left or no of good apples left for the current pair + int add = min(p.first - i, p.second); + eatenApples += add; + // set the day upto which we have already eaten so as to check for the comming days + i += add - 1; + + } + } + + } + + return eatenApples; + } +}; + ``` + + + +### Complexity Analysis + +- Time Complexity: $ O(NlogN) $ +- Space Complexity: $ O(N)$ + +## References + +- **LeetCode Problem**: [Maximum Number of Eaten Apples](https://leetcode.com/problems/maximum-number-of-eaten-apples/description/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/maximum-number-of-eaten-apples/solutions/) diff --git a/solutions/lc-solutions/1700-1799/1706-Where-Will-the-Ball-Fall.md b/solutions/lc-solutions/1700-1799/1706-Where-Will-the-Ball-Fall.md new file mode 100644 index 0000000..acc9c3a --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1706-Where-Will-the-Ball-Fall.md @@ -0,0 +1,142 @@ +--- +id: where-will-the-ball-fall +title: Where Will the Ball Fall +sidebar_label: 1706. Where Will the Ball Fall +tags: [Array, Simulation, C++, Python, Java] +description: "This is a solution to the Where Will the Ball Fall problem on LeetCode." +--- + +## Problem Description + +You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides. + +Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. + +- A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. +- A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. +- We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a `"V"` shaped pattern between two boards or if a board redirects the ball into either wall of the box. + +Return an array `answer` of size n where `answer[i]` is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or `-1` if the ball gets stuck in the box. + +### Examples + +**Example 1:** + +``` +Input: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]] +Output: [1,-1,-1,-1,-1] +Explanation: This example is shown in the photo. +Ball b0 is dropped at column 0 and falls out of the box at column 1. +Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. +Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. +Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. +Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. + +``` + +**Example 2:** + +``` +Input: grid = [[-1]] +Output: [-1] +Explanation: The ball gets stuck against the left wall. + +``` +**Example 3:** +``` +Input: grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]] +Output: [0,1,2,3,4,-1] + +``` + +### Constraints + +- `m == grid.length` +- `n == grid[i].length` +- `1 <= m, n <= 100` + +## Solution for 1706. Where Will the Ball Fall + + +### Approach + +We drop the ball at `grid[0][i]` +and track ball position i1, which initlized as i. + +An observation is that, +if the ball wants to move from `i1` to `i2`, +we must have the board direction `grid[j][i1] == grid[j][i2]` + +### Code in Different Languages + + + + + ```python + def findBall(self, grid): + m, n = len(grid), len(grid[0]) + + def test(i): + for j in xrange(m): + i2 = i + grid[j][i] + if i2 < 0 or i2 >= n or grid[j][i2] != grid[j][i]: + return -1 + i = i2 + return i + return map(test, range(n)) + ``` + + + + ```java + public int[] findBall(int[][] grid) { + int m = grid.length, n = grid[0].length, res[] = new int[n]; + for (int i = 0; i < n; ++i) { + int i1 = i, i2; + for (int j = 0; j < m; ++j) { + i2 = i1 + grid[j][i1]; + if (i2 < 0 || i2 >= n || grid[j][i2] != grid[j][i1]) { + i1 = -1; + break; + } + i1 = i2; + } + res[i] = i1; + } + return res; + } + ``` + + + + ```cpp + vector findBall(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector res; + for (int i = 0; i < n; ++i) { + int i1 = i, i2; + for (int j = 0; j < m; ++j) { + i2 = i1 + grid[j][i1]; + if (i2 < 0 || i2 >= n || grid[j][i2] != grid[j][i1]) { + i1 = -1; + break; + } + i1 = i2; + } + res.push_back(i1); + } + return res; + } + ``` + + + +### Complexity Analysis + +- Time Complexity: $ O(N*M) $ +- Space Complexity: $ O(N)$ + +## References + +- **LeetCode Problem**: [Where Will the Ball Fall](https://leetcode.com/problems/where-will-the-ball-fall/description/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/where-will-the-ball-fall/solutions/) diff --git a/solutions/lc-solutions/1700-1799/1710-Maximum-Units-on-a-Truck.md b/solutions/lc-solutions/1700-1799/1710-Maximum-Units-on-a-Truck.md new file mode 100644 index 0000000..760840d --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1710-Maximum-Units-on-a-Truck.md @@ -0,0 +1,119 @@ +--- +id: maximum-units-on-a-truck +title: Maximum Units on a Truck +sidebar_label: 1710. Maximum Units on a Truck +tags: [Array, Simulation, C++, Python, Java] +description: "This is a solution to the Maximum Units on a Truck problem on LeetCode." +--- + +## Problem Description + +You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: + +- `numberOfBoxesi` is the number of boxes of type `i`. +- `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. +You are also given an integer `truckSize`, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. + +Return the maximum total number of units that can be put on the truck. + +### Examples + +**Example 1:** + +``` +Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4 +Output: 8 +Explanation: There are: +- 1 box of the first type that contains 3 units. +- 2 boxes of the second type that contain 2 units each. +- 3 boxes of the third type that contain 1 unit each. +You can take all the boxes of the first and second types, and one box of the third type. +The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8. + +``` + +**Example 2:** + +``` +Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10 +Output: 91 + +``` + +### Constraints + +- `1 <= boxTypes.length <= 1000` +- `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000` +- `1 <= truckSize <= 10^6` + +## Solution for 1710. Maximum Units on a Truck + + +### Approach + +The given constraints for numberOfUnitsPerBox are small enough that we can use an approach similar to counting sort to reduce the time complexity to $O(N)$. + +Here, we can declare an array freq of `size=1000` (which is maximum number of units per box) where `freq[i]` will denote the number of boxes that can hold `i` number of units. We can iterate through the given boxTypes array and populate the freq array. Then we can iterate over the freq array and greedily choose starting from `i=1000` till we run out of truckSize or pick all available boxes. + +### Code in Different Languages + + + + + ```python + def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: + freq, max_units = [0]*1001, 0 + for box in boxTypes: + freq[box[1]] += box[0] + for units in range(1000,0,-1): + if truckSize < 0: break + max_units += min(truckSize, freq[units]) * units + truckSize -= freq[units] + return max_units + + ``` + + + + ```java + class Solution { + public int maximumUnits(int[][] boxTypes, int truckSize) { + Arrays.sort(boxTypes, Comparator.comparingInt(o -> -o[1])); + int ans = 0, i = 0, n = boxTypes.length; + while (i < n && truckSize > 0) { + int maxi = Math.min(boxTypes[i][0], truckSize); + ans += maxi * boxTypes[i][1]; + i++; + truckSize -= maxi; + } + return ans; + } +} + ``` + + + + ```cpp + int maximumUnits(vector>& boxTypes, int truckSize) { + int freq[1001]{0}, maxUnits = 0; // freq[i] = number of boxes that can hold i units + for(auto& box : boxTypes) freq[box[1]] += box[0]; + // greedily choose starting from max units till either truckSize runs out or you choose all boxes + for(int units = 1000; truckSize > 0 && ~units; --units) { + maxUnits += min(truckSize, freq[units]) * units; + truckSize -= freq[units]; + } + return maxUnits; +} + ``` + + + +### Complexity Analysis + +- Time Complexity: $ O(N) $ +- Space Complexity: $ O(1)$ + +## References + +- **LeetCode Problem**: [Where Will the Ball Fall](https://leetcode.com/problems/maximum-units-on-a-truck/description/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/maximum-units-on-a-truck/solutions/) diff --git a/solutions/lc-solutions/1700-1799/1711-count-good-meals.md b/solutions/lc-solutions/1700-1799/1711-count-good-meals.md new file mode 100644 index 0000000..05cdd3a --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1711-count-good-meals.md @@ -0,0 +1,132 @@ +--- +id: count-good-meals +title: Count Good Meals +sidebar_label: 1711. Count Good Meals +tags: [Array, Simulation, C++, Python, Java] +description: "This is a solution to the Count Good Meals problem on LeetCode." +--- + +## Problem Description + +A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. + +You can pick any two different foods to make a good meal. + +Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​​​​​` item of food, return the number of different good meals you can make from this list modulo `10^9 + 7`. + +Note that items with different indices are considered different even if they have the same deliciousness value. + +### Examples + +**Example 1:** + +``` +Input: deliciousness = [1,3,5,7,9] +Output: 4 +Explanation: The good meals are (1,3), (1,7), (3,5) and, (7,9). +Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. + +``` + +**Example 2:** + +``` +Input: deliciousness = [1,1,1,3,3,3,7] +Output: 15 +Explanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. + +``` + +### Constraints + +- `1 <= deliciousness.length <= 10^5` +- `0 <= deliciousness[i] <= 2^20` + +## Solution for 1711. Count Good Meals + + +### Intuition + +Each box takes the same amount of space on the truck. To maximize the total units on the truck, we want to prioritize boxes with more units in them. Let's put the boxes with the most units first. This suggests a greedy solution. + +### Implementation + +1. Sort boxTypes so that boxes with the most units appear first. +2. Iterate through the boxes in sorted order. +3. Instead of counting down one by one how many boxes to take, we can calculate how many boxes of + the current type to take by taking min(truckSize, numberOfBoxes). This is because the truck can fit at most truckSize more boxes, but we have numberOfBoxes left. +4. Decrease the remaining truckSize by subtracting the number of boxes we included. + +### Code in Different Languages + + + + + ```python + class Solution: + def countPairs(self, deliciousness: List[int]) -> int: + result = 0 + hm = Counter() + for num in deliciousness: + for i in range(22): result += hm[2**i-num] + hm[num] += 1 + return result % ((10 ** 9) + 7) + ``` + + + + ```java + class Solution { + int mod = 1000000007; + public int countPairs(int[] arr) { + Map map = new HashMap<>(); + int n = arr.length; + long res = 0; + for (int num : arr) { + int power = 1; + for (int i = 0; i < 22; i++) { + if (map.containsKey(power - num)) { + res += map.get(power - num); + res %= mod; + } + power *= 2; + } + map.put(num, map.getOrDefault(num, 0) + 1); + } + return (int) res; + } +} + ``` + + + + ```cpp + + class Solution { + public: + int countPairs(vector& a) { + unordered_map lks; + long long ans=0; + for(int x : a){ + for(int i=1;i<=(1<<22);i*=2){ + if(lks.count(i-x)) ans+=lks[i-x]; + } + lks[x]+=1; + } + return ans % (int)(1e9 + 7); + } + }; + +``` + + + +### Complexity Analysis + +- Time Complexity: $ O(N) $ +- Space Complexity: $ O(1)$ + +## References + +- **LeetCode Problem**: [Count Good Meals](https://leetcode.com/problems/count-good-meals/description/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/count-good-meals/solutions/) diff --git a/solutions/lc-solutions/1700-1799/1712-ways-to-split-array-into-three-subarrays.md b/solutions/lc-solutions/1700-1799/1712-ways-to-split-array-into-three-subarrays.md new file mode 100644 index 0000000..5a18162 --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1712-ways-to-split-array-into-three-subarrays.md @@ -0,0 +1,130 @@ +--- +id: ways-to-split-array-into-three-subarrays +title: Ways to Split Array Into Three Subarrays +sidebar_label: 1711. Ways to Split Array Into Three Subarrays +tags: [Array, Simulation, C++, Python, Java] +description: "This is a solution to the Ways to Split Array Into Three Subarrays problem on LeetCode." +--- + +## Problem Description + +A split of an integer array is good if: + +- The array is split into three non-empty contiguous subarrays - named `left`, `mid`, `right` respectively from `left` to `right`. +- The sum of the elements in `left` is less than or equal to the sum of the elements in `mid`, and the sum of the elements in mid is less than or equal to the sum of the elements in `right`. +Given `nums`, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo `10^9 + 7`. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,1,1] +Output: 1 +Explanation: The only good way to split nums is [1] [1] [1]. + +``` + +**Example 2:** + +``` +Input: nums = [1,2,2,2,5,0] +Output: 3 +Explanation: There are three good ways of splitting nums: +[1] [2] [2,2,5,0] +[1] [2,2] [2,5,0] +[1,2] [2,2] [5,0] + +``` + +### Constraints + +- `3 <= nums.length <= 10^5` +- `0 <= nums[i] <= 10^4` + +## Solution for 1712. Ways to Split Array Into Three Subarrays + + +### Approach + +The approach is not too hard, but the implementation was tricky for me to get right. + +First, we prepare the prefix sum array, so that we can compute subarray sums in $O(1)$. Then, we move the boundary of the first subarray `left` to `right`. This is the first pointer - i. + +For each point i, we find the minimum `(j)` and maximum `(k)` boundaries of the second subarray: + +`nums[j] >= 2 * nums[i]` +`nums[sz - 1] - nums[k] >= nums[k] - nums[i]` +Note that in the code and examples below, k points to the element after the second array. In other words, it marks the start of the (shortest) third subarray. This makes the logic a bit simpler. + +With these conditions, `sum(0, i) <= sum(i + 1, j)`, and `sum(i + 1, k - 1) < sum(k, n)`. Therefore, for a point `i`, we can build `k - j` subarrays satisfying the problem requirements. + +Final thing is to realize that `j` and `k` will only move forward, which result in a linear-time solution. + +### Code in Different Languages + + + + + ```python + class Solution: + def waysToSplit(self, nums: List[int]) -> int: + sz, res, j, k = len(nums), 0, 0, 0 + nums = list(accumulate(nums)) + for i in range(sz - 2): + while j <= i or (j < sz - 1 and nums[j] < nums[i] * 2): + j += 1 + while k < j or (k < sz - 1 and nums[k] - nums[i] <= nums[-1] - nums[k]): + k += 1 + res = (res + k - j) % 1000000007 + return res + ``` + + + + ```java + public int waysToSplit(int[] nums) { + int sz = nums.length, res = 0; + for (int i = 1; i < sz; ++i) + nums[i] += nums[i - 1]; + for (int i = 0, j = 0, k = 0; i < sz - 2; ++i) { + while (j <= i || (j < sz - 1 && nums[j] < nums[i] * 2)) + ++j; + while (k < j || ( k < sz - 1 && nums[k] - nums[i] <= nums[sz - 1] - nums[k])) + ++k; + res = (res + k - j) % 1000000007; + } + return res; +} + ``` + + + + ```cpp +int waysToSplit(vector& nums) { + int res = 0, sz = nums.size(); + partial_sum(begin(nums), end(nums), begin(nums)); + for (int i = 0, j = 0, k = 0; i < sz - 2; ++i) { + j = max(i + 1, j); + while (j < sz - 1 && nums[j] < nums[i] * 2) + ++j; + k = max(j, k); + while (k < sz - 1 && nums[k] - nums[i] <= nums[sz - 1] - nums[k]) + ++k; + res = (res + k - j) % 1000000007; + } + return res; +} +``` + + + +### Complexity Analysis + +- Time Complexity: $ O(N) $ +- Space Complexity: $ O(1)$ + +## References + +- **LeetCode Problem**: [Ways to Split Array Into Three Subarrays](https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/description/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/solutions/) diff --git a/solutions/lc-solutions/1700-1799/1713-Minimum-Operations-to-Make-a-Subsequence.md b/solutions/lc-solutions/1700-1799/1713-Minimum-Operations-to-Make-a-Subsequence.md new file mode 100644 index 0000000..5cfcb6e --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1713-Minimum-Operations-to-Make-a-Subsequence.md @@ -0,0 +1,146 @@ +--- +id: minimum-operations-to-make-a-subsequence +title: Minimum Operations to Make a Subsequence +sidebar_label: 1713. Minimum Operations to Make a Subsequence +tags: [Array, Simulation, C++, Python, Java] +description: "This is a solution to the Minimum Operations to Make a Subsequence problem on LeetCode." +--- + +## Problem Description + +You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. + +In one operation, you can insert any integer at any position in arr. For example, if `arr = [1,4,1,2]`, you can add `3` in the middle and make it `[1,4,3,1,2]`. Note that you can insert the integer at the very beginning or end of the array. + +Return the minimum number of operations needed to make target a subsequence of arr. + +A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not. + +### Examples + +**Example 1:** + +``` +Input: target = [5,1,3], arr = [9,4,2,3,4] +Output: 2 +Explanation: You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr. + +``` + +**Example 2:** + +``` +Input: target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1] +Output: 3 + +``` + +### Constraints + +- `1 <= target.length, arr.length <= 10^5` +- `1 <= target[i], arr[i] <= 10^9` + +## Solution for 1713. Minimum Operations to Make a Subsequence + + +### Approach + +Seems to be LCS problem, +and we can easily solve in $O(n^2)$, +then it will get TLE. + +Actually there is a bold hint in the statement, +"You are given an array target that consists of distinct integers" + +So there is an order for elements in the target. +For element in A, if it's not in target, we ignore it. +If it's in target, we want find the sequence ending with lower order. + +So we we actually want to find an increase sequence in the A. +This a typical LIS problems. +Just a small difference, +we don't want it to be increase in the element's value, +but in the element's order. + + +### Code in Different Languages + + + + + ```python + def minOperations(self, target, A): + ha = {a: i for i, a in enumerate(target)} + stack = [] + for a in A: + if a not in ha: continue + i = bisect.bisect_left(stack, h[a]) + if i == len(stack): + stack.append(0) + stack[i] = h[a] + return len(target) - len(stack) + + ``` + + + + ```java + public int minOperations(int[] target, int[] A) { + Map h = new HashMap<>(); + for (int i = 0; i < target.length; ++i) { + h.put(target[i], i); + } + int lis = 0, stack[] = new int[A.length + 1]; + for (int a : A) { + if (!h.containsKey(a)) continue; + int i = Arrays.binarySearch(stack, 0, lis, h.get(a)); + i = Math.max(i, ~i); + stack[i] = h.get(a); + lis = Math.max(lis, i + 1); + } + return target.length - lis; + } + ``` + + + + ```cpp + int minOperations(vector& target, vector& A) { + unordered_map h; + int n = A.size(); + for (int i = 0; i < target.size(); ++i) + h[target[i]] = i; + + vector stack; + for (int a : A) { + if (h.find(a) == h.end()) continue; + if (stack.empty() || h[a] > stack.back()) { + stack.push_back(h[a]); + continue; + } + int left = 0, right = stack.size() - 1, mid; + while (left < right) { + mid = (left + right) / 2; + if (stack[mid] < h[a]) + left = mid + 1; + else + right = mid; + } + stack[left] = h[a]; + } + return target.size() - stack.size(); + } + +``` + + + +### Complexity Analysis + +- Time Complexity: $ O(NlogN) $ +- Space Complexity: $ O(N)$ + +## References + +- **LeetCode Problem**: [Minimum Operations to Make a Subsequence](https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/description/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/solutions/ diff --git a/solutions/lc-solutions/1700-1799/1716-Calculate-Money-in-Leetcode-Bank.md b/solutions/lc-solutions/1700-1799/1716-Calculate-Money-in-Leetcode-Bank.md new file mode 100644 index 0000000..5759784 --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1716-Calculate-Money-in-Leetcode-Bank.md @@ -0,0 +1,122 @@ +--- +id: calculate-money-in-leetcode-bank +title: Calculate Money in Leetcode Bank +sidebar_label: 1716. Calculate Money in Leetcode Bank +tags: [Array, Simulation, C++, Python, Java] +description: "This is a solution to the Calculate Money in Leetcode Bank problem on LeetCode." +--- + +## Problem Description + +Hercy wants to save money for his first car. He puts money in the Leetcode bank every day. + +He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the previous Monday. +Given `n`, return the total amount of money he will have in the Leetcode bank at the end of the `nth` day. + +### Examples + +**Example 1:** + +``` +Input: n = 4 +Output: 10 +Explanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10. + +``` + +**Example 2:** + +``` +Input: n = 10 +Output: 37 +Explanation: After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. + +``` +**Example 3:** +``` +Input: n = 20 +Output: 96 +Explanation: After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. + +``` +### Constraints + +- `1 <= n <= 1000` + +## Solution for 1710. Calculate Money in Leetcode Bank + +### Intuition + Hercy contributes money to the Leetcode bank based on a specific pattern. He starts with $1 on the first day and increases his contribution by $1 each subsequent day. Additionally, on each Monday, he increases the contribution by $1 more than the previous Monday. To calculate the total amount after a certain number of days, we need to follow this contribution pattern. +### Approach + +1. Calculate the number of complete weeks `(week_count = n / 7)`. +2. Calculate the total contribution from complete weeks using the arithmetic sum formula for each week: `((week_count * (week_count - 1)) / 2) * 7`. +3. Calculate the total contribution from days beyond complete weeks using the arithmetic sum formula: `(week_count * 28)`. +4. Calculate the contribution from the remaining days (less than a week) using the arithmetic sum formula for the remaining days: `((remaining_days * (remaining_days + 1)) / 2) + (week_count * remaining_days)`. +5. Sum up the contributions calculated in steps `2`, `3`, and `4` to get the total amount. + +### Code in Different Languages + + + + + ```python + class Solution(object): + def totalMoney(self, n): + week_count = n // 7 + remaining_days = n % 7 + + total = ((week_count * (week_count - 1)) // 2) * 7 + total += week_count * 28 + total += ((remaining_days * (remaining_days + 1)) // 2) + (week_count * remaining_days) + + return total + + ``` + + + + ```java + class Solution { + public int totalMoney(int n) { + int week_count = n / 7; + int remaining_days = n % 7; + + int total = ((week_count * (week_count - 1)) / 2) * 7; // Contribution from complete weeks + total += week_count * 28; // Contribution from complete weeks (additional on Mondays) + total += ((remaining_days * (remaining_days + 1)) / 2) + (week_count * remaining_days); // Contribution from remaining days + + return total; + } +} + ``` + + + + ```cpp + class Solution { +public: + int totalMoney(int n) { + int week_count = n / 7; + int remaining_days = n % 7; + + int total = ((week_count * (week_count - 1)) / 2) * 7; // Contribution from complete weeks + total += week_count * 28; // Contribution from complete weeks (additional on Mondays) + total += ((remaining_days * (remaining_days + 1)) / 2) + (week_count * remaining_days); // Contribution from remaining days + + return total; + } +}; + ``` + + + +### Complexity Analysis + +- Time Complexity: $ O(1) $ +- Space Complexity: $ O(1)$ + +## References + +- **LeetCode Problem**: [Calculate Money in Leetcode Bank](https://leetcode.com/problems/calculate-money-in-leetcode-bank/description/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/calculate-money-in-leetcode-bank/solutions/) diff --git a/solutions/lc-solutions/1700-1799/1717-maximum-score-from-removing-substrings.md b/solutions/lc-solutions/1700-1799/1717-maximum-score-from-removing-substrings.md new file mode 100644 index 0000000..ad16e19 --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1717-maximum-score-from-removing-substrings.md @@ -0,0 +1,428 @@ +--- +id: maximum-score-from-removing-substrings +title: 1717. Maximum Score From Removing Substrings +sidebar_label: 1717. Maximum Score From Removing Substrings +tags: +- String +- Stack + +description: "This is a solution to the 1717. Maximum Score From Removing Substrings problem on LeetCode." +--- + +## Problem Description +You are given a string s and two integers x and y. You can perform two types of operations any number of times. + +Remove substring "ab" and gain x points. +For example, when removing "ab" from "cabxbae" it becomes "cxbae". +Remove substring "ba" and gain y points. +For example, when removing "ba" from "cabxbae" it becomes "cabxe". +Return the maximum points you can gain after applying the above operations on s. + ### Examples +**Example 1:** +``` +Input: s = "cdbcbbaaabab", x = 4, y = 5 +Output: 19 +Explanation: +- Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score. +- Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score. +- Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score. +- Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score. +Total score = 5 + 4 + 5 + 5 = 19. +``` + +### Constraints +- `1 <= s.length <= 10^5` +- `1 <= x, y <= 10^4` +- `s consists of lowercase English letters.` +## Solution for 1717. Maximum Score From Removing Substrings + + + + + #### Implementation + ```jsx live + function Solution(arr) { + var maximumGain = function(s, x, y) { + let gt = x > y; + let pts = 0; + let st = []; + + if (gt) { + let i = s.length - 1; + // ab + while (i >= 0) { + if (st.length && s[i] === 'a') { + if (st[st.length - 1] === 'b') { + st.pop(); + pts += x; + } else { + st.push(s[i]); + } + } else { + st.push(s[i]); + } + i--; + } + + let rem = ''; + while (st.length) { + rem += st.pop(); + } + + let j = rem.length - 1; + // ba + while (j >= 0) { + if (st.length && rem[j] === 'b') { + if (st[st.length - 1] === 'a') { + st.pop(); + pts += y; + } else { + st.push(rem[j]); + } + } else { + st.push(rem[j]); + } + j--; + } + } else { + let i = s.length - 1; + // ba + while (i >= 0) { + if (st.length && s[i] === 'b') { + if (st[st.length - 1] === 'a') { + st.pop(); + pts += y; + } else { + st.push(s[i]); + } + } else { + st.push(s[i]); + } + i--; + } + + let rem = ''; + while (st.length) { + rem += st.pop(); + } + + let j = rem.length - 1; + // ab + while (j >= 0) { + if (st.length && rem[j] === 'a') { + if (st[st.length - 1] === 'b') { + st.pop(); + pts += x; + } else { + st.push(rem[j]); + } + } else { + st.push(rem[j]); + } + j--; + } + } + + return pts; +}; + + + const input = "cdbcbbaaabab", x = 4, y = 5 + const output = maximumGain(input ,x,y) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n^2) $ + - Space Complexity: $ O(n)$ + + ## Code in Different Languages + + + + ```python + class Solution: + def maximumGain(self, s: str, x: int, y: int) -> int: + gt = x > y + pts = 0 + + if gt: + st = [] + i = len(s) - 1 + # ab + while i >= 0: + if st and s[i] == 'a': + if st[-1] == 'b': + st.pop() + pts += x + else: + st.append(s[i]) + else: + st.append(s[i]) + i -= 1 + + rem = [] + while st: + rem.append(st.pop()) + + j = len(rem) - 1 + # ba + while j >= 0: + if st and rem[j] == 'b': + if st[-1] == 'a': + st.pop() + pts += y + else: + st.append(rem[j]) + else: + st.append(rem[j]) + j -= 1 + + else: + st = [] + i = len(s) - 1 + # ba + while i >= 0: + if st and s[i] == 'b': + if st[-1] == 'a': + st.pop() + pts += y + else: + st.append(s[i]) + else: + st.append(s[i]) + i -= 1 + + rem = [] + while st: + rem.append(st.pop()) + + j = len(rem) - 1 + # ab + while j >= 0: + if st and rem[j] == 'a': + if st[-1] == 'b': + st.pop() + pts += x + else: + st.append(rem[j]) + else: + st.append(rem[j]) + j -= 1 + + return pts + + ``` + + + + + ```java + import java.util.Stack; + +public class Solution { + public int maximumGain(String s, int x, int y) { + boolean gt = x > y; + int pts = 0; + Stack st = new Stack<>(); + + if (gt) { + int i = s.length() - 1; + // ab + while (i >= 0) { + if (!st.isEmpty() && s.charAt(i) == 'a') { + if (st.peek() == 'b') { + st.pop(); + pts += x; + } else { + st.push(s.charAt(i)); + } + } else { + st.push(s.charAt(i)); + } + i--; + } + + StringBuilder rem = new StringBuilder(); + while (!st.isEmpty()) { + rem.append(st.pop()); + } + + int j = rem.length() - 1; + // ba + while (j >= 0) { + if (!st.isEmpty() && rem.charAt(j) == 'b') { + if (st.peek() == 'a') { + st.pop(); + pts += y; + } else { + st.push(rem.charAt(j)); + } + } else { + st.push(rem.charAt(j)); + } + j--; + } + } else { + int i = s.length() - 1; + // ba + while (i >= 0) { + if (!st.isEmpty() && s.charAt(i) == 'b') { + if (st.peek() == 'a') { + st.pop(); + pts += y; + } else { + st.push(s.charAt(i)); + } + } else { + st.push(s.charAt(i)); + } + i--; + } + + StringBuilder rem = new StringBuilder(); + while (!st.isEmpty()) { + rem.append(st.pop()); + } + + int j = rem.length() - 1; + // ab + while (j >= 0) { + if (!st.isEmpty() && rem.charAt(j) == 'a') { + if (st.peek() == 'b') { + st.pop(); + pts += x; + } else { + st.push(rem.charAt(j)); + } + } else { + st.push(rem.charAt(j)); + } + j--; + } + } + + return pts; + } +} + + ``` + + + + + + ```cpp + class Solution { +public: + int maximumGain(string s, int x, int y) { + int gt = x > y; + int pts = 0; + if (gt) { + stack st; + int i = s.size() - 1; + // ab + while (i >= 0) { + if (!st.empty() && s[i] == 'a') { + if (st.top() == 'b') { + st.pop(); + pts += x; + } else { + st.push(s[i]); + } + } else { + st.push(s[i]); + } + i--; + } + + string rem = ""; + while (!st.empty()) { + rem += st.top(); + st.pop(); + } + int j = rem.size() - 1; + + // ba + while (j >= 0) { + if (!st.empty() && rem[j] == 'b') { + if (st.top() == 'a') { + st.pop(); + pts += y; + } else { + st.push(rem[j]); + } + } else { + st.push(rem[j]); + } + j--; + } + } else if (gt == 0) { + stack st; + int i = s.size() - 1; + // ba + while (i >= 0) { + if (!st.empty() && s[i] == 'b') { + if (st.top() == 'a') { + st.pop(); + pts += y; + } else { + st.push(s[i]); + } + } else { + st.push(s[i]); + } + i--; + } + + // ab + string rem = ""; + while (!st.empty()) { + rem += st.top(); + st.pop(); + } + cout<= 0) { + if (!st.empty() && rem[j] == 'a') { + if (st.top() == 'b') { + st.pop(); + pts += x; + } else { + st.push(rem[j]); + } + } else { + st.push(rem[j]); + } + j--; + } + } + + return pts; + } +}; +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [ 1717. Maximum Score From Removing Substrings](https://leetcode.com/problems/maximum-score-from-removing-substrings/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/maximum-score-from-removing-substrings/) + diff --git a/solutions/lc-solutions/1700-1799/1726-tuple-with-same-product.md b/solutions/lc-solutions/1700-1799/1726-tuple-with-same-product.md new file mode 100644 index 0000000..a42b390 --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1726-tuple-with-same-product.md @@ -0,0 +1,252 @@ +--- +id: tuple-with-same-product +title: Tuple with Same Product +sidebar_label: 1726 - Tuple with Same Product +tags: +- Array +- Hash Table +- Counting + +description: "This is a solution to theTuple with Same Product problem on LeetCode." +--- + +## Problem Description +Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d. + +### Examples + +**Example 1:** +``` +Input: nums = [2,3,4,6] +Output: 8 +Explanation: There are 8 valid tuples: +(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3) +(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2) + +``` + +**Example 2:** + +``` +Input: nums = [1,2,4,5,10] +Output: 16 +Explanation: There are 16 valid tuples: +(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2) +(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1) +(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4) +(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2) +``` + + +### Constraints +- `1 <= nums.length <= 1000` +- `1 <= nums[i] <= 10^4` +- `All elements in nums are distinct.` + +## Solution for Path With Minimum Effort Problem +### Approach +#### Brute Force - +- The first approach that is find all sets of a , b ,c , d by using 4 nested loop . Time Complexity of this approach is very high $ O(N^4)$ which is not feasible +#### Optimized Approach Using Hashmap + +##### Calculate Product Pairs: + +- Iterate through each possible pair of elements in the array. +- For each pair (nums[i], nums[j]), calculate their product. +- Store the product in a hash map (mp) where the key is the product and the value is the count of pairs that produce this product. +##### Count Tuples: +- Iterate through the hash map. +- For each unique product that appears n times, the number of ways to choose 2 pairs from n pairs is given by the combination formula C(n, 2) = n * (n - 1) / 2. +- Since each valid tuple of pairs can be permuted in 8 different ways (each pair can be swapped with the other), multiply the result by 8. +##### Return the Result: +- Sum up the counts from all unique products to get the total number of valid tuples and multiply by 8. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + var tupleSameProduct = function(nums) { + let mp = new Map(); + + for (let i = 0; i < nums.length; ++i) { + for (let j = i + 1; j < nums.length; ++j) { + let product = nums[i] * nums[j]; + mp.set(product, (mp.get(product) || 0) + 1); + } + } + + let ans = 0; + + for (let count of mp.values()) { + ans += (count * (count - 1)) / 2; + } + + return ans * 8; + }; + const input = [2,3,4,6] + const output = tupleSameProduct(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(N^2) $ + - Space Complexity: $ O(N^2)$ + + ## Code in Different Languages + + + + ```javascript + var tupleSameProduct = function(nums) { + let mp = new Map(); + + for (let i = 0; i < nums.length; ++i) { + for (let j = i + 1; j < nums.length; ++j) { + let product = nums[i] * nums[j]; + mp.set(product, (mp.get(product) || 0) + 1); + } + } + + let ans = 0; + + for (let count of mp.values()) { + ans += (count * (count - 1)) / 2; + } + + return ans * 8; +}; + ``` + + + + + ```typescript + function tupleSameProduct(nums: number[]): number { + let mp = new Map(); + + for (let i = 0; i < nums.length; ++i) { + for (let j = i + 1; j < nums.length; ++j) { + let product = nums[i] * nums[j]; + mp.set(product, (mp.get(product) || 0) + 1); + } + } + + let ans = 0; + + for (let count of mp.values()) { + ans += (count * (count - 1)) / 2; + } + + return ans * 8; +} + + ``` + + + + ```python + from collections import defaultdict + +class Solution: + def tupleSameProduct(self, nums: list[int]) -> int: + mp = defaultdict(int) + + for i in range(len(nums)): + for j in range(i + 1, len(nums)): + product = nums[i] * nums[j] + mp[product] += 1 + + ans = 0 + + for count in mp.values(): + ans += (count * (count - 1)) // 2 + + return ans * 8 + + ``` + + + + + ```java + import java.util.HashMap; +import java.util.Map; + +public class Solution { + public int tupleSameProduct(int[] nums) { + Map mp = new HashMap<>(); + + for (int i = 0; i < nums.length; ++i) { + for (int j = i + 1; j < nums.length; ++j) { + int product = nums[i] * nums[j]; + mp.put(product, mp.getOrDefault(product, 0) + 1); + } + } + + int ans = 0; + + for (Map.Entry entry : mp.entrySet()) { + int n = entry.getValue(); + ans += (n * (n - 1)) / 2; + } + + return ans * 8; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + int tupleSameProduct(vector& nums) { + unordered_map mp; + + for (int i = 0; i < nums.size(); ++i) { + for (int j = i + 1; j < nums.size(); ++j) { + int product = nums[i] * nums[j]; + mp[product]++; + } + } + + int ans = 0; + + for (auto it = mp.begin(); it != mp.end(); ++it) { + int n = it->second; + ans += (n * (n - 1)) / 2; // total tuples + } + + return ans * 8; + } +}; + + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Tuple With Same Product](https://leetcode.com/problems/tuple-with-same-product/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/tuple-with-same-product/solutions) + diff --git a/solutions/lc-solutions/1700-1799/1768-merge-strings-alternately.md b/solutions/lc-solutions/1700-1799/1768-merge-strings-alternately.md new file mode 100644 index 0000000..5a6f1e3 --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1768-merge-strings-alternately.md @@ -0,0 +1,254 @@ +--- + +id: merge-strings-alternately +title: Merge Strings Alternately Solution +sidebar_label: 1768 - Merge Strings Alternately +tags: + - Merge Strings + - Two Pointers + - Brute Force + - LeetCode + - JavaScript + - TypeScript + - Python + - Java + - C++ +description: "This is a solution to the Merge Strings Alternately problem on LeetCode." +sidebar_position: 2 + +--- + +In this tutorial, we will solve the Merge Strings Alternately problem using two different approaches: brute force and two-pointer technique. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, and C++. + +## Problem Description + +You are given two strings `word1` and `word2`. Merge the strings by adding letters in alternating order, starting with `word1`. If a string is longer than the other, append the additional letters onto the end of the merged string. + +Return the merged string. + +### Examples + +**Example 1:** + +```plaintext +Input: word1 = "abc", word2 = "pqr" +Output: "apbqcr" +``` + +**Example 2:** + +```plaintext +Input: word1 = "ab", word2 = "pqrs" +Output: "apbqrs" +``` + +**Example 3:** + +```plaintext +Input: word1 = "abcd", word2 = "pq" +Output: "apbqcd" +``` + +### Constraints + +- $1 \leq \text{word1.length}, \text{word2.length} \leq 100$ +- `word1` and `word2` consist of lowercase English letters. + +--- + +## Solution for Merge Strings Alternately Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or a two-pointer technique. The brute force approach directly iterates through the strings and constructs the result, while the two-pointer technique uses two pointers to merge the strings in an alternating manner. + + + + +### Approach 1: Brute Force (Naive) + +The brute force approach iterates through each character of both strings and appends them alternately to the result string. If one string is exhausted before the other, the remaining characters of the longer string are appended to the result string. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + string mergeAlternately(string word1, string word2) { + string result; + int i = 0, j = 0; + while (i < word1.length() && j < word2.length()) { + result += word1[i++]; + result += word2[j++]; + } + while (i < word1.length()) { + result += word1[i++]; + } + while (j < word2.length()) { + result += word2[j++]; + } + return result; + } +}; +``` + + + + + +```java +class Solution { + public String mergeAlternately(String word1, String word2) { + StringBuilder result = new StringBuilder(); + int i = 0, j = 0; + while (i < word1.length() && j < word2.length()) { + result.append(word1.charAt(i++)); + result.append(word2.charAt(j++)); + } + while (i < word1.length()) { + result.append(word1.charAt(i++)); + } + while (j < word2.length()) { + result.append(word2.charAt(j++)); + } + return result.toString(); + } +} +``` + + + + + +```python +class Solution: + def mergeAlternately(self, word1: str, word2: str) -> str: + result = [] + i, j = 0, 0 + while i < len(word1) and j < len(word2): + result.append(word1[i]) + result.append(word2[j]) + i += 1 + j += 1 + while i < len(word1): + result.append(word1[i]) + i += 1 + while j < len(word2): + result.append(word2[j]) + j += 1 + return ''.join(result) +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n + m)$ +- Space Complexity: $O(n + m)$ +- Where `n` is the length of `word1` and `m` is the length of `word2`. +- The time complexity is $O(n + m)$ because we iterate through both strings once. +- The space complexity is $O(n + m)$ because we store the result in a new string. +- This approach is efficient and straightforward. + + + + +### Approach 2: Using Two Pointers + +The two-pointer approach uses two pointers to iterate through both strings simultaneously, appending characters alternately to the result string. When one string is exhausted, the remaining characters of the other string are appended to the result string. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + string mergeAlternately(string word1, string word2) { + string result; + int i = 0, j = 0; + while (i < word1.length() || j < word2.length()) { + if (i < word1.length()) { + result += word1[i++]; + } + if (j < word2.length()) { + result += word2[j++]; + } + } + return result; + } +}; +``` + + + + + +```java +class Solution { + public String mergeAlternately(String word1, String word2) { + StringBuilder result = new StringBuilder(); + int i = 0, j = 0; + while (i < word1.length() || j < word2.length()) { + if (i < word1.length()) { + result.append(word1.charAt(i++)); + } + if (j < word2.length()) { + result.append(word2.charAt(j++)); + } + } + return result.toString(); + } +} +``` + + + + + +```python +class Solution: + def mergeAlternately(self, word1: str, word2: str) -> str: + result = [] + i, j = 0, 0 + while i < len(word1) or j < len(word2): + if i < len(word1): + result.append(word1[i]) + i += 1 + if j < len(word2): + result.append(word2[j]) + j += 1 + return ''.join(result) +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n + m)$ +- Space Complexity: $O(n + m)$ +- Where `n` is the length of `word1` and `m` is the length of `word2`. +- The time complexity is $O(n + m)$ because we iterate through both strings once. +- The space complexity is $O(n + m)$ because we store the result in a new string. +- This approach is efficient and straightforward. + + + + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/1700-1799/1781-sum-of-beauty-of-all-substrings.md b/solutions/lc-solutions/1700-1799/1781-sum-of-beauty-of-all-substrings.md new file mode 100644 index 0000000..03e9b12 --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1781-sum-of-beauty-of-all-substrings.md @@ -0,0 +1,290 @@ +--- +id: sum-of-beauty-of-all-substrings +title: 1781. Sum of Beauty of All Substrings +sidebar_label: 1781. Sum of Beauty of All Substrings +tags: +- Array +- Hash Table +- Counting + +description: "This is a solution to the Sum of Beauty of All Substrings problem on LeetCode." +--- + +## Problem Description +The beauty of a string is the difference in frequencies between the most frequent and least frequent characters. + +For example, the beauty of "abaacc" is 3 - 1 = 2. +Given a string s, return the sum of beauty of all of its substrings. + +### Examples + +**Example 1:** +``` +Input: s = "aabcb" +Output: 5 +Explanation: The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1. +``` + +**Example 2:** + +``` +Input: s = "aabcbaa" +Output: 17 +``` + + +### Constraints +- `1 <= s.length <= 500` +- `s consists of only lowercase English letters.` +## Solution for 1781. Sum of Beauty of All Substrings Problem +### Approach +The goal of the `beautySum` problem is to find the sum of beauty values for all possible substrings of a given string `s`. The beauty value of a substring is defined as the difference between the maximum frequency and the minimum frequency of characters within that substring. + +#### Steps to Solve the Problem + +1. **Initialization**: + - Initialize a variable `ans` to store the sum of beauty values. + +2. **Iterate through the string**: + - Use a nested loop where the outer loop (`i`) iterates through each character in the string and the inner loop (`j`) iterates from the current character to the end of the string, effectively generating all substrings starting from each character. + +3. **Track character frequencies**: + - Use a dictionary (or hashmap) to keep track of the frequency of each character in the current substring. + - Update the dictionary as you extend the substring in the inner loop. + +4. **Calculate the beauty value**: + - For each substring, calculate its beauty value by finding the maximum and minimum frequencies of characters in the substring. + - Update the sum of beauty values (`ans`) with the beauty value of the current substring. + +5. **Return the result**: + - After processing all substrings, return the total sum of beauty values. + + + + #### Implementation + ```jsx live + function Solution(arr) { + function beauty(mp) { + let mini = Infinity; + let maxi = -Infinity; + + for (let key in mp) { + maxi = Math.max(maxi, mp[key]); + mini = Math.min(mini, mp[key]); + } + + return maxi - mini; + } + + function beautySum(s) { + let ans = 0; + for (let i = 0; i < s.length; i++) { + let mp = {}; + + for (let j = i; j < s.length; j++) { + mp[s[j]] = (mp[s[j]] || 0) + 1; + ans += beauty(mp); + } + } + + return ans; + } + const input = "aabcb" + const output = beautySum(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(N^2) $ + - Space Complexity: $ O(N)$ + + ## Code in Different Languages + + + + ```javascript + function beauty(mp) { + let mini = Infinity; + let maxi = -Infinity; + + for (let key in mp) { + maxi = Math.max(maxi, mp[key]); + mini = Math.min(mini, mp[key]); + } + + return maxi - mini; + } + + function beautySum(s) { + let ans = 0; + for (let i = 0; i < s.length; i++) { + let mp = {}; + + for (let j = i; j < s.length; j++) { + mp[s[j]] = (mp[s[j]] || 0) + 1; + ans += this.beauty(mp); + } + } + + return ans; + } + ``` + + + + + ```typescript + class Solution { + beauty(mp: { [key: string]: number }): number { + let mini = Infinity; + let maxi = -Infinity; + + for (let key in mp) { + maxi = Math.max(maxi, mp[key]); + mini = Math.min(mini, mp[key]); + } + + return maxi - mini; + } + + beautySum(s: string): number { + let ans = 0; + for (let i = 0; i < s.length; i++) { + let mp: { [key: string]: number } = {}; + + for (let j = i; j < s.length; j++) { + mp[s[j]] = (mp[s[j]] || 0) + 1; + ans += this.beauty(mp); + } + } + + return ans; + } +} + + ``` + + + + ```python + class Solution: + def beauty(self, mp): + mini = float('inf') + maxi = float('-inf') + + for value in mp.values(): + maxi = max(maxi, value) + mini = min(mini, value) + + return maxi - mini + + def beautySum(self, s: str) -> int: + ans = 0 + for i in range(len(s)): + mp = {} + + for j in range(i, len(s)): + mp[s[j]] = mp.get(s[j], 0) + 1 + ans += self.beauty(mp) + + return ans + + ``` + + + + + ```java + import java.util.HashMap; + +class Solution { + private int beauty(HashMap mp) { + int mini = Integer.MAX_VALUE; + int maxi = Integer.MIN_VALUE; + + for (int value : mp.values()) { + maxi = Math.max(maxi, value); + mini = Math.min(mini, value); + } + + return maxi - mini; + } + + public int beautySum(String s) { + int ans = 0; + for (int i = 0; i < s.length(); i++) { + HashMap mp = new HashMap<>(); + + for (int j = i; j < s.length(); j++) { + mp.put(s.charAt(j), mp.getOrDefault(s.charAt(j), 0) + 1); + ans += beauty(mp); + } + } + + return ans; + } +} + + ``` + + + + + ```cpp + class Solution { + int beauty(unordered_map&mp) + { + int mini=INT_MAX; + int maxi=INT_MIN; + + for(auto i:mp) + { + maxi=max(maxi,i.second); + mini=min(mini,i.second); + } + + return maxi-mini; + + } +public: + int beautySum(string s) { + int ans=0; + for(int i=0;imp; + + for(int j=i;j + + +
+
+ +## References + +- **LeetCode Problem**: [ Sum of Beauty of All Substrings](https://leetcode.com/problems/sum-of-beauty-of-all-substrings/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/sum-of-beauty-of-all-substrings/description/) + diff --git a/solutions/lc-solutions/1700-1799/1791-find-center-of-star-graph.md b/solutions/lc-solutions/1700-1799/1791-find-center-of-star-graph.md new file mode 100644 index 0000000..fc44bed --- /dev/null +++ b/solutions/lc-solutions/1700-1799/1791-find-center-of-star-graph.md @@ -0,0 +1,249 @@ +--- +id: find-center-of-star-graph +title: Find Center of Star Graph +sidebar_label: 1791. Find Center of Star Graph + +tags: +- Graph + +description: "This is a solution to the Find Center of Star Graph problem on LeetCode." +--- + +## Problem Description +There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node. + +You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph. + +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2021/02/24/star_graph.png) +``` +Input: edges = [[1,2],[2,3],[4,2]] +Output: 2 +Explanation: As shown in the figure above, node 2 is connected to every other node, so 2 is the center. + +``` + +**Example 2:** + +``` +Input: edges = [[1,2],[5,1],[1,3],[1,4]] +Output: 1 +``` + + +### Constraints +- `3 <= n <= 10^5` +- `edges.length == n - 1` +- `edges[i].length == 2` +- `1 <= ui, vi <= n` +- `ui != vi` + +## Solution for Path With Minimum Effort Problem +### Approach + +1. **Adjacency List Creation**: First, we create an adjacency list to store the connections between nodes. +2. **Counting Connections**: Traverse the `edges` list to fill the adjacency list. +3. **Finding the Center**: The node that has exactly `n` connections (where `n` is the number of edges) is the center of the star graph because it is connected to all other nodes. + +### Intuition: +In a star graph with `n` edges: +- The center node will have exactly `n` connections. +- All other nodes will have exactly one connection (to the center). + +Thus, by counting the number of connections each node has, we can identify the center of the star graph. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function findCenter(edges) { + let n = edges.length; + let adj = new Array(n + 2).fill(0).map(() => []); + + for (let i = 0; i < edges.length; i++) { + adj[edges[i][0]].push(edges[i][1]); + adj[edges[i][1]].push(edges[i][0]); + } + + for (let i = 1; i <= n + 1; i++) { + if (adj[i].length === edges.length) { + return i; + } + } + return 0; + } + const input = [[1,2],[2,3],[4,2]] + const output = findCenter(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(N) $ + - Space Complexity: $ O(N)$ + + ## Code in Different Languages + + + + ```javascript + function findCenter(edges) { + let n = edges.length; + let adj = new Array(n + 2).fill(0).map(() => []); + + for (let i = 0; i < edges.length; i++) { + adj[edges[i][0]].push(edges[i][1]); + adj[edges[i][1]].push(edges[i][0]); + } + + for (let i = 1; i <= n + 1; i++) { + if (adj[i].length === edges.length) { + return i; + } + } + return 0; + } + ``` + + + + + ```typescript + class Solution { + findCenter(edges: number[][]): number { + let n = edges.length; + let adj: number[][] = new Array(n + 2).fill(0).map(() => []); + + for (let i = 0; i < edges.length; i++) { + adj[edges[i][0]].push(edges[i][1]); + adj[edges[i][1]].push(edges[i][0]); + } + + for (let i = 1; i <= n + 1; i++) { + if (adj[i].length === edges.length) { + return i; + } + } + return 0; + } +} + +// Usage example: +let solution = new Solution(); +let edges = [[1, 2], [2, 3], [4, 2]]; +console.log(solution.findCenter(edges)); // Output: 2 + + ``` + + + + ```python + class Solution: + def findCenter(self, edges): + n = len(edges) + adj = [[] for _ in range(n + 2)] + + for edge in edges: + adj[edge[0]].append(edge[1]) + adj[edge[1]].append(edge[0]) + + for i in range(1, n + 2): + if len(adj[i]) == n: + return i + return 0 + +# Usage example: +solution = Solution() +edges = [[1, 2], [2, 3], [4, 2]] +print(solution.findCenter(edges)) # Output: 2 + + ``` + + + + + ```java + import java.util.ArrayList; +import java.util.List; + +class Solution { + public int findCenter(int[][] edges) { + int n = edges.length; + List[] adj = new ArrayList[n + 2]; + for (int i = 0; i < n + 2; i++) { + adj[i] = new ArrayList<>(); + } + + for (int i = 0; i < edges.length; i++) { + adj[edges[i][0]].add(edges[i][1]); + adj[edges[i][1]].add(edges[i][0]); + } + + for (int i = 1; i <= n + 1; i++) { + if (adj[i].size() == n) { + return i; + } + } + return 0; + } + + // Usage example: + public static void main(String[] args) { + Solution solution = new Solution(); + int[][] edges = {{1, 2}, {2, 3}, {4, 2}}; + System.out.println(solution.findCenter(edges)); // Output: 2 + } +} + + ``` + + + + + ```cpp + class Solution { +public: + int findCenter(vector>& edges) { + int n = edges.size(); + vector adj[n + 2]; + + for (int i = 0; i < edges.size(); i++) { + adj[edges[i][0]].push_back(edges[i][1]); + adj[edges[i][1]].push_back(edges[i][0]); + } + + for (int i = 1; i <= n+1; i++) { + if (adj[i].size() == edges.size()) + return i; + } + return 0; + } +}; + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Find Center of Star Graph](https://leetcode.com/problems/find-center-of-star-graph/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/find-center-of-star-graph/description/) + diff --git a/solutions/lc-solutions/1700-1799/Maximum XOR With an Element From Array.md b/solutions/lc-solutions/1700-1799/Maximum XOR With an Element From Array.md new file mode 100644 index 0000000..4d3a8eb --- /dev/null +++ b/solutions/lc-solutions/1700-1799/Maximum XOR With an Element From Array.md @@ -0,0 +1,129 @@ +--- +id: maximum-xor-with-an-element-from-array +title: Maximum XOR With an Element From Array +sidebar_label: 1707 - Maximum XOR With an Element From Array +tags: [Trie, Bit Manipulation, Sorting, C++] +description: Solve the problem of finding the maximum bitwise XOR of an element with given elements that do not exceed a specified value using trie and bit manipulation. +--- + +## Problem Statement + +### Problem Description + +You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`. + +The answer to the ith query is the maximum bitwise XOR value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for all `j` such that `nums[j] <= mi`. If all elements in `nums` are larger than `mi`, then the answer is -1. + +Return an integer array `answer` where `answer.length == queries.length` and `answer[i]` is the answer to the ith query. + +### Example + +**Example 1:** +``` +Input: nums = [0, 1, 2, 3, 4], queries = [[3, 1], [1, 3], [5, 6]] +Output: [3, 3, 7] +``` + + +**Explanation:** +1. 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3. +2. 1 XOR 2 = 3. +3. 5 XOR 2 = 7. + +**Example 2:** +``` +Input: nums = [5, 2, 4, 6, 6, 3], queries = [[12, 4], [8, 1], [6, 3]] +Output: [15, -1, 5] +``` + +### Constraints + +- 1 <= `nums.length`, `queries.length` <= 10^5 +- `queries[i].length == 2` +- 0 <= `nums[j]`, `xi`, `mi` <= 10^9 + +## Solution + +### Intuition + +To efficiently solve this problem, we can use a combination of sorting and Trie (prefix tree) to manage and query the maximum XOR. + +1. **Sort `nums` and `queries`**: Sort `nums` and `queries` based on the second element of each query (`mi`). This allows us to process each query in increasing order of `mi`, ensuring that we only consider valid `nums` elements for each query. + +2. **Use a Trie for Maximum XOR**: We will maintain a Trie of the binary representations of the numbers. For each query, we will insert numbers into the Trie that are less than or equal to `mi`, and then compute the maximum XOR for the current `xi`. + +### Time Complexity and Space Complexity Analysis + +- **Time Complexity**: + - Sorting `nums` and `queries` takes $O(n \log n)$ and $O(q \log q)$ respectively. + - Inserting each number into the Trie takes $O(31)$ for each number (as the maximum number of bits is 31). + - Finding the maximum XOR for each query takes $O(31)$ for each query. + - Overall time complexity is $O((n + q) \log(n + q))$. + +- **Space Complexity**: + - The Trie will store up to `n` numbers, each taking $O(31)$ space. + - The space complexity is $O(n \cdot 31)$. + +### Code + +#### C++ + +```cpp +class Solution { + struct TrieNode { + TrieNode* children[2] = {}; + }; + + TrieNode* root = new TrieNode(); + + void insert(int num) { + TrieNode* node = root; + for (int i = 30; i >= 0; --i) { + int bit = (num >> i) & 1; + if (!node->children[bit]) { + node->children[bit] = new TrieNode(); + } + node = node->children[bit]; + } + } + + int getMaxXOR(int num) { + TrieNode* node = root; + int maxXOR = 0; + for (int i = 30; i >= 0; --i) { + int bit = (num >> i) & 1; + if (node->children[1 - bit]) { + maxXOR |= (1 << i); + node = node->children[1 - bit]; + } else { + node = node->children[bit]; + } + } + return maxXOR; + } + +public: + vector maximizeXor(vector& nums, vector>& queries) { + sort(nums.begin(), nums.end()); + vector>> q; + int qLen = queries.size(); + for (int i = 0; i < qLen; ++i) { + q.push_back({queries[i][1], {queries[i][0], i}}); + } + sort(q.begin(), q.end()); + + vector result(qLen); + int idx = 0; + for (const auto& [mi, xi_idx] : q) { + int xi = xi_idx.first; + int queryIdx = xi_idx.second; + while (idx < nums.size() && nums[idx] <= mi) { + insert(nums[idx]); + ++idx; + } + result[queryIdx] = idx ? getMaxXOR(xi) : -1; + } + return result; + } +}; +``` diff --git a/solutions/lc-solutions/1700-1799/Minimum Elements to Add to Form a Given Sum.md b/solutions/lc-solutions/1700-1799/Minimum Elements to Add to Form a Given Sum.md new file mode 100644 index 0000000..8d0f759 --- /dev/null +++ b/solutions/lc-solutions/1700-1799/Minimum Elements to Add to Form a Given Sum.md @@ -0,0 +1,100 @@ +--- +id: minimum-elements-to-add-to-form-a-given-sum +title: Minimum Elements to Add to Form a Given Sum +sidebar_label: 1785 - Minimum Elements to Add to Form a Given Sum +tags: [Greedy, Array, C++] +description: Solve the problem of finding the minimum number of elements to add to an array to make the sum equal to a given goal while maintaining the property that absolute value of elements does not exceed a specified limit. +--- + +## Problem Statement + +### Problem Description + +You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`. + +Return the minimum number of elements you need to add to make the sum of the array equal to `goal`. The array must maintain its property that `abs(nums[i]) <= limit`. + +Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise. + +### Example + +**Example 1:** +``` +Input: nums = [1, -1, 1], limit = 3, goal = -4 +Output: 2 +``` +**Explanation:** You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4. + + +**Example 2:** +``` +Input: nums = [1, -10, 9, 1], limit = 100, goal = 0 +Output: 1 +``` + +### Constraints + +- 1 <= `nums.length` <= 10^5 +- 1 <= `limit` <= 10^6 +- -`limit` <= `nums[i]` <= `limit` +- -10^9 <= `goal` <= 10^9 + +## Solution + +### Intuition + +To solve this problem efficiently, we can use a greedy approach. We need to calculate the difference between the current sum of `nums` and the `goal`. Based on this difference, we can determine how many elements are required to achieve the desired sum. The key steps are: + +1. **Calculate the Current Sum**: Compute the sum of the `nums` array. +2. **Determine the Difference**: Find the absolute difference between the current sum and the `goal`. +3. **Calculate the Minimum Number of Elements**: Given that each element added can have a maximum magnitude of `limit`, compute the minimum number of such elements required to cover the difference. + +### Time Complexity and Space Complexity Analysis + +- **Time Complexity**: + - Calculating the sum of the `nums` array takes $O(n)$, where `n` is the length of the array. + - Calculating the minimum number of elements involves a simple arithmetic operation, which is $O(1)$. + + Overall time complexity is $O(n)$. + +- **Space Complexity**: + - The space complexity is $O(1)$ as we are using a fixed amount of extra space. + +### Code + +#### C++ + +```cpp +class Solution { +public: + int minElements(vector& nums, int limit, int goal) { + long long sum = accumulate(nums.begin(), nums.end(), 0LL); + long long diff = abs(sum - goal); + return (diff + limit - 1) / limit; // Equivalent to ceil(diff / limit) + } +}; +``` +#### Python +```python +class Solution: + def minElements(self, nums: List[int], limit: int, goal: int) -> int: + current_sum = sum(nums) + diff = abs(current_sum - goal) + return (diff + limit - 1) // limit # Equivalent to ceil(diff / limit) +``` + +#### Java +```java +import java.util.List; + +class Solution { + public int minElements(List nums, int limit, int goal) { + long currentSum = 0; + for (int num : nums) { + currentSum += num; + } + long diff = Math.abs(currentSum - goal); + return (int) ((diff + limit - 1) / limit); // Equivalent to ceil(diff / limit) + } +} +``` diff --git a/solutions/lc-solutions/1700-1799/_category_.json b/solutions/lc-solutions/1700-1799/_category_.json new file mode 100644 index 0000000..15e31c1 --- /dev/null +++ b/solutions/lc-solutions/1700-1799/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "1700-1799", + "position": 19, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (1700 - 1799)" + } +} diff --git a/solutions/lc-solutions/1800-1899/1800-maximum-ascending-subarray-sum.md b/solutions/lc-solutions/1800-1899/1800-maximum-ascending-subarray-sum.md new file mode 100644 index 0000000..ac4be97 --- /dev/null +++ b/solutions/lc-solutions/1800-1899/1800-maximum-ascending-subarray-sum.md @@ -0,0 +1,251 @@ +--- +id: maximum-ascending-subarray-sum +title: Maximum Ascending Subarray Sum +sidebar_label: 1800 - Maximum Ascending Subarray Sum +tags: +- Array + + +description: "This is a solution to the Maximum Ascending Subarray Sum problem on LeetCode." +--- + +## Problem Description +Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums. + +A subarray is defined as a contiguous sequence of numbers in an array. + +A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where `l <= i < r, numsi < numsi+1`. Note that a subarray of size 1 is ascending. +### Examples + +**Example 1:** + +``` +Input: nums = [10,20,30,5,10,50] +Output: 65 +Explanation: [5,10,50] is the ascending subarray with the maximum sum of 65. +``` + +**Example 2:** +``` +Input: nums = [10,20,30,40,50] +Output: 150 +Explanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150. +``` + +### Constraints + +- `1 <= arr.length <= 10^5` + +## Solution for Maximum Ascending Subarray Sum Problem +### Approach + + +1. **Initialization**: + - Initialize a variable `sum` to keep track of the maximum ascending subarray sum found. + +2. **Iterate Through the Array**: + - Use an outer loop to iterate through each element of the array. + - For each element, initialize `prev` to the current element and `curr` to the same value. `prev` keeps track of the previous element in the current ascending subarray, and `curr` keeps the sum of the current ascending subarray. + +3. **Find Ascending Subarrays**: + - Use an inner loop to continue from the next element of the outer loop index. + - If the current element in the inner loop is greater than `prev`, add it to `curr` and update `prev`. + - If the current element is not greater than `prev`, break out of the inner loop as the subarray is no longer strictly increasing. + +4. **Update Maximum Sum**: + - After exiting the inner loop, update `sum` with the maximum value between `sum` and `curr`. + +5. **Return the Result**: + - After iterating through all elements, return the value of `sum` as the result. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function maxAscendingSum(nums) { + let sum = 0; + + for (let i = 0; i < nums.length; i++) { + let prev = nums[i]; + let curr = prev; + for (let j = i + 1; j < nums.length; j++) { + if (nums[j] > prev) { + curr += nums[j]; + prev = nums[j]; + } else { + break; + } + } + sum = Math.max(sum, curr); + } + return sum; + } + const input = [10,20,30,5,10,50] + const output =maxAscendingSum(input) ; + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(n^2) $ because of sorting, where n is the size of array + - Space Complexity: $ O(1) $ + + ## Code in Different Languages + + + + ```javascript + class Solution { + maxAscendingSum(nums) { + let sum = 0; + + for (let i = 0; i < nums.length; i++) { + let prev = nums[i]; + let curr = prev; + for (let j = i + 1; j < nums.length; j++) { + if (nums[j] > prev) { + curr += nums[j]; + prev = nums[j]; + } else { + break; + } + } + sum = Math.max(sum, curr); + } + return sum; + } +} + + ``` + + + + + ```typescript + class Solution { + maxAscendingSum(nums: number[]): number { + let sum = 0; + + for (let i = 0; i < nums.length; i++) { + let prev = nums[i]; + let curr = prev; + for (let j = i + 1; j < nums.length; j++) { + if (nums[j] > prev) { + curr += nums[j]; + prev = nums[j]; + } else { + break; + } + } + sum = Math.max(sum, curr); + } + return sum; + } +} + + ``` + + + + ```python + class Solution: + def maxAscendingSum(self, nums: List[int]) -> int: + sum = 0 + + for i in range(len(nums)): + prev = nums[i] + curr = prev + for j in range(i + 1, len(nums)): + if nums[j] > prev: + curr += nums[j] + prev = nums[j] + else: + break + sum = max(sum, curr) + + return sum + + ``` + + + + + ```java + public class Solution { + public int maxAscendingSum(int[] nums) { + int sum = 0; + + for (int i = 0; i < nums.length; i++) { + int prev = nums[i]; + int curr = prev; + for (int j = i + 1; j < nums.length; j++) { + if (nums[j] > prev) { + curr += nums[j]; + prev = nums[j]; + } else { + break; + } + } + sum = Math.max(sum, curr); + } + return sum; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + int maxAscendingSum(vector& nums) { + int sum=0; + + for(int i=0;iprev) + { + curr+=nums[j]; + prev= nums[j]; + } + else{ + break; + } + } + sum=max(sum , curr); + } + return sum; + } +}; + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Maximum Ascending Subarray Sum](https://leetcode.com/problems/maximum-ascending-subarray-sum/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/maximum-ascending-subarray-sum/description/) + diff --git a/solutions/lc-solutions/1800-1899/1807-evaluate-the-bracket-pairs-of-a-string.md b/solutions/lc-solutions/1800-1899/1807-evaluate-the-bracket-pairs-of-a-string.md new file mode 100644 index 0000000..bdbe483 --- /dev/null +++ b/solutions/lc-solutions/1800-1899/1807-evaluate-the-bracket-pairs-of-a-string.md @@ -0,0 +1,192 @@ +--- +id: evaluate-the-bracket-pairs-of-a-string +title: Evaluate the Bracket Pairs of a String +sidebar_label: 1807-Evaluate the Bracket Pairs of a String +tags: + - String Manipulation + - Hash Table + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Evaluate Bracket Pairs problem on LeetCode." +sidebar_position: 30 +--- + +## Problem Description + +You are given a string `s` that contains some bracket pairs, with each pair containing a non-empty key. + +For example, in the string `"(name)is(age)yearsold"`, there are two bracket pairs that contain the keys "name" and "age". You know the values of a wide range of keys. This is represented by a 2D string array `knowledge` where each `knowledge[i] = [keyi, valuei]` indicates that key `keyi` has a value of `valuei`. + +You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key `keyi`, you will: +- Replace `keyi` and the bracket pair with the key's corresponding `valuei`. +- If you do not know the value of the key, you will replace `keyi` and the bracket pair with a question mark "?" (without the quotation marks). + +Each key will appear at most once in your knowledge. There will not be any nested brackets in `s`. + +Return the resulting string after evaluating all of the bracket pairs. + +### Examples + +**Example 1:** + +``` +Input: s = "(name)is(age)yearsold", knowledge = [["name","bob"],["age","two"]] +Output: "bobistwoyearsold" +Explanation: +The key "name" has a value of "bob", so replace "(name)" with "bob". +The key "age" has a value of "two", so replace "(age)" with "two". +``` + +**Example 2:** + +``` +Input: s = "hi(name)", knowledge = [["a","b"]] +Output: "hi?" +Explanation: As you do not know the value of the key "name", replace "(name)" with "?". +``` + +**Example 3:** + +``` +Input: s = "(a)(a)(a)aaa", knowledge = [["a","yes"]] +Output: "yesyesyesaaa" +Explanation: The same key can appear multiple times. +The key "a" has a value of "yes", so replace all occurrences of "(a)" with "yes". +Notice that the "a"s not in a bracket pair are not evaluated. +``` + +### Constraints + +- `1 <= s.length <= 10^5` +- `0 <= knowledge.length <= 10^5` +- `knowledge[i].length == 2` +- `1 <= keyi.length, valuei.length <= 10` +- `s` consists of lowercase English letters and round brackets '(' and ')'. +- Every open bracket '(' in `s` will have a corresponding close bracket ')'. +- The key in each bracket pair of `s` will be non-empty. +- There will not be any nested bracket pairs in `s`. +- `keyi` and `valuei` consist of lowercase English letters. +- Each `keyi` in knowledge is unique. + +--- + +## Solution for Evaluate Bracket Pairs Problem + +To solve this problem, we need to use a hash map to store the key-value pairs from the knowledge array. Then, we can iterate through the string `s` and build the resulting string by replacing the keys within brackets with their corresponding values from the hash map. + +### Approach + +1. Create a hash map from the knowledge array. +2. Initialize a result string. +3. Traverse the string `s`: + - If we encounter a '(', start collecting the key until we find a ')'. + - Replace the key with its value from the hash map, or '?' if the key is not found. +4. Continue until the entire string is processed. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + string evaluate(string s, vector>& knowledge) { + unordered_map map; + for (auto& pair : knowledge) { + map[pair[0]] = pair[1]; + } + + string result; + int i = 0; + while (i < s.size()) { + if (s[i] == '(') { + int j = i + 1; + while (s[j] != ')') j++; + string key = s.substr(i + 1, j - i - 1); + result += map.count(key) ? map[key] : "?"; + i = j + 1; + } else { + result += s[i++]; + } + } + return result; + } +}; +``` + + + + + +```java +class Solution { + public String evaluate(String s, List> knowledge) { + Map map = new HashMap<>(); + for (List pair : knowledge) { + map.put(pair.get(0), pair.get(1)); + } + + StringBuilder result = new StringBuilder(); + int i = 0; + while (i < s.length()) { + if (s.charAt(i) == '(') { + int j = i + 1; + while (s.charAt(j) != ')') j++; + String key = s.substring(i + 1, j); + result.append(map.getOrDefault(key, "?")); + i = j + 1; + } else { + result.append(s.charAt(i++)); + } + } + return result.toString(); + } +} +``` + + + + + +```python +class Solution: + def evaluate(self, s: str, knowledge: List[List[str]]) -> str: + knowledge_dict = {key: value for key, value in knowledge} + result = [] + i = 0 + while i < len(s): + if s[i] == '(': + j = i + 1 + while s[j] != ')': + j += 1 + key = s[i + 1:j] + result.append(knowledge_dict.get(key, "?")) + i = j + 1 + else: + result.append(s[i]) + i += 1 + return ''.join(result) +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: $O(n + m)$, where `n` is the length of the string `s` and `m` is the number of key-value pairs in `knowledge`. +- **Space Complexity**: $O(m)$, for storing the hash map of knowledge. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
+``` \ No newline at end of file diff --git a/solutions/lc-solutions/1800-1899/1816-Truncate-Sentence.md b/solutions/lc-solutions/1800-1899/1816-Truncate-Sentence.md new file mode 100644 index 0000000..b1a0550 --- /dev/null +++ b/solutions/lc-solutions/1800-1899/1816-Truncate-Sentence.md @@ -0,0 +1,81 @@ +--- +id: truncate-sentence +title: Truncate Sentence +sidebar_label: 1816-Truncate-Sentence +tags: +- String +- Easy +description: "Given a sentence and a number k, truncate the sentence to the first k words." +--- + +## Problem + +You are given a sentence `s` and an integer `k`. You need to truncate the sentence such that it contains only the first `k` words. A word is defined as a substring consisting of non-space characters only. + +### Examples + +**Example 1:** + +**Input:** `s = "Hello how are you Contestant", k = 4` +**Output:** `"Hello how are you"` + +**Example 2:** + +**Input:** `s = "What is the solution to this problem", k = 4` +**Output:** `"What is the solution"` + +**Example 3:** + +**Input:** `s = "chopper is not a tanuki", k = 5` +**Output:** `"chopper is not a tanuki"` + +### Constraints + +- `1 <= s.length <= 500` +- `k` is in the range `[1, the number of words in s]` +- `s` consists of only lowercase and uppercase English letters and spaces. +- The words in `s` are separated by a single space. +- There are no leading or trailing spaces. + +--- + +## Approach + +To solve this problem, we can follow a straightforward approach: + +1. Split the sentence `s` into a list of words. +2. Extract the first `k` words from this list. +3. Join these `k` words back into a string with spaces. + +### Solution + +#### Python + +```python +class Solution: + def truncateSentence(self, s: str, k: int) -> str: + # Split the sentence into words + words = s.split() + # Get the first k words + truncated_words = words[:k] + # Join the first k words into a string + truncated_sentence = " ".join(truncated_words) + return truncated_sentence +``` + +### Explanation + +1. **Split the sentence**: We use the `split()` method to split the sentence into a list of words. +2. **Extract first `k` words**: We use list slicing `[:k]` to get the first `k` words. +3. **Join the words**: We use the `join()` method to join the first `k` words into a single string separated by spaces. + +### Complexity Analysis + +**Time Complexity:** O(n) +> Reason: Splitting the sentence and joining the words both take linear time, where `n` is the length of the sentence. + +**Space Complexity:** O(n) +> Reason: We store the words of the sentence in a list and then the truncated sentence, both of which take linear space relative to the input size. + +### References +**LeetCode Problem:** Truncate Sentence diff --git a/solutions/lc-solutions/1800-1899/1823-find-the-winner-of-the-circular-game.md b/solutions/lc-solutions/1800-1899/1823-find-the-winner-of-the-circular-game.md new file mode 100644 index 0000000..da42d04 --- /dev/null +++ b/solutions/lc-solutions/1800-1899/1823-find-the-winner-of-the-circular-game.md @@ -0,0 +1,93 @@ +--- +id: find-the-winner-of-the-circular-game +title: Find The Winner Of The Circular Game +sidebar_label: 1823 Find The Winner Of The Circular Game +tags: + - Array + - Math + - Recursion + - Queue + - Simulation + +description: "This is a solution to the Find the Winner of the Circular Game problem on LeetCode." + +sidebar_position: 1823 +--- + +## Problem Description +There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the friend , and moving clockwise from the nth friend brings you to the 1st friend. + +### Examples + +**Example 1:** + +``` +Input: n = 5, k = 2 +Output: 3 +Explanation: Here are the steps of the game: +1) Start at friend 1. +2) Count 2 friends clockwise, which are friends 1 and 2. +3) Friend 2 leaves the circle. Next start is friend 3. +4) Count 2 friends clockwise, which are friends 3 and 4. +5) Friend 4 leaves the circle. Next start is friend 5. +6) Count 2 friends clockwise, which are friends 5 and 1. +7) Friend 1 leaves the circle. Next start is friend 3. +8) Count 2 friends clockwise, which are friends 3 and 5. +9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner. +``` + +**Example 2:** +``` +Input: n = 6, k = 5 +Output: 1 +Explanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1. +``` + +### Constraints + +- `1 <= k <= n <= 500` + +## Solution for Find the Winner of the Circular Game +### Approach + +1. **Initialization**: + - Initialize a variable `winner` to keep track of the winner found. + +2. **Iterate Through the Numbers**: + - Use a loop to iterate through each element. + - Apply the formula to find the new winner. + +3. **Return the Result**: + - After iterating through all elements, return the value of `winner` as the result. + + +#### Complexity Analysis: + +- **Time Complexity:** $O(n)$, because of iterating through the elements, +- **Space Complexity:** $O(1)$ + + +#### C++ Solution + +```cpp +class Solution { +public: + int findTheWinner(int n, int k) { + int winner = 1; + for(int i = 1; i < n; i++){ + winner = (winner + k - 1) % (i + 1) + 1; + } + return winner; + } +}; + +``` + + + + +## References + +- **LeetCode Problem**: [Find the Winner of the Circular Game](https://leetcode.com/problems/find-the-winner-of-the-circular-game) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/find-the-winner-of-the-circular-game) diff --git a/solutions/lc-solutions/1800-1899/1832-Check-if-the-sentence-is-panagram.md b/solutions/lc-solutions/1800-1899/1832-Check-if-the-sentence-is-panagram.md new file mode 100644 index 0000000..c8db1ba --- /dev/null +++ b/solutions/lc-solutions/1800-1899/1832-Check-if-the-sentence-is-panagram.md @@ -0,0 +1,277 @@ +--- +id: check-if-the-sentence-is-pangram +title: Check if the sentence is Pangram +sidebar_label: 1832. Check if the sentence is Pangram + +tags: +- vector +- string +- pangram + +description: "This is a solution to the Check if the sentence is Pangram problem on LeetCode." +--- + +## Problem Description +A **pangram** is a sentence where every letter of the English alphabet appears at least once. +Given a string `sentence` containing only lowercase English letters, return `true` *if `sentence` is a **pangram**, or `false` otherwise*. +### Examples + +**Example 1:** + +``` +Input: sentence = "thequickbrownfoxjumpsoverthelazydog" +Output: true +Explanation: sentence contains at least one of every letter of the English alphabet. +``` + +**Example 2:** +``` +Input: sentence = "leetcode" +Output: false +``` + + +### Constraints +- `1 <= sentence.length <= 1000` +- `sentence` consists of lowercase English letters. + + +## Solution for Check if the sentence is Pangram +### Approach +#### Brute Force +- Create a set of all 26 letters of the English alphabet. +- Iterate through each character in the sentence. +- Remove each character from the set if it exists in the set. +- After processing the entire sentence, check if the set is empty. If it is empty, it means every letter was found at least once in the sentence. + +**Complexity** +- **Time Complexity:** O(n), where n is the length of the sentence. This is because we need to iterate through each character of the sentence once. +- **Space Complexity:** O(1), since the size of the alphabet set is fixed (26 letters). + +**Corner Cases:** +- An empty string should immediately return `false`. +- A string shorter than 26 characters cannot be a pangram. +- Strings with all letters but mixed with additional characters should still return `true`. + +**Recursive function:** +```python +def is_pangram_brute_force(sentence): + # Define the set of all alphabet letters + alphabet_set = set("abcdefghijklmnopqrstuvwxyz") + + # Iterate through each character in the sentence + for char in sentence: + # Remove the character from the alphabet set + alphabet_set.discard(char) + # If the set is empty, we found all the letters + if not alphabet_set: + return True + + # Check if the alphabet set is empty + return len(alphabet_set) == 0 + +# Test cases +print(is_pangram_brute_force("thequickbrownfoxjumpsoverthelazydog")) # Output: True +print(is_pangram_brute_force("leetcode")) # Output: False +``` + +#### Optimized Approach +- Use a set to keep track of unique characters in the sentence. +- Iterate through each character in the sentence and add it to the set. +- After processing the entire sentence, check if the set contains 26 unique characters. + +**Complexity:** +- Time Complexity: `O(n)`, where n is the length of the sentence. This is because we need to iterate through each character of the sentence once. +- Space Complexity: `O(1)`, since the maximum size of the set is 26 (the number of unique letters in the English alphabet). + +**Corner Cases:** +- Similar to the brute force approach: an empty string, a string shorter than 26 characters, and strings with all letters plus additional characters should be handled correctly. + +**Optimized Solution:** + +```python +def is_pangram_optimized(sentence): + # Use a set to store unique characters + seen_characters = set() + + # Iterate through each character in the sentence + for char in sentence: + # Add the character to the set + seen_characters.add(char) + # If the set size is 26, it means we have seen all letters + if len(seen_characters) == 26: + return True + + # Check if we have 26 unique characters + return len(seen_characters) == 26 + +# Test cases +print(is_pangram_optimized("thequickbrownfoxjumpsoverthelazydog")) # Output: True +print(is_pangram_optimized("leetcode")) # Output: False +``` + + + + +#### Implementation + + ```jsx live + function Solution(string) { + var checkIfPangram = function(sentence) { + // Use a set to store unique characters + const seenCharacters = new Set(); + + // Iterate through each character in the sentence + for (const char of sentence) { + // Add the character to the set + seenCharacters.add(char); + // If the set size is 26, it means we have seen all letters + if (seenCharacters.size === 26) { + return true; + } + } + + // Check if we have 26 unique characters + return seenCharacters.size === 26; + }; + + const input = "thequickbrownfoxjumpsoverthelazydog"; + const output = checkIfPangram(input); + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + ## Code in Different Languages + + + + + + + ```javascript + /** + * @param {string} sentence + * @return {boolean} + */ + var checkIfPangram = function(sentence) { + const seenCharacters = new Set(); + + for (const char of sentence) { + seenCharacters.add(char); + if (seenCharacters.size === 26) { + return true; + } + } + + return seenCharacters.size === 26; + }; + ``` + + + + + + + ```typescript + function checkIfPangram(sentence: string): boolean { + const seenCharacters: Set = new Set(); + + for (const char of sentence) { + seenCharacters.add(char); + if (seenCharacters.size === 26) { + return true; + } + } + + return seenCharacters.size === 26; + }; + ``` + + + + + + + ```python + class Solution(object): + def checkIfPangram(self, sentence): + """ + :type sentence: str + :rtype: bool + """ + seen_characters = set() + + for char in sentence: + seen_characters.add(char) + if len(seen_characters) == 26: + return True + + return len(seen_characters) == 26 + ``` + + + + + + + ```java + class Solution { + public boolean checkIfPangram(String sentence) { + Set seenCharacters = new HashSet<>(); + + for (char c : sentence.toCharArray()) { + seenCharacters.add(c); + if (seenCharacters.size() == 26) { + return true; + } + } + + return seenCharacters.size() == 26; + } + } + ``` + + + + + + + ```cpp + class Solution { + public: + bool checkIfPangram(string sentence) { + unordered_set seenCharacters; + + for (char c : sentence) { + seenCharacters.insert(c); + if (seenCharacters.size() == 26) { + return true; + } + } + + return seenCharacters.size() == 26; + } + }; + ``` + + + + +
+
+ +## References + +- **LeetCode Problem**: [Check if the sentence is Pangram](https://leetcode.com/problems/check-if-the-sentence-is-pangram/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/check-if-the-sentence-is-pangram/solutions/) \ No newline at end of file diff --git a/solutions/lc-solutions/1800-1899/1838-frequency-of-the-most-frequent-element.md b/solutions/lc-solutions/1800-1899/1838-frequency-of-the-most-frequent-element.md new file mode 100644 index 0000000..eddf022 --- /dev/null +++ b/solutions/lc-solutions/1800-1899/1838-frequency-of-the-most-frequent-element.md @@ -0,0 +1,255 @@ +--- +id: frequency-of-the-most-frequent-element +title: Frequency of the Most Frequent Element +sidebar_label: 1838 -Frequency of the Most Frequent Element +tags: +- Array +- Binary Search +- Greedy +- Sliding Window +- Sorting +- Prefix Sum + +description: "This is a solution to the Frequency of the Most Frequent Element problem on LeetCode." +--- + +## Problem Description +The frequency of an element is the number of times it occurs in an array. + +You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1. + +Return the maximum possible frequency of an element after performing at most k operations. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,4], k = 5 +Output: 3 +Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4]. +4 has a frequency of 3. + +``` + +**Example 2:** +``` +Input: nums = [1,4,8,13], k = 5 +Output: 2 +Explanation: There are multiple optimal solutions: +- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2. +- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2. +- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2. +``` + +**Example 3:** +``` +Input: nums = [3,9,6], k = 2 +Output: 1 +``` + +### Constraints + +- `1 <= nums.length <= 10^5` +- `1 <= nums[i] <= 10^5` +- `1 <= k <= 10^5` +## Solution for Frequency of the Most Frequent Element Problem +### Approach +To determine the amount needed to convert the current sliding window [1, 2, 4] into [4, 4, 4], we use the formula (num_rightΓ—(rightβˆ’left+1))βˆ’total, where num_right is the value we want to fill the window with (in this case, 4), right and left are the indices defining the window, and total is the sum of the current window. If this amount is within the budget k, i.e., (num_rightΓ—(rightβˆ’left+1))βˆ’total≀k, then it is possible to achieve the desired frequency with a cost equal to the window length (right - left + 1). + +#### Steps +##### Sorting: +- Sorting the array helps to bring similar values closer together. This makes it easier to increase the frequency of a number by making other numbers in the subarray equal to it with minimal increments. +##### Sliding Window: + +- The sliding window technique allows us to consider subarrays of the sorted array incrementally. +- We maintain a window [i, j] where j is the current end of the window, and i is the start. +##### Sum Calculation: +- We keep a running sum of the elements within the window. +- For each new element added to the window (i.e., extending j), we calculate the total number of operations needed to make all elements in the window equal to the current element nums[j]. +- This is checked using the formula (jβˆ’i+1)Γ—nums[j]βˆ’sum. If this value is greater than k, it means we need more than k operations to make all elements equal to nums[j]. +##### Adjusting the Window: + +- If the current window requires more than k operations, we shrink the window from the left by incrementing i until the condition is satisfied. +- If the condition is satisfied, it means the current window can be made equal with at most k increments, and we update the maximum frequency (maxFreq) with the size of the current window. +##### Result: +- The maximum frequency (maxFreq) found during the iterations will be the result. + + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function maxFrequency(nums, k) { + nums.sort((a, b) => a - b); + let maxFreq = 1; + let i = 0; + let sum = 0; + + for (let j = 0; j < nums.length; j++) { + sum += nums[j]; + while ((j - i + 1) * nums[j] - sum > k) { + sum -= nums[i]; + i++; + } + maxFreq = Math.max(maxFreq, j - i + 1); + } + + return maxFreq; + } + const input = [1, 2 ,4]; + const k = 5 + const output = maxFrequency(input , k) ; + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(nlogn) $ because of sorting, where n is the size of array + - Space Complexity: $ O(1) $ + + ## Code in Different Languages + + + + ```javascript + function maxFrequency(nums, k) { + nums.sort((a, b) => a - b); + let maxFreq = 1; + let i = 0; + let sum = 0; + + for (let j = 0; j < nums.length; j++) { + sum += nums[j]; + while ((j - i + 1) * nums[j] - sum > k) { + sum -= nums[i]; + i++; + } + maxFreq = Math.max(maxFreq, j - i + 1); + } + + return maxFreq; +} + ``` + + + + + ```typescript + function maxFrequency(nums: number[], k: number): number { + nums.sort((a, b) => a - b); + let maxFreq = 1; + let i = 0; + let sum = 0; + + for (let j = 0; j < nums.length; j++) { + sum += nums[j]; + while ((j - i + 1) * nums[j] - sum > k) { + sum -= nums[i]; + i++; + } + maxFreq = Math.max(maxFreq, j - i + 1); + } + + return maxFreq; +} + + ``` + + + + ```python + class Solution: + def maxFrequency(self, nums, k): + nums.sort() + maxFreq = 1 + i = 0 + sum = 0 + + for j in range(len(nums)): + sum += nums[j] + while (j - i + 1) * nums[j] - sum > k: + sum -= nums[i] + i += 1 + maxFreq = max(maxFreq, j - i + 1) + + return maxFreq + + ``` + + + + + ```java + import java.util.Arrays; + +public class Solution { + public int maxFrequency(int[] nums, int k) { + Arrays.sort(nums); + long maxFreq = 1; + long i = 0; + long sum = 0; + + for (long j = 0; j < nums.length; j++) { + sum += nums[(int) j]; + while ((j - i + 1) * nums[(int) j] - sum > k) { + sum -= nums[(int) i]; + i++; + } + maxFreq = Math.max(maxFreq, j - i + 1); + } + + return (int) maxFreq; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + int maxFrequency(vector& nums, int k) { + sort(nums.begin(), nums.end()); + long maxFreq = 1; + long i = 0; + long j = 0; + long long sum = 0; + + while (j < nums.size()) { + sum += nums[j]; + while ((j - i + 1) * nums[j] - sum > k) sum -= nums[i++]; + maxFreq =max(maxFreq, j-i+1); + j++; + } + return maxFreq; + } +}; + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Frequency of the Most Frequent Element](https://leetcode.com/problems/frequency-of-the-most-frequent-element/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/frequency-of-the-most-frequent-element/solution) + diff --git a/solutions/lc-solutions/1800-1899/1839-longest-substring-of-all-vowels-in-order.md b/solutions/lc-solutions/1800-1899/1839-longest-substring-of-all-vowels-in-order.md new file mode 100644 index 0000000..15c130f --- /dev/null +++ b/solutions/lc-solutions/1800-1899/1839-longest-substring-of-all-vowels-in-order.md @@ -0,0 +1,292 @@ +--- +id: longest-substring-of-all-vowels-in-order +title: Longest Substring Of All Vowels in Order +sidebar_label: 1839 - Longest Substring Of All Vowels in Order +tags: +- String +- Sliding Window + + +description: "This is a solution to the Longest Substring Of All Vowels in Order problem on LeetCode." +--- + +## Problem Description +A string is considered beautiful if it satisfies the following conditions: + +Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it. +The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before 'i's, etc.). +For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but "uaeio", "aeoiu", and "aaaeeeooo" are not beautiful. + +Given a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0. + +A substring is a contiguous sequence of characters in a string. + +### Examples + +**Example 1:** + +``` +Input: word = "aeiaaioaaaaeiiiiouuuooaauuaeiu" +Output: 13 +Explanation: The longest beautiful substring in word is "aaaaeiiiiouuu" of length 13. + +``` + +**Example 2:** +``` +Input: word = "aeeeiiiioooauuuaeiou" +Output: 5 +Explanation: The longest beautiful substring in word is "aeiou" of length 5. +``` + +### Constraints + +- `1 <= s.length <= 10^5` + +## Solution for Longest Substring Of All Vowels in Order Problem +### Approach + +1. **Initialization**: + - Use a map `mp` to assign numeric values to each vowel based on their alphabetical order: `'a'` = 1, `'e'` = 2, `'i'` = 3, `'o'` = 4, `'u'` = 5. + - Initialize variables `i` to iterate through the string and `len` to store the maximum length of the valid substring found. + +2. **Iterate Through the String**: + - Start iterating from the beginning of the string `word`. + - Whenever encountering the first character `'a'`, begin checking for the sequence of vowels `'a'`, `'e'`, `'i'`, `'o'`, `'u'`. + - Use a set `st` to track which vowels have been seen in the current sequence. + +3. **Check for Valid Substring**: + - If the current character is `'a'`, add it to the set `st`. + - Continue iterating through the string while the next character maintains the order defined by `mp` (i.e., `mp[word[i]] <= mp[word[i + 1]]`) and add each vowel encountered to `st`. + - If `st` contains all five vowels after processing a valid substring, update `len` with the maximum length found. + +4. **Return the Result**: + - After iterating through the entire string, `len` will hold the length of the longest valid substring found. If no such substring exists where all five vowels are present in order, return 0. + + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function longestBeautifulSubstring(word) { + const mp = { 'a': 1, 'e': 2, 'i': 3, 'o': 4, 'u': 5 }; + let i = 0; + let len = 0; + + while (i < word.length) { + const start = i; + const st = new Set(); + if (word[i] === 'a') { + st.add(word[i]); + while (i < word.length - 1 && mp[word[i]] <= mp[word[i + 1]]) { + i++; + st.add(word[i]); + } + if (st.size === 5) { + len = Math.max(len, i - start + 1); + } + } + i++; + } + return len; + } + const input = "aeiaaioaaaaeiiiiouuuooaauuaeiu" + const output = longestBeautifulSubstring(input) ; + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(nlogn) $ because of sorting, where n is the size of array + - Space Complexity: $ O(n) $ + + ## Code in Different Languages + + + + ```javascript + class Solution { + longestBeautifulSubstring(word) { + const mp = { 'a': 1, 'e': 2, 'i': 3, 'o': 4, 'u': 5 }; + let i = 0; + let len = 0; + + while (i < word.length) { + const start = i; + const st = new Set(); + if (word[i] === 'a') { + st.add(word[i]); + while (i < word.length - 1 && mp[word[i]] <= mp[word[i + 1]]) { + i++; + st.add(word[i]); + } + if (st.size === 5) { + len = Math.max(len, i - start + 1); + } + } + i++; + } + return len; + } +} + + ``` + + + + + ```typescript + class Solution { + longestBeautifulSubstring(word: string): number { + const mp: { [key: string]: number } = { 'a': 1, 'e': 2, 'i': 3, 'o': 4, 'u': 5 }; + let i = 0; + let len = 0; + + while (i < word.length) { + const start = i; + const st = new Set(); + if (word[i] === 'a') { + st.add(word[i]); + while (i < word.length - 1 && mp[word[i]] <= mp[word[i + 1]]) { + i++; + st.add(word[i]); + } + if (st.size === 5) { + len = Math.max(len, i - start + 1); + } + } + i++; + } + return len; + } +} + + ``` + + + + ```python + class Solution: + def longestBeautifulSubstring(self, word: str) -> int: + mp = {'a': 1, 'e': 2, 'i': 3, 'o': 4, 'u': 5} + i = 0 + len_ = 0 + + while i < len(word): + start = i + st = set() + if word[i] == 'a': + st.add(word[i]) + while i < len(word) - 1 and mp[word[i]] <= mp[word[i + 1]]: + i += 1 + st.add(word[i]) + if len(st) == 5: + len_ = max(len_, i - start + 1) + i += 1 + return len_ + + ``` + + + + + ```java + import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +class Solution { + public int longestBeautifulSubstring(String word) { + Map mp = new HashMap<>(); + mp.put('a', 1); + mp.put('e', 2); + mp.put('i', 3); + mp.put('o', 4); + mp.put('u', 5); + + int i = 0; + int len = 0; + + while (i < word.length()) { + int start = i; + Set st = new HashSet<>(); + if (word.charAt(i) == 'a') { + st.add(word.charAt(i)); + while (i < word.length() - 1 && mp.get(word.charAt(i)) <= mp.get(word.charAt(i + 1))) { + i++; + st.add(word.charAt(i)); + } + if (st.size() == 5) { + len = Math.max(len, i - start + 1); + } + } + i++; + } + return len; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + int longestBeautifulSubstring(string word) { + map mp; + mp['a'] = 1; + mp['e'] = 2; + mp['i'] = 3; + mp['o'] = 4; + mp['u'] = 5; + + int i = 0; + int len = 0; + while (i < word.size()) { + int start = i; + set st; + if (word[i] == 'a') { + st.insert(word[i]); + while (i < word.size() - 1 && (mp[word[i]] <= mp[word[i + 1]])) { + i++; + st.insert(word[i]); + } + if (st.size() == 5) { + len = max(len, i - start + 1); + } + } + i++; + } + return len; + } +}; + + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Longest Substring Of All Vowels in Order](https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/solution) + diff --git a/solutions/lc-solutions/1800-1899/_category_.json b/solutions/lc-solutions/1800-1899/_category_.json new file mode 100644 index 0000000..e94fae8 --- /dev/null +++ b/solutions/lc-solutions/1800-1899/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "1800-1899", + "position": 20, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (1800 - 1899)" + } +} diff --git a/solutions/lc-solutions/1900-1999/1902-depth-of-bst-given-insertion-order.md b/solutions/lc-solutions/1900-1999/1902-depth-of-bst-given-insertion-order.md new file mode 100644 index 0000000..539c975 --- /dev/null +++ b/solutions/lc-solutions/1900-1999/1902-depth-of-bst-given-insertion-order.md @@ -0,0 +1,281 @@ +--- +id: depth-of-bst-given-insertion-order +title: Depth of BST Given Insertion Order +sidebar_label: 1902-depth-of-bst-given-insertion-order +tags: +- Binary Search Tree +- Tree +- Binary Tree +- Ordered Set +description: "This document provides solutions for depth-of-bst-given-insertion-order." +--- + +## Problem + +You are given an array order which is a permutation of integers from 1 to n. This array represents the sequence in which nodes are inserted into a binary search tree (BST). The properties of a BST are such that: + + 1- The left subtree of a node contains only nodes with keys less than + the node's key. + 2- The right subtree of a node contains only nodes with keys greater + than the node's key. + 3- Both the left and right subtrees must also be binary search trees. + +The first element of order is the root of the BST. All subsequent elements are inserted one by one, at the correct position to maintain the BST property. You need to find the depth of this binary search tree, which is the number of nodes along the longest path from the root node down to the farthest leaf node. + +### Examples + +**Example 1:** + +Input: order = [2,1,4,3] +Output: 3 +Explanation: The binary search tree has a depth of 3 with path `2->3->4`. + +**Example 2:** + +Input: order = [2,1,3,4] +Output: 3 +Explanation: The binary search tree has a depth of 3 with path `2->3->4`. + +**Example 3:** + +Input: order = [1,2,3,4] +Output: 4 +Explanation: The binary search tree has a depth of 4 with path `1->2->3->4`. + +### Constraints + +- `n == order.length` +- `1 <= n <= 105` +- order is a permutation of integers between `1` and `n`. + +--- + +## Approach + +1. Initialization: We initiate the SortedDict with a mapping from 0 to + depth 0, infinity to depth 0, and the first element of the order array (which is the root node) to depth 1. Both 0 and infinity are sentinel values that assist in determining the depth of the subsequent nodes. + + - `sd = SortedDict({0: 0, inf: 0, order[0]: 1})` + +2. Iterate through order: After the root node is added, we iterate + through the remaining numbers in order array. For each number (node) v, we want to find where it fits in the tree and calculate its depth. + + - `for v in order[1:]: # Skip the first element as it is the root` + +3. Binary Search for Depth: For each number, we perform a binary search + (bisect_left(v)) on the SortedDict keys to find the closest smaller value (the predecessor or lower) and the direct successor (higher). These are the two possible parents in the BST. + + - `lower = sd.bisect_left(v) - 1` + - `higher = lower + 1` + +4. Calculate the Depth of the Node: The depth of the new node we are + inserting is one more than the maximum depth between its potential parents (lower and higher), this is because in the BST the new node will become the child of one of these nodes. + + - `depth = 1 + max(sd.values()[lower], sd.values()[higher])` + +5. Update the SortedDict and ans: Insert the new node v with its + calculated depth into the SortedDict. Also, update ans with the new depth if it is greater than the current maximum depth found. + + - `ans = max(ans, depth)` + - `sd[v] = depth` + +6. Return the Maximum Depth: Once we have inserted all the elements, + ans will hold the maximum depth of the tree, which we then return. + + - `return ans` + +## Solution for Depth of BST Given Insertion Order + +### Java Solution + +```java +class Solution { + + public int maxDepthBST(int[] order) { + + // TreeMap to store the nodes with their corresponding depths + + TreeMap depthMap = new TreeMap<>(); + + // Dummy nodes to handle edge cases + + depthMap.put(0, 0); // Represents the leftmost boundary + + depthMap.put(Integer.MAX_VALUE, 0); // Represents the rightmost boundary + + // Initial case: the root node has a depth of 1 + + depthMap.put(order[0], 1); + + // The starting maximum depth is the depth of the root, which is 1 + + int maxDepth = 1; + + + // Iterate over the remaining nodes in the "order" array + + for (int i = 1; i < order.length; ++i) { + + int currentValue = order[i]; + + // Find the immediate lower and higher entries in the TreeMap + + Map.Entry lowerEntry = depthMap.lowerEntry(currentValue); + + Map.Entry higherEntry = depthMap.higherEntry(currentValue); + + // Compute the depth of the current node as one plus the maximum of the depths of lower and higher entry + + int currentDepth = 1 + Math.max(lowerEntry.getValue(), higherEntry.getValue()); + + // Update the maximum depth found so far + + maxDepth = Math.max(maxDepth, currentDepth); + + // Insert the current value and its depth into the TreeMap + + depthMap.put(currentValue, currentDepth); + + } + + // Return the maximum depth found + + return maxDepth; + + } + +} +``` +### C++ solution + +```cpp +#include + +#include + +#include + + +class Solution { + +public: + + int maxDepthBST(std::vector& order) { + + // TreeMap to store the nodes with their corresponding depths + + std::map depthMap; + + // Dummy nodes to handle edge cases + + depthMap[0] = 0; // Represents the leftmost boundary + + depthMap[INT_MAX] = 0; // Represents the rightmost boundary + + // Initial case: the root node has a depth of 1 + + depthMap[order[0]] = 1; + + // The starting maximum depth is the depth of the root, which is 1 + + int maxDepth = 1; + + + // Iterate over the remaining nodes in the "order" vector + + for (size_t i = 1; i < order.size(); ++i) { + + int currentValue = order[i]; + + // Find the immediate lower and higher entries in the map + + auto lowerEntry = --depthMap.lower_bound(currentValue); + + auto higherEntry = depthMap.upper_bound(currentValue); + + // Compute the depth of the current node as one plus the maximum of the depths of lower and higher entry + + int currentDepth = 1 + std::max(lowerEntry->second, higherEntry->second); + + // Update the maximum depth found so far + + maxDepth = std::max(maxDepth, currentDepth); + + // Insert the current value and its depth into the map + + depthMap[currentValue] = currentDepth; + + } + + // Return the maximum depth found + + return maxDepth; + + } + +}; +``` +### Python Solution + +```python +from sortedcontainers import SortedDict +from typing import List +class Solution: + + def maxDepthBST(self, order: List[int]) -> int: + + # Create a SortedDict initialized with border elements with depth 0 and + + # the root of BST with depth 1 + + sorted_dict = SortedDict({0: 0, float('inf'): 0, order[0]: 1}) + + + + # Initialize answer with the depth of the first element (root), which is 1 + + max_depth = 1 + + + + # Iterate over the remaining elements in the order list starting from the second + + for value in order[1:]: + + # Find the keys that would be immediate predecessors and successors of the value + + lower_index = sorted_dict.bisect_left(value) - 1 + + higher_index = lower_index + 1 + + + + # The new depth is calculated by 1 plus the max depth of immediate lower and higher keys + + depth = 1 + max(sorted_dict.peekitem(lower_index)[1], sorted_dict.peekitem(higher_index)[1]) + + + + # Update the answer if the new calculated depth is greater than the previous max depth + + max_depth = max(max_depth, depth) + + + + # Insert the current value with its calculated depth into the sorted dictionary + + sorted_dict[value] = depth + + + + # Finally, return the maximum depth of the binary search tree + + return max_depth +``` +### Complexity Analysis +**Time Complexity:** $O((n - 1) * log k)$ + +**Space Complexity:** $O(n)$ + +### References +**LeetCode Problem:** Depth of BST Given Insertion Order \ No newline at end of file diff --git a/solutions/lc-solutions/1900-1999/1910-remove-all-occurences-of-a-substring.md b/solutions/lc-solutions/1900-1999/1910-remove-all-occurences-of-a-substring.md new file mode 100644 index 0000000..6b67d59 --- /dev/null +++ b/solutions/lc-solutions/1900-1999/1910-remove-all-occurences-of-a-substring.md @@ -0,0 +1,128 @@ +--- +id: remove-all-occurences-of-a-substring +title: Remove All Occurences of a Substring +sidebar_label: 1910-Remove All Occurences of a Substring +tags: + - String + +description: "This is a solution to Remove All Occurences of a Substring in leetcode " +--- + +## Problem Description + +Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: + +1. Find the leftmost occurrence of the substring part and remove it from s. +Return s after removing all occurrences of part. + +A substring is a contiguous sequence of characters in a string. + + +### Examples + +**Example 1:** + +``` +Input: s = "daabcbaabcbc", part = "abc" +Output: "dab" +Explanation: The following operations are done: +- s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc". +- s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc". +- s = "dababc", remove "abc" starting at index 3, so s = "dab". +Now s has no occurrences of "abc". + +``` +**Example 2:** +``` +Input: s = "axxxxyyyyb", part = "xy" +Output: "ab" +Explanation: The following operations are done: +- s = "axxxxyyyyb", remove "xy" starting at index 4 so s = "axxxyyyb". +- s = "axxxyyyb", remove "xy" starting at index 3 so s = "axxyyb". +- s = "axxyyb", remove "xy" starting at index 2 so s = "axyb". +- s = "axyb", remove "xy" starting at index 1 so s = "ab". +Now s has no occurrences of "xy". + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(n)$ + +*** Space Complexity:** $O(n)$ + +### Constraints + +- `1 <= s.length <= 1000` +- `1 <= part.length <= 1000` +- `s`​​​​​​ and `part` consists of lowercase English letters. + + +### Solution +## Approach +To solve the problem of removing all occurrences of the substring part from the string s, we use an iterative approach. We repeatedly search for the leftmost occurrence of part within s and remove it. This process continues until part no longer appears in s. + +We start by initializing our search at the beginning of the string. In each iteration, we find the first occurrence of part using a search function (like find in C++ or the in operator in Python). Once we locate part, we remove it by slicing the string to exclude the found substring. We then reset our search position to the start of the modified string to ensure all overlapping occurrences are also removed. The process is repeated until the string s no longer contains the substring part. Finally, we return the modified string s. + +This approach guarantees that all instances of part are removed, even if they overlap, ensuring the final string is free of the specified substring. + +## Code in Different Languages + + + + + +```cpp + +class Solution { +public: + std::string removeOccurrences(std::string s, std::string part) { + size_t pos = 0; + while ((pos = s.find(part)) != std::string::npos) { + s.erase(pos, part.length()); + } + return s; + } +}; + + +``` + + + + +```java +class Solution { + public String removeOccurrences(String s, String part) { + for(int i=0;i<=s.length()-part.length();){ + String ch=s.substring(i,i+part.length()); + if(ch.equals(part)){ + s=s.substring(0,i)+s.substring(i+part.length()); + //s=s.replace(ch,""); + i=0;} + else + i++; + } + + return s; + } +} +``` + + + + +```python +class Solution: + def removeOccurrences(self, s: str, part: str) -> str: + while part in s: + s = s.replace(part, "", 1) + return s +``` + + + +## References + +- **LeetCode Problem**: [Remove All Occurences of a Substring](https://leetcode.com/problems/remove-all-occurrences-of-a-substring/solutions/) + +- **Solution Link**: [Remove All Occurences of a Substring](https://leetcode.com/problems/remove-all-occurrences-of-a-substring/post-solution/?submissionId=1230096138) diff --git a/solutions/lc-solutions/1900-1999/1920-build-array-from-permutation.md b/solutions/lc-solutions/1900-1999/1920-build-array-from-permutation.md new file mode 100644 index 0000000..7fca07b --- /dev/null +++ b/solutions/lc-solutions/1900-1999/1920-build-array-from-permutation.md @@ -0,0 +1,112 @@ +--- +id: build-array-from-permutation +title: Build Array From Permutation +sidebar_label: 1920-Build Array From Permutation +tags: + - Array + - Simulation + +description: "This is a solution to the build array from permutation in a string in leetcode" +--- + +## Problem Description + +Given a zero-based permutation nums (0-indexed), build an array ans of the same length where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it. + +A zero-based permutation nums is an array of distinct integers from `0` to `nums.length - 1` (inclusive). + + +### Examples + +**Example 1:** + +``` +Input: nums = [0,2,1,5,3,4] +Output: [0,1,2,4,5,3] +Explanation: The array ans is built as follows: +ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]] + = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]] + = [0,1,2,4,5,3] + +``` +**Example 2:** +``` +Input: nums = [5,0,1,2,3,4] +Output: [4,5,0,1,2,3] +Explanation: The array ans is built as follows: +ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]] + = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]] + = [4,5,0,1,2,3] + ``` +## Complexity Analysis + +*** Time Complexity:** $O(n)$ + +*** Space Complexity:** $O(n)$ + +### Constraints + +- `1 <= nums.length <= 1000` +- `0 <= nums[i] < nums.length` + + + +### Solution +## Approach +The given approach involves constructing a new array ans based on the input array nums, where each element in ans is determined by the value at the index specified by the corresponding element in nums. Specifically, for each index i in nums, the value at ans[i] is set to nums[nums[i]]. To implement this, an empty list ans is initialized, and then a loop iterates over each index i in nums. During each iteration, nums[nums[i]] is appended to ans. This process continues until all elements of nums have been processed, and the resulting list ans is returned. This approach ensures that the new array is built efficiently in a single pass through the input array. +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + std::vector buildArray(std::vector& nums) { + std::vector ans; + for (int i = 0; i < nums.size(); i++) { + ans.push_back(nums[nums[i]]); + } + return ans; + } +}; + +``` + + + + +```java +class Solution { + public List buildArray(List nums) { + List ans = new ArrayList<>(); + for (int i = 0; i < nums.size(); i++) { + ans.add(nums.get(nums.get(i))); + } + return ans; + } +} + +``` + + + + +```python +class Solution: + def buildArray(self, nums: List[int]) -> List[int]: + ans=[] + for i in range(0,len(nums)): + ans.append(nums[nums[i]]) + return ans + +``` + + + +## References + +- **LeetCode Problem**: [Build Array From Permutation](https://leetcode.com/problems/build-array-from-permutation/description/) + +- **Solution Link**: [Build Array From Permutation](https://leetcode.com/problems/build-array-from-permutation/post-solution/?submissionId=1169753613) diff --git a/solutions/lc-solutions/1900-1999/1926-nearest-exit-from-entrance-in-maze.md b/solutions/lc-solutions/1900-1999/1926-nearest-exit-from-entrance-in-maze.md new file mode 100644 index 0000000..ad25acb --- /dev/null +++ b/solutions/lc-solutions/1900-1999/1926-nearest-exit-from-entrance-in-maze.md @@ -0,0 +1,378 @@ +--- +id: nearest-exit-from-entrance-in-maze +title: Nearest Exit from Entrance in Maze +sidebar_label: 1926. Nearest Exit from Entrance in Maze +tags: +- Array +- Breadth-First Search +- Matrix + +description: "This is a solution to the Nearest Exit from Entrance in Maze problem on LeetCode." +--- + +## Problem Description +You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at. + +In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit. + +Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists. +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2021/06/04/nearest1-grid.jpg) +``` +Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2] +Output: 1 +Explanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3]. +Initially, you are at the entrance cell [1,2]. +- You can reach [1,0] by moving 2 steps left. +- You can reach [0,2] by moving 1 step up. +It is impossible to reach [2,3] from the entrance. +Thus, the nearest exit is [0,2], which is 1 step away. +``` + +**Example 2:** +![image](https://assets.leetcode.com/uploads/2021/06/04/nearesr2-grid.jpg) +``` +Input: maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0] +Output: 2 +Explanation: There is 1 exit in this maze at [1,2]. +[1,0] does not count as an exit since it is the entrance cell. +Initially, you are at the entrance cell [1,0]. +- You can reach [1,2] by moving 2 steps right. +Thus, the nearest exit is [1,2], which is 2 steps away. +``` + +**Example 3:** +![image](https://assets.leetcode.com/uploads/2021/06/04/nearest3-grid.jpg) +``` +Input: maze = [[".","+"]], entrance = [0,0] +Output: -1 +Explanation: There are no exits in this maze. +``` + +### Constraints + +- `maze.length == m` +- `maze[i].length == n` +- `1 <= m, n <= 100` +- `maze[i][j] is either '.' or '+'.` +- `entrance.length == 2` +- `0 <= entrancerow < m` +- `0 <= entrancecol < n` +- `entrance will always be an empty cell.` + +## Solution for Nearest Exit from Entrance in Maze Problem +### Intuition + +The problem requires finding the shortest path from an entrance in a maze to the nearest exit. An exit is defined as any cell on the boundary of the maze that is not the entrance itself. The maze consists of open paths represented by `'.'` and walls represented by `'+'`. The goal is to traverse the maze and determine the minimum number of steps required to reach an exit. + +To solve this problem, we can use the Breadth-First Search (BFS) algorithm. BFS is particularly suitable for finding the shortest path in an unweighted grid because it explores all nodes at the present "depth" (or distance) before moving on to nodes at the next depth level. + +### Approach + +1. **Initialize Direction Vectors**: Use direction vectors to facilitate movement in four possible directions (up, right, down, left). + +2. **Mark the Entrance as Visited**: Create a visited matrix to keep track of visited cells. Mark the entrance cell as visited to avoid revisiting it. + +3. **Initialize BFS Queue**: Use a queue to implement the BFS. Enqueue the entrance cell with its coordinates. + +4. **BFS Traversal**: + - While the queue is not empty, iterate through each cell in the current level. + - For each cell, try moving to its neighboring cells (up, right, down, left) using the direction vectors. + - If a neighboring cell is within bounds, is not a wall, and has not been visited, mark it as visited and enqueue it. + - If the neighboring cell is on the boundary of the maze and is not the entrance, return the current distance as it represents the shortest path to an exit. + +5. **Return Result**: If the BFS completes without finding an exit, return -1 to indicate that no exit is reachable. + + + + #### Implementation + ```jsx live + function Solution(arr) { + function nearestExit(maze, entrance) { + const delRow = [-1, 0, 1, 0]; + const delCol = [0, 1, 0, -1]; + const n = maze.length; + const m = maze[0].length; + const vis = Array.from({ length: n }, () => Array(m).fill(0)); + + vis[entrance[0]][entrance[1]] = 1; + + const q = []; + q.push([entrance[0], entrance[1]]); + let move = 0; + + while (q.length > 0) { + let size = q.length; + move++; + + while (size-- > 0) { + const [row, col] = q.shift(); + + for (let i = 0; i < 4; i++) { + const newRow = row + delRow[i]; + const newCol = col + delCol[i]; + + if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < m && maze[newRow][newCol] !== '+' && vis[newRow][newCol] !== 1) { + if (newRow === 0 || newRow === n - 1 || newCol === 0 || newCol === m - 1) return move; + vis[newRow][newCol] = 1; + q.push([newRow, newCol]); + } + } + } + } + return -1; + } + + const input = [["+","+","+"],[".",".","."],["+","+","+"]] + const entrance = [1,0] + const output = nearestExit(input , entrance) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(n*m) $ + - Space Complexity: $ O(n*m) $ + + ## Code in Different Languages + + + + ```javascript + function nearestExit(maze, entrance) { + const delRow = [-1, 0, 1, 0]; + const delCol = [0, 1, 0, -1]; + const n = maze.length; + const m = maze[0].length; + const vis = Array.from({ length: n }, () => Array(m).fill(0)); + + vis[entrance[0]][entrance[1]] = 1; + + const q = []; + q.push([entrance[0], entrance[1]]); + let move = 0; + + while (q.length > 0) { + let size = q.length; + move++; + + while (size-- > 0) { + const [row, col] = q.shift(); + + for (let i = 0; i < 4; i++) { + const newRow = row + delRow[i]; + const newCol = col + delCol[i]; + + if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < m && maze[newRow][newCol] !== '+' && vis[newRow][newCol] !== 1) { + if (newRow === 0 || newRow === n - 1 || newCol === 0 || newCol === m - 1) return move; + vis[newRow][newCol] = 1; + q.push([newRow, newCol]); + } + } + } + } + return -1; +} + + ``` + + + + + ```typescript + function nearestExit(maze: string[][], entrance: number[]): number { + const delRow = [-1, 0, 1, 0]; + const delCol = [0, 1, 0, -1]; + const n = maze.length; + const m = maze[0].length; + const vis: number[][] = Array.from({ length: n }, () => Array(m).fill(0)); + + vis[entrance[0]][entrance[1]] = 1; + + const q: [number, number][] = []; + q.push([entrance[0], entrance[1]]); + let move = 0; + + while (q.length > 0) { + let size = q.length; + move++; + + while (size-- > 0) { + const [row, col] = q.shift()!; + + for (let i = 0; i < 4; i++) { + const newRow = row + delRow[i]; + const newCol = col + delCol[i]; + + if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < m && maze[newRow][newCol] !== '+' && vis[newRow][newCol] !== 1) { + if (newRow === 0 || newRow === n - 1 || newCol === 0 || newCol === m - 1) return move; + vis[newRow][newCol] = 1; + q.push([newRow, newCol]); + } + } + } + } + return -1; +} + + ``` + + + + ```python + from collections import deque + +def nearest_exit(maze, entrance): + delRow = [-1, 0, 1, 0] + delCol = [0, 1, 0, -1] + n = len(maze) + m = len(maze[0]) + vis = [[0] * m for _ in range(n)] + + vis[entrance[0]][entrance[1]] = 1 + + q = deque([(entrance[0], entrance[1])]) + move = 0 + + while q: + size = len(q) + move += 1 + + for _ in range(size): + row, col = q.popleft() + + for i in range(4): + newRow = row + delRow[i] + newCol = col + delCol[i] + + if 0 <= newRow < n and 0 <= newCol < m and maze[newRow][newCol] != '+' and vis[newRow][newCol] != 1: + if newRow == 0 or newRow == n - 1 or newCol == 0 or newCol == m - 1: + return move + vis[newRow][newCol] = 1 + q.append((newRow, newCol)) + + return -1 + + ``` + + + + + ```java + import java.util.*; + +class Solution { + public int nearestExit(char[][] maze, int[] entrance) { + int[] delRow = {-1, 0, 1, 0}; + int[] delCol = {0, 1, 0, -1}; + int n = maze.length, m = maze[0].length; + int[][] vis = new int[n][m]; + + vis[entrance[0]][entrance[1]] = 1; + + Queue q = new LinkedList<>(); + q.add(new int[]{entrance[0], entrance[1]}); + int move = 0; + + while (!q.isEmpty()) { + int size = q.size(); + move++; + + while (size-- > 0) { + int[] current = q.poll(); + int row = current[0]; + int col = current[1]; + + for (int i = 0; i < 4; i++) { + int newRow = row + delRow[i]; + int newCol = col + delCol[i]; + + if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < m && maze[newRow][newCol] != '+' && vis[newRow][newCol] != 1) { + if (newRow == 0 || newRow == n - 1 || newCol == 0 || newCol == m - 1) return move; + vis[newRow][newCol] = 1; + q.add(new int[]{newRow, newCol}); + } + } + } + } + return -1; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + int nearestExit(vector>& maze, vector& entrance) { + int delRow[] = {-1,0,+1,0}; + int delCol[] = {0,1,0,-1}; + + queue>q; + int n = maze.size() , m = maze[0].size(); + vector>vis(n,vector(m,0)); + + vis[entrance[0]][entrance[1]]=1; + + q.push({entrance[0],entrance[1]}); + int move=0; + + while(!q.empty()) + { + int size=q.size(); + move++; + + while(size--) + { + int row=q.front().first; + int col=q.front().second; + q.pop(); + + for(int i=0;i<4;i++) + { + int newRow=row+delRow[i]; + int newCol=col+delCol[i]; + + if(newRow>=0 && newRow=0 && newCol + + +
+
+ +## References + +- **LeetCode Problem**: [Nearest Exit from Entrance in Maze](https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/nearest-exit-from-entrance-in-mazet/solution) + diff --git a/solutions/lc-solutions/1900-1999/1929-concatenation-of-array.md b/solutions/lc-solutions/1900-1999/1929-concatenation-of-array.md new file mode 100644 index 0000000..e144db5 --- /dev/null +++ b/solutions/lc-solutions/1900-1999/1929-concatenation-of-array.md @@ -0,0 +1,178 @@ +--- + +id: concatenation-of-array +title: Concatenation of Array +sidebar_label: 1929-Concatenation of Array +tags: + - Concatenation + - Arrays + - Brute Force + - Optimized + - LeetCode + - Python + - Java + - C++ +description: "This is a solution to the Concatenate Array problem on LeetCode." +sidebar_position: 2 + +--- + +In this tutorial, we will solve the Concatenate Array problem using a simple approach and an optimized approach. We will provide the implementation of the solution in C++, Java, and Python. + +## Problem Description + +Given an integer array `nums` of length `n`, you want to create an array `ans` of length `2n` where `ans[i] == nums[i]` and `ans[i + n] == nums[i]` for `0 <= i < n` (0-indexed). + +Specifically, `ans` is the concatenation of two `nums` arrays. + +Return the array `ans`. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,1] +Output: [1,2,1,1,2,1] +``` + +**Example 2:** + +``` +Input: nums = [1,3,2,1] +Output: [1,3,2,1,1,3,2,1] +``` + +### Constraints + +- `n == nums.length` +- ` 1 <= n <= 1000` + + + +--- + +## Solution for Concatenate Array Problem + +### Approach 1: Simple Concatenation + +The approach is straightforward: iterate through the array `nums` and copy each element twice, once to the first half and once to the second half of the result array `ans`. + + + + + +```cpp +class Solution { +public: + vector getConcatenation(vector& nums) { + int n = nums.size(); + vector ans(2 * n); + for (int i = 0; i < n; ++i) { + ans[i] = nums[i]; + ans[i + n] = nums[i]; + } + return ans; + } +}; +``` + + + + + +```java +class Solution { + public int[] getConcatenation(int[] nums) { + int n = nums.length; + int[] ans = new int[2 * n]; + for (int i = 0; i < n; i++) { + ans[i] = nums[i]; + ans[i + n] = nums[i]; + } + return ans; + } +} +``` + + + + + +```python +class Solution: + def getConcatenation(self, nums: List[int]) -> List[int]: + n = len(nums) + ans = [0] * (2 * n) + for i in range(n): + ans[i] = nums[i] + ans[i + n] = nums[i] + return ans +``` + + + + +### Approach 2: Optimized Concatenation + +An optimized approach for concatenation in some languages can take advantage of built-in functions to concatenate the array directly. + + + + + +```cpp +class Solution { +public: + vector getConcatenation(vector& nums) { + vector ans = nums; + ans.insert(ans.end(), nums.begin(), nums.end()); + return ans; + } +}; +``` + + + + + +```java +import java.util.*; + +class Solution { + public int[] getConcatenation(int[] nums) { + int n = nums.length; + int[] ans = Arrays.copyOf(nums, 2 * n); + System.arraycopy(nums, 0, ans, n, n); + return ans; + } +} +``` + + + + + +```python +class Solution: + def getConcatenation(self, nums: List[int]) -> List[int]: + return nums + nums +``` + + + + +#### Complexity Analysis + +- **Time Complexity:** $O(n)$, where `n` is the length of the input array `nums`. We iterate through the array once. +- **Space Complexity:** $O(n)$, since we are using a new array `ans` of size `2n`. + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/1900-1999/1950-maximum-of-minimum-values-in-all-subarrays.md b/solutions/lc-solutions/1900-1999/1950-maximum-of-minimum-values-in-all-subarrays.md new file mode 100644 index 0000000..14319a3 --- /dev/null +++ b/solutions/lc-solutions/1900-1999/1950-maximum-of-minimum-values-in-all-subarrays.md @@ -0,0 +1,403 @@ +--- +id: maximum-of-minimum-values-in-all-subarrays +title: Maximum of Minimum Values in All Subarrays +sidebar_label: 1950-maximum-of-minimum-values-in-all-subarrays +tags: +- Stack +- Array +- Monotonic Stack +description: "This document provides solutions for maximum of minimum values in all subarrays." +--- + +## Problem + +You are given an integer array nums of size n. You are asked to solve n queries for each integer `i` in the range `0 <= i < n`. + +To solve the ith query: + + 1- Find the minimum value in each possible subarray of size `i + 1` of + the array nums. + 2- Find the maximum of those minimum values. This maximum is the + answer to the query. + +Return a `0-indexed` integer array ans of size n such that `ans[i]` is the answer to the `ith query`. + +A subarray is a contiguous sequence of elements in an array. + +### Examples + +**Example 1:** + +`Input: nums = [0,1,2,4] +Output: [4,2,1,0] +Explanation: +i=0: +- The subarrays of size 1 are [0], [1], [2], [4]. The minimum values are 0, 1, 2, 4. +- The maximum of the minimum values is 4. +i=1: +- The subarrays of size 2 are [0,1], [1,2], [2,4]. The minimum values are 0, 1, 2. +- The maximum of the minimum values is 2. +i=2: +- The subarrays of size 3 are [0,1,2], [1,2,4]. The minimum values are 0, 1. +- The maximum of the minimum values is 1. +i=3: +- There is one subarray of size 4, which is [0,1,2,4]. The minimum value is 0. +- There is only one value, so the maximum is 0.` + +**Example 2:** + +`Input: nums = [10,20,50,10] +Output: [50,20,10,10] +Explanation: +i=0: +- The subarrays of size 1 are [10], [20], [50], [10]. The minimum values are 10, 20, 50, 10. +- The maximum of the minimum values is 50. +i=1: +- The subarrays of size 2 are [10,20], [20,50], [50,10]. The minimum values are 10, 20, 10. +- The maximum of the minimum values is 20. +i=2: +- The subarrays of size 3 are [10,20,50], [20,50,10]. The minimum values are 10, 10. +- The maximum of the minimum values is 10. +i=3: +- There is one subarray of size 4, which is [10,20,50,10]. The minimum value is 10. +- There is only one value, so the maximum is 10.` + +### Constraints + +- `n == nums.length` +- `1 <= n <= 10^5` +- `0 <= nums[i] <= 109`. + +--- + +## Approach + +The implementation of the solution involves a single pass algorithm using the concept of Monotonic Stacks for finding the next smaller elements on both left and right sides for each element in the input array nums. This is essential in determining the maximum minimum for different subarray sizes. + +Here's a step-by-step walkthrough of the solution: + + Initialize two arrays left and right with lengths equal to that of nums. Set all values in left to -1 and in right to n, where n is the size of nums. Also, create an empty list stk to be used as our Monotonic Stack. + + Iterate through nums from left to right (using index i): + Pop elements from the stack stk while the top of the stack is greater than or equal to the current element nums[i]. + If stk is not empty after popping elements, it means stk[-1] is the previous smaller element's index, which we assign to left[i]. + Push the current index i onto stk, indicating that we are considering nums[i] for the next elements' previous smaller check. + + Reset the stack stk and perform a similar process from right to left (using a decreasing index i): + Pop elements while the top of the stack is greater than or equal to nums[i]. + If stk is not empty after the popping process, the top element of stk is the next smaller element's index, which we assign to right[i]. + Push the current index i onto stk. + + After constructing left and right arrays, initialize the answer array ans with zeros, with the same size as nums. + + For every index i in nums, calculate the width m as the number of subarrays where nums[i] is the minimum by right[i] - left[i] - 1, and update ans[m - 1] with the maximum of its current value and nums[i]. + + Iterate through ans in reverse (starting from second to last element), making sure each ans[i] is at least as large as ans[i + 1]. This step ensures the answers are correct and handle the case where a smaller subarray may have the same maximum minimum as a larger subarray. + + +## Solution for Maximum of Minimum Values in All Subarrays + +### Java Solution + +```java +public class Solution { + + public int[] findMaximums(int[] nums) { + + int n = nums.length; + + // Initialize arrays to keep track of the left and right boundaries + + int[] leftBoundaries = new int[n]; + + int[] rightBoundaries = new int[n]; + + // Fill the arrays with initial values indicating no boundary found yet + + Arrays.fill(leftBoundaries, -1); + + Arrays.fill(rightBoundaries, n); + // Stack to keep track of indices for which we haven't found a smaller number yet + + Deque stack = new ArrayDeque<>(); + // Iterating from left to right to compute left boundaries + + for (int i = 0; i < n; ++i) { + + // Pop elements from the stack that are greater or equal to the current element + + while (!stack.isEmpty() && nums[stack.peek()] >= nums[i]) { + + stack.pop(); + + } + + // If stack is not empty, the current top is the closest left smaller element + + if (!stack.isEmpty()) { + + leftBoundaries[i] = stack.peek(); + + } + + // Push the current index onto the stack + + stack.push(i); + + } + // Clear the stack for the next iteration + + stack.clear(); + + // Iterating from right to left to compute right boundaries + + for (int i = n - 1; i >= 0; --i) { + + // Pop elements from the stack that are greater or equal to the current element + + while (!stack.isEmpty() && nums[stack.peek()] >= nums[i]) { + + stack.pop(); + + } + + // If stack is not empty, the current top is the closest right smaller element + + if (!stack.isEmpty()) { + + rightBoundaries[i] = stack.peek(); + + } + + // Push the current index onto the stack + + stack.push(i); + + } + + + + // Initialize the result array + + int[] result = new int[n]; + + // Find the maximum value for every possible window size + + for (int i = 0; i < n; ++i) { + + int windowSize = rightBoundaries[i] - leftBoundaries[i] - 1; + + result[windowSize - 1] = Math.max(result[windowSize - 1], nums[i]); + + } + + // Iterate to ensure each element represents the maximum for window size >= i+1 + + for (int i = n - 2; i >= 0; --i) { + + result[i] = Math.max(result[i], result[i + 1]); + + } + + // Return the filled in result array + + return result; + + } + +} +``` +### C++ solution + +```cpp +#include +#include +using std::vector; +using std::stack; +using std::max; +class Solution { +public: + + // Function to find the maximums of subarrays of all possible sizes + + vector findMaximums(vector& nums) { + + int n = nums.size(); + // Vectors to store indices of previous and next smaller elements + + vector left(n, -1); + + vector right(n, n); + + // Stack to keep track of indices as we search for smaller elements + + stack stk; + // Calculate the previous smaller element for each element in nums + + for (int i = 0; i < n; ++i) { + + // Pop elements from the stack until the current element is greater + + while (!stk.empty() && nums[stk.top()] >= nums[i]) { + + stk.pop(); + + } + + // If the stack isn't empty, set the left bound + + if (!stk.empty()) { + + left[i] = stk.top(); + + } + + // Push the current index onto the stack + + stk.push(i); + + } + // Clear the stack to reuse it for the next smaller elements on the right + + stk = stack(); + // Calculate the next smaller element for each element in nums + for (int i = n - 1; i >= 0; --i) { + + // Pop elements from the stack until the current element is greater + + while (!stk.empty() && nums[stk.top()] >= nums[i]) { + + stk.pop(); + + } + + // If the stack isn't empty, set the right bound + + if (!stk.empty()) { + + right[i] = stk.top(); + + } + + // Push the current index onto the stack + + stk.push(i); + + } + // Vector to store the maximums of subarrays of all possible sizes + + vector maxSubarraySizes(n); + // Find the maximum element seen for each subarray size + + for (int i = 0; i < n; ++i) { + + // Calculate the size of the largest window that the current element can be the minimum + + int windowSize = right[i] - left[i] - 1; + + // Update the maximum value for this window size if the current element is larger + + maxSubarraySizes[windowSize - 1] = max(maxSubarraySizes[windowSize - 1], nums[i]); + + } + // Ensure the maximum value for each size is at least as large as for the size above + + for (int i = n - 2; i >= 0; --i) { + + maxSubarraySizes[i] = max(maxSubarraySizes[i], maxSubarraySizes[i + 1]); + + } + // Return the vector of maximums + + return maxSubarraySizes; + + } + +}; + +``` +### Python Solution + +```python +from typing import List +class Solution: + + def findMaximums(self, nums: List[int]) -> List[int]: + + n = len(nums) + + # Initialize the left boundary for each element's minimum window + + left_boundaries = [-1] * n + + # Initialize the right boundary for each element's minimum window + + right_boundaries = [n] * n + + stack = [] + # Determine the previous less element for each number in nums + + for index, value in enumerate(nums): + + # Pop elements from the stack if the current value is less or equal + + while stack and nums[stack[-1]] >= value: + + stack.pop() + + # Set the left boundary if there is a previous less element + + if stack: + + left_boundaries[index] = stack[-1] + + stack.append(index) + # Reset the stack for determining next less element + + stack = [] + # Determine the next less element for each number in nums + + for index in range(n - 1, -1, -1): + + # Pop elements from the stack if the current number is less or equal + + while stack and nums[stack[-1]] >= nums[index]: + + stack.pop() + + # Set the right boundary if there is a next less element + + if stack: + + right_boundaries[index] = stack[-1] + + stack.append(index) + # Initialize the result array to store the maximums for each window size + + results = [0] * n + + # Update results array with the maximum values for each window size + + for index in range(n): + + window_size = right_boundaries[index] - left_boundaries[index] - 1 + + results[window_size - 1] = max(results[window_size - 1], nums[index]) + + # Propagate the maximums for larger window sizes + + for index in range(n - 2, -1, -1): + + results[index] = max(results[index], results[index + 1]) + + return results +``` +### Complexity Analysis +**Time Complexity:** O(n) + +**Space Complexity:** O(n) + +### References +**LeetCode Problem:** Maximum of Minimum Values in All Subarrays + + diff --git a/solutions/lc-solutions/1900-1999/1952-Three-Divisor.md b/solutions/lc-solutions/1900-1999/1952-Three-Divisor.md new file mode 100644 index 0000000..8dee346 --- /dev/null +++ b/solutions/lc-solutions/1900-1999/1952-Three-Divisor.md @@ -0,0 +1,59 @@ +--- +id: three-divisors +title: Three-divisors +sidebar_label: 1952-Three-Divisors +tags: + - Math + - Enumeration + - Number Theory +--- + +## Problem Description +Given an integer `n`, return `true` if `n` has exactly three positive divisors. Otherwise, return `false`. + +An integer `m` is a divisor of `n` if there exists an integer `k` such that `n = k * m`. + + +### Example + +**Example 1:** + +``` +Input: n = 2 +Output: false +Explantion: 2 has only two divisors: 1 and 2. +``` + +**Example 2:** +``` +Input: n = 4 +Output: true +Explantion: 4 has three divisors: 1, 2, and 4. +``` +### Constraints + +- `1 <= n <= 104` + +## Solution Approach + +### Intuition: + +To efficiently determine the number that is divisible by 3 integers. + + +## Solution Implementation + +### Code (C++): +```cpp +class Solution { +public: + bool isThree(int n) { + int cnt = 0; + for(int i=1; i<=n; i++){ + if(n%i==0) cnt++; + } + if(cnt==3) return true; + return false; + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/1900-1999/1960 - Maximum Product of the Length of Two Palindromic Substrings.md b/solutions/lc-solutions/1900-1999/1960 - Maximum Product of the Length of Two Palindromic Substrings.md new file mode 100644 index 0000000..9c7d7a8 --- /dev/null +++ b/solutions/lc-solutions/1900-1999/1960 - Maximum Product of the Length of Two Palindromic Substrings.md @@ -0,0 +1,217 @@ +--- +id: maximum-product-of-length-of-two-palindromic-substrings +title: Maximum Product of the Length of Two Palindromic Substrings +sidebar_label: Maximum Product of the Length of Two Palindromic Substrings +tags: [String, Palindrome, C++, Python, Java] +description: Solve the problem of finding the maximum product of the lengths of two non-intersecting palindromic substrings in a given string. +--- + +## Problem Statement + +### Problem Description + +You are given a 0-indexed string `s` and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized. + +More formally, you want to choose four integers `i, j, k, l` such that $0 \leq i \leq j < k \leq l \lt s.length$ and both the substrings `s[i...j]` and `s[k...l]` are palindromes and have odd lengths. `s[i...j]` denotes a substring from index `i` to index `j` inclusive. + +Return the maximum possible product of the lengths of the two non-intersecting palindromic substrings. + +A palindrome is a string that is the same forward and backward. A substring is a contiguous sequence of characters in a string. + +### Example + +**Example 1:** +``` +Input: s = "ababbb" +Output: 9 +``` +**Explanation:** Substrings "aba" and "bbb" are palindromes with odd length. product = 3 * 3 = 9. + + +### Constraints + +- $2 \leq s.length \leq 10^5$ +- `s` consists of lowercase English letters. + +## Solution + +### Intuition + +To solve this problem, we can use dynamic programming and a sliding window approach to find all possible palindromic substrings of odd length. By iterating through the string, we can determine the longest palindromic substring ending at each position and the longest palindromic substring starting at each position. Then, we calculate the maximum product of the lengths of two non-intersecting palindromic substrings. + +### Time Complexity and Space Complexity Analysis + +- **Time Complexity**: The solution involves a linear scan of the string and dynamic programming updates, making the time complexity $O(n)$. +- **Space Complexity**: The space complexity is $O(n)$ due to the storage required for dynamic programming arrays. + +### Code + +#### C++ + +```java +class Solution { + public int maxProduct(String s) { + int n = s.length(); + int[] left = new int[n]; + int[] right = new int[n]; + + // Calculate longest palindromic substring length ending at each index + int l = 0, r = -1; + for (int i = 0; i < n; i++) { + if (i > r) { + l = r = i; + while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) { + l--; + r++; + } + left[i] = r - l - 1; + } else { + int k = (r - i) / 2; + if (left[i - k] / 2 + i < r) { + left[i] = left[i - k]; + } else { + l = i - (r - i); + while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) { + l--; + r++; + } + left[i] = r - l - 1; + } + } + } + + // Calculate longest palindromic substring length starting at each index + l = n - 1; + r = n; + for (int i = n - 1; i >= 0; i--) { + if (i < l) { + l = r = i; + while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) { + l--; + r++; + } + right[i] = r - l - 1; + } else { + int k = (i - l) / 2; + if (right[i + k] / 2 + i > l) { + right[i] = right[i + k]; + } else { + l = i + (i - l); + while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) { + l--; + r++; + } + right[i] = r - l - 1; + } + } + } + + // Calculate the maximum product +``` + +```cpp +class Solution { +public: + int maxProduct(string s) { + int n = s.size(); + vector left(n, 0), right(n, 0); + + // Calculate longest palindromic substring length ending at each index + for (int i = 0, l = 0, r = -1; i < n; i++) { + if (i > r) { + l = r = i; + while (l >= 0 && r < n && s[l] == s[r]) l--, r++; + left[i] = r - l - 1; + } else { + int k = (r - i) / 2; + if (left[i - k] / 2 + i < r) { + left[i] = left[i - k]; + } else { + l = i - (r - i); + while (l >= 0 && r < n && s[l] == s[r]) l--, r++; + left[i] = r - l - 1; + } + } + } + + // Calculate longest palindromic substring length starting at each index + for (int i = n - 1, l = n - 1, r = n; i >= 0; i--) { + if (i < l) { + l = r = i; + while (l >= 0 && r < n && s[l] == s[r]) l--, r++; + right[i] = r - l - 1; + } else { + int k = (i - l) / 2; + if (right[i + k] / 2 + i > l) { + right[i] = right[i + k]; + } else { + l = i + (i - l); + while (l >= 0 && r < n && s[l] == s[r]) l--, r++; + right[i] = r - l - 1; + } + } + } + + // Calculate the maximum product + int maxProduct = 0; + for (int i = 0; i < n - 1; i++) { + maxProduct = max(maxProduct, (left[i] / 2) * (right[i + 1] / 2)); + } + return maxProduct; + } +}; +``` +#### Python +```python +class Solution: + def maxProduct(self, s: str) -> int: + n = len(s) + left = [0] * n + right = [0] * n + + # Calculate longest palindromic substring length ending at each index + l, r = 0, -1 + for i in range(n): + if i > r: + l, r = i, i + while l >= 0 and r < n and s[l] == s[r]: + l -= 1 + r += 1 + left[i] = r - l - 1 + else: + k = (r - i) // 2 + if left[i - k] // 2 + i < r: + left[i] = left[i - k] + else: + l = i - (r - i) + while l >= 0 and r < n and s[l] == s[r]: + l -= 1 + r += 1 + left[i] = r - l - 1 + + # Calculate longest palindromic substring length starting at each index + l, r = n - 1, n + for i in range(n - 1, -1, -1): + if i < l: + l, r = i, i + while l >= 0 and r < n and s[l] == s[r]: + l -= 1 + r += 1 + right[i] = r - l - 1 + else: + k = (i - l) // 2 + if right[i + k] // 2 + i > l: + right[i] = right[i + k] + else: + l = i + (i - l) + while l >= 0 and r < n and s[l] == s[r]: + l -= 1 + r += 1 + right[i] = r - l - 1 + + # Calculate the maximum product + maxProduct = 0 + for i in range(n - 1): + maxProduct = max(maxProduct, (left[i] // 2) * (right[i + 1] // 2)) + return maxProduct +``` diff --git a/solutions/lc-solutions/1900-1999/1962-remove-stones-to-minimize-the-total.md b/solutions/lc-solutions/1900-1999/1962-remove-stones-to-minimize-the-total.md new file mode 100644 index 0000000..a9fd684 --- /dev/null +++ b/solutions/lc-solutions/1900-1999/1962-remove-stones-to-minimize-the-total.md @@ -0,0 +1,240 @@ +--- +id: remove-stones-to-minimize-the-total +title: Remove Stones to Minimize the Total +sidebar_label: 1962. Remove Stones to Minimize the Total +tags: +- Array +- Greedy +- Heap (Priority Queue) + +description: "This is a solution to the Remove Stones to Minimize the Total problem on LeetCode." +--- + +## Problem Description +You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times: + +Choose any piles[i] and remove floor(piles[i] / 2) stones from it. +Notice that you can apply the operation on the same pile more than once. + +Return the minimum possible total number of stones remaining after applying the k operations. + +floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down). + +### Examples + +**Example 1:** +``` +Input: piles = [5,4,9], k = 2 +Output: 12 +Explanation: Steps of a possible scenario are: +- Apply the operation on pile 2. The resulting piles are [5,4,5]. +- Apply the operation on pile 0. The resulting piles are [3,4,5]. +The total number of stones in [3,4,5] is 12. + +``` + +**Example 2:** +``` +Input: piles = [4,3,6,7], k = 3 +Output: 12 +Explanation: Steps of a possible scenario are: +- Apply the operation on pile 2. The resulting piles are [4,3,3,7]. +- Apply the operation on pile 3. The resulting piles are [4,3,3,4]. +- Apply the operation on pile 0. The resulting piles are [2,3,3,4]. +The total number of stones in [2,3,3,4] is 12. +``` + + +### Constraints +- `1 <= piles.length <= 10^5` +- `1 <= piles[i] <= 10^4` +- `1 <= k <= 10^5` + +## Solution for Remove Stones to Minimize the Total Problem +### Intuition + +The problem requires reducing the total number of stones in a collection of piles through a series of operations. Each operation involves taking the largest pile and removing half (rounded down) of its stones. The goal is to perform this operation `k` times and determine the minimum possible total number of stones remaining. + +To efficiently manage the piles and always access the largest pile in constant time, we use a max heap (priority queue). This data structure allows us to repeatedly extract and modify the largest element efficiently. + +### Approach + +1. **Heap Initialization**: + - Convert the given `piles` array into a max heap. This involves sorting the array in descending order to simulate the max heap property. + +2. **Heap Operations**: + - Perform the given operation `k` times: + - Extract the largest pile (root of the heap). + - Reduce the pile size by half (rounded down). + - Reinsert the modified pile back into the heap, maintaining the max heap property using the `heapifyDown` function. + +3. **Summing Remaining Stones**: + - After completing the `k` operations, sum up all the remaining stones in the heap to get the final result. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + const minStoneSum = ( piles, k ) => { + let c = Array(10001).fill(0), s = 0 + piles.forEach( i => c[i]++ ) + for ( let i = c.length-1; i > 0; i-- ) + while ( c[i]-- > 0 ) + k-- > 0 ? c[Math.ceil(i/2)]++ : s += i + return s +} + const input = [5,4,9], k = 2 + + const output =minStoneSum(input , k) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(nlogn) $ + - Space Complexity: $ O(n) $ + + ## Code in Different Languages + + + + ```javascript + const minStoneSum = ( piles, k ) => { + let c = Array(10001).fill(0), s = 0 + piles.forEach( i => c[i]++ ) + for ( let i = c.length-1; i > 0; i-- ) + while ( c[i]-- > 0 ) + k-- > 0 ? c[Math.ceil(i/2)]++ : s += i + return s +} + ``` + + + + + ```typescript + class Solution { + minStoneSum(piles: number[], k: number): number { + const pq = new MaxPriorityQueue({ priority: (x) => x }); + for (let i of piles) { + pq.enqueue(i); + } + + for (let i = 0; i < k; i++) { + let x = pq.dequeue().element; + x = x - Math.floor(x / 2); + pq.enqueue(x); + } + + let ans = 0; + while (!pq.isEmpty()) { + ans += pq.dequeue().element; + } + return ans; + } +} + + ``` + + + + ```python +import heapq + +class Solution: + def minStoneSum(self, piles, k): + pq = [-x for x in piles] # Using negative values for max heap + heapq.heapify(pq) + + for _ in range(k): + x = -heapq.heappop(pq) + x = x - x // 2 + heapq.heappush(pq, -x) + + return -sum(pq) + + ``` + + + + + ```java + import java.util.PriorityQueue; + +class Solution { + public int minStoneSum(int[] piles, int k) { + PriorityQueue pq = new PriorityQueue<>((a, b) -> b - a); + for (int i : piles) { + pq.add(i); + } + + for (int i = 0; i < k; i++) { + int x = pq.poll(); + x = x - x / 2; + pq.add(x); + } + + int ans = 0; + while (!pq.isEmpty()) { + ans += pq.poll(); + } + return ans; + } +} + ``` + + + + + ```cpp + class Solution { +public: + int minStoneSum(vector& piles, int k) { + priority_queuepq; + for(auto i :piles) + { + pq.push(i); + } + + for(int i=0;i + + +
+
+ +## References + +- **LeetCode Problem**: [Remove Stones to Minimize the Total](https://leetcode.com/problems/remove-stones-to-minimize-the-total/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/remove-stones-to-minimize-the-total/solution) + diff --git a/solutions/lc-solutions/1900-1999/1970 - Last Day Where You Can Still Cross.md b/solutions/lc-solutions/1900-1999/1970 - Last Day Where You Can Still Cross.md new file mode 100644 index 0000000..a66ebbd --- /dev/null +++ b/solutions/lc-solutions/1900-1999/1970 - Last Day Where You Can Still Cross.md @@ -0,0 +1,110 @@ +--- +id: last-day-where-you-can-still-cross +title: Last Day Where You Can Still Cross +sidebar_label: Last Day Where You Can Still Cross +tags: [Binary Matrix, BFS, Union Find, Binary Search, C++, Python, Java] +description: Find the last day where it is possible to walk from the top to the bottom of a binary matrix by only walking on land cells. +--- + +## Problem Statement + +### Problem Description + +There is a 1-based binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. + +Initially on day `0`, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `i`th day, the cell on the `ri`th row and `ci`th column (1-based coordinates) will be covered with water (i.e., changed to `1`). + +You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down). + +Return the last day where it is possible to walk from the top to the bottom by only walking on land cells. + +### Example + +**Example 1:** +``` +Input: row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]] +Output: 2 +``` +**Explanation:** The above image depicts how the matrix changes each day starting from day 0. +The last day where it is possible to cross from top to bottom is on day 2. + + +### Constraints + +- `2 <= row, col <= 2 \times 10^4` +- All the values of `cells` are unique. + +## Solution + +### Intuition + +To solve this problem, we can use binary search combined with a BFS (Breadth-First Search) to determine the latest possible day where a valid path exists from the top to the bottom of the matrix. The key idea is to simulate the flooding process in reverse and check if a path exists using BFS. + +### Time Complexity and Space Complexity Analysis + +- **Time Complexity**: $O((row \times col) \cdot \log(row \times col))$, due to the binary search combined with BFS traversal. +- **Space Complexity**: $O(row \times col)$, for the matrix and auxiliary space used in BFS. + +### Code + +#### C++ + +```cpp +#include +#include +#include +using namespace std; + +class Solution { +public: + int latestDayToCross(int row, int col, vector>& cells) { + vector> grid(row, vector(col, 0)); + int left = 0, right = cells.size() - 1; + + auto canCross = [&](int day) -> bool { + vector> tempGrid = grid; + for (int i = 0; i <= day; ++i) { + int r = cells[i][0] - 1, c = cells[i][1] - 1; + tempGrid[r][c] = 1; + } + + vector> visited(row, vector(col, false)); + queue> q; + + for (int c = 0; c < col; ++c) { + if (tempGrid[0][c] == 0) { + q.push({0, c}); + visited[0][c] = true; + } + } + + while (!q.empty()) { + auto [r, c] = q.front(); + q.pop(); + + if (r == row - 1) return true; + + for (const auto& [dr, dc] : vector>{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}) { + int nr = r + dr, nc = c + dc; + if (nr >= 0 && nr < row && nc >= 0 && nc < col && !visited[nr][nc] && tempGrid[nr][nc] == 0) { + visited[nr][nc] = true; + q.push({nr, nc}); + } + } + } + return false; + }; + + while (left <= right) { + int mid = left + (right - left) / 2; + if (canCross(mid)) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return right; + } +}; +``` diff --git a/solutions/lc-solutions/1900-1999/1979-Find-Greatest-Common-Divisor-Of-Array.md b/solutions/lc-solutions/1900-1999/1979-Find-Greatest-Common-Divisor-Of-Array.md new file mode 100644 index 0000000..1155cd0 --- /dev/null +++ b/solutions/lc-solutions/1900-1999/1979-Find-Greatest-Common-Divisor-Of-Array.md @@ -0,0 +1,165 @@ +--- +id: find-greatest-common-divisor-of-array +title: Find Greatest Common Divisor of Array +sidebar_label: 1979-Find-Greatest-Common-Divisor-Of-Array +tags: + - Math + - Array + - Number Theory +--- + +## Problem Description +Given an integer array `nums`, return the greatest common divisor of the smallest number and largest number in `nums`. + +The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers. + + +### Example + +**Example 1:** + + +``` +Input: nums = [2,5,6,9,10] +Output: 2 +Explanation: +The smallest number in nums is 2. +The largest number in nums is 10. +The greatest common divisor of 2 and 10 is 2. +``` +**Example 2:** +``` +Input: nums = [7,5,6,8,3] +Output: 1 +Explanation: +The smallest number in nums is 3. +The largest number in nums is 8. +The greatest common divisor of 3 and 8 is 1. +``` +### Constraints + +- `1 <= nums[i] <= 1000` + +## Solution Approach + +### Intuition: + +To efficiently determine Find Greatest Common Divisor of Array. +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + +class Solution { + findGCD(nums) { + let n = nums.length; + let mini = Math.max(...nums); + let maxi = Math.min(...nums); + let divisor = 1; + for(let i=1; i<=mini; i++){ + if(mini%i==0 && maxi%i==0) divisor = i; + } + return divisor; + } +} + + + + ``` + + + + + ```typescript + class Solution { + findGCD(nums: number[]): number { + let n = nums.length; + let mini = Math.max(...nums); + let maxi = Math.min(...nums); + let divisor = 1; + for(let i=1; i<=mini; i++){ + if(mini%i==0 && maxi%i==0) divisor = i; + } + return divisor; + } +} + + + ``` + + + + + ```python + class Solution: + def findGCD(self, nums: List[int]) -> int: + n = len(nums) + mini = max(nums) + maxi = min(nums) + divisor = 1 + for i in range(1, mini+1): + if mini%i==0 and maxi%i==0: + divisor = i + return divisor + + + + ``` + + + + + ```java + public class Solution { + public int findGCD(int[] nums) { + int n = nums.length; + int mini = Arrays.stream(nums).max().getAsInt(); + int maxi = Arrays.stream(nums).min().getAsInt(); + int divisor = 1; + for(int i=1; i<=mini; i++){ + if(mini%i==0 && maxi%i==0) divisor = i; + } + return divisor; + } +} + + + + ``` + + + + + ```cpp +class Solution { +public: + int findGCD(vector& nums) { + int n = nums.size(); + int mini = INT_MAX; + int maxi = INT_MIN; + int divisor = 1; + + for(int i=0; imaxi) maxi = nums[i]; + if(nums[i] + + +#### Complexity Analysis + +- Time Complexity: $$O(n+mini)$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(n + mini)$$ where n is the length of the input array nums and mini is the smallest element in the array. This is because the function iterates over the array once to find the minimum and maximum values, and then iterates up to the minimum value to find the GCD. +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/1900-1999/1991-find-the-middle-index-in-array.md b/solutions/lc-solutions/1900-1999/1991-find-the-middle-index-in-array.md new file mode 100644 index 0000000..890562a --- /dev/null +++ b/solutions/lc-solutions/1900-1999/1991-find-the-middle-index-in-array.md @@ -0,0 +1,134 @@ +--- +id: find-the-middle-index-in-array +title: Find The Middle Index In Array +sidebar_label: 1991-find-the-middle-index-in-array +tags: +- Array +- Prefix Sum +description: "This document provides solutions for find the middle index in array." +--- + +## Problem + +Given a `0-indexed` integer array nums, find the **leftmost** middleIndex `(i.e., the smallest amongst all the possible ones)`. + +A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]. + +If `middleIndex == 0`, the left side sum is considered to be `0`. Similarly, if `middleIndex == nums.length - 1`, the right side sum is considered to be `0`. + +Return the **leftmost** middleIndex that satisfies the condition, or -1 if there is no such index. + +### Examples + +**Example 1:** + +**Input:** nums = [2,3,-1,8,4] + +**Output:** 3 + +**Explanation**: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4 +The sum of the numbers after index 3 is: 4 = 4 + +**Example 2:** + +**Input:** nums = [1,-1,4] + +**Output:** 2 + +**Explanation**: The sum of the numbers before index 2 is: 1 + -1 = 0 +The sum of the numbers after index 2 is: 0 + +**Example 3:** + +**Input:** nums = [2,5] + +**Output:** -1 + +**Explanation**: There is no valid middleIndex. + +### Constraints + +- `1 <= nums.length <= 100` +- `-1000 <= nums[i] <= 1000` + +--- + +## Approach + +1. Initialize prefix to 0 and suffix to the sum of all elements in nums. + +2. Iterate through the elements of nums: + + - For each element, subtract it from suffix. + - Check if prefix is equal to suffix. If true, return the current + index i. + - Add the current element to prefix. + +3. If no such index is found, return -1. + +## Solution for Remove Linked List Elements + +### Java Solution + +```java +class Solution { + public int findMiddleIndex(int[] nums) { + int prefix = 0; + int suffix = Arrays.stream(nums).sum(); + + for (int i = 0; i < nums.length; ++i) { + suffix -= nums[i]; + if (prefix == suffix) + return i; + prefix += nums[i]; + } + + return -1; + } +} +``` +### C++ solution + +```cpp +class Solution { + public: + int findMiddleIndex(vector& nums) { + int prefix = 0; + int suffix = accumulate(nums.begin(), nums.end(), 0); + + for (int i = 0; i < nums.size(); ++i) { + suffix -= nums[i]; + if (prefix == suffix) + return i; + prefix += nums[i]; + } + + return -1; + } +}; +``` +### Python Solution + +```python +class Solution: + def findMiddleIndex(self, nums: List[int]) -> int: + prefix = 0 + suffix = sum(nums) + + for i, num in enumerate(nums): + suffix -= num + if prefix == suffix: + return i + prefix += num + + return -1 +``` +### Complexity Analysis +**Time Complexity:** O(n) + +**Space Complexity:** O(1) + +### References +**LeetCode Problem:** find-the-middle-index-in-array + + diff --git a/solutions/lc-solutions/1900-1999/1992-find-all-groups-of-farmland.md b/solutions/lc-solutions/1900-1999/1992-find-all-groups-of-farmland.md new file mode 100644 index 0000000..5784b04 --- /dev/null +++ b/solutions/lc-solutions/1900-1999/1992-find-all-groups-of-farmland.md @@ -0,0 +1,351 @@ +--- +id: find-all-groups-of-farmland +title: Find All Groups of Farmland +sidebar_label: 1992. Find All Groups of Farmland +tags: +- Array +- Greedy +- Heap (Priority Queue) + +description: "This is a solution to the Remove Stones to Minimize the Total problem on LeetCode." +--- + +## Problem Description +You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. + +To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group. + +land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2]. + +Return a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order. +### Examples + +**Example 1:** +![image](https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-23-15-copy-of-diagram-drawio-diagrams-net.png) +``` +Input: land = [[1,0,0],[0,1,1],[0,1,1]] +Output: [[0,0,0,0],[1,1,2,2]] +``` + +**Example 2:** +![image](https://assets.leetcode.com/uploads/2021/07/27/screenshot-2021-07-27-at-12-30-26-copy-of-diagram-drawio-diagrams-net.png) + +``` +Input: land = [[1,1],[1,1]] +Output: [[0,0,1,1]] +Explanation: +The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1]. +``` + + +### Constraints +- `m == land.length` +- `n == land[i].length` +- `1 <= m, n <= 300` +- land consists of only 0's and 1's. +- Groups of farmland are rectangular in shape. + +## Solution for Remove Stones to Minimize the Total Problem +## Intuition + +The problem is to find all the rectangular farmlands in a grid. Each cell in the grid is either part of a farmland (denoted by 1) or not (denoted by 0). Farmlands are connected horizontally or vertically and form rectangular shapes. The goal is to identify the top-left and bottom-right coordinates of each rectangular farmland. + +## Approach + +1. **Grid Traversal**: + - Traverse each cell in the grid. + - When encountering a cell with a value of 1 (indicating the start of a new farmland), initiate a Breadth-First Search (BFS) to find the extent of this farmland. + +2. **Breadth-First Search (BFS)**: + - Use a queue to explore all cells connected to the current farmland. + - Track the maximum row and column indices (`eR` and `eC`) to determine the bottom-right corner of the farmland. + - For each cell, check its four neighboring cells (up, down, left, right). If a neighboring cell is part of the farmland (i.e., its value is 1), add it to the queue and mark it as visited (set its value to 0). + +3. **Record Farmland**: + - After completing the BFS for a farmland, record its top-left and bottom-right coordinates. + - Continue the grid traversal to find all farmlands. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function findFarmland(land) { + const ans = []; + const m = land.length; + const n = land[0].length; + const delRow = [-1, 0, 1, 0]; + const delCol = [0, 1, 0, -1]; + const q = []; + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (land[i][j] === 1) { + q.push([i, j]); + land[i][j] = 0; + let eR = i, eC = j; + while (q.length > 0) { + const [sR, sC] = q.shift(); + + for (let k = 0; k < 4; k++) { + const nR = sR + delRow[k]; + const nC = sC + delCol[k]; + if (nR >= 0 && nR < m && nC >= 0 && nC < n && land[nR][nC] === 1) { + q.push([nR, nC]); + land[nR][nC] = 0; + eR = Math.max(eR, nR); + eC = Math.max(eC, nC); + } + } + } + ans.push([i, j, eR, eC]); + } + } + } + return ans; +} + + const input = [[1,0,0],[0,1,1],[0,1,1]] + + const output =findFarmland(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(n*m) $ + - Space Complexity: $ O(n*m) $ + + ## Code in Different Languages + + + + ```javascript + function findFarmland(land) { + const ans = []; + const m = land.length; + const n = land[0].length; + const delRow = [-1, 0, 1, 0]; + const delCol = [0, 1, 0, -1]; + const q = []; + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (land[i][j] === 1) { + q.push([i, j]); + land[i][j] = 0; + let eR = i, eC = j; + while (q.length > 0) { + const [sR, sC] = q.shift(); + + for (let k = 0; k < 4; k++) { + const nR = sR + delRow[k]; + const nC = sC + delCol[k]; + if (nR >= 0 && nR < m && nC >= 0 && nC < n && land[nR][nC] === 1) { + q.push([nR, nC]); + land[nR][nC] = 0; + eR = Math.max(eR, nR); + eC = Math.max(eC, nC); + } + } + } + ans.push([i, j, eR, eC]); + } + } + } + return ans; +} + + ``` + + + + + ```typescript + function findFarmland(land: number[][]): number[][] { + const ans: number[][] = []; + const m = land.length; + const n = land[0].length; + const delRow = [-1, 0, 1, 0]; + const delCol = [0, 1, 0, -1]; + const q: [number, number][] = []; + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (land[i][j] === 1) { + q.push([i, j]); + land[i][j] = 0; + let eR = i, eC = j; + while (q.length > 0) { + const [sR, sC] = q.shift()!; + + for (let k = 0; k < 4; k++) { + const nR = sR + delRow[k]; + const nC = sC + delCol[k]; + if (nR >= 0 && nR < m && nC >= 0 && nC < n && land[nR][nC] === 1) { + q.push([nR, nC]); + land[nR][nC] = 0; + eR = Math.max(eR, nR); + eC = Math.max(eC, nC); + } + } + } + ans.push([i, j, eR, eC]); + } + } + } + return ans; +} + + ``` + + + + ```python + from collections import deque + +class Solution: + def findFarmland(self, land: List[List[int]]) -> List[List[int]]: + ans = [] + m, n = len(land), len(land[0]) + delRow = [-1, 0, 1, 0] + delCol = [0, 1, 0, -1] + q = deque() + + for i in range(m): + for j in range(n): + if land[i][j] == 1: + q.append((i, j)) + land[i][j] = 0 + eR, eC = i, j + while q: + sR, sC = q.popleft() + + for k in range(4): + nR, nC = sR + delRow[k], sC + delCol[k] + if 0 <= nR < m and 0 <= nC < n and land[nR][nC] == 1: + q.append((nR, nC)) + land[nR][nC] = 0 + eR = max(eR, nR) + eC = max(eC, nC) + ans.append([i, j, eR, eC]) + return ans + + ``` + + + + + ```java + import java.util.*; + +class Solution { + public List findFarmland(int[][] land) { + List ans = new ArrayList<>(); + Queue q = new LinkedList<>(); + int m = land.length; + int n = land[0].length; + int[] delRow = {-1, 0, 1, 0}; + int[] delCol = {0, 1, 0, -1}; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (land[i][j] == 1) { + q.add(new int[]{i, j}); + land[i][j] = 0; + int eR = i, eC = j; + while (!q.isEmpty()) { + int[] cell = q.poll(); + int sR = cell[0]; + int sC = cell[1]; + + for (int k = 0; k < 4; k++) { + int nR = sR + delRow[k]; + int nC = sC + delCol[k]; + if (nR >= 0 && nR < m && nC >= 0 && nC < n && land[nR][nC] == 1) { + q.add(new int[]{nR, nC}); + land[nR][nC] = 0; + eR = Math.max(eR, nR); + eC = Math.max(eC, nC); + } + } + } + ans.add(new int[]{i, j, eR, eC}); + } + } + } + return ans; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + vector> findFarmland(vector>& land) { + vector> ans; + queue> q; + int m = land.size(); + int n = land[0].size(); + int delRow[4] = {-1, 0, 1, 0}; + int delCol[4] = {0, 1, 0, -1}; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (land[i][j] == 1) { + q.push({i, j}); + land[i][j] = 0; + int eR = i, eC = j; + while (!q.empty()) { + int sR = q.front().first; + int sC = q.front().second; + q.pop(); + + for (int k = 0; k < 4; k++) { + int nR = sR + delRow[k]; + int nC = sC + delCol[k]; + if (nR >= 0 && nR < m && nC >= 0 && nC < n && land[nR][nC] == 1) { + q.push({nR, nC}); + land[nR][nC] = 0; + eR = max(eR, nR); + eC = max(eC, nC); + } + } + } + ans.push_back({i, j, eR, eC}); + } + } + } + return ans; + } +}; + + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Find All Groups of Farmland](https://leetcode.com/problems/find-all-groups-of-farmland/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/find-all-groups-of-farmland/description/) + diff --git a/solutions/lc-solutions/1900-1999/Remove One Element to Make the Array Strictly Increasing.md b/solutions/lc-solutions/1900-1999/Remove One Element to Make the Array Strictly Increasing.md new file mode 100644 index 0000000..d0f0975 --- /dev/null +++ b/solutions/lc-solutions/1900-1999/Remove One Element to Make the Array Strictly Increasing.md @@ -0,0 +1,117 @@ +--- +id: remove-one-element-to-make-array-strictly-increasing +title: Remove One Element to Make the Array Strictly Increasing +sidebar_label: Remove One Element to Make Array Strictly Increasing +tags: [Array, Greedy, C++, Python, Java] +description: Solve the problem of determining whether an array can be made strictly increasing by removing exactly one element. +--- + +## Problem Statement + +### Problem Description + +Given a 0-indexed integer array `nums`, return `true` if it can be made strictly increasing after removing exactly one element, or `false` otherwise. If the array is already strictly increasing, return `true`. + +The array `nums` is strictly increasing if `nums[i - 1] < nums[i]` for each index `1 <= i < nums.length`. + +### Example + +**Example 1:** + +``` +Input: nums = [1, 2, 10, 5, 7] +Output: true +``` +**Explanation:** By removing 10 at index 2 from nums, it becomes [1, 2, 5, 7]. +[1, 2, 5, 7] is strictly increasing, so return true. + + +**Example 2:** +``` +Input: nums = [2, 3, 1, 2] +Output: false +``` +**Explanation:** +[3, 1, 2] is the result of removing the element at index 0. +[2, 1, 2] is the result of removing the element at index 1. +[2, 3, 2] is the result of removing the element at index 2. +[2, 3, 1] is the result of removing the element at index 3. +No resulting array is strictly increasing, so return false. + + +### Constraints + +- 2 <= `nums.length` <= 1000 +- 1 <= `nums[i]` <= 1000 + +## Solution + +### Intuition + +To solve this problem, we can use a greedy approach by iterating through the array and checking if there are any elements that violate the strictly increasing condition. If we find such an element, we can attempt to remove either the current element or the previous element and check if the resulting array (excluding that element) is strictly increasing. If any such removal results in a strictly increasing array, we return `true`. Otherwise, we return `false`. + +### Time Complexity and Space Complexity Analysis + +- **Time Complexity**: + - The solution involves a single pass through the array and a few constant-time checks, resulting in an overall time complexity of $O(n)$, where `n` is the length of the array. + +- **Space Complexity**: + - The space complexity is $O(1)$ as we are only using a fixed amount of extra space for variables. + +### Code + +#### C++ + +```cpp +class Solution { +public: + bool canBeIncreasing(vector& nums) { + int count = 0; + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] <= nums[i - 1]) { + count++; + if (count > 1) return false; + if (i > 1 && nums[i] <= nums[i - 2] && i < nums.size() - 1 && nums[i + 1] <= nums[i - 1]) + return false; + } + } + return true; + } +}; +``` + +#### Python +```python +class Solution: + def canBeIncreasing(self, nums: List[int]) -> bool: + count = 0 + for i in range(1, len(nums)): + if nums[i] <= nums[i - 1]: + count += 1 + if count > 1: + return False + if i > 1 and nums[i] <= nums[i - 2] and i < len(nums) - 1 and nums[i + 1] <= nums[i - 1]: + return False + return True +``` + +#### Java +```java +class Solution { + public boolean canBeIncreasing(int[] nums) { + int count = 0; + for (int i = 1; i < nums.length; i++) { + if (nums[i] <= nums[i - 1]) { + count++; + if (count > 1) { + return false; + } + if (i > 1 && nums[i] <= nums[i - 2] && i < nums.length - 1 && nums[i + 1] <= nums[i - 1]) { + return false; + } + } + } + return true; + } +} +``` diff --git a/solutions/lc-solutions/1900-1999/_category_.json b/solutions/lc-solutions/1900-1999/_category_.json new file mode 100644 index 0000000..6a80ecc --- /dev/null +++ b/solutions/lc-solutions/1900-1999/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "1900-1999", + "position": 21, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (1900 - 1999)" + } +} diff --git a/solutions/lc-solutions/2000-2099/2000-counting-visible-nodes-in-binary-tree.md b/solutions/lc-solutions/2000-2099/2000-counting-visible-nodes-in-binary-tree.md new file mode 100644 index 0000000..202dedb --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2000-counting-visible-nodes-in-binary-tree.md @@ -0,0 +1,164 @@ +--- +id: counting-visible-nodes-in-binary-tree +title: Counting Visible Nodes in Binary Tree +sidebar_label: 2000-Counting-Visible-Nodes-in-Binary-Tree +tags: +- Tree +- Depth-First Search +- Breadth-First Search +description: "Given a binary tree, count the number of visible nodes. A node is considered visible if, in the path from the root to that node, there are no nodes with a greater value." +--- + +## Problem + +Given a binary tree `root`, count the number of visible nodes. A node is considered visible if, in the path from the root to that node, there are no nodes with a greater value. + +### Examples + +**Example 1:** + +**Input:** `root = [5,3,10,20,21,1,null,null,2]` +**Output:** `4` +**Explanation:** There are 4 visible nodes: 5, 10, 21, and 2. + +**Example 2:** + +**Input:** `root = [8,2,9,1,3,null,4]` +**Output:** `5` +**Explanation:** There are 5 visible nodes: 8, 9, 3, 4, and 1. + +### Constraints + +- The number of nodes in the tree is in the range `[0, 10^4]`. +- `-10^9 <= Node.val <= 10^9` + +--- + +## Approach + +To solve this problem, we can use a recursive depth-first search (DFS) approach. The idea is to traverse the tree while keeping track of the maximum value encountered along the path from the root to the current node. If the current node's value is greater than or equal to this maximum value, it is considered visible, and we recursively count visible nodes in its left and right subtrees. + +### Steps: + +1. Implement a recursive function that takes the current node and the maximum value encountered so far. +2. Initialize a count variable to keep track of the number of visible nodes. +3. If the current node is `null`, return 0. +4. If the current node's value is greater than or equal to the maximum value encountered so far, increment the count and recursively count visible nodes in both left and right subtrees, updating the maximum value accordingly. +5. Return the total count of visible nodes. + +### Solution + +#### Java + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int countVisibleNodes(TreeNode root) { + return countVisibleNodes(root, Integer.MIN_VALUE); + } + + private int countVisibleNodes(TreeNode node, int maxSoFar) { + if (node == null) { + return 0; + } + + int count = 0; + if (node.val >= maxSoFar) { + count++; + maxSoFar = node.val; + } + + count += countVisibleNodes(node.left, maxSoFar); + count += countVisibleNodes(node.right, maxSoFar); + + return count; + } +} +``` + +#### C++ + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + int countVisibleNodes(TreeNode* root) { + return countVisibleNodes(root, INT_MIN); + } + +private: + int countVisibleNodes(TreeNode* node, int maxSoFar) { + if (node == nullptr) { + return 0; + } + + int count = 0; + if (node->val >= maxSoFar) { + count++; + maxSoFar = node->val; + } + + count += countVisibleNodes(node->left, maxSoFar); + count += countVisibleNodes(node->right, maxSoFar); + + return count; + } +}; +``` + +#### Python + +```python +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def countVisibleNodes(self, root: TreeNode) -> int: + return self.countVisibleNodesRecursive(root, float('-inf')) + + def countVisibleNodesRecursive(self, node: TreeNode, maxSoFar: int) -> int: + if not node: + return 0 + + count = 0 + if node.val >= maxSoFar: + count += 1 + maxSoFar = node.val + + count += self.countVisibleNodesRecursive(node.left, maxSoFar) + count += self.countVisibleNodesRecursive(node.right, maxSoFar) + + return count +``` + +### Complexity Analysis + +**Time Complexity:** O(n) +- The algorithm visits each node in the tree once, where n is the total number of nodes in the tree. + +**Space Complexity:** O(h) +- The space complexity is determined by the recursion stack, which can go up to the height h of the tree. In the worst case, the tree is skewed, so the space complexity is O(n). + +### References + +- **LeetCode Problem:** [Count Visible Nodes in Binary Tree](https://leetcode.com/problems/count-visible-nodes-in-binary-tree/) diff --git a/solutions/lc-solutions/2000-2099/2001-number-of-pairs-of-interchangeable-rectangles.md b/solutions/lc-solutions/2000-2099/2001-number-of-pairs-of-interchangeable-rectangles.md new file mode 100644 index 0000000..fd12913 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2001-number-of-pairs-of-interchangeable-rectangles.md @@ -0,0 +1,112 @@ +--- +id: number-of-pairs-of-interchangeable-rectangles +title: Number of Pairs of Interchangeable Rectangles +sidebar_label: 2001 Number of Pairs of Interchangeable Rectangles +tags: + - Array + - Hash Table + - Math + - LeetCode + - C++ +description: "This is a solution to the Number of Pairs of Interchangeable Rectangles problem on LeetCode." +sidebar_position: 2001 +--- + +## Problem Description + +You are given `n` rectangles represented by a 0-indexed 2D integer array `rectangles`, where `rectangles[i] = [widthi, heighti]` denotes the width and height of the ith rectangle. + +Two rectangles `i` and `j` (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if `widthi/heighti == widthj/heightj` (using decimal division, not integer division). + +Return the number of pairs of interchangeable rectangles in `rectangles`. + +### Examples + +**Example 1:** + +``` +Input: rectangles = [[4,8],[3,6],[10,20],[15,30]] +Output: 6 + +Explanation: The following are the interchangeable pairs of rectangles by index (0-indexed): + +Rectangle 0 with rectangle 1: 4/8 == 3/6. +Rectangle 0 with rectangle 2: 4/8 == 10/20. +Rectangle 0 with rectangle 3: 4/8 == 15/30. +Rectangle 1 with rectangle 2: 3/6 == 10/20. +Rectangle 1 with rectangle 3: 3/6 == 15/30. +Rectangle 2 with rectangle 3: 10/20 == 15/30. +``` + +**Example 2:** + +``` +Input: rectangles = [[4,5],[7,8]] +Output: 0 + +Explanation: There are no interchangeable pairs of rectangles. +``` + + +### Constraints +- `n == rectangles.length` +- `1 <= n <= 10^5` +- `rectangles[i].length == 2` +- `1 <= widthi, heighti <= 10^5` + +### Approach + +To solve this problem, we can use a hash map to keep track of the frequency of each unique width-to-height ratio. We iterate through the array of rectangles, calculate the ratio for each rectangle, and use the hash map to count the pairs that have the same ratio. + +### Complexity + +- **Time complexity**: $O(n)$, where `n` is the number of rectangles. This is because we are iterating through the array once. +- **Space complexity**: $O(n)$, for storing the ratios in the hash map. + +#### C++ + +```cpp +class Solution { +public: + long long interchangeableRectangles(vector>& rectangles) { + // Store the counts of each width-to-height ratio + unordered_map ratio_counts; + long long res = 0; + + for (const auto& rectangle: rectangles){ + // Calculate the ratio of current rectangle + double ratio = static_cast(rectangle.front()) / rectangle.back(); + + // Add the current count of this ratio to the result, as all rectangles + // with the same ratio encountered so far are interchangeable with this one + res += ratio_counts[ratio]++; + } + + return res; + } +}; +``` + +#### Java + +```java +class Solution { + public long interchangeableRectangles(int[][] rectangles) { + Map mp = new HashMap(); + long anss = 0; + for(int i=0;i mpp:mp.entrySet()){ + // System.out.println(mpp.getValue()); + long temp = (long)(mpp.getValue())-1; + anss+= (temp*(temp+1))/2; + } + return anss; + + } +} +``` diff --git a/solutions/lc-solutions/2000-2099/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.md b/solutions/lc-solutions/2000-2099/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.md new file mode 100644 index 0000000..fab9fcf --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.md @@ -0,0 +1,426 @@ +--- +id: maximum-product-of-the-length-of-two-palindromic-subsequences +title: Maximum Product of the Length of Two Palindromic Subsequences +sidebar_label: 2002. Maximum Product of the Length of Two Palindromic Subsequences + +tags: +- String +- Backtracking +- Dynamic Programming +- Bit Manupulation + +description: "This is a solution to the 2002. Maximum Product of the Length of Two Palindromic Subsequences problem on LeetCode." +--- + +## Problem Description +Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index. + +Return the maximum possible product of the lengths of the two palindromic subsequences. + +A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward. +### Examples +**Example 1:** +![image](https://assets.leetcode.com/uploads/2021/08/24/two-palindromic-subsequences.png) + +``` +Input: s = "leetcodecom" +Output: 9 +Explanation: An optimal solution is to choose "ete" for the 1st subsequence and "cdc" for the 2nd subsequence. +The product of their lengths is: 3 * 3 = 9. +``` + +**Example 2:** +``` +Input: s = "accbcaxxcxx" +Output: 25 +Explanation: An optimal solution is to choose "accca" for the 1st subsequence and "xxcxx" for the 2nd subsequence. +The product of their lengths is: 5 * 5 = 25. +``` + +### Constraints +- `2 <= s.length <= 12` +- `s consists of lowercase English letters only.` + +## Solution for Maximum Product of the Length of Two Palindromic Subsequences +1. **Generate All Subsequences:** + - The function `sub` recursively generates all subsequences of the input string `s`. + - For each subsequence, it checks if it is a palindrome using the `isPalindrome` function. + - If a subsequence is a palindrome, it is added to the global result list `ans`. + +2. **Check Palindromes:** + - The function `isPalindrome` takes a string and a list of indices (subsequence) and checks if the characters at these indices form a palindrome. + +3. **Check Non-overlapping Subsequences:** + - The function `check` takes two subsequences and checks if they have any common elements (indices). + - If they don't share any indices, they are considered non-overlapping. + +4. **Calculate Maximum Product:** + - The function `maxProduct` iterates through all pairs of palindromic subsequences. + - For each pair, it checks if they are non-overlapping using the `check` function. + - If they are non-overlapping, it calculates the product of their lengths and updates the maximum product found. + +### Intuition +- The idea is to find all palindromic subsequences and then determine the maximum product of the lengths of two non-overlapping palindromic subsequences. +- Generating all subsequences ensures that no potential palindromic subsequences are missed. +- Checking for non-overlapping ensures that the two subsequences do not share any characters, thus making the product calculation valid. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + const ans = []; + + function isPalindrome(s, ans) { + let a = 0, b = ans.length - 1; + while (a <= b) { + if (s[ans[a]] !== s[ans[b]]) return false; + a++; + b--; + } + return true; + } + + function check(a, b) { + for (let i = 0; i < a.length; i++) { + for (let j = 0; j < b.length; j++) { + if (a[i] === b[j]) return false; + } + } + return true; + } + + function sub(nums, i, temp) { + if (isPalindrome(nums, temp)) ans.push([...temp]); + if (i >= nums.length) return; + + temp.push(i); + sub(nums, i + 1, temp); + + temp.pop(); + sub(nums, i + 1, temp); + } + + function maxProduct(s) { + const temp = []; + sub(s, 0, temp); + let res = 0; + for (let i = 0; i < ans.length; i++) { + for (let j = i + 1; j < ans.length; j++) { + let x = ans[i].length * ans[j].length; + if (check(ans[i], ans[j])) { + res = Math.max(res, x); + } + } + } + return res; + } + + const input = "leetcodecom" + const output = maxProduct(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n * 4^n) $ + - Space Complexity: $ O(n * 2^n)$ + + ## Code in Different Languages + + + + ```javascript + const ans = []; + +function isPalindrome(s, ans) { + let a = 0, b = ans.length - 1; + while (a <= b) { + if (s[ans[a]] !== s[ans[b]]) return false; + a++; + b--; + } + return true; +} + +function check(a, b) { + for (let i = 0; i < a.length; i++) { + for (let j = 0; j < b.length; j++) { + if (a[i] === b[j]) return false; + } + } + return true; +} + +function sub(nums, i, temp) { + if (isPalindrome(nums, temp)) ans.push([...temp]); + if (i >= nums.length) return; + + temp.push(i); + sub(nums, i + 1, temp); + + temp.pop(); + sub(nums, i + 1, temp); +} + +function maxProduct(s) { + const temp = []; + sub(s, 0, temp); + let res = 0; + for (let i = 0; i < ans.length; i++) { + for (let j = i + 1; j < ans.length; j++) { + let x = ans[i].length * ans[j].length; + if (check(ans[i], ans[j])) { + res = Math.max(res, x); + } + } + } + return res; +} + + ``` + + + + + ```typescript + class Solution { + ans: number[][] = []; + + isPalindrome(s: string, ans: number[]): boolean { + let a = 0, b = ans.length - 1; + while (a <= b) { + if (s[ans[a]] !== s[ans[b]]) return false; + a++; + b--; + } + return true; + } + + check(a: number[], b: number[]): boolean { + for (let i = 0; i < a.length; i++) { + for (let j = 0; j < b.length; j++) { + if (a[i] === b[j]) return false; + } + } + return true; + } + + sub(nums: string, i: number, temp: number[]): void { + if (this.isPalindrome(nums, temp)) this.ans.push([...temp]); + if (i >= nums.length) return; + + temp.push(i); + this.sub(nums, i + 1, temp); + + temp.pop(); + this.sub(nums, i + 1, temp); + } + + maxProduct(s: string): number { + let temp: number[] = []; + this.sub(s, 0, temp); + let res = 0; + for (let i = 0; i < this.ans.length; i++) { + for (let j = i + 1; j < this.ans.length; j++) { + let x = this.ans[i].length * this.ans[j].length; + if (this.check(this.ans[i], this.ans[j])) { + res = Math.max(res, x); + } + } + } + return res; + } +} + + ``` + + + + ```python + class Solution: + def __init__(self): + self.ans = [] + + def isPalindrome(self, s, ans): + a, b = 0, len(ans) - 1 + while a <= b: + if s[ans[a]] != s[ans[b]]: + return False + a += 1 + b -= 1 + return True + + def check(self, a, b): + for i in a: + for j in b: + if i == j: + return False + return True + + def sub(self, nums, i, temp): + if self.isPalindrome(nums, temp): + self.ans.append(temp[:]) + if i >= len(nums): + return + + temp.append(i) + self.sub(nums, i + 1, temp) + + temp.pop() + self.sub(nums, i + 1, temp) + + def maxProduct(self, s): + temp = [] + self.sub(s, 0, temp) + res = 0 + for i in range(len(self.ans)): + for j in range(i + 1, len(self.ans)): + x = len(self.ans[i]) * len(self.ans[j]) + if self.check(self.ans[i], self.ans[j]): + res = max(res, x) + return res + + ``` + + + + + ```java + import java.util.ArrayList; +import java.util.List; + +class Solution { + public List> ans = new ArrayList<>(); + + public boolean isPalindrome(String s, List ans) { + int a = 0, b = ans.size() - 1; + while (a <= b) { + if (s.charAt(ans.get(a)) != s.charAt(ans.get(b))) + return false; + a++; + b--; + } + return true; + } + + public boolean check(List a, List b) { + for (int i = 0; i < a.size(); i++) + for (int j = 0; j < b.size(); j++) + if (a.get(i).equals(b.get(j))) + return false; + return true; + } + + public void sub(String nums, int i, List temp) { + if (isPalindrome(nums, temp)) + ans.add(new ArrayList<>(temp)); + if (i >= nums.length()) { + return; + } + + temp.add(i); + sub(nums, i + 1, temp); + + temp.remove(temp.size() - 1); + sub(nums, i + 1, temp); + } + + public int maxProduct(String s) { + List temp = new ArrayList<>(); + sub(s, 0, temp); + int res = 0; + for (int i = 0; i < ans.size(); i++) { + for (int j = i + 1; j < ans.size(); j++) { + int x = ans.get(i).size() * ans.get(j).size(); + if (check(ans.get(i), ans.get(j))) { + res = Math.max(res, x); + } + } + } + return res; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + vector> ans; + bool isPalindrome(string& s, vector& ans) { + int a = 0, b = ans.size() - 1; + while (a <= b) { + if (s[ans[a]] != s[ans[b]]) + return false; + a++; + b--; + } + return true; + } + + bool check(vector& a, vector& b) { + for (int i = 0; i < a.size(); i++) + for (int j = 0; j < b.size(); j++) + if (a[i] == b[j]) + return false; + return true; + } + + void sub(string &nums, int i, vector& temp) { + if (isPalindrome(nums, temp)) + ans.push_back(temp); + if (i >= nums.size()) { + return; + } + + temp.push_back(i); + sub(nums, i + 1, temp); + + temp.pop_back(); + sub(nums, i + 1, temp); + } + + int maxProduct(string s) { + vector temp; + sub(s , 0 ,temp); + int res = 0; + for (int i = 0; i < ans.size(); i++) { + for (int j = i + 1; j < ans.size(); j++) { + int x = static_cast(ans[i].size() * ans[j].size()); + if (check(ans[i], ans[j])) { + res = max(res, x); + } + } + } + return res; + } +}; +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [ Maximum Product of the Length of Two Palindromic Subsequences](https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/description/) + diff --git a/solutions/lc-solutions/2000-2099/2003-smallest-missing-genetic-value-in-each-subtree.md b/solutions/lc-solutions/2000-2099/2003-smallest-missing-genetic-value-in-each-subtree.md new file mode 100644 index 0000000..56afee9 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2003-smallest-missing-genetic-value-in-each-subtree.md @@ -0,0 +1,156 @@ +--- +id: smallest-missing-genetic-value-in-each-subtree +title: Smallest Missing Genetic Value in Each Subtree +sidebar_label: 2003 Smallest Missing Genetic Value in Each Subtree +tags: + - Tree + - Dynamic Programming + - Depth-First Search + - LeetCode + - C++ +description: "This is a solution to the Smallest Missing Genetic Value in Each Subtree problem on LeetCode." +sidebar_position: 2003 +--- + +## Problem Description + +There is a family tree rooted at 0 consisting of `n` nodes numbered `0` to `n - 1`. You are given a 0-indexed integer array `parents`, where `parents[i]` is the parent for node `i`. Since node 0 is the root, `parents[0] == -1`. + +There are `10^5` genetic values, each represented by an integer in the inclusive range `[1, 10^5]`. You are given a 0-indexed integer array `nums`, where `nums[i]` is a distinct genetic value for node `i`. + +Return an array `ans` of length `n` where `ans[i]` is the smallest genetic value that is missing from the subtree rooted at node `i`. + +The subtree rooted at a node `x` contains node `x` and all of its descendant nodes. + +### Examples + +**Example 1:** + +``` +Input: parents = [-1,0,0,2], nums = [1,2,3,4] +Output: [5,1,1,1] +Explanation: The answer for each subtree is calculated as follows: + +0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value. +1: The subtree contains only node 1 with value 2. 1 is the smallest missing value. +2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value. +3: The subtree contains only node 3 with value 4. 1 is the smallest missing value. +``` + + +**Example 2:** + +``` +Input: parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3] +Output: [7,1,1,4,2,1] +Explanation: The answer for each subtree is calculated as follows: + +0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value. +1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value. +2: The subtree contains only node 2 with value 6. 1 is the smallest missing value. +3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value. +4: The subtree contains only node 4 with value 1. 2 is the smallest missing value. +5: The subtree contains only node 5 with value 3. 1 is the smallest missing value. +``` + + +**Example 3:** + +``` +Input: parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8] +Output: [1,1,1,1,1,1,1] +Explanation: The value 1 is missing from all the subtrees. +``` + + +### Constraints + +- `n == parents.length == nums.length` +- `2 <= n <= 10^5` +- `0 <= parents[i] <= n - 1 for i != 0` +- `parents[0] == -1` +- `parents` represents a valid tree. +- `1 <= nums[i] <= 10^5` +- Each `nums[i]` is distinct. + +### Approach + +To solve this problem, we will use a Depth-First Search (DFS) approach to traverse the tree. We will maintain an array `ans` where `ans[i]` will store the smallest missing genetic value for the subtree rooted at node `i`. + +1. Construct the tree from the `parents` array. +2. Use DFS to traverse the tree and keep track of the genetic values present in the subtree using a set. +3. For each node, find the smallest missing genetic value by checking sequentially from 1 onwards. +4. Store the result in the `ans` array. + +### Complexity + +- **Time complexity**: $O(n + k)$, where `n` is the number of nodes and `k` is the maximum value in `nums`. +- **Space complexity**: $O(n + k)$, for storing the tree and the set of genetic values. + +### Solution + +#### C++ + +```cpp +class Solution { +public: + vector smallestMissingValueSubtree(vector& parents, vector& nums) { + int n = parents.size(); + vector> tree(n); + for (int i = 1; i < n; ++i) { + tree[parents[i]].push_back(i); + } + + vector ans(n, 1); + vector visited(100001, 0); + + function dfs = [&](int node) { + visited[nums[node]] = 1; + for (int child : tree[node]) { + dfs(child); + } + while (visited[ans[node]]) { + ans[node]++; + } + }; + + dfs(0); + return ans; + } +}; +``` + +#### Java + +```java +class Solution { + public int[] smallestMissingValueSubtree(int[] parents, int[] nums) { + int n = parents.length; + List[] tree = new ArrayList[n]; + for (int i = 0; i < n; i++) { + tree[i] = new ArrayList<>(); + } + for (int i = 1; i < n; i++) { + tree[parents[i]].add(i); + } + + int[] ans = new int[n]; + Arrays.fill(ans, 1); + boolean[] visited = new boolean[100001]; + + dfs(tree, nums, visited, ans, 0); + + return ans; + } + + private void dfs(List[] tree, int[] nums, boolean[] visited, int[] ans, int node) { + visited[nums[node]] = true; + for (int child : tree[node]) { + dfs(tree, nums, visited, ans, child); + } + while (visited[ans[node]]) { + ans[node]++; + } + } +} +``` diff --git a/solutions/lc-solutions/2000-2099/2004-number-of-seniors-and-juniors-to-join-the-company.md b/solutions/lc-solutions/2000-2099/2004-number-of-seniors-and-juniors-to-join-the-company.md new file mode 100644 index 0000000..d0f6b8a --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2004-number-of-seniors-and-juniors-to-join-the-company.md @@ -0,0 +1,117 @@ +--- +id: number-of-seniors-and-juniors-to-join-the-company +title: The Number of Seniors and Juniors to Join the Company +sidebar_label: 2004 The Number of Seniors and Juniors to Join the Company +tags: + - SQL + - LeetCode +description: "This is a solution to the The Number of Seniors and Juniors to Join the Company problem on LeetCode." +sidebar_position: 2004 +--- + +## Problem Description + +Table: Candidates + +| Column Name | Type | +|-------------|------| +| employee_id | int | +| experience | enum | +| salary | int | + +- `employee_id` is the primary key column for this table. +- `experience` is an enum with one of the values ('Senior', 'Junior'). +- Each row of this table indicates the id of a candidate, their monthly salary, and their experience. + +A company wants to hire new employees. The budget of the company for the salaries is $70,000. The company's criteria for hiring are: + +1. Hiring the largest number of seniors. +2. After hiring the maximum number of seniors, use the remaining budget to hire the largest number of juniors. + +Write an SQL query to find the number of seniors and juniors hired under the mentioned criteria. + +Return the result table in any order. + +### Examples + +**Example 1:** + +``` +Input: +Candidates table: + +| employee_id | experience | salary | +|-------------|------------|--------| +| 1 | Junior | 10000 | +| 9 | Junior | 10000 | +| 2 | Senior | 20000 | +| 11 | Senior | 20000 | +| 13 | Senior | 50000 | +| 4 | Junior | 40000 | + +Output: + +| experience | accepted_candidates | +|------------|---------------------| +| Senior | 2 | +| Junior | 2 | + +Explanation: +We can hire 2 seniors with IDs (2, 11). Since the budget is $70,000 and the sum of their salaries is $40,000, we still have $30,000 but they are not enough to hire the senior candidate with ID 13. +We can hire 2 juniors with IDs (1, 9). Since the remaining budget is $30,000 and the sum of their salaries is $20,000, we still have $10,000 but they are not enough to hire the junior candidate with ID 4. +``` + +**Example 2:** + +``` +Input: +Candidates table: + +| employee_id | experience | salary | +|-------------|------------|--------| +| 1 | Junior | 10000 | +| 9 | Junior | 10000 | +| 2 | Senior | 80000 | +| 11 | Senior | 80000 | +| 13 | Senior | 80000 | +| 4 | Junior | 40000 | + +Output: + +| experience | accepted_candidates | +|------------|---------------------| +| Senior | 0 | +| Junior | 3 | + +Explanation: +We cannot hire any seniors with the current budget as we need at least $80,000 to hire one senior. +We can hire all three juniors with the remaining budget. +``` + +### Approach + +To solve this problem, we can use the following SQL query. We need to first calculate the number of seniors that can be hired within the budget. After hiring the maximum number of seniors, we calculate the remaining budget and then determine the number of juniors that can be hired with this remaining budget. + +#### SQL + +```sql +WITH SeniorCandidates AS ( + SELECT COUNT(*) AS num_seniors, SUM(salary) AS total_senior_salary + FROM Candidates + WHERE experience = 'Senior' + HAVING SUM(salary) <= 70000 +), +JuniorCandidates AS ( + SELECT COUNT(*) AS num_juniors, SUM(salary) AS total_junior_salary + FROM Candidates + WHERE experience = 'Junior' + HAVING SUM(salary) <= 70000 - COALESCE((SELECT total_senior_salary FROM SeniorCandidates), 0) +) +SELECT + 'Senior' AS experience, + COALESCE((SELECT num_seniors FROM SeniorCandidates), 0) AS accepted_candidates +UNION +SELECT + 'Junior' AS experience, + COALESCE((SELECT num_juniors FROM JuniorCandidates), 0) AS accepted_candidates; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2005-subtree-removal-game-with-fibonacci-tree.md b/solutions/lc-solutions/2000-2099/2005-subtree-removal-game-with-fibonacci-tree.md new file mode 100644 index 0000000..2bea2e0 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2005-subtree-removal-game-with-fibonacci-tree.md @@ -0,0 +1,144 @@ +--- +id: subtree-removal-game-with-fibonacci-tree +title: Subtree Removal Game with Fibonacci Tree +sidebar_label: 2005 Subtree Removal Game with Fibonacci Tree +tags: + - Binary Tree + - Dynamic Programming + - Game Theory + - LeetCode +description: "This is a solution to the Subtree Removal Game with Fibonacci Tree problem on LeetCode." +sidebar_position: 2005 +--- + +## Problem Description + +A Fibonacci tree is a binary tree created using the order function `order(n)`: + +- `order(0)` is the empty tree. +- `order(1)` is a binary tree with only one node. +- `order(n)` is a binary tree that consists of a root node with the left subtree as `order(n - 2)` and the right subtree as `order(n - 1)`. + +Alice and Bob are playing a game with a Fibonacci tree with Alice starting first. On each turn, a player selects a node and removes that node and its subtree. The player that is forced to delete the root loses. + +Given the integer `n`, return `true` if Alice wins the game or `false` if Bob wins, assuming both players play optimally. + +A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. + +### Examples + +**Example 1:** + +``` +Input: `n = 3` +Output: `true` +Explanation: +Alice takes the node `1` in the right subtree. +Bob takes either the `1` in the left subtree or the `2` in the right subtree. +Alice takes whichever node Bob doesn't take. +Bob is forced to take the root node `3`, so Bob will lose. +Return `true` because Alice wins. +``` + +**Example 2:** +``` +Input: `n = 1` +Output: `false` +Explanation: +Alice is forced to take the root node `1`, so Alice will lose. +Return `false` because Alice loses. +``` + +**Example 3:** + +``` +Input: `n = 2` +Output: `true` +Explanation: +Alice takes the node `1`. +Bob is forced to take the root node `2`, so Bob will lose. +Return `true` because Alice wins. +``` + +### Constraints + +- `1 <= n <= 100` + +### Approach + +The solution to this problem relies on game theory. We need to determine whether Alice can force a win by always making optimal moves. + +The Fibonacci tree grows in a specific way, and we can use dynamic programming to determine the winner for any given `n`. + +We can observe that: +- For `n = 1`, Bob wins because Alice is forced to remove the root node. +- For `n = 2`, Alice wins because she can remove the single node in the right subtree, forcing Bob to remove the root node. + +This pattern can be extended. We'll use a dynamic programming array `dp` where `dp[i]` is `true` if Alice wins with a tree of order `i`, and `false` otherwise. + +The recursion relies on two main observations: +1. If `dp[n-1]` is `false` or `dp[n-2]` is `false`, then `dp[n]` should be `true` because Alice can force Bob into a losing position. +2. Otherwise, `dp[n]` is `false`. + +#### C++ + +```cpp +class Solution { +public: + bool aliceWins(int n) { + // Initialize a dp array where dp[i] will be true if Alice wins with a tree of order i + vector dp(n + 1, false); + + // Base cases + if (n >= 1) dp[1] = false; // Bob wins if there's only one node + if (n >= 2) dp[2] = true; // Alice wins if there are two nodes + + // Fill the dp array based on the previous results + for (int i = 3; i <= n; ++i) { + dp[i] = !dp[i - 1] || !dp[i - 2]; + } + + // The result for the given n is stored in dp[n] + return dp[n]; + } +}; + +// Example usage +int main() { + Solution solution; + // Test the function with examples + bool result1 = solution.aliceWins(3); // Expected output: true + bool result2 = solution.aliceWins(1); // Expected output: false + bool result3 = solution.aliceWins(2); // Expected output: true + + // Print the results + printf("Result for n = 3: %s\n", result1 ? "true" : "false"); + printf("Result for n = 1: %s\n", result2 ? "true" : "false"); + printf("Result for n = 2: %s\n", result3 ? "true" : "false"); + + return 0; +} +``` + +#### Python + +```python +def alice_wins(n: int) -> bool: + dp = [False] * (n + 1) + if n >= 1: + dp[1] = False # Base case: Bob wins if there's only one node + if n >= 2: + dp[2] = True # Base case: Alice wins if there are two nodes + + for i in range(3, n + 1): + dp[i] = not dp[i - 1] or not dp[i - 2] + + return dp[n] + +# Test the function with examples +print(alice_wins(3)) # Output: true +print(alice_wins(1)) # Output: false +print(alice_wins(2)) # Output: true + +``` + diff --git a/solutions/lc-solutions/2000-2099/2006-count-number-of-pairs-with-absolute-difference-k.md b/solutions/lc-solutions/2000-2099/2006-count-number-of-pairs-with-absolute-difference-k.md new file mode 100644 index 0000000..c2b2b46 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2006-count-number-of-pairs-with-absolute-difference-k.md @@ -0,0 +1,113 @@ +--- +id: count-number-of-pairs-with-absolute-difference-k +title: Count Number of Pairs With Absolute Difference K +sidebar_label: 2006 Count Number of Pairs With Absolute Difference K +tags: + - Array + - LeetCode +description: "This is a solution to the Count Number of Pairs With Absolute Difference K problem on LeetCode." +sidebar_position: 2006 +--- + +## Problem Description + +You are given an integer array `nums` and an integer `k`. Return the number of pairs `(i, j)` where `i < j` such that `|nums[i] - nums[j]| == k`. + +The value of `|x|` is defined as: +- `x` if `x >= 0` +- `-x` if `x < 0` + +### Examples + +**Example 1:** +``` +Input: nums = [1,2,2,1], k = 1 +Output: 4 +Explanation: The pairs with an absolute difference of 1 are: +- (0,1) +- (0,2) +- (1,3) +- (2,3) +``` + + +**Example 2:** +``` +Input: nums = [1,3], k = 2 +Output: 0 +Explanation: There are no pairs with an absolute difference of 2. +``` + +**Example 3:** +``` +Input: nums = [3,2,1,5,4], k = 2 +Output: 3 +Explanation: The pairs with an absolute difference of 2 are: +- [3,2,1,5,4] +- [3,2,1,5,4] +- [3,2,1,5,4] +``` +## Constraints + +- `1 <= nums.length <= 200` +- `1 <= nums[i] <= 100` +- `1 <= k <= 99` + +## Approach + +To solve this problem efficiently: +1. Use a hash map (`freq`) to count occurrences of each number in `nums`. +2. Iterate through each number `num` in `nums`: + - Check if `num - k` exists in `freq`: + - If yes, add `freq[num - k]` to the count of valid pairs. + - Check if `num + k` exists in `freq`: + - If yes (and `k` is not zero to avoid double counting), add `freq[num + k]` to the count. +3. Update `freq[num]` after processing each number to ensure correct counts for subsequent pairs. + +This approach ensures that we count pairs in linear time `O(n)`, where `n` is the length of `nums`, due to the efficient lookups and updates in the hash map. + +#### C++ + +```cpp + +class Solution { +public: + int countPairs(vector& nums, int k) { + unordered_map freq; + int count = 0; + + for (int num : nums) { + if (freq.count(num - k)) { + count += freq[num - k]; + } + if (freq.count(num + k) && k != 0) { // Avoid double counting when k == 0 + count += freq[num + k]; + } + freq[num]++; + } + + return count; + } +}; +``` + +#### Python + +```python +def countPairs(nums, k): + freq = {} + count = 0 + + for num in nums: + if num - k in freq: + count += freq[num - k] + if num + k in freq and k != 0: # Avoid double counting when k == 0 + count += freq[num + k] + + if num in freq: + freq[num] += 1 + else: + freq[num] = 1 + + return count +``` diff --git a/solutions/lc-solutions/2000-2099/2007-find-original-array-from-doubled-array.md b/solutions/lc-solutions/2000-2099/2007-find-original-array-from-doubled-array.md new file mode 100644 index 0000000..c982651 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2007-find-original-array-from-doubled-array.md @@ -0,0 +1,97 @@ +--- +id: find-original-array-from-doubled-array +title: Find Original Array From Doubled Array +sidebar_label: 2007 Find Original Array From Doubled Array +tags: + - Array + - Hash Table + - Sorting + - LeetCode +description: "This is a solution to the Find Original Array From Doubled Array problem on LeetCode." +sidebar_position: 2007 +--- + +## Problem Description + +An integer array `original` is transformed into a doubled array `changed` by appending twice the value of every element in `original`, and then randomly shuffling the resulting array. + +Given an array `changed`, return `original` if `changed` is a doubled array. If `changed` is not a doubled array, return an empty array. The elements in `original` may be returned in any order. + +## Examples + +**Example 1:** +``` +Input: changed = [1,3,4,2,6,8] +Output: [1,3,4] +Explanation: One possible original array could be [1,3,4]: + +Twice the value of 1 is 1 * 2 = 2. +Twice the value of 3 is 3 * 2 = 6. +Twice the value of 4 is 4 * 2 = 8. +Other original arrays could be [4,3,1] or [3,1,4]. + +``` + +**Example 2:** +``` +Input: changed = [6,3,0,1] +Output: [] +Explanation: changed is not a doubled array. +``` + +**Example 3:** + +``` +Input: changed = [1] +Output: [] +Explanation: changed is not a doubled array. +``` + +## Constraints + +- `1 <= changed.length <= 10^5` +- `0 <= changed[i] <= 10^5` + +## Approach + +To solve this problem efficiently: +1. Use a hash map (`freq`) to count occurrences of each number in `changed`. +2. Sort `changed` to process elements in increasing order. +3. Iterate through each number `num` in sorted `changed`: + - Check if `freq[num]` is greater than `freq[2 * num]`: + - If yes, return an empty array since `changed` cannot be a doubled array. + - Decrease `freq[num]` and `freq[2 * num]` accordingly. +4. After iterating through all elements, construct and return the original array from `freq`. + +This approach ensures correctness by leveraging sorting and counting with a hash map to validate if `changed` can indeed represent a doubled array of some original array `original`. + +#### C++ Solution + +```cpp +class Solution { +public: + vector findOriginalArray(vector& changed) { + unordered_map freq; + vector original; + + for (int num : changed) { + freq[num]++; + } + + sort(changed.begin(), changed.end()); + + for (int num : changed) { + if (freq[num] > freq[2 * num]) { + return {}; + } + for (int i = 0; i < freq[num]; ++i) { + original.push_back(num); + freq[2 * num]--; + } + freq[num] = 0; + } + + return original; + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2008-maximum-earnings-from-taxi.md b/solutions/lc-solutions/2000-2099/2008-maximum-earnings-from-taxi.md new file mode 100644 index 0000000..cc60ba7 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2008-maximum-earnings-from-taxi.md @@ -0,0 +1,100 @@ +--- +id: maximum-earnings-from-taxi +title: Maximum Earnings From Taxi +sidebar_label: 2008 Maximum Earnings From Taxi +tags: + - Array + - Dynamic Programming + - Greedy + - LeetCode +description: "This is a solution to the Maximum Earnings From Taxi problem on LeetCode." +sidebar_position: 2008 +--- + +## Problem Description + +There are `n` points on a road labeled from 1 to `n` in the direction you are going. You want to drive from point 1 to point `n` to make money by picking up passengers. You cannot change the direction of the taxi. + +Passengers are represented by a 0-indexed 2D integer array `rides`, where `rides[i] = [starti, endi, tipi]` denotes the `i-th` passenger requesting a ride from point `starti` to point `endi` and is willing to give a `tipi` dollar tip. + +For each passenger you pick up, you earn `endi - starti + tipi` dollars. You may only drive at most one passenger at a time. + +Given `n` and `rides`, return the maximum number of dollars you can earn by picking up passengers optimally. + +## Examples + +**Example 1:** + +``` +Input: n = 5, rides = [[2,5,4],[1,5,1]] +Output: 7 +Explanation: We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars. + +``` + +**Example 2:** + +``` +Input: n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]] +Output: 20 +Explanation: We will pick up the following passengers: + +Drive passenger 1 from point 3 to point 10 for a profit of 10 - 3 + 2 = 9 dollars. +Drive passenger 2 from point 10 to point 12 for a profit of 12 - 10 + 3 = 5 dollars. +Drive passenger 5 from point 13 to point 18 for a profit of 18 - 13 + 1 = 6 dollars. +We earn 9 + 5 + 6 = 20 dollars in total. +``` + +## Constraints + +- `1 <= n <= 10^5` +- `1 <= rides.length <= 3 * 10^4` +- `rides[i].length == 3` +- `1 <= starti < endi <= n` +- `1 <= tipi <= 10^5` + +## Approach + +To solve this problem efficiently: +1. Sort the `rides` array based on the end points `endi`. If two rides end at the same point, sort by their start points `starti`. +2. Use dynamic programming (DP) to compute the maximum earnings up to each endpoint `endi`: + - Initialize a DP array `dp` where `dp[i]` represents the maximum earnings up to point `i`. + - Iterate through each ride and update `dp[endi]` with the maximum earnings considering picking up the ride or not. +3. Traverse the `dp` array to find the maximum earnings possible by the endpoint `n`. + +This approach ensures efficiency by leveraging sorting and dynamic programming to compute the optimal solution. + +#### C++ Solution + +```cpp +class Solution { +public: + long long maxTaxiEarnings(int n, vector>& rides) { + sort(rides.begin(), rides.end(), [](const vector& a, const vector& b) { + if (a[1] == b[1]) { + return a[0] < b[0]; + } + return a[1] < b[1]; + }); + + vector dp(n + 1); + int j = 0; + long long maxProfit = 0; + + for (int i = 1; i <= n; ++i) { + dp[i] = dp[i - 1]; + while (j < rides.size() && rides[j][1] == i) { + int start = rides[j][0]; + int end = rides[j][1]; + int tip = rides[j][2]; + long long profit = end - start + tip; + dp[end] = max(dp[end], dp[start] + profit); + ++j; + } + maxProfit = max(maxProfit, dp[i]); + } + + return maxProfit; + } +}; +``` diff --git a/solutions/lc-solutions/2000-2099/2009-minimum-number-of-operations-to-make-array-continuous.md b/solutions/lc-solutions/2000-2099/2009-minimum-number-of-operations-to-make-array-continuous.md new file mode 100644 index 0000000..e0c0875 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2009-minimum-number-of-operations-to-make-array-continuous.md @@ -0,0 +1,93 @@ +--- +id: minimum-number-of-operations-to-make-array-continuous +title: Minimum Number of Operations to Make Array Continuous +sidebar_label: 2009 Minimum Number of Operations to Make Array Continuous +tags: + - Array + - Sorting + - Sliding Window + - LeetCode +description: "This is a solution to the Minimum Number of Operations to Make Array Continuous problem on LeetCode." +sidebar_position: 2009 +--- + +## Problem Description + +You are given an integer array `nums`. In one operation, you can replace any element in `nums` with any integer. + +`nums` is considered continuous if both of the following conditions are fulfilled: + +1. All elements in `nums` are unique. +2. The difference between the maximum element and the minimum element in `nums` equals `nums.length - 1`. + +For example, `nums = [4, 2, 5, 3]` is continuous, but `nums = [1, 2, 3, 5, 6]` is not continuous. + +Return the minimum number of operations to make `nums` continuous. + +### Examples + +**Example 1:** + +``` +Input: nums = [4,2,5,3] +Output: 0 +Explanation: nums is already continuous. +``` + +**Example 2:** + +``` +Input: nums = [1,2,3,5,6] +Output: 1 +Explanation: One possible solution is to change the last element to 4. +The resulting array is [1,2,3,5,4], which is continuous. +``` + +**Example 3:** + +``` +Input: nums = [1,10,100,1000] +Output: 3 +Explanation: One possible solution is to: + +Change the second element to 2. +Change the third element to 3. +Change the fourth element to 4. +The resulting array is [1,2,3,4], which is continuous. +``` + + +### Constraints + +- `1 <= nums.length <= 10^5` +- `1 <= nums[i] <= 10^9` + +### Approach + +To solve this problem: +1. Sort the array `nums` to facilitate finding the longest continuous subsequence. +2. Use a sliding window to find the longest subsequence that satisfies the conditions of being continuous. +3. Calculate the minimum number of operations as the difference between the length of `nums` and the length of the longest continuous subsequence found. + +#### C++ Solution + +```cpp +class Solution { +public: + int minOperations(vector& nums) { + sort(nums.begin(), nums.end()); + nums.erase(unique(nums.begin(), nums.end()), nums.end()); + + int n = nums.size(); + int ans = n; + for (int i = 0, j = 0; i < n; ++i) { + while (j < n && nums[j] <= nums[i] + n - 1) { + ++j; + } + ans = min(ans, n - (j - i)); + } + + return ans; + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2010-number-of-seniors-and-juniors-to-join-the-company-ii.md b/solutions/lc-solutions/2000-2099/2010-number-of-seniors-and-juniors-to-join-the-company-ii.md new file mode 100644 index 0000000..d8dd140 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2010-number-of-seniors-and-juniors-to-join-the-company-ii.md @@ -0,0 +1,133 @@ +--- +id: number-of-seniors-and-juniors-to-join-the-company-ii +title: The Number of Seniors and Juniors to Join the Company II +sidebar_label: 2010 The Number of Seniors and Juniors to Join the Company II +tags: + - SQL + - Hiring + - Company + - Leetcode +description: "This is a solution to the problem The Number of Seniors and Juniors to Join the Company II." +sidebar_position: 2010 +--- + +## Problem Description + +A company wants to hire new employees. The budget of the company for the salaries is $70,000. The company's criteria for hiring are: + +1. Keep hiring the senior with the smallest salary until you cannot hire any more seniors. +2. Use the remaining budget to hire the junior with the smallest salary. +3. Keep hiring the junior with the smallest salary until you cannot hire any more juniors. + +Write an SQL query to find the IDs of seniors and juniors hired under the mentioned criteria. + +Return the result table in any order. + +### Example 1: + +``` + +Input: + +Candidates table: +| employee_id | experience | salary | +|-------------|------------|--------| +| 1 | Junior | 10000 | +| 9 | Junior | 15000 | +| 2 | Senior | 20000 | +| 11 | Senior | 16000 | +| 13 | Senior | 50000 | +| 4 | Junior | 40000 | + +Output: +| employee_id | +|-------------| +| 11 | +| 2 | +| 1 | +| 9 | + +Explanation: +We can hire 2 seniors with IDs (11, 2). Since the budget is $70,000 and the sum of their salaries is $36,000, we still have $34,000 but they are not enough to hire the senior candidate with ID 13. +We can hire 2 juniors with IDs (1, 9). Since the remaining budget is $34,000 and the sum of their salaries is $25,000, we still have $9,000 but they are not enough to hire the junior candidate with ID 4. + +``` + +### Example 2: + +``` +Input: + +Candidates table: +| employee_id | experience | salary | +|-------------|------------|--------| +| 1 | Junior | 25000 | +| 9 | Junior | 10000 | +| 2 | Senior | 85000 | +| 11 | Senior | 80000 | +| 13 | Senior | 90000 | +| 4 | Junior | 30000 | + +Output: +| employee_id | +|-------------| +| 9 | +| 1 | +| 4 | + +Explanation: +We cannot hire any seniors with the current budget as we need at least $80,000 to hire one senior. +We can hire all three juniors with the remaining budget. + +``` + +## Approach + +To solve this problem, we can use a combination of window functions and common table expressions (CTEs) to track the cumulative sum of salaries for seniors and juniors, ensuring we stay within the budget. + +#### SQL Solution + +```sql +WITH Seniors AS ( + SELECT + employee_id, + salary, + SUM(salary) OVER (ORDER BY salary) AS cumulative_salary + FROM Candidates + WHERE experience = 'Senior' +), +HiredSeniors AS ( + SELECT + employee_id, + salary + FROM Seniors + WHERE cumulative_salary <= 70000 +), +RemainingBudget AS ( + SELECT + 70000 - IFNULL(MAX(cumulative_salary), 0) AS budget_left + FROM Seniors + WHERE cumulative_salary <= 70000 +), +Juniors AS ( + SELECT + employee_id, + salary, + SUM(salary) OVER (ORDER BY salary) AS cumulative_salary + FROM Candidates + WHERE experience = 'Junior' +), +HiredJuniors AS ( + SELECT + employee_id, + salary + FROM Juniors, RemainingBudget + WHERE cumulative_salary <= budget_left +) +SELECT employee_id +FROM HiredSeniors +UNION ALL +SELECT employee_id +FROM HiredJuniors; +``` + diff --git a/solutions/lc-solutions/2000-2099/2011-final-value-of-variable-after-performing-operations.md b/solutions/lc-solutions/2000-2099/2011-final-value-of-variable-after-performing-operations.md new file mode 100644 index 0000000..99794cd --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2011-final-value-of-variable-after-performing-operations.md @@ -0,0 +1,112 @@ +--- +id: final-value-of-variable-after-performing-operations +title: Final Value of Variable After Performing Operations +sidebar_label: 2011 Final Value of Variable After Performing Operations +tags: + - Array + - Simulation + - LeetCode +description: "This is a solution to the Final Value of Variable After Performing Operations problem on LeetCode." +sidebar_position: 2011 +--- + +## Problem Description + +There is a programming language with only four operations and one variable `X`: + +- `++X` and `X++` increment the value of the variable `X` by 1. +- `--X` and `X--` decrement the value of the variable `X` by 1. + +Initially, the value of `X` is 0. + +Given an array of strings `operations` containing a list of operations, return the final value of `X` after performing all the operations. + +### Examples + +**Example 1:** + +``` +Input: operations = ["--X","X++","X++"] +Output: 1 +Explanation: The operations are performed as follows: +Initially, X = 0. +--X: X is decremented by 1, X = 0 - 1 = -1. +X++: X is incremented by 1, X = -1 + 1 = 0. +X++: X is incremented by 1, X = 0 + 1 = 1. + +``` + +**Example 2:** + +``` + +Input: operations = ["++X","++X","X++"] +Output: 3 +Explanation: The operations are performed as follows: +Initially, X = 0. +++X: X is incremented by 1, X = 0 + 1 = 1. +++X: X is incremented by 1, X = 1 + 1 = 2. +X++: X is incremented by 1, X = 2 + 1 = 3. + +``` + +**Example 3:** + +``` + +Input: operations = ["X++","++X","--X","X--"] +Output: 0 +Explanation: The operations are performed as follows: +Initially, X = 0. +X++: X is incremented by 1, X = 0 + 1 = 1. +++X: X is incremented by 1, X = 1 + 1 = 2. +--X: X is decremented by 1, X = 2 - 1 = 1. +X--: X is decremented by 1, X = 1 - 1 = 0. +``` + +### Constraints + +- `1 <= operations.length <= 100` +- `operations[i]` will be either `"++X"`, `"X++"`, `"--X"`, or `"X--"`. + +### Approach + +To solve this problem, we will: +1. Initialize `X` to 0. +2. Iterate through each operation in the `operations` array. +3. Depending on the operation, increment or decrement `X`. +4. Return the final value of `X`. + +#### C++ + +``` cpp +class Solution { +public: + int finalValueAfterOperations(std::vector& operations) { + int X = 0; + for (const auto& operation : operations) { + if (operation == "++X" || operation == "X++") { + X += 1; + } else { + X -= 1; + } + } + return X; + } +}; + +``` + +#### Python + +``` python + +def finalValueAfterOperations(operations): + X = 0 + for operation in operations: + if operation == "++X" or operation == "X++": + X += 1 + else: + X -= 1 + return X +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2012-sum-of-beauty-in-the-array.md b/solutions/lc-solutions/2000-2099/2012-sum-of-beauty-in-the-array.md new file mode 100644 index 0000000..8f4c357 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2012-sum-of-beauty-in-the-array.md @@ -0,0 +1,108 @@ +--- +id: sum-of-beauty-in-the-array +title: Sum of Beauty in the Array +sidebar_label: 2012 Sum of Beauty in the Array +tags: + - Array + - Prefix Sum + - LeetCode +description: "This is a solution to the Sum of Beauty in the Array problem on LeetCode." +sidebar_position: 2012 +--- + +## Problem Description + +You are given a 0-indexed integer array `nums`. For each index `i` (`1 <= i <= nums.length - 2`) the beauty of `nums[i]` equals: +- 2, if `nums[j] < nums[i] < nums[k]`, for all `0 <= j < i` and for all `i < k <= nums.length - 1`. +- 1, if `nums[i - 1] < nums[i] < nums[i + 1]`, and the previous condition is not satisfied. +- 0, if none of the previous conditions holds. + +Return the sum of beauty of all `nums[i]` where `1 <= i <= nums.length - 2`. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,3] +Output: 2 +Explanation: For each index i in the range 1 <= i <= 1: + +The beauty of nums[1] equals 2. +``` + +**Example 2:** + +``` +Input: nums = [2,4,6,4] +Output: 1 +Explanation: For each index i in the range 1 <= i <= 2: + +The beauty of nums[1] equals 1. +The beauty of nums[2] equals 0. +``` + +**Example 3:** + +``` +Input: nums = [3,2,1] +Output: 0 +Explanation: For each index i in the range 1 <= i <= 1: + +The beauty of nums[1] equals 0. +``` + +### Constraints + +- `3 <= nums.length <= 10^5` +- `1 <= nums[i] <= 10^5` + +## Approach + +To solve this problem efficiently, we need to use the concept of prefix and suffix arrays to keep track of the maximum and minimum values to the left and right of each index, respectively. + +Steps + +1. **Initialize Prefix and Suffix Arrays:** + - `leftMax[i]`: Maximum value from the start of the array to index `i-1`. + - `rightMin[i]`: Minimum value from index `i+1` to the end of the array. + +2. **Fill Prefix and Suffix Arrays:** + - Traverse from left to right to fill `leftMax`. + - Traverse from right to left to fill `rightMin`. + +3. **Calculate Beauty:** + - For each index `i` from 1 to `n-2`, check the conditions using `leftMax` and `rightMin` to determine the beauty and accumulate the total sum. + +#### C++ Solution + +```cpp +class Solution { +public: + int sumOfBeauties(vector& nums) { + int n = nums.size(); + vector leftMax(n, 0), rightMin(n, 0); + + leftMax[0] = nums[0]; + for (int i = 1; i < n; ++i) { + leftMax[i] = max(leftMax[i-1], nums[i]); + } + + rightMin[n-1] = nums[n-1]; + for (int i = n-2; i >= 0; --i) { + rightMin[i] = min(rightMin[i+1], nums[i]); + } + + int beautySum = 0; + for (int i = 1; i <= n-2; ++i) { + if (leftMax[i-1] < nums[i] && nums[i] < rightMin[i+1]) { + beautySum += 2; + } else if (nums[i-1] < nums[i] && nums[i] < nums[i+1]) { + beautySum += 1; + } + } + + return beautySum; + } +}; +``` diff --git a/solutions/lc-solutions/2000-2099/2013-detect-squares.md b/solutions/lc-solutions/2000-2099/2013-detect-squares.md new file mode 100644 index 0000000..d3f070e --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2013-detect-squares.md @@ -0,0 +1,94 @@ +--- +id: detect-squares +title: Detect Squares +sidebar_label: 2013 Detect Squares +tags: + - Data Structures + - HashMap + - LeetCode +description: "This is a solution to the Detect Squares problem on LeetCode." +sidebar_position: 2013 +--- + +## Problem Description + +You are given a stream of points on the X-Y plane. Design an algorithm that: +- Adds new points from the stream into a data structure. Duplicate points are allowed and should be treated as different points. +- Given a query point, counts the number of ways to choose three points from the data structure such that the three points and the query point form an axis-aligned square with positive area. + +An axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis. + +Implement the `DetectSquares` class: +- `DetectSquares()` Initializes the object with an empty data structure. +- `void add(int[] point)` Adds a new point `point = [x, y]` to the data structure. +- `int count(int[] point)` Counts the number of ways to form axis-aligned squares with `point = [x, y]` as described above. + +### Examples + +**Example 1:** + +``` +Input +["DetectSquares", "add", "add", "add", "count", "count", "add", "count"] +[[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]] +Output +[null, null, null, null, 1, 0, null, 2] +``` + + +### Constraints + +- `point.length == 2` +- `0 <= x, y <= 1000` +- At most `3000` calls in total will be made to `add` and `count`. + +## Approach + +To solve this problem, we use a hash map to store the count of points at each coordinate. This allows us to efficiently add points and count the number of squares. + +1. **Initialize Data Structures**: + - Use a hash map to count occurrences of points. + +2. **Add Points**: + - For each point, increment its count in the hash map. + +3. **Count Squares**: + - For a given query point, iterate over all points that have the same x or y coordinate. + - Check if these points can form a square with the query point. + - Count the number of valid squares and return the result. + +#### C++ Solution + +```cpp +class DetectSquares { +public: + DetectSquares() { + } + + void add(vector point) { + countMap[{point[0], point[1]}]++; + } + + int count(vector point) { + int x = point[0]; + int y = point[1]; + int result = 0; + + for (auto& p : countMap) { + int px = p.first.first; + int py = p.first.second; + + // Only consider points that form a square with (x, y) + if (abs(px - x) != abs(py - y) || px == x || py == y) continue; + + // Calculate the number of ways to form squares + result += countMap[{x, py}] * countMap[{px, y}] * countMap[{px, py}]; + } + + return result; + } + +private: + map, int> countMap; +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2014-longest-subsequence-repeated-k-times.md b/solutions/lc-solutions/2000-2099/2014-longest-subsequence-repeated-k-times.md new file mode 100644 index 0000000..e253663 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2014-longest-subsequence-repeated-k-times.md @@ -0,0 +1,351 @@ +--- +id: longest-subsequence-repeated-k-times +title: Longest Subsequence Repeated k Times +sidebar_label: 2014. Longest Subsequence Repeated k Times + +tags: +- String +- Backtracking +- Greedy +- Counting +- Enumeration + +description: "This is a solution to the Longest Subsequence Repeated k Times problem on LeetCode." +--- + +## Problem Description +You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s. + +A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. + +A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times. + +For example, "bba" is repeated 2 times in the string "bababcba", because the string "bbabba", constructed by concatenating "bba" 2 times, is a subsequence of the string "bababcba". +Return the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string. + + +### Examples +**Example 1:** +![image](https://assets.leetcode.com/uploads/2021/08/30/longest-subsequence-repeat-k-times.png) + +``` +Input: s = "letsleetcode", k = 2 +Output: "let" +Explanation: There are two longest subsequences repeated 2 times: "let" and "ete". +"let" is the lexicographically largest one. +``` + +**Example 2:** +``` +Input: s = "bb", k = 2 +Output: "b" +Explanation: The longest subsequence repeated 2 times is "b". +``` + +### Constraints +- `n == s.length` +- `2 <= n, k <= 2000` +- `2 <= n < k * 8` +- `s consists of lowercase English letters.` + +## Solution forLongest Subsequence Repeated k Times + +### Intuition + +To solve this problem, the goal is to find the longest subsequence of `s` that can appear at least `k` times in `s`. This requires checking various subsequences and determining their repeatability. The challenge is to efficiently explore the possible subsequences and verify their validity. + +### Approach +The approach involves a Depth-First Search (DFS) combined with a helper function to verify if a subsequence can be repeated `k` times. Here's a step-by-step breakdown: + +1. **DFS Traversal**: + - Use DFS to explore possible subsequences of `s`. Start with an empty subsequence and try to build it by adding characters from 'z' to 'a' (descending order helps in maximizing the subsequence length early). + - For each character added, check if the new subsequence can be repeated `k` times in `s`. + +2. **Check Repeatability**: + - Implement a helper function `checkK(s, ans, k)` to verify if the current subsequence `ans` can be repeated `k` times within `s`. + - This function iterates through `s`, matching characters of `ans` and counting how many times the entire subsequence `ans` appears. + +3. **Pruning**: + - If a subsequence `ans` cannot be repeated `k` times, prune that branch and do not explore further with this subsequence. + - This reduces unnecessary computations and helps in focusing on potential valid subsequences. + + + + #### Implementation + ```jsx live + function Solution(arr) { + function checkK(s, ans, k) { + let j = 0, m = ans.length; + for (let i = 0; i < s.length; i++) { + if (s[i] === ans[j]) j++; + if (j === m) { + k--; + if (k === 0) return true; + j = 0; + } + } + return k <= 0; + } + + function dfs(s, ans, k) { + let val = 0; + let r = ""; + for (let ch = 'z'; ch >= 'a'; ch = String.fromCharCode(ch.charCodeAt(0) - 1)) { + if (checkK(s, ans + ch, k)) { + ans += ch; + let tmp = ch + dfs(s, ans, k); + if (val < tmp.length) { + r = tmp; + val = tmp.length; + } + ans = ans.slice(0, -1); + } + } + return r; + } + + function longestSubsequenceRepeatedK(s, k) { + let ans = ""; + return dfs(s, ans, k); + } + + const input = "letsleetcode" + const k =2; + const output =longestSubsequenceRepeatedK(input ,k) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n*2^8) $ + - Space Complexity: $ O(n)$ + + ## Code in Different Languages + + + + ```javascript + checkK(s, ans, k) { + let j = 0, m = ans.length; + for (let i = 0; i < s.length; i++) { + if (s[i] === ans[j]) j++; + if (j === m) { + k--; + if (k === 0) return true; + j = 0; + } + } + return k <= 0; + } + + dfs(s, ans, k) { + let val = 0; + let r = ""; + for (let ch = 'z'; ch >= 'a'; ch = String.fromCharCode(ch.charCodeAt(0) - 1)) { + if (this.checkK(s, ans + ch, k)) { + ans += ch; + let tmp = ch + this.dfs(s, ans, k); + if (val < tmp.length) { + r = tmp; + val = tmp.length; + } + ans = ans.slice(0, -1); + } + } + return r; + } + + longestSubsequenceRepeatedK(s, k) { + let ans = ""; + return this.dfs(s, ans, k); + } + ``` + + + + + ```typescript + class Solution { + checkK(s: string, ans: string, k: number): boolean { + let j = 0, m = ans.length; + for (let i = 0; i < s.length; i++) { + if (s[i] === ans[j]) j++; + if (j === m) { + k--; + if (k === 0) return true; + j = 0; + } + } + return k <= 0; + } + + dfs(s: string, ans: string, k: number): string { + let val = 0; + let r = ""; + for (let ch = 'z'; ch >= 'a'; ch = String.fromCharCode(ch.charCodeAt(0) - 1)) { + if (this.checkK(s, ans + ch, k)) { + ans += ch; + let tmp = ch + this.dfs(s, ans, k); + if (val < tmp.length) { + r = tmp; + val = tmp.length; + } + ans = ans.slice(0, -1); + } + } + return r; + } + + longestSubsequenceRepeatedK(s: string, k: number): string { + let ans = ""; + return this.dfs(s, ans, k); + } +} + + ``` + + + + ```python + class Solution: + def checkK(self, s: str, ans: str, k: int) -> bool: + j, m = 0, len(ans) + for i in range(len(s)): + if s[i] == ans[j]: + j += 1 + if j == m: + k -= 1 + if k == 0: + return True + j = 0 + return k <= 0 + + def dfs(self, s: str, ans: str, k: int) -> str: + val = 0 + r = "" + for ch in range(ord('z'), ord('a') - 1, -1): + ch = chr(ch) + if self.checkK(s, ans + ch, k): + ans += ch + tmp = ch + self.dfs(s, ans, k) + if val < len(tmp): + r = tmp + val = len(tmp) + ans = ans[:-1] + return r + + def longestSubsequenceRepeatedK(self, s: str, k: int) -> str: + ans = "" + return self.dfs(s, ans, k) + + ``` + + + + + ```java + public class Solution { + private boolean checkK(String s, String ans, int k) { + int j = 0, m = ans.length(); + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == ans.charAt(j)) j++; + if (j == m) { + k--; + if (k == 0) return true; + j = 0; + } + } + return k <= 0; + } + + private String dfs(String s, String ans, int k) { + int val = 0; + String r = ""; + for (char ch = 'z'; ch >= 'a'; ch--) { + if (checkK(s, ans + ch, k)) { + ans += ch; + String tmp = ch + dfs(s, ans, k); + if (val < tmp.length()) { + r = tmp; + val = tmp.length(); + } + ans = ans.substring(0, ans.length() - 1); + } + } + return r; + } + + public String longestSubsequenceRepeatedK(String s, int k) { + String ans = ""; + return dfs(s, ans, k); + } +} + + ``` + + + + + ```cpp + class Solution { + bool checkK(string& s, string ans, int k) { + int j = 0, m = ans.size(); + for (int i = 0; i < s.size(); i++) { + if (s[i] == ans[j]) + j++; + if (j == m) { + --k; + if (k == 0) + return true; + j = 0; + } + } + return k <= 0; + } + string dfs(string& s, string& ans, int k) { + int val = 0; + string r = ""; + for (char ch = 'z'; ch >= 'a'; ch--) { + if (checkK(s, ans + ch, k)) { + ans += ch; + string tmp = ch + dfs(s, ans, k); + if (val < tmp.size()) { + r = tmp; + val = tmp.size(); + } + ans.pop_back(); + } + } + return r; + } + +public: + string longestSubsequenceRepeatedK(string s, int k) { + string ans = ""; + return dfs(s, ans, k); + } +}; +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Longest Subsequence Repeated k Times](https://leetcode.com/problems/longest-subsequence-repeated-k-times/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/longest-subsequence-repeated-k-times/description/) + diff --git a/solutions/lc-solutions/2000-2099/2015-average-height-of-buildings.md b/solutions/lc-solutions/2000-2099/2015-average-height-of-buildings.md new file mode 100644 index 0000000..0faa5b5 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2015-average-height-of-buildings.md @@ -0,0 +1,149 @@ +--- +id: average-height-of-buildings +title: Average Height of Buildings in Each Segment +sidebar_label: 2015 Average Height of Buildings in Each Segment +tags: + - Data Structures + - Sweep Line + - LeetCode +description: "This is a solution to the Average Height of Buildings in Each Segment problem on LeetCode." +sidebar_position: 2015 +--- + +## Problem Description + +A perfectly straight street is represented by a number line. The street has building(s) on it and is represented by a 2D integer array `buildings`, where `buildings[i] = [starti, endi, heighti]`. This means that there is a building with `heighti` in the half-closed segment `[starti, endi)`. + +You want to describe the heights of the buildings on the street with the minimum number of non-overlapping segments. The street can be represented by the 2D integer array `street` where `street[j] = [leftj, rightj, averagej]` describes a half-closed segment `[leftj, rightj)` of the road where the average heights of the buildings in the segment is `averagej`. + +For example, if `buildings = [[1,5,2],[3,10,4]]`, the street could be represented by `street = [[1,3,2],[3,5,3],[5,10,4]]` because: +- From 1 to 3, there is only the first building with an average height of 2 / 1 = 2. +- From 3 to 5, both the first and the second building are there with an average height of (2+4) / 2 = 3. +- From 5 to 10, there is only the second building with an average height of 4 / 1 = 4. + +Given `buildings`, return the 2D integer array `street` as described above (excluding any areas of the street where there are no buildings). You may return the array in any order. + +The average of `n` elements is the sum of the `n` elements divided (integer division) by `n`. + +A half-closed segment `[a, b)` is the section of the number line between points `a` and `b` including point `a` and not including point `b`. + +### Examples + +**Example 1:** + +``` + +Input: buildings = [[1,4,2],[3,9,4]] +Output: [[1,3,2],[3,4,3],[4,9,4]] +Explanation: +From 1 to 3, there is only the first building with an average height of 2 / 1 = 2. +From 3 to 4, both the first and the second building are there with an average height of (2+4) / 2 = 3. +From 4 to 9, there is only the second building with an average height of 4 / 1 = 4. + +``` + +**Example 2:** +``` +Input: buildings = [[1,3,2],[2,5,3],[2,8,3]] +Output: [[1,3,2],[3,8,3]] +Explanation: +From 1 to 2, there is only the first building with an average height of 2 / 1 = 2. +From 2 to 3, all three buildings are there with an average height of (2+3+3) / 3 = 2. +From 3 to 5, both the second and the third building are there with an average height of (3+3) / 2 = 3. +From 5 to 8, there is only the last building with an average height of 3 / 1 = 3. +The average height from 1 to 3 is the same so we can group them into one segment. +The average height from 3 to 8 is the same so we can group them into one segment. +``` + +**Example 3:** + +``` +Input: buildings = [[1,2,1],[5,6,1]] +Output: [[1,2,1],[5,6,1]] +Explanation: +From 1 to 2, there is only the first building with an average height of 1 / 1 = 1. +From 2 to 5, there are no buildings, so it is not included in the output. +From 5 to 6, there is only the second building with an average height of 1 / 1 = 1. +We cannot group the segments together because an empty space with no buildings separates the segments. +``` + +### Constraints +- `1 <= buildings.length <= 10^5` +- `buildings[i].length == 3` +- `0 <= starti < endi <= 10^8` +- `1 <= heighti <= 10^5` + +### Approach + +The problem can be solved using a sweep line algorithm. We can process the events of adding and removing buildings at their respective start and end points, maintaining the current active set of buildings, and calculating the average height for each segment. + +#### C++ + +``` cpp +class Solution { +public: + vector> averageHeightOfBuildings(vector>& buildings) { + map height, cnt; + for (auto& v : buildings) { + int s = v[0], e = v[1], h = v[2]; + cnt[s]++, cnt[e]--; + height[s] += h, height[e] -= h; + } + vector> ans; + int i = 0, h = 0, n = 0; + for (auto& [j, _] : cnt) { + if (n) { + vector t = {i, j, h / n}; + if (ans.size() && ans.back()[1] == i && ans.back()[2] == t[2]) { + ans.back()[1] = j; + } else { + ans.push_back(t); + } + } + i = j; + h += height[j]; + n += cnt[j]; + } + return ans; + } +}; +``` + +#### Java + +``` java +class Solution { + public int[][] averageHeightOfBuildings(int[][] buildings) { + TreeMap height = new TreeMap<>(); + TreeMap cnt = new TreeMap<>(); + for (var v : buildings) { + int s = v[0], e = v[1], h = v[2]; + cnt.put(s, cnt.getOrDefault(s, 0) + 1); + cnt.put(e, cnt.getOrDefault(e, 0) - 1); + height.put(s, height.getOrDefault(s, 0) + h); + height.put(e, height.getOrDefault(e, 0) - h); + } + int i = 0, h = 0, n = 0; + List res = new ArrayList<>(); + for (int j : cnt.keySet()) { + if (n > 0) { + int[] t = new int[] {i, j, h / n}; + int k = res.size() - 1; + if (k >= 0 && res.get(k)[1] == i && res.get(k)[2] == t[2]) { + res.get(k)[1] = j; + } else { + res.add(t); + } + } + h += height.get(j); + n += cnt.get(j); + i = j; + } + int[][] ans = new int[res.size()][3]; + for (i = 0; i < ans.length; ++i) { + ans[i] = res.get(i); + } + return ans; + } +} +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2016-maximum-difference-between-increasing-elements.md b/solutions/lc-solutions/2000-2099/2016-maximum-difference-between-increasing-elements.md new file mode 100644 index 0000000..8cc1d82 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2016-maximum-difference-between-increasing-elements.md @@ -0,0 +1,76 @@ +--- +id: maximum-difference-between-increasing-elements +title: Maximum Difference Between Increasing Elements +sidebar_label: 2016 Maximum Difference Between Increasing Elements +tags: + - Array + - Greedy + - LeetCode +description: "This is a solution to the Maximum Difference Between Increasing Elements problem on LeetCode." +sidebar_position: 2016 +--- + +## Problem Description + +Given a 0-indexed integer array `nums` of size `n`, find the maximum difference between `nums[i]` and `nums[j]` (i.e., `nums[j] - nums[i]`), such that `0 <= i < j < n` and `nums[i] < nums[j]`. + +Return the maximum difference. If no such `i` and `j` exists, return `-1`. + +### Examples + +**Example 1:** + +``` +Input: nums = [7,1,5,4] +Output: 4 +Explanation: +The maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4. +Note that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i > j, so it is not valid. +``` + +**Example 2:** +``` +Input: nums = [9,4,3,2] +Output: -1 +Explanation: +There is no i and j such that i < j and nums[i] < nums[j]. +``` + +**Example 3:** +``` +Input: nums = [1,5,2,10] +Output: 9 +Explanation: +The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9. +``` + +### Constraints + +- `n == nums.length` +- `2 <= n <= 1000` +- `1 <= nums[i] <= 10^9` + +### Approach + +To solve this problem efficiently, we can use a greedy approach. We keep track of the minimum value encountered so far as we iterate through the array. For each element, we calculate the difference between the current element and the minimum value encountered so far. If this difference is greater than the current maximum difference, we update the maximum difference. + +#### C++ + +```cpp +class Solution { +public: + int maximumDifference(vector& nums) { + int min_val = nums[0]; + int max_diff = -1; + + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] > min_val) { + max_diff = max(max_diff, nums[i] - min_val); + } + min_val = min(min_val, nums[i]); + } + + return max_diff; + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2017-grid-game.md b/solutions/lc-solutions/2000-2099/2017-grid-game.md new file mode 100644 index 0000000..bb4b80d --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2017-grid-game.md @@ -0,0 +1,95 @@ +--- +id: grid-game +title: Grid Game +sidebar_label: 2017 Grid Game +tags: + - Array + - Dynamic Programming + - Game Theory +description: "This is a solution to the Grid Game problem where two robots play optimally on a 2D grid." +sidebar_position: 2017 +--- + +### Problem Description + +You are given a `0-indexed 2D array` `grid` of size `2 x n`, where `grid[r][c]` represents the number of points at position `(r, c)` on the matrix. Two robots initially start at `(0, 0)` and want to reach `(1, n-1)`. Each robot may only move to the right `((r, c) to (r, c + 1)) `or down `((r, c) `to `(r + 1, c))`. + +At the start of the game, the first robot moves from` (0, 0) to (1, n-1)`, collecting all the points from the cells on its path. For all cells` (r, c)` traversed on the path, `grid[r][c]` is set to `0`. Then, the second robot moves from `(0, 0) to (1, n-1)`, collecting the points on its path. Note that their paths may intersect with one another. + +The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot. + +### Examples + +**Example 1:** + +``` +Input: `grid = [[2,5,4],[1,5,1]]` +Output: `4` +Explanation: +- The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue. +- The cells visited by the first robot are set to 0. +- The second robot will collect 0 + 0 + 4 + 0 = 4 points. +``` + +**Example 2:** + +``` +Input: `grid = [[3,3,1],[8,5,2]]` +Output: `4` +Explanation: +- The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue. +- The cells visited by the first robot are set to 0. +- The second robot will collect 0 + 3 + 1 + 0 = 4 points. +``` + +**Example 3:** +``` +Input: `grid = [[1,3,1,15],[1,3,3,1]]` +Output: `7` +Explanation: +- The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue. +- The cells visited by the first robot are set to 0. +- The second robot will collect 0 + 1 + 3 + 3 + 0 = 7 points. +``` + +### Approach + +In solving the problem, we employ two dynamic programming arrays, `dp1` and `dp2`. `dp1[j]` tracks the maximum points collected by the first robot as it moves across the grid from left to right, starting at `(0, 0)`. Simultaneously, `dp2[j]` records the maximum points collected by the second robot moving from right to left, starting at `(0, n-1)`. The approach ensures optimal play: after `dp1` is computed, `dp2` is filled backwards while calculating the maximum points `max_points` that the second robot can collect after the first has minimized its score. + +#### C++ + +``` cpp +class Solution { +public: + long long gridGame(vector>& grid) { + int n = grid[0].size(); + + // Initialize dp arrays + vector dp1(n), dp2(n); + + // Initialize dp1 + dp1[0] = grid[0][0]; + for (int j = 1; j < n; ++j) { + dp1[j] = dp1[j - 1] + grid[0][j]; + } + + // Initialize dp2 + dp2[n - 1] = grid[1][n - 1]; + for (int j = n - 2; j >= 0; --j) { + dp2[j] = dp2[j + 1] + grid[1][j]; + } + + // Find maximum points for the second robot + long long max_points = LLONG_MAX; + for (int j = 0; j < n; ++j) { + max_points = min(max_points, max(dp1[j], (j > 0 ? dp2[j - 1] : LLONG_MAX))); + } + + return max_points; + } +}; + +``` + + + diff --git a/solutions/lc-solutions/2000-2099/2018-check-if-word-can-be-placed-in-crossword.md b/solutions/lc-solutions/2000-2099/2018-check-if-word-can-be-placed-in-crossword.md new file mode 100644 index 0000000..5cfdd8e --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2018-check-if-word-can-be-placed-in-crossword.md @@ -0,0 +1,136 @@ +--- +id: check-if-word-can-be-placed-in-crossword +title: Check if Word Can Be Placed in Crossword +sidebar_label: 2018 Check if Word Can Be Placed in Crossword +tags: + - Matrix + - String Matching + - LeetCode +description: "This is a solution to the Check if Word Can Be Placed in Crossword problem on LeetCode." +sidebar_position: 2018 +--- + +## Problem Description + +You are given an m x n matrix `board`, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any empty cells, and `'#'` to represent any blocked cells. + +A word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if: + +- It does not occupy a cell containing the character `'#'`. +- The cell each letter is placed in must either be `' '` (empty) or match the letter already on the board. +- There must not be any empty cells `' '` or other lowercase letters directly left or right of the word if the word was placed horizontally. +- There must not be any empty cells `' '` or other lowercase letters directly above or below the word if the word was placed vertically. + +Given a string `word`, return `true` if `word` can be placed in `board`, or `false` otherwise. + +### Examples + +**Example 1:** + +``` +Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", "c", " "]], word = "abc" +Output: true +Explanation: The word "abc" can be placed as shown above (top to bottom). +``` + +**Example 2:** +``` +Input: board = [[" ", "#", "a"], [" ", "#", "c"], [" ", "#", "a"]], word = "ac" +Output: false +Explanation: It is impossible to place the word because there will always be a space/letter above or below it. +``` + +**Example 3:** +``` +Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", " ", "c"]], word = "ca" +Output: true +Explanation: The word "ca" can be placed as shown above (right to left). +``` + +### Constraints + +- `m == board.length` +- `n == board[i].length` +- `1 <= m * n <= 2 * 10^5` +- `board[i][j] will be ' ', '#', or a lowercase English letter.` +- `1 <= word.length <= max(m, n)` +- `word will contain only lowercase English letters.` + +### Approach + +We will check all possible placements of the word on the board horizontally and vertically, both left-to-right/right-to-left and top-to-bottom/bottom-to-top. For each potential placement, ensure the word fits in the specified direction without any blocking characters `('#')` or conflicting letters. If any valid placement is found, return true; otherwise, return false. + +#### C++ + +``` cpp +bool canPlaceWordHorizontally(const std::vector>& board, const std::string& word, int row, int col, bool reverse) { + int n = board[0].size(); + int m = word.size(); + + if (reverse) { + if (col - m < -1) return false; + if (col - m >= 0 && board[row][col - m] != '#') return false; + if (col + 1 < n && board[row][col + 1] != '#') return false; + for (int i = 0; i < m; ++i) { + if (board[row][col - i] != ' ' && board[row][col - i] != word[i]) return false; + } + } else { + if (col + m > n) return false; + if (col + m < n && board[row][col + m] != '#') return false; + if (col - 1 >= 0 && board[row][col - 1] != '#') return false; + for (int i = 0; i < m; ++i) { + if (board[row][col + i] != ' ' && board[row][col + i] != word[i]) return false; + } + } + + return true; +} + +bool canPlaceWordVertically(const std::vector>& board, const std::string& word, int row, int col, bool reverse) { + int m = board.size(); + int n = word.size(); + + if (reverse) { + if (row - n < -1) return false; + if (row - n >= 0 && board[row - n][col] != '#') return false; + if (row + 1 < m && board[row + 1][col] != '#') return false; + for (int i = 0; i < n; ++i) { + if (board[row - i][col] != ' ' && board[row - i][col] != word[i]) return false; + } + } else { + if (row + n > m) return false; + if (row + n < m && board[row + n][col] != '#') return false; + if (row - 1 >= 0 && board[row - 1][col] != '#') return false; + for (int i = 0; i < n; ++i) { + if (board[row + i][col] != ' ' && board[row + i][col] != word[i]) return false; + } + } + + return true; +} + +bool placeWordInCrossword(std::vector>& board, std::string word) { + int m = board.size(); + int n = board[0].size(); + + // Check horizontally + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (canPlaceWordHorizontally(board, word, i, j, false) || canPlaceWordHorizontally(board, word, i, j, true)) { + return true; + } + } + } + + // Check vertically + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (canPlaceWordVertically(board, word, i, j, false) || canPlaceWordVertically(board, word, i, j, true)) { + return true; + } + } + } + + return false; +} +``` diff --git a/solutions/lc-solutions/2000-2099/2019-score-of-students-solving-math-expression.md b/solutions/lc-solutions/2000-2099/2019-score-of-students-solving-math-expression.md new file mode 100644 index 0000000..3fdcbe7 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2019-score-of-students-solving-math-expression.md @@ -0,0 +1,142 @@ +--- +id: score-of-students-solving-math-expression +title: Score of Students Solving Math Expression +sidebar_label: 2019 Score of Students Solving Math Expression +tags: + - Math + - Dynamic Programming + - LeetCode +description: "This is a solution to the Score of Students Solving Math Expression problem on LeetCode." +sidebar_position: 2019 +--- + +## Problem Description + +You are given a string `s` that contains digits 0-9, addition symbols `+`, and multiplication symbols `*` only, representing a valid math expression of single digit numbers (e.g., `3+5*2`). This expression was given to `n` elementary school students. The students were instructed to get the answer of the expression by following this order of operations: + +1. Compute multiplication, reading from left to right. +2. Compute addition, reading from left to right. + +You are given an integer array `answers` of length `n`, which are the submitted answers of the students in no particular order. You are asked to grade the answers, by following these rules: + +- If an answer equals the correct answer of the expression, this student will be rewarded 5 points; +- Otherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic, this student will be rewarded 2 points; +- Otherwise, this student will be rewarded 0 points. + +Return the sum of the points of the students. + +### Examples + +**Example 1:** + +``` +Input: s = "7+312", answers = [20, 13, 42] +Output: 7 +Explanation: +The correct answer of the expression is 13, therefore one student is rewarded 5 points. +A student might have applied the operators in this wrong order: ((7+3)*1)*2 = 20. Therefore one student is rewarded 2 points. +The points for the students are: [2, 5, 0]. The sum of the points is 2+5+0=7. + +``` + +**Example 2:** +``` +Input: s = "3+5*2", answers = [13, 0, 10, 13, 13, 16, 16] +Output: 19 +Explanation: +The correct answer of the expression is 13, therefore three students are rewarded 5 points each. +A student might have applied the operators in this wrong order: (3+5)*2 = 16. Therefore two students are rewarded 2 points. +The points for the students are: [5, 0, 0, 5, 5, 2, 2]. The sum of the points is 5+0+0+5+5+2+2=19. +``` + +**Example 3:** + +``` +Input: s = "6+0*1", answers = [12, 9, 6, 4, 8, 6] +Output: 10 +Explanation: +The correct answer of the expression is 6. +If a student had incorrectly done (6+0)*1, the answer would also be 6. +By the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points. +The points for the students are: [0, 0, 5, 0, 0, 5]. The sum of the points is 10. +``` + + +### Constraints + +- `3 <= s.length <= 31` +- `s` represents a valid expression that contains only digits` 0-9,` `+`, and `*` only. +- All the integer operands in the expression are in the inclusive range `[0, 9]`. +- `1 <= The count of all operators ('+' and '*') in the math expression <= 15` +- Test data are generated such that the correct answer of the expression is in the range of `[0, 1000]`. +- `n == answers.length` +- `1 <= `n` <= 10^4` +-` 0 <= `answers[i]` <= 1000` + +## Approach + +To solve this problem, we will calculate the correct answer of the expression using the given order of operations (multiplication before addition). We will also use dynamic programming to compute all possible values students could get if they evaluated the expression with different operator orders. For each answer in the provided answers list, we will reward points based on the correct answer and possible values. + +#### C++ + +```cpp + +class Solution { +public: + int scoreOfStudents(string s, vector& answers) { + int n = s.size(); + vector>> dp(n, vector>(n)); + unordered_map> memo; + + function dfs = [&](int l, int r) { + if (!dp[l][r].empty()) return; + if (l == r) { + dp[l][r].insert(s[l] - '0'); + return; + } + for (int i = l; i < r; i++) { + if (s[i] == '+' || s[i] == '*') { + dfs(l, i - 1); + dfs(i + 1, r); + for (int a : dp[l][i - 1]) { + for (int b : dp[i + 1][r]) { + if (s[i] == '+') { + if (a + b <= 1000) dp[l][r].insert(a + b); + } else { + if (a * b <= 1000) dp[l][r].insert(a * b); + } + } + } + } + } + }; + + dfs(0, n - 1); + unordered_set possible_values = dp[0][n - 1]; + + int correct_answer = 0; + vector stack; + for (char c : s) { + if (isdigit(c)) { + stack.push_back(c - '0'); + } else if (c == '*') { + int a = stack.back(); stack.pop_back(); + int b = c - '0'; + stack.push_back(a * b); + } + } + correct_answer = accumulate(stack.begin(), stack.end(), 0, plus()); + + int total_points = 0; + for (int ans : answers) { + if (ans == correct_answer) { + total_points += 5; + } else if (possible_values.count(ans)) { + total_points += 2; + } + } + + return total_points; + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2020-number-of-accounts-that-did-not-stream.md b/solutions/lc-solutions/2000-2099/2020-number-of-accounts-that-did-not-stream.md new file mode 100644 index 0000000..e77fc4e --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2020-number-of-accounts-that-did-not-stream.md @@ -0,0 +1,99 @@ +--- +id: number-of-accounts-that-did-not-stream +title: Number of Accounts That Did Not Stream +sidebar_label: 2020 Number of Accounts That Did Not Stream +tags: + - SQL + - LeetCode +description: "This is a solution to the Number of Accounts That Did Not Stream problem on LeetCode." +sidebar_position: 2020 +--- + +## Problem Description + +You are given two tables, `subscriptions` and `streams`. + +### Subscriptions Table +| Column Name | Type | +|-------------|------| +| account_id | int | +| start_date | date | +| end_date | date | + +- `account_id` is the primary key column for this table. +- Each row of this table indicates the start and end dates of an account's subscription. +- Note that always `start_date` < `end_date`. + +### Streams Table +| Column Name | Type | +|-------------|------| +| session_id | int | +| account_id | int | +| stream_date | date | + +- `session_id` is the primary key column for this table. +- `account_id` is a foreign key from the Subscriptions table. +- Each row of this table contains information about the account and the date associated with a stream session. + +Write an SQL query to report the number of accounts that bought a subscription in 2021 but did not have any stream session. + +### Example +``` + +Input: + +Subscriptions table: + +| account_id | start_date | end_date | +|------------|------------|------------| +| 9 | 2020-02-18 | 2021-10-30 | +| 3 | 2021-09-21 | 2021-11-13 | +| 11 | 2020-02-28 | 2020-08-18 | +| 13 | 2021-04-20 | 2021-09-22 | +| 4 | 2020-10-26 | 2021-05-08 | +| 5 | 2020-09-11 | 2021-01-17 | + +Streams table: + +| session_id | account_id | stream_date | +|------------|------------|-------------| +| 14 | 9 | 2020-05-16 | +| 16 | 3 | 2021-10-27 | +| 18 | 11 | 2020-04-29 | +| 17 | 13 | 2021-08-08 | +| 19 | 4 | 2020-12-31 | +| 13 | 5 | 2021-01-05 | + +Output + +| accounts_count | +|----------------| +| 2 | + +Explanation: Users 4 and 9 did not stream in 2021. User 11 did not subscribe in 2021. +``` + +## Approach + +The SQL query involves filtering subscriptions that started in 2021 and checking which of those accounts did not have any streams in 2021. + + +#### SQL Query + +```sql +WITH SubscriptionsIn2021 AS ( + SELECT account_id + FROM subscriptions + WHERE YEAR(start_date) = 2021 +), +StreamsIn2021 AS ( + SELECT DISTINCT account_id + FROM streams + WHERE YEAR(stream_date) = 2021 +) +SELECT COUNT(s.account_id) AS accounts_count +FROM SubscriptionsIn2021 s +LEFT JOIN StreamsIn2021 st +ON s.account_id = st.account_id +WHERE st.account_id IS NULL; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2021-brightest-position-on-street.md b/solutions/lc-solutions/2000-2099/2021-brightest-position-on-street.md new file mode 100644 index 0000000..1bbd280 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2021-brightest-position-on-street.md @@ -0,0 +1,113 @@ +--- +id: brightest-position-on-street +title: Brightest Position on Street +sidebar_label: 2021 Brightest Position on Street +tags: + - Array + - Prefix Sum + - LeetCode + - C++ +description: "This is a solution to the Brightest Position on Street problem on LeetCode." +sidebar_position: 2021 +--- + +## Problem Description + +A perfectly straight street is represented by a number line. The street has street lamp(s) on it and is represented by a 2D integer array `lights`. Each `lights[i] = [positioni, rangei]` indicates that there is a street lamp at `positioni` that lights up the area from `[positioni - rangei, positioni + rangei]` (inclusive). + +The brightness of a position `p` is defined as the number of street lamp that light up the position `p`. + +Given `lights`, return the brightest position on the street. If there are multiple brightest positions, return the smallest one. + +### Examples + +**Example 1:** + +``` +Input: lights = [[-3,2],[1,2],[3,3]] +Output: -1 +Explanation: +The first street lamp lights up the area from [(-3) - 2, (-3) + 2] = [-5, -1]. +The second street lamp lights up the area from [1 - 2, 1 + 2] = [-1, 3]. +The third street lamp lights up the area from [3 - 3, 3 + 3] = [0, 6]. + +Position -1 has a brightness of 2, illuminated by the first and second street light. +Positions 0, 1, 2, and 3 have a brightness of 2, illuminated by the second and third street light. +Out of all these positions, -1 is the smallest, so return it. + +``` + +**Example 2:** + +``` +Input: lights = [[1,0],[0,1]] +Output: 1 +Explanation: +The first street lamp lights up the area from [1 - 0, 1 + 0] = [1, 1]. +The second street lamp lights up the area from [0 - 1, 0 + 1] = [-1, 1]. + +Position 1 has a brightness of 2, illuminated by the first and second street light. +Return 1 because it is the brightest position on the street. + +``` + +**Example 3:** + +``` +Input: lights = [[1,2]] +Output: -1 +Explanation: +The first street lamp lights up the area from [1 - 2, 1 + 2] = [-1, 3]. + +Positions -1, 0, 1, 2, and 3 have a brightness of 1, illuminated by the first street light. +Out of all these positions, -1 is the smallest, so return it. + +``` + + +### Constraints + +- `1 <= lights.length <= 10^5` +- `lights[i].length == 2` +- `-10^8 <= positioni <= 10^8` +- `0 <= rangei <= 10^8` + +### Approach + +We can solve this problem using a prefix sum approach to handle the range updates efficiently. We will mark the start and end of each light's range and then use a sweep line algorithm to determine the brightest position. + +### Complexity + +- **Time complexity**: $O(n \log n)$ due to sorting the events. +- **Space complexity**: $O(n)$ for storing the events. + +#### C++ + +```cpp + +class Solution { +public: + int brightestPosition(vector>& lights) { + map events; + + for (const auto& light : lights) { + int start = light[0] - light[1]; + int end = light[0] + light[1]; + events[start]++; + events[end + 1]--; + } + + int maxBrightness = 0, currentBrightness = 0, brightestPos = 0; + + for (const auto& event : events) { + currentBrightness += event.second; + if (currentBrightness > maxBrightness) { + maxBrightness = currentBrightness; + brightestPos = event.first; + } + } + + return brightestPos; + } +}; +``` diff --git a/solutions/lc-solutions/2000-2099/2022-convert-1d-array-into-2d-array.md b/solutions/lc-solutions/2000-2099/2022-convert-1d-array-into-2d-array.md new file mode 100644 index 0000000..aa39ca1 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2022-convert-1d-array-into-2d-array.md @@ -0,0 +1,133 @@ +--- +id: convert-1d-array-into-2d-array +title: Convert 1D Array Into 2D Array +sidebar_label: 2022 Convert 1D Array Into 2D Array +tags: + - Array + - Matrix + - LeetCode +description: "This is a solution to the Convert 1D Array Into 2D Array problem on LeetCode." +sidebar_position: 2022 +--- + +## Problem Description + +You are given a 0-indexed 1-dimensional (1D) integer array `original`, and two integers, `m` and `n`. You are tasked with creating a 2-dimensional (2D) array with `m` rows and `n` columns using all the elements from `original`. + +The elements from indices 0 to `n - 1` (inclusive) of `original` should form the first row of the constructed 2D array, the elements from indices `n` to `2 * n - 1` (inclusive) should form the second row of the constructed 2D array, and so on. + +Return an `m x n` 2D array constructed according to the above procedure, or an empty 2D array if it is impossible. + +### Examples + +**Example 1:** + +``` +Input: original = [1,2,3,4], m = 2, n = 2 +Output: [[1,2],[3,4]] +Explanation: The constructed 2D array should contain 2 rows and 2 columns. +The first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array. +The second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array. + +``` + +**Example 2:** + +``` + +Input: original = [1,2,3], m = 1, n = 3 +Output: [[1,2,3]] +Explanation: The constructed 2D array should contain 1 row and 3 columns. +Put all three elements in original into the first row of the constructed 2D array. + +``` + +**Example 3:** + +``` + +Input: original = [1,2], m = 1, n = 1 +Output: [] +Explanation: There are 2 elements in original. +It is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array. + +``` + +### Constraints + +- `1 <= original.length <= 5 * 10^4` +- `1 <= original[i] <= 10^5` +- `1 <= m, n <= 4 * 10^4` + +### Approach + +To solve this problem: +1. Verify if the total number of elements in the 1D array `original` is equal to `m * n`. + - If not, return an empty 2D array since it's impossible to create a 2D array of the given dimensions. +2. Initialize an empty 2D array `result` with `m` rows. +3. Iterate through the `original` array, filling the `result` array row by row. + - Use integer division and modulus to determine the correct row and column positions. + +This approach ensures that the solution is constructed in linear time `O(n)`, where `n` is the length of the `original` array. + +#### C++ Solution + +```cpp +class Solution { +public: + vector> construct2DArray(vector& original, int m, int n) { + if (original.size() != m * n) { + return {}; + } + + vector> result(m, vector(n)); + for (int i = 0; i < original.size(); ++i) { + result[i / n][i % n] = original[i]; + } + + return result; + } +}; + +``` + +#### Java + +```java + +public class Solution { + + public static int[][] construct2DArray(int[] original, int m, int n) { + // Check if the total number of elements in the original array equals m * n + if (original.length != m * n) { + return new int[0][0]; // Return an empty 2D array if it's impossible to form the 2D array + } + + // Initialize the 2D array with the specified number of rows and columns + int[][] result = new int[m][n]; + + // Fill the 2D array with elements from the original array + for (int i = 0; i < original.length; i++) { + result[i / n][i % n] = original[i]; + } + + // Return the constructed 2D array + return result; + } + + public static void main(String[] args) { + // Test cases + int[] original1 = {1, 2, 3, 4}; + int m1 = 2, n1 = 2; + System.out.println(Arrays.deepToString(construct2DArray(original1, m1, n1))); + + int[] original2 = {1, 2, 3}; + int m2 = 1, n2 = 3; + System.out.println(Arrays.deepToString(construct2DArray(original2, m2, n2))); + + int[] original3 = {1, 2}; + int m3 = 1, n3 = 1; + System.out.println(Arrays.deepToString(construct2DArray(original3, m3, n3))); + } +} +``` diff --git a/solutions/lc-solutions/2000-2099/2023-number-of-pairs-of-strings-with-concatenation-equal-to-target.md b/solutions/lc-solutions/2000-2099/2023-number-of-pairs-of-strings-with-concatenation-equal-to-target.md new file mode 100644 index 0000000..cd8667c --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2023-number-of-pairs-of-strings-with-concatenation-equal-to-target.md @@ -0,0 +1,96 @@ +--- +id: number-of-pairs-of-strings-with-concatenation-equal-to-target +title: Number of Pairs of Strings With Concatenation Equal to Target +sidebar_label: 2023 Number of Pairs of Strings With Concatenation Equal to Target +tags: + - Array + - String + - LeetCode +description: "This is a solution to the Number of Pairs of Strings With Concatenation Equal to Target problem on LeetCode." +sidebar_position: 2023 +--- + +## Problem Description + +Given an array of digit strings `nums` and a digit string `target`, return the number of pairs of indices `(i, j)` (where `i != j`) such that the concatenation of `nums[i] + nums[j]` equals `target`. + +### Examples + +**Example 1:** + +``` +Input: nums = ["777","7","77","77"], target = "7777" +Output: 4 +Explanation: Valid pairs are: + +(0, 1): "777" + "7" +(1, 0): "7" + "777" +(2, 3): "77" + "77" +(3, 2): "77" + "77" +``` + +**Example 2:** +``` +Input: nums = ["123","4","12","34"], target = "1234" +Output: 2 +Explanation: Valid pairs are: + +(0, 1): "123" + "4" +(2, 3): "12" + "34" +``` + +**Example 3:** + +``` +Input: nums = ["1","1","1"], target = "11" +Output: 6 +Explanation: Valid pairs are: + +(0, 1): "1" + "1" +(1, 0): "1" + "1" +(0, 2): "1" + "1" +(2, 0): "1" + "1" +(1, 2): "1" + "1" +(2, 1): "1" + "1" +``` + + +### Constraints + +- `2 <= nums.length <= 100` +- `1 <= nums[i].length <= 100` +- `2 <= target.length <= 100` +- `nums[i]` and `target` consist of digits. +- `nums[i]` and `target` do not have leading zeros. + +### Approach + +To solve this problem: +1. Initialize a counter `count` to keep track of the number of valid pairs. +2. Use nested loops to iterate through all pairs `(i, j)` such that `i != j`. +3. For each pair, check if the concatenation of `nums[i]` and `nums[j]` equals `target`. + - If true, increment the counter `count`. +4. Return the counter `count` as the result. + +This approach ensures that we check all possible pairs in the array, resulting in a time complexity of `O(n^2)` where `n` is the length of the `nums` array. + +#### C++ Solution + +```cpp +class Solution { +public: + int numOfPairs(vector& nums, string target) { + int count = 0; + + for (int i = 0; i < nums.size(); ++i) { + for (int j = 0; j < nums.size(); ++j) { + if (i != j && nums[i] + nums[j] == target) { + count++; + } + } + } + + return count; + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2024-maximize-the-confusion-of-an-exam.md b/solutions/lc-solutions/2000-2099/2024-maximize-the-confusion-of-an-exam.md new file mode 100644 index 0000000..cafec39 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2024-maximize-the-confusion-of-an-exam.md @@ -0,0 +1,128 @@ +--- +id: maximize-the-confusion-of-an-exam +title: Maximize the Confusion of an Exam +sidebar_label: 2024 Maximize the Confusion of an Exam +tags: + - String + - Sliding Window + - LeetCode + - C++ +description: "This is a solution to the Maximize the Confusion of an Exam problem on LeetCode." +sidebar_position: 2024 +--- + +## Problem Description + +A teacher is writing a test with `n` true/false questions, with `'T'` denoting true and `'F'` denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row). + +You are given a string `answerKey`, where `answerKey[i]` is the original answer to the ith question. In addition, you are given an integer `k`, the maximum number of times you may perform the following operation: + +Change the answer key for any question to `'T'` or `'F'`. + +Return the maximum number of consecutive `'T'`s or `'F'`s in the answer key after performing the operation at most `k` times. + +### Examples + +**Example 1:** + +``` +Input: answerKey = "TTFF", k = 2 +Output: 4 +Explanation: We can replace both the 'F's with 'T's to make answerKey = "TTTT". +There are four consecutive 'T's. + +``` + +**Example 2:** + +``` +Input: answerKey = "TFFT", k = 1 +Output: 3 +Explanation: We can replace the first 'T' with an 'F' to make answerKey = "FFFT". +Alternatively, we can replace the second 'T' with an 'F' to make answerKey = "TFFF". +In both cases, there are three consecutive 'F's. + +``` + +**Example 3:** + +``` +Input: answerKey = "TTFTTFTT", k = 1 +Output: 5 +Explanation: We can replace the first 'F' to make answerKey = "TTTTTFTT" +Alternatively, we can replace the second 'F' to make answerKey = "TTFTTTTT". +In both cases, there are five consecutive 'T's. +``` + + +### Constraints + +- `n == answerKey.length` +- `1 <= n <= 5 * 10^4` +- `answerKey[i]` is either `'T'` or `'F'` +- `1 <= k <= n` + +### Approach + +To solve this problem, we can use a sliding window approach. We'll maintain two sliding windows, one for counting the maximum consecutive `'T'`s after converting up to `k` `'F'`s to `'T'`, and another for counting the maximum consecutive `'F'`s after converting up to `k` `'T'`s to `'F'`. The maximum of these two results will be our answer. + +### Complexity + +- **Time complexity**: $O(n)$, where `n` is the length of `answerKey`. This is because we traverse the string a constant number of times. +- **Space complexity**: $O(1)$, as we use only a few extra variables. + +#### C++ + +```cpp +class Solution { +public: + int maxW(string list, int n, char c, int k) { + int ans = 0; + int flip = 0, l = 0; + for (int r = 0; r < n; r++) { + flip += (list[r] != c); + if (flip > k) { + while (list[l] == c) + l++; + l++; + flip--; + } + ans = max(ans, r - l + 1); + } + return ans; + } + + int maxConsecutiveAnswers(string answerKey, int k) { + int n = answerKey.size(); + return max(maxW(answerKey, n, 'T', k), maxW(answerKey, n, 'F', k)); + } +}; +``` + +#### Python + +```python +class Solution: + def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int: + n=len(answerKey) + + # Define a helper function maxW that calculates the maximum number of consecutive + # answers for a given character c ('T' or 'F') + def maxW(c): + ans=0 + flip=0 + l=0 + for r in range(n): + if answerKey[r]!=c: # If the current answer is not equal to c, increment flip + flip+=1 + if flip>k: # If flip exceeds k, adjust the window by moving l + while answerKey[l]==c: # Skip all consecutive occurrences of c + l+=1 + l+=1 # Move l to the next position after skipping + flip-=1 # Decrement flip since we have adjusted the window + ans=max(ans, r-l+1) # Update ans with the maximum consecutive count + return ans + + # Return the maximum of maxW('T') and maxW('F') as the result + return max(maxW('T'), maxW('F')) +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2025-maximum-number-of-ways-to-partition-an-array.md b/solutions/lc-solutions/2000-2099/2025-maximum-number-of-ways-to-partition-an-array.md new file mode 100644 index 0000000..ffbd3e0 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2025-maximum-number-of-ways-to-partition-an-array.md @@ -0,0 +1,116 @@ +--- +id: maximum-number-of-ways-to-partition-an-array +title: Maximum Number of Ways to Partition an Array +sidebar_label: 2025. Maximum Number of Ways to Partition an Array +tags: + - Array + - Partition + - Prefix Sum + - LeetCode +description: "This is a solution to the Maximum Number of Ways to Partition an Array problem on LeetCode." +sidebar_position: 2025 +--- + +## Problem Description + +You are given a 0-indexed integer array `nums` of length `n`. The number of ways to partition `nums` is the number of pivot indices that satisfy both conditions: + +1. `1 <= pivot < n` +2. `nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]` + +You are also given an integer `k`. You can choose to change the value of one element of `nums` to `k`, or to leave the array unchanged. + +Return the maximum possible number of ways to partition `nums` to satisfy both conditions after changing at most one element. + +### Examples + +**Example 1:** + +``` +Input: nums = [2,-1,2], k = 3 +Output: 1 +Explanation: One optimal approach is to change nums[0] to k. The array becomes [3,-1,2]. +There is one way to partition the array: +- For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2. +``` +**Example 2:** + +``` +Input: nums = [0,0,0], k = 1 +Output: 2 +Explanation: The optimal approach is to leave the array unchanged. +There are two ways to partition the array: +- For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0. +- For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0. +``` +**Example 3:** +``` +Input: nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33 +Output: 4 +Explanation: One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14]. +There are four ways to partition the array. +``` + +### Constraints + +- `n == nums.length` +- `2 <= n <= 105` +- `-105 <= k, nums[i] <= 105` + +### Approach + +First, compute prefix sums to determine all valid pivot indices where the sum of the left partition equals the sum of the right partition. Then, consider the effect of changing each element to `k` and how it affects the partitioning. Keep track of all potential pivot points in both the original and modified arrays to find the maximum number of valid partitions. + +#### C++ + +``` cpp +class Solution { +public: + int waysToPartition(vector& nums, int k) { + int n = nums.size(); + vector prefixSum(n + 1, 0); + unordered_map leftCount, rightCount; + + for (int i = 0; i < n; ++i) { + prefixSum[i + 1] = prefixSum[i] + nums[i]; + } + + long long totalSum = prefixSum[n]; + int result = 0; + + for (int i = 1; i < n; ++i) { + long long leftSum = prefixSum[i]; + long long rightSum = totalSum - leftSum; + if (leftSum == rightSum) { + result++; + } + rightCount[leftSum]++; + } + + int maxResult = result; + + for (int i = 0; i < n; ++i) { + long long newLeftSum = prefixSum[i] + k; + long long newRightSum = totalSum - prefixSum[i] - nums[i] + k; + + int tempResult = result; + + if (leftCount.count(newRightSum)) { + tempResult += leftCount[newRightSum]; + } + if (rightCount.count(newLeftSum)) { + tempResult += rightCount[newLeftSum]; + } + + maxResult = max(maxResult, tempResult); + + if (i < n - 1) { + rightCount[prefixSum[i + 1]]--; + leftCount[prefixSum[i + 1]]++; + } + } + + return maxResult; + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2026-low-quality-problems.md b/solutions/lc-solutions/2000-2099/2026-low-quality-problems.md new file mode 100644 index 0000000..215db3a --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2026-low-quality-problems.md @@ -0,0 +1,73 @@ +--- +id: low-quality-problems +title: Low-Quality Problems +sidebar_label: 2026 Low-Quality Problems +tags: + - SQL +--- + +## Problem Description + +You are given a table `Problems` with columns `problem_id`, `likes`, and `dislikes`. The `problem_id` is the primary key column representing the ID of each LeetCode problem, while `likes` and `dislikes` represent the number of likes and dislikes for each problem, respectively. + +Write an SQL query to report the IDs of the low-quality problems. A LeetCode problem is considered low-quality if the like percentage (likes / (likes + dislikes)) is strictly less than 60%. + +Return the result table ordered by `problem_id` in ascending order. + +### Examples + +**Example 1** + +``` +Input + +Problems table: ++------------+-------+----------+ +| problem_id | likes | dislikes | ++------------+-------+----------+ +| 6 | 1290 | 425 | +| 11 | 2677 | 8659 | +| 1 | 4446 | 2760 | +| 7 | 8569 | 6086 | +| 13 | 2050 | 4164 | +| 10 | 9002 | 7446 | ++------------+-------+----------+ + +Output:* + ++------------+ +| problem_id | ++------------+ +| 7 | +| 10 | +| 11 | +| 13 | ++------------+ + +Explanation: +The like percentages are as follows: +- Problem 1: (4446 / (4446 + 2760)) * 100 = 61.69858% +- Problem 6: (1290 / (1290 + 425)) * 100 = 75.21866% +- Problem 7: (8569 / (8569 + 6086)) * 100 = 58.47151% +- Problem 10: (9002 / (9002 + 7446)) * 100 = 54.73006% +- Problem 11: (2677 / (2677 + 8659)) * 100 = 23.61503% +- Problem 13: (2050 / (2050 + 4164)) * 100 = 32.99002% + +Problems 7, 10, 11, and 13 are low-quality problems because their like percentages are less than 60%. +``` + +### Approach + +To solve this problem, we need to: +1. Calculate the like percentage for each problem using the formula `(likes / (likes + dislikes)) * 100`. +2. Select the `problem_id` where the calculated like percentage is less than 60%. +3. Order the results by `problem_id` in ascending order. + +#### SQL Query + +```sql +SELECT problem_id +FROM Problems +WHERE likes * 100 / (likes + dislikes) < 60 +ORDER BY problem_id; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2027-minimum-moves-to-convert-string.md b/solutions/lc-solutions/2000-2099/2027-minimum-moves-to-convert-string.md new file mode 100644 index 0000000..fdad85d --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2027-minimum-moves-to-convert-string.md @@ -0,0 +1,72 @@ +--- +id: minimum-moves-to-convert-string +title: Minimum Moves to Convert String +sidebar_label: 2027 Minimum Moves to Convert String +tags: + - String + - Leetcode +--- + +## Problem Description + +You are given a string `s` consisting of `n` characters which are either 'X' or 'O'. + +A move is defined as selecting three consecutive characters of `s` and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same. + +Return the minimum number of moves required so that all the characters of `s` are converted to 'O'. + +### Examples + +**Example 1** + +``` +Input: s = "XXX" +Output: 1 +Explanation: XXX -> OOO +We select all the 3 characters and convert them in one move. +``` + +**Example 2** + +``` +Input: s = "XXOX" +Output: 2 +Explanation: XXOX -> OOOX -> OOOO +We select the first 3 characters in the first move, and convert them to 'O'. +Then we select the last 3 characters and convert them so that the final string contains all 'O's. +``` + +**Example 3** + +``` +Input: s = "OOOO" +Output: 0 +Explanation: There are no 'X's in s to convert. +``` + +### Constraints + +- `3 <= s.length <= 1000` +- `Each character `s[i]` is either 'X' or 'O'.` + +### Approach + +To solve this problem, count the number of 'X' characters in the string `s`. Since each move converts three consecutive 'X' characters to 'O', the minimum number of moves required will be equal to the ceiling of the count of 'X's divided by 3 (`ceil(count_X / 3)`). + +#### C++ + +```cpp +class Solution { +public: + int minimumMoves(string s) { + int countX = 0; + for (char ch : s) { + if (ch == 'X') { + countX++; + } + } + return ceil(countX / 3.0); + } +}; +``` + diff --git a/solutions/lc-solutions/2000-2099/2028-find-missing-observations.md b/solutions/lc-solutions/2000-2099/2028-find-missing-observations.md new file mode 100644 index 0000000..3525284 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2028-find-missing-observations.md @@ -0,0 +1,78 @@ +--- +id: find-missing-observations +title: Find Missing Observations +sidebar_label: 2028 Find Missing Observations +tags: + - Array + - Simulation + - Leetcode +--- + +## Problem Description + +You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls. + +You are given an integer array rolls of length m where rolls[i] is the value of the ith observation. You are also given the two integers mean and n. + +Return an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean. If there are multiple valid answers, return any of them. If no such array exists, return an empty array. + +### Examples + +**Example 1** + +``` +Input: rolls = [3,2,4,3], mean = 4, n = 2 +Output: [6,6] +Explanation: The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4. +``` +**Example 2** + +``` +Input: rolls = [1,5,6], mean = 3, n = 4 +Output: [2,3,2,2] +Explanation: The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3. +``` + +**Example 3** +``` +Input: rolls = [1,2,3,4], mean = 6, n = 4 +Output: [] +Explanation: It is impossible for the mean to be 6 no matter what the 4 missing rolls are. +``` + +### Constraints + +- `m == rolls.length` +- `1 <= n, m <= 10^5` +- `1 <= rolls[i], mean <= 6` + +### Approach + +To find the missing observations, calculate the total sum required for the n + m rolls based on the given mean. Then determine the sum of the provided rolls (`sum_rolls`). Compute the target sum for all rolls (`total_sum = mean * (n + m)`). Calculate the difference `missing_sum = total_sum - sum_rolls`. If `missing_sum` is negative or not divisible by n, return an empty array. Otherwise, distribute `missing_sum / n` to each missing observation in the result array. + +#### C++ + +```cpp + +class Solution { +public: + vector missingRolls(vector& rolls, int mean, int n) { + int m = rolls.size(); + int sumRolls = 0; + + for (int roll : rolls) { + sumRolls += roll; + } + + int totalSum = mean * (n + m); + int missingSum = totalSum - sumRolls; + + if (missingSum < n || missingSum > 6 * n || missingSum % n != 0) { + return {}; + } + + vector result(n, missingSum / n); + return result; + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2029-stone-game-ix.md b/solutions/lc-solutions/2000-2099/2029-stone-game-ix.md new file mode 100644 index 0000000..20ddcab --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2029-stone-game-ix.md @@ -0,0 +1,84 @@ +id: stone-game-ix +title: Stone Game IX +sidebar_label: 2029 Stone Game IX +tags: + - Array + - Game Theory + - Leetcode +--- + +## Problem Description + +Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones, where `stones[i]` is the value of the ith stone. + +Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones. The player who removes a stone loses if the sum of the values of all removed stones is divisible by `3`. Bob will win automatically if there are no remaining stones (even if it is Alice's turn). + +Assuming both players play optimally, return `true` if Alice wins and `false` if Bob wins. + +### Examples + +**Example 1** + +``` +Input: stones = [2,1] +Output: true +Explanation: The game will be played as follows: + +Turn 1: Alice can remove either stone. +Turn 2: Bob removes the remaining stone. +The sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game. +``` + +**Example 2** +``` +Input: stones = [2] +Output: false +Explanation: Alice will remove the only stone, and the sum of the values on the removed stones is 2. +Since all the stones are removed and the sum of values is not divisible by 3, Bob wins the game. + +``` +**Example 3** +``` +Input: stones = [5,1,2,4,3] +Output: false +Explanation: Bob will always win. One possible way for Bob to win is shown below: + +Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1. +Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4. +Turn 3: Alice removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8. +Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10. +Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15. +Alice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game. + +``` + + +### Constraints + +- `1 <= stones.length <= 10^5` +- `1 <= stones[i] <= 10^4` + +### Approach + +To solve this problem, observe that the sum of the removed stones modulo 3 plays a critical role. We can classify stones based on their values modulo 3 and then use game theory to determine the outcome. The key is to simulate the game while checking if a player can force the opponent into a losing position. + +#### C++ + +```cpp +class Solution { +public: + bool stoneGameIX(vector& stones) { + vector count(3, 0); + for (int stone : stones) { + count[stone % 3]++; + } + + // If the count of stones with value % 3 == 0 is even, then we need to check the counts of the other two categories + if (count[0] % 2 == 0) { + return count[1] > 0 && count[2] > 0; + } + // If the count of stones with value % 3 == 0 is odd, then we need to check the counts of the other two categories + return abs(count[1] - count[2]) > 2; + } +}; +``` diff --git a/solutions/lc-solutions/2000-2099/2030-smallest-k-length-subsequence.md b/solutions/lc-solutions/2000-2099/2030-smallest-k-length-subsequence.md new file mode 100644 index 0000000..c213b92 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2030-smallest-k-length-subsequence.md @@ -0,0 +1,93 @@ +--- +id: smallest-k-length-subsequence +title: Smallest K-Length Subsequence With Occurrences of a Letter +sidebar_label: 2030 Smallest K-Length Subsequence With Occurrences of a Letter +tags: + - String + - Subsequence + - Leetcode +--- + +## Problem Description + +You are given a string s, an integer k, a letter letter, and an integer repetition. + +Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times. The test cases are generated so that the letter appears in s at least repetition times. + +A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. + +A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. + +### Examples + +**Example 1** +``` +Input: s = "leet", k = 3, letter = "e", repetition = 1 +Output: "eet" +Explanation: There are four subsequences of length 3 that have the letter 'e' appear at least 1 time: + +"lee" (from "leet") +"let" (from "leet") +"let" (from "leet") +"eet" (from "leet") +The lexicographically smallest subsequence among them is "eet". +``` + +**Example 2** +``` +Input: s = "leetcode", k = 4, letter = "e", repetition = 2 +Output: "ecde" +Explanation: "ecde" is the lexicographically smallest subsequence of length 4 that has the letter "e" appear at least 2 times. +``` + +**Example 3** +``` +Input: s = "bb", k = 2, letter = "b", repetition = 2 +Output: "bb" +Explanation: "bb" is the only subsequence of length 2 that has the letter "b" appear at least 2 times. +``` + +### Constraints + +- `1 <= repetition <= k <= s.length <= 5 * 10^4` +- `s` consists of lowercase English letters. +- `letter` is a lowercase English letter, and appears in `s` at least `repetition` times. + +### Approach + +To solve this problem, use a greedy algorithm to construct the subsequence while maintaining the conditions. Use a stack to keep track of the smallest possible sequence and ensure that the required conditions (length and number of occurrences of the specified letter) are met. + +#### C++ + +```cpp +class Solution { +public: + string smallestSubsequence(string s, int k, char letter, int repetition) { + int n = s.size(); + int count = 0; + for (char c : s) { + if (c == letter) count++; + } + + string result = ""; + int letterCount = 0; + + for (int i = 0; i < n; ++i) { + while (!result.empty() && result.back() > s[i] && result.size() - 1 + n - i >= k && + letterCount + (result.back() == letter ? -1 : 0) + count >= repetition) { + letterCount -= result.back() == letter; + result.pop_back(); + } + + if (result.size() < k) { + result.push_back(s[i]); + letterCount += s[i] == letter; + if (s[i] == letter) repetition--; + } + count -= s[i] == letter; + } + + return result; + } +}; +``` diff --git a/solutions/lc-solutions/2000-2099/2032-Two-Out-of-three-problem.md b/solutions/lc-solutions/2000-2099/2032-Two-Out-of-three-problem.md new file mode 100644 index 0000000..f808364 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2032-Two-Out-of-three-problem.md @@ -0,0 +1,154 @@ +--- +id: Two-out-of-three +title: Two Out of Three +sidebar_label: 2032 - Two Out of Three +tags: [Array, Hash Table, Set, C++] +description: Return a distinct array containing all the values that are present in at least two out of the three arrays. +sidebar_position: 33 +--- + +## Problem Statement + +### Problem Description + +Given three integer arrays `nums1`, `nums2`, and `nums3`, return a distinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order. + +### Examples + +**Example 1:** +``` + Input: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3] + Output: [3,2] + Explanation: The values that are present in at least two arrays are: + 3, in all three arrays. + 2, in nums1 and nums2. +``` +**Example 2:** + +``` +Input: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2] +Output: [2,3,1] +Explanation:The values that are present in at least two arrays are: + 2, in nums2 and nums3. + 3, in nums1 and nums2. + 1, in nums1 and nums3. +``` +### Contraints + +- `1 <= nums1.length, nums2.length, nums3.length <= 100` +- `1 <= nums1[i], nums2[j], nums3[k] <= 100` + +## Solution of Given Problem +### Intuition + +The given solution uses an `unordered_map` to keep track of the presence of elements across the three arrays. Here's the step-by-step breakdown of the approach: + +1. **Initialization**: An `unordered_map` is used to store each element as the key and a character as the value to track its presence in the arrays. +2. **First Array Processing**: Iterate through the first array `nums1` and mark each element with 'A' in the map. +3. **Second Array Processing**: Iterate through the second array `nums2`: + - If the element is already marked 'A' or 'C' (indicating it was in `nums1`), mark it 'C'. + - Otherwise, mark it 'B'. +4. **Third Array Processing**: Iterate through the third array `nums3`: + - If the element is marked 'C', 'B', or 'A', keep it 'C'. + - Otherwise, mark it 'K'. +5. **Re-processing First Array**: Iterate through the first array `nums1` again: + - If the element is marked 'B', 'K', or 'C', mark it 'C'. + - Otherwise, keep it 'A'. +6. **Result Construction**: Finally, iterate through the map and collect all keys marked 'C' into the result vector `ans`. + +This approach ensures that any element present in at least two out of the three arrays is marked 'C' and included in the result. + +### Time Complexity Analysis + +The time complexity of the solution can be broken down into the following parts: + +1. **Initialization of Map**: Initializing the map with elements from `nums1` takes O(n1) time, where n1 is the length of `nums1`. +2. **Processing Second Array**: Processing the elements in `nums2` takes O(n2) time, where n2 is the length of `nums2`. +3. **Processing Third Array**: Processing the elements in `nums3` takes O(n3) time, where n3 is the length of `nums3`. +4. **Re-processing First Array**: Re-processing the elements in `nums1` takes O(n1) time. +5. **Result Construction**: Constructing the result vector from the map takes O(m) time, where m is the number of distinct elements across the three arrays (bounded by max(n1, n2, n3)). + +Therefore, the overall time complexity is: + +\[ O(n1 + n2 + n3) \] + +The space complexity is dominated by the space required for the `unordered_map`, which stores up to O(n1 + n2 + n3) distinct elements. + +### Codes in different languages + +#### C++ + +```cpp + class Solution { + public: + vector twoOutOfThree(vector& nums1, vector& nums2, vector& nums3) { + unordered_map mp; + for (auto i : nums1) mp[i] = 'A'; + for (auto i : nums2) { + if (mp[i] == 'A' || mp[i] == 'C') mp[i] = 'C'; + else mp[i] = 'B'; + } + for (auto i : nums3) { + if (mp[i] == 'C' || mp[i] == 'B' || mp[i] == 'A') mp[i] = 'C'; + else mp[i] = 'K'; + } + for (auto i : nums1) { + if (mp[i] == 'B' || mp[i] == 'K' || mp[i] == 'C') mp[i] = 'C'; + else mp[i] = 'A'; + } + vector ans; + for (auto i : mp) if (i.second == 'C') ans.push_back(i.first); + return ans; + } + }; +``` +#### JS +```js + /** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @param {number[]} nums3 + * @return {number[]} + */ + var twoOutOfThree = function(nums1, nums2, nums3) { + + const res = [] + const arr = new Set ([...nums1,...nums2,...nums3]) + + arr.forEach((val)=>{ + if(nums1.includes(val) && nums2.includes(val) || nums1.includes(val) + && nums3.includes(val) || nums2.includes(val) && nums3.includes(val)){ + res.push(val) + } + }) + + return res + }; +``` + +#### Java +```Java + + class Solution { + public List twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) { + Set set = new HashSet<>(); + for(int num : nums1) + set.add(num); + + List result = new ArrayList<>(); + Set set2 = new HashSet<>(); + for(int num : nums2){ + if(set.contains(num) && !set2.contains(num)) + result.add(num); + + set2.add(num); + } + + for(int num : nums3) + if(!result.contains(num) && (set.contains(num) || set2.contains(num))) + result.add(num); + + return result; + } + } +``` diff --git a/solutions/lc-solutions/2000-2099/2037-minimum-number-of-moves-to-seat-everyone.md b/solutions/lc-solutions/2000-2099/2037-minimum-number-of-moves-to-seat-everyone.md new file mode 100644 index 0000000..1684351 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2037-minimum-number-of-moves-to-seat-everyone.md @@ -0,0 +1,298 @@ +--- +id: minimum-number-of-moves-to-seat-everyone +title: Minimum Number of Moves to Seat Everyone +sidebar_label: 2037-Minimum Number of Moves to Seat Everyone +tags: + - Brute Force + - Greedy + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to theMinimum Number of Moves to Seat Everyone problem on LeetCode." +sidebar_position: 2 +--- + + + +## Problem Description + +Given `n` available seats and `n` students standing in a room, you are given an array `seats` of length `n`, where `seats[i]` is the position of the `i`-th seat. You are also given the array `students` of length `n`, where `students[j]` is the position of the `j`-th student. You can increase or decrease the position of the `i`-th student by 1 any number of times. Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat. + +### Examples + +**Example 1:** + +``` +Input: seats = [3,1,5], students = [2,7,4] +Output: 4 +Explanation: The students are moved as follows: +- The first student is moved from position 2 to position 1 using 1 move. +- The second student is moved from position 7 to position 5 using 2 moves. +- The third student is moved from position 4 to position 3 using 1 move. +In total, 1 + 2 + 1 = 4 moves were used. +``` + +**Example 2:** + +``` +Input: seats = [4,1,5,9], students = [1,3,2,6] +Output: 7 +Explanation: The students are moved as follows: +- The first student is not moved. +- The second student is moved from position 3 to position 4 using 1 move. +- The third student is moved from position 2 to position 5 using 3 moves. +- The fourth student is moved from position 6 to position 9 using 3 moves. +In total, 0 + 1 + 3 + 3 = 7 moves were used. +``` + +**Example 3:** + +``` +Input: seats = [2,2,6,6], students = [1,3,2,6] +Output: 4 +Explanation: Note that there are two seats at position 2 and two seats at position 6. +The students are moved as follows: +- The first student is moved from position 1 to position 2 using 1 move. +- The second student is moved from position 3 to position 6 using 3 moves. +- The third student is not moved. +- The fourth student is not moved. +In total, 1 + 3 + 0 + 0 = 4 moves were used. +``` + +### Constraints + +- `n == seats.length == students.length` +- `1 <= n <= 100` +- `1 <= seats[i], students[j] <= 100` + +--- + +## Solution for Minimum Moves to Seat Students Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized greedy approach. The brute force approach examines all possible assignments of students to seats, while the greedy approach sorts the seats and students and pairs them to minimize the total number of moves. + + + + +### Approach 1: Brute Force (Naive) + +The brute force approach iterates through each possible permutation of the students and calculates the total number of moves for each permutation to find the minimum. + +#### Code in Different Languages + + + + + +```cpp +#include +#include + +class Solution { +public: + int minMovesToSeat(std::vector& seats, std::vector& students) { + int min_moves = INT_MAX; + std::sort(seats.begin(), seats.end()); + std::sort(students.begin(), students.end()); + do { + int moves = 0; + for (int i = 0; i < seats.size(); ++i) { + moves += abs(seats[i] - students[i]); + } + min_moves = std::min(min_moves, moves); + } while (std::next_permutation(students.begin(), students.end())); + return min_moves; + } +}; +``` + + + + + +```java +import java.util.Arrays; + +class Solution { + public int minMovesToSeat(int[] seats, int[] students) { + Arrays.sort(seats); + Arrays.sort(students); + int minMoves = Integer.MAX_VALUE; + + do { + int moves = 0; + for (int i = 0; i < seats.length; i++) { + moves += Math.abs(seats[i] - students[i]); + } + minMoves = Math.min(minMoves, moves); + } while (nextPermutation(students)); + + return minMoves; + } + + private boolean nextPermutation(int[] nums) { + int i = nums.length - 2; + while (i >= 0 && nums[i] >= nums[i + 1]) { + i--; + } + if (i < 0) { + return false; + } + int j = nums.length - 1; + while (nums[j] <= nums[i]) { + j--; + } + swap(nums, i, j); + reverse(nums, i + 1, nums.length - 1); + return true; + } + + private void swap(int[] nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } + + private void reverse(int[] nums, int start, int end) { + while (start < end) { + int temp = nums[start]; + nums[start] = nums[end]; + nums[end] = temp; + start++; + end--; + } + } +} +``` + + + + + +```python +import itertools + +class Solution: + def minMovesToSeat(self, seats: List[int], students: List[int]) -> int: + seats.sort() + students.sort() + min_moves = float('inf') + + for perm in itertools.permutations(students): + moves = sum(abs(seat - student) for seat, student in zip(seats, perm)) + min_moves = min(min_moves, moves) + + return min_moves +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n!*n)$ due to generating all permutations and calculating moves. +- Space Complexity: $O(n)$ for storing permutations and temporary variables. +- Where `n` is the length of the seats and students arrays. +- The time complexity is $O(n!*n)$ because we generate all permutations. +- The space complexity is $O(n)$ because we store temporary variables and permutations. + + + + +### Approach 2: Greedy (Optimized) + +The greedy approach involves sorting the seats and students arrays and then pairing each student with the corresponding seat. This ensures that the total number of moves is minimized. + +#### Code in Different Languages + + + + + +```cpp +#include +#include + +class Solution { +public: + int minMovesToSeat(std::vector& seats, std::vector& students) { + std::sort(seats.begin(), seats.end()); + std::sort(students.begin(), students.end()); + + int moves = 0; + for (int i = 0; i < seats.size(); ++i) { + moves += abs(seats[i] - students[i]); + } + + return moves; + } +}; +``` + + + + + +```java +import java.util.Arrays; + +class Solution { + public int minMovesToSeat(int[] seats, int[] students) { + Arrays.sort(seats); + Arrays.sort(students); + + int moves = 0; + for (int i = 0; i < seats.length; ++i) { + moves += Math.abs(seats[i] - students[i]); + } + + return moves; + } +} +``` + + + + + +```python +class Solution: + def minMovesToSeat(self, seats: List[int], students: List[int]) -> int: + seats.sort() + students.sort() + + moves = 0 + for seat, student in zip(seats, students): + moves += abs(seat - student) + + return moves +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(nlogn)$ due to sorting. +- Space Complexity: $O(1)$ if sorting in place. +- Where `n` is the length of the seats and + + students arrays. +- The time complexity is $O(nlogn)$ because of the sorting operations. +- The space complexity is $O(1)$ if the sorting is done in place, otherwise $O(n)$. + + + + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.md b/solutions/lc-solutions/2000-2099/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.md new file mode 100644 index 0000000..1488a02 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.md @@ -0,0 +1,228 @@ +--- +id: remove-colored-pieces-if-both-neighbors-are-the-same-color +title: Remove Colored Pieces if Both Neighbors are the Same Color +sidebar_label: 2038. Remove Colored Pieces if Both Neighbors are the Same Color + +tags: +- 'Array' + +description: "This is a solution to the Remove Colored Pieces if Both Neighbors are the Same Color problem on LeetCode." +--- + +## Problem Description +There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece. + +Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first. + +Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A'. She is not allowed to remove pieces that are colored 'B'. +Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B'. He is not allowed to remove pieces that are colored 'A'. +Alice and Bob cannot remove pieces from the edge of the line. +If a player cannot make a move on their turn, that player loses and the other player wins. +Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins. +### Examples +**Example 1:** + +```Input: colors = "AAABABB" +Output: true +Explanation: +AAABABB -> AABABB +Alice moves first. +She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'. + +Now it's Bob's turn. +Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'. +Thus, Alice wins, so return true. +``` + +**Example 2:** +``` +Input: colors = "ABBBBBBBAAA" +Output: false +Explanation: +ABBBBBBBAAA -> ABBBBBBBAA +Alice moves first. +Her only option is to remove the second to last 'A' from the right. + +ABBBBBBBAA -> ABBBBBBAA +Next is Bob's turn. +He has many options for which 'B' piece to remove. He can pick any. + +On Alice's second turn, she has no more pieces that she can remove. +Thus, Bob wins, so return false. +``` + +### Constraints + +- `1 <= colors.length <= 10^5` +- `colors consists of only the letters 'A' and 'B'` + +## Solution for Remove Colored Pieces if Both Neighbors are the Same Color +### Approach + +1. **Initialization**: Start with two counters, `countA` and `countB`, initialized to zero. These will keep track of the number of triplets 'AAA' and 'BBB' found in the string `colors`. + +2. **Iteration**: Loop through the string `colors` from the beginning to the third last character (`n - 2`), where `n` is the length of `colors`. + +3. **Counting Triplets**: + - Check for sequences of three consecutive 'A's (`'AAA'`). If found, increment `countA`. + - Check for sequences of three consecutive 'B's (`'BBB'`). If found, increment `countB`. + +4. **Comparison**: After iterating through the string: + - Compare `countA` and `countB`. + - Return `true` if `countA` (number of 'AAA' sequences) is greater than `countB` (number of 'BBB' sequences), indicating player 'A' has more winning sequences. + - Otherwise, return `false`. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + + function winnerOfGame(colors) { + let countA = 0, countB = 0; + const n = colors.length; + for (let i = 0; i < n - 2; i++) { + if (colors[i] === 'A' && colors[i + 1] === 'A' && colors[i + 2] === 'A') { + countA++; + } + if (colors[i] === 'B' && colors[i + 1] === 'B' && colors[i + 2] === 'B') { + countB++; + } + } + return countA > countB; +} + + const input = "AAABABB" + + const output =winnerOfGame(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n) $ + - Space Complexity: $ O(1)$ + + ## Code in Different Languages + + + + ```javascript + function winnerOfGame(colors) { + let countA = 0, countB = 0; + const n = colors.length; + for (let i = 0; i < n - 2; i++) { + if (colors[i] === 'A' && colors[i + 1] === 'A' && colors[i + 2] === 'A') { + countA++; + } + if (colors[i] === 'B' && colors[i + 1] === 'B' && colors[i + 2] === 'B') { + countB++; + } + } + return countA > countB; +} + + ``` + + + + + ```typescript + function winnerOfGame(colors: string): boolean { + let countA: number = 0, countB: number = 0; + const n: number = colors.length; + for (let i: number = 0; i < n - 2; i++) { + if (colors[i] === 'A' && colors[i + 1] === 'A' && colors[i + 2] === 'A') { + countA++; + } + if (colors[i] === 'B' && colors[i + 1] === 'B' && colors[i + 2] === 'B') { + countB++; + } + } + return countA > countB; +} + + ``` + + + + ```python + def winner_of_game(colors: str) -> bool: + countA = countB = 0 + n = len(colors) + for i in range(n - 2): + if colors[i] == 'A' and colors[i + 1] == 'A' and colors[i + 2] == 'A': + countA += 1 + if colors[i] == 'B' and colors[i + 1] == 'B' and colors[i + 2] == 'B': + countB += 1 + return countA > countB + + ``` + + + + + ```java + public class Solution { + public boolean winnerOfGame(String colors) { + int countA = 0, countB = 0; + int n = colors.length(); + for (int i = 0; i < n - 2; i++) { + if (colors.charAt(i) == 'A' && colors.charAt(i + 1) == 'A' && colors.charAt(i + 2) == 'A') { + countA++; + } + if (colors.charAt(i) == 'B' && colors.charAt(i + 1) == 'B' && colors.charAt(i + 2) == 'B') { + countB++; + } + } + return countA > countB; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + bool winnerOfGame(string colors) { + int countA = 0, countB = 0; + int n = colors.length(); + for (int i = 0; i < n - 2; i++) { + if (colors[i] == 'A' && colors[i + 1] == 'A' && colors[i + 2] == 'A') { + countA++; + } + if (colors[i] == 'B' && colors[i + 1] == 'B' && colors[i + 2] == 'B') { + countB++; + } + } + return countA > countB; + } +}; +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Remove Colored Pieces if Both Neighbors are the Same Color](https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/description/) + diff --git a/solutions/lc-solutions/2000-2099/2042-check-if-numbers-are-ascending-in-a-sentence.md b/solutions/lc-solutions/2000-2099/2042-check-if-numbers-are-ascending-in-a-sentence.md new file mode 100644 index 0000000..c02da7e --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2042-check-if-numbers-are-ascending-in-a-sentence.md @@ -0,0 +1,278 @@ +--- +id: check-if-numbers-are-ascending-in-a-sentence +title: Check If Numbers are Ascending in a Sentence +sidebar_label: 2042-Check If Numbers are Ascending in a Sentence +tags: + - Valid Numbers + - Brute Force + - Optimized + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Check If Numbers are Ascending in a Sentence on LeetCode." +sidebar_position: 2 +--- + + + +## Problem Description + +A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters. + +For example, "a puppy has 2 eyes 4 legs" is a sentence with seven tokens: "2" and "4" are numbers and the other tokens such as "puppy" are words. +Given a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s). + +Return true if so, or false otherwise. + + + +### Examples + +**Example 1:** + +``` +Input: s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles" +Output: true +Explanation: The numbers in s are: 1, 3, 4, 6, 12. +They are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12. +``` + +**Example 2:** + +``` +Input: s = "hello world 5 x 5" +Output: false +Explanation: The numbers in s are: 5, 5. They are not strictly increasing. +``` + +**Example 3:** + +``` +Input: s = "sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s" +Output: false +Explanation: The numbers in s are: 7, 51, 50, 60. They are not strictly increasing. +``` + +### Constraints + +- `3 <= s.length <= 200` +- `s` consists of lowercase English letters, spaces, and digits from 0 to 9, inclusive. +- The number of tokens in `s` is between 2 and 100, inclusive. +- The tokens in `s` are separated by a single space. +- There are at least two numbers in `s`. +- Each number in `s` is a positive number less than 100, with no leading zeros. +- `s` contains no leading or trailing spaces. + +--- + +## Solution for Strictly Increasing Numbers in Sentence Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized approach. The brute force approach directly iterates through the tokens of the sentence, extracts the numbers, and checks if they are strictly increasing. The optimized approach ensures efficient token processing and number validation. + + + + +### Approach 1: Brute Force + +The brute force approach iterates through each token of the sentence, extracts the numbers, and checks if they are strictly increasing. + +#### Code in Different Languages + + + + + +```cpp +#include +#include + +class Solution { +public: + bool areNumbersAscending(std::string s) { + std::istringstream iss(s); + std::string token; + int prevNumber = -1; + + while (iss >> token) { + if (isdigit(token[0])) { + int number = std::stoi(token); + if (number <= prevNumber) { + return false; + } + prevNumber = number; + } + } + + return true; + } +}; +``` + + + + + +```java +class Solution { + public boolean areNumbersAscending(String s) { + String[] tokens = s.split(" "); + int prevNumber = -1; + + for (String token : tokens) { + if (Character.isDigit(token.charAt(0))) { + int number = Integer.parseInt(token); + if (number <= prevNumber) { + return false; + } + prevNumber = number; + } + } + + return true; + } +} +``` + + + + + +```python +class Solution: + def are_numbers_ascending(self, s: str) -> bool: + tokens = s.split() + prev_number = -1 + + for token in tokens: + if token.isdigit(): + number = int(token) + if number <= prev_number: + return False + prev_number = number + + return True +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ +- Space Complexity: $O(n)$ +- Where `n` is the length of the sentence. +- The time complexity is $O(n)$ because we iterate through the tokens once. +- The space complexity is $O(n)$ because we store the tokens in a list. + + + + +### Approach 2: Optimized Approach + +The optimized approach uses similar logic but includes improvements such as pre-checking token conditions or using efficient string methods. + +#### Code in Different Languages + + + + + +```cpp +#include +#include + +class Solution { +public: + bool areNumbersAscending(std::string s) { + std::istringstream iss(s); + std::string token; + int prevNumber = -1; + + while (iss >> token) { + if (std::all_of(token.begin(), token.end(), ::isdigit)) { + int number = std::stoi(token); + if (number <= prevNumber) { + return false; + } + prevNumber = number; + } + } + + return true; + } +}; +``` + + + + + +```java +import java.util.*; + +class Solution { + public boolean areNumbersAscending(String s) { + String[] tokens = s.split(" "); + int prevNumber = -1; + + for (String token : tokens) { + if (token.chars().allMatch(Character::isDigit)) { + int number = Integer.parseInt(token); + if (number <= prevNumber) { + return false; + } + prevNumber = number; + } + } + + return true; + } +} +``` + + + + + +```python +class Solution: + def are_numbers_ascending(self, s: str) -> bool: + tokens = s.split() + prev_number = -1 + + for token in tokens: + if token.isdigit(): + number = int(token) + if number <= prev_number: + return False + prev_number = number + + return True +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ +- Space Complexity: $O(n)$ +- Where `n` is the length of the sentence. +- The time complexity is $O(n)$ because we iterate through the tokens once. +- The space complexity is $O(n)$ because we store the tokens in a list. + + + + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2047-number-of-valid-words-in-a-sentence.md b/solutions/lc-solutions/2000-2099/2047-number-of-valid-words-in-a-sentence.md new file mode 100644 index 0000000..a77a761 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2047-number-of-valid-words-in-a-sentence.md @@ -0,0 +1,397 @@ +--- +id: number-of-valid-words-in-a-sentence +title: Number of Valid Words in a Sentence +sidebar_label: 2047-Number of Valid Words in a Sentence +tags: + - Valid Words + - Brute Force + - Optimized + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Number of Valid Words problem on LeetCode." +sidebar_position: 2 +--- + +In this tutorial, we will solve the Number of Valid Words problem using two different approaches: brute force and optimized. We will provide the implementation of the solution in C++, Java, and Python. + +## Problem Description + +Given a sentence, count the number of valid words. A valid word is defined by the following rules: +1. It only contains lowercase letters, hyphens, and/or punctuation (no digits). +2. There is at most one hyphen ('-'). If present, it must be surrounded by lowercase characters ("a-b" is valid, but "-ab" and "ab-" are not valid). +3. There is at most one punctuation mark ('!', '.', ','). If present, it must be at the end of the token ("ab,", "cd!", and "." are valid, but "a!b" and "c.," are not valid). + +### Examples + +**Example 1:** + +``` +Input: sentence = "cat and dog" +Output: 3 +Explanation: The valid words in the sentence are "cat", "and", and "dog". +``` + +**Example 2:** + +``` +Input: sentence = "!this 1-s b8d!" +Output: 0 +Explanation: There are no valid words in the sentence. "!this" is invalid because it starts with a punctuation mark. "1-s" and "b8d" are invalid because they contain digits. + +``` + +**Example 3:** + +``` +Input: sentence = "alice and bob are playing stone-game10" +Output: 5 +Explanation: The valid words in the sentence are "alice", "and", "bob", "are", and "playing". "stone-game10" is invalid because it contains digits. +``` + +### Constraints + +- `1 <= sentence.length <= 1000` +- `sentence` only contains lowercase English letters, digits, ' ', '-', '!', '.', and ','. +- There will be at least 1 token. + +--- + +## Solution for Number of Valid Words Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized approach. The brute force approach directly iterates through the string and checks each token for validity, while the optimized approach streamlines the validation process. + + + + +### Approach 1: Brute Force + +The brute force approach iterates through each token of the sentence, validates it according to the given rules, and counts the number of valid tokens. + +#### Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +public: + int countValidWords(std::string sentence) { + std::istringstream iss(sentence); + std::string word; + int validWordCount = 0; + + while (iss >> word) { + if (isValid(word)) { + validWordCount++; + } + } + + return validWordCount; + } + +private: + bool isValid(const std::string& word) { + int hyphenCount = 0; + int punctuationCount = 0; + + for (int i = 0; i < word.length(); i++) { + if (isdigit(word[i])) { + return false; + } + if (word[i] == '-') { + hyphenCount++; + if (hyphenCount > 1 || i == 0 || i == word.length() - 1 || !islower(word[i-1]) || !islower(word[i+1])) { + return false; + } + } + if (word[i] == '!' || word[i] == '.' || word[i] == ',') { + punctuationCount++; + if (punctuationCount > 1 || i != word.length() - 1) { + return false; + } + } + } + + return true; + } +}; +``` + + + + + +```java +class Solution { + public int countValidWords(String sentence) { + String[] tokens = sentence.split("\\s+"); + int validWordCount = 0; + + for (String token : tokens) { + if (isValid(token)) { + validWordCount++; + } + } + + return validWordCount; + } + + private boolean isValid(String word) { + int hyphenCount = 0; + int punctuationCount = 0; + + for (int i = 0; i < word.length(); i++) { + char c = word.charAt(i); + + if (Character.isDigit(c)) { + return false; + } + if (c == '-') { + hyphenCount++; + if (hyphenCount > 1 || i == 0 || i == word.length() - 1 || !Character.isLowerCase(word.charAt(i - 1)) || !Character.isLowerCase(word.charAt(i + 1))) { + return false; + } + } + if (c == '!' || c == '.' || c == ',') { + punctuationCount++; + if (punctuationCount > 1 || i != word.length() - 1) { + return false; + } + } + } + + return true; + } +} +``` + + + + + +```python +class Solution: + def countValidWords(self, sentence: str) -> int: + tokens = sentence.split() + valid_word_count = 0 + + for token in tokens: + if self.is_valid(token): + valid_word_count += 1 + + return valid_word_count + + def is_valid(self, word: str) -> bool: + hyphen_count = 0 + punctuation_count = 0 + + for i, c in enumerate(word): + if c.isdigit(): + return False + if c == '-': + hyphen_count += 1 + if hyphen_count > 1 or i == 0 or i == len(word) - 1 or not (word[i - 1].islower() and word[i + 1].islower()): + return False + if c in "!.,": + punctuation_count += 1 + if punctuation_count > 1 or i != len(word) - 1: + return False + + return True +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ +- Space Complexity: $O(n)$ +- Where `n` is the length of the sentence. +- The time complexity is $O(n)$ because we iterate through each character in the sentence once. +- The space complexity is $O(n)$ because we store the result in a new string or list of strings. + + + + +### Approach 2: Optimized Approach + +The optimized approach uses similar logic but may include improvements such as pre-checking token conditions or using efficient string methods. + +#### Code in Different Languages + + + + + +```cpp +#include +#include +#include + +class Solution { +public: + int countValidWords(std::string sentence) { + std::istringstream iss(sentence); + std::string word; + int validWordCount = 0; + + while (iss >> word) { + if (isValid(word)) { + validWordCount++; + } + } + + return validWordCount; + } + +private: + bool isValid(const std::string& word) { + int hyphenCount = 0; + int punctuationCount = 0; + int n = word.length(); + + for (int i = 0; i < n; i++) { + char c = word[i]; + + if (isdigit(c)) { + return false; + } + if (c == '-') { + hyphenCount++; + if (hyphenCount > 1 || i == 0 || i == n - 1 || !islower(word[i-1]) || !islower(word[i+1])) { + return false; + } + } + if (c == '!' || c == '.' || c == ',') { + punctuationCount++; + if (punctuationCount > 1 || i != n - 1) { + return false; + } + } + } + + return true; + } +}; +``` + + + + + +```java +class Solution { + public int countValidWords(String sentence) { + String[] tokens = sentence.split("\\s+"); + int validWordCount = 0; + + for (String token : tokens) { + if (isValid(token)) { + validWordCount++; + } + } + + return validWordCount; + } + + private boolean isValid(String word) { + int hyphenCount = 0; + int punctuation + + Count = 0; + int n = word.length(); + + for (int i = 0; i < n; i++) { + char c = word.charAt(i); + + if (Character.isDigit(c)) { + return false; + } + if (c == '-') { + hyphenCount++; + if (hyphenCount > 1 || i == 0 || i == n - 1 || !Character.isLowerCase(word.charAt(i - 1)) || !Character.isLowerCase(word.charAt(i + 1))) { + return false; + } + } + if (c == '!' || c == '.' || c == ',') { + punctuationCount++; + if (punctuationCount > 1 || i != n - 1) { + return false; + } + } + } + + return true; + } +} +``` + + + + + +```python +class Solution: + def countValidWords(self, sentence: str) -> int: + tokens = sentence.split() + valid_word_count = 0 + + for token in tokens: + if self.is_valid(token): + valid_word_count += 1 + + return valid_word_count + + def is_valid(self, word: str) -> bool: + hyphen_count = 0 + punctuation_count = 0 + n = len(word) + + for i, c in enumerate(word): + if c.isdigit(): + return False + if c == '-': + hyphen_count += 1 + if hyphen_count > 1 or i == 0 or i == n - 1 or not (word[i - 1].islower() and word[i + 1].islower()): + return False + if c in "!.,": + punctuation_count += 1 + if punctuation_count > 1 or i != n - 1: + return False + + return True +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ +- Space Complexity: $O(n)$ +- Where `n` is the length of the sentence. +- The time complexity is $O(n)$ because we iterate through each character in the sentence once. +- The space complexity is $O(n)$ because we store the result in a new string or list of strings. + + + + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/2000-2099/2063-vowels-of-all-substrings.md b/solutions/lc-solutions/2000-2099/2063-vowels-of-all-substrings.md new file mode 100644 index 0000000..2f994b2 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2063-vowels-of-all-substrings.md @@ -0,0 +1,314 @@ +--- +id: vowels-of-all-substrings +title: Vowels of All Substrings +sidebar_label: 2063. Vowels of All Substrings + +tags: +- Math +- String +- Dynamic Programming +- Combinatorics + +description: "This is a solution to the Vowels of All Substrings problem on LeetCode." +--- + +## Problem Description +Given a string word, return the sum of the number of vowels ('a', 'e', 'i', 'o', and 'u') in every substring of word. + +A substring is a contiguous (non-empty) sequence of characters within a string. + +Note: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations. + + +### Examples +**Example 1:** + +```Input:word = "aba" +Output: 6 +Explanation: +All possible substrings are: "a", "ab", "aba", "b", "ba", and "a". +- "b" has 0 vowels in it +- "a", "ab", "ba", and "a" have 1 vowel each +- "aba" has 2 vowels in it +Hence, the total sum of vowels = 0 + 1 + 1 + 1 + 1 + 2 = 6. +``` + +**Example 2:** +``` +Input: word = "abc" +Output: 3 +Explanation: +All possible substrings are: "a", "ab", "abc", "b", "bc", and "c". +- "a", "ab", and "abc" have 1 vowel each +- "b", "bc", and "c" have 0 vowels each +Hence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3. +``` + +### Constraints + +- `1 <= word.length <= 10^5` + +## Solution for 2063. Vowels of All Substrings +### Approach + + +1. **Identify Vowels**: + - Create a helper function to check if a character is a vowel by verifying if it is one of 'a', 'e', 'i', 'o', 'u' (case insensitive). + +2. **Prefix Sum Array**: + - Initialize a prefix sum array where `prefix[i]` represents the number of vowels in all substrings ending at index `i`. + +3. **Initialization**: + - Initialize the prefix sum array and a variable to store the final count of vowels. + +4. **Fill Prefix Sum Array**: + - If the first character is a vowel, set `prefix[0]` to 1 and increment the count of vowels. + - For each subsequent character: + - If it is a vowel, update the prefix sum at that index to include all substrings ending at that index plus the previous prefix sum. + - If it is not a vowel, carry forward the previous prefix sum. + +5. **Compute Result**: + - Sum up all the values in the prefix sum array to get the total number of vowels in all substrings. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function isVowel(ch) { + return 'aeiouAEIOU'.indexOf(ch) !== -1; + } + + function countVowels(word) { + let n = word.length; + let prefix = new Array(n).fill(0); + let ans = 0; + + if (isVowel(word[0])) { + prefix[0] = 1; + ans = 1; + } + + for (let i = 1; i < n; i++) { + if (isVowel(word[i])) { + prefix[i] = i + 1 + prefix[i - 1]; + } else { + prefix[i] = prefix[i - 1]; + } + } + + for (let i = 1; i < n; i++) { + ans += prefix[i]; + } + + return ans; + } + const input = "aba" + + const output =countVowels(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n) $ + - Space Complexity: $ O(n)$ + + ## Code in Different Languages + + + + ```javascript +class Solution { + isVowel(ch) { + return 'aeiouAEIOU'.indexOf(ch) !== -1; + } + + countVowels(word) { + let n = word.length; + let prefix = new Array(n).fill(0); + let ans = 0; + + if (this.isVowel(word[0])) { + prefix[0] = 1; + ans = 1; + } + + for (let i = 1; i < n; i++) { + if (this.isVowel(word[i])) { + prefix[i] = i + 1 + prefix[i - 1]; + } else { + prefix[i] = prefix[i - 1]; + } + } + + for (let i = 1; i < n; i++) { + ans += prefix[i]; + } + + return ans; + } +} + + ``` + + + + + ```typescript + class Solution { + isVowel(ch: string): boolean { + return 'aeiouAEIOU'.indexOf(ch) !== -1; + } + + countVowels(word: string): number { + let n = word.length; + let prefix: number[] = new Array(n).fill(0); + let ans = 0; + + if (this.isVowel(word[0])) { + prefix[0] = 1; + ans = 1; + } + + for (let i = 1; i < n; i++) { + if (this.isVowel(word[i])) { + prefix[i] = i + 1 + prefix[i - 1]; + } else { + prefix[i] = prefix[i - 1]; + } + } + + for (let i = 1; i < n; i++) { + ans += prefix[i]; + } + + return ans; + } +} + + ``` + + + + ```python + class Solution: + def isVowel(self, ch: str) -> bool: + return ch in 'aeiouAEIOU' + + def countVowels(self, word: str) -> int: + n = len(word) + prefix = [0] * n + ans = 0 + + if self.isVowel(word[0]): + prefix[0] = 1 + ans = 1 + + for i in range(1, n): + if self.isVowel(word[i]): + prefix[i] = i + 1 + prefix[i - 1] + else: + prefix[i] = prefix[i - 1] + + for i in range(1, n): + ans += prefix[i] + + return ans + + ``` + + + + + ```java + public class Solution { + public boolean isVowel(char ch) { + return "aeiouAEIOU".indexOf(ch) != -1; + } + + public long countVowels(String word) { + int n = word.length(); + long[] prefix = new long[n]; + long ans = 0; + + if (isVowel(word.charAt(0))) { + prefix[0] = 1; + ans = 1; + } + + for (int i = 1; i < n; i++) { + if (isVowel(word.charAt(i))) { + prefix[i] = i + 1 + prefix[i - 1]; + } else { + prefix[i] = prefix[i - 1]; + } + } + + for (int i = 1; i < n; i++) { + ans += prefix[i]; + } + + return ans; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + bool isVowel(char ch) { + return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'; + } + + long long countVowels(string word) { + int n = word.size(); + vector prefix(n, 0); + long long ans = 0; + if(isVowel(word[0])) { + prefix[0] = 1; + ans=1; + } + for(int i = 1; i < n; i++) { + if(isVowel(word[i])) { + prefix[i] = i+1 + prefix[i-1]; + } else { + prefix[i] = prefix[i-1]; + } + } + for(int i = 1; i < n; i++) { + ans+=prefix[i]; + } + return ans; + } +}; + +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [2063. Vowels of All Substrings](https://leetcode.com/problems/vowels-of-all-substrings/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/vowels-of-all-substrings/description/) + diff --git a/solutions/lc-solutions/2000-2099/2069-Walking-Robot-Simulation.md b/solutions/lc-solutions/2000-2099/2069-Walking-Robot-Simulation.md new file mode 100644 index 0000000..b73cb68 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2069-Walking-Robot-Simulation.md @@ -0,0 +1,159 @@ +--- +id: walking-robot-simulation-ii +title: Walking Robot Simulation II +sidebar_label: 2069 - Walking Robot Simulation II +tags: [Simulation, Grid, Robot, C++] +description: Implement a walking robot simulation on a grid where the robot moves forward, turns, and follows specific instructions. + +--- + +## Problem Statement + +### Problem Description + +A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal directions ("North", "East", "South", and "West"). A robot is initially at cell (0, 0) facing direction "East". + +The robot can be instructed to move for a specific number of steps. For each step, it does the following: +- Attempts to move forward one cell in the direction it is facing. +- If the cell the robot is moving to is out of bounds, the robot instead turns 90 degrees counterclockwise and retries the step. + +After the robot finishes moving the number of steps required, it stops and awaits the next instruction. + +Implement the `Robot` class: + +- `Robot(int width, int height)`: Initializes the width x height grid with the robot at (0, 0) facing "East". +- `void step(int num)`: Instructs the robot to move forward num steps. +- `int[] getPos()`: Returns the current cell the robot is at, as an array of length 2, `[x, y]`. +- `String getDir()`: Returns the current direction of the robot, "North", "East", "South", or "West". + +### Example + +**Example 1:** + +``` +Input: +["Robot", "step", "step", "getPos", "getDir", "step", "step", "step", "getPos", "getDir"] +[[6, 3], [2], [2], [], [], [2], [1], [4], [], []] + +Output: +[null, null, null, [4, 0], "East", null, null, null, [1, 2], "West"] +``` +**Explanation:** + +Robot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East. + +robot.step(2); // It moves two steps East to (2, 0), and faces East. + +robot.step(2); // It moves two steps East to (4, 0), and faces East. + +robot.getPos(); // return [4,0] + +robot.getDir(); // return "East" + +robot.step(2); // It moves one step East to (5, 0), and faces East. + +// Moving the next step East would be out of bounds, so it turns and faces North. + +// Then, it moves one step North to (5, 1), and faces North. + +robot.step(1); // It moves one step North to (5, 2), and faces North (not West). + +robot.step(4); // Moving the next step North would be out of bounds, so it turns and faces West. + +// Then, it moves four steps West to (1, 2), and faces West. + +robot.getPos(); // return [1, 2] + +robot.getDir(); // return "West" + + +### Constraints + +- `2 <= width, height <= 100` +- `1 <= num <= 10^5` +- At most `10^4` calls in total will be made to `step`, `getPos`, and `getDir`. + +## Solution + +### Intuition + +- Calculating perimeter with given height and width. +- Using the modulo operator to quickly compute the position and direction the robot stops. +- Note: if the robot moves, its direction for [0, 0] will be South, while it starts at [0, 0] facing East. + + +### Time Complexity and Space Complexity Analysis + +- **Initialization**: + - The `Robot` constructor initializes the grid dimensions and sets the starting position and direction of the robot. This involves a few assignments and does not depend on the size of the input grid. Therefore, the time complexity is O(1). + +- **Step Method**: + - The `step` method updates the robot's position and direction based on the given number of steps. + - The key operation is the modulo operation `count = (count + num) % (2 * (w + h - 2))`. This operation helps in managing large numbers of steps efficiently by reducing the problem to a smaller equivalent number of steps, as the robot will be back to the starting position after every full lap around the grid. The modulo operation is O(1). + - Depending on the value of `count`, the method calculates the new position and direction using simple arithmetic operations and conditional checks. These calculations do not involve any loops or recursive calls and thus take constant time, O(1). + +- **Get Methods**: + - Both `getPos` and `getDir` methods simply return the current position and direction of the robot, which are stored in instance variables. These operations involve accessing and returning stored values, making them O(1). + +- **Overall Time Complexity**: + - The overall time complexity for each method (`Robot` constructor, `step`, `getPos`, and `getDir`) in the `Robot` class is O(1). This means that the time taken by these methods does not depend on the size of the input grid or the number of steps. + +#### Space Complexity Analysis + +- **Instance Variables**: + - The `Robot` class maintains a few instance variables: `w`, `h`, `idx`, `count`, `pos`, `dir`, and `dir_str`. These variables store the dimensions of the grid, the current direction index, the count of steps taken, the current position, and the predefined directions and their string representations. + - The space required to store these variables is constant and does not depend on the input size. The arrays `dir` and `dir_str` have fixed sizes, and other variables are single integers or arrays of fixed length. + +- **Auxiliary Space**: + - The methods `step`, `getPos`, and `getDir` do not use any additional space that grows with the input size. All computations and storage are done using the instance variables. + +- **Overall Space Complexity**: + - The overall space complexity of the `Robot` class is O(1). This means that the space required by the class does not depend on the size of the input grid or the number of steps. + + +- **Time Complexity**: O(1) for each method. +- **Space Complexity**: O(1) for the entire class. + +### Code + +#### C++ +```cpp +class Robot { +public: + vector> dir = {{1,0},{0,1},{-1,0},{0,-1}}; + vector dir_str = {"East","North","West","South"}; + vector pos = {0,0}; + int w, h, idx=0, count=0; + + Robot(int width, int height) { + w = width; + h = height; + } + + void step(int num) { + count = (count + num) % (2 * (w + h - 2)); + + if (count >= 0 && count < w) { + pos = {count, 0}; + idx = count == 0 ? 3 : 0; + } else if (count >= w && count < w + h - 1) { + pos = {w - 1, count - w + 1}; + idx = 1; + } else if (count >= w + h - 1 && count < 2 * w + h - 2) { + pos = {2 * w + h - count - 3, h - 1}; + idx = 2; + } else { + pos = {0, 2 * h + 2 * w - count - 4}; + idx = 3; + } + } + + vector getPos() { + return pos; + } + + string getDir() { + return dir_str[idx]; + } +}; +``` diff --git a/solutions/lc-solutions/2000-2099/2089-find-target-indices-after-sorting-array.md b/solutions/lc-solutions/2000-2099/2089-find-target-indices-after-sorting-array.md new file mode 100644 index 0000000..50b18c5 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2089-find-target-indices-after-sorting-array.md @@ -0,0 +1,137 @@ +--- +id: find-target-indices-after-sorting-array +title: Find Target Indices After Sorting Array +sidebar_label: 2089-Find Target Indices After Sorting Array +tags: + - Array + - Sorting + +description: "This is a solution to find target indices after sorting array in leetcode" +--- + +## Problem Description + +You are given a 0-indexed integer array nums and a target element target. + +A target index is an index i such that `nums[i] == target`. + +Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order. + + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,5,2,3], target = 2 +Output: [1,2] +Explanation: After sorting, nums is [1,2,2,3,5]. +The indices where nums[i] == 2 are 1 and 2. + +``` +**Example 2:** +``` +Input: nums = [1,2,5,2,3], target = 3 +Output: [3] +Explanation: After sorting, nums is [1,2,2,3,5]. +The index where nums[i] == 3 is 3. + + ``` + +**Example 3:** +``` +Input: nums = [1,2,5,2,3], target = 5 +Output: [4] +Explanation: After sorting, nums is [1,2,2,3,5]. +The index where nums[i] == 5 is 4. + ``` +## Complexity Analysis + +*** Time Complexity:** $O(n)$ + +*** Space Complexity:** $O(n)$ + +### Constraints + +- `1 <= nums.length <= 100` +- `1 <= nums[i], target <= 100` + + +### Solution +## Approach + +The first step in solving this problem is to sort the input array, 'nums', in non-decreasing order. Sorting the array helps in locating the target values efficiently because, once sorted, any occurrences of the target value will be contiguous. After sorting the array, we then initialize an empty list , which will store the indices of the target value. We iterate through the sorted array and for each element, we check if it equals the target value. If it does, we add the index of this element to our result list. By the end of the iteration, the result list will contain all the indices where the target value appears in the sorted array. This approach ensures that we correctly identify and record all occurrences of the target value in an orderly manner. + +## Code in Different Languages + + + + + +```cpp +#include +#include + +class Solution { +public: + std::vector targetIndices(std::vector& nums, int target) { + std::sort(nums.begin(), nums.end()); + std::vector result; + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] == target) { + result.push_back(i); + } + } + return result; + } +}; + + + + + +``` + + + + +```java +class Solution { + public List targetIndices(int[] nums, int target) { + Arrays.sort(nums); + ArrayList a=new ArrayList<>(); + for(int i=0;i + + + +```python + + +class Solution: + def targetIndices(self, nums: List[int], target: int) -> List[int]: + nums.sort() + result = [] + for i in range(len(nums)): + if nums[i] == target: + result.append(i) + return result + +``` + + + +## References + +- **LeetCode Problem**: [Find Target Indices After Sorting Array](https://leetcode.com/problems/find-target-indices-after-sorting-array/description/) + +- **Solution Link**: [Find Target Indices After Sorting Array](https://leetcode.com/problems/find-target-indices-after-sorting-array/post-solution/?submissionId=1314681123) diff --git a/solutions/lc-solutions/2000-2099/2096-step-by-step-directions-from-a-binary-tree-node-to-another.md b/solutions/lc-solutions/2000-2099/2096-step-by-step-directions-from-a-binary-tree-node-to-another.md new file mode 100644 index 0000000..3c94db0 --- /dev/null +++ b/solutions/lc-solutions/2000-2099/2096-step-by-step-directions-from-a-binary-tree-node-to-another.md @@ -0,0 +1,283 @@ +--- +id: step-by-step-directions-from-a-binary-tree-node-to-another +title: 2096. Step-By-Step Directions From a Binary Tree Node to Another +sidebar_label: 2096. Step-By-Step Directions From a Binary Tree Node to Another +tags: +- Binary Tree +- DFS + +description: "This is a solution to the 2096. Step-By-Step Directions From a Binary Tree Node to Another problem on LeetCode." +--- + +## Problem Description +You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. + +Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: + +'L' means to go from a node to its left child node. +'R' means to go from a node to its right child node. +'U' means to go from a node to its parent node. +Return the step-by-step directions of the shortest path from node s to node t. + + ### Examples +**Example 1:** +![images](https://assets.leetcode.com/uploads/2021/11/15/eg1.png) +``` +Input: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6 +Output: "UURL" +Explanation: The shortest path is: 3 β†’ 1 β†’ 5 β†’ 2 β†’ 6. +``` + +### Constraints +- `The number of nodes in the tree is n.` +- `2 <= n <= 10^5` +- `1 <= Node.val <= n` +- `All the values in the tree are unique.` +- `1 <= startValue, destValue <= n` +- `startValue != destValue` +## Solution for 2096. Step-By-Step Directions From a Binary Tree Node to Another + + + + + #### Implementation + ```jsx live + function Solution(arr) { + + class TreeNode { + constructor(val = 0, left = null, right = null) { + this.val = val; + this.left = left; + this.right = right; + } +} + +class Solve { + constructor() { + this.path1 = ""; + this.path2 = ""; + } + + solve(root, node, temp, st) { + if (!root) return; + + if (root.val === node) { + if (st === 1) this.path1 = temp; + else this.path2 = temp; + return; + } + + temp += 'L'; + this.solve(root.left, node, temp, st); + temp = temp.slice(0, -1); + + temp += 'R'; + this.solve(root.right, node, temp, st); + temp = temp.slice(0, -1); + } + + getDirections(root, startValue, destValue) { + let temp = ""; + this.solve(root, startValue, temp, 1); + temp = ""; + this.solve(root, destValue, temp, 0); + + let i = 0; + while (i < this.path1.length && i < this.path2.length && this.path1[i] === this.path2[i]) { + i++; + } + + let result = ""; + for (let j = i; j < this.path1.length; j++) { + result += 'U'; + } + + result += this.path2.substring(i); + return result; + } +} + + const input =0 + const output = 0 + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n) $ + - Space Complexity: $ O(n)$ + + ## Code in Different Languages + + + + ```python + class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def __init__(self): + self.path1 = "" + self.path2 = "" + + def solve(self, root, node, temp, st): + if not root: + return + + if root.val == node: + if st == 1: + self.path1 = temp + else: + self.path2 = temp + return + + self.solve(root.left, node, temp + 'L', st) + self.solve(root.right, node, temp + 'R', st) + + def getDirections(self, root, startValue, destValue): + self.solve(root, startValue, "", 1) + self.solve(root, destValue, "", 0) + + i = 0 + while i < len(self.path1) and i < len(self.path2) and self.path1[i] == self.path2[i]: + i += 1 + + result = 'U' * (len(self.path1) - i) + self.path2[i:] + return result + + ``` + + + + + ```java +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +public class Solution { + String path1 = ""; + String path2 = ""; + + void solve(TreeNode root, int node, StringBuilder temp, int st) { + if (root == null) return; + + if (root.val == node) { + if (st == 1) path1 = temp.toString(); + else path2 = temp.toString(); + return; + } + + temp.append('L'); + solve(root.left, node, temp, st); + temp.deleteCharAt(temp.length() - 1); + + temp.append('R'); + solve(root.right, node, temp, st); + temp.deleteCharAt(temp.length() - 1); + } + + public String getDirections(TreeNode root, int startValue, int destValue) { + StringBuilder temp = new StringBuilder(); + solve(root, startValue, temp, 1); + temp = new StringBuilder(); + solve(root, destValue, temp, 0); + + int i = 0; + while (i < path1.length() && i < path2.length() && path1.charAt(i) == path2.charAt(i)) { + i++; + } + + StringBuilder result = new StringBuilder(); + for (int j = i; j < path1.length(); j++) { + result.append('U'); + } + + result.append(path2.substring(i)); + return result.toString(); + } +} + + + ``` + + + + + + ```cpp + class Solution { +public: + string path1 = ""; + string path2 = ""; + + void solve(TreeNode* root, int node, string &temp, int st) { + if (!root) return ; + + if (root->val == node) { + if (st == 1) path1 = temp; + else path2 = temp; + return ; + } + + temp.push_back('L'); + solve(root->left, node, temp, st); + temp.pop_back(); + + temp.push_back('R'); + solve(root->right, node, temp, st); + temp.pop_back(); + } + + string getDirections(TreeNode* root, int startValue, int destValue) { + string temp = ""; + solve(root, startValue, temp, 1); + temp = ""; + solve(root, destValue, temp, 0); + + cout << path1 <<" "< + + +
+
+ +## References + +- **LeetCode Problem**: [2096. Step-By-Step Directions From a Binary Tree Node to Another](https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/) + diff --git a/solutions/lc-solutions/2000-2099/_category_.json b/solutions/lc-solutions/2000-2099/_category_.json new file mode 100644 index 0000000..a7509fb --- /dev/null +++ b/solutions/lc-solutions/2000-2099/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "2000-2099", + "position": 22, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (2000 - 2099)" + } +} diff --git a/solutions/lc-solutions/2100-2199/2108-find-first-palindromic-string-in-the-array.md b/solutions/lc-solutions/2100-2199/2108-find-first-palindromic-string-in-the-array.md new file mode 100644 index 0000000..bb29239 --- /dev/null +++ b/solutions/lc-solutions/2100-2199/2108-find-first-palindromic-string-in-the-array.md @@ -0,0 +1,145 @@ +--- +id: find-first-palindromic-string-in-the-array +title: Find First Palindromic String in the Array +sidebar_label: 2108-Find First Palindromic String in the Array +tags: + - Array + - Two Pointers + - String + +description: "This is a solution to the Find First Palindromic String in the Array in leetcode" +--- + +## Problem Description + +Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "". + +A string is palindromic if it reads the same forward and backward. + + + + +### Examples + +**Example 1:** + +``` +Input: words = ["abc","car","ada","racecar","cool"] +Output: "ada" +Explanation: The first string that is palindromic is "ada". +Note that "racecar" is also palindromic, but it is not the first. + +``` +**Example 2:** +``` +Input: words = ["notapalindrome","racecar"] +Output: "racecar" +Explanation: The first and only string that is palindromic is "racecar". + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(1)$ + +*** Space Complexity:** $O(1)$ + +### Constraints + +- `1 <= words.length <= 100` +- `1 <= words[i].length <= 100` +- `words[i]` consists only of lowercase English letters. + + + + +### Solution +## Approach +The approach involves iterating through each word in the list and checking if it is a palindrome by comparing it to its reverse. If a palindrome is found, it is returned immediately. If no palindromes are found after checking all the words, an empty string is returned. This ensures the first palindrome in the list is identified efficiently. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + std::string firstPalindrome(const std::vector& words) { + for (const std::string& word : words) { + if (isPalindrome(word)) { + return word; + } + } + return ""; + } + +private: + bool isPalindrome(const std::string& word) { + int left = 0; + int right = word.size() - 1; + while (left < right) { + if (word[left] != word[right]) { + return false; + } + left++; + right--; + } + return true; + } +}; + + +``` + + + + +```java +class Solution { + public String firstPalindrome(String[] words) { + for (String word : words) { + if (isPalindrome(word)) { + return word; + } + } + return ""; + } + + private boolean isPalindrome(String word) { + int left = 0; + int right = word.length() - 1; + while (left < right) { + if (word.charAt(left) != word.charAt(right)) { + return false; + } + left++; + right--; + } + return true; + } +} + +``` + + + + +```python +class Solution: + def firstPalindrome(self, words: List[str]) -> str: + for i in words: + if i==i[::-1]: + return i + return "" + + +``` + + + +## References + +- **LeetCode Problem**: [Find First Palindromic String in the Array](https://leetcode.com/problems/find-first-palindromic-string-in-the-array/description/) + +- **Solution Link**: [Find First Palindromic String in the Array](https://leetcode.com/problems/find-first-palindromic-string-in-the-array/post-solution/?submissionId=1215484481) diff --git a/solutions/lc-solutions/2100-2199/2114-maximum-number-of-words-found-in-sentences.md b/solutions/lc-solutions/2100-2199/2114-maximum-number-of-words-found-in-sentences.md new file mode 100644 index 0000000..ba59271 --- /dev/null +++ b/solutions/lc-solutions/2100-2199/2114-maximum-number-of-words-found-in-sentences.md @@ -0,0 +1,134 @@ +--- +id: maximum-number-of-words-found-in-sentences +title: Maximum Number of Words Found in Sentences +sidebar_label: 2114-Maximum Number of Words Found in Sentences + - Array + - String +description: "This is a solution to the maximum number of words found in sentences in leetcode" +--- + +## Problem Description + +A sentence is a list of words that are separated by a single space with no leading or trailing spaces. +You are given an array of strings sentences, where each sentences[i] represents a single sentence. +Return the maximum number of words that appear in a single sentence. + + +### Examples + +**Example 1:** + +``` +Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"] +Output: 6 +Explanation: +- The first sentence, "alice and bob love leetcode", has 5 words in total. +- The second sentence, "i think so too", has 4 words in total. +- The third sentence, "this is great thanks very much", has 6 words in total. +Thus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words. + +``` +**Example 2:** +``` +Input: sentences = ["please wait", "continue to fight", "continue to win"] +Output: 3 +Explanation: It is possible that multiple sentences contain the same number of words. +In this example, the second and third sentences (underlined) have the same number of words. + + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(n*m)$ + +*** Space Complexity:** $O(1)$ + +### Constraints + +- `1 <= sentences.length <= 100` +- `1 <= sentences[i].length <= 10` +- + +### Solution +## Approach +The approach for solving the problem of finding the sentence with the most words involves the following steps: +1. Initialize a Maximum Word Count Variable: Start by initializing a variable (maxWords) to keep track of the maximum number of words found in any sentence. Set it initially to 0. + +2. Iterate Through Each Sentence: Loop through each sentence in the provided list of sentences. + +3. Split Each Sentence into Words: For each sentence, split it into words. This can be done using a space (' ') as the delimiter. + +4. Count the Number of Words: Count the number of words in the current sentence by finding the length of the resulting list of words. + +5. Update the Maximum Word Count: Compare the word count of the current sentence with the current maximum word count. If the current sentence has more words, update the maxWords variable. + +6. Return the Maximum Word Count: After iterating through all the sentences, return the value of maxWords, which now holds the maximum number of words found in any sentence. + +## Code in Different Languages + + + + + +```cpp +#include +#include +#include +#include + +class Solution { +public: + int mostWordsFound(std::vector& sentences) { + int maxWords = 0; + for (const std::string& sentence : sentences) { + int wordCount = std::count(sentence.begin(), sentence.end(), ' ') + 1; + maxWords = std::max(maxWords, wordCount); + } + return maxWords; + } +}; + +``` + + + + +```java +class Solution { + public int mostWordsFound(String[] sentences) { + //int n=sentences.length; + //int[] a=new int[n]; + int max=0; + for(String ch:sentences){ + String[] a=ch.split(" "); + max=Math.max(max,a.length); + + + } + return max; +} +} +``` + + + + +```python +class Solution: + def most_words_found(self, sentences): + max_words = 0 + for sentence in sentences: + word_count = len(sentence.split()) + max_words = max(max_words, word_count) + return max_words + + +``` + + + +## References + +- **LeetCode Problem**: [Maximum Number of Words Found in Sentences](https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/description/) + +- **Solution Link**: [Maximum Number of Words Found in Sentences](https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/post-solution/?submissionId=1230077072) diff --git a/solutions/lc-solutions/2100-2199/2119-A-Number-After-A-Double_reversal.md b/solutions/lc-solutions/2100-2199/2119-A-Number-After-A-Double_reversal.md new file mode 100644 index 0000000..2a40925 --- /dev/null +++ b/solutions/lc-solutions/2100-2199/2119-A-Number-After-A-Double_reversal.md @@ -0,0 +1,73 @@ +--- +id: a-number-after-a-double-reversal +title: A Number After a Double Reversal +sidebar_label: 2119-A-Number-After-A-Double_reversal +tags: + - Math +--- + +## Problem Description +Reversing an integer means to reverse all its digits. + +For example, reversing `2021` gives `1202`. Reversing `12300` gives `321` as the leading zeros are not retained. +Given an integer `num`, reverse `num` to get `reversed1`, then reverse `reversed1` to get `reversed2`. Return `true` if `reversed2` equals `num`. Otherwise return `false`. + + +### Example + +**Example 1:** + + +``` +Input: num = 526 +Output: true +Explanation: Reverse num to get 625, then reverse 625 to get 526, which equals num. +``` +**Example 2:** +``` +Input: num = 1800 +Output: false +Explanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num. + +``` +### Constraints + +- `0 <= num <= 106` + +## Solution Approach + +### Intuition: + +To efficiently determine the number + +## Solution Implementation + +### Code (C++): +```cpp +class Solution { +public: + bool isSameAfterReversals(int num) { + int rev1 = 0; + int rem1 = 0; + int temp1 = num; + + while(num>0){ + + rem1 = num%10; + rev1 = rev1*10+rem1; + num/=10; + } + int rev2 = 0; + int rem2 = 0; + while(rev1>0){ + rem2 = rev1%10; + rev2 = rev2*10+rem2; + rev1/=10; + } + if(temp1==rev2) return true; + return false; + + + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2100-2199/2150.find-all-lonely-numbers-in-the-array.md b/solutions/lc-solutions/2100-2199/2150.find-all-lonely-numbers-in-the-array.md new file mode 100644 index 0000000..9926116 --- /dev/null +++ b/solutions/lc-solutions/2100-2199/2150.find-all-lonely-numbers-in-the-array.md @@ -0,0 +1,266 @@ +--- +id: find-all-lonely-numbers-in-the-array +title: 2150. Find All Lonely Numbers in the Array +sidebar_label: 2150. Find All Lonely Numbers in the Array + +tags: +- Array +- Hash Table +- Counting + +description: "This is a solution to the 2150. Find All Lonely Numbers in the Array problem on LeetCode." +--- + +## Problem Description +You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array. + +Return all lonely numbers in nums. You may return the answer in any order. + + +### Examples +**Example 1:** + +``` +Input: nums = [10,6,5,8] +Output: [10,8] +Explanation: +- 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums. +- 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums. +- 5 is not a lonely number since 6 appears in nums and vice versa. +Hence, the lonely numbers in nums are [10, 8]. +Note that [8, 10] may also be returned. +``` + +**Example 2:** +``` +Input: nums = [1,3,5,3] +Output: [1,5] +Explanation: +- 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums. +- 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums. +- 3 is not a lonely number since it appears twice. +Hence, the lonely numbers in nums are [1, 5]. +Note that [5, 1] may also be returned. + +``` + +### Constraints +- `0 <= nums.length <= 10^5` + +## Solution for 2150. Find All Lonely Numbers in the Array +## 1. Count Frequencies +- Use a map (or dictionary) to count the frequency of each number in the array. + +## 2. Identify Lonely Numbers +- Iterate through the map (or dictionary) to find numbers that appear exactly once and do not have adjacent numbers (num-1 and num+1) present in the map. + +## 3. Return the Result +- Collect all such lonely numbers in a list and return the list. + + + + + #### Implementation + ```jsx live + function findLonely(nums) { + let ans = []; + let mp = {}; + + for (let i of nums) { + mp[i] = (mp[i] || 0) + 1; + } + + for (let key in mp) { + if (mp[key] === 1) { + if (mp.hasOwnProperty(key - 1) || mp.hasOwnProperty(Number(key) + 1)) { + continue; + } else { + ans.push(Number(key)); + } + } + } + return ans; +} + const input = [10,6,5,8] + const output = findLonely(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(nlogn) $ + - Space Complexity: $ O(n)$ + + ## Code in Different Languages + + + + ```javascript + class Solution { + findLonely(nums) { + let ans = []; + let mp = new Map(); + + for (let i of nums) { + mp.set(i, (mp.get(i) || 0) + 1); + } + + for (let [key, value] of mp) { + if (value === 1) { + if (mp.has(key - 1) || mp.has(key + 1)) { + continue; + } else { + ans.push(key); + } + } + } + return ans; + } +} + + ``` + + + + + ```typescript + class Solution { + findLonely(nums: number[]): number[] { + let ans: number[] = []; + let mp: Map = new Map(); + + for (let i of nums) { + mp.set(i, (mp.get(i) || 0) + 1); + } + + for (let [key, value] of mp) { + if (value === 1) { + if (mp.has(key - 1) || mp.has(key + 1)) { + continue; + } else { + ans.push(key); + } + } + } + return ans; + } +} + + ``` + + + + ```python + class Solution: + def findLonely(self, nums: List[int]) -> List[int]: + ans = [] + mp = {} + + for i in nums: + if i in mp: + mp[i] += 1 + else: + mp[i] = 1 + + for key, value in mp.items(): + if value == 1: + if (key - 1) in mp or (key + 1) in mp: + continue + else: + ans.append(key) + + return ans + + ``` + + + + + ```java + import java.util.*; + +class Solution { + public List findLonely(int[] nums) { + List ans = new ArrayList<>(); + Map mp = new HashMap<>(); + + for (int i : nums) { + mp.put(i, mp.getOrDefault(i, 0) + 1); + } + + for (Map.Entry entry : mp.entrySet()) { + int key = entry.getKey(); + int value = entry.getValue(); + if (value == 1) { + if (mp.containsKey(key - 1) || mp.containsKey(key + 1)) { + continue; + } else { + ans.add(key); + } + } + } + return ans; + } +} + + ``` + + + + + ```cpp +class Solution { +public: + vector findLonely(vector& nums) { + vectorans; + mapmp; + + for(auto i:nums) + { + mp[i]++; + } + + for(auto i:mp) + { + if(i.second==1) + { + if(mp.find(i.first-1)!=mp.end()) + { + continue; + } + else if(mp.find(i.first+1)!=mp.end()) + { + continue; + } + else{ + ans.push_back(i.first); + } + } + } + return ans; + } +}; + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [2150. Find All Lonely Numbers in the Array](https://leetcode.com/problems/find-all-lonely-numbers-in-the-array/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/find-all-lonely-numbers-in-the-array/) + diff --git a/solutions/lc-solutions/2100-2199/2154-Keep-Multiplying-Found-Values-By-Two.md b/solutions/lc-solutions/2100-2199/2154-Keep-Multiplying-Found-Values-By-Two.md new file mode 100644 index 0000000..d3aa994 --- /dev/null +++ b/solutions/lc-solutions/2100-2199/2154-Keep-Multiplying-Found-Values-By-Two.md @@ -0,0 +1,178 @@ +--- +id: keep-multiplying-found-values-by-two +title: Keep Multiplying Found Values by Two +sidebar_label: 2154-Keep-Multiplying-Found-Values-By-Two +tags: + - Array + - Hash Table + - Sorting + - Simulation + +description: The problem no. is 1351. The Problem is Count Negative Numbers in a Sorted Matrix. +--- + +## Problem Description +You are given an array of integers `nums`. You are also given an integer `original` which is the first number that needs to be searched for in `nums`. + +You then do the following steps: + +If `original` is found in `nums`, multiply it by two (i.e., set `original = 2 * original)`. +Otherwise, stop the process. +Repeat this process with the new number as long as you keep finding the number. +Return the final value of `original`. + + +### Example + +**Example 1:** + + +``` +Input: nums = [5,3,6,1,12], original = 3 +Output: 24 +Explanation: +- 3 is found in nums. 3 is multiplied by 2 to obtain 6. +- 6 is found in nums. 6 is multiplied by 2 to obtain 12. +- 12 is found in nums. 12 is multiplied by 2 to obtain 24. +- 24 is not found in nums. Thus, 24 is returned. +``` +**Example 2:** +``` +Input: nums = [2,7,9], original = 4 +Output: 4 +Explanation: +- 4 is not found in nums. Thus, 4 is returned. +``` +### Constraints + +- `1 <= nums[i], original <= 1000` + +## Solution Approach + +### Intuition: + +To efficiently Keep Multiplying Found Values by Two +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + +class Solution { + findFinalValue(nums, original) { + let n = nums.length; + let i = 0; + while(i < n){ + if(nums[i] === original){ + original *= 2; + i = 0; + } else { + i++; + } + } + return original; + } +} + + + ``` + + + + + ```typescript + +class Solution { + findFinalValue(nums: number[], original: number): number { + let n = nums.length; + let i = 0; + while(i < n){ + if(nums[i] === original){ + original *= 2; + i = 0; + } else { + i++; + } + } + return original; + } +} + ``` + + + + + ```python + class Solution: + def findFinalValue(self, nums, original): + n = len(nums) + i = 0 + while i < n: + if nums[i] == original: + original *= 2 + i = 0 + else: + i += 1 + return original + + + ``` + + + + + ```java + public class Solution { + public int findFinalValue(int[] nums, int original) { + int n = nums.length; + int i = 0; + while(i < n){ + if(nums[i] == original){ + original *= 2; + i = 0; + } else { + i++; + } + } + return original; + } +} + + + + ``` + + + + + ```cpp +class Solution { +public: + int findFinalValue(vector& nums, int original) { + int n = nums.size(); + int i = 0; + while(i + + +#### Complexity Analysis + +- Time Complexity: $$O(m*n)$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(log(n))$$ where n is the length of the input array nums. This is because in the worst case, the algorithm may need to iterate through the entire array for each doubling of original, resulting in a linear time complexity. +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/2100-2199/2169-Count-Operations-to-Obtain-Zero.md b/solutions/lc-solutions/2100-2199/2169-Count-Operations-to-Obtain-Zero.md new file mode 100644 index 0000000..30c33d7 --- /dev/null +++ b/solutions/lc-solutions/2100-2199/2169-Count-Operations-to-Obtain-Zero.md @@ -0,0 +1,184 @@ +--- +id: count-operations-to-obtain-zero +title: Count Operations to Obtain Zero +sidebar_label: 2169-Count-Operations-to-Obtain-Zero +tags: + - Math + - Simulation + +description: The problem no. is 2169. The Problem is to count Operations to Obtain Zero. +--- + +## Problem Description +You are given two non-negative integers `num1` and `num2`. + +In one operation, if `num1 >= num2`, you must subtract `num2` from `num1`, otherwise subtract `num1` from `num2`. + +For example, if `num1 = 5` and `num2 = 4`, subtract `num2` from `num1`, thus obtaining `num1 = 1` and `num2 = 4`. However, if `num1 = 4` and `num2 = 5`, after one operation, `num1 = 4` and `num2 = 1`. +Return the number of operations required to make either `num1 = 0` or `num2 = 0`. + + +### Example + +**Example 1:** + + +``` +Input: num1 = 2, num2 = 3 +Output: 3 +Explanation: +- Operation 1: num1 = 2, num2 = 3. Since num1 < num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1. +- Operation 2: num1 = 2, num2 = 1. Since num1 > num2, we subtract num2 from num1. +- Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1. +Now num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations. +So the total number of operations required is 3. +``` +**Example 2:** +``` +Input: num1 = 10, num2 = 10 +Output: 1 +Explanation: +- Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0. +Now num1 = 0 and num2 = 10. Since num1 == 0, we are done. +So the total number of operations required is 1. +``` +### Constraints + +- `0 <= num1, num2 <= 105` + +## Solution Approach + +### Intuition: + +To efficiently Count Operations to Obtain Zero +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + +class Solution { + countOperations(num1, num2) { + let cnt = 0; + while(num1 !== 0 && num2 !== 0){ + if(num1 >= num2){ + cnt += Math.floor(num1 / num2); + num1 = num1 % num2; + } else { + cnt += Math.floor(num2 / num1); + num2 = num2 % num1; + } + } + return cnt; + } +} + + + + ``` + + + + + ```typescript + +class Solution { + countOperations(num1: number, num2: number): number { + let cnt = 0; + while(num1 !== 0 && num2 !== 0){ + if(num1 >= num2){ + cnt += Math.floor(num1 / num2); + num1 = num1 % num2; + } else { + cnt += Math.floor(num2 / num1); + num2 = num2 % num1; + } + } + return cnt; + } +} + + ``` + + + + + ```python + +class Solution: + def countOperations(self, num1, num2): + cnt = 0 + while num1 != 0 and num2 != 0: + if num1 >= num2: + cnt += num1 // num2 + num1 = num1 % num2 + else: + cnt += num2 // num1 + num2 = num2 % num1 + return cnt + + + + ``` + + + + + ```java + public class Solution { + public int countOperations(int num1, int num2) { + long cnt = 0; + while(num1 != 0 && num2 != 0){ + if(num1 >= num2){ + cnt += num1 / num2; + num1 = num1 % num2; + } else { + cnt += num2 / num1; + num2 = num2 % num1; + } + } + return (int) cnt; + } +} + + + + + ``` + + + + + ```cpp +class Solution { +public: + int countOperations(int num1, int num2) { + long long cnt = 0; + while(num1!=0 && num2!=0){ + if(num1>=num2){ + cnt += num1/num2; + num1 = num1%num2; + } + else { + cnt += num2/num1; + num2 = num2%num1; + } + } + return cnt; + + } +}; + +``` + + + +#### Complexity Analysis + +- Time Complexity: $$O(log(max(num1, num2)))$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(log(max(num1, num2)))$$, where num1 and num2 are the input numbers. This is because in each iteration, the larger number is reduced by a factor of at least 2 (due to the division and modulo operations). +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/2100-2199/2176-Count-Equal-And-Divisible-Pairs-In-An-Array.md b/solutions/lc-solutions/2100-2199/2176-Count-Equal-And-Divisible-Pairs-In-An-Array.md new file mode 100644 index 0000000..bd2ab3b --- /dev/null +++ b/solutions/lc-solutions/2100-2199/2176-Count-Equal-And-Divisible-Pairs-In-An-Array.md @@ -0,0 +1,149 @@ +--- +id: count-equal-and-divisible-pairs-in-an-array +title: Count Equal and Divisible Pairs in an Array +sidebar_label: 2176-Count-Equal-And-Divisible-Pairs-In-An-Array +tags: + - Array + +description: The problem no. is 2176. The Problem is to Count Equal and Divisible Pairs in an Array. +--- + +## Problem Description +Given a 0-indexed integer array `nums` of length n and an integer `k`, return the number of pairs `(i, j)` where `0 <= i < j < n`, such that `nums[i] == nums[j]` and `(i * j)` is divisible by `k`. + + +### Example + +**Example 1:** +``` +Input: nums = [3,1,2,2,2,1,3], k = 2 +Output: 4 +Explanation: +There are 4 pairs that meet all the requirements: +- nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2. +- nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2. +- nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2. +- nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2. +``` + + +**Example 2:** +``` +Input: nums = [1,2,3,4], k = 1 +Output: 0 +Explanation: Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements. +``` +### Constraints + +- `1 <= nums[i], k <= 100` + +## Solution Approach + +### Intuition: + +To efficiently Count Equal and Divisible Pairs in an Array + + + +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + +class Solution { + countPairs(nums, k) { + const n = nums.length; + let cnt = 0; + for(let i = 0; i < n - 1; i++){ + for(let j = i + 1; j < n; j++){ + if(nums[i] === nums[j]){ + if((i * j) % k === 0) cnt++; + } + } + } + return cnt; + } +} + ``` + + + + + ```typescript + +class Solution { + countPairs(nums: number[], k: number): number { + const n = nums.length; + let cnt = 0; + for(let i = 0; i < n - 1; i++){ + for(let j = i + 1; j < n; j++){ + if(nums[i] === nums[j]){ + if((i * j) % k === 0) cnt++; + } + } + } + return cnt; + } +} + + + ``` + + + + + ```python + +class Solution: + def countPairs(self, nums, k): + n = len(nums) + cnt = 0 + for i in range(n - 1): + for j in range(i + 1, n): + if nums[i] == nums[j]: + if (i * j) % k == 0: + cnt += 1 + return cnt + ``` + + + + + ```java + public class Solution { + public int countPairs(int[] nums, int k) { + int n = nums.length; + int cnt = 0; + for(int i = 0; i < n - 1; i++){ + for(int j = i + 1; j < n; j++){ + if(nums[i] == nums[j]){ + if((i * j) % k == 0) cnt++; + } + } + } + return cnt; + } +} + + ``` + + + + + ```cpp + + +``` + + + +#### Complexity Analysis + +- Time Complexity: $$O(n^2)$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(n^2)$$, where n is the length of the input array nums. This is because the algorithm uses nested loops to iterate over all pairs of elements in the array. +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/2100-2199/2177.find-three-consecutive-integers-that-sum-to-a-given-number.md b/solutions/lc-solutions/2100-2199/2177.find-three-consecutive-integers-that-sum-to-a-given-number.md new file mode 100644 index 0000000..6ce7927 --- /dev/null +++ b/solutions/lc-solutions/2100-2199/2177.find-three-consecutive-integers-that-sum-to-a-given-number.md @@ -0,0 +1,197 @@ +--- +id: find-three-consecutive-integers-that-sum-to-a-given-number +title: 2177. Find Three Consecutive Integers That Sum to a Given Number +sidebar_label: 2177. Find Three Consecutive Integers That Sum to a Given Number + +tags: +- Maths + +description: "This is a solution to the 2177. Find Three Consecutive Integers That Sum to a Given Number problem on LeetCode." +--- + +## Problem Description +Given an integer num, return three consecutive integers (as a sorted array) that sum to num. If num cannot be expressed as the sum of three consecutive integers, return an empty array. + + +### Examples +**Example 1:** + +``` +Input: num = 33 +Output: [10,11,12] +Explanation: 33 can be expressed as 10 + 11 + 12 = 33. +10, 11, 12 are 3 consecutive integers, so we return [10, 11, 12]. +``` + +**Example 2:** +``` +Input: num = 4 +Output: [] +Explanation: There is no way to express 4 as the sum of 3 consecutive integers. +``` + +### Constraints +- `0 <= num <= 10^15` + +## Solution for 2177. Find Three Consecutive Integers That Sum to a Given Number + +1. **Function Definition**: + - Define a function `sumOfThree` that takes a number `num` as input. + - Initialize an empty list `v` to store the result. + +2. **Check Divisibility**: + - Check if `num` is divisible by 3. + - If not, return the empty list `v`. + +3. **Calculate Consecutive Integers**: + - If `num` is divisible by 3, calculate the three consecutive integers: + - The first integer is `(num / 3) - 1`. + - The second integer is `num / 3`. + - The third integer is `(num / 3) + 1`. + - Add these integers to the list `v`. + +4. **Return the Result**: + - Return the list `v` containing the three consecutive integers if they exist, otherwise return the empty list. + + + + + #### Implementation + ```jsx live + function sumOfThree(num) { + let v = []; + if (num % 3 === 0) { + v.push((num / 3) - 1); + v.push(num / 3); + v.push((num / 3) + 1); + } + return v; + } + const input = 33 + const output = sumOfThree(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(1) $ + - Space Complexity: $ O(1)$ + + ## Code in Different Languages + + + + ```javascript + class Solution { + sumOfThree(num) { + let v = []; + if (num % 3 === 0) { + v.push((num / 3) - 1); + v.push(num / 3); + v.push((num / 3) + 1); + } + return v; + } +} + + ``` + + + + + ```typescript + class Solution { + sumOfThree(num: number): number[] { + let v: number[] = []; + if (num % 3 === 0) { + v.push((num / 3) - 1); + v.push(num / 3); + v.push((num / 3) + 1); + } + return v; + } +} + + ``` + + + + ```python + class Solution: + def sumOfThree(self, num: int): + v = [] + if num % 3 == 0: + v.append((num // 3) - 1) + v.append(num // 3) + v.append((num // 3) + 1) + return v + + + ``` + + + + + ```java + import java.util.*; + +class Solution { + public List sumOfThree(long num) { + List v = new ArrayList<>(); + if (num % 3 == 0) { + v.add((num / 3) - 1); + v.add(num / 3); + v.add((num / 3) + 1); + } + return v; + } +} + + ``` + + + + + ```cpp +class Solution { +public: + vector sumOfThree(long long num) { + vectorv; + if(num%3==0) + { + v.push_back((num/3)-1); + v.push_back((num/3)); + v.push_back((num/3)+1); + } + else + { + return v; + } + return v; + + } +}; + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [2177. Find Three Consecutive Integers That Sum to a Given Number](https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/) + diff --git a/solutions/lc-solutions/2100-2199/2180-Count-Integers-With-Even-Digit-Sum.md b/solutions/lc-solutions/2100-2199/2180-Count-Integers-With-Even-Digit-Sum.md new file mode 100644 index 0000000..2addd64 --- /dev/null +++ b/solutions/lc-solutions/2100-2199/2180-Count-Integers-With-Even-Digit-Sum.md @@ -0,0 +1,200 @@ +--- +id: count-integers-even-digit-sum +title: Count Integers With Even Digit Sum +sidebar_label: 2180-Count-Integers-With-Even-Digit-Sum +tags: + - Math + - Simulation + +description: The problem no. is 2180. The Problem is to Count Integers With Even Digit Sum +--- + +## Problem Description +Given a positive integer `num`, return the number of positive integers less than or equal to `num` whose digit sums are even. + +The digit sum of a positive integer is the sum of all its digits. + + +### Example + +**Example 1:** + + +``` +Input: num = 4 +Output: 2 +Explanation: +The only integers less than or equal to 4 whose digit sums are even are 2 and 4. +``` +**Example 2:** +``` +Input: num = 30 +Output: 14 +Explanation: +The 14 integers less than or equal to 30 whose digit sums are even are +2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28. +``` +### Constraints + +- `1 <= num <= 1000` + +## Solution Approach + +### Intuition: + +To efficiently Count Integers With Even Digit Sum + + +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + +class Solution { + countEven(num) { + let cnt = 0; + for(let i = 1; i <= num; i++){ + let sum = 0; + if(i < 10){ + if(i % 2 == 0) cnt++; + } else{ + let temp = i; + while(temp > 0){ + let rev = temp % 10; + sum += rev; + temp = Math.floor(temp / 10); + } + if(sum % 2 == 0) cnt++; + } + } + return cnt; + } +} + + + ``` + + + + + ```typescript + +class Solution { + countEven(num: number): number { + let cnt = 0; + for(let i = 1; i <= num; i++){ + let sum = 0; + if(i < 10){ + if(i % 2 == 0) cnt++; + } else{ + let temp = i; + while(temp > 0){ + let rev = temp % 10; + sum += rev; + temp = Math.floor(temp / 10); + } + if(sum % 2 == 0) cnt++; + } + } + return cnt; + } +} + + + ``` + + + + + ```python + +class Solution: + def countEven(self, num): + cnt = 0 + for i in range(1, num + 1): + sum = 0 + if i < 10: + if i % 2 == 0: + cnt += 1 + else: + temp = i + while temp > 0: + rev = temp % 10 + sum += rev + temp = temp // 10 + if sum % 2 == 0: + cnt += 1 + return cnt + + + ``` + + + + + ```java + public class Solution { + public int countEven(int num) { + int cnt = 0; + for(int i = 1; i <= num; i++){ + int sum = 0; + if(i < 10){ + if(i % 2 == 0) cnt++; + } else{ + int temp = i; + while(temp > 0){ + int rev = temp % 10; + sum += rev; + temp = temp / 10; + } + if(sum % 2 == 0) cnt++; + } + } + return cnt; + } +} + + ``` + + + + + ```cpp +class Solution { +public: + int countEven(int num) { + int cnt = 0; + for(int i=1; i<=num; i++){ + int sum = 0; + if(i<10){ + if(i%2==0) cnt++; + } + else{ + int temp = i; + while(temp>0){ + int rev = temp%10; + sum+=rev; + temp/=10; + } + if(sum%2==0) cnt++; + + } + } + return cnt; + } +}; + +``` + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(n)$$,where n is the input number num. This is because the algorithm uses a single loop that iterates from 1 to num. +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/2100-2199/2192.all-ancestors-of-a-node-in-a-directed-acyclic-graph.md b/solutions/lc-solutions/2100-2199/2192.all-ancestors-of-a-node-in-a-directed-acyclic-graph.md new file mode 100644 index 0000000..b130208 --- /dev/null +++ b/solutions/lc-solutions/2100-2199/2192.all-ancestors-of-a-node-in-a-directed-acyclic-graph.md @@ -0,0 +1,311 @@ +--- +id: all-ancestors-of-a-node-in-a-directed-acyclic-graph +title: 2192. All Ancestors of a Node in a Directed Acyclic Graph +sidebar_label: 2192. All Ancestors of a Node in a Directed Acyclic Graph + +tags: +- Depth-First Search +- Breadth-First Search +- Graph +- Topological Sort + +description: "This is a solution to the 2192. All Ancestors of a Node in a Directed Acyclic Graph problem on LeetCode." +--- + +## Problem Description +You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive). + +You are also given a 2D integer array edges, where edges[i] = [fromi, toi] denotes that there is a unidirectional edge from fromi to toi in the graph. + +Return a list answer, where answer[i] is the list of ancestors of the ith node, sorted in ascending order. + +A node u is an ancestor of another node v if u can reach v via a set of edges. + + +### Examples +**Example 1:** +![image](https://assets.leetcode.com/uploads/2019/12/12/e1.png) + +``` +Input: n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]] +Output: [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]] +Explanation: +The above diagram represents the input graph. +- Nodes 0, 1, and 2 do not have any ancestors. +- Node 3 has two ancestors 0 and 1. +- Node 4 has two ancestors 0 and 2. +- Node 5 has three ancestors 0, 1, and 3. +- Node 6 has five ancestors 0, 1, 2, 3, and 4. +- Node 7 has four ancestors 0, 1, 2, and 3. +``` + +**Example 2:** +![image](https://assets.leetcode.com/uploads/2019/12/12/e2.png) + +``` +Input: n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] +Output: [[],[0],[0,1],[0,1,2],[0,1,2,3]] +Explanation: +The above diagram represents the input graph. +- Node 0 does not have any ancestor. +- Node 1 has one ancestor 0. +- Node 2 has two ancestors 0 and 1. +- Node 3 has three ancestors 0, 1, and 2. +- Node 4 has four ancestors 0, 1, 2, and 3. +``` + +### Constraints +- `1 <= n <= 1000` +- `0 <= edges.length <= min(2000, n * (n - 1) / 2)` +- `edges[i].length == 2` +- `0 <= fromi, toi <= n - 1` +- `fromi != toi` +- `There are no duplicate edges.` +- `The graph is directed and acyclic.` + +## Solution for 2192. All Ancestors of a Node in a Directed Acyclic Graph + +## 1. Initialize Data Structures +- Create an adjacency list to represent the graph. +- Create an answer list to store the ancestors for each node. + +## 2. Build the Graph +- Populate the adjacency list from the given edges. Each edge `[u, v]` represents a directed edge from node `u` to node `v`. + +## 3. Depth-First Search (DFS) Traversal +- For each node in the graph, perform a DFS to find all its ancestors. +- Mark the current node as visited. +- For each adjacent node that has not been visited, add the parent node to its ancestor list and continue the DFS traversal. + +## 4. Return the Result +- After traversing all nodes, return the list of ancestors for each node. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function dfs(node, parent, ans, vis, adj) { + vis[node] = 1; + for (let adjNode of adj[node]) { + if (!vis[adjNode]) { + ans[adjNode].push(parent); + dfs(adjNode, parent, ans, vis, adj); + } + } + } + + function getAncestors(n, edges) { + let ans = Array.from({ length: n }, () => []); + let adj = Array.from({ length: n }, () => []); + for (let [u, v] of edges) { + adj[u].push(v); + } + + for (let i = 0; i < n; i++) { + let vis = new Array(n).fill(0); + dfs(i, i, ans, vis, adj); + } + return ans; + } + const input = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]] + const output = getAncestors(input, edgeList) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(N^2 + N*E) $ + - Space Complexity: $ O(N^2)$ + + ## Code in Different Languages + + + + ```javascript + class Solution { + dfs(node, parent, ans, vis, adj) { + vis[node] = 1; + for (let adjNode of adj[node]) { + if (!vis[adjNode]) { + ans[adjNode].push(parent); + this.dfs(adjNode, parent, ans, vis, adj); + } + } + } + + getAncestors(n, edges) { + let ans = Array.from({ length: n }, () => []); + let adj = Array.from({ length: n }, () => []); + for (let [u, v] of edges) { + adj[u].push(v); + } + + for (let i = 0; i < n; i++) { + let vis = new Array(n).fill(0); + this.dfs(i, i, ans, vis, adj); + } + return ans; + } +} + + ``` + + + + + ```typescript + class Solution { + dfs(node: number, parent: number, ans: number[][], vis: number[], adj: number[][]): void { + vis[node] = 1; + for (let adjNode of adj[node]) { + if (!vis[adjNode]) { + ans[adjNode].push(parent); + this.dfs(adjNode, parent, ans, vis, adj); + } + } + } + + getAncestors(n: number, edges: number[][]): number[][] { + let ans = Array.from({ length: n }, () => []); + let adj: number[][] = Array.from({ length: n }, () => []); + for (let [u, v] of edges) { + adj[u].push(v); + } + + for (let i = 0; i < n; i++) { + let vis: number[] = new Array(n).fill(0); + this.dfs(i, i, ans, vis, adj); + } + return ans; + } +} + + ``` + + + + ```python + class Solution: + def dfs(self, node, parent, ans, vis, adj): + vis[node] = 1 + for adjNode in adj[node]: + if not vis[adjNode]: + ans[adjNode].append(parent) + self.dfs(adjNode, parent, ans, vis, adj) + + def getAncestors(self, n, edges): + ans = [[] for _ in range(n)] + adj = [[] for _ in range(n)] + for u, v in edges: + adj[u].append(v) + + for i in range(n): + vis = [0] * n + self.dfs(i, i, ans, vis, adj) + return ans + + ``` + + + + + ```java + import java.util.*; + +class Solution { + void dfs(int node, int parent, List> ans, boolean[] vis, List[] adj) { + vis[node] = true; + for (int adjNode : adj[node]) { + if (!vis[adjNode]) { + ans.get(adjNode).add(parent); + dfs(adjNode, parent, ans, vis, adj); + } + } + } + + public List> getAncestors(int n, int[][] edges) { + List> ans = new ArrayList<>(); + for (int i = 0; i < n; i++) { + ans.add(new ArrayList<>()); + } + + List[] adj = new ArrayList[n]; + for (int i = 0; i < n; i++) { + adj[i] = new ArrayList<>(); + } + + for (int[] edge : edges) { + adj[edge[0]].add(edge[1]); + } + + for (int i = 0; i < n; i++) { + boolean[] vis = new boolean[n]; + dfs(i, i, ans, vis, adj); + } + return ans; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + void dfs(int node ,int parent ,vector>&ans, vector&vis , vectoradj[]) + { + vis[node]=1; + for(auto adjNode : adj[node]) + { + if(!vis[adjNode]) + { + ans[adjNode].push_back(parent); + dfs(adjNode ,parent ,ans , vis , adj); + } + } + + } + vector> getAncestors(int n, vector>& edges) { + vector>ans(n); + vectoradj[n]; + for(auto i:edges) + { + adj[i[0]].push_back(i[1]); + } + + for(int i=0;ivis(n,0); + dfs(i,i, ans , vis , adj); + } + return ans; + } +}; + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [2192. All Ancestors of a Node in a Directed Acyclic Graph](https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/) + diff --git a/solutions/lc-solutions/2100-2199/_category_.json b/solutions/lc-solutions/2100-2199/_category_.json new file mode 100644 index 0000000..3c4e3a1 --- /dev/null +++ b/solutions/lc-solutions/2100-2199/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "2100-2199", + "position": 23, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (2100 - 2199)" + } +} diff --git a/solutions/lc-solutions/2200-2299/2200-Find All K-Distant Indices in an Array.md b/solutions/lc-solutions/2200-2299/2200-Find All K-Distant Indices in an Array.md new file mode 100644 index 0000000..c93f614 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2200-Find All K-Distant Indices in an Array.md @@ -0,0 +1,185 @@ +--- +id: Find-All-K-Distant-Indices-in-an-Array +title: Find All K-Distant Indices in an Array +sidebar_label: 2200 Find All K-Distant Indices in an Array +tags: + - Arrays + - C++ + - Java + - Python +description: "This document provides a solution where we will be returning an array in increasing order , satisfying the condition given" +--- + +## Problem + +You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| < = k and nums[j] == key. + +Return a list of all k-distant indices sorted in increasing order. + +### Examples + +**Example 1:** + +Input: nums = [3,4,9,1,3,9,5], key = 9, k = 1 +Output: [1,2,3,4,5,6] +Explanation: Here, nums[2] == key and nums[5] == key. +- For index 0, |0 - 2| > k and |0 - 5| > k, so there is no j where |0 - j| < = k and nums[j] == key. Thus, 0 is not a k-distant index. +- For index 1, |1 - 2| < = k and nums[2] == key, so 1 is a k-distant index. +- For index 2, |2 - 2| < = k and nums[2] == key, so 2 is a k-distant index. +- For index 3, |3 - 2| < = k and nums[2] == key, so 3 is a k-distant index. +- For index 4, |4 - 5| < = k and nums[5] == key, so 4 is a k-distant index. +- For index 5, |5 - 5| < = k and nums[5] == key, so 5 is a k-distant index. +- For index 6, |6 - 5| < = k and nums[5] == key, so 6 is a k-distant index. +Thus, we return [1,2,3,4,5,6] which is sorted in increasing order. + +**Example 2:** + +Input: nums = [2,2,2,2,2], key = 2, k = 2 +Output: [0,1,2,3,4] +Explanation: For all indices i in nums, there exists some index j such that |i - j| < = k and nums[j] == key, so every index is a k-distant index. +Hence, we return [0,1,2,3,4]. + +### Constraints + +- 1 < = nums.length < 1000 +- 1 < nums[i] < 1000 +- key is an integer from the array nums. +- 1 < k < nums.length + +### Approach + +1.Identify all indices where the value in the array equals the key. +2.For each key index, mark all indices within the distance k as k-distant. +3.Collect all unique k-distant indices and sort them in increasing order. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +#include +#include + +std::vector findKDistantIndices(std::vector& nums, int key, int k) { + std::vector key_indices; + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] == key) { + key_indices.push_back(i); + } + } + + std::set k_distant_indices; + for (int key_index : key_indices) { + int start = std::max(0, key_index - k); + int end = std::min((int)nums.size() - 1, key_index + k); + for (int i = start; i <= end; ++i) { + k_distant_indices.insert(i); + } + } + + return std::vector(k_distant_indices.begin(), k_distant_indices.end()); +} + +int main() { + std::vector nums = {3, 4, 9, 1, 3, 9, 5}; + int key = 9; + int k = 1; + std::vector result = findKDistantIndices(nums, key, k); + + for (int index : result) { + std::cout << index << " "; + } + // Output: 1 2 3 4 5 6 + return 0; +} + +``` + +### Java Solution + +```java +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.Collections; + +public class Main { + public static List findKDistantIndices(int[] nums, int key, int k) { + List keyIndices = new ArrayList<>(); + for (int i = 0; i < nums.length; i++) { + if (nums[i] == key) { + keyIndices.add(i); + } + } + + Set kDistantIndices = new HashSet<>(); + for (int keyIndex : keyIndices) { + int start = Math.max(0, keyIndex - k); + int end = Math.min(nums.length - 1, keyIndex + k); + for (int i = start; i <= end; i++) { + kDistantIndices.add(i); + } + } + + List result = new ArrayList<>(kDistantIndices); + Collections.sort(result); + return result; + } + + public static void main(String[] args) { + int[] nums = {3, 4, 9, 1, 3, 9, 5}; + int key = 9; + int k = 1; + List result = findKDistantIndices(nums, key, k); + + for (int index : result) { + System.out.print(index + " "); + } + // Output: [1, 2, 3, 4, 5, 6] + } +} + +``` + +### Python Solution + +```python +def find_k_distant_indices(nums, key, k): + key_indices = [i for i, num in enumerate(nums) if num == key] + k_distant_indices = set() + + for key_index in key_indices: + start = max(0, key_index - k) + end = min(len(nums) - 1, key_index + k) + for i in range(start, end + 1): + k_distant_indices.add(i) + + return sorted(k_distant_indices) + +# Example usage: +nums = [3, 4, 9, 1, 3, 9, 5] +key = 9 +k = 1 +print(find_k_distant_indices(nums, key, k)) # Output: [1, 2, 3, 4, 5, 6] + +``` + +### Complexity Analysis + +### Time Complexity: $O(nlogn)$ + +> **Reason**: for identifying key indices , marking k-distinct indices and for sorting +### Space Complexity: $O(n)$ + +> **Reason**: for storing key indices, k-distant indices and for sorting. + + + +### References + +**LeetCode Problem:** Find All K-Distant Indices in an Array diff --git a/solutions/lc-solutions/2200-2299/2220-minimum-bit-flips-to-convert-number.md b/solutions/lc-solutions/2200-2299/2220-minimum-bit-flips-to-convert-number.md new file mode 100644 index 0000000..f76588a --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2220-minimum-bit-flips-to-convert-number.md @@ -0,0 +1,128 @@ +--- +id: minimum-bit-flips-to-convert-number +title: 2220. Minimum Bit Flips to Convert Number +sidebar_label: 2220. Minimum Bit Flips to Convert Number +tags: +- Bit Manipulation + +description: "This is a solution to the 2220. Minimum Bit Flips to Convert Number." +--- + +## Problem Description +A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. + +For example, for x = 7, the binary representation is 111 and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get 110, flip the second bit from the right to get 101, flip the fifth bit from the right (a leading zero) to get 10111, etc. + +Given two integers start and goal, return the minimum number of bit flips to convert start to goal. + + ### Examples +**Example 1:** +``` +Input: start = 10, goal = 7 + +Output: 3 + +Explanation: + +The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps: +- Flip the first bit from the right: 1010 -> 1011. +- Flip the third bit from the right: 1011 -> 1111. +- Flip the fourth bit from the right: 1111 -> 0111. +It can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3. +``` + +**Example 2:** +``` +Input: start = 3, goal = 4 + +Output: 3 + +Explanation: + +The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps: +- Flip the first bit from the right: 011 -> 010. +- Flip the second bit from the right: 010 -> 000. +- Flip the third bit from the right: 000 -> 100. +It can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3. +``` + +### Constraints +- `0 <= start, goal <= 10^9` +## Solution for 2220. Minimum Bit Flips to Convert Number + +The problem seems to involve finding the minimum number of bit flips required to transform one integer (start) into another integer (goal). + +## Approach + +The approach used in the provided code involves XORing the start and goal integers to find the positions where the bits differ. Then, the number of set bits in the result is counted to determine the minimum number of flips needed. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + int minBitFlips(int start, int goal) { + int res=start^goal; // XOR to find the differing bits + int count=0; + while(res){ + count+=res&1; // Count the set bits + res>>=1; // Right shift to check next bit + } + return count; + } +}; +``` + + + +```java +class Solution { + public int minBitFlips(int start, int goal) { + int res = start ^ goal; // XOR to find the differing bits + int count = 0; + while (res != 0) { + count += res & 1; // Count the set bits + res >>= 1; // Right shift to check the next bit + } + return count; + } +} +``` + + + + + + +```python +class Solution: + def minBitFlips(self, start: int, goal: int) -> int: + res = start ^ goal # XOR to find the differing bits + count = 0 + while res: + count += res & 1 # Count the set bits + res >>= 1 # Right shift to check the next bit + return count +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: The time complexity of this solution is $O(n)$, where n is the number of bits in the integers. +- **Space Complexity**: The space complexity is $O(1)$ because the algorithm only uses a constant amount of extra space. + +--- + +

Authors:

+ +
+{['nagalakshmi08'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/2200-2299/2226-Maximum-Candies-Allocated-to-K-Children.md b/solutions/lc-solutions/2200-2299/2226-Maximum-Candies-Allocated-to-K-Children.md new file mode 100644 index 0000000..be57e23 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2226-Maximum-Candies-Allocated-to-K-Children.md @@ -0,0 +1,189 @@ +--- +id: Maximum-Candies-Allocated-to-K-Children +title: Maximum Candies Allocated to K Children +sidebar_label: 2226-Maximum Candies Allocated to K Children +tags: + - Arrays + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together. + +You are also given an integer k. You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused. + +Return the maximum number of candies each child can get. +### Examples + +**Example 1:** + +Input: candies = [5,8,6], k = 3 +Output: 5 +Explanation: We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies. + +**Example 2:** + +Input: candies = [2,5], k = 11 +Output: 0 +Explanation: There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0. + + + + +### Constraints + +- `1 <= candies.length <= 105` +- `1 <= candies[i] <= 107` +- `1 <= k <= 1012` + +### Approach + +Initialize: Set the search range from 1 to the maximum number of candies in any pile. +Binary Search: +- Calculate the middle value of the current range. +- Check if it's possible to distribute this many candies per child to all k children by dividing the piles. +- Adjust the range based on whether the distribution was possible. +Return Result: The highest feasible value found during the search is the answer. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +using namespace std; + +bool canDistribute(const vector& candies, long long mid, long long k) { + long long count = 0; + for (int candy : candies) { + count += candy / mid; + } + return count >= k; +} + +int maxCandies(vector& candies, long long k) { + long long left = 1, right = *max_element(candies.begin(), candies.end()); + while (left <= right) { + long long mid = left + (right - left) / 2; + if (canDistribute(candies, mid, k)) { + left = mid + 1; + } else { + right = mid - 1; + } + } + return right; +} + +// Example usage: +#include +int main() { + vector candies1 = {5, 8, 6}; + long long k1 = 3; + cout << maxCandies(candies1, k1) << endl; // Output: 5 + + vector candies2 = {2, 5}; + long long k2 = 11; + cout << maxCandies(candies2, k2) << endl; // Output: 0 + + return 0; +} + + + +``` + +### Java Solution + +```java +public class MaxCandies { + public static boolean canDistribute(int[] candies, long mid, long k) { + long count = 0; + for (int candy : candies) { + count += candy / mid; + } + return count >= k; + } + + public static int maxCandies(int[] candies, long k) { + long left = 1, right = Integer.MIN_VALUE; + for (int candy : candies) { + right = Math.max(right, candy); + } + + while (left <= right) { + long mid = left + (right - left) / 2; + if (canDistribute(candies, mid, k)) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return (int) right; + } + + public static void main(String[] args) { + int[] candies1 = {5, 8, 6}; + long k1 = 3; + System.out.println(maxCandies(candies1, k1)); // Output: 5 + + int[] candies2 = {2, 5}; + long k2 = 11; + System.out.println(maxCandies(candies2, k2)); // Output: 0 + } +} + + +``` + +### Python Solution + +```python +def maxCandies(candies, k): + def canDistribute(mid): + count = 0 + for candy in candies: + count += candy // mid + return count >= k + + left, right = 1, max(candies) + while left <= right: + mid = (left + right) // 2 + if canDistribute(mid): + left = mid + 1 + else: + right = mid - 1 + + return right + +# Example usage: +candies1 = [5, 8, 6] +k1 = 3 +print(maxCandies(candies1, k1)) # Output: 5 + +candies2 = [2, 5] +k2 = 11 +print(maxCandies(candies2, k2)) # Output: 0 + + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n*logm)$ + +> **Reason**:Binary search runs in O(logm), and each check inside the binary search takes O(n). + + +### Space Complexity: $O(1)$ + +> **Reason**: Only a constant amount of extra space is used, regardless of the input size. + diff --git a/solutions/lc-solutions/2200-2299/2229-Check-if-an-Array-Is-Consecutive.md b/solutions/lc-solutions/2200-2299/2229-Check-if-an-Array-Is-Consecutive.md new file mode 100644 index 0000000..98d6255 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2229-Check-if-an-Array-Is-Consecutive.md @@ -0,0 +1,153 @@ +--- +id: Check-if-an-Array-Is-Consecutive +title: Check if an Array Is Consecutive +sidebar_label: 2229- Check if an Array Is Consecutive +tags: + - Arrays + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +You are given an array of integers. You need to determine if the elements of the array form a consecutive sequence. A sequence is considered consecutive if each number appears exactly once and the difference between the maximum and minimum number in the array is equal to the length of the array minus one. + +### Examples + +**Example 1:** + +Input: `[4, 2, 3, 5, 1]` +Output: `true` +Explanation: The array `[4, 2, 3, 5, 1]` contains all numbers from 1 to 5 without any missing elements. The difference between the maximum (5) and minimum (1) is 4, which equals the length of the array minus one. + +**Example 2:** + +Input: `[7, 6, 5, 8, 9]` +Output: `true` +Explanation: The array `[7, 6, 5, 8, 9]` contains all numbers from 5 to 9 without any missing elements. The difference between the maximum (9) and minimum (5) is 4, which equals the length of the array minus one. + +**Example 3"** + +Input: `[1, 2, 4, 5]` +Output: `false` +Explanation: The array `[1, 2, 4, 5]` is not consecutive because the number 3 is missing. The difference between the maximum (5) and minimum (1) is 4, but the length of the array is only 4, so it's not consecutive. + + +### Constraints + +- The array contains distinct integers. +- The length of the array is between 1 and 100,000. + +### Approach + +To determine if an array is consecutive, follow these steps: + +- Find the minimum and maximum values in the array. +- Check if the difference between the maximum and minimum values is equal to the length of the array minus one. +- Use a set to check for uniqueness and presence of all elements between the minimum and maximum values. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +#include +#include +#include + +bool isConsecutive(const std::vector& arr) { + if (arr.empty()) return false; + int minVal = INT_MAX; + int maxVal = INT_MIN; + std::unordered_set uniqueElements; + + for (int num : arr) { + if (num < minVal) minVal = num; + if (num > maxVal) maxVal = num; + uniqueElements.insert(num); + } + + return (maxVal - minVal == arr.size() - 1) && (uniqueElements.size() == arr.size()); +} + +int main() { + std::vector arr1 = {4, 2, 3, 5, 1}; + std::vector arr2 = {1, 2, 4, 5}; + std::cout << (isConsecutive(arr1) ? "true" : "false") << std::endl; // Output: true + std::cout << (isConsecutive(arr2) ? "false" : "true") << std::endl; // Output: false + return 0; +} + + +``` + +### Java Solution + +```java +import java.util.HashSet; +import java.util.Set; + +public class ConsecutiveArrayCheck { + public static boolean isConsecutive(int[] arr) { + if (arr.length == 0) return false; + int minVal = Integer.MAX_VALUE; + int maxVal = Integer.MIN_VALUE; + Set uniqueElements = new HashSet<>(); + + for (int num : arr) { + if (num < minVal) minVal = num; + if (num > maxVal) maxVal = num; + uniqueElements.add(num); + } + + return (maxVal - minVal == arr.length - 1) && (uniqueElements.size() == arr.length); + } + + // Example usage + public static void main(String[] args) { + int[] arr1 = {4, 2, 3, 5, 1}; + int[] arr2 = {1, 2, 4, 5}; + System.out.println(isConsecutive(arr1)); // Output: true + System.out.println(isConsecutive(arr2)); // Output: false + } +} + +``` + +### Python Solution + +```python +def is_consecutive(arr): + if not arr: + return False + min_val = min(arr) + max_val = max(arr) + if max_val - min_val != len(arr) - 1: + return False + return len(set(arr)) == len(arr) + +# Example usage +print(is_consecutive([4, 2, 3, 5, 1])) # Output: True +print(is_consecutive([1, 2, 4, 5])) # Output: False + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n)$ + +> **Reason**:for finding the minimum and maximum ,converting the list to a set and checking its length + + +### Space Complexity: $O(n)$ + +> **Reason**: for using a set to store unique elements of the array. + + diff --git a/solutions/lc-solutions/2200-2299/2233-Maximum-Product-After-K-Increments.md b/solutions/lc-solutions/2200-2299/2233-Maximum-Product-After-K-Increments.md new file mode 100644 index 0000000..97a77de --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2233-Maximum-Product-After-K-Increments.md @@ -0,0 +1,177 @@ +--- +id: Maximum-Product-After-K-Increments +title: Maximum Product After K Increments +sidebar_label: 2233-Maximum Product After K Increments +tags: + - Arrays + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. + +Return the maximum product of nums after at most k operations. + +### Examples + +**Example 1:** + +Input: nums = [0,4], k = 5 +Output: 20 +Explanation: Increment the first number 5 times. +Now nums = [5, 4], with a product of 5 * 4 = 20. +It can be shown that 20 is maximum product possible, so we return 20. +Note that there may be other ways to increment nums to have the maximum product. + +**Example 2:** + +Input: nums = [6,3,3,2], k = 2 +Output: 216 +Explanation: Increment the second number 1 time and increment the fourth number 1 time. +Now nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216. +It can be shown that 216 is maximum product possible, so we return 216. +Note that there may be other ways to increment nums to have the maximum product. + + +### Constraints + +- `1 <= nums.length, k <= 105` +- `0 <= nums[i] <= 106` +### Approach + +Use a Min-Heap: Convert the array into a min-heap to efficiently manage the smallest element. +Perform Increments: For each of the +k operations: +- Extract the smallest element from the heap. +- Increment this element by 1. +- Push the incremented element back into the heap. +Calculate the Product: After completing all increments, compute the product of all elements in the heap. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +#include + +using namespace std; + +int maxProduct(vector& nums, int k) { + const int MOD = 1e9 + 7; + priority_queue, greater> minHeap(nums.begin(), nums.end()); + + for (int i = 0; i < k; ++i) { + int minVal = minHeap.top(); + minHeap.pop(); + minHeap.push(minVal + 1); + } + + long long product = 1; + while (!minHeap.empty()) { + product = (product * minHeap.top()) % MOD; + minHeap.pop(); + } + + return product; +} + +int main() { + vector nums1 = {0, 4}; + int k1 = 5; + cout << maxProduct(nums1, k1) << endl; // Output: 20 + + vector nums2 = {6, 3, 3, 2}; + int k2 = 2; + cout << maxProduct(nums2, k2) << endl; // Output: 216 + + return 0; +} + + + +``` + +### Java Solution + +```java +import java.util.PriorityQueue; + +public class MaxProduct { + public static int maxProduct(int[] nums, int k) { + final int MOD = 1_000_000_007; + PriorityQueue minHeap = new PriorityQueue<>(); + for (int num : nums) { + minHeap.add(num); + } + + for (int i = 0; i < k; ++i) { + int minVal = minHeap.poll(); + minHeap.add(minVal + 1); + } + + long product = 1; + while (!minHeap.isEmpty()) { + product = (product * minHeap.poll()) % MOD; + } + + return (int) product; + } + + public static void main(String[] args) { + int[] nums1 = {0, 4}; + int k1 = 5; + System.out.println(maxProduct(nums1, k1)); // Output: 20 + + int[] nums2 = {6, 3, 3, 2}; + int k2 = 2; + System.out.println(maxProduct(nums2, k2)); // Output: 216 + } +} + + +``` + +### Python Solution + +```python +import heapq + +def maxProduct(nums, k): + MOD = 10**9 + 7 + heapq.heapify(nums) # Turn nums into a min-heap + + for _ in range(k): + min_val = heapq.heappop(nums) + heapq.heappush(nums, min_val + 1) + + product = 1 + for num in nums: + product = (product * num) % MOD + + return product + +# Example usage +print(maxProduct([0, 4], 5)) # Output: 20 +print(maxProduct([6, 3, 3, 2], 2)) # Output: 216 + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n+k*logn)$ + +> **Reason**:$O(n)$ for heapifying the array and $O(k*logn)$ for k increment operations + +### Space Complexity: $O(n)$ + +> **Reason**: due to the storage required for the heap. + diff --git a/solutions/lc-solutions/2200-2299/2235-add-two-integers.md b/solutions/lc-solutions/2200-2299/2235-add-two-integers.md new file mode 100644 index 0000000..4e6a053 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2235-add-two-integers.md @@ -0,0 +1,88 @@ +--- +id: add-two-integers +title: Add Two Integers +sidebar_label: 2255 - Add Two Integers +tags: + - Functions + - Arguments +description: Given two integers `num1` and `num2`, return the **sum** of the two integers. +sidebar_position: 2235 +--- + +## Problem Statement +Given two integers `num1` and `num2`, return the **sum** of the two integers. + +### Examples + +**Example 1:** + +``` +Input: num1 = 12, num2 = 5 +Output: 17 +Explination: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned. +``` + +**Example 2:** + +``` +Input: num1 = -10, num2 = 4 +Output: -6 +Explination: num1 + num2 = -6, so -6 is returned. +``` + + + +### Constraints + +- `-100 <= num1, num2 <= 100` + +## Solution + +#### C++ Implementation + +```cpp +class Solution { +public: + int sum(int num1, int num2) { + return num1 + num2; + } +}; +``` + +#### Python Implementation + +```python +class Solution: + def sum(self, num1: int, num2: int) -> int: + return num1 + num2 +``` + +#### Java Implementation + +```java +class Solution { + public int sum(int num1, int num2) { + return num1 + num2; + } +} +``` + +#### JavaScript Implementation + +```javascript + var sum = function(num1, num2) { + return num1 + num2; +}; +``` + +#### TypeScript Implementation + +```typescript + function sum(num1: number, num2: number): number { + return num1 + num2; +}; +``` + +### Conclusion + +These implementations handle the addition of two integers and return their sum. The examples provided also show how to use each function. The problem is straightforward and has a constant time complexity of 𝑂(1) for each implementation. diff --git a/solutions/lc-solutions/2200-2299/2236- Root-Equals-Sum-of-Children.md b/solutions/lc-solutions/2200-2299/2236- Root-Equals-Sum-of-Children.md new file mode 100644 index 0000000..07a884a --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2236- Root-Equals-Sum-of-Children.md @@ -0,0 +1,127 @@ +--- +id: Root-Equals-Sum-of-Children +title: Root Equals Sum of Children +sidebar_label: 2236- Root Equals Sum of Children +tags: + - Trees + - C++ + - Java + - Python +description: "This document provides a solution for the given problem in c++ , java and python languages" +--- + +## Problem + +You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. + +Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise. + + +### Examples + +**Example 1:** + +Input: root = [10,4,6] +Output: true +Explanation: The values of the root, its left child, and its right child are 10, 4, and 6, respectively. +10 is equal to 4 + 6, so we return true. + +**Example 2:** + +Input: root = [5,3,1] +Output: false +Explanation: The values of the root, its left child, and its right child are 5, 3, and 1, respectively. +5 is not equal to 3 + 1, so we return false. + +### Constraints + +- The tree consists only of the root, its left child, and its right child. +- -100 <= Node.val <= 100 + + +### Approach + +1.Traversal: Since the tree structure is fixed with exactly three nodes, we can directly access the root and its children. +2.Comparison: Check if the value of the root node equals the sum of its left and right children. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} +}; + +class Solution { +public: + bool isSumEqual(TreeNode* root) { + if (!root) return false; + int leftVal = (root->left) ? root->left->val : 0; + int rightVal = (root->right) ? root->right->val : 0; + return root->val == leftVal + rightVal; + } +}; + + +``` + +### Java Solution + +```java +class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int val) { + this.val = val; + } +} + +public class Solution { + public boolean isSumEqual(TreeNode root) { + if (root == null) return false; + int leftVal = (root.left != null) ? root.left.val : 0; + int rightVal = (root.right != null) ? root.right.val : 0; + return root.val == leftVal + rightVal; + } +} + +``` + +### Python Solution + +```python +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def isSumEqual(self, root: TreeNode) -> bool: + if not root: + return False + left_val = root.left.val if root.left else 0 + right_val = root.right.val if root.right else 0 + return root.val == left_val + right_val + +``` + +### Complexity Analysis + +### Time Complexity: $O(1)$ + +> **Reason**: for accessing the value of root node and its children , performing comparisons +### Space Complexity: $O(1)$ + +> **Reason**: we are not using any additional data structures. + + + diff --git a/solutions/lc-solutions/2200-2299/2239-Find-Closest-Number-to-Zero.md b/solutions/lc-solutions/2200-2299/2239-Find-Closest-Number-to-Zero.md new file mode 100644 index 0000000..42c45ad --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2239-Find-Closest-Number-to-Zero.md @@ -0,0 +1,146 @@ +--- +id: Find-Closest-Number-to-Zero +title: Find Closest Number to Zero +sidebar_label: 2239-Find Closest Number to Zero +tags: + - Arrays + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +Given an integer array nums of size n, return the number with the value closest to 0 in nums. If there are multiple answers, return the number with the largest value. + + + +### Examples + +**Example 1:** + +Input: nums = [-4,-2,1,4,8] +Output: 1 +Explanation: +The distance from -4 to 0 is |-4| = 4. +The distance from -2 to 0 is |-2| = 2. +The distance from 1 to 0 is |1| = 1. +The distance from 4 to 0 is |4| = 4. +The distance from 8 to 0 is |8| = 8. +Thus, the closest number to 0 in the array is 1. + +**Example 2:** + +Input: nums = [2,-1,1] +Output: 1 +Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned. + + + + +### Constraints + +- 1 <= n <= 1000 +- 105 <= nums[i] <= 105 + +### Approach +Iterate through the array and keep track of the number with the smallest absolute value (closest to zero). If two numbers have the same absolute value, the larger number is preferred. + + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +#include +using namespace std; + +int closestToZero(vector& nums) { + int closest = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + if (abs(nums[i]) < abs(closest) || (abs(nums[i]) == abs(closest) && nums[i] > closest)) { + closest = nums[i]; + } + } + return closest; +} + +int main() { + vector nums = {-4, -2, 1, 4, 8}; + int result = closestToZero(nums); + cout << "Output: " << result << endl; // Output: 1 + + vector nums2 = {2, -1, 1}; + int result2 = closestToZero(nums2); + cout << "Output: " << result2 << endl; // Output: 1 + + return 0; +} + +``` + +### Java Solution + +```java +import java.util.Arrays; + +public class ClosestToZero { + public static int closestToZero(int[] nums) { + int closest = nums[0]; + for (int i = 1; i < nums.length; i++) { + if (Math.abs(nums[i]) < Math.abs(closest) || (Math.abs(nums[i]) == Math.abs(closest) && nums[i] > closest)) { + closest = nums[i]; + } + } + return closest; + } + + public static void main(String[] args) { + int[] nums1 = {-4, -2, 1, 4, 8}; + System.out.println("Output: " + closestToZero(nums1)); // Output: 1 + + int[] nums2 = {2, -1, 1}; + System.out.println("Output: " + closestToZero(nums2)); // Output: 1 + } +} + + +``` + +### Python Solution + +```python +def closest_to_zero(nums): + closest = nums[0] + for num in nums[1:]: + if abs(num) < abs(closest) or (abs(num) == abs(closest) and num > closest): + closest = num + return closest + +# Example usage: +nums1 = [-4, -2, 1, 4, 8] +print("Output:", closest_to_zero(nums1)) # Output: 1 + +nums2 = [2, -1, 1] +print("Output:", closest_to_zero(nums2)) # Output: 1 + + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n)$ + +> **Reason**:Iteration through the array where n is the length of the array. + +### Space Complexity: $O(n)$ + +> **Reason**: for storing elements of the array. + + diff --git a/solutions/lc-solutions/2200-2299/2240-Number-of-Ways-to-Buy-Pens-and-Pencils.md b/solutions/lc-solutions/2200-2299/2240-Number-of-Ways-to-Buy-Pens-and-Pencils.md new file mode 100644 index 0000000..b644574 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2240-Number-of-Ways-to-Buy-Pens-and-Pencils.md @@ -0,0 +1,130 @@ +--- +id: Number-of-Ways-to-Buy-Pens-and-Pencils +title: Number of Ways to Buy Pens and Pencils +sidebar_label: 2240-Number of Ways to Buy Pens and Pencils +tags: + - Enumerations + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +You are given an integer total indicating the amount of money you have. You are also given two integers cost1 and cost2 indicating the price of a pen and pencil respectively. You can spend part or all of your money to buy multiple quantities (or none) of each kind of writing utensil. + +Return the number of distinct ways you can buy some number of pens and pencils. + +### Examples + +**Example 1:** + +Input: total = 20, cost1 = 10, cost2 = 5 +Output: 9 +Explanation: The price of a pen is 10 and the price of a pencil is 5. +- If you buy 0 pens, you can buy 0, 1, 2, 3, or 4 pencils. +- If you buy 1 pen, you can buy 0, 1, or 2 pencils. +- If you buy 2 pens, you cannot buy any pencils. +The total number of ways to buy pens and pencils is 5 + 3 + 1 = 9. + +**Example 2:** + +Input: total = 5, cost1 = 10, cost2 = 10 +Output: 1 +Explanation: The price of both pens and pencils are 10, which cost more than total, so you cannot buy any writing utensils. Therefore, there is only 1 way: buy 0 pens and 0 pencils. + + +### Constraints + +- `1 <= total, cost1, cost2 <= 106` + +### Approach + +Iterate Over Possible Pen Purchases: Iterate over the number of pens that can be bought, starting from 0 up to the maximum number that can be afforded with the total money. +Calculate Remaining Money for Pencils: For each number of pens bought, calculate the remaining money that can be used to buy pencils. +Calculate Number of Pencils: Determine the number of pencils that can be bought with the remaining money. +Sum Up All Combinations: Sum up all the valid combinations of pens and pencils that can be bought. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include + +int waysToBuyPensPencils(int total, int cost1, int cost2) { + int count = 0; + for (int pens = 0; pens <= total / cost1; ++pens) { + int remaining_money = total - pens * cost1; + int pencils = remaining_money / cost2; + count += pencils + 1; + } + return count; +} + +int main() { + std::cout << waysToBuyPensPencils(20, 10, 5) << std::endl; // Output: 9 + std::cout << waysToBuyPensPencils(5, 10, 10) << std::endl; // Output: 1 + return 0; +} + + + +``` + +### Java Solution + +```java +public class Main { + public static int waysToBuyPensPencils(int total, int cost1, int cost2) { + int count = 0; + for (int pens = 0; pens <= total / cost1; ++pens) { + int remainingMoney = total - pens * cost1; + int pencils = remainingMoney / cost2; + count += pencils + 1; + } + return count; + } + + public static void main(String[] args) { + System.out.println(waysToBuyPensPencils(20, 10, 5)); // Output: 9 + System.out.println(waysToBuyPensPencils(5, 10, 10)); // Output: 1 + } +} + + +``` + +### Python Solution + +```python +def waysToBuyPensPencils(total, cost1, cost2): + count = 0 + for pens in range(total // cost1 + 1): + remaining_money = total - pens * cost1 + pencils = remaining_money // cost2 + count += pencils + 1 + return count + +# Example usage: +print(waysToBuyPensPencils(20, 10, 5)) # Output: 9 +print(waysToBuyPensPencils(5, 10, 10)) # Output: 1 + + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n)$ + +> **Reason**:Here, n represents the total amount of money, and the complexity indicates that the number of operations scales linearly with n. This simplification assumes a worst-case scenario where the number of iterations is directly proportional to the total amount of money. + +### Space Complexity: $O(1)$ + +> **Reason**: no extra auxiliary space. + + diff --git a/solutions/lc-solutions/2200-2299/2241-Design-an-ATM-Machine.md b/solutions/lc-solutions/2200-2299/2241-Design-an-ATM-Machine.md new file mode 100644 index 0000000..78eedb4 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2241-Design-an-ATM-Machine.md @@ -0,0 +1,268 @@ +--- +id: Design-an-ATM-Machine +title: Design an ATM Machine +sidebar_label: 2241-Design an ATM Machine +tags: + - Arrays + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +There is an ATM machine that stores banknotes of 5 denominations: 20, 50, 100, 200, and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money. + +When withdrawing, the machine prioritizes using banknotes of larger values. + +For example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes. +However, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100. Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote. +Implement the ATM class: + +ATM() Initializes the ATM object. +void deposit(int[] banknotesCount) Deposits new banknotes in the order $20, $50, $100, $200, and $500. +int[] withdraw(int amount) Returns an array of length 5 of the number of banknotes that will be handed to the user in the order $20, $50, $100, $200, and $500, and update the number of banknotes in the ATM after withdrawing. Returns [-1] if it is not possible (do not withdraw any banknotes in this case). + +### Examples + +**Example 1:** + +Input +["ATM", "deposit", "withdraw", "deposit", "withdraw", "withdraw"] +[[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]] +Output +[null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]] + +Explanation +ATM atm = new ATM(); +atm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes, + // and 1 $500 banknote. +atm.withdraw(600); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote + // and 1 $500 banknote. The banknotes left over in the + // machine are [0,0,0,2,0]. +atm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote. + // The banknotes in the machine are now [0,1,0,3,1]. +atm.withdraw(600); // Returns [-1]. The machine will try to use a $500 banknote + // and then be unable to complete the remaining $100, + // so the withdraw request will be rejected. + // Since the request is rejected, the number of banknotes + // in the machine is not modified. +atm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote + // and 1 $500 banknote. +### Constraints + +- `banknotesCount.length == 5` +- `0 <= banknotesCount[i] <= 109` +- `1 <= amount <= 109` +- `At most 5000 calls in total will be made to withdraw and deposit.` +- `At least one call will be made to each function withdraw and deposit.` +- `Sum of banknotesCount[i] in all deposits doesn't exceed 109` + +### Approach + +The ATM class manages banknotes of denominations $20, $50, $100, $200, and $500. It allows depositing and withdrawing money according to specified rules: + +Deposit Operation: Accepts an array of counts for each banknote denomination and updates the ATM's inventory. +Withdraw Operation: Attempts to withdraw a specified amount using the fewest possible banknotes, prioritizing higher denominations first. +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +#include +using namespace std; + +class ATM { +private: + deque banknotes; + +public: + ATM() : banknotes(5, 0) {} + + void deposit(vector& banknotesCount) { + for (int i = 0; i < 5; ++i) { + banknotes[i] += banknotesCount[i]; + } + } + + vector withdraw(int amount) { + vector withdrawn(5, 0); + vector banknotes_values = {500, 200, 100, 50, 20}; + + for (int i = 0; i < 5; ++i) { + if (amount <= 0) break; + int count = min(banknotes[i], amount / banknotes_values[i]); + withdrawn[i] = count; + amount -= count * banknotes_values[i]; + } + + if (amount == 0) { + for (int i = 0; i < 5; ++i) { + banknotes[i] -= withdrawn[i]; + } + return withdrawn; + } else { + return {-1}; + } + } +}; + +// Example usage: +int main() { + ATM atm; + atm.deposit({0, 0, 1, 2, 1}); + vector result1 = atm.withdraw(600); // Result: [0, 0, 1, 0, 1] + for (int num : result1) { + cout << num << " "; + } + cout << endl; + + atm.deposit({0, 1, 0, 1, 1}); + vector result2 = atm.withdraw(600); // Result: [-1] + for (int num : result2) { + cout << num << " "; + } + cout << endl; + + vector result3 = atm.withdraw(550); // Result: [0, 1, 0, 0, 1] + for (int num : result3) { + cout << num << " "; + } + cout << endl; + + return 0; +} + + + +``` + +### Java Solution + +```java +import java.util.ArrayDeque; +import java.util.Deque; + +public class ATM { + private Deque banknotes; + + public ATM() { + banknotes = new ArrayDeque<>(); + for (int i = 0; i < 5; i++) { + banknotes.offerLast(0); + } + } + + public void deposit(int[] banknotesCount) { + for (int i = 0; i < 5; i++) { + banknotesCount[i] += banknotes.pollFirst(); + banknotes.offerLast(banknotesCount[i]); + } + } + + public int[] withdraw(int amount) { + int[] withdrawn = new int[5]; + int[] banknotes_values = {500, 200, 100, 50, 20}; + + for (int i = 0; i < 5; i++) { + if (amount <= 0) break; + int count = Math.min(banknotes.peekFirst(), amount / banknotes_values[i]); + withdrawn[i] = count; + amount -= count * banknotes_values[i]; + } + + if (amount == 0) { + for (int i = 0; i < 5; i++) { + banknotes.offerFirst(banknotes.pollFirst() - withdrawn[i]); + } + return withdrawn; + } else { + return new int[] {-1}; + } + } + + public static void main(String[] args) { + ATM atm = new ATM(); + atm.deposit(new int[] {0, 0, 1, 2, 1}); + int[] result1 = atm.withdraw(600); // Output: [0, 0, 1, 0, 1] + for (int num : result1) { + System.out.print(num + " "); + } + System.out.println(); + + atm.deposit(new int[] {0, 1, 0, 1, 1}); + int[] result2 = atm.withdraw(600); // Output: [-1] + for (int num : result2) { + System.out.print(num + " "); + } + System.out.println(); + + int[] result3 = atm.withdraw(550); // Output: [0, 1, 0, 0, 1] + for (int num : result3) { + System.out.print(num + " "); + } + System.out.println(); + } +} + + +``` + +### Python Solution + +```python +from collections import deque + +class ATM: + def __init__(self): + self.banknotes = deque([0] * 5) # Initialize banknotes counts [20, 50, 100, 200, 500] + + def deposit(self, banknotesCount): + for i in range(5): + self.banknotes[i] += banknotesCount[i] + + def withdraw(self, amount): + withdrawn = [0] * 5 + banknotes_values = [500, 200, 100, 50, 20] + + for i, value in enumerate(banknotes_values): + if amount <= 0: + break + count = min(self.banknotes[i], amount // value) + withdrawn[i] = count + amount -= count * value + + if amount == 0: + for i in range(5): + self.banknotes[i] -= withdrawn[i] + return withdrawn + else: + return [-1] + +# Example usage: +atm = ATM() +atm.deposit([0, 0, 1, 2, 1]) +print(atm.withdraw(600)) # Output: [0, 0, 1, 0, 1] +atm.deposit([0, 1, 0, 1, 1]) +print(atm.withdraw(600)) # Output: [-1] +print(atm.withdraw(550)) # Output: [0, 1, 0, 0, 1] + + +``` + +### Complexity Analysis + +### Time Complexity: $O(1)$ + +> **Reason**:Both deposit and withdraw operations are $O(1)$, assuming a fixed number of denominations. + +### Space Complexity: $O(1)$ + +> **Reason**: for the fixed-size array or deque used to store banknote counts. + + diff --git a/solutions/lc-solutions/2200-2299/2242-Maximum-Score-of-a-Node-sequence.md b/solutions/lc-solutions/2200-2299/2242-Maximum-Score-of-a-Node-sequence.md new file mode 100644 index 0000000..9790dd9 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2242-Maximum-Score-of-a-Node-sequence.md @@ -0,0 +1,104 @@ +--- +id: Maximum-Score-of-a-Node-Sequence +title: Maximum-Score-of-a-Node-Sequence +sidebar_label: 2242-Maximum-Score-of-a-Node-Sequence +tags: + - Arrays + - graph + - sorting + - Enumeration +description: "This document provides solutions to this problem implemented in Java, and Python." +--- + +## Problem + +There is an undirected graph with n nodes, numbered from 0 to n - 1. + +You are given a 0-indexed integer array scores of length n where scores[i] denotes the score of node i. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi. + +A node sequence is valid if it meets the following conditions: + +There is an edge connecting every pair of adjacent nodes in the sequence. +No node appears more than once in the sequence. +The score of a node sequence is defined as the sum of the scores of the nodes in the sequence. + +Return the maximum score of a valid node sequence with a length of 4. If no such sequence exists, return -1. + +### Examples + +**Example 1:** + +Input: scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]] +Output: 24 +Explanation: The figure above shows the graph and the chosen node sequence [0,1,2,3]. +The score of the node sequence is 5 + 2 + 9 + 8 = 24. +It can be shown that no other node sequence has a score of more than 24. +Note that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24. +The sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3. +### Constraints + +- `banknotesCount.length == 5` +- `0 <= banknotesCount[i] <= 109` +- `1 <= amount <= 109` + +### Solution + +#### Code in Different Languages + +### Java Solution + +```java + public int maximumScore(int[] A, int[][] edges) { + int n = A.length; + PriorityQueue[] q = new PriorityQueue[n]; + for (int i = 0; i < n; i++) + q[i] = new PriorityQueue<>((a, b) -> A[a] - A[b]); + for (int[] e : edges) { + q[e[0]].offer(e[1]); + q[e[1]].offer(e[0]); + if (q[e[0]].size() > 3) q[e[0]].poll(); + if (q[e[1]].size() > 3) q[e[1]].poll(); + } + int res = -1; + for (int[] edge : edges) + for (int i : q[edge[0]]) + for (int j : q[edge[1]]) + if (i != j && i != edge[1] && j != edge[0]) + res = Math.max(res, A[i] + A[j] + A[edge[0]] + A[edge[1]]); + return res; + } + + +``` + +### Python Solution + +```python + def maximumScore(self, A, edges): + n = len(A) + G = [[] for i in range(n)] + for i,j in edges: + G[i].append([A[j], j]) + G[j].append([A[i], i]) + for i in range(n): + G[i] = nlargest(3, G[i]) + + res = -1 + for i,j in edges: + for vii, ii in G[i]: + for vjj, jj in G[j]: + if ii != jj and ii != j and j != ii: + res = max(res, vii + vjj + A[i] + A[j]) + return res + +``` + +### Complexity Analysis + +### Time Complexity: $O(1)$ + +> **Reason**:Both deposit and withdraw operations are $O(1)$, assuming a fixed number of denominations. + +### Space Complexity: $O(1)$ + +> **Reason**: for the fixed-size array or deque used to store banknote counts. diff --git a/solutions/lc-solutions/2200-2299/2243-Calculate-Digit-Sum-of-a-String.md b/solutions/lc-solutions/2200-2299/2243-Calculate-Digit-Sum-of-a-String.md new file mode 100644 index 0000000..528cadd --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2243-Calculate-Digit-Sum-of-a-String.md @@ -0,0 +1,192 @@ +--- +id: Calculate-Digit-Sum-of-a-String +title: Calculate Digit Sum of a String +sidebar_label: 2243-Calculate Digit Sum of a String +tags: + - Strings + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +You are given a string s consisting of digits and an integer k. + +A round can be completed if the length of s is greater than k. In one round, do the following: + +Divide s into consecutive groups of size k such that the first k characters are in the first group, the next k characters are in the second group, and so on. Note that the size of the last group can be smaller than k. +Replace each group of s with a string representing the sum of all its digits. For example, "346" is replaced with "13" because 3 + 4 + 6 = 13. +Merge consecutive groups together to form a new string. If the length of the string is greater than k, repeat from step 1. +Return s after all rounds have been completed. + + + +### Examples + +**Example 1:** + +Input: s = "11111222223", k = 3 +Output: "135" +Explanation: +- For the first round, we divide s into groups of size 3: "111", "112", "222", and "23". + ​​​​​Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5. + So, s becomes "3" + "4" + "6" + "5" = "3465" after the first round. +- For the second round, we divide s into "346" and "5". + Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5. + So, s becomes "13" + "5" = "135" after second round. +Now, s.length <= k, so we return "135" as the answer. + +**Example 2:** + +Input: s = "00000000", k = 3 +Output: "000" +Explanation: +We divide s into "000", "000", and "00". +Then we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. +s becomes "0" + "0" + "0" = "000", whose length is equal to k, so we return "000". + + + +### Constraints + +- 1 < = s.length < = 100 +- 2 < = k < = 100 +- s consists of digits only. + +### Approach + +1.Initial Setup: Start with the given string s. +2.Repeat Until Condition: Continue rounds of processing until the length of s is less than or equal to k. +3.Round Processing: + Divide s into consecutive groups of size k. + Calculate the digit sum for each group. + Construct a new string from these sums. +4.Update s: Replace s with the newly constructed string. +5.Termination: When the length of s is less than or equal to k, return s. + + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +using namespace std; + +class Solution { +public: + string digitSum(string s, int k) { + while (s.length() > k) { + string new_s; + for (int i = 0; i < s.length(); i += k) { + int sum = 0; + for (int j = i; j < min(i + k, (int)s.length()); j++) { + sum += s[j] - '0'; + } + new_s += to_string(sum); + } + s = new_s; + } + return s; + } +}; + +int main() { + Solution solution; + + string s1 = "11111222223"; + int k1 = 3; + cout << solution.digitSum(s1, k1) << endl; // Output: "135" + + string s2 = "00000000"; + int k2 = 3; + cout << solution.digitSum(s2, k2) << endl; // Output: "000" + + return 0; +} + + +``` + +### Java Solution + +```java +public class Solution { + public String digitSum(String s, int k) { + while (s.length() > k) { + StringBuilder sb = new StringBuilder(); + int i = 0; + while (i < s.length()) { + int sum = 0; + for (int j = i; j < Math.min(i + k, s.length()); j++) { + sum += s.charAt(j) - '0'; + } + sb.append(sum); + i += k; + } + s = sb.toString(); + } + return s; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + + String s1 = "11111222223"; + int k1 = 3; + System.out.println(solution.digitSum(s1, k1)); // Output: "135" + + String s2 = "00000000"; + int k2 = 3; + System.out.println(solution.digitSum(s2, k2)); // Output: "000" + } +} + +``` + +### Python Solution + +```python +class Solution: + def digitSum(self, s: str, k: int) -> str: + while len(s) > k: + new_s = [] + i = 0 + while i < len(s): + group_sum = sum(int(s[j]) for j in range(i, min(i + k, len(s)))) + new_s.append(str(group_sum)) + i += k + s = ''.join(new_s) + return s + +# Example usage +solution = Solution() +s1 = "11111222223" +k1 = 3 +print(solution.digitSum(s1, k1)) # Output: "135" + +s2 = "00000000" +k2 = 3 +print(solution.digitSum(s2, k2)) # Output: "000" + + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n)$ + +> **Reason**:Iterating through the string `s`. + + +### Space Complexity: $O(n)$ + +> **Reason**: depends on the storage of the input string `s`. + + diff --git a/solutions/lc-solutions/2200-2299/2244-Minimum-Rounds-to-Complete-All-Tasks.md b/solutions/lc-solutions/2200-2299/2244-Minimum-Rounds-to-Complete-All-Tasks.md new file mode 100644 index 0000000..8a9b523 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2244-Minimum-Rounds-to-Complete-All-Tasks.md @@ -0,0 +1,153 @@ +--- +id: Minimum-Rounds-to-Complete-All-Tasks +title: Minimum Rounds to Complete All Tasks +sidebar_label: 2244-Minimum Rounds to Complete All Tasks +tags: + - Arrays + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level. + +Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks. + +### Examples + +**Example 1:** + +Input: tasks = [2,2,3,3,2,4,4,4,4,4] +Output: 4 +Explanation: To complete all the tasks, a possible plan is: +- In the first round, you complete 3 tasks of difficulty level 2. +- In the second round, you complete 2 tasks of difficulty level 3. +- In the third round, you complete 3 tasks of difficulty level 4. +- In the fourth round, you complete 2 tasks of difficulty level 4. +It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4. + +**Example 2:** + +Input: tasks = [2,3,3] +Output: -1 +Explanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1. + + + +### Constraints + +- `1 <= tasks.length <= 105` +- `1 <= tasks[i] <= 109` + +### Approach + +Count the Frequency: Use a hash map or dictionary to count the occurrences of each task difficulty. +Check for Feasibility: For each difficulty level, check if the count is 1 (which is impossible to complete). +Calculate Rounds: Use integer division and modulo operations to determine the minimum rounds needed, prioritizing 3-task rounds over 2-task rounds. +Sum Rounds: Sum the rounds for all difficulty levels to get the total rounds required. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +#include +using namespace std; + +int minRounds(vector& tasks) { + unordered_map counts; + for (int task : tasks) counts[task]++; + int rounds = 0; + for (auto& pair : counts) { + int count = pair.second; + if (count == 1) return -1; + rounds += (count + 2) / 3; + } + return rounds; +} + +// Example usage: +int main() { + vector tasks = {2, 2, 3, 3, 2, 4, 4, 4, 4, 4}; + cout << minRounds(tasks) << endl; // Output: 4 + return 0; +} + +``` + +### Java Solution + +```java +import java.util.HashMap; +import java.util.Map; + +public class MinRounds { + public static int minRounds(int[] tasks) { + Map counts = new HashMap<>(); + for (int task : tasks) counts.put(task, counts.getOrDefault(task, 0) + 1); + int rounds = 0; + for (int count : counts.values()) { + if (count == 1) return -1; + rounds += (count + 2) / 3; + } + return rounds; + } + + // Example usage: + public static void main(String[] args) { + int[] tasks = {2, 2, 3, 3, 2, 4, 4, 4, 4, 4}; + System.out.println(minRounds(tasks)); // Output: 4 + } +} + + +``` + +### Python Solution + +```python +from collections import Counter + +def minRounds(tasks): + task_counts = Counter(tasks) + rounds = 0 + + for count in task_counts.values(): + if count == 1: + return -1 # Not possible to complete a single task on its own + elif count % 3 == 0: + rounds += count // 3 # If the count is divisible by 3, use 3-task rounds + else: + rounds += count // 3 + 1 # If not, use the remaining tasks to form an additional round + + return rounds + +# Example 1 +tasks1 = [2, 2, 3, 3, 2, 4, 4, 4, 4, 4] +print(minRounds(tasks1)) # Output: 4 + +# Example 2 +tasks2 = [2, 3, 3] +print(minRounds(tasks2)) # Output: -1 + + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n)$ + +> **Reason**:for counting frequencies and calculating rounds. + +### Space Complexity: $O(n)$ + +> **Reason**: We use a dictionary or hash map to store the frequency of each difficulty level. + diff --git a/solutions/lc-solutions/2200-2299/2245-Maximum-Trailing-Zeros-in-a-Cornered-Path.md b/solutions/lc-solutions/2200-2299/2245-Maximum-Trailing-Zeros-in-a-Cornered-Path.md new file mode 100644 index 0000000..5030ab3 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2245-Maximum-Trailing-Zeros-in-a-Cornered-Path.md @@ -0,0 +1,246 @@ +--- +id: Maximum-Trailing-Zeros-in-a-Cornered-Path +title: Maximum Trailing Zeros in a Cornered Path +sidebar_label: 2245-Maximum Trailing Zeros in a Cornered Path +tags: + - Arrays + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +You are given a 2D integer array grid of size m x n, where each cell contains a positive integer. + +A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell. + +The product of a path is defined as the product of all the values in the path. + +Return the maximum number of trailing zeros in the product of a cornered path found in grid. + +### Examples + +**Example 1:** + +Input: grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]] +Output: 3 +Explanation: The grid on the left shows a valid cornered path. +It has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros. +It can be shown that this is the maximum trailing zeros in the product of a cornered path. + +The grid in the middle is not a cornered path as it has more than one turn. +The grid on the right is not a cornered path as it requires a return to a previously visited cell. + +**Example 2:** + +Input: grid = [[4,3,2],[7,6,1],[8,8,8]] +Output: 0 +Explanation: The grid is shown in the figure above. +There are no cornered paths in the grid that result in a product with a trailing zero. + + +### Constraints + +- `m == grid.length` +- `n == grid[i].length` +- ` 1 <= m, n <= 105` +- `1 <= m * n <= 105` +- `1 <= grid[i][j] <= 1000` + +### Approach + +To find the maximum number of trailing zeros in the product of a cornered path in a grid, we can follow these steps: + +Precompute Factors: Calculate the number of 2's and 5's (factors that contribute to trailing zeros) in each cell. +Prefix Sum Arrays: Use prefix sums to quickly compute the number of 2's and 5's in any subarray of the grid. +Evaluate Paths: For each possible turn (L-shape), evaluate all possible paths and compute the product's trailing zeros using the precomputed prefix sums. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include + +using namespace std; + +int countFactors(int x, int p) { + int count = 0; + while (x % p == 0) { + x /= p; + count++; + } + return count; +} + +int maxTrailingZeros(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + vector> prefix_2(m + 1, vector(n + 1, 0)); + vector> prefix_5(m + 1, vector(n + 1, 0)); + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int num_2 = countFactors(grid[i][j], 2); + int num_5 = countFactors(grid[i][j], 5); + prefix_2[i + 1][j + 1] = prefix_2[i + 1][j] + prefix_2[i][j + 1] - prefix_2[i][j] + num_2; + prefix_5[i + 1][j + 1] = prefix_5[i + 1][j] + prefix_5[i][j + 1] - prefix_5[i][j] + num_5; + } + } + + int max_trailing_zeros = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + for (int k = i; k < m; k++) { + for (int l = j; l < n; l++) { + if (j < n - 1 && i < m - 1) { + int total_2 = prefix_2[i + 1][l + 1] - prefix_2[i + 1][j] + prefix_2[k + 1][l + 1] - prefix_2[i + 1][l + 1]; + int total_5 = prefix_5[i + 1][l + 1] - prefix_5[i + 1][j] + prefix_5[k + 1][l + 1] - prefix_5[i + 1][l + 1]; + max_trailing_zeros = max(max_trailing_zeros, min(total_2, total_5)); + } + + if (j < n - 1 && i < m - 1) { + int total_2 = prefix_2[k + 1][j + 1] - prefix_2[i][j + 1] + prefix_2[k + 1][l + 1] - prefix_2[k + 1][j + 1]; + int total_5 = prefix_5[k + 1][j + 1] - prefix_5[i][j + 1] + prefix_5[k + 1][l + 1] - prefix_5[k + 1][j + 1]; + max_trailing_zeros = max(max_trailing_zeros, min(total_2, total_5)); + } + } + } + } + } + + return max_trailing_zeros; +} + + +``` + +### Java Solution + +```java +import java.util.*; + +class Solution { + public int maxTrailingZeros(int[][] grid) { + int m = grid.length; + int n = grid[0].length; + + int[][] prefix_2 = new int[m + 1][n + 1]; + int[][] prefix_5 = new int[m + 1][n + 1]; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int num_2 = countFactors(grid[i][j], 2); + int num_5 = countFactors(grid[i][j], 5); + prefix_2[i + 1][j + 1] = prefix_2[i + 1][j] + prefix_2[i][j + 1] - prefix_2[i][j] + num_2; + prefix_5[i + 1][j + 1] = prefix_5[i + 1][j] + prefix_5[i][j + 1] - prefix_5[i][j] + num_5; + } + } + + int max_trailing_zeros = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + for (int k = i; k < m; k++) { + for (int l = j; l < n; l++) { + if (j < n - 1 && i < m - 1) { + int total_2 = prefix_2[i + 1][l + 1] - prefix_2[i + 1][j] + prefix_2[k + 1][l + 1] - prefix_2[i + 1][l + 1]; + int total_5 = prefix_5[i + 1][l + 1] - prefix_5[i + 1][j] + prefix_5[k + 1][l + 1] - prefix_5[i + 1][l + 1]; + max_trailing_zeros = Math.max(max_trailing_zeros, Math.min(total_2, total_5)); + } + + if (j < n - 1 && i < m - 1) { + int total_2 = prefix_2[k + 1][j + 1] - prefix_2[i][j + 1] + prefix_2[k + 1][l + 1] - prefix_2[k + 1][j + 1]; + int total_5 = prefix_5[k + 1][j + 1] - prefix_5[i][j + 1] + prefix_5[k + 1][l + 1] - prefix_5[k + 1][j + 1]; + max_trailing_zeros = Math.max(max_trailing_zeros, Math.min(total_2, total_5)); + } + } + } + } + } + + return max_trailing_zeros; + } + + private int countFactors(int x, int p) { + int count = 0; + while (x % p == 0) { + x /= p; + count++; + } + return count; + } +} + +``` + +### Python Solution + +```python +def maxTrailingZeros(grid): + m, n = len(grid), len(grid[0]) + + def count_factors(x, p): + count = 0 + while x % p == 0: + x //= p + count += 1 + return count + + # Initialize prefix sums + prefix_2 = [[0] * (n + 1) for _ in range(m + 1)] + prefix_5 = [[0] * (n + 1) for _ in range(m + 1)] + + for i in range(m): + for j in range(n): + num_2 = count_factors(grid[i][j], 2) + num_5 = count_factors(grid[i][j], 5) + prefix_2[i + 1][j + 1] = prefix_2[i + 1][j] + prefix_2[i][j + 1] - prefix_2[i][j] + num_2 + prefix_5[i + 1][j + 1] = prefix_5[i + 1][j] + prefix_5[i][j + 1] - prefix_5[i][j] + num_5 + + max_trailing_zeros = 0 + + # Evaluate all possible cornered paths + for i in range(m): + for j in range(n): + for k in range(i, m): + for l in range(j, n): + # Horizontal then vertical (right then down) + if j < n - 1 and i < m - 1: + total_2 = prefix_2[i + 1][l + 1] - prefix_2[i + 1][j] + prefix_2[k + 1][l + 1] - prefix_2[i + 1][l + 1] + total_5 = prefix_5[i + 1][l + 1] - prefix_5[i + 1][j] + prefix_5[k + 1][l + 1] - prefix_5[i + 1][l + 1] + max_trailing_zeros = max(max_trailing_zeros, min(total_2, total_5)) + + # Vertical then horizontal (down then right) + if j < n - 1 and i < m - 1: + total_2 = prefix_2[k + 1][j + 1] - prefix_2[i][j + 1] + prefix_2[k + 1][l + 1] - prefix_2[k + 1][j + 1] + total_5 = prefix_5[k + 1][j + 1] - prefix_5[i][j + 1] + prefix_5[k + 1][l + 1] - prefix_5[k + 1][j + 1] + max_trailing_zeros = max(max_trailing_zeros, min(total_2, total_5)) + + return max_trailing_zeros + +# Example usage +grid = [[23, 17, 15, 3, 20], [8, 1, 20, 27, 11], [9, 4, 6, 2, 21], [40, 9, 1, 10, 6], [22, 7, 4, 5, 3]] +print(maxTrailingZeros(grid)) # Output: 3 + + + +``` + +### Complexity Analysis + +### Time Complexity: $O((m*n)^2)$ + +> **Reason**:for factor counting ,prefix sum calculation and for evaluating paths. + +### Space Complexity: $O(m*n)$ + +> **Reason**: for using a prefix sum array + + diff --git a/solutions/lc-solutions/2200-2299/2248-Intersection-of-Multiple-Arrays.md b/solutions/lc-solutions/2200-2299/2248-Intersection-of-Multiple-Arrays.md new file mode 100644 index 0000000..bcf7f35 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2248-Intersection-of-Multiple-Arrays.md @@ -0,0 +1,174 @@ +--- +id: Intersection-of-Multiple-Arrays +title: Intersection of Multiple Arrays +sidebar_label: 2248-Intersection of Multiple Arrays +tags: + - Arrays + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums sorted in ascending order. + +### Examples + +**Example 1:** + +Input: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]] +Output: [3,4] +Explanation: +The only integers present in each of nums[0] = [3,1,2,4,5], nums[1] = [1,2,3,4], and nums[2] = [3,4,5,6] are 3 and 4, so we return [3,4]. + +**Example 2:** + +Input: nums = [[1,2,3],[4,5,6]] +Output: [] +Explanation: +There does not exist any integer present both in nums[0] and nums[1], so we return an empty list []. + + +### Constraints + +- `1 <= nums.length <= 1000` +- `1 <= sum(nums[i].length) <= 1000` +- `1 <= nums[i][j] <= 1000` +- `All the values of nums[i] are unique.` + +### Approach + +To solve the problem of finding integers that are present in each array of a given 2D integer array nums and returning them in ascending order, we can follow these steps: + +1.Use a hash set to keep track of the common elements. +2.Initialize the set with the elements of the first array. +3.For each subsequent array, retain only those elements in the set that are also in the current array. +4.Convert the resulting set to a list, sort it, and return. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +#include +#include +#include + +std::vector commonElements(std::vector>& nums) { + std::unordered_set common(nums[0].begin(), nums[0].end()); + + for (int i = 1; i < nums.size(); i++) { + std::unordered_set currentSet(nums[i].begin(), nums[i].end()); + for (auto it = common.begin(); it != common.end();) { + if (currentSet.find(*it) == currentSet.end()) { + it = common.erase(it); + } else { + ++it; + } + } + } + + std::vector result(common.begin(), common.end()); + std::sort(result.begin(), result.end()); + return result; +} + +int main() { + std::vector> nums1 = {{3, 1, 2, 4, 5}, {1, 2, 3, 4}, {3, 4, 5, 6}}; + std::vector> nums2 = {{1, 2, 3}, {4, 5, 6}}; + + auto result1 = commonElements(nums1); + auto result2 = commonElements(nums2); + + for (int num : result1) { + std::cout << num << " "; + } + std::cout << std::endl; + + for (int num : result2) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} + + + +``` + +### Java Solution + +```java +import java.util.*; + +public class CommonElements { + public static List commonElements(int[][] nums) { + Set common = new HashSet<>(); + for (int num : nums[0]) { + common.add(num); + } + + for (int i = 1; i < nums.length; i++) { + Set currentSet = new HashSet<>(); + for (int num : nums[i]) { + currentSet.add(num); + } + common.retainAll(currentSet); + } + + List result = new ArrayList<>(common); + Collections.sort(result); + return result; + } + + public static void main(String[] args) { + int[][] nums1 = {{3, 1, 2, 4, 5}, {1, 2, 3, 4}, {3, 4, 5, 6}}; + int[][] nums2 = {{1, 2, 3}, {4, 5, 6}}; + + System.out.println(commonElements(nums1)); // Output: [3, 4] + System.out.println(commonElements(nums2)); // Output: [] + } +} + + +``` + +### Python Solution + +```python +def common_elements(nums): + common = set(nums[0]) + + for arr in nums[1:]: + common.intersection_update(arr) + + result = sorted(common) + return result + +# Example usage +nums1 = [[3, 1, 2, 4, 5], [1, 2, 3, 4], [3, 4, 5, 6]] +nums2 = [[1, 2, 3], [4, 5, 6]] + +print(common_elements(nums1)) # Output: [3, 4] +print(common_elements(nums2)) # Output: [] + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n*m)$ + +> **Reason**:here n is the number of arrays and m is the average length of the arrays. Each intersection operation takes linear time relative to the number of elements. + +### Space Complexity: $O(m)$ + +> **Reason**: the space used by the set to store common elements + diff --git a/solutions/lc-solutions/2200-2299/2249-Count-Lattice-Points-Inside-a-Circle.md b/solutions/lc-solutions/2200-2299/2249-Count-Lattice-Points-Inside-a-Circle.md new file mode 100644 index 0000000..cf2d69f --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2249-Count-Lattice-Points-Inside-a-Circle.md @@ -0,0 +1,213 @@ +--- +id: Count-Lattice-Points-Inside-a-Circle +title: Count Lattice Points Inside a Circle +sidebar_label: 2249-Count Lattice Points Inside a Circle +tags: + - Arrays + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +Given a 2D integer array circles where circles[i] = [xi, yi, ri] represents the center (xi, yi) and radius ri of the ith circle drawn on a grid, return the number of lattice points that are present inside at least one circle. + +### Examples + +**Example 1:** + +Input: circles = [[2,2,1]] +Output: 5 +Explanation: +The figure above shows the given circle. +The lattice points present inside the circle are (1, 2), (2, 1), (2, 2), (2, 3), and (3, 2) and are shown in green. +Other points such as (1, 1) and (1, 3), which are shown in red, are not considered inside the circle. +Hence, the number of lattice points present inside at least one circle is 5. + +**Example 2:** + +Input: circles = [[2,2,2],[3,4,1]] +Output: 16 +Explanation: +The figure above shows the given circles. +There are exactly 16 lattice points which are present inside at least one circle. +Some of them are (0, 2), (2, 0), (2, 4), (3, 2), and (4, 4). + + + + +### Constraints + +- `1 <= circles.length <= 200` +- `circles[i].length == 3` +- `1 <= xi, yi <= 100` +- `1 <= ri <= min(xi, yi)` + +### Approach + +- For each circle, we iterate over a square grid that bounds the circle. +- For each point in this bounding grid, we check if it lies within the circle +- Use a set to keep track of unique lattice points that fall within any circle. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +#include + +using namespace std; + +struct Point { + int x, y; + bool operator==(const Point& other) const { + return x == other.x && y == other.y; + } +}; + +namespace std { + template <> + struct hash { + size_t operator()(const Point& point) const { + return hash()(point.x) ^ hash()(point.y); + } + }; +} + +bool isInsideCircle(int x, int y, int cx, int cy, int r) { + int dx = x - cx; + int dy = y - cy; + return dx * dx + dy * dy <= r * r; +} + +int countLatticePoints(vector>& circles) { + unordered_set points; + + for (const auto& circle : circles) { + int cx = circle[0], cy = circle[1], r = circle[2]; + + for (int x = cx - r; x <= cx + r; ++x) { + for (int y = cy - r; y <= cy + r; ++y) { + if (isInsideCircle(x, y, cx, cy, r)) { + points.insert({x, y}); + } + } + } + } + + return points.size(); +} + +int main() { + vector> circles = {{2, 2, 1}, {3, 4, 1}}; + cout << countLatticePoints(circles) << endl; // Output: 16 + return 0; +} + + +``` + +### Java Solution + +```java +import java.util.HashSet; +import java.util.Set; + +public class LatticePointsInCircles { + + static class Point { + int x, y; + + Point(int x, int y) { + this.x = x; + this.y = y; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + Point point = (Point) obj; + return x == point.x && y == point.y; + } + + @Override + public int hashCode() { + return 31 * x + y; + } + } + + private static boolean isInsideCircle(int x, int y, int cx, int cy, int r) { + int dx = x - cx; + int dy = y - cy; + return dx * dx + dy * dy <= r * r; + } + + public static int countLatticePoints(int[][] circles) { + Set points = new HashSet<>(); + + for (int[] circle : circles) { + int cx = circle[0], cy = circle[1], r = circle[2]; + + for (int x = cx - r; x <= cx + r; ++x) { + for (int y = cy - r; y <= cy + r; ++y) { + if (isInsideCircle(x, y, cx, cy, r)) { + points.add(new Point(x, y)); + } + } + } + } + + return points.size(); + } + + public static void main(String[] args) { + int[][] circles = {{2, 2, 1}, {3, 4, 1}}; + System.out.println(countLatticePoints(circles)); // Output: 16 + } +} + + +``` + +### Python Solution + +```python +def countLatticePoints(circles): + points = set() + + for x, y, r in circles: + for i in range(x - r, x + r + 1): + for j in range(y - r, y + r + 1): + if (i - x) ** 2 + (j - y) ** 2 <= r ** 2: + points.add((i, j)) + + return len(points) + +# Example usage +circles = [[2, 2, 1]] +print(countLatticePoints(circles)) # Output: 5 + +circles = [[2, 2, 2], [3, 4, 1]] +print(countLatticePoints(circles)) # Output: 16 + + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n*r*r)$ + +> **Reason**:where n is the number of circles and r is the average radius of the circles. + +### Space Complexity: $O(n*r*r)$ + +> **Reason**: where n is the number of circles and r is the average radius of the circles. This accounts for the storage of unique lattice points within all circles. + diff --git a/solutions/lc-solutions/2200-2299/2250-Count-Number-of-Rectangles-Containing-Each-Point.md b/solutions/lc-solutions/2200-2299/2250-Count-Number-of-Rectangles-Containing-Each-Point.md new file mode 100644 index 0000000..cad7990 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2250-Count-Number-of-Rectangles-Containing-Each-Point.md @@ -0,0 +1,215 @@ +--- +id: Count-Number-of-Rectangles-Containing-Each-Point +title: Count Number of Rectangles Containing Each Point +sidebar_label: 2250-Count Number of Rectangles Containing Each Point +tags: + - Arrays + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +You are given a 2D integer array `rectangles` where `rectangles[i] = [li, hi]` indicates that the `i`-th rectangle has a length of `li` and a height of `hi`. You are also given a 2D integer array `points` where `points[j] = [xj, yj]` is a point with coordinates `(xj, yj)`. + +The `i`-th rectangle has its bottom-left corner point at the coordinates (0, 0) and its top-right corner point at `(li, hi)`. + +Return an integer array `count` of length `points.length` where `count[j]` is the number of rectangles that contain the `j`-th point. + +The `i`-th rectangle contains the `j`-th point if `0 <= xj <= li` and `0 <= yj <= hi`. Note that points that lie on the edges of a rectangle are also considered to be contained by that rectangle. + +### Examples + +*Example 1:* + +```plaintext +Input: rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]] +Output: [2,1] +Explanation: +The first rectangle contains no points. +The second rectangle contains only the point (2, 1). +The third rectangle contains the points (2, 1) and (1, 4). +The number of rectangles that contain the point (2, 1) is 2. +The number of rectangles that contain the point (1, 4) is 1. +Therefore, we return [2, 1]. +``` + +*Example 2:* + +```plaintext +Input: rectangles = [[1,1],[2,2],[3,3]], points = [[1,3],[1,1]] +Output: [1,3] +Explanation: +The first rectangle contains only the point (1, 1). +The second rectangle contains only the point (1, 1). +The third rectangle contains the points (1, 3) and (1, 1). +The number of rectangles that contain the point (1, 3) is 1. +The number of rectangles that contain the point (1, 1) is 3. +Therefore, we return [1, 3]. +``` + +### Constraints + +- `1 <= rectangles.length, points.length <= 5 * 10^4` +- `rectangles[i].length == points[j].length == 2` +- `1 <= li, xj <= 10^9` +- `1 <= hi, yj <= 100` +- All the rectangles are unique. +- All the points are unique. + +### Approach + +1. **Sort Rectangles by Height:** First, sort the rectangles by their height in ascending order. +2. **Group Rectangles by Height:** Create a list of rectangles grouped by their height. +3. **Sort Points:** Sort the points by their y-coordinate in ascending order. +4. **Use Binary Search:** For each point, use binary search to quickly find the count of rectangles that can contain that point based on the x-coordinate. +5. **Iterate Efficiently:** As we iterate through each point, maintain a dynamic list of valid rectangle lengths that can contain the current point, and use this list to count rectangles. + +### Solution + +#### C++ Solution + +```cpp +#include +#include +using namespace std; + +vector countRectangles(vector>& rectangles, vector>& points) { + sort(rectangles.begin(), rectangles.end(), [](const vector& a, const vector& b) { + return a[1] < b[1]; + }); + + vector> points_with_index; + for (int i = 0; i < points.size(); ++i) { + points_with_index.emplace_back(points[i][0], points[i][1]); + } + + sort(points_with_index.begin(), points_with_index.end(), [](const pair& a, const pair& b) { + return a.second < b.second; + }); + + vector result(points.size()); + vector rectangle_lengths; + int rect_index = 0; + + for (const auto& point : points_with_index) { + int x = point.first; + int y = point.second; + + while (rect_index < rectangles.size() && rectangles[rect_index][1] <= y) { + rectangle_lengths.push_back(rectangles[rect_index][0]); + ++rect_index; + } + + auto it = lower_bound(rectangle_lengths.begin(), rectangle_lengths.end(), x); + result[&point - &points_with_index[0]] = rectangle_lengths.end() - it; + } + + return result; +} + +// Example usage: +int main() { + vector> rectangles = {{1, 2}, {2, 3}, {2, 5}}; + vector> points = {{2, 1}, {1, 4}}; + vector result = countRectangles(rectangles, points); + for (int count : result) { + cout << count << " "; + } + // Output: 2 1 + return 0; +} +``` + +#### Java Solution + +```java +import java.util.*; + +public class CountRectangles { + public static int[] countRectangles(int[][] rectangles, int[][] points) { + Arrays.sort(rectangles, Comparator.comparingInt(a -> a[1])); + + int[][] pointsWithIndex = new int[points.length][3]; + for (int i = 0; i < points.length; i++) { + pointsWithIndex[i][0] = points[i][0]; + pointsWithIndex[i][1] = points[i][1]; + pointsWithIndex[i][2] = i; + } + + Arrays.sort(pointsWithIndex, Comparator.comparingInt(a -> a[1])); + + int[] result = new int[points.length]; + List rectangleLengths = new ArrayList<>(); + int rectIndex = 0; + + for (int[] point : pointsWithIndex) { + int x = point[0]; + int y = point[1]; + int originalIndex = point[2]; + + while (rectIndex < rectangles.length && rectangles[rectIndex][1] <= y) { + rectangleLengths.add(rectangles[rectIndex][0]); + rectIndex++; + } + + int count = rectangleLengths.size() - Collections.binarySearch(rectangleLengths, x); + if (count < 0) { + count = ~count; + } + result[originalIndex] = rectangleLengths.size() - count; + } + + return result; + } + + // Example usage: + public static void main(String[] args) { + int[][] rectangles = {{1, 2}, {2, 3}, {2, 5}}; + int[][] points = {{2, 1}, {1, 4}}; + int[] result = countRectangles(rectangles, points); + System.out.println(Arrays.toString(result)); // Output: [2, 1] + } +} +``` + +#### Python Solution + +```python +from collections import defaultdict +from bisect import bisect_left + +def countRectangles(rectangles, points): + rectangles.sort(key=lambda x: x[1]) # Sort by height + points_with_index = sorted([(p[0], p[1], i) for i, p in enumerate(points)], key=lambda x: x[1]) + + result = [0] * len(points) + rectangle_lengths = [] + rect_index = 0 + + for x, y, original_index in points_with_index: + # Add all rectangles with height >= y to the list + while rect_index < len(rectangles) and rectangles[rect_index][1] <= y: + rectangle_lengths.append(rectangles[rect_index][0]) + rect_index += 1 + + # Count rectangles with length >= x + result[original_index] = len(rectangle_lengths) - bisect_left(rectangle_lengths, x) + + return result + +# Example usage: +rectangles = [[1, 2], [2, 3], [2, 5]] +points = [[2, 1], [1, 4]] +print(countRectangles(rectangles, points)) # Output: [2, 1] +``` + +### Complexity Analysis + +- **Time Complexity:** $O((n+m) \log n)$ + - *Reason:* where `n` is the number of rectangles and `m` is the number of points, due to sorting and binary search operations. + +- **Space Complexity:** $O(n+m)$ + - *Reason:* where `n` is the number of rectangles and `m` is the number of points, primarily due to storing rectangles, points with indices, and auxiliary data structures like lists or arrays. diff --git a/solutions/lc-solutions/2200-2299/2256-Minimum-Average-Difference.md b/solutions/lc-solutions/2200-2299/2256-Minimum-Average-Difference.md new file mode 100644 index 0000000..57738b6 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2256-Minimum-Average-Difference.md @@ -0,0 +1,177 @@ +--- +id: Minimum-Average-Difference +title: Minimum Average Difference +sidebar_label: 2256-Minimum Average Difference +tags: + - Arrays + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +You are given a 0-indexed integer array nums of length n. + +The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer. + +Return the index with the minimum average difference. If there are multiple such indices, return the smallest one. + +### Examples + +**Example 1:** + +Input: nums = [2,5,3,9,5,3] +Output: 3 +Explanation: +- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3. +- The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2. +- The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2. +- The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0. +- The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1. +- The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4. +The average difference of index 3 is the minimum average difference so return 3. + +**Example 2:** + +Input: nums = [0] +Output: 0 +Explanation: +The only index is 0 so return 0. +The average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0. + + +### Constraints + +-` 1 <= nums.length <= 105` +- `0 <= nums[i] <= 105` + +### Approach + +Prefix Sum Calculation: Compute prefix sums to efficiently calculate sums of subarrays. +Total Sum Calculation: Compute the total sum of the array to derive suffix sums. +Iteration and Calculation: Iterate through each index, compute left and right sums, calculate rounded averages, and track the index with the minimum average difference. +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +int minAvgDifferenceIndex(vector& nums) { + int n = nums.size(); + vector prefixSum(n); + prefixSum[0] = nums[0]; + for (int i = 1; i < n; i++) { + prefixSum[i] = prefixSum[i - 1] + nums[i]; + } + int totalSum = prefixSum[n - 1]; + int minDiff = INT_MAX, minIndex = 0; + for (int i = 0; i < n; i++) { + int leftSum = (i == 0) ? 0 : prefixSum[i - 1]; + int rightSum = totalSum - prefixSum[i]; + int leftAvg = leftSum / (i + 1); + int rightAvg = rightSum / (n - i - 1); + int avgDiff = abs(leftAvg - rightAvg); + if (avgDiff < minDiff || (avgDiff == minDiff && i < minIndex)) { + minDiff = avgDiff; + minIndex = i; + } + } + return minIndex; +} + + + +``` + +### Java Solution + +```java +public int minAvgDifferenceIndex(int[] nums) { + int n = nums.length; + int[] prefixSum = new int[n]; + prefixSum[0] = nums[0]; + for (int i = 1; i < n; i++) { + prefixSum[i] = prefixSum[i - 1] + nums[i]; + } + int totalSum = prefixSum[n - 1]; + int minDiff = Integer.MAX_VALUE, minIndex = 0; + for (int i = 0; i < n; i++) { + int leftSum = (i == 0) ? 0 : prefixSum[i - 1]; + int rightSum = totalSum - prefixSum[i]; + int leftAvg = leftSum / (i + 1); + int rightAvg = rightSum / (n - i - 1); + int avgDiff = Math.abs(leftAvg - rightAvg); + if (avgDiff < minDiff || (avgDiff == minDiff && i < minIndex)) { + minDiff = avgDiff; + minIndex = i; + } + } + return minIndex; +} + + +``` + +### Python Solution + +```python +def min_avg_difference_index(nums): + n = len(nums) + + # Compute prefix sums + prefix_sum = [0] * n + prefix_sum[0] = nums[0] + for i in range(1, n): + prefix_sum[i] = prefix_sum[i - 1] + nums[i] + + total_sum = prefix_sum[-1] # sum of all elements in nums + min_diff = float('inf') + min_index = 0 + + # Compute average differences + for i in range(n): + if i == 0: + left_sum = 0 + else: + left_sum = prefix_sum[i - 1] + right_sum = total_sum - prefix_sum[i] + + # Calculate average differences rounded down + left_avg = left_sum // (i + 1) + right_avg = right_sum // (n - i - 1) + + avg_diff = abs(left_avg - right_avg) + + # Update minimum average difference and index + if avg_diff < min_diff: + min_diff = avg_diff + min_index = i + elif avg_diff == min_diff: + min_index = min(min_index, i) + + return min_index + +# Example usage: +nums1 = [2, 5, 3, 9, 5, 3] +nums2 = [0] + +print(min_avg_difference_index(nums1)) # Output: 3 +print(min_avg_difference_index(nums2)) # Output: 0 + + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n)$ + +> **Reason**: because they involve linear scans to compute prefix sums, total sum, and iterate through each index + +### Space Complexity: $O(n)$ + +> **Reason**: due to the storage of prefix sums array, which is proportional to the input size n. + diff --git a/solutions/lc-solutions/2200-2299/2257-Count-Unguarded-Cells-in-the-Grid.md b/solutions/lc-solutions/2200-2299/2257-Count-Unguarded-Cells-in-the-Grid.md new file mode 100644 index 0000000..30f38b3 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2257-Count-Unguarded-Cells-in-the-Grid.md @@ -0,0 +1,446 @@ +--- +id: Count-Unguarded-Cells-in-the-Grid +title: Count Unguarded Cells in the Grid +sidebar_label: 2257-Count-Unguarded-Cells-in-the-Grid +tags: + - Arrays + - Brute Force + - Optimized approach + - LeetCode + - Python + - Java + - C++ + +description: "This is a solution to Count Unguarded Cells in the Grid problem on LeetCode." +sidebar_position: 58 +--- + +## Problem Statement +In this tutorial, we will solve the Count Unguarded Cells in the Grid problem . We will provide the implementation of the solution in Python, Java, and C++. + +### Problem Description + +You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj] represent the positions of the ith guard and jth wall respectively. + +A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it. + +Return the number of unoccupied cells that are not guarded. + +### Examples + +**Example 1:** +Input: m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]] +Output: 7 +Explanation: The guarded and unguarded cells are shown in red and green respectively in the above diagram. +There are a total of 7 unguarded cells, so we return 7. +**Example 2:** +Input: m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]] +Output: 4 +Explanation: The unguarded cells are shown in green in the above diagram. +There are a total of 4 unguarded cells, so we return 4. + +### Constraints +- `1 <= m, n <= 105` +- `2 <= m * n <= 105` +- `1 <= guards.length, walls.length <= 5 * 104` +- `2 <= guards.length + walls.length <= m * n` +- `guards[i].length == walls[j].length == 2` +- `0 <= rowi, rowj < m` +- `0 <= coli, colj < n` +- `All the positions in guards and walls are unique.` + +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +Brute Force Approach: Simulates each guard's visibility across the entire grid, marking cells until obstacles are encountered. It then counts unguarded cells. + +#### Codes in Different Languages + + + + + +```cpp +#include +#include + +using namespace std; + +int countUnguarded(int m, int n, vector>& guards, vector>& walls) { + vector> grid(m, vector(n, 0)); + + // Mark guards on the grid + for (auto& guard : guards) { + grid[guard[0]][guard[1]] = -1; + } + + // Mark walls on the grid + for (auto& wall : walls) { + grid[wall[0]][wall[1]] = 1; + } + + // Function to check if a cell is within bounds and unguarded + auto isUnguarded = [&](int x, int y) -> bool { + return x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0; + }; + + // Directions for scanning (north, east, south, west) + vector> directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + + // Simulate visibility for each guard + for (auto& guard : guards) { + int x = guard[0], y = guard[1]; + for (auto& dir : directions) { + int dx = dir.first, dy = dir.second; + int nx = x + dx, ny = y + dy; + while (isUnguarded(nx, ny)) { + grid[nx][ny] = 1; + nx += dx; + ny += dy; + } + } + } + + // Count unguarded cells + int unguardedCount = 0; + for (int x = 0; x < m; ++x) { + for (int y = 0; y < n; ++y) { + if (grid[x][y] == 0) { + ++unguardedCount; + } + } + } + + return unguardedCount; +} + +``` + + + + +```java +import java.util.*; + +class Solution { + public int countUnguarded(int m, int n, int[][] guards, int[][] walls) { + int[][] grid = new int[m][n]; + + // Mark guards on the grid + for (int[] guard : guards) { + grid[guard[0]][guard[1]] = -1; + } + + // Mark walls on the grid + for (int[] wall : walls) { + grid[wall[0]][wall[1]] = 1; + } + + // Function to check if a cell is within bounds and unguarded + boolean isUnguarded(int x, int y) { + return x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0; + } + + // Directions for scanning (north, east, south, west) + int[][] directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + + // Simulate visibility for each guard + for (int[] guard : guards) { + int x = guard[0], y = guard[1]; + for (int[] dir : directions) { + int dx = dir[0], dy = dir[1]; + int nx = x + dx, ny = y + dy; + while (isUnguarded(nx, ny)) { + grid[nx][ny] = 1; + nx += dx; + ny += dy; + } + } + } + + // Count unguarded cells + int unguardedCount = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 0) { + unguardedCount++; + } + } + } + + return unguardedCount; + } +} + + + + +``` + + + + + + +```python +def countUnguarded(m, n, guards, walls): + grid = [[0] * n for _ in range(m)] + + # Mark guards on the grid + for x, y in guards: + grid[x][y] = -1 + + # Mark walls on the grid + for x, y in walls: + grid[x][y] = 1 + + # Function to check if a cell is within bounds and unguarded + def isUnguarded(x, y): + return 0 <= x < m and 0 <= y < n and grid[x][y] == 0 + + # Directions for scanning (north, east, south, west) + directions = [(-1, 0), (0, 1), (1, 0), (0, -1)] + + # Simulate visibility for each guard + for x, y in guards: + for dx, dy in directions: + nx, ny = x + dx, y + dy + while isUnguarded(nx, ny): + grid[nx][ny] = 1 + nx += dx + ny += dy + + # Count unguarded cells + unguarded_count = sum(grid[x][y] == 0 for x in range(m) for y in range(n)) + + return unguarded_count + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O((g+w)*(n+m))$ +- Space Complexity: $O(n*m)$ +- where:g is the number of guards,w is the number of walls,n is the number of rows in the grid,m is the number of columns in the grid. +- The time complexity is $O((g+w)*(n+m))$ .This complexity arises because each guard potentially scans in all four cardinal directions, and each scan operation could traverse up to n or m cells. +- Additional space may be required for storing guards' and walls' positions, but this is typically bounded by O(g + w), where g is the number of guards and w is the number of walls. + + + + +### Approach 2: Optimized approach + +Optimized Approach: Uses sets to efficiently track guarded cells and avoid redundant calculations, resulting in a more optimized solution by leveraging direct visibility calculations. + +#### Code in Different Languages + + + + + +```cpp +#include +#include + +using namespace std; + +int countUnguarded(int m, int n, vector>& guards, vector>& walls) { + unordered_set guardSet; + unordered_set wallSet; + unordered_set guardedSet; + + // Populate guard set + for (auto& guard : guards) { + guardSet.insert(to_string(guard[0]) + "," + to_string(guard[1])); + } + + // Populate wall set + for (auto& wall : walls) { + wallSet.insert(to_string(wall[0]) + "," + to_string(wall[1])); + } + + // Directions for scanning (north, east, south, west) + vector> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + + // Function to check if a position is within bounds and not obstructed + auto isValid = [&](int x, int y) -> bool { + string key = to_string(x) + "," + to_string(y); + return x >= 0 && x < m && y >= 0 && y < n && !wallSet.count(key); + }; + + // Calculate guarded cells + for (auto& guard : guards) { + int x = guard[0], y = guard[1]; + for (auto& dir : directions) { + int dx = dir.first, dy = dir.second; + int nx = x + dx, ny = y + dy; + while (isValid(nx, ny)) { + guardedSet.insert(to_string(nx) + "," + to_string(ny)); + nx += dx; + ny += dy; + } + } + } + + // Total number of cells + int totalCells = m * n; + + // Count unguarded cells + int unguardedCount = totalCells - guardedSet.size() - wallSet.size(); + + return unguardedCount; +} + +``` + + + + +```java +import java.util.*; + +class Solution { + public int countUnguardedCells(int m, int n, int[][] guards, int[][] walls) { + Set guardSet = new HashSet<>(); + Set wallSet = new HashSet<>(); + Set guardedSet = new HashSet<>(); + + // Populate guard set + for (int[] guard : guards) { + guardSet.add(Arrays.toString(guard)); + } + + // Populate wall set + for (int[] wall : walls) { + wallSet.add(Arrays.toString(wall)); + } + + // Function to check if a position is within grid bounds + boolean isValid(int row, int col) { + return row >= 0 && row < m && col >= 0 && col < n; + } + + // Directions: north, east, south, west + int[][] directions = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} }; + + // Calculate visibility and mark guarded cells + for (int[] guard : guards) { + int r = guard[0]; + int c = guard[1]; + for (int[] dir : directions) { + int nr = r + dir[0]; + int nc = c + dir[1]; + while (isValid(nr, nc) && !wallSet.contains(Arrays.toString(new int[]{nr, nc}))) { + guardedSet.add(Arrays.toString(new int[]{nr, nc})); + nr += dir[0]; + nc += dir[1]; + } + } + } + + // Count unguarded cells + int unguardedCount = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + String pos = Arrays.toString(new int[]{i, j}); + if (!guardSet.contains(pos) && !guardedSet.contains(pos)) { + unguardedCount++; + } + } + } + + return unguardedCount; + } + + public static void main(String[] args) { + Solution sol = new Solution(); + + // Example usage: + int m1 = 4, n1 = 6; + int[][] guards1 = { {0, 0}, {1, 1}, {2, 3} }; + int[][] walls1 = { {0, 1}, {2, 2}, {1, 4} }; + System.out.println(sol.countUnguardedCells(m1, n1, guards1, walls1)); // Output: 7 + + int m2 = 3, n2 = 3; + int[][] guards2 = { {1, 1} }; + int[][] walls2 = { {0, 1}, {1, 0}, {2, 1}, {1, 2} }; + System.out.println(sol.countUnguardedCells(m2, n2, guards2, walls2)); // Output: 4 + } +} + +``` + + + + + + +```python +def countUnguarded(m, n, guards, walls): + guard_set = set(tuple(g) for g in guards) + wall_set = set(tuple(w) for w in walls) + guarded_set = set() + + directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # north, south, west, east + + # Function to check if a position is within bounds and not obstructed + def is_valid(x, y): + return 0 <= x < m and 0 <= y < n and (x, y) not in wall_set + + # Calculate guarded cells + for x, y in guards: + for dx, dy in directions: + nx, ny = x + dx, y + dy + while is_valid(nx, ny): + guarded_set.add((nx, ny)) + nx += dx + ny += dy + + # Total number of cells + total_cells = m * n + + # Count unguarded cells + unguarded_count = total_cells - len(guarded_set) - len(wall_set) + + return unguarded_count + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(g*(m+n))$ +- Space Complexity: $O(g+w+g*(m+n)+m*n)$ +- g: Number of guards ,m: Number of rows in the grid + ,n: Number of columns in the grid,w: Number of walls +- The time complexity is $O(n + m)$ because we iterate through both strings once. +- The space complexity is $O(n + m)$ because we store the result in a new string. +- This approach is efficient and straightforward. + + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/2200-2299/2259-Remove-Digit-From-Number-to-Maximize-Result.md b/solutions/lc-solutions/2200-2299/2259-Remove-Digit-From-Number-to-Maximize-Result.md new file mode 100644 index 0000000..ba97fea --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2259-Remove-Digit-From-Number-to-Maximize-Result.md @@ -0,0 +1,150 @@ +--- +id: Remove-Digit-From-Number-to-Maximize-Result +title: Remove Digit From Number to Maximize Result +sidebar_label: 2259-Remove Digit From Number to Maximize Result +tags: + - Strings + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +You are given a string number representing a positive integer and a character digit. + +Return the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized. The test cases are generated such that digit occurs at least once in number. + +### Examples + +**Example 1:** + +Input: number = "123", digit = "3" +Output: "12" +Explanation: There is only one '3' in "123". After removing '3', the result is "12". + +**Example 2:** + +Input: number = "1231", digit = "1" +Output: "231" +Explanation: We can remove the first '1' to get "231" or remove the second '1' to get "123". +Since 231 `>` 123, we return "231". + +**Example 2:** + +Input: number = "551", digit = "5" +Output: "51" +Explanation: We can remove either the first or second '5' from "551". +Both result in the string "51". + + + +### Constraints + +- `2 <= number.length <= 100` +- `number consists of digits from '1' to '9'.` +- `digit is a digit from '1' to '9'.` +- `digit occurs at least once in number.` + +### Approach + +To solve the problem of removing one occurrence of a specific digit from a string representation of a number to maximize its value, we can follow these steps: + +1.Iterate through the string and identify all positions where the specified digit occurs. +2.For each position, create a new string by removing the digit at that position. +3.Compare all resulting strings and return the one with the maximum value. +This approach ensures that we find the optimal string by evaluating all possible removals of the specified digit. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +using namespace std; + +string removeDigitToMaximize(string number, char digit) { + string maxNumber = ""; + for (int i = 0; i < number.length(); i++) { + if (number[i] == digit) { + string candidate = number.substr(0, i) + number.substr(i + 1); + if (candidate > maxNumber) { + maxNumber = candidate; + } + } + } + return maxNumber; +} + +int main() { + cout << removeDigitToMaximize("123", '3') << endl; // Output: "12" + cout << removeDigitToMaximize("1231", '1') << endl; // Output: "231" + cout << removeDigitToMaximize("551", '5') << endl; // Output: "51" + return 0; +} + + + +``` + +### Java Solution + +```java +public class RemoveDigit { + public static String removeDigitToMaximize(String number, char digit) { + String maxNumber = ""; + for (int i = 0; i < number.length(); i++) { + if (number.charAt(i) == digit) { + String candidate = number.substring(0, i) + number.substring(i + 1); + if (candidate.compareTo(maxNumber) > 0) { + maxNumber = candidate; + } + } + } + return maxNumber; + } + + public static void main(String[] args) { + System.out.println(removeDigitToMaximize("123", '3')); // Output: "12" + System.out.println(removeDigitToMaximize("1231", '1')); // Output: "231" + System.out.println(removeDigitToMaximize("551", '5')); // Output: "51" + } +} + + + +``` + +### Python Solution + +```python +def remove_digit_to_maximize(number, digit): + max_number = "" + for i in range(len(number)): + if number[i] == digit: + candidate = number[:i] + number[i+1:] + if candidate > max_number: + max_number = candidate + return max_number + +# Example usage +print(remove_digit_to_maximize("123", "3")) # Output: "12" +print(remove_digit_to_maximize("1231", "1")) # Output: "231" +print(remove_digit_to_maximize("551", "5")) # Output: "51" + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n*n)$ + +> **Reason**:here n is the length of the string. This is because for each digit occurrence, creating a new string involves copying n characters, and there can be up to n such occurrences. + +### Space Complexity: $O(m)$ + +> **Reason**: for storing the maximum string and the temporary candidate strings. diff --git a/solutions/lc-solutions/2200-2299/2260-minimum-consecutive-cards-to-pick-up.md b/solutions/lc-solutions/2200-2299/2260-minimum-consecutive-cards-to-pick-up.md new file mode 100644 index 0000000..f8c6b89 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2260-minimum-consecutive-cards-to-pick-up.md @@ -0,0 +1,223 @@ +--- +id: minimum-consecutive-cards-to-pick-up +title: Minimum Consecutive Cards to Pick Up +sidebar_label: 2260. Minimum Consecutive Cards to Pick Up +tags: +- Array +- Hash Table +- Sliding Window +description: "This is a solution to the 2260. Minimum Consecutive Cards to Pick Up problem on LeetCode." +--- + +## Problem Description +You are given an integer array cards where cards[i] represents the value of the ith card. A pair of cards are matching if the cards have the same value. + +Return the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards, return -1. + + + +### Examples + +**Example 1:** + +``` +Input: cards = [3,4,2,3,4,7] +Output: 4 +Explanation: We can pick up the cards [3,4,2,3] which contain a matching pair of cards with value 3. Note that picking up the cards [4,2,3,4] is also optimal. +``` + +**Example 2:** +``` +Input: cards = [1,0,5,3] +Output: -1 +Explanation: There is no way to pick up a set of consecutive cards that contain a pair of matching cards. +``` + +### Constraints + +- `1 <= cards.length <= 10^5` + +## Solution for 2260. Minimum Consecutive Cards to Pick Up Substring +### Approach +1. **Initialize Variables**: + - `ans` to store the minimum length of the subarray. Initially set to infinity (`INT_MAX` or `float('inf')`). + - `mp` to store the most recent index of each card value encountered. + +2. **Iterate Through the Cards**: + - For each card in the array `cards`, check if the card value is already in the map `mp`. + - If it is, calculate the length of the subarray from the previous occurrence to the current index. Update `ans` with the minimum value between the current `ans` and the calculated length. + - Update the map `mp` with the current index of the card. + +3. **Return the Result**: + - After iterating through the cards, check if `ans` is still infinity. If it is, return -1, indicating no such pair exists. + - Otherwise, return `ans`. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + class Solution { + function minimumCardPickup(cards) { + let ans = Infinity; + let mp = new Map(); + for (let i = 0; i < cards.length; i++) { + if (mp.has(cards[i])) { + let len = i - mp.get(cards[i]) + 1; + ans = Math.min(ans, len); + } + mp.set(cards[i], i); + } + return ans === Infinity ? -1 : ans; + } +} + + const input =[3,4,2,3,4,7] + + const output = minimumCardPickup(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(nlogn) $ + - Space Complexity: $ O(n) $ + + ## Code in Different Languages + + + + ```javascript + class Solution { + minimumCardPickup(cards) { + let ans = Infinity; + let mp = new Map(); + for (let i = 0; i < cards.length; i++) { + if (mp.has(cards[i])) { + let len = i - mp.get(cards[i]) + 1; + ans = Math.min(ans, len); + } + mp.set(cards[i], i); + } + return ans === Infinity ? -1 : ans; + } +} + + ``` + + + + + ```typescript + class Solution { + minimumCardPickup(cards: number[]): number { + let ans = Infinity; + let mp = new Map(); + for (let i = 0; i < cards.length; i++) { + if (mp.has(cards[i])) { + let len = i - mp.get(cards[i])! + 1; + ans = Math.min(ans, len); + } + mp.set(cards[i], i); + } + return ans === Infinity ? -1 : ans; + } +} + + ``` + + + + ```python + class Solution: + def minimumCardPickup(self, cards: List[int]) -> int: + ans = float('inf') + mp = {} + for i, card in enumerate(cards): + if card in mp: + len_ = i - mp[card] + 1 + ans = min(ans, len_) + mp[card] = i + + return -1 if ans == float('inf') else ans + + ``` + + + + + ```java + import java.util.HashMap; +import java.util.Map; + +class Solution { + public int minimumCardPickup(int[] cards) { + int ans = Integer.MAX_VALUE; + Map mp = new HashMap<>(); + for (int i = 0; i < cards.length; i++) { + if (mp.containsKey(cards[i])) { + int len = i - mp.get(cards[i]) + 1; + ans = Math.min(ans, len); + } + mp.put(cards[i], i); + } + + return ans == Integer.MAX_VALUE ? -1 : ans; + } +} + + + ``` + + + + + ```cpp + class Solution { +public: + int minimumCardPickup(vector& cards) { + int ans=INT_MAX; + mapmp; + for(int i=0;i + + +
+
+ +## References + +- **LeetCode Problem**: [Minimum Consecutive Cards to Pick Up](https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/description/) + + diff --git a/solutions/lc-solutions/2200-2299/2261-K-Divisible-Elements-Subarrays.md b/solutions/lc-solutions/2200-2299/2261-K-Divisible-Elements-Subarrays.md new file mode 100644 index 0000000..8e30ff3 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2261-K-Divisible-Elements-Subarrays.md @@ -0,0 +1,287 @@ +--- +id: K-Divisible-Elements-Subarrays +title: K Divisible Elements Subarrays +sidebar_label: 2261-K Divisible Elements Subarrays +tags: + - Arrays + - Brute Force + - Optimized approach + - LeetCode + - Python + - Java + - C++ + +description: "This is a solution to Count Unguarded Cells in the Grid problem on LeetCode." +sidebar_position: 62 +--- + +## Problem Statement +In this tutorial, we will solve the K Divisible Elements Subarrays problem . We will provide the implementation of the solution in Python, Java, and C++. + +### Problem Description + +Given an integer array nums and two integers k and p, return the number of distinct subarrays, which have at most k elements that are divisible by p. + +Two arrays nums1 and nums2 are said to be distinct if: + +They are of different lengths, or +There exists at least one index i where nums1[i] != nums2[i]. +A subarray is defined as a non-empty contiguous sequence of elements in an array. + + +### Examples + +**Example 1:** +Input: nums = [2,3,3,2,2], k = 2, p = 2 +Output: 11 +Explanation: +The elements at indices 0, 3, and 4 are divisible by p = 2. +The 11 distinct subarrays which have at most k = 2 elements divisible by 2 are: +[2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2]. +Note that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once. +The subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2. +**Example 2:** +Input: nums = [1,2,3,4], k = 4, p = 1 +Output: 10 +Explanation: +All element of nums are divisible by p = 1. +Also, every subarray of nums will have at most 4 elements that are divisible by 1. +Since all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10. +### Constraints +- `1 <= nums.length <= 200` +- `1 <= nums[i], p <= 200` +- `1 <= k <= nums.length` + +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +Brute Force Approach: Generate all possible subarrays and count those that satisfy the condition (at most k elements divisible by p). + +#### Codes in Different Languages + + + + + +```cpp +#include +#include + +using namespace std; + +int countDistinctSubarrays(vector& nums, int k, int p) { + unordered_set subarrays; + int n = nums.size(); + + for (int start = 0; start < n; ++start) { + int count = 0; + for (int end = start; end < n; ++end) { + if (nums[end] % p == 0) count++; + if (count > k) break; + string subarray; + for (int i = start; i <= end; ++i) { + subarray += to_string(nums[i]) + ","; + } + subarrays.insert(subarray); + } + } + return subarrays.size(); +} + + +``` + + + + +```java +import java.util.HashSet; + +public class Solution { + public int countDistinctSubarrays(int[] nums, int k, int p) { + HashSet subarrays = new HashSet<>(); + int n = nums.length; + + for (int start = 0; start < n; ++start) { + int count = 0; + for (int end = start; end < n; ++end) { + if (nums[end] % p == 0) count++; + if (count > k) break; + StringBuilder subarray = new StringBuilder(); + for (int i = start; i <= end; ++i) { + subarray.append(nums[i]).append(","); + } + subarrays.add(subarray.toString()); + } + } + return subarrays.size(); + } +} + + +``` + + + + + + +```python +def countDistinctSubarrays(nums, k, p): + subarrays = set() + n = len(nums) + + for start in range(n): + count = 0 + for end in range(start, n): + if nums[end] % p == 0: + count += 1 + if count > k: + break + subarray = ','.join(map(str, nums[start:end + 1])) + subarrays.add(subarray) + + return len(subarrays) + + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(n^3)$ +- where n is the length of the array due to nested loops. +- Space Complexity: $O(n^2)$ +- Additional space may be required for storing for storing subarrays in a set. + + + + +### Approach 2: Optimized approach + +Optimized Approach: Utilize a sliding window technique to efficiently count valid subarrays, avoiding redundant checks. + + +#### Code in Different Languages + + + + + +```cpp +#include +#include + +using namespace std; + +int countDistinctSubarrays(vector& nums, int k, int p) { + unordered_set subarrays; + int n = nums.size(); + + for (int start = 0; start < n; ++start) { + int count = 0; + for (int end = start; end < n; ++end) { + if (nums[end] % p == 0) count++; + if (count > k) break; + string subarray; + for (int i = start; i <= end; ++i) { + subarray += to_string(nums[i]) + ","; + } + subarrays.insert(subarray); + } + } + return subarrays.size(); +} + + +``` + + + + +```java +import java.util.HashSet; + +public class Solution { + public int countDistinctSubarrays(int[] nums, int k, int p) { + HashSet subarrays = new HashSet<>(); + int n = nums.length; + + for (int start = 0; start < n; ++start) { + int count = 0; + for (int end = start; end < n; ++end) { + if (nums[end] % p == 0) count++; + if (count > k) break; + StringBuilder subarray = new StringBuilder(); + for (int i = start; i <= end; ++i) { + subarray.append(nums[i]).append(","); + } + subarrays.add(subarray.toString()); + } + } + return subarrays.size(); + } +} + +``` + + + + + + +```python +def countDistinctSubarrays(nums, k, p): + subarrays = set() + n = len(nums) + + for start in range(n): + count = 0 + for end in range(start, n): + if nums[end] % p == 0: + count += 1 + if count > k: + break + subarray = ','.join(map(str, nums[start:end + 1])) + subarrays.add(subarray) + + return len(subarrays) + + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n^2)$ +- due to the sliding window mechanism. +- Space Complexity: $O(n^2)$ +- The space complexity is $O(n^2)$ in the worst case for storing subarrays in a set. +- This approach is efficient and straightforward. + + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/2200-2299/2262-Total-Appeal-of-a-String.md b/solutions/lc-solutions/2200-2299/2262-Total-Appeal-of-a-String.md new file mode 100644 index 0000000..9470ab8 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2262-Total-Appeal-of-a-String.md @@ -0,0 +1,173 @@ +--- +id: total-appeal-of-a-string +title: Total Appeal of a String +sidebar_label: 2262-Total-Appeal-of-a-String +tags: + - Strings + - Dynamic Programming + - C++ + - Java + - Python +description: "This document provides a solution to the Total Appeal of a String problem, where we need to calculate the total appeal of all substrings of a given string." +--- + +## Problem + +The appeal of a string is the number of distinct characters found in the string. For example, the appeal of "abbca" is 3 because it has 3 distinct characters: 'a', 'b', and 'c'. + +Given a string `s`, return the total appeal of all of its substrings. + +### Examples + +**Example 1:** + +Input: s = "abbca" +Output: 28 +Explanation: The following are the substrings of "abbca": + +- "a" has an appeal of 1. +- "b" has an appeal of 1. +- "b" has an appeal of 1. +- "c" has an appeal of 1. +- "a" has an appeal of 1. +- "ab" has an appeal of 2. +- "bb" has an appeal of 1. +- "bc" has an appeal of 2. +- "ca" has an appeal of 2. +- "abb" has an appeal of 2. +- "bbc" has an appeal of 2. +- "bca" has an appeal of 3. +- "abbc" has an appeal of 3. +- "bbca" has an appeal of 3. +- "abbca" has an appeal of 3. + The total appeal is 1 + 1 + 1 + 1 + 1 + 2 + 1 + 2 + 2 + 2 + 2 + 3 + 3 + 3 + 3 = 28. + +**Example 2:** + +Input: s = "code" +Output: 20 +Explanation: The following are the substrings of "code": + +- "c" has an appeal of 1. +- "o" has an appeal of 1. +- "d" has an appeal of 1. +- "e" has an appeal of 1. +- "co" has an appeal of 2. +- "od" has an appeal of 2. +- "de" has an appeal of 2. +- "cod" has an appeal of 3. +- "ode" has an appeal of 3. +- "code" has an appeal of 4. + The total appeal is 1 + 1 + 1 + 1 + 2 + 2 + 2 + 3 + 3 + 4 = 20. + +### Constraints + +- `1 <= s.length <= 10^5` +- `s` consists of lowercase English letters. + +### Approach + +To solve this problem, we need to calculate the total appeal of all substrings. The key idea is to use dynamic programming and track the last occurrence of each character. For each character in the string, we compute its contribution to the total appeal based on its position and previous occurrences. + +Detailed steps: + +1. Initialize an array `last_occurrence` to store the last occurrence index of each character. +2. Traverse the string and for each character, compute its contribution to the total appeal based on its last occurrence. +3. Update the last occurrence of the character to the current position. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +#include +#include + +using namespace std; + +long long appealSum(string s) { + vector last_occurrence(26, -1); + long long total_appeal = 0, current_appeal = 0; + + for (int i = 0; i < s.size(); ++i) { + current_appeal += i - last_occurrence[s[i] - 'a']; + total_appeal += current_appeal; + last_occurrence[s[i] - 'a'] = i; + } + + return total_appeal; +} + +int main() { + string s = "abbca"; + cout << appealSum(s) << endl; // Output: 28 +} +``` + +### Java Solution + +```java +import java.util.*; + +public class TotalAppealOfString { + public long appealSum(String s) { + int[] last_occurrence = new int[26]; + Arrays.fill(last_occurrence, -1); + long total_appeal = 0, current_appeal = 0; + + for (int i = 0; i < s.length(); ++i) { + current_appeal += i - last_occurrence[s.charAt(i) - 'a']; + total_appeal += current_appeal; + last_occurrence[s.charAt(i) - 'a'] = i; + } + + return total_appeal; + } + + public static void main(String[] args) { + TotalAppealOfString solution = new TotalAppealOfString(); + String s = "abbca"; + System.out.println(solution.appealSum(s)); // Output: 28 + } +} +``` + +### Python Solution + +```python +def appealSum(s: str) -> int: + last_occurrence = [-1] * 26 + total_appeal = 0 + current_appeal = 0 + + for i, char in enumerate(s): + current_appeal += i - last_occurrence[ord(char) - ord('a')] + total_appeal += current_appeal + last_occurrence[ord(char) - ord('a')] = i + + return total_appeal + +# Test +s = "abbca" +print(appealSum(s)) # Output: 28 +``` + +### Complexity Analysis + +**Time Complexity:** O(n) + +> Reason: We traverse the string once, and each operation inside the loop takes constant time. + +**Space Complexity:** O(1) + +> Reason: We use a fixed array of size 26 to store the last occurrences of each character. + +This solution calculates the total appeal of all substrings by efficiently tracking the last occurrence of each character and computing their contributions. The time complexity is linear, and the space complexity is constant, making it suitable for large input sizes. + +### References + +**LeetCode Problem:** Total Appeal of a String diff --git a/solutions/lc-solutions/2200-2299/2264-Largest-3-Same-Digit-Number-in-String.md b/solutions/lc-solutions/2200-2299/2264-Largest-3-Same-Digit-Number-in-String.md new file mode 100644 index 0000000..f7e9356 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2264-Largest-3-Same-Digit-Number-in-String.md @@ -0,0 +1,153 @@ +--- +id: Largest-3-Same-Digit-Number-in-String +title: Largest 3-Same-Digit Number in String +sidebar_label: 2264-Largest 3-Same-Digit Number in String +tags: + - Strings + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +You are given a string num representing a large integer. An integer is good if it meets the following conditions: + +It is a substring of num with length 3. +It consists of only one unique digit. +Return the maximum good integer as a string or an empty string "" if no such integer exists. + + + + +### Examples + +**Example 1:** + +Input: num = "6777133339" +Output: "777" +Explanation: There are two distinct good integers: "777" and "333". +"777" is the largest, so we return "777". + +**Example 2:** + +Input: num = "2300019" +Output: "000" +Explanation: "000" is the only good integer. + +**Example 3"** + +Input: num = "42352338" +Output: "" +Explanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers. + + + +### Constraints + +- `3 <= num.length <= 1000` +- `num only consists of digits.` + +### Approach + +Here is a simple and brief approach to solve the problem: + +- Initialize a variable to store the largest good integer: Start with an empty string or an appropriate initial value. +- Iterate through the string: Loop through the string from the beginning to len(num) - 3 to check all possible substrings of length 3. +- Check each substring: For each position in the string, extract the substring of length 3 and check if all three characters are the same. +- Update the largest good integer: If the current good integer (substring of length 3 with all same characters) is greater than the previously found largest good integer, update the stored value. +- Return the result: After iterating through the entire string, return the stored value as the result. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +using namespace std; + +string largestGoodInteger(string num) { + string result = ""; + for (int i = 0; i < num.length() - 2; ++i) { + if (num[i] == num[i + 1] && num[i] == num[i + 2]) { + string goodInteger = num.substr(i, 3); + if (goodInteger > result) { + result = goodInteger; + } + } + } + return result; +} + +int main() { + string num = "6777133339"; + cout << largestGoodInteger(num) << endl; // Output: "777" + return 0; +} + + + +``` + +### Java Solution + +```java +public class LargestGoodInteger { + public static String largestGoodInteger(String num) { + String result = ""; + for (int i = 0; i < num.length() - 2; ++i) { + if (num.charAt(i) == num.charAt(i + 1) && num.charAt(i) == num.charAt(i + 2)) { + String goodInteger = num.substring(i, 3); + if (goodInteger.compareTo(result) > 0) { + result = goodInteger; + } + } + } + return result; + } + + public static void main(String[] args) { + String num = "6777133339"; + System.out.println(largestGoodInteger(num)); // Output: "777" + } +} + +``` + +### Python Solution + +```python +def largestGoodInteger(num: str) -> str: + result = "" + for i in range(len(num) - 2): + if num[i] == num[i + 1] and num[i] == num[i + 2]: + good_integer = num[i:i + 3] + if good_integer > result: + result = good_integer + return result + +# Test cases +print(largestGoodInteger("6777133339")) # Output: "777" +print(largestGoodInteger("2300019")) # Output: "000" +print(largestGoodInteger("42352338")) # Output: "" + + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n)$ + +> **Reason**:loop through the string , for each iteration, we perform a constant amount of workβ€”checking if three characters are the same and comparing the current substring with the largest good integer found so far. + + +### Space Complexity: $O(1)$ + +> **Reason**: no additional data structure. + + diff --git a/solutions/lc-solutions/2200-2299/2265-Count-Nodes-Equal-to-Average-of-Subtree.md b/solutions/lc-solutions/2200-2299/2265-Count-Nodes-Equal-to-Average-of-Subtree.md new file mode 100644 index 0000000..6f3dcdb --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2265-Count-Nodes-Equal-to-Average-of-Subtree.md @@ -0,0 +1,315 @@ +--- +id: Count-Nodes-Equal-to-Average-of-Subtree +title: Count Nodes Equal to Average of Subtree +sidebar_label: 2265-Count Nodes Equal to Average of Subtree +tags: + - Arrays + - Brute Force + - Optimized approach + - LeetCode + - Python + - Java + - C++ + +description: "This is a solution to Count Nodes Equal to Average of Subtree problem on LeetCode." +sidebar_position: 66 +--- + +## Problem Statement +In this tutorial, we will solve the Count Nodes Equal to Average of Subtree problem . We will provide the implementation of the solution in Python, Java, and C++. + +### Problem Description + +Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree. + +Note: + +The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer. +A subtree of root is a tree consisting of root and all of its descendants. + +### Examples + +**Example 1:** +Input: root = [4,8,5,0,1,null,6] +Output: 5 +Explanation: +For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4. +For the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5. +For the node with value 0: The average of its subtree is 0 / 1 = 0. +For the node with value 1: The average of its subtree is 1 / 1 = 1. +For the node with value 6: The average of its subtree is 6 / 1 = 6. +**Example 2:** +Input: root = [1] +Output: 1 +Explanation: For the node with value 1: The average of its subtree is 1 / 1 = 1. + +### Constraints +- `The number of nodes in the tree is in the range [1, 1000].` +- `0 <= Node.val <= 1000` + +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +In the brute force approach, we can perform the following steps: + +- Traverse each node in the tree. +- For each node, calculate the sum and count of the nodes in its subtree. +- Compute the average value of the subtree. +- Check if the node’s value equals the computed average. + +#### Codes in Different Languages + + + + + +```cpp +#include +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +pair subtreeSumCount(TreeNode* root) { + if (!root) return {0, 0}; + auto left = subtreeSumCount(root->left); + auto right = subtreeSumCount(root->right); + int sum = root->val + left.first + right.first; + int count = 1 + left.second + right.second; + return {sum, count}; +} + +int bruteForceCount(TreeNode* root) { + if (!root) return 0; + auto [sum, count] = subtreeSumCount(root); + int average = sum / count; + int match = (root->val == average) ? 1 : 0; + return match + bruteForceCount(root->left) + bruteForceCount(root->right); +} + + +``` + + + + +```java +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +class Solution { + private int[] subtreeSumCount(TreeNode root) { + if (root == null) return new int[]{0, 0}; + int[] left = subtreeSumCount(root.left); + int[] right = subtreeSumCount(root.right); + int sum = root.val + left[0] + right[0]; + int count = 1 + left[1] + right[1]; + return new int[]{sum, count}; + } + + public int bruteForceCount(TreeNode root) { + if (root == null) return 0; + int[] res = subtreeSumCount(root); + int average = res[0] / res[1]; + int match = (root.val == average) ? 1 : 0; + return match + bruteForceCount(root.left) + bruteForceCount(root.right); + } +} + + +``` + + + + + + +```python +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +def subtree_sum_count(root): + if not root: + return (0, 0) + left = subtree_sum_count(root.left) + right = subtree_sum_count(root.right) + subtree_sum = root.val + left[0] + right[0] + subtree_count = 1 + left[1] + right[1] + return (subtree_sum, subtree_count) + +def brute_force_count(root): + if not root: + return 0 + subtree_sum, subtree_count = subtree_sum_count(root) + average = subtree_sum // subtree_count + match = 1 if root.val == average else 0 + return match + brute_force_count(root.left) + brute_force_count(root.right) + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(n^2)$ +- For each node, calculate the sum and count of the nodes in its subtree. +- Compute the average and check if it matches the node’s value. +- Traverse each node to repeat the above steps. +- Space Complexity: $O(h)$ +- where h is the height of the tree due to the recursion stack. + + + +### Approach 2: Optimized approach + +In the optimized approach, we can perform a single post-order traversal to calculate the sum and count of each subtree. During this traversal, we can also check if the current node's value is equal to the average of its subtree. + + +#### Code in Different Languages + + + + + +```cpp +#include +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +pair subtreeSumCount(TreeNode* root, int& count) { + if (!root) return {0, 0}; + auto left = subtreeSumCount(root->left, count); + auto right = subtreeSumCount(root->right, count); + int sum = root->val + left.first + right.first; + int nodes = 1 + left.second + right.second; + if (root->val == sum / nodes) count++; + return {sum, nodes}; +} + +int optimizedCount(TreeNode* root) { + int count = 0; + subtreeSumCount(root, count); + return count; +} + + + +``` + + + + +```java +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} + +class Solution { + private int[] subtreeSumCount(TreeNode root, int[] count) { + if (root == null) return new int[]{0, 0}; + int[] left = subtreeSumCount(root.left, count); + int[] right = subtreeSumCount(root.right, count); + int sum = root.val + left[0] + right[0]; + int nodes = 1 + left[1] + right[1]; + if (root.val == sum / nodes) count[0]++; + return new int[]{sum, nodes}; + } + + public int optimizedCount(TreeNode root) { + int[] count = new int[1]; + subtreeSumCount(root, count); + return count[0]; + } +} + +``` + + + + + + +```python +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +def subtree_sum_count(root, count): + if not root: + return (0, 0) + left = subtree_sum_count(root.left, count) + right = subtree_sum_count(root.right, count) + subtree_sum = root.val + left[0] + right[0] + subtree_count = 1 + left[1] + right[1] + if root.val == subtree_sum // subtree_count: + count[0] += 1 + return (subtree_sum, subtree_count) + +def optimized_count(root): + count = [0] + subtree_sum_count(root, count) + return count[0] + + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ +- Perform a single post-order traversal to compute the sum and count of each subtree. +- Check if the current node's value matches the average of its subtree during the traversal. +- Use the results of the traversal to count matching nodes. +- Space Complexity: $O(h)$ + +- where h is the height of the tree due to the recursion stack. + + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/2200-2299/2266- Count-Number-of-Texts.md b/solutions/lc-solutions/2200-2299/2266- Count-Number-of-Texts.md new file mode 100644 index 0000000..409143f --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2266- Count-Number-of-Texts.md @@ -0,0 +1,319 @@ +--- +id: Count-Number-of-Texts +title: Count Number of Texts +sidebar_label: 2266-Count Number of Texts +tags: + - Hash table + - Brute Force + - Optimized approach + - LeetCode + - Python + - Java + - C++ + +description: "This is a solution to Count Number of Texts problem on LeetCode." +sidebar_position: 67 +--- + +## Problem Statement +In this tutorial, we will solve the Count Number of Texts problem . We will provide the implementation of the solution in Python, Java, and C++. + +### Problem Description + +Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below. + + +In order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key. + +For example, to add the letter 's', Alice has to press '7' four times. Similarly, to add the letter 'k', Alice has to press '5' twice. +Note that the digits '0' and '1' do not map to any letters, so Alice does not use them. +However, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead. + +For example, when Alice sent the message "bob", Bob received the string "2266622". +Given a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent. + +Since the answer may be very large, return it modulo 109 + 7. + + +### Examples + +**Example 1:** +Input: pressedKeys = "22233" +Output: 8 +Explanation: +The possible text messages Alice could have sent are: +"aaadd", "abdd", "badd", "cdd", "aaae", "abe", "bae", and "ce". +Since there are 8 possible messages, we return 8. +**Example 2:** +Input: pressedKeys = "222222222222222222222222222222222222" +Output: 82876089 +Explanation: +There are 2082876103 possible text messages Alice could have sent. +Since we need to return the answer modulo 109 + 7, we return 2082876103 % (109 + 7) = 82876089. +### Constraints +- `1 <= pressedKeys.length <= 105` +- `pressedKeys only consists of digits from '2' - '9'.` +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +In the brute force approach, we will generate all possible combinations of letters for the given string of pressed keys and count the valid messages. However, due to the constraints, this approach is impractical for large inputs. + +#### Codes in Different Languages + + + + + +```cpp +#include +#include +#include +using namespace std; + +const int MOD = 1e9 + 7; +vector mappings = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + +void generateCombinations(const string &keys, int index, string current, vector &results) { + if (index == keys.size()) { + results.push_back(current); + return; + } + int digit = keys[index] - '2'; + for (char c : mappings[digit]) { + generateCombinations(keys, index + 1, current + c, results); + } +} + +int bruteForce(const string &pressedKeys) { + vector results; + generateCombinations(pressedKeys, 0, "", results); + return results.size(); +} + +int main() { + string pressedKeys = "22233"; + cout << bruteForce(pressedKeys) << endl; // Output: 8 + return 0; +} + + +``` + + + + +```java +import java.util.*; + +public class Main { + static final int MOD = 1_000_000_007; + static final String[] mappings = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + + public static void generateCombinations(String keys, int index, String current, List results) { + if (index == keys.length()) { + results.add(current); + return; + } + int digit = keys.charAt(index) - '2'; + for (char c : mappings[digit].toCharArray()) { + generateCombinations(keys, index + 1, current + c, results); + } + } + + public static int bruteForce(String pressedKeys) { + List results = new ArrayList<>(); + generateCombinations(pressedKeys, 0, "", results); + return results.size(); + } + + public static void main(String[] args) { + String pressedKeys = "22233"; + System.out.println(bruteForce(pressedKeys)); // Output: 8 + } +} + + +``` + + + + + + +```python +mappings = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] + +def generate_combinations(keys, index, current, results): + if index == len(keys): + results.append(current) + return + digit = int(keys[index]) - 2 + for c in mappings[digit]: + generate_combinations(keys, index + 1, current + c, results) + +def brute_force(pressed_keys): + results = [] + generate_combinations(pressed_keys, 0, "", results) + return len(results) + +pressed_keys = "22233" +print(brute_force(pressed_keys)) # Output: 8 + + + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(3^n)$ or $O(4^n)$ +- due to generating all possible letter combinations for each key press sequence. +- Space Complexity: $O(3^n)$ or $O(4^n)$ +- because we store all generated combinations. + + + + +### Approach 2: Optimized approach + +The optimized approach uses dynamic programming to efficiently calculate the number of valid messages. We maintain a DP array where dp[i] represents the number of possible messages for the substring pressedKeys[0:i+1]. + + +#### Code in Different Languages + + + + + +```cpp +#include +#include +#include +using namespace std; + +const int MOD = 1e9 + 7; + +int optimizedCount(const string &pressedKeys) { + int n = pressedKeys.size(); + vector dp(n + 1, 0); + dp[0] = 1; + + for (int i = 1; i <= n; ++i) { + dp[i] = dp[i - 1]; + if (i > 1 && pressedKeys[i - 1] == pressedKeys[i - 2]) + dp[i] = (dp[i] + dp[i - 2]) % MOD; + if (i > 2 && pressedKeys[i - 1] == pressedKeys[i - 2] && pressedKeys[i - 2] == pressedKeys[i - 3]) + dp[i] = (dp[i] + dp[i - 3]) % MOD; + if (i > 3 && pressedKeys[i - 1] == pressedKeys[i - 2] && pressedKeys[i - 2] == pressedKeys[i - 3] && pressedKeys[i - 3] == pressedKeys[i - 4] && (pressedKeys[i - 1] == '7' || pressedKeys[i - 1] == '9')) + dp[i] = (dp[i] + dp[i - 4]) % MOD; + } + return dp[n]; +} + +int main() { + string pressedKeys = "22233"; + cout << optimizedCount(pressedKeys) << endl; // Output: 8 + return 0; +} + + + +``` + + + + +```java +public class Main { + static final int MOD = 1_000_000_007; + + public static int optimizedCount(String pressedKeys) { + int n = pressedKeys.length(); + long[] dp = new long[n + 1]; + dp[0] = 1; + + for (int i = 1; i <= n; ++i) { + dp[i] = dp[i - 1]; + if (i > 1 && pressedKeys.charAt(i - 1) == pressedKeys.charAt(i - 2)) + dp[i] = (dp[i] + dp[i - 2]) % MOD; + if (i > 2 && pressedKeys.charAt(i - 1) == pressedKeys.charAt(i - 2) && pressedKeys.charAt(i - 2) == pressedKeys.charAt(i - 3)) + dp[i] = (dp[i] + dp[i - 3]) % MOD; + if (i > 3 && pressedKeys.charAt(i - 1) == pressedKeys.charAt(i - 2) && pressedKeys.charAt(i - 2) == pressedKeys.charAt(i - 3) && pressedKeys.charAt(i - 3) == pressedKeys.charAt(i - 4) && (pressedKeys.charAt(i - 1) == '7' || pressedKeys.charAt(i - 1) == '9')) + dp[i] = (dp[i] + dp[i - 4]) % MOD; + } + return (int) dp[n]; + } + + public static void main(String[] args) { + String pressedKeys = "22233"; + System.out.println(optimizedCount(pressedKeys)); // Output: 8 + } +} + + +``` + + + + + + +```python +MOD = 1_000_000_007 + +def optimized_count(pressed_keys): + n = len(pressed_keys) + dp = [0] * (n + 1) + dp[0] = 1 + + for i in range(1, n + 1): + dp[i] = dp[i - 1] + if i > 1 and pressed_keys[i - 1] == pressed_keys[i - 2]: + dp[i] = (dp[i] + dp[i - 2]) % MOD + if i > 2 and pressed_keys[i - 1] == pressed_keys[i - 2] == pressed_keys[i - 3]: + dp[i] = (dp[i] + dp[i - 3]) % MOD + if i > 3 and pressed_keys[i - 1] == pressed_keys[i - 2] == pressed_keys[i - 3] == pressed_keys[i - 4] and pressed_keys[i - 1] in '79': + dp[i] = (dp[i] + dp[i - 4]) % MOD + + return dp[n] + +pressed_keys = "22233" +print(optimized_count(pressed_keys)) # Output: 8 + + + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ +- as we use a dynamic programming approach with a single pass through the input string. +- Space Complexity: $O(n)$ +- for storing the DP array. + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/2200-2299/2267-check-if-there-is-a-valid-parentheses-string-path.md b/solutions/lc-solutions/2200-2299/2267-check-if-there-is-a-valid-parentheses-string-path.md new file mode 100644 index 0000000..ec8eb02 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2267-check-if-there-is-a-valid-parentheses-string-path.md @@ -0,0 +1,278 @@ +--- +id: check-if-there-is-a-valid-parenthesis-string-path +title: Check If there is a Valid Parenthesis String Path +sidebar_label: 2267-Check If there is a Valid Parenthesis String Path +tags: + - Valid Parentheses Path + - Brute Force + - Optimized + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the Valid Parentheses Path problem on LeetCode." +sidebar_position: 2 +--- + +In this tutorial, we will solve the Valid Parentheses Path problem using two different approaches: brute force and optimized. We will provide the implementation of the solution in C++, Java, and Python. + +## Problem Description + +Given an m x n matrix of parentheses grid, a valid parentheses string path in the grid is a path satisfying all of the following conditions: + +- The path starts from the upper left cell (0, 0). +- The path ends at the bottom-right cell (m - 1, n - 1). +- The path only ever moves down or right. +- The resulting parentheses string formed by the path is valid. + +Return true if there exists a valid parentheses string path in the grid. Otherwise, return false. + +### Examples + +**Example 1:** + +``` +Input: grid = [["(","(","("],[")","(",")"],["(","(",")"],["(","(",")"]] +Output: true +Explanation: The above diagram shows two possible paths that form valid parentheses strings. +The first path shown results in the valid parentheses string "()(())". +The second path shown results in the valid parentheses string "((()))". +Note that there may be other valid parentheses string paths. +``` + +**Example 2:** + +``` +Input: grid = [[")",")"],["(","("]] +Output: false +Explanation: The two possible paths form the parentheses strings "))(" and ")((". Since neither of them are valid parentheses strings, we return false. + +``` + +### Constraints + +- `m == grid.length` +- `n == grid[i].length` +- `1 <= m, n <= 100` +- `grid[i][j]` is either '(' or ')'. + +--- + +## Solution for Valid Parentheses Path Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized approach. The brute force approach directly explores all possible paths, while the optimized approach uses dynamic programming to efficiently check valid paths. + + + + +### Approach 1: Brute Force (Naive) + +The brute force approach recursively explores all possible paths from the top-left to the bottom-right cell, ensuring the parentheses string remains valid. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + bool isValidPath(vector>& grid, int i, int j, int balance) { + if (i >= grid.size() || j >= grid[0].size() || balance < 0) return false; + balance += (grid[i][j] == '(') ? 1 : -1; + if (i == grid.size() - 1 && j == grid[0].size() - 1) return balance == 0; + return isValidPath(grid, i + 1, j, balance) || isValidPath(grid, i, j + 1, balance); + } + + bool hasValidPath(vector>& grid) { + return isValidPath(grid, 0, 0, 0); + } +}; +``` + + + + + +```java +class Solution { + public boolean isValidPath(char[][] grid, int i, int j, int balance) { + if (i >= grid.length || j >= grid[0].length || balance < 0) return false; + balance += (grid[i][j] == '(') ? 1 : -1; + if (i == grid.length - 1 && j == grid[0].length - 1) return balance == 0; + return isValidPath(grid, i + 1, j, balance) || isValidPath(grid, i, j + 1, balance); + } + + public boolean hasValidPath(char[][] grid) { + return isValidPath(grid, 0, 0, 0); + } +} +``` + + + + + +```python +class Solution: + def isValidPath(self, grid: List[List[str]], i: int, j: int, balance: int) -> bool: + if i >= len(grid) or j >= len(grid[0]) or balance < 0: + return False + balance += 1 if grid[i][j] == '(' else -1 + if i == len(grid) - 1 and j == len(grid[0]) - 1: + return balance == 0 + return self.isValidPath(grid, i + 1, j, balance) or self.isValidPath(grid, i, j + 1, balance) + + def hasValidPath(self, grid: List[List[str]]) -> bool: + return self.isValidPath(grid, 0, 0, 0) +``` + + + + +#### Complexity Analysis + +- Time Complexity: Exponential due to exploring all paths. +- Space Complexity: Exponential due to recursive call stack. +- The brute force approach is inefficient for larger grids. + + + + +### Approach 2: Optimized Approach + +The optimized approach uses dynamic programming to track valid paths with different balances at each cell. This significantly reduces redundant calculations. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + bool hasValidPath(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + if (grid[0][0] == ')') return false; + vector>> dp(m, vector>(n, vector(m + n, false))); + dp[0][0][1] = true; + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k <= m + n; ++k) { + if (dp[i][j][k]) { + if (i + 1 < m) { + int new_balance = k + (grid[i + 1][j] == '(' ? 1 : -1); + if (new_balance >= 0 && new_balance <= m + n) { + dp[i + 1][j][new_balance] = true; + } + } + if (j + 1 < n) { + int new_balance = k + (grid[i][j + 1] == '(' ? 1 : -1); + if (new_balance >= 0 && new_balance <= m + n) { + dp[i][j + 1][new_balance] = true; + } + } + } + } + } + } + + return dp[m - 1][n - 1][0]; + } +}; +``` + + + + + +```java +class Solution { + public boolean hasValidPath(char[][] grid) { + int m = grid.length, n = grid[0].length; + if (grid[0][0] == ')') return false; + boolean[][][] dp = new boolean[m][n][m + n]; + dp[0][0][1] = true; + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k <= m + n; ++k) { + if (dp[i][j][k]) { + if (i + 1 < m) { + int new_balance = k + (grid[i + 1][j] == '(' ? 1 : -1); + if (new_balance >= 0 && new_balance <= m + n) { + dp[i + 1][j][new_balance] = true; + } + } + if (j + 1 < n) { + int new_balance = k + (grid[i][j + 1] == '(' ? 1 : -1); + if (new_balance >= 0 && new_balance <= m + n) { + dp[i][j + 1][new_balance] = true; + } + } + } + } + } + } + + return dp[m - 1][n - 1][0]; + } +} +``` + + + + + +```python +class Solution: + def hasValidPath(self, grid: List[List[str]]) -> bool: + m, n = len(grid), len(grid[0]) + if grid[0][0] == ')': + return False + dp = [[[False] * (m + n) for _ in range(n)] for _ in range(m)] + dp[0][0][1] = True + + for i in range(m): + for j in range(n): + for k in range(m + n): + if dp[i][j][k]: + if i + 1 < m: + new_balance = k + (1 if grid[i + 1][j] == '(' else -1) + if 0 <= new_balance <= m + n: + dp[i + 1][j][new_balance] = True + if j + 1 < n: + new_balance = k + (1 if grid[i][j + 1] == '(' else -1) + if 0 <= new_balance <= m + n: + dp[i][j + 1][new_balance] = True + + return dp[m - 1][n - 1][0] +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O( (m + n))$ +- Space Complexity: $O( (m + n))$ +- Where `m` is the number of rows and `n` is the number of columns. +- The optimized approach efficiently tracks valid paths using dynamic programming. + + + + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
\ No newline at end of file diff --git a/solutions/lc-solutions/2200-2299/2269-Find-the-K-Beauty-of-a-Number.md b/solutions/lc-solutions/2200-2299/2269-Find-the-K-Beauty-of-a-Number.md new file mode 100644 index 0000000..e7616d3 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2269-Find-the-K-Beauty-of-a-Number.md @@ -0,0 +1,154 @@ +--- +id: Find-the-K-Beauty-of-a-Number +title: Find the K-Beauty of a Number +sidebar_label: 2269-Find the K-Beauty of a Number + +tags: + - Strings + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +The k-beauty of an integer num is defined as the number of substrings of num when it is read as a string that meet the following conditions: + +It has a length of k. +It is a divisor of num. +Given integers num and k, return the k-beauty of num. + +### Examples + +**Example 1:** + +Input: num = 240, k = 2 +Output: 2 +Explanation: The following are the substrings of num of length k: +- "24" from "240": 24 is a divisor of 240. +- "40" from "240": 40 is a divisor of 240. +Therefore, the k-beauty is 2. + +**Example 2:** + +Input: num = 430043, k = 2 +Output: 2 +Explanation: The following are the substrings of num of length k: +- "43" from "430043": 43 is a divisor of 430043. +- "30" from "430043": 30 is not a divisor of 430043. +- "00" from "430043": 0 is not a divisor of 430043. +- "04" from "430043": 4 is not a divisor of 430043. +- "43" from "430043": 43 is a divisor of 430043. +Therefore, the k-beauty is 2. + + + +### Constraints + +- `1 <= num <= 109` +- `1 <= k <= num.length (taking num as a string)` + +### Approach + +- Convert the integer num to its string representation. +- Iterate through the string to extract all possible substrings of length k. +- For each substring, check if it is not zero and if it is a divisor of the original number num. +- If both conditions are met, increment the count. +- Return the count as the result. +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include + +int kBeauty(int num, int k) { + std::string numStr = std::to_string(num); + int length = numStr.length(); + int count = 0; + + for (int i = 0; i <= length - k; i++) { + std::string substring = numStr.substr(i, k); + int subNum = std::stoi(substring); + if (subNum != 0 && num % subNum == 0) { + count += 1; + } + } + return count; +} + +int main() { + std::cout << kBeauty(240, 2) << std::endl; // Output: 2 + std::cout << kBeauty(430043, 2) << std::endl; // Output: 2 + return 0; +} + + +``` + +### Java Solution + +```java +public class KBeauty { + public static int kBeauty(int num, int k) { + String numStr = String.valueOf(num); + int length = numStr.length(); + int count = 0; + + for (int i = 0; i <= length - k; i++) { + String substring = numStr.substring(i, i + k); + int subNum = Integer.parseInt(substring); + if (subNum != 0 && num % subNum == 0) { + count += 1; + } + } + return count; + } + + public static void main(String[] args) { + System.out.println(kBeauty(240, 2)); // Output: 2 + System.out.println(kBeauty(430043, 2)); // Output: 2 + } +} + + +``` + +### Python Solution + +```python +def k_beauty(num, k): + num_str = str(num) + length = len(num_str) + count = 0 + + for i in range(length - k + 1): + substring = num_str[i:i+k] + if int(substring) != 0 and num % int(substring) == 0: + count += 1 + + return count + +# Example usage +print(k_beauty(240, 2)) # Output: 2 +print(k_beauty(430043, 2)) # Output: 2 + + + +``` + +### Complexity Analysis + +### Time Complexity: $O(d*k)$ + +> **Reason**:It involes string conversion , loop iteration , substring operation , divisibility check. + +### Space Complexity: $O(d)$ + +> **Reason**: Storing the string representation of num. + + diff --git a/solutions/lc-solutions/2200-2299/2270-Number-of-Ways-to-Split-Array.md b/solutions/lc-solutions/2200-2299/2270-Number-of-Ways-to-Split-Array.md new file mode 100644 index 0000000..d65d658 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2270-Number-of-Ways-to-Split-Array.md @@ -0,0 +1,286 @@ +--- +id: Number-of-Ways-to-Split-Array +title: Number of Ways to Split Array +sidebar_label: 2270-Number of Ways to Split Array +tags: + - Arrays + - Brute Force + - Optimized approach + - LeetCode + - Python + - Java + - C++ + +description: "This is a solution to Number of Ways to Split Array problem on LeetCode." +sidebar_position: 71 +--- + +## Problem Statement +In this tutorial, we will solve the Number of Ways to Split Array problem . We will provide the implementation of the solution in Python, Java, and C++. + +### Problem Description + +You are given a 0-indexed integer array nums of length n. + +nums contains a valid split at index i if the following are true: + +The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements. +There is at least one element to the right of i. That is, 0 <= i < n - 1. +Return the number of valid splits in nums. + +### Examples + +**Example 1:** +Input: nums = [10,4,-8,7] +Output: 2 +Explanation: +There are three ways of splitting nums into two non-empty parts: +- Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 >= 3, i = 0 is a valid split. +- Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 >= -1, i = 1 is a valid split. +- Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 < 7, i = 2 is not a valid split. +Thus, the number of valid splits in nums is 2. +**Example 2:** +Input: nums = [2,3,1,0] +Output: 2 +Explanation: +There are two valid splits in nums: +- Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 >= 1, i = 1 is a valid split. +- Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 >= 0, i = 2 is a valid split. + +### Constraints +- `2 <= nums.length <= 105` +- `-105 <= nums[i] <= 105` +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +Brute Force Approach: In the brute force approach, we will iterate through all possible split points and check if the condition of a valid split is satisfied. +#### Codes in Different Languages + + + + + +```cpp +#include +#include +#include + +int validSplitsBruteForce(const std::vector& nums) { + int n = nums.size(); + int count = 0; + for (int i = 0; i < n - 1; ++i) { + int leftSum = std::accumulate(nums.begin(), nums.begin() + i + 1, 0); + int rightSum = std::accumulate(nums.begin() + i + 1, nums.end(), 0); + if (leftSum >= rightSum) { + count++; + } + } + return count; +} + +int main() { + std::vector nums = {10, 4, -8, 7}; + std::cout << "Number of valid splits: " << validSplitsBruteForce(nums) << std::endl; + return 0; +} + + +``` + + + + +```java +import java.util.*; + +public class Main { + public static int validSplitsBruteForce(int[] nums) { + int n = nums.length; + int count = 0; + for (int i = 0; i < n - 1; ++i) { + int leftSum = 0, rightSum = 0; + for (int j = 0; j <= i; ++j) { + leftSum += nums[j]; + } + for (int j = i + 1; j < n; ++j) { + rightSum += nums[j]; + } + if (leftSum >= rightSum) { + count++; + } + } + return count; + } + + public static void main(String[] args) { + int[] nums = {10, 4, -8, 7}; + System.out.println("Number of valid splits: " + validSplitsBruteForce(nums)); + } +} + + +``` + + + + + + +```python +def valid_splits_brute_force(nums): + n = len(nums) + count = 0 + for i in range(n - 1): + left_sum = sum(nums[:i + 1]) + right_sum = sum(nums[i + 1:]) + if left_sum >= right_sum: + count += 1 + return count + +nums = [10, 4, -8, 7] +print("Number of valid splits:", valid_splits_brute_force(nums)) + + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(n^2)$ +- because for each split point, we calculate the sum of the left and right parts independently, leading to nested iterations. +- Space Complexity: $O(1)$ +- as no extra space is used other than a few variables for counting and summing. + + + + +### Approach 2: Optimized approach + +Optimized Approach: In the optimized approach, we will use prefix sums to avoid recalculating the sum of elements multiple times. + +#### Code in Different Languages + + + + + +```cpp +#include +#include + +int validSplitsOptimized(const std::vector& nums) { + int n = nums.size(); + int totalSum = 0; + for (int num : nums) { + totalSum += num; + } + + int leftSum = 0, count = 0; + for (int i = 0; i < n - 1; ++i) { + leftSum += nums[i]; + if (leftSum >= totalSum - leftSum) { + count++; + } + } + return count; +} + +int main() { + std::vector nums = {10, 4, -8, 7}; + std::cout << "Number of valid splits: " << validSplitsOptimized(nums) << std::endl; + return 0; +} + + + +``` + + + + +```java +public class Main { + public static int validSplitsOptimized(int[] nums) { + int n = nums.length; + int totalSum = 0; + for (int num : nums) { + totalSum += num; + } + + int leftSum = 0, count = 0; + for (int i = 0; i < n - 1; ++i) { + leftSum += nums[i]; + if (leftSum >= totalSum - leftSum) { + count++; + } + } + return count; + } + + public static void main(String[] args) { + int[] nums = {10, 4, -8, 7}; + System.out.println("Number of valid splits: " + validSplitsOptimized(nums)); + } +} + + +``` + + + + + + +```python +def valid_splits_optimized(nums): + n = len(nums) + total_sum = sum(nums) + left_sum = 0 + count = 0 + for i in range(n - 1): + left_sum += nums[i] + if left_sum >= total_sum - left_sum: + count += 1 + return count + +nums = [10, 4, -8, 7] +print("Number of valid splits:", valid_splits_optimized(nums)) + + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ +- because we compute the total sum once and then iterate through the array once to update the left sum and check the condition. +- Space Complexity: $O(1)$ +- as only a few variables are used for summing and counting. +- This approach is efficient and straightforward. + + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/2200-2299/2271-Maximum-White-Tiles-Covered-by-a-Carpet.md b/solutions/lc-solutions/2200-2299/2271-Maximum-White-Tiles-Covered-by-a-Carpet.md new file mode 100644 index 0000000..be51552 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2271-Maximum-White-Tiles-Covered-by-a-Carpet.md @@ -0,0 +1,329 @@ +--- +id: Maximum-White-Tiles-Covered-by-a-Carpet +title: Maximum White Tiles Covered by a Carpet +sidebar_label: 2271-Maximum White Tiles Covered by a Carpet +tags: + - Arrays + - Brute Force + - Optimized approach + - LeetCode + - Python + - Java + - C++ + +description: "This is a solution to Maximum White Tiles Covered by a Carpet problem on LeetCode." +sidebar_position: 72 +--- + +## Problem Statement +In this tutorial, we will solve the Maximum White Tiles Covered by a Carpet problem . We will provide the implementation of the solution in Python, Java, and C++. + +### Problem Description + +You are given a 2D integer array tiles where tiles[i] = [li, ri] represents that every tile j in the range `li <= j <= ri` is colored white. + +You are also given an integer carpetLen, the length of a single carpet that can be placed anywhere. + +Return the maximum number of white tiles that can be covered by the carpet. + +### Examples + +**Example 1:** +Input: tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10 +Output: 9 +Explanation: Place the carpet starting on tile 10. +It covers 9 white tiles, so we return 9. +Note that there may be other places where the carpet covers 9 white tiles. +It can be shown that the carpet cannot cover more than 9 white tiles. +**Example 2:** +Input: tiles = [[10,11],[1,1]], carpetLen = 2 +Output: 2 +Explanation: Place the carpet starting on tile 10. +It covers 2 white tiles, so we return 2. +### Constraints +- `1 <= tiles.length <= 5 * 104` +- `tiles[i].length == 2` +- `1 <= li <= ri <= 109` +- `1 <= carpetLen <= 109` +- `The tiles are non-overlapping.` +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +Brute Force Approach: In the brute force approach, we try placing the carpet starting at every possible position and calculate the number of tiles it covers. This approach is inefficient, especially for large inputs, but it provides a straightforward way to understand the problem. + +#### Codes in Different Languages + + + + + +```cpp +#include +#include +#include + +int maxWhiteTilesBruteForce(std::vector>& tiles, int carpetLen) { + std::sort(tiles.begin(), tiles.end()); + int maxCovered = 0; + + for (const auto& tile : tiles) { + int start = tile[0]; + int end = start + carpetLen - 1; + int covered = 0; + + for (const auto& t : tiles) { + if (t[1] < start) continue; + if (t[0] > end) break; + covered += std::min(t[1], end) - std::max(t[0], start) + 1; + } + maxCovered = std::max(maxCovered, covered); + } + return maxCovered; +} + +int main() { + std::vector> tiles = {{1, 5}, {10, 11}, {12, 18}, {20, 25}, {30, 32}}; + int carpetLen = 10; + std::cout << "Maximum white tiles covered: " << maxWhiteTilesBruteForce(tiles, carpetLen) << std::endl; + return 0; +} + + +``` + + + + +```java +import java.util.*; + +public class Main { + public static int maxWhiteTilesBruteForce(int[][] tiles, int carpetLen) { + Arrays.sort(tiles, Comparator.comparingInt(a -> a[0])); + int maxCovered = 0; + + for (int[] tile : tiles) { + int start = tile[0]; + int end = start + carpetLen - 1; + int covered = 0; + + for (int[] t : tiles) { + if (t[1] < start) continue; + if (t[0] > end) break; + covered += Math.min(t[1], end) - Math.max(t[0], start) + 1; + } + maxCovered = Math.max(maxCovered, covered); + } + return maxCovered; + } + + public static void main(String[] args) { + int[][] tiles = {{1, 5}, {10, 11}, {12, 18}, {20, 25}, {30, 32}}; + int carpetLen = 10; + System.out.println("Maximum white tiles covered: " + maxWhiteTilesBruteForce(tiles, carpetLen)); + } +} + + + +``` + + + + + + +```python +def max_white_tiles_brute_force(tiles, carpet_len): + tiles.sort() + max_covered = 0 + + for start, _ in tiles: + end = start + carpet_len - 1 + covered = 0 + + for l, r in tiles: + if r < start: + continue + if l > end: + break + covered += min(r, end) - max(l, start) + 1 + + max_covered = max(max_covered, covered) + return max_covered + +tiles = [[1, 5], [10, 11], [12, 18], [20, 25], [30, 32]] +carpet_len = 10 +print("Maximum white tiles covered:", max_white_tiles_brute_force(tiles, carpet_len)) + + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(n^2)$ +- because we iterate through all possible start points and check each tile range for each starting point. +- Space Complexity: $O(1)$ +- as we only use a few extra variables for counting. + + + + +### Approach 2: Optimized approach + +Optimized Approach: The optimized approach uses a sliding window technique to find the maximum number of tiles covered by the carpet. This approach takes advantage of the sorted order of the tiles and moves the start of the carpet incrementally, updating the number of covered tiles using a two-pointer method. + +#### Code in Different Languages + + + + + +```cpp +#include +#include +#include + +int maxWhiteTilesOptimized(std::vector>& tiles, int carpetLen) { + std::sort(tiles.begin(), tiles.end()); + int n = tiles.size(); + int maxCovered = 0; + int currentCovered = 0; + int j = 0; + + for (int i = 0; i < n; ++i) { + while (j < n && tiles[j][1] < tiles[i][0] + carpetLen) { + currentCovered += tiles[j][1] - tiles[j][0] + 1; + ++j; + } + if (j < n) { + maxCovered = std::max(maxCovered, currentCovered + std::max(0, tiles[i][0] + carpetLen - tiles[j][0])); + } else { + maxCovered = std::max(maxCovered, currentCovered); + } + currentCovered -= tiles[i][1] - tiles[i][0] + 1; + } + + return maxCovered; +} + +int main() { + std::vector> tiles = {{1, 5}, {10, 11}, {12, 18}, {20, 25}, {30, 32}}; + int carpetLen = 10; + std::cout << "Maximum white tiles covered: " << maxWhiteTilesOptimized(tiles, carpetLen) << std::endl; + return 0; +} + + +``` + + + + +```java +import java.util.*; + +public class Main { + public static int maxWhiteTilesOptimized(int[][] tiles, int carpetLen) { + Arrays.sort(tiles, Comparator.comparingInt(a -> a[0])); + int n = tiles.length; + int maxCovered = 0; + int currentCovered = 0; + int j = 0; + + for (int i = 0; i < n; ++i) { + while (j < n && tiles[j][1] < tiles[i][0] + carpetLen) { + currentCovered += tiles[j][1] - tiles[j][0] + 1; + ++j; + } + if (j < n) { + maxCovered = Math.max(maxCovered, currentCovered + Math.max(0, tiles[i][0] + carpetLen - tiles[j][0])); + } else { + maxCovered = Math.max(maxCovered, currentCovered); + } + currentCovered -= tiles[i][1] - tiles[i][0] + 1; + } + + return maxCovered; + } + + public static void main(String[] args) { + int[][] tiles = {{1, 5}, {10, 11}, {12, 18}, {20, 25}, {30, 32}}; + int carpetLen = 10; + System.out.println("Maximum white tiles covered: " + maxWhiteTilesOptimized(tiles, carpetLen)); + } +} + + +``` + + + + + + +```python +def max_white_tiles_optimized(tiles, carpet_len): + tiles.sort() + max_covered = 0 + current_covered = 0 + j = 0 + + for i in range(len(tiles)): + while j < len(tiles) and tiles[j][1] < tiles[i][0] + carpet_len: + current_covered += tiles[j][1] - tiles[j][0] + 1 + j += 1 + + if j < len(tiles): + max_covered = max(max_covered, current_covered + max(0, tiles[i][0] + carpet_len - tiles[j][0])) + else: + max_covered = max(max_covered, current_covered) + + current_covered -= tiles[i][1] - tiles[i][0] + 1 + + return max_covered + +tiles = [[1, 5], [10, 11], [12, 18], [20, 25], [30, 32]] +carpet_len = 10 +print("Maximum white tiles covered:", max_white_tiles_optimized(tiles, carpet_len)) + + + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n*logn+n)$ +- because of sorting the tiles, followed by a linear scan with a sliding window. +- Space Complexity: $O(1)$ +- as we only use a few extra variables for counting. +- This approach is efficient and straightforward. + + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/2200-2299/2273-Find-Resultant-Array-After-Removing-Anagrams.md b/solutions/lc-solutions/2200-2299/2273-Find-Resultant-Array-After-Removing-Anagrams.md new file mode 100644 index 0000000..6c95cac --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2273-Find-Resultant-Array-After-Removing-Anagrams.md @@ -0,0 +1,192 @@ +--- +id: Find Resultant Array After Removing Anagrams +title: Find Resultant Array After Removing Anagrams +sidebar_label: 2273-Find Resultant Array After Removing Anagrams +tags: + - Strings + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +You are given a 0-indexed string array words, where words[i] consists of lowercase English letters. + +In one operation, select any index i such that `0 < i < words.length` and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index that satisfies the conditions. + +Return words after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result. + +An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, "dacb" is an anagram of "abdc". + + + +### Examples + +**Example 1:** + +Input: words = ["abba","baba","bbaa","cd","cd"] +Output: ["abba","cd"] +Explanation: +One of the ways we can obtain the resultant array is by using the following operations: +- Since words[2] = "bbaa" and words[1] = "baba" are anagrams, we choose index 2 and delete words[2]. + Now words = ["abba","baba","cd","cd"]. +- Since words[1] = "baba" and words[0] = "abba" are anagrams, we choose index 1 and delete words[1]. + Now words = ["abba","cd","cd"]. +- Since words[2] = "cd" and words[1] = "cd" are anagrams, we choose index 2 and delete words[2]. + Now words = ["abba","cd"]. +We can no longer perform any operations, so ["abba","cd"] is the final answer. + +**Example 2:** + +Input: words = ["a","b","c","d","e"] +Output: ["a","b","c","d","e"] +Explanation: +No two adjacent strings in words are anagrams of each other, so no operations are performed. + + + +### Constraints + +- `1 <= words.length <= 100` +-` 1 <= words[i].length <= 10` +- `words[i] consists of lowercase English letters.` + +### Approach + +A concise approach involves: + +- Iterating through the list. +- Using a helper function to check if two words are anagrams. +- Removing the word if it is an anagram of the previous word. +- Repeating the process until no more deletions can be made. +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +#include +#include + +bool isAnagram(const std::string &word1, const std::string &word2) { + std::string sorted1 = word1; + std::string sorted2 = word2; + std::sort(sorted1.begin(), sorted1.end()); + std::sort(sorted2.begin(), sorted2.end()); + return sorted1 == sorted2; +} + +std::vector removeAnagrams(std::vector words) { + int i = 1; + while (i < words.size()) { + if (isAnagram(words[i], words[i - 1])) { + words.erase(words.begin() + i); + } else { + i++; + } + } + return words; +} + +int main() { + std::vector words1 = {"abba", "baba", "bbaa", "cd", "cd"}; + std::vector words2 = {"a", "b", "c", "d", "e"}; + + auto result1 = removeAnagrams(words1); + auto result2 = removeAnagrams(words2); + + for (const auto &word : result1) { + std::cout << word << " "; + } + std::cout << std::endl; + + for (const auto &word : result2) { + std::cout << word << " "; + } + std::cout << std::endl; + + return 0; +} + + + +``` + +### Java Solution + +```java +import java.util.*; + +public class RemoveAnagrams { + public static List removeAnagrams(List words) { + int i = 1; + while (i < words.size()) { + if (isAnagram(words.get(i), words.get(i - 1))) { + words.remove(i); + } else { + i++; + } + } + return words; + } + + private static boolean isAnagram(String word1, String word2) { + char[] arr1 = word1.toCharArray(); + char[] arr2 = word2.toCharArray(); + Arrays.sort(arr1); + Arrays.sort(arr2); + return Arrays.equals(arr1, arr2); + } + + public static void main(String[] args) { + List words1 = new ArrayList<>(Arrays.asList("abba", "baba", "bbaa", "cd", "cd")); + List words2 = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e")); + + System.out.println(removeAnagrams(words1)); // Output: [abba, cd] + System.out.println(removeAnagrams(words2)); // Output: [a, b, c, d, e] + } +} + +``` + +### Python Solution + +```python +def removeAnagrams(words): + def is_anagram(word1, word2): + return sorted(word1) == sorted(word2) + + i = 1 + while i < len(words): + if is_anagram(words[i], words[i - 1]): + words.pop(i) + else: + i += 1 + return words + +# Example usage +words1 = ["abba", "baba", "bbaa", "cd", "cd"] +words2 = ["a", "b", "c", "d", "e"] + +print(removeAnagrams(words1)) # Output: ["abba", "cd"] +print(removeAnagrams(words2)) # Output: ["a", "b", "c", "d", "e"] + + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n*(l*logl))$ + +> **Reason**:for checking for anagramsand iterating through the list of words.Here,n is the number of words in the list, and l is the average length of the words. + +### Space Complexity: $O(n*l)$ + +> **Reason**: This accounts for storing the list of words and the temporary space used during sorting. + diff --git a/solutions/lc-solutions/2200-2299/2274-Maximum-Consecutive-Floors-Without-Special-Floors.md b/solutions/lc-solutions/2200-2299/2274-Maximum-Consecutive-Floors-Without-Special-Floors.md new file mode 100644 index 0000000..bd7dd61 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2274-Maximum-Consecutive-Floors-Without-Special-Floors.md @@ -0,0 +1,272 @@ +--- +id: Maximum-Consecutive-Floors-Without-Special-Floors +title: Maximum Consecutive Floors Without Special Floors +sidebar_label: 2274-Maximum Consecutive Floors Without Special Floors +tags: + - Arrays + - Sorting + - Brute Force + - Optimized approach + - LeetCode + - Python + - Java + - C++ + +description: "This is a solution to Maximum Consecutive Floors Without Special Floors problem on LeetCode." +sidebar_position: 75 +--- + +## Problem Statement +In this tutorial, we will solve the Maximum Consecutive Floors Without Special Floors problem . We will provide the implementation of the solution in Python, Java, and C++. + +### Problem Description +Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be special floors, used for relaxation only. + +You are given two integers bottom and top, which denote that Alice has rented all the floors from bottom to top (inclusive). You are also given the integer array special, where special[i] denotes a special floor that Alice has designated for relaxation. + +Return the maximum number of consecutive floors without a special floor. + +### Examples + +**Example 1:** +Input: bottom = 2, top = 9, special = [4,6] +Output: 3 +Explanation: The following are the ranges (inclusive) of consecutive floors without a special floor: +- (2, 3) with a total amount of 2 floors. +- (5, 5) with a total amount of 1 floor. +- (7, 9) with a total amount of 3 floors. +Therefore, we return the maximum number which is 3 floors. +**Example 2:** +Input: bottom = 6, top = 8, special = [7,6,8] +Output: 0 +Explanation: Every floor rented is a special floor, so we return 0. + +### Constraints +- `1 <= special.length <= 105` +- `1 <= bottom <= special[i] <= top <= 109` +- `All the values of special are unique.` +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +Brute Force Approach: Generate all possible ranges between bottom and top. +Check each range to see if it contains any special floors. +Track the length of the longest range that does not contain any special floors. +#### Codes in Different Languages + + + + + +```cpp +#include +#include + +int maxConsecutiveBruteForce(int bottom, int top, std::vector& special) { + int max_consecutive = 0; + for (int start = bottom; start <= top; ++start) { + for (int end = start; end <= top; ++end) { + bool is_special = false; + for (int floor = start; floor <= end; ++floor) { + if (std::find(special.begin(), special.end(), floor) != special.end()) { + is_special = true; + break; + } + } + if (!is_special) { + max_consecutive = std::max(max_consecutive, end - start + 1); + } + } + } + return max_consecutive; +} + + +``` + + + + +```java +import java.util.*; + +public class MaxConsecutiveBruteForce { + public int maxConsecutive(int bottom, int top, int[] special) { + int max_consecutive = 0; + for (int start = bottom; start <= top; ++start) { + for (int end = start; end <= top; ++end) { + boolean is_special = false; + for (int floor = start; floor <= end; ++floor) { + if (Arrays.binarySearch(special, floor) >= 0) { + is_special = true; + break; + } + } + if (!is_special) { + max_consecutive = Math.max(max_consecutive, end - start + 1); + } + } + } + return max_consecutive; + } +} + + +``` + + + + + + +```python +def max_consecutive_brute_force(bottom, top, special): + max_consecutive = 0 + for start in range(bottom, top + 1): + for end in range(start, top + 1): + is_special = False + for floor in range(start, end + 1): + if floor in special: + is_special = True + break + if not is_special: + max_consecutive = max(max_consecutive, end - start + 1) + return max_consecutive + + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(n*m)$ +- where n is (top-bottom) , m is len(special) , it generates all possible floor ranges and checks each floor within those ranges against the special floors, resulting in a very high computational cost. +- Space Complexity: $O(1)$ +- It uses a constant amount of extra space regardless of the input size, as it only keeps track of the maximum consecutive floors. + + + +### Approach 2: Optimized approach + +Optimized Approach: Sort the special floors. +Compute the gaps between consecutive special floors. +Consider the floors before the first special floor and after the last special floor. +Track the length of the longest gap. + +#### Code in Different Languages + + + + + +```cpp +#include +#include + +int maxConsecutiveOptimized(int bottom, int top, std::vector& special) { + std::sort(special.begin(), special.end()); + int max_consecutive = 0; + + // Consider the gap before the first special floor + max_consecutive = special[0] - bottom; + + // Consider the gaps between consecutive special floors + for (int i = 1; i < special.size(); ++i) { + max_consecutive = std::max(max_consecutive, special[i] - special[i - 1] - 1); + } + + // Consider the gap after the last special floor + max_consecutive = std::max(max_consecutive, top - special.back()); + + return max_consecutive; +} + + +``` + + + + +```java +import java.util.*; + +public class MaxConsecutiveOptimized { + public int maxConsecutive(int bottom, int top, int[] special) { + Arrays.sort(special); + int max_consecutive = 0; + + // Consider the gap before the first special floor + max_consecutive = special[0] - bottom; + + // Consider the gaps between consecutive special floors + for (int i = 1; i < special.length; ++i) { + max_consecutive = Math.max(max_consecutive, special[i] - special[i - 1] - 1); + } + + // Consider the gap after the last special floor + max_consecutive = Math.max(max_consecutive, top - special[special.length - 1]); + + return max_consecutive; + } +} + + +``` + + + + + + +```python +def max_consecutive_optimized(bottom, top, special): + special.sort() + max_consecutive = 0 + + # Consider the gap before the first special floor + max_consecutive = special[0] - bottom + + # Consider the gaps between consecutive special floors + for i in range(1, len(special)): + max_consecutive = max(max_consecutive, special[i] - special[i - 1] - 1) + + # Consider the gap after the last special floor + max_consecutive = max(max_consecutive, top - special[-1]) + + return max_consecutive + + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n*logn)$ +- Sorting the special floors takes O(n log n) time, and finding the gaps between them is O(n), leading to an efficient overall complexity. +- Space Complexity: $O(1)$ +- The extra space used is constant, as the sorting operation is in-place and only a few additional variables are used to track the maximum gap. + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/2200-2299/2275-Largest-Combination-With-Bitwise-AND-Greater-Than-Zero.md b/solutions/lc-solutions/2200-2299/2275-Largest-Combination-With-Bitwise-AND-Greater-Than-Zero.md new file mode 100644 index 0000000..200e15d --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2275-Largest-Combination-With-Bitwise-AND-Greater-Than-Zero.md @@ -0,0 +1,312 @@ +--- +id: Largest-Combination-With-Bitwise-AND-Greater-Than-Zero +title: Largest Combination With Bitwise AND Greater Than Zero +sidebar_label: 2275-Largest Combination With Bitwise AND Greater Than Zero + - Arrays + - Brute Force + - Optimized approach + - LeetCode + - Python + - Java + - C++ + +description: "This is a solution to Largest Combination With Bitwise AND Greater Than Zero problem on LeetCode." +sidebar_position: 76 +--- + +## Problem Statement +In this tutorial, we will solve the Largest Combination With Bitwise AND Greater Than Zero problem . We will provide the implementation of the solution in Python, Java, and C++. + +### Problem Description + +The bitwise AND of an array nums is the bitwise AND of all integers in nums. + +For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1. +Also, for nums = [7], the bitwise AND is 7. +You are given an array of positive integers candidates. Evaluate the bitwise AND of every combination of numbers of candidates. Each number in candidates may only be used once in each combination. + +Return the size of the largest combination of candidates with a bitwise AND greater than 0. + + +### Examples + +**Example 1:** +Input: candidates = [16,17,71,62,12,24,14] +Output: 4 +Explanation: The combination [16,17,62,24] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0. +The size of the combination is 4. +It can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0. +Note that more than one combination may have the largest size. +For example, the combination [62,12,24,14] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0. +**Example 2:** +Input: candidates = [8,8] +Output: 2 +Explanation: The largest combination [8,8] has a bitwise AND of 8 & 8 = 8 > 0. +The size of the combination is 2, so we return 2. + +### Constraints +- `1 <= candidates.length <= 105` +- `1 <= candidates[i] <= 107` +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +Brute Force Approach: The brute force approach would involve evaluating the bitwise AND for every possible combination of the given candidates. However, given the constraints, this approach is impractical due to its high computational complexity. +#### Codes in Different Languages + + + + + +```cpp +#include +#include + +int largestCombinationBruteForce(std::vector& candidates) { + int n = candidates.size(); + int max_size = 0; + + // Iterate over all possible combinations of candidates + for (int mask = 1; mask < (1 << n); ++mask) { + int bitwise_and = -1; // Initialize with all bits set + int count = 0; + + for (int i = 0; i < n; ++i) { + if (mask & (1 << i)) { + if (bitwise_and == -1) { + bitwise_and = candidates[i]; + } else { + bitwise_and &= candidates[i]; + } + ++count; + } + } + + if (bitwise_and > 0) { + max_size = std::max(max_size, count); + } + } + + return max_size; +} + + + +``` + + + + +```java +import java.util.*; + +public class BruteForceSolution { + public int largestCombinationBruteForce(int[] candidates) { + int n = candidates.length; + int max_size = 0; + + // Iterate over all possible combinations of candidates + for (int mask = 1; mask < (1 << n); ++mask) { + int bitwiseAnd = -1; // Initialize with all bits set + int count = 0; + + for (int i = 0; i < n; ++i) { + if ((mask & (1 << i)) != 0) { + if (bitwiseAnd == -1) { + bitwiseAnd = candidates[i]; + } else { + bitwiseAnd &= candidates[i]; + } + ++count; + } + } + + if (bitwiseAnd > 0) { + max_size = Math.max(max_size, count); + } + } + + return max_size; + } +} + + +``` + + + + + + +```python +import java.util.*; + +public class BruteForceSolution { + public int largestCombinationBruteForce(int[] candidates) { + int n = candidates.length; + int max_size = 0; + + // Iterate over all possible combinations of candidates + for (int mask = 1; mask < (1 << n); ++mask) { + int bitwiseAnd = -1; // Initialize with all bits set + int count = 0; + + for (int i = 0; i < n; ++i) { + if ((mask & (1 << i)) != 0) { + if (bitwiseAnd == -1) { + bitwiseAnd = candidates[i]; + } else { + bitwiseAnd &= candidates[i]; + } + ++count; + } + } + + if (bitwiseAnd > 0) { + max_size = Math.max(max_size, count); + } + } + + return max_size; + } +} + + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(2^n*n)$ +- Evaluates all possible subsets (2^n) and performs bitwise AND operations on each subset. +- Space Complexity: $O(1)$ +- Uses a constant amount of extra space. + + + + + +### Approach 2: Optimized approach + +Optimized Approach: We can use bitwise manipulation to efficiently determine the largest combination of candidates with a bitwise AND greater than 0. The key idea is to examine each bit position independently and count how many numbers have that bit set. The maximum number of such numbers for any bit position gives the size of the largest combination with a bitwise AND greater than 0. + +#### Code in Different Languages + + + + + +```cpp +#include +#include + +int largestCombinationOptimized(const std::vector& candidates) { + int max_count = 0; + + // Iterate over each bit position + for (int bit = 0; bit < 31; ++bit) { + int count = 0; + int bit_mask = 1 << bit; + + for (int num : candidates) { + if (num & bit_mask) { + ++count; + } + } + + max_count = std::max(max_count, count); + } + + return max_count; +} + + +``` + + + + +```java +import java.util.*; + +public class OptimizedSolution { + public int largestCombinationOptimized(int[] candidates) { + int maxCount = 0; + + // Iterate over each bit position + for (int bit = 0; bit < 31; ++bit) { + int count = 0; + int bitMask = 1 << bit; + + for (int num : candidates) { + if ((num & bitMask) != 0) { + ++count; + } + } + + maxCount = Math.max(maxCount, count); + } + + return maxCount; + } +} + + +``` + + + + + + +```python +def largest_combination_optimized(candidates): + max_count = 0 + + # Iterate over each bit position + for bit in range(31): + bit_mask = 1 << bit + count = sum(1 for num in candidates if num & bit_mask) + + max_count = max(max_count, count) + + return max_count + + + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ +- Iterates over each of the 31 possible bit positions and counts how many candidates have that bit set. +- Space Complexity: $O(1)$ +- Uses only a few extra variables for counting and tracking the maximum size. +- This approach is efficient and straightforward. + + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/2200-2299/2278-Two-Furthest-Houses-With-Different-Colors.md b/solutions/lc-solutions/2200-2299/2278-Two-Furthest-Houses-With-Different-Colors.md new file mode 100644 index 0000000..cd87d08 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2278-Two-Furthest-Houses-With-Different-Colors.md @@ -0,0 +1,181 @@ +--- +id: Two-Furthest-Houses-With-Different-Colors +title: Two Furthest Houses With Different Colors +sidebar_label: 2278-Two Furthest Houses With Different Colors +tags: + - Arrays + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house. + +Return the maximum distance between two houses with different colors. + +The distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x. +### Examples + +**Example 1:** + +Input: colors = [1,1,1,6,1,1,1] +Output: 3 +Explanation: In the above image, color 1 is blue, and color 6 is red. +The furthest two houses with different colors are house 0 and house 3. +House 0 has color 1, and house 3 has color 6. The distance between them is abs(0 - 3) = 3. +Note that houses 3 and 6 can also produce the optimal answer. + +**Example 2:** + +Input: colors = [1,8,3,8,3] +Output: 4 +Explanation: In the above image, color 1 is blue, color 8 is yellow, and color 3 is green. +The furthest two houses with different colors are house 0 and house 4. +House 0 has color 1, and house 4 has color 3. The distance between them is abs(0 - 4) = 4. + +**Example 3"** + +Input: colors = [0,1] +Output: 1 +Explanation: The furthest two houses with different colors are house 0 and house 1. +House 0 has color 0, and house 1 has color 1. The distance between them is abs(0 - 1) = 1. + + +### Constraints + +- `n == colors.length` +- `2 <= n <= 100` +- `0 <= colors[i] <= 100` +-` Test data are generated such that at least two houses have different colors.` + +### Approach + +Identify Extremes: + +- Calculate the distance between the first house and the farthest house with a different color. +- Calculate the distance between the last house and the farthest house with a different color. + +Maximize Distance: +- Use the distances found in step 1 to determine the maximum distance between houses of different colors. + +Return Result: +- Return the maximum of the calculated distances. + + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +#include +using namespace std; + +int maxDistance(vector& colors) { + int n = colors.size(); + int maxDist = 0; + + for (int i = 0; i < n; ++i) { + for (int j = n - 1; j > i; --j) { + if (colors[i] != colors[j]) { + maxDist = max(maxDist, abs(j - i)); + break; // since we want the maximum distance, we break here + } + } + } + return maxDist; +} + +int main() { + vector colors1 = {1, 1, 1, 6, 1, 1, 1}; + vector colors2 = {1, 8, 3, 8, 3}; + vector colors3 = {0, 1}; + + cout << maxDistance(colors1) << endl; // Output: 3 + cout << maxDistance(colors2) << endl; // Output: 4 + cout << maxDistance(colors3) << endl; // Output: 1 + + return 0; +} + + + +``` + +### Java Solution + +```java +public class MaxDistance { + public static int maxDistance(int[] colors) { + int n = colors.length; + int maxDist = 0; + + for (int i = 0; i < n; ++i) { + for (int j = n - 1; j > i; --j) { + if (colors[i] != colors[j]) { + maxDist = Math.max(maxDist, Math.abs(j - i)); + break; // since we want the maximum distance, we break here + } + } + } + return maxDist; + } + + public static void main(String[] args) { + int[] colors1 = {1, 1, 1, 6, 1, 1, 1}; + int[] colors2 = {1, 8, 3, 8, 3}; + int[] colors3 = {0, 1}; + + System.out.println(maxDistance(colors1)); // Output: 3 + System.out.println(maxDistance(colors2)); // Output: 4 + System.out.println(maxDistance(colors3)); // Output: 1 + } +} + + +``` + +### Python Solution + +```python +def max_distance(colors): + n = len(colors) + max_dist = 0 + + for i in range(n): + for j in range(n - 1, i, -1): + if colors[i] != colors[j]: + max_dist = max(max_dist, abs(j - i)) + break # since we want the maximum distance, we break here + + return max_dist + +# Example usage: +colors1 = [1, 1, 1, 6, 1, 1, 1] +colors2 = [1, 8, 3, 8, 3] +colors3 = [0, 1] + +print(max_distance(colors1)) # Output: 3 +print(max_distance(colors2)) # Output: 4 +print(max_distance(colors3)) # Output: 1 + + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n)$ + +> **Reason**:We iterate through the list of houses once to check distances from both ends, resulting in a linear time complexity. + +### Space Complexity: $O(1)$ + +> **Reason**: We use a constant amount of additional space for variables to store distances and the maximum distance, leading to a constant space complexity. + diff --git a/solutions/lc-solutions/2200-2299/2279-Maximum-Bags-With-Full-Capacity-of-Rocks.md b/solutions/lc-solutions/2200-2299/2279-Maximum-Bags-With-Full-Capacity-of-Rocks.md new file mode 100644 index 0000000..d73ed78 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2279-Maximum-Bags-With-Full-Capacity-of-Rocks.md @@ -0,0 +1,326 @@ +--- +id: Maximum-Bags-With-Full-Capacity-of-Rocks +title: Maximum Bags With Full Capacity of Rocks +sidebar_label: 2279-Maximum Bags With Full Capacity of Rocks +tags: + - Arrays + - Brute Force + - Optimized approach + - LeetCode + - Python + - Java + - C++ + +description: "This is a solution to Maximum Bags With Full Capacity of Rocks problem on LeetCode." +sidebar_position: 80 +--- + +## Problem Statement +In this tutorial, we will solve the Maximum Bags With Full Capacity of Rocks problem . We will provide the implementation of the solution in Python, Java, and C++. + +### Problem Description + +You have n bags numbered from 0 to n - 1. You are given two 0-indexed integer arrays capacity and rocks. The ith bag can hold a maximum of capacity[i] rocks and currently contains rocks[i] rocks. You are also given an integer additionalRocks, the number of additional rocks you can place in any of the bags. + +Return the maximum number of bags that could have full capacity after placing the additional rocks in some bags. + +### Examples + +**Example 1:** +Input: capacity = [2,3,4,5], rocks = [1,2,4,4], additionalRocks = 2 +Output: 3 +Explanation: +Place 1 rock in bag 0 and 1 rock in bag 1. +The number of rocks in each bag are now [2,3,4,4]. +Bags 0, 1, and 2 have full capacity. +There are 3 bags at full capacity, so we return 3. +It can be shown that it is not possible to have more than 3 bags at full capacity. +Note that there may be other ways of placing the rocks that result in an answer of 3. +**Example 2:** +Input: capacity = [10,2,2], rocks = [2,2,0], additionalRocks = 100 +Output: 3 +Explanation: +Place 8 rocks in bag 0 and 2 rocks in bag 2. +The number of rocks in each bag are now [10,2,2]. +Bags 0, 1, and 2 have full capacity. +There are 3 bags at full capacity, so we return 3. +It can be shown that it is not possible to have more than 3 bags at full capacity. +Note that we did not use all of the additional rocks. +### Constraints +- `n == capacity.length == rocks.length` +- `1 <= n <= 5 * 104` +- `1 <= capacity[i] <= 109` +- `0 <= rocks[i] <= capacity[i]` +- `1 <= additionalRocks <= 109` +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +Brute Force Approach: The brute force approach involves trying every possible way to distribute the additional rocks among the bags to maximize the number of full bags. This approach is infeasible for large inputs due to its high complexity. +#### Codes in Different Languages + + + + + +```cpp +#include +#include + +int distributeRocks(std::vector& capacity, std::vector& rocks, int additionalRocks, int idx) { + if (idx == capacity.size() || additionalRocks == 0) { + int fullBags = 0; + for (int i = 0; i < capacity.size(); ++i) { + if (rocks[i] == capacity[i]) { + ++fullBags; + } + } + return fullBags; + } + + int maxBags = distributeRocks(capacity, rocks, additionalRocks, idx + 1); + + for (int i = 1; i <= additionalRocks; ++i) { + if (rocks[idx] + i <= capacity[idx]) { + rocks[idx] += i; + maxBags = std::max(maxBags, distributeRocks(capacity, rocks, additionalRocks - i, idx + 1)); + rocks[idx] -= i; + } + } + + return maxBags; +} + +int maximumBagsBruteForce(std::vector& capacity, std::vector& rocks, int additionalRocks) { + return distributeRocks(capacity, rocks, additionalRocks, 0); +} + + +``` + + + + +```java +import java.util.*; + +public class BruteForceSolution { + public int distributeRocks(int[] capacity, int[] rocks, int additionalRocks, int idx) { + if (idx == capacity.length || additionalRocks == 0) { + int fullBags = 0; + for (int i = 0; i < capacity.length; ++i) { + if (rocks[i] == capacity[i]) { + ++fullBags; + } + } + return fullBags; + } + + int maxBags = distributeRocks(capacity, rocks, additionalRocks, idx + 1); + + for (int i = 1; i <= additionalRocks; ++i) { + if (rocks[idx] + i <= capacity[idx]) { + rocks[idx] += i; + maxBags = Math.max(maxBags, distributeRocks(capacity, rocks, additionalRocks - i, idx + 1)); + rocks[idx] -= i; + } + } + + return maxBags; + } + + public int maximumBagsBruteForce(int[] capacity, int[] rocks, int additionalRocks) { + return distributeRocks(capacity, rocks, additionalRocks, 0); + } +} + + + +``` + + + + + + +```python +def distribute_rocks(capacity, rocks, additional_rocks, idx): + if idx == len(capacity) or additional_rocks == 0: + full_bags = sum(1 for i in range(len(capacity)) if rocks[i] == capacity[i]) + return full_bags + + max_bags = distribute_rocks(capacity, rocks, additional_rocks, idx + 1) + + for i in range(1, additional_rocks + 1): + if rocks[idx] + i <= capacity[idx]: + rocks[idx] += i + max_bags = max(max_bags, distribute_rocks(capacity, rocks, additional_rocks - i, idx + 1)) + rocks[idx] -= i + + return max_bags + +def maximum_bags_brute_force(capacity, rocks, additional_rocks): + return distribute_rocks(capacity, rocks, additional_rocks, 0) + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(2^n)$ +- due to trying all combinations. +- Space Complexity: $O(n)$ +- for the recursive stack. + + + + +### Approach 2: Optimized approach + +Optimized Approach: Calculate the difference between the capacity and the current number of rocks in each bag. +Sort these differences in ascending order. +Start filling the bags with the smallest difference first until the additional rocks are exhausted. +Count the number of bags that have been filled to their capacity. + +#### Code in Different Languages + + + + + +```cpp +#include +#include + +int maximumBags(std::vector& capacity, std::vector& rocks, int additionalRocks) { + int n = capacity.size(); + std::vector spaceNeeded(n); + + // Calculate the space needed to fill each bag + for (int i = 0; i < n; ++i) { + spaceNeeded[i] = capacity[i] - rocks[i]; + } + + // Sort the space needed in ascending order + std::sort(spaceNeeded.begin(), spaceNeeded.end()); + + int fullBags = 0; + + // Fill the bags with the smallest space needed first + for (int i = 0; i < n; ++i) { + if (spaceNeeded[i] <= additionalRocks) { + additionalRocks -= spaceNeeded[i]; + ++fullBags; + } else { + break; + } + } + + return fullBags; +} + + + + +``` + + + + +```java +import java.util.Arrays; + +public class Solution { + public int maximumBags(int[] capacity, int[] rocks, int additionalRocks) { + int n = capacity.length; + int[] spaceNeeded = new int[n]; + + // Calculate the space needed to fill each bag + for (int i = 0; i < n; ++i) { + spaceNeeded[i] = capacity[i] - rocks[i]; + } + + // Sort the space needed in ascending order + Arrays.sort(spaceNeeded); + + int fullBags = 0; + + // Fill the bags with the smallest space needed first + for (int i = 0; i < n; ++i) { + if (spaceNeeded[i] <= additionalRocks) { + additionalRocks -= spaceNeeded[i]; + ++fullBags; + } else { + break; + } + } + + return fullBags; + } +} + + +``` + + + + + + +```python +def maximum_bags(capacity, rocks, additional_rocks): + space_needed = [capacity[i] - rocks[i] for i in range(len(capacity))] + + # Sort the space needed in ascending order + space_needed.sort() + + full_bags = 0 + + # Fill the bags with the smallest space needed first + for space in space_needed: + if space <= additional_rocks: + additional_rocks -= space + full_bags += 1 + else: + break + + return full_bags + + + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n*logn)$ +- due to sorting the differences. +- Space Complexity: $O(n)$ +- for storing the differences. +- This approach is efficient and straightforward. + + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/2200-2299/2284-Sender-With-Largest-Word-Count.md b/solutions/lc-solutions/2200-2299/2284-Sender-With-Largest-Word-Count.md new file mode 100644 index 0000000..14a3696 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2284-Sender-With-Largest-Word-Count.md @@ -0,0 +1,333 @@ +--- +id: Sender-With-Largest-Word-Count +title: Sender With Largest Word Count +sidebar_label: 2284-Sender With Largest Word Count +tags: + - Strings + - Brute Force + - Optimized approach + - LeetCode + - Python + - Java + - C++ + +description: "This is a solution to Sender With Largest Word Count problem on LeetCode." +sidebar_position: 85 +--- + +## Problem Statement +In this tutorial, we will solve the Sender With Largest Word Count problem. We will provide the implementation of the solution in Python, Java, and C++. + +### Problem Description + +You have a chat log of n messages. You are given two string arrays messages and senders where messages[i] is a message sent by senders[i]. + +A message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note that a sender may send more than one message. + +Return the sender with the largest word count. If there is more than one sender with the largest word count, return the one with the lexicographically largest name. + +### Examples + +**Example 1:** +Input: messages = ["Hello userTwooo", "Hi userThree", "Wonderful day Alice", "Nice day userThree"], senders = ["Alice", "userTwo", "userThree", "Alice"] +Output: "Alice" +Explanation: Alice sends a total of 2 + 3 = 5 words. +userTwo sends a total of 2 words. +userThree sends a total of 3 words. +Since Alice has the largest word count, we return "Alice". +**Example 2:** +Input: messages = ["How is leetcode for everyone","Leetcode is useful for practice"], senders = ["Bob","Charlie"] +Output: "Charlie" +Explanation: Bob sends a total of 5 words. +Charlie sends a total of 5 words. +Since there is a tie for the largest word count, we return the sender with the lexicographically larger name, Charlie. + +### Constraints +- `n == messages.length == senders.length` +- `1 <= n <= 104` +- `1 <= messages[i].length <= 100` +- `1 <= senders[i].length <= 10` +- `messages[i] consists of uppercase and lowercase English letters and ' '.` +- `All the words in messages[i] are separated by a single space.` +- `messages[i] does not have leading or trailing spaces.` +- `senders[i] consists of uppercase and lowercase English letters only.` +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + +## Approach 1:Brute Force (Naive) + +Count Words for Each Sender: + +Iterate through the messages array. +For each message, count the number of words and add this count to the corresponding sender's total in a dictionary. +Determine the Sender with the Largest Word Count: + +Traverse the dictionary to find the sender with the maximum word count. In case of a tie, choose the sender with the lexicographically larger name. +#### Codes in Different Languages + + + + + +```cpp +#include +#include +#include +#include +#include + +std::string largestWordCount(std::vector& messages, std::vector& senders) { + std::unordered_map wordCount; + + for (int i = 0; i < messages.size(); i++) { + std::istringstream iss(messages[i]); + int count = 0; + std::string word; + while (iss >> word) count++; + wordCount[senders[i]] += count; + } + + std::string result; + int maxCount = 0; + + for (const auto& entry : wordCount) { + if (entry.second > maxCount || (entry.second == maxCount && entry.first > result)) { + maxCount = entry.second; + result = entry.first; + } + } + + return result; +} + +``` + + + + +```java +import java.util.*; + +public class Solution { + public String largestWordCount(String[] messages, String[] senders) { + Map wordCount = new HashMap<>(); + + for (int i = 0; i < messages.length; i++) { + int count = messages[i].split(" ").length; + wordCount.put(senders[i], wordCount.getOrDefault(senders[i], 0) + count); + } + + String result = ""; + int maxCount = 0; + + for (Map.Entry entry : wordCount.entrySet()) { + if (entry.getValue() > maxCount || (entry.getValue() == maxCount && entry.getKey().compareTo(result) > 0)) { + maxCount = entry.getValue(); + result = entry.getKey(); + } + } + + return result; + } +} + + + +``` + + + + + + +```python +from collections import defaultdict + +def largest_word_count(messages, senders): + word_count = defaultdict(int) + + for i in range(len(messages)): + count = len(messages[i].split()) + word_count[senders[i]] += count + + max_count = 0 + result = "" + + for sender, count in word_count.items(): + if count > max_count or (count == max_count and sender > result): + max_count = count + result = sender + + return result + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(n+k)$ +- where n is the number of messages and k is the number of unique senders. +- Space Complexity: $O(k)$ +- for storing word counts of senders. + +## Approach 2: Optimized approach + +Optimized Approach: Word Count Calculation: +For each message, split the message string and count the words. This step is O(1) in complexity since the maximum length of a message is fixed. +Tracking Maximum Word Count and Sender: +Keep track of the maximum word count and the sender with that count directly while iterating through the dictionary. This avoids the need for a separate loop to find the maximum. + +#### Code in Different Languages + + + + + +```cpp +#include +#include +#include +#include +#include + +std::string largestWordCount(std::vector& messages, std::vector& senders) { + std::unordered_map wordCount; + std::string result; + int maxCount = 0; + + for (int i = 0; i < messages.size(); i++) { + int count = std::count(messages[i].begin(), messages[i].end(), ' ') + 1; + wordCount[senders[i]] += count; + + if (wordCount[senders[i]] > maxCount || (wordCount[senders[i]] == maxCount && senders[i] > result)) { + maxCount = wordCount[senders[i]]; + result = senders[i]; + } + } + + return result; +} + + + + +``` + + + + +```java +import java.util.*; + +public class Solution { + public String largestWordCount(String[] messages, String[] senders) { + Map wordCount = new HashMap<>(); + String result = ""; + int maxCount = 0; + + for (int i = 0; i < messages.length; i++) { + int count = messages[i].split(" ").length; + wordCount.put(senders[i], wordCount.getOrDefault(senders[i], 0) + count); + + if (wordCount.get(senders[i]) > maxCount || + (wordCount.get(senders[i]) == maxCount && senders[i].compareTo(result) > 0)) { + maxCount = wordCount.get(senders[i]); + result = senders[i]; + } + } + + return result; + } +} + +``` + + + + + + +```python +from collections import defaultdict + +def largest_word_count(messages, senders): + word_count = defaultdict(int) + max_count = 0 + result = "" + + for message, sender in zip(messages, senders): + count = len(message.split()) + word_count[sender] += count + + if word_count[sender] > max_count or (word_count[sender] == max_count and sender > result): + max_count = word_count[sender] + result = sender + + return result + + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n+k)$ + +- Space Complexity: $O(k)$ + +- This approach is efficient and straightforward. + +## Video Explanation of Given Problem + + + + + + + + + + + + + + + + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/2200-2299/2286 - Booking Concert Tickets in Groups.md b/solutions/lc-solutions/2200-2299/2286 - Booking Concert Tickets in Groups.md new file mode 100644 index 0000000..745ec91 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2286 - Booking Concert Tickets in Groups.md @@ -0,0 +1,229 @@ +--- +id: Booking-concert-tickets-in-groups +title: Booking Concert Tickets in Groups +sidebar_label: 2286 Booking Concert Tickets in Groups +tags: + - Java + - Binary Search + - Design + - Segmnent Tree + - Binary Indexed Tree +description: "This document provides a solution where we need to design a ticketing system that can allocate seats." +--- + +## Problem + +A concert hall has $n$ rows numbered from $0$ to $n - 1$, each with $m$ seats, numbered from $0$ to $m - 1$. You need to design a ticketing system that can allocate seats in the following cases: + +- If a group of $k$ spectators can sit **together** in a row. +- If **every** member of a group of $k$ spectators can get a seat. They may or **may not** sit together. + +Note that the spectators are very picky. Hence: + +- They will book seats only if each member of their group can get a seat with row number **less than or equal** to $maxRow$. $maxRow$ can vary from group to group. +- In case there are multiple rows to choose from, the row with the **smallest** number is chosen. If there are multiple seats to choose in the same row, the seat with the **smallest** number is chosen. + +Implement the $BookMyShow$ class: + +- $BookMyShow(int n, int m)$ Initializes the object with $n$ as number of rows and $m$ as number of seats per row. +- $int[] gather(int k, int maxRow)$ Returns an array of length $2$ denoting the row and seat number (respectively) of the **first seat** being allocated to the $k$ members of the group, who must sit **together**. In other words, it returns the smallest possible $r$ and $c$ such that all $[c, c + k - 1]$ seats are valid and empty in row $r$, and $r <= maxRow$. Returns $[]$ in case it is **not possible** to allocate seats to the group. + +- $boolean scatter(int k, int maxRow)$ Returns $true$ if all $k$ members of the group can be allocated seats in rows $0$ to $maxRow$, who may or **may not** sit together. If the seats can be allocated, it allocates $k$ seats to the group with the **smallest** row numbers, and the smallest possible seat numbers in each row. Otherwise, returns $false$. + +### Examples + +**Example 1:** + +``` +Input: ["BookMyShow", "gather", "gather", "scatter", "scatter"] +[[2, 5], [4, 0], [2, 0], [5, 1], [5, 1]] + +Output: [null, [0, 0], [], true, false] + +Explanation: + +BookMyShow bms = new BookMyShow(2, 5); // There are 2 rows with 5 seats each +bms.gather(4, 0); // return [0, 0] + // The group books seats [0, 3] of row 0. + +bms.gather(2, 0); // return [] + // There is only 1 seat left in row 0, + // so it is not possible to book 2 consecutive seats. + +bms.scatter(5, 1); // return True + // The group books seat 4 of row 0 and seats [0, 3] of row 1. + +bms.scatter(5, 1); // return False + // There is only one seat left in the hall. +``` + +### Constraints + +- $1 <= n <= 5 * 10^4$ +- $1 <= m, k <= 10^9$ +- $0 <= maxRow <= n - 1$ +- At most $5 * 10^4$ calls in total will be made to $gather$ and $scatter$. + +--- + +## Approach + +To solve the problem, we need to understand the nature of the allowed moves: + +1. **Segment Tree**: + + - **Build**: Construct the segment tree with initial values, where each node stores the sum and maximum number of seats in the range it represents. + - **Update**: Update the segment tree when seats are booked, modifying the relevant nodes to reflect the new seat counts. + + - **Queries**: + + - **Gather Query**: Find a row with at least **'k'** seats available within the first **'maxRow'** rows. + + - **Sum Query**: Compute the total number of seats available within the first **'maxRow'** rows. + +2. **BookMyShow Class**: + + - **Constructor**: Initialize the segment tree and an array to keep track of seats available in each row. + - **Gather**: Check if there is a row with at least **'k'** seats and update the tree and row seat count accordingly. + - **Scatter**: Allocate **'k'** + +## Solution for Booking Concert Tickets in Groups + +- The problem revolves around efficiently managing and querying seat allocations in a theater. The segment tree is used to handle range queries and updates swiftly, ensuring that operations like finding available seats or updating seat counts are performed in logarithmic time. + +#### Code in Java + +```java +class BookMyShow { + static class SegTree{ + long sum[]; // store sum of seats in a range + long segTree[]; // store maximum seats in a range + int m, n; + public SegTree(int n, int m) { + this.m = m; + this.n = n; + segTree = new long[4*n]; + sum = new long[4*n]; + build(0, 0, n-1, m); + } + + private void build(int index, int lo, int hi, long val){ + if(lo == hi){ + segTree[index] = val; // initialize segement tree with initial seat capacity + sum[index] = val; // initialize "sum" with initial seat capacity of a row + return; + } + int mid = (lo + hi)/2; + build(2*index +1, lo, mid, val); // build left sub tree + build(2*index +2, mid+1, hi, val); // build right sub tree + segTree[index] = Math.max(segTree[2*index + 1], segTree[2*index + 2]); // maximum seats in a row for subtrees + sum[index] = sum[2*index + 1] + sum[2*index + 2]; // sum of seats in a range + } + + private void update(int index, int lo, int hi, int pos, int val){ + /** + Method to update segment tree based on the available seats in a row + **/ + if(lo == hi){ + segTree[index] = val; + sum[index] = val; + return; + } + int mid = (lo + hi) / 2; + if (pos <= mid) { // position to update is in left + update(2 * index + 1, lo, mid, pos, val); + } else { // position to update is in right + update(2 * index + 2, mid+1, hi, pos, val); + } + // update segment tree and "sum" based on the update in "pos" index + segTree[index] = Math.max(segTree[2*index + 1] , segTree[2*index + 2]); + sum[index] = sum[2*index + 1] + sum[2*index + 2]; + } + + public void update(int pos, int val){ + update(0, 0, n - 1 , pos, val); + } + + public int gatherQuery(int k, int maxRow){ + return gatherQuery(0, 0, n - 1 , k, maxRow); + } + + private int gatherQuery(int index, int lo, int hi, int k, int maxRow){ + /** + Method to check if seats are available in a single row + **/ + if(segTree[index] < k || lo > maxRow) + return -1; + if(lo == hi) return lo; + int mid = (lo + hi) / 2; + int c = gatherQuery(2*index + 1, lo, mid, k, maxRow); + if(c == -1){ + c = gatherQuery(2*index + 2, mid +1, hi, k, maxRow); + } + return c; + } + + public long sumQuery(int k, int maxRow){ + return sumQuery(0, 0, n-1, k, maxRow); + } + + private long sumQuery(int index, int lo, int hi, int l, int r){ + if(lo > r || hi < l ) return 0; // not in range + if(lo >= l && hi <= r) return sum[index]; // in range + int mid = (lo + hi)/2; + return sumQuery(2*index+1, lo, mid, l, r) + sumQuery(2*index+2, mid+1, hi, l, r); + } + } + + SegTree segTree; + int[] rowSeats; // stores avaiable seats in a row, helps to find the vacant seat in a row + + public BookMyShow(int n, int m) { + segTree = new SegTree(n, m); + rowSeats = new int[n]; + Arrays.fill(rowSeats, m); // initialize vacant seats count to "m" for all the rows + } + + + public int[] gather(int k, int maxRow) { + int row = segTree.gatherQuery(k, maxRow); // find row which has k seats + if(row == -1) return new int[]{}; // can't find a row with k seats + int col = segTree.m - rowSeats[row]; // find column in the row which has k seats + rowSeats[row] -= k; // reduce the seats + segTree.update(row, rowSeats[row]); // update the segment tree + return new int[]{row, col}; + + } + + public boolean scatter(int k, int maxRow) { + long sum = segTree.sumQuery(0, maxRow); // find the sum for the given range [0, maxRow] + if(sum < k) return false; // can't find k seats in [0, maxRow] + + for(int i=0; i<=maxRow && k !=0 ; i++){ + if(rowSeats[i] > 0){ // if current row has seats then allocate those seats + long t = Math.min(rowSeats[i], k); + rowSeats[i] -= t; + k -= t; + segTree.update(i,rowSeats[i]); // update the segment tree + } + } + return true; + } +} +``` + +### Complexity Analysis + +#### Time Complexity: $O(logn)$ + +> **Reason**: Segment tree operations are build: $O(n)$, update: $O(log n)$, gather query: $O(log n)$, sum query: $O(log n)$; BookMyShow operations are constructor: $O(n)$, gather: $O(log n)$, scatter: $O(n log n)$. + +#### Space Complexity: $O(n)$ + +> **Reason**: The space complexity is $O(n)$, The **'rowSeats'** array requires O(n) space to store the seat counts for each row. + +# References + +- **LeetCode Problem:** [Booking Concert Tickets in Groups](https://leetcode.com/problems/booking-concert-tickets-in-groups/description/) +- **Solution Link:** [Booking Concert Tickets in Groups Solution on LeetCode](https://leetcode.com/problems/booking-concert-tickets-in-groups/solutions/) +- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/vivekvardhan43862/) diff --git a/solutions/lc-solutions/2200-2299/2287-Rearrange-Characters-to-Make-Target-String.md b/solutions/lc-solutions/2200-2299/2287-Rearrange-Characters-to-Make-Target-String.md new file mode 100644 index 0000000..9d9c6a7 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2287-Rearrange-Characters-to-Make-Target-String.md @@ -0,0 +1,215 @@ +--- +id: Rearrange-Characters-to-Make-Target-String +title: Rearrange Characters to Make Target String +sidebar_label: 2287-Rearrange Characters to Make Target String +tags: + - String + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings. + +Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them. + +### Examples + +**Example 1:** + +Input: s = "ilovecodingonleetcode", target = "code" +Output: 2 +Explanation: +For the first copy of "code", take the letters at indices 4, 5, 6, and 7. +For the second copy of "code", take the letters at indices 17, 18, 19, and 20. +The strings that are formed are "ecod" and "code" which can both be rearranged into "code". +We can make at most two copies of "code", so we return 2. + +**Example 2:** + +Input: s = "abcba", target = "abc" +Output: 1 +Explanation: +We can make one copy of "abc" by taking the letters at indices 0, 1, and 2. +We can make at most one copy of "abc", so we return 1. +Note that while there is an extra 'a' and 'b' at indices 3 and 4, we cannot reuse the letter 'c' at index 2, so we cannot make a second copy of "abc". +**Example 3"** + +Input: s = "abbaccaddaeea", target = "aaaaa" +Output: 1 +Explanation: +We can make one copy of "aaaaa" by taking the letters at indices 0, 3, 6, 9, and 12. +We can make at most one copy of "aaaaa", so we return 1. + + +### Constraints + +- `1 <= s.length <= 100` +- `1 <= target.length <= 10` +- `s and target consist of lowercase English letters.` +### Approach + +Count Frequencies: + +- Count the frequency of each character in both the string s and the target target. +Determine Maximum Copies: + +- For each character in the target, calculate how many times it can be formed from the string s by dividing the frequency in s by the frequency in the target. +Find Minimum: + +- The maximum number of copies of the target string that can be formed is the minimum value of these quotients. + +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +#include +#include +#include +using namespace std; + +int maxCopies(string s, string target) { + unordered_map count_s, count_target; + for (char c : s) { + count_s[c]++; + } + for (char c : target) { + count_target[c]++; + } + + int max_copies = INT_MAX; + for (auto& [char_target, count] : count_target) { + if (count_s.find(char_target) == count_s.end()) { + return 0; // If any character in target is not in s, we can't form the target at all + } + max_copies = min(max_copies, count_s[char_target] / count); + } + + return max_copies; +} + +int main() { + string s1 = "ilovecodingonleetcode"; + string target1 = "code"; + cout << maxCopies(s1, target1) << endl; // Output: 2 + + string s2 = "abcba"; + string target2 = "abc"; + cout << maxCopies(s2, target2) << endl; // Output: 1 + + string s3 = "abbaccaddaeea"; + string target3 = "aaaaa"; + cout << maxCopies(s3, target3) << endl; // Output: 1 + + return 0; +} + + + +``` + +### Java Solution + +```java +import java.util.HashMap; +import java.util.Map; + +public class MaxCopies { + public static int maxCopies(String s, String target) { + Map countS = new HashMap<>(); + Map countTarget = new HashMap<>(); + + for (char c : s.toCharArray()) { + countS.put(c, countS.getOrDefault(c, 0) + 1); + } + for (char c : target.toCharArray()) { + countTarget.put(c, countTarget.getOrDefault(c, 0) + 1); + } + + int maxCopies = Integer.MAX_VALUE; + for (Map.Entry entry : countTarget.entrySet()) { + char charTarget = entry.getKey(); + int count = entry.getValue(); + + if (!countS.containsKey(charTarget)) { + return 0; // If any character in target is not in s, we can't form the target at all + } + maxCopies = Math.min(maxCopies, countS.get(charTarget) / count); + } + + return maxCopies; + } + + public static void main(String[] args) { + String s1 = "ilovecodingonleetcode"; + String target1 = "code"; + System.out.println(maxCopies(s1, target1)); // Output: 2 + + String s2 = "abcba"; + String target2 = "abc"; + System.out.println(maxCopies(s2, target2)); // Output: 1 + + String s3 = "abbaccaddaeea"; + String target3 = "aaaaa"; + System.out.println(maxCopies(s3, target3)); // Output: 1 + } +} + + +``` + +### Python Solution + +```python +from collections import Counter + +def max_copies(s, target): + count_s = Counter(s) + count_target = Counter(target) + + # Determine the maximum number of copies of target that can be formed + max_copies = float('inf') + for char in count_target: + if char in count_s: + max_copies = min(max_copies, count_s[char] // count_target[char]) + else: + return 0 # If any character in target is not in s, we can't form the target at all + + return max_copies + +# Example usage: +s1 = "ilovecodingonleetcode" +target1 = "code" +print(max_copies(s1, target1)) # Output: 2 + +s2 = "abcba" +target2 = "abc" +print(max_copies(s2, target2)) # Output: 1 + +s3 = "abbaccaddaeea" +target3 = "aaaaa" +print(max_copies(s3, target3)) # Output: 1 + + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n+m)$ + +> **Reason**:where m is the length of string target and n is the length of string s + + +### Space Complexity: $O(1)$ + +> **Reason**: The space used for the frequency counters is constant, as we only count the frequency of lowercase English letters + diff --git a/solutions/lc-solutions/2200-2299/2293-Min-Max-Game.md b/solutions/lc-solutions/2200-2299/2293-Min-Max-Game.md new file mode 100644 index 0000000..d6a6eb5 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2293-Min-Max-Game.md @@ -0,0 +1,169 @@ +--- +id: Min-Max-Game +title: Min Max Game +sidebar_label: 2293-Min Max Game +tags: + - Arrays + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +You are given a 0-indexed integer array nums whose length is a power of 2. + +Apply the following algorithm on nums: + +Let n be the length of nums. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n / 2. +For every even index i where `0 <= i < n / 2`, assign the value of newNums[i] as min(nums[2 * i], nums[2 * i + 1]). +For every odd index i where `0 <= i < n / 2`, assign the value of newNums[i] as max(nums[2 * i], nums[2 * i + 1]). +Replace the array nums with newNums. +Repeat the entire process starting from step 1. +Return the last number that remains in nums after applying the algorithm. + +### Examples + +**Example 1:** + +Input: nums = [1,3,5,2,4,8,2,2] +Output: 1 +Explanation: The following arrays are the results of applying the algorithm repeatedly. +First: nums = [1,5,4,2] +Second: nums = [1,4] +Third: nums = [1] +1 is the last remaining number, so we return 1. + +**Example 2:** + +Input: nums = [3] +Output: 3 +Explanation: 3 is already the last remaining number, so we return 3. + + + + +### Constraints + +- `1 <= nums.length <= 1024` +- `1 <= nums[i] <= 109` +- `nums.length is a power of 2.` +### Approach + +Initialize: Start with the array nums. + +Iterate and Reduce: + +- While nums has more than 1 element: +- Create newNums with half the length. +- For each even index, assign the minimum of the corresponding pair from nums. +- For each odd index, assign the maximum. +- Replace nums with newNums. +Return: Return the last remaining element in nums. +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +#include +using namespace std; + +int minMaxGame(vector& nums) { + while (nums.size() > 1) { + vector newNums(nums.size() / 2); + for (int i = 0; i < newNums.size(); ++i) { + if (i % 2 == 0) { + newNums[i] = min(nums[2 * i], nums[2 * i + 1]); + } else { + newNums[i] = max(nums[2 * i], nums[2 * i + 1]); + } + } + nums = newNums; + } + return nums[0]; +} + +// Example usage: +#include +int main() { + vector nums1 = {1, 3, 5, 2, 4, 8, 2, 2}; + cout << minMaxGame(nums1) << endl; // Output: 1 + + vector nums2 = {3}; + cout << minMaxGame(nums2) << endl; // Output: 3 + return 0; +} + + +``` + +### Java Solution + +```java +public class MinMaxGame { + public static int minMaxGame(int[] nums) { + while (nums.length > 1) { + int[] newNums = new int[nums.length / 2]; + for (int i = 0; i < newNums.length; i++) { + if (i % 2 == 0) { + newNums[i] = Math.min(nums[2 * i], nums[2 * i + 1]); + } else { + newNums[i] = Math.max(nums[2 * i], nums[2 * i + 1]); + } + } + nums = newNums; + } + return nums[0]; + } + + public static void main(String[] args) { + int[] nums1 = {1, 3, 5, 2, 4, 8, 2, 2}; + System.out.println(minMaxGame(nums1)); // Output: 1 + + int[] nums2 = {3}; + System.out.println(minMaxGame(nums2)); // Output: 3 + } +} + + +``` + +### Python Solution + +```python +def minMaxGame(nums): + while len(nums) > 1: + newNums = [] + for i in range(len(nums) // 2): + if i % 2 == 0: + newNums.append(min(nums[2 * i], nums[2 * i + 1])) + else: + newNums.append(max(nums[2 * i], nums[2 * i + 1])) + nums = newNums + return nums[0] + +# Example usage: +nums1 = [1, 3, 5, 2, 4, 8, 2, 2] +print(minMaxGame(nums1)) # Output: 1 + +nums2 = [3] +print(minMaxGame(nums2)) # Output: 3 + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n*logn)$ + +> **Reason**:Each iteration halves the array length, and there are logn iterations .Each iteration involves $O(n)$ operations, leading to a total time complexity of $O(n*logn)$. + +### Space Complexity: $O(n)$ + +> **Reason**: The space complexity is primarily determined by the storage of intermediate arrays, which in the worst case is proportional to the size of the input array n. + + diff --git a/solutions/lc-solutions/2200-2299/2299-Strong-Password-Checker-II.md b/solutions/lc-solutions/2200-2299/2299-Strong-Password-Checker-II.md new file mode 100644 index 0000000..494e7ae --- /dev/null +++ b/solutions/lc-solutions/2200-2299/2299-Strong-Password-Checker-II.md @@ -0,0 +1,191 @@ +--- +id: Strong-Password-Checker-II +title: Strong Password Checker II +sidebar_label: 2299-Strong Password Checker II +tags: + - Arrays + - C++ + - Java + - Python +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem + +A password is said to be strong if it satisfies all the following criteria: + +It has at least 8 characters. +It contains at least one lowercase letter. +It contains at least one uppercase letter. +It contains at least one digit. +It contains at least one special character. The special characters are the characters in the following string: "!@#$%^&*()-+". +It does not contain 2 of the same character in adjacent positions (i.e., "aab" violates this condition, but "aba" does not). +Given a string password, return true if it is a strong password. Otherwise, return false. + + + +### Examples + +**Example 1:** + +Input: password = "IloveLe3tcode!" +Output: true +Explanation: The password meets all the requirements. Therefore, we return true. + +**Example 2:** + +Input: password = "Me+You--IsMyDream" +Output: false +Explanation: The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false. + +**Example 3"** + +Input: password = "1aB!" +Output: false +Explanation: The password does not meet the length requirement. Therefore, we return false. + +### Constraints + +- `1 <= password.length <= 100` +- `password consists of letters, digits, and special characters: "!@#$%^&*()-+".` + +### Approach + +Length Check: Ensure the password has at least 8 characters. +Character Type Checks: Verify that the password contains: +- At least one lowercase letter. +- At least one uppercase letter. +- At least one digit. +- At least one special character from "!@#$%^&*()-+". +Adjacent Duplicate Check: Ensure no two identical characters are adjacent. +### Solution + +#### Code in Different Languages + +### C++ Solution + +```cpp +#include +using namespace std; + +bool isStrongPassword(const string& password) { + if (password.size() < 8) return false; + + bool hasLower = false, hasUpper = false, hasDigit = false, hasSpecial = false; + string specialChars = "!@#$%^&*()-+"; + + for (size_t i = 0; i < password.size(); ++i) { + if (islower(password[i])) hasLower = true; + if (isupper(password[i])) hasUpper = true; + if (isdigit(password[i])) hasDigit = true; + if (specialChars.find(password[i]) != string::npos) hasSpecial = true; + if (i > 0 && password[i] == password[i - 1]) return false; + } + + return hasLower && hasUpper && hasDigit && hasSpecial; +} + +// Example usage: +#include +int main() { + string password1 = "IloveLe3tcode!"; + cout << isStrongPassword(password1) << endl; // Output: 1 (true) + + string password2 = "Me+You--IsMyDream"; + cout << isStrongPassword(password2) << endl; // Output: 0 (false) + + string password3 = "1aB!"; + cout << isStrongPassword(password3) << endl; // Output: 0 (false) + + return 0; +} + + + +``` + +### Java Solution + +```java +public class StrongPasswordChecker { + public static boolean isStrongPassword(String password) { + if (password.length() < 8) return false; + + boolean hasLower = false, hasUpper = false, hasDigit = false, hasSpecial = false; + String specialChars = "!@#$%^&*()-+"; + + for (int i = 0; i < password.length(); i++) { + char ch = password.charAt(i); + if (Character.isLowerCase(ch)) hasLower = true; + if (Character.isUpperCase(ch)) hasUpper = true; + if (Character.isDigit(ch)) hasDigit = true; + if (specialChars.indexOf(ch) != -1) hasSpecial = true; + if (i > 0 && ch == password.charAt(i - 1)) return false; + } + + return hasLower && hasUpper && hasDigit && hasSpecial; + } + + public static void main(String[] args) { + String password1 = "IloveLe3tcode!"; + System.out.println(isStrongPassword(password1)); // Output: true + + String password2 = "Me+You--IsMyDream"; + System.out.println(isStrongPassword(password2)); // Output: false + + String password3 = "1aB!"; + System.out.println(isStrongPassword(password3)); // Output: false + } +} + +``` + +### Python Solution + +```python +def is_strong_password(password): + if len(password) < 8: + return False + + has_lower = has_upper = has_digit = has_special = False + special_chars = "!@#$%^&*()-+" + + for i in range(len(password)): + if password[i].islower(): + has_lower = True + if password[i].isupper(): + has_upper = True + if password[i].isdigit(): + has_digit = True + if password[i] in special_chars: + has_special = True + if i > 0 and password[i] == password[i - 1]: + return False + + return has_lower and has_upper and has_digit and has_special + +# Example usage: +password1 = "IloveLe3tcode!" +print(is_strong_password(password1)) # Output: True + +password2 = "Me+You--IsMyDream" +print(is_strong_password(password2)) # Output: False + +password3 = "1aB!" +print(is_strong_password(password3)) # Output: False + + + +``` + +### Complexity Analysis + +### Time Complexity: $O(n)$ + +> **Reason**:Where n is the length of the password. Each character is checked once. + +### Space Complexity: $O(1)$ + +> **Reason**: Only a constant amount of extra space is used. + + diff --git a/solutions/lc-solutions/2200-2299/_category_.json b/solutions/lc-solutions/2200-2299/_category_.json new file mode 100644 index 0000000..7629b52 --- /dev/null +++ b/solutions/lc-solutions/2200-2299/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "2200-2299", + "position": 24, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (2200 - 2299)" + } +} diff --git a/solutions/lc-solutions/2200-2299/image.png b/solutions/lc-solutions/2200-2299/image.png new file mode 100644 index 0000000..161a428 Binary files /dev/null and b/solutions/lc-solutions/2200-2299/image.png differ diff --git a/solutions/lc-solutions/2300-2399/2331-evaluate-boolean-binary-tree.md b/solutions/lc-solutions/2300-2399/2331-evaluate-boolean-binary-tree.md new file mode 100644 index 0000000..4174b07 --- /dev/null +++ b/solutions/lc-solutions/2300-2399/2331-evaluate-boolean-binary-tree.md @@ -0,0 +1,158 @@ +--- +id: evaluate-boolean-binary-tree +title: Evaluate Boolean Binary Tree +sidebar_label: 2331-evaluate-boolean-binary-tree +tags: +- Tree +- Depth-First Search +- Binary Tree +description: "Given the root of a full binary tree, evaluate the boolean result based on the given rules." +--- + +## Problem Description + +You are given the root of a full binary tree with the following properties: + +- Leaf nodes have either the value `0` or `1`, where `0` represents `False` and `1` represents `True`. +- Non-leaf nodes have either the value `2` or `3`, where `2` represents the boolean `OR` and `3` represents the boolean `AND`. + +The evaluation of a node is as follows: + +- If the node is a leaf node, the evaluation is the value of the node, i.e., `True` or `False`. +- Otherwise, evaluate the node's two children and apply the boolean operation of its value with the children's evaluations. + +Return the boolean result of evaluating the root node. + +A full binary tree is a binary tree where each node has either `0` or `2` children. A leaf node is a node that has zero children. + +### Examples + +**Example 1:** + +``` +Input: root = [2,1,3,null,null,0,1] +Output: true +Explanation: The AND node evaluates to `False AND True = False`. The OR node evaluates to `True OR False = True`. The root node evaluates to `True`, so we return `true`. +``` +**Example 2:** +``` +Input: root = [0] +Output: false +Explanation: The root node is a leaf node and it evaluates to `false`, so we return `false`. +``` +### Constraints + +- The number of nodes in the tree is in the range `[1, 1000]`. +- `0 <= Node.val <= 3` +- Every node has either `0` or `2` children. +- Leaf nodes have a value of `0` or `1`. +- Non-leaf nodes have a value of `2` or `3`. + + +## Approach + +To evaluate the boolean binary tree, we use a depth-first search (DFS) approach. We recursively evaluate the left and right children of each node and apply the boolean operation represented by the node's value. + +### Steps: + +1. **Base Case:** If the node is a leaf node (i.e., it has no children), return its boolean value. +2. **Recursive Case:** If the node is not a leaf node: + - If the node's value is `2`, apply the `OR` operation to the evaluations of its children. + - If the node's value is `3`, apply the `AND` operation to the evaluations of its children. + +### Solution + +#### Java Solution + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean evaluateTree(TreeNode root) { + if (root.left == null && root.right == null) { + return root.val == 1; + } else { + if (root.val == 2) { + return evaluateTree(root.left) || evaluateTree(root.right); + } else { + return evaluateTree(root.left) && evaluateTree(root.right); + } + } + } +} +``` + +#### C++ Solution + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool evaluateTree(TreeNode* root) { + if (!root->left && !root->right) { + return root->val == 1; + } else { + if (root->val == 2) { + return evaluateTree(root->left) || evaluateTree(root->right); + } else { + return evaluateTree(root->left) && evaluateTree(root->right); + } + } + } +}; +``` + +#### Python Solution + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right + +class Solution: + def evaluateTree(self, root: TreeNode) -> bool: + if not root.left and not root.right: + return root.val == 1 + else: + if root.val == 2: + return self.evaluateTree(root.left) or self.evaluateTree(root.right) + else: + return self.evaluateTree(root.left) and self.evaluateTree(root.right) +``` + +### Complexity Analysis + +**Time Complexity:** O(n) +> We visit each node exactly once. + +**Space Complexity:** O(h) +> The space complexity is determined by the height of the tree, due to the recursion stack. + +### References +**LeetCode Problem:** Evaluate Boolean Binary Tree diff --git a/solutions/lc-solutions/2300-2399/2348.number-of-zero-filled-subarrays.md b/solutions/lc-solutions/2300-2399/2348.number-of-zero-filled-subarrays.md new file mode 100644 index 0000000..48cb227 --- /dev/null +++ b/solutions/lc-solutions/2300-2399/2348.number-of-zero-filled-subarrays.md @@ -0,0 +1,215 @@ +--- +id: number-of-zero-filled-subarrays +title: 2348. Number of Zero-Filled Subarrays +sidebar_label: 2348. Number of Zero-Filled Subarrays + +tags: +- Array +- Math + +description: "This is a solution to the 2348. Number of Zero-Filled Subarrays problem on LeetCode." +--- + +## Problem Description +Given an integer array nums, return the number of subarrays filled with 0. + +A subarray is a contiguous non-empty sequence of elements within an array. + +### Examples +**Example 1:** + +``` +Input: nums = [1,3,0,0,2,0,0,4] +Output: 6 +Explanation: +There are 4 occurrences of [0] as a subarray. +There are 2 occurrences of [0,0] as a subarray. +There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6. + +``` + +**Example 2:** +``` +Input: nums = [0,0,0,2,0,0] +Output: 9 +Explanation: +There are 5 occurrences of [0] as a subarray. +There are 3 occurrences of [0,0] as a subarray. +There is 1 occurrence of [0,0,0] as a subarray. +There is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9. +``` + +### Constraints +- `0 <= nums.length <= 10^5` + +## Solution for 2348. Number of Zero-Filled Subarrays + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function zeroFilledSubarray(nums) { + let ans = 0; + let i = 0; + while (i < nums.length) { + if (nums[i] === 0) { + let j = i; + while (i < nums.length && nums[i] === 0) { + ans += (i - j + 1); + i++; + } + } + i++; + } + return ans; + } + + const input = [1,3,0,0,2,0,0,4] + const output =zeroFilledSubarray(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n) $ + - Space Complexity: $ O(1)$ + + ## Code in Different Languages + + + + ```javascript + function zeroFilledSubarray(nums) { + let ans = 0; + let i = 0; + while (i < nums.length) { + if (nums[i] === 0) { + let j = i; + while (i < nums.length && nums[i] === 0) { + ans += (i - j + 1); + i++; + } + } + i++; + } + return ans; +} + + ``` + + + + + ```typescript + function zeroFilledSubarray(nums: number[]): number { + let ans: number = 0; + let i: number = 0; + while (i < nums.length) { + if (nums[i] === 0) { + let j: number = i; + while (i < nums.length && nums[i] === 0) { + ans += (i - j + 1); + i++; + } + } + i++; + } + return ans; +} + + ``` + + + + ```python + class Solution: + def zeroFilledSubarray(self, nums: List[int]) -> int: + ans = 0 + i = 0 + while i < len(nums): + if nums[i] == 0: + j = i + while i < len(nums) and nums[i] == 0: + ans += (i - j + 1) + i += 1 + i += 1 + return ans + + ``` + + + + + ```java + class Solution { + public long zeroFilledSubarray(int[] nums) { + long ans = 0; + int i = 0; + while (i < nums.length) { + if (nums[i] == 0) { + int j = i; + while (i < nums.length && nums[i] == 0) { + ans += (i - j + 1); + i++; + } + } + i++; + } + return ans; + } +} + + ``` + + + + + ```cpp +class Solution { +public: + long long zeroFilledSubarray(vector& nums) { + long long ans=0; + int i=0; + while(i + + +
+
+ +## References + +- **LeetCode Problem**: [2348. Number of Zero-Filled Subarrays](https://leetcode.com/problems/number-of-zero-filled-subarrays/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/number-of-zero-filled-subarrays/) + diff --git a/solutions/lc-solutions/2300-2399/2353-design-a-food-rating-system.md b/solutions/lc-solutions/2300-2399/2353-design-a-food-rating-system.md new file mode 100644 index 0000000..0ce776b --- /dev/null +++ b/solutions/lc-solutions/2300-2399/2353-design-a-food-rating-system.md @@ -0,0 +1,375 @@ +--- +id: design-a-food-rating-system +title: Design a Food Rating System +sidebar_label: 2353 - Design a Food Rating System +tags: +- Hash Table +- Ordered Set +- Heap (Priority Queue) +description: "This is a solution to the Design a Food Rating System problem on LeetCode." +--- + +## Problem Description + +Design a food rating system that can do the following: + +- **Modify** the rating of a food item listed in the system. +- Return the highest-rated food item for a type of cuisine in the system. + +Implement the `FoodRatings` class: + +- `FoodRatings(String[] foods, String[] cuisines, int[] ratings)` Initializes the system. The food items are described by `foods`, `cuisines` and `ratings`, all of which have a length of `n`. + - `foods[i]` is the name of the `ith` food, + - `cuisines[i]` is the type of cuisine of the `ith` food, and + - `ratings[i]` is the initial rating of the `ith` food. +- `void changeRating(String food, int newRating)` Changes the rating of the food item with the name food. +- `String highestRated(String cuisine)` Returns the name of the food item that has the highest rating for the given type of `cuisine`. If there is a tie, return the item with the **lexicographically smaller** name. +Note that a string `x` is lexicographically smaller than string `y` if `x` comes before y in dictionary order, that is, either `x` is a prefix of `y`, or if `i` is the first position such that `x[i] != y[i]`, then `x[i]` comes before `y[i]` in alphabetic order. + + + +### Examples + +**Example 1:** + +``` +Input +["FoodRatings", "highestRated", "highestRated", "changeRating", "highestRated", "changeRating", "highestRated"] +[[["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]], ["korean"], ["japanese"], ["sushi", 16], ["japanese"], ["ramen", 16], ["japanese"]] +Output +[null, "kimchi", "ramen", null, "sushi", null, "ramen"] +Explanation +FoodRatings foodRatings = new FoodRatings(["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]); +foodRatings.highestRated("korean"); // return "kimchi" + // "kimchi" is the highest rated korean food with a rating of 9. +foodRatings.highestRated("japanese"); // return "ramen" + // "ramen" is the highest rated japanese food with a rating of 14. +foodRatings.changeRating("sushi", 16); // "sushi" now has a rating of 16. +foodRatings.highestRated("japanese"); // return "sushi" + // "sushi" is the highest rated japanese food with a rating of 16. +foodRatings.changeRating("ramen", 16); // "ramen" now has a rating of 16. +foodRatings.highestRated("japanese"); // return "ramen" + // Both "sushi" and "ramen" have a rating of 16. + // However, "ramen" is lexicographically smaller than "sushi". +``` + +### Constraints + +- $1 \leq n \leq 2 * 10^4$ +- `n == foods.length == cuisines.length == ratings.length` +- `1 <= foods[i].length, cuisines[i].length <= 10` +- `foods[i], cuisines[i]` consist of lowercase English letters. +- $1 \leq ratings[i] \leq 10^8$ +- All the strings in `foods` are **distinct**. +- `food` will be the name of a food item in the system across all calls to changeRating. +- `cuisine` will be a type of cuisine of **at least one** food item in the system across all calls to highestRated. +- At most $2 * 10^4$ calls in total will be made to `changeRating` and `highestRated`. + +## Solution for Design a Food Rating System + +### Approach : Hash Maps and Priority Queue + +#### Intuition +We are given three arrays: +`foods`, containing food's names, +`cuisines`, containing the name of the cuisine of the food at the respective index in the foods array, and +`ratings`, containing the rating of the food at respective index in the `foods` array. + + +We have to update the food's ratings in the method `changeRating(food, newRating)`. + +One way is to search for the `food` in the `foods` array and then update the rating at the respective index in the `ratings` array. However, searching for `food` in the `foods` array for every update will not be efficient. +Instead, we should keep the food names mapped with their ratings, we can use a hash map (named `foodRatingMap`) and this hash map will enable quick retrieval and modification of the respective food's rating. + +To change the rating of any `food`, we simply update the rating stored in this `foodRatingMap` + +![image](https://assets.leetcode.com/static_assets/media/original_images/2353/Slide1a.jpg) + +Another requirement is to return the highest-rated food of a particular cuisine in the method `highestRated(cuisine)`. We are given `cuisines` and `foods` arrays, we can group and store all foods belonging to one cuisine together beforehand, this will help prevent iterating on foods that don't belong to the given cuisine. + +For grouping, we can again use a hash map (named `cuisineFoodMap`) that maps cuisine names and arrays of foods belonging to that particular cuisine. This hash map will enable quick retrieval of all foods belonging to a particular cuisine. + +![image](https://assets.leetcode.com/static_assets/media/original_images/2353/Slide1b.jpg) + +However, retrieving the highest-rated food would require iterating over all the foods of that particular cuisine each time. If we could maintain the food in `cuisineFoodMap` arrays in a sorted order (sorted according to ratings) then it might save us some time. + +You might be thinking of sorting the array using the in-built `sort()` method, but if any element of the array changes (i.e. rating of any food changes) we will have to again sort the whole array using the `sort()` method, this will make the algorithm inefficient. + +**This hints that we should store the foods of a particular cuisine in a max-heap instead of an array.** + +> Max-heap data structure is a complete binary tree, where the parent nodes are always bigger than the corresponding child nodes, in order to keep the maximum-valued element at the root node of the tree. Here, pushing and popping an element are both logarithmic time operations, but getting the maximum-valued element is a constant time operation. + +We will use priority queues which are internally implemented using a heap. Each element of the priority queue will be an object of `class Food(integer foodRating, string foodName)`. To keep the appropriate element on the top of the priority queue we will use a custom comparator to define the logic for comparing two elements. + +Since the priority queue will keep the elements sorted based on their ratings, you might be thinking: when we modify the rating of food, do we need to remove this food with the old rating from the priority queue to ensure accuracy and then add the food with the new rating? + +For example, if we change the rating of food `X` from `10` to `1`, the old data `(10, X)` in the queue might become the highest-rated food, which it shouldn't be. Should we remove it in this case? + +![image](https://assets.leetcode.com/static_assets/media/original_images/2353/Slide2.jpg) + +First of all, searching for elements in the priority queue is a time-consuming task as in the worst case we would have to iterate over all elements stored in the priority queue. + +Secondly, we can avoid the deletion of old rating elements. + +If we fetch any element `(foodRating, foodName)` from the priority queue then there are only two cases: either the element has the correct `foodRating` or an old rating. +One food can only have one rating, we can verify the fetched element's `foodRating` with the rating stored in `foodRatingMap` against the key `foodName`. If the values don't match, it means the rating for `foodName` was changed and we can safely discard this fetched element of the priority queue and move on to the next highest rating in the priority queue. + +![image](https://assets.leetcode.com/static_assets/media/original_images/2353/Slide3.jpg) + +Also remember that while changing the rating, it is necessary to get the cuisine name of that corresponding food to push the new rating element into the appropriate priority queue. To obtain the cuisine name, we must map the food name to its respective cuisine name as well using another hash map (say `foodCuisineMap`). + +![image](https://assets.leetcode.com/static_assets/media/original_images/2353/Slide4.jpg) + +### Algorithm + +1. Create a class `Food` containing foodRating and foodName properties, and overload less than operator method to keep the highest rated or lexicographically smaller named element on the top in the priority queue. + +2. Create three hash maps: + + - `foodRatingMap`, to store ratings associated with the respective food. + - `foodCuisineMap`, to store the cuisine name of the respective food. + - `cuisineFoodMap`, to store `Food(foodRating, foodName)` elements in a priority queue associated with the respective cuisine. + +3. Initialization. Iterate on all indices of the foods array, and for each index i: + + - Store `(foods[i], ratings[i])` and `(foods[i], cuisines[i])` key-value pairs in `foodRatingMap` and `foodCuisineMap` respectively. + - Insert `Food(ratings[i], foods[i])` element in the priority queue of `cuisines[i]` key of cuisineFoodMap. + +4. Implementing `changeRating(food, newRating)` method: + + - Update new rating in `foodRatingMap`. + - Fetch the cuisine name for `food` from `foodCuisineMap`. + - Insert the `Food(newRating, food)` element in the priority queue of the cuisine name in `cuisineFoodMap`. + +5. Implementing `highestRated(cuisine)` method: + + - Get the top element `(i.e. highestRated)` from the priority queue of `cuisine` in `cuisineFoodMap`. + - If the rating of the top element and the rating of the corresponding food in foodRatingMap are not the same, i.e. `highestRated.foodRating != foodRatingMap[highestRated.foodName]`, then we discard and remove the current top element and fetch the next top element from the priority queue. Repeat this step until ratings are the same. + - Return the food name of the top element, i.e. `highestRated.foodName`. + +## Code in Different Languages + + + + + +```cpp +class Food { +public: + // Store the food's rating. + int foodRating; + // Store the food's name. + string foodName; + + Food(int foodRating, string foodName) { + this->foodRating = foodRating; + this->foodName = foodName; + } + + // Overload the less than operator for comparison + bool operator<(const Food& other) const { + // If food ratings are the same sort on the basis of their name. (lexicographically smaller name food will be on top) + if (foodRating == other.foodRating) { + return foodName > other.foodName; + } + // Sort on the basis of food rating. (bigger rating food will be on top) + return foodRating < other.foodRating; + } +}; + +class FoodRatings { + // Map food with its rating. + unordered_map foodRatingMap; + // Map food with the cuisine it belongs to. + unordered_map foodCuisineMap; + + // Store all food of a cuisine in priority queue (to sort them on ratings/name) + // Priority queue element -> Food: (foodRating, foodName) + unordered_map> cuisineFoodMap; + +public: + FoodRatings(vector& foods, vector& cuisines, vector& ratings) { + for (int i = 0; i < foods.size(); ++i) { + // Store 'rating' and 'cuisine' of current 'food' in 'foodRatingMap' and 'foodCuisineMap' maps. + foodRatingMap[foods[i]] = ratings[i]; + foodCuisineMap[foods[i]] = cuisines[i]; + // Insert the '(rating, name)' element in current cuisine's priority queue. + cuisineFoodMap[cuisines[i]].push(Food(ratings[i], foods[i])); + } + } + + void changeRating(string food, int newRating) { + // Update food's rating in 'foodRating' map. + foodRatingMap[food] = newRating; + // Insert the '(new rating, name)' element in respective cuisine's priority queue. + auto cuisineName = foodCuisineMap[food]; + cuisineFoodMap[cuisineName].push(Food(newRating, food)); + } + + string highestRated(string cuisine) { + // Get the highest rated 'food' of 'cuisine'. + auto highestRated = cuisineFoodMap[cuisine].top(); + + // If the latest rating of 'food' doesn't match the 'rating' on which it was sorted in the priority queue, + // then we discard this element of the priority queue. + while (foodRatingMap[highestRated.foodName] != highestRated.foodRating) { + cuisineFoodMap[cuisine].pop(); + highestRated = cuisineFoodMap[cuisine].top(); + } + // Return name of the highest rated 'food' of 'cuisine'. + return highestRated.foodName; + } +}; +``` + + + + +```java +class Food implements Comparable { + // Store the food's rating. + public int foodRating; + // Store the food's name. + public String foodName; + + public Food(int foodRating, String foodName) { + this.foodRating = foodRating; + this.foodName = foodName; + } + + // Implement the compareTo method for comparison + @Override + public int compareTo(Food other) { + // If food ratings are the same, sort based on their names (lexicographically smaller name food will be on top) + if (foodRating == other.foodRating) { + return foodName.compareTo(other.foodName); + } + // Sort based on food rating (bigger rating food will be on top) + return -1 * Integer.compare(foodRating, other.foodRating); + } +} + +class FoodRatings { + // Map food with its rating. + private Map foodRatingMap; + // Map food with the cuisine it belongs to. + private Map foodCuisineMap; + + // Store all food of a cuisine in a priority queue (to sort them on ratings/name) + // Priority queue element -> Food: (foodRating, foodName) + private Map> cuisineFoodMap; + + public FoodRatings(String[] foods, String[] cuisines, int[] ratings) { + foodRatingMap = new HashMap<>(); + foodCuisineMap = new HashMap<>(); + cuisineFoodMap = new HashMap<>(); + + for (int i = 0; i < foods.length; ++i) { + // Store 'rating' and 'cuisine' of the current 'food' in 'foodRatingMap' and 'foodCuisineMap' maps. + foodRatingMap.put(foods[i], ratings[i]); + foodCuisineMap.put(foods[i], cuisines[i]); + // Insert the '(rating, name)' element into the current cuisine's priority queue. + cuisineFoodMap.computeIfAbsent(cuisines[i], k -> new PriorityQueue<>()).add(new Food(ratings[i], foods[i])); + } + } + + public void changeRating(String food, int newRating) { + // Update food's rating in the 'foodRating' map. + foodRatingMap.put(food, newRating); + // Insert the '(new food rating, food name)' element into the respective cuisine's priority queue. + String cuisineName = foodCuisineMap.get(food); + cuisineFoodMap.get(cuisineName).add(new Food(newRating, food)); + } + + public String highestRated(String cuisine) { + // Get the highest rated 'food' of 'cuisine'. + Food highestRated = cuisineFoodMap.get(cuisine).peek(); + + // If the latest rating of 'food' doesn't match the 'rating' on which it was sorted in the priority queue, + // then we discard this element from the priority queue. + while (foodRatingMap.get(highestRated.foodName) != highestRated.foodRating) { + cuisineFoodMap.get(cuisine).poll(); + highestRated = cuisineFoodMap.get(cuisine).peek(); + } + + // Return the name of the highest-rated 'food' of 'cuisine'. + return highestRated.foodName; + } +} +``` + + + + + +```python +class Food: + def __init__(self, food_rating, food_name): + # Store the food's rating. + self.food_rating = food_rating + # Store the food's name. + self.food_name = food_name + + def __lt__(self, other): + # Overload the less-than operator for comparison. + # If food ratings are the same, sort based on their name (lexicographically smaller name food will be on top). + if self.food_rating == other.food_rating: + return self.food_name < other.food_name + # Sort based on food rating (bigger rating food will be on top). + return self.food_rating > other.food_rating + +class FoodRatings: + def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]): + # Map food with its rating. + self.food_rating_map = {} + # Map food with the cuisine it belongs to. + self.food_cuisine_map = {} + # Store all food of cuisine in a priority queue (to sort them on ratings/name). + # Priority queue element -> Food: (food_rating, food_name) + self.cuisine_food_map = defaultdict(list) + + for i in range(len(foods)): + # Store 'rating' and 'cuisine' of the current 'food' in 'food_rating_map' and 'food_cuisine_map' maps. + self.food_rating_map[foods[i]] = ratings[i] + self.food_cuisine_map[foods[i]] = cuisines[i] + # Insert the '(rating, name)' element into the current cuisine's priority queue. + heapq.heappush(self.cuisine_food_map[cuisines[i]], Food(ratings[i], foods[i])) + + def changeRating(self, food: str, newRating: int) -> None: + # Update food's rating in 'food_rating' map. + self.food_rating_map[food] = newRating + # Insert the '(new rating, name)' element in the respective cuisine's priority queue. + cuisineName = self.food_cuisine_map[food] + heapq.heappush(self.cuisine_food_map[cuisineName], Food(newRating, food)) + + def highestRated(self, cuisine: str) -> str: + # Get the highest rated 'food' of 'cuisine'. + highest_rated = self.cuisine_food_map[cuisine][0] + + # If the latest rating of 'food' doesn't match with the 'rating' on which it was sorted in the priority queue, + # then we discard this element from the priority queue. + while self.food_rating_map[highest_rated.food_name] != highest_rated.food_rating: + heapq.heappop(self.cuisine_food_map[cuisine]) + highest_rated = self.cuisine_food_map[cuisine][0] + + # Return the name of the highest-rated 'food' of 'cuisine'. + return highest_rated.food_name +``` + + + +## Complexity Analysis + +### Time Complexity: $O(nlogn+mlog(n+m))$ + +> **Reason**: Initialization is $O(nlogn)$, and each of the changeRating and highestRated methods take $O(mlog(n+m))$. + +### Space Complexity: $O(N)$ + +> **Reason**:Requires $O(n)$ space for hash maps and $O(n+m)$ space for priority queues. + +## References + +- **LeetCode Problem**: [Design a Food Rating System](https://leetcode.com/problems/design-a-food-rating-system/description/) + +- **Solution Link**: [Design a Food Rating System](https://leetcode.com/problems/design-a-food-rating-system/solutions/) diff --git a/solutions/lc-solutions/2300-2399/2367-number-of-arithmetic-triplets.md b/solutions/lc-solutions/2300-2399/2367-number-of-arithmetic-triplets.md new file mode 100644 index 0000000..7330371 --- /dev/null +++ b/solutions/lc-solutions/2300-2399/2367-number-of-arithmetic-triplets.md @@ -0,0 +1,138 @@ +--- +id: number-of-arithmetic-triples +title: Number of Arithmetic Triplets +sidebar_label: 2367-Number of Arithmetic Triplets +tags: + - Array + - HashTable + - Two Pointers +description: "This is a solution to the Number of Arithmetic Triplets in leetcode" +--- + +## Problem Description + +You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff. A triplet (i, j, k) is an arithmetic triplet if the following conditions are met + +1. `i < j < k,` +2. nums[j] - nums[i] == diff, and +3. nums[k] - nums[j] == diff. + +Return the number of unique arithmetic triplets. + + + + + +### Examples + +**Example 1:** + +``` +Input: nums = [0,1,4,6,7,10], diff = 3 +Output: 2 +Explanation: +(1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3. +(2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3. + +``` +**Example 2:** +``` +Input: nums = [4,5,6,7,8,9], diff = 2 +Output: 2 +Explanation: +(0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2. +(1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2. + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(n*n*n)$ + +*** Space Complexity:** $O(1)$ + +### Constraints + +- `3 <= nums.length <= 200` +- `0 <= nums[i] <= 200` +- `1 <= diff <= 50` + + +### Solution +## Approach +The provided solution for finding arithmetic triplets in an array employs a brute-force approach. It iterates through all possible combinations of three distinct indices (i, j, k) within the array 'nums', ensuring that 'i < j < k'. For each combination, it checks if the difference between the elements at these indices matches the specified difference 'diff'. Specifically, it verifies if the difference between 'nums[j]' and 'nums[i]' equals 'diff' and if the difference between 'nums[k]' and 'nums[j]' also equals 'diff'. If both conditions are met, it counts this triplet as a valid arithmetic triplet. The nested loops ensure that all combinations are considered, making the solution straightforward but not optimal for large input sizes due to its O(n^3) time complexity. +## Code in Different Languages + + + + + +```cpp +#include +using namespace std; + +class Solution { +public: + int arithmeticTriplets(vector& nums, int diff) { + int c = 0; + for (int i = 0; i < nums.size() - 2; i++) { + for (int j = i + 1; j < nums.size() - 1; j++) { + for (int k = j + 1; k < nums.size(); k++) { + if (nums[j] - nums[i] == diff && nums[k] - nums[j] == diff) { + c++; + } + } + } + } + return c; + } +}; + + +``` + + + + +```java +class Solution { + public int arithmeticTriplets(int[] nums, int diff) { + int c=0; + for(int i=0;i + + + +```python +class Solution: + def arithmeticTriplets(self, nums, diff): + c = 0 + for i in range(len(nums) - 2): + for j in range(i + 1, len(nums) - 1): + for k in range(j + 1, len(nums)): + if nums[j] - nums[i] == diff and nums[k] - nums[j] == diff: + c += 1 + return c + + +``` + + + +## References + +- **LeetCode Problem**: [Number of Arithmetic Triplets](https://leetcode.com/problems/number-of-arithmetic-triplets/description/) + +- **Solution Link**: [Number of Arithmetic Triplets](https://leetcode.com/problems/number-of-arithmetic-triplets/post-solution/?submissionId=1267331792) diff --git a/solutions/lc-solutions/2300-2399/2396-strictly-palindromic-number.md b/solutions/lc-solutions/2300-2399/2396-strictly-palindromic-number.md new file mode 100644 index 0000000..f3c759c --- /dev/null +++ b/solutions/lc-solutions/2300-2399/2396-strictly-palindromic-number.md @@ -0,0 +1,80 @@ +--- +id: strictly-palindromic-number +title: Strictly Palindromic Number +level: medium +sidebar_label: Strictly Palindromic Number +tags: + - Math + - Palindrome + - Java +description: "This document provides solutions for the Strictly Palindromic Number problem." +--- + +## Problem Statement + +An integer `n` is strictly palindromic if, for every base `b` between 2 and `n - 2` (inclusive), the string representation of the integer `n` in base `b` is palindromic. + +Given an integer `n`, return `true` if `n` is strictly palindromic and `false` otherwise. + +A string is palindromic if it reads the same forward and backward. + +**Example 1:** + +Input: `n = 9` +Output: `false` + +Explanation: +In base 2: 9 = 1001 (base 2), which is palindromic. +In base 3: 9 = 100 (base 3), which is not palindromic. +Therefore, 9 is not strictly palindromic so we return false. +Note that in bases 4, 5, 6, and 7, n = 9 is also not palindromic. + +**Example 2:** + +Input: `n = 4` +Output: `false` + +Explanation: +We only consider base 2: 4 = 100 (base 2), which is not palindromic. +Therefore, we return false. + +**Constraints:** + +- `4 <= n <= 10^5` + +## Solutions + +### Intuition + +To determine if a number `n` is strictly palindromic, we need to check its representation in all bases from 2 to `n - 2`. If any representation is not palindromic, then `n` is not strictly palindromic. + +### Approach + +1. **Check Base Representation:** + - Convert the number `n` to each base from 2 to `n - 2`. + - Check if the representation in each base is palindromic. + +2. **Early Termination:** + - If any base representation is not palindromic, return `false`. + +### Java + +```java +class Solution { + public boolean isStrictlyPalindromic(int n) { + return false; + } +} +``` +### Python + +```Python + +class Solution: + def isStrictlyPalindromic(self, n: int) -> bool: + return False + +``` + +### Conclusion +For the given problem constraints, the function always returns false. This is because it's mathematically impossible for any number greater than 4 to be strictly palindromic according to the given definition. diff --git a/solutions/lc-solutions/2300-2399/_category_.json b/solutions/lc-solutions/2300-2399/_category_.json new file mode 100644 index 0000000..2e09595 --- /dev/null +++ b/solutions/lc-solutions/2300-2399/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "2300-2399", + "position": 25, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (2300 - 2399)" + } +} diff --git a/solutions/lc-solutions/2400-2499/2402-meeting-room-allocation-problem.md b/solutions/lc-solutions/2400-2499/2402-meeting-room-allocation-problem.md new file mode 100644 index 0000000..d83d2e4 --- /dev/null +++ b/solutions/lc-solutions/2400-2499/2402-meeting-room-allocation-problem.md @@ -0,0 +1,359 @@ +--- +id: meeting-room-allocation-problem +title: Meeting Room Allocation Problem +sidebar_label: 2402-Meeting Room +tags: [dsa, leetcode] +description: Problem solution of Meeting Room Allocation Problem +--- + +## Problem Statement + +### Problem Description + +You are given an integer `n`, representing the number of rooms numbered from `0` to `n - 1`. + +You are also given a 2D integer array `meetings` where `meetings[i] = [starti, endi]` means that a meeting will be held during the half-closed time interval `[starti, endi)`. All the values of `starti` are unique. + +Meetings are allocated to rooms in the following manner: +- Each meeting will occur in the unused room with the lowest number. +- If there are no available rooms, the meeting will be delayed until a room becomes free. The delayed meeting should have the same duration as the original meeting. +- When a room becomes unused, meetings with an earlier original start time should be given the room. + +Return the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number. + +A half-closed interval `[a, b)` is the interval between `a` and `b` including `a` and not `b`. + +### Examples + +#### Example 1 +``` +Input: n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]] +Output: 0 +Explanation: +- At time 0, both rooms are not being used. The first meeting starts in room 0. +- At time 1, only room 1 is not being used. The second meeting starts in room 1. +- At time 2, both rooms are being used. The third meeting is delayed. +- At time 3, both rooms are being used. The fourth meeting is delayed. +- At time 5, the meeting in room 1 finishes. The third meeting starts in room 1 for the time period [5,10). +- At time 10, the meetings in both rooms finish. The fourth meeting starts in room 0 for the time period [10,11). +Both rooms 0 and 1 held 2 meetings, so we return 0. +``` + +### Constraints + +- `1 <= n <= 100` +- `1 <= meetings.length <= 10^4` +- `meetings[i].length == 2` +- `0 <= starti < endi <= 5 * 10^5` +- All the values of `starti` are unique. + +## Solution of Given Problem + +### Intuition and Approach + +The goal is to efficiently schedule meetings in available rooms and identify the room with the most bookings. The approach involves the following steps: + +1. **Initialize Data Structures**: + - `ans`: A vector to keep track of the number of meetings booked for each room. + - `q`: A priority queue to store ongoing meetings sorted by their end times. + - `freeRooms`: A priority queue to store available rooms sorted by their room numbers. + +2. **Sort Meetings by Start Time**: + - Sort the `meetings` array based on the start time of each meeting. + +3. **Iterate Through Meetings**: + - For each meeting in the sorted `meetings` array: + - Check if any ongoing meetings have ended by comparing their end times with the start time of the current meeting. + - If there are such meetings, free up the corresponding rooms and update the end times of ongoing meetings. + - If there are no available rooms, dequeue the meeting that ends earliest from `q`, calculate the end time of the next meeting, increment the count of meetings for the corresponding room, and enqueue the next meeting. + - If there are available rooms, assign the current meeting to an available room, increment the count of meetings for the corresponding room, and dequeue the room from `freeRooms`. + +4. **Find Room with Maximum Bookings**: + - After processing all meetings, iterate through the `ans` vector to find the room with the maximum number of bookings. + - Return the room number with the maximum bookings. + - Handle tiebreakers by returning the room with the lowest number in case of multiple rooms with the same maximum number of bookings. + +5. **Return Result**: + - Return the room number with the maximum bookings as the result. + +### Approaches + +#### Codes in Different Languages + + + + + ```javascript + class MeetingRoomAllocator { + mostBooked(n, meetings) { + meetings.sort((a, b) => a[0] - b[0]); + + const pq = new MinPriorityQueue({ priority: x => x[1] }); + const freeRooms = new MinPriorityQueue({ priority: x => x }); + const ans = Array(n).fill(0); + + for (let i = 0; i < n; i++) freeRooms.enqueue(i); + + for (const [start, end] of meetings) { + while (!pq.isEmpty() && pq.front().element[1] <= start) { + freeRooms.enqueue(pq.dequeue().element[0]); + } + + if (freeRooms.isEmpty()) { + const [room, endTime] = pq.dequeue().element; + pq.enqueue([room, endTime + (end - start)]); + ans[room]++; + } else { + const room = freeRooms.dequeue().element; + pq.enqueue([room, end]); + ans[room]++; + } + } + + let maxMeetings = 0; + let roomWithMaxMeetings = 0; + + for (let i = 0; i < n; i++) { + if (ans[i] > maxMeetings) { + maxMeetings = ans[i]; + roomWithMaxMeetings = i; + } + } + + return roomWithMaxMeetings; + } + } + ``` + + + + ```typescript + class MeetingRoomAllocator { + mostBooked(n: number, meetings: number[][]): number { + meetings.sort((a, b) => a[0] - b[0]); + + const pq = new MinPriorityQueue({ priority: (x: [number, number]) => x[1] }); + const freeRooms = new MinPriorityQueue({ priority: (x: number) => x }); + const ans = Array(n).fill(0); + + for (let i = 0; i < n; i++) freeRooms.enqueue(i); + + for (const [start, end] of meetings) { + while (!pq.isEmpty() && pq.front().element[1] <= start) { + freeRooms.enqueue(pq.dequeue().element[0]); + } + + if (freeRooms.isEmpty()) { + const [room, endTime] = pq.dequeue().element; + pq.enqueue([room, endTime + (end - start)]); + ans[room]++; + } else { + const room = freeRooms.dequeue().element; + pq.enqueue([room, end]); + ans[room]++; + } + } + + let maxMeetings = 0; + let roomWithMaxMeetings = 0; + + for (let i = 0; i < n; i++) { + if (ans[i] > maxMeetings) { + maxMeetings = ans[i]; + roomWithMaxMeetings = i; + } + } + + return roomWithMaxMeetings; + } + } + ``` + + + + ```python + import heapq + + class MeetingRoomAllocator: + def mostBooked(self, n: int, meetings: List[List[int]]) -> int: + meetings.sort() + free_rooms = list(range(n)) + heapq.heapify(free_rooms) + pq = [] + ans = [0] * n + + for start, end in meetings: + while pq and pq[0][0] <= start: + end_time, room = heapq.heappop(pq) + heapq.heappush(free_rooms, room) + + if free_rooms: + room = heapq.heappop(free_rooms) + heapq.heappush(pq, (end, room)) + else: + end_time, room = heapq.heappop(pq) + heapq.heappush(pq, (end_time + (end - start), room)) + + ans[room] += 1 + + max_meetings = max(ans) + return ans.index(max_meetings) + ``` + + + + ```java + import java.util.*; + + class MeetingRoomAllocator { + public int mostBooked(int n, int[][] meetings) { + Arrays.sort(meetings, Comparator.comparingInt(a -> a[0])); + PriorityQueue pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1])); + PriorityQueue freeRooms = new PriorityQueue<>(); + int[] ans = new int[n]; + + for (int i = 0; i < n; i++) freeRooms.add(i); + + for (int[] meeting : meetings) { + int start = meeting[0]; + int end = meeting[1 + +]; + + while (!pq.isEmpty() && pq.peek()[1] <= start) { + freeRooms.add(pq.poll()[0]); + } + + if (freeRooms.isEmpty()) { + int[] nextMeeting = pq.poll(); + pq.add(new int[]{nextMeeting[0], nextMeeting[1] + (end - start)}); + ans[nextMeeting[0]]++; + } else { + int room = freeRooms.poll(); + pq.add(new int[]{room, end}); + ans[room]++; + } + } + + int maxMeetings = 0; + int roomWithMaxMeetings = 0; + + for (int i = 0; i < n; i++) { + if (ans[i] > maxMeetings) { + maxMeetings = ans[i]; + roomWithMaxMeetings = i; + } + } + + return roomWithMaxMeetings; + } + } + ``` + + + + ```cpp + #include + #include + #include + using namespace std; + + class Solution { + class comparator { + public: + bool operator()(pair a, pair b) const { + if (a.second == b.second) + return a.first > b.first; + return a.second > b.second; + } + }; + + public: + int mostBooked(int n, vector> &meetings) { + sort(meetings.begin(), meetings.end(), + [](const vector &a, const vector &b) { + return a[0] < b[0]; + }); + + priority_queue, vector>, comparator> q; + priority_queue, greater> freeRooms; + vector ans(n); + + for (int i = 0; i < n; i++) + freeRooms.push(i); + + for (int i = 0; i < meetings.size(); i++) { + while (!q.empty() && q.top().second <= meetings[i][0]) { + auto p = q.top(); + q.pop(); + freeRooms.push(p.first); + } + + if (freeRooms.empty()) { + auto p = q.top(); + q.pop(); + long long timeForNextMeet = meetings[i][1] - meetings[i][0]; + long long endTime = p.second + timeForNextMeet; + ans[p.first]++; + q.push({p.first, endTime}); + } else { + q.push({freeRooms.top(), meetings[i][1]}); + ans[freeRooms.top()]++; + freeRooms.pop(); + } + } + + int maxi = 0; + int index = 0; + for (int k = 0; k < n; k++) { + if (ans[k] > maxi) { + maxi = ans[k]; + index = k; + } + } + + return index; + } + }; + ``` + + + +### Complexity Analysis + +#### Time Complexity + +- Sorting the `meetings` array: $O(n \log n)$, where $n$ is the number of meetings. +- Iterating through each meeting: $O(n)$, where $n$ is the number of meetings. +- Inside the loop, operations like pushing/popping elements from priority queues have logarithmic time complexity: \(O(\log n)\) per iteration. +- Finding the room with maximum bookings: $O(n)$, where $n$ is the number of rooms. + +Therefore, the overall time complexity is $O(n \log n) + O(n \log n) + O(n) = O(n \log n)$. + +#### Space Complexity + +- Priority queue `q` to store ongoing meetings: $O(n)$. +- Priority queue `freeRooms` to store available rooms: $O(n)$. +- Vector `ans` to keep track of the number of meetings booked for each room: $(O(n)$. + +Therefore, the overall space complexity is $O(n)$. + +## Video Explanation of Given Problem + + + +--- + +

Authors:

+ +
+{['sreevidya-16'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/2400-2499/2404-Most-Frequent-Even-Element.md b/solutions/lc-solutions/2400-2499/2404-Most-Frequent-Even-Element.md new file mode 100644 index 0000000..d895a05 --- /dev/null +++ b/solutions/lc-solutions/2400-2499/2404-Most-Frequent-Even-Element.md @@ -0,0 +1,324 @@ +--- +id: Most-Frequent-Even-Element +title: Most Frequent Even Element +sidebar_label: 2404-Most Frequent Even Element +tags: [dsa, leetcode] +description: Problem solution of Most Frequent Even Element +--- + +## Problem Statement + +### Problem Description + +Given an integer array nums, return the most frequent even element. + +If there is a tie, return the smallest one. If there is no such element, return -1. + + +### Examples + +#### Example 1 +``` +Input: nums = [0,1,2,2,4,4,1] +Output: 2 +Explanation: +The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most. +We return the smallest one, which is 2. +``` + +### Example 2 +``` +Input: nums = [4,4,4,9,2,4] +Output: 4 +Explanation: 4 is the even element appears the most. +``` + +### Example 3 +``` +Input: nums = [29,47,21,41,13,37,25,7] +Output: -1 +Explanation: There is no even element +``` + +### Constraints + +-` 1 <= nums.length <= 2000` +- `0 <= nums[i] <= 105` + +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +Brute Force Approach: Iterate through the array and count the frequency of each even number using a dictionary or a similar data structure. +Iterate through the frequency map to find the even number with the highest frequency. In case of a tie, select the smallest even number. +#### Codes in Different Languages + + + + + +```cpp +#include +#include +#include +using namespace std; + +int mostFrequentEven(vector& nums) { + unordered_map freq; + for (int num : nums) { + if (num % 2 == 0) { + freq[num]++; + } + } + + int maxFreq = 0; + int res = -1; + for (auto& [num, count] : freq) { + if (count > maxFreq || (count == maxFreq && num < res)) { + maxFreq = count; + res = num; + } + } + + return res; +} + +int main() { + vector nums = {0, 1, 2, 2, 4, 4, 1}; + cout << mostFrequentEven(nums) << endl; // Output: 2 + return 0; +} + +``` + + + + +```java +import java.util.HashMap; + +public class Main { + public static int mostFrequentEven(int[] nums) { + HashMap freq = new HashMap<>(); + for (int num : nums) { + if (num % 2 == 0) { + freq.put(num, freq.getOrDefault(num, 0) + 1); + } + } + + int maxFreq = 0; + int res = -1; + for (int num : freq.keySet()) { + int count = freq.get(num); + if (count > maxFreq || (count == maxFreq && num < res)) { + maxFreq = count; + res = num; + } + } + + return res; + } + + public static void main(String[] args) { + int[] nums = {0, 1, 2, 2, 4, 4, 1}; + System.out.println(mostFrequentEven(nums)); // Output: 2 + } +} + + + + +``` + + + + + + +```python +from collections import defaultdict + +def most_frequent_even(nums): + freq = defaultdict(int) + for num in nums: + if num % 2 == 0: + freq[num] += 1 + + max_freq = 0 + result = -1 + for num, count in freq.items(): + if count > max_freq or (count == max_freq and num < result): + max_freq = count + result = num + + return result + +nums = [0, 1, 2, 2, 4, 4, 1] +print(most_frequent_even(nums)) # Output: 2 + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(n^2)$ +- due to the nested loop for counting frequency and finding the maximum. +- Space Complexity: $O(n)$ +- for storing the frequency of numbers. + + + + +### Approach 2: Optimized approach + +Optimized Approach: Similar to the brute force method, but the counting and maximum frequency determination are optimized. +Use a single pass to find the most frequent even element and track the maximum frequency simultaneously. + +#### Code in Different Languages + + + + + +```cpp +#include +#include +#include +using namespace std; + +int mostFrequentEven(vector& nums) { + unordered_map freq; + int maxFreq = 0; + int res = -1; + + for (int num : nums) { + if (num % 2 == 0) { + freq[num]++; + if (freq[num] > maxFreq || (freq[num] == maxFreq && num < res)) { + maxFreq = freq[num]; + res = num; + } + } + } + + return res; +} + +int main() { + vector nums = {0, 1, 2, 2, 4, 4, 1}; + cout << mostFrequentEven(nums) << endl; // Output: 2 + return 0; +} + + + +``` + + + + +```java +import java.util.HashMap; + +public class Main { + public static int mostFrequentEven(int[] nums) { + HashMap freq = new HashMap<>(); + int maxFreq = 0; + int res = -1; + + for (int num : nums) { + if (num % 2 == 0) { + freq.put(num, freq.getOrDefault(num, 0) + 1); + if (freq.get(num) > maxFreq || (freq.get(num) == maxFreq && num < res)) { + maxFreq = freq.get(num); + res = num; + } + } + } + + return res; + } + + public static void main(String[] args) { + int[] nums = {0, 1, 2, 2, 4, 4, 1}; + System.out.println(mostFrequentEven(nums)); // Output: 2 + } +} + + +``` + + + + + + +```python +from collections import defaultdict + +def most_frequent_even(nums): + freq = defaultdict(int) + max_freq = 0 + result = -1 + + for num in nums: + if num % 2 == 0: + freq[num] += 1 + if freq[num] > max_freq or (freq[num] == max_freq and num < result): + max_freq = freq[num] + result = num + + return result + +nums = [0, 1, 2, 2, 4, 4, 1] +print(most_frequent_even(nums)) # Output: 2 + + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ +- due to a single pass through the array. +- Space Complexity: $O(n)$ +- for storing the frequency map. +- This approach is efficient and straightforward. + + + + + +## Video Explanation of Given Problem + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
+ diff --git a/solutions/lc-solutions/2400-2499/2409-Count-Days-Spent-Together.md b/solutions/lc-solutions/2400-2499/2409-Count-Days-Spent-Together.md new file mode 100644 index 0000000..8f2310a --- /dev/null +++ b/solutions/lc-solutions/2400-2499/2409-Count-Days-Spent-Together.md @@ -0,0 +1,336 @@ +--- +id: Count-Days-Spent-Together +title: Count Days Spent Together +sidebar_label: 2409-Count Days Spent Together +tags: [dsa, leetcode] +description: Problem solution of Count Days Spent Together +--- + +## Problem Statement + +### Problem Description + +Alice and Bob are traveling to Rome for separate business meetings. + +You are given 4 strings arriveAlice, leaveAlice, arriveBob, and leaveBob. Alice will be in the city from the dates arriveAlice to leaveAlice (inclusive), while Bob will be in the city from the dates arriveBob to leaveBob (inclusive). Each will be a 5-character string in the format "MM-DD", corresponding to the month and day of the date. + +Return the total number of days that Alice and Bob are in Rome together. + +You can assume that all dates occur in the same calendar year, which is not a leap year. + +### Examples + +#### Example 1 +``` +Input: arriveAlice = "08-15", leaveAlice = "08-18", arriveBob = "08-16", leaveBob = "08-19" +Output: 3 +Explanation: Alice will be in Rome from August 15 to August 18. Bob will be in Rome from August 16 to August 19. They are both in Rome together on August 16th, 17th, and 18th, so the answer is 3. +``` + +### Example 2 +``` +Input: arriveAlice = "10-01", leaveAlice = "10-31", arriveBob = "11-01", leaveBob = "12-31" +Output: 0 +Explanation: There is no day when Alice and Bob are in Rome together, so we return 0. +``` + +### Constraints + +- `All dates are provided in the format "MM-DD".` +- `Alice and Bob's arrival dates are earlier than or equal to their leaving dates.` +- `The given dates are valid dates of a non-leap year.` + +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +Brute Force Approach: Check each day in the range of Alice’s stay and see if it falls within Bob’s stay. +#### Codes in Different Languages + + + + + +```cpp +#include +#include +#include +#include +#include + +int countOverlapBruteForce(std::string arriveAlice, std::string leaveAlice, std::string arriveBob, std::string leaveBob) { + auto date_to_tm = [](const std::string& date_str) { + std::tm t = {}; + std::stringstream ss(date_str); + ss >> std::get_time(&t, "%m-%d"); + t.tm_year = 2024 - 1900; // Assume the year 2024 + return t; + }; + + auto startAlice = date_to_tm(arriveAlice); + auto endAlice = date_to_tm(leaveAlice); + auto startBob = date_to_tm(arriveBob); + auto endBob = date_to_tm(leaveBob); + + std::tm currentDay = startAlice; + int count = 0; + + while (std::mktime(¤tDay) <= std::mktime(&endAlice)) { + if (std::mktime(¤tDay) >= std::mktime(&startBob) && std::mktime(¤tDay) <= std::mktime(&endBob)) { + count++; + } + currentDay.tm_mday++; + std::mktime(¤tDay); + } + + return count; +} + +int main() { + std::cout << countOverlapBruteForce("08-15", "08-18", "08-16", "08-19") << std::endl; // Output: 3 +} + + +``` + + + + +```java +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; + +public class Main { + public static int countOverlapBruteForce(String arriveAlice, String leaveAlice, String arriveBob, String leaveBob) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd"); + LocalDate startAlice = LocalDate.parse(arriveAlice, formatter); + LocalDate endAlice = LocalDate.parse(leaveAlice, formatter); + LocalDate startBob = LocalDate.parse(arriveBob, formatter); + LocalDate endBob = LocalDate.parse(leaveBob, formatter); + + int count = 0; + LocalDate currentDay = startAlice; + + while (!currentDay.isAfter(endAlice)) { + if (!currentDay.isBefore(startBob) && !currentDay.isAfter(endBob)) { + count++; + } + currentDay = currentDay.plusDays(1); + } + + return count; + } + + public static void main(String[] args) { + System.out.println(countOverlapBruteForce("08-15", "08-18", "08-16", "08-19")); // Output: 3 + } +} + + + + + +``` + + + + + + +```python +from datetime import datetime, timedelta + +def count_overlap_brute_force(arriveAlice, leaveAlice, arriveBob, leaveBob): + def date_from_str(date_str): + return datetime.strptime(date_str, "%m-%d") + + start_alice = date_from_str(arriveAlice) + end_alice = date_from_str(leaveAlice) + start_bob = date_from_str(arriveBob) + end_bob = date_from_str(leaveBob) + + count = 0 + current_day = start_alice + + while current_day <= end_alice: + if start_bob <= current_day <= end_bob: + count += 1 + current_day += timedelta(days=1) + + return count + +# Example usage +print(count_overlap_brute_force("08-15", "08-18", "08-16", "08-19")) # Output: 3 + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(n)$ +- where n is the number of days in Alice’s stay (or Bob’s, whichever is longer). This is because we check each day individually. +- Space Complexity: $O(1)$ +- as we only need a constant amount of extra space to store dates and counters. + + + +### Approach 2: Optimized approach + +Optimized Approach: Calculate the overlapping period directly by finding the intersection of the two date ranges. +#### Code in Different Languages + + + + + +```cpp +#include +#include +#include +#include +#include + +int countOverlapOptimized(std::string arriveAlice, std::string leaveAlice, std::string arriveBob, std::string leaveBob) { + auto date_to_tm = [](const std::string& date_str) { + std::tm t = {}; + std::stringstream ss(date_str); + ss >> std::get_time(&t, "%m-%d"); + t.tm_year = 2024 - 1900; // Assume the year 2024 + return t; + }; + + auto startAlice = date_to_tm(arriveAlice); + auto endAlice = date_to_tm(leaveAlice); + auto startBob = date_to_tm(arriveBob); + auto endBob = date_to_tm(leaveBob); + + std::tm startOverlap = (std::mktime(&startAlice) > std::mktime(&startBob)) ? startAlice : startBob; + std::tm endOverlap = (std::mktime(&endAlice) < std::mktime(&endBob)) ? endAlice : endBob; + + if (std::mktime(&startOverlap) > std::mktime(&endOverlap)) { + return 0; + } + + double days = std::difftime(std::mktime(&endOverlap), std::mktime(&startOverlap)) / (60 * 60 * 24) + 1; + return static_cast(days); +} + +int main() { + std::cout << countOverlapOptimized("08-15", "08-18", "08-16", "08-19") << std::endl; // Output: 3 +} + + + + +``` + + + + +```java +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +public class Main { + public static int countOverlapOptimized(String arriveAlice, String leaveAlice, String arriveBob, String leaveBob) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd"); + LocalDate startAlice = LocalDate.parse(arriveAlice, formatter); + LocalDate endAlice = LocalDate.parse(leaveAlice, formatter); + LocalDate startBob = LocalDate.parse(arriveBob, formatter); + LocalDate endBob = LocalDate.parse(leaveBob, formatter); + + LocalDate startOverlap = startAlice.isAfter(startBob) ? startAlice : startBob; + LocalDate endOverlap = endAlice.isBefore(endBob) ? endAlice : endBob; + + if (startOverlap.isAfter(endOverlap)) { + return 0; + } + + return (int) (endOverlap.toEpochDay() - startOverlap.toEpochDay() + 1); + } + + public static void main(String[] args) { + System.out.println(countOverlapOptimized("08-15", "08-18", "08-16", "08-19")); // Output: 3 + } +} + + +``` + + + + + + +```python +from datetime import datetime + +def count_overlap_optimized(arriveAlice, leaveAlice, arriveBob, leaveBob): + def date_from_str(date_str): + return datetime.strptime(date_str, "%m-%d") + + start_alice = date_from_str(arriveAlice) + end_alice = date_from_str(leaveAlice) + start_bob = date_from_str(arriveBob) + end_bob = date_from_str(leaveBob) + + # Calculate the overlapping period + start_overlap = max(start_alice, start_bob) + end_overlap = min(end_alice, end_bob) + + if start_overlap > end_overlap: + return 0 + + return (end_overlap - start_overlap).days + 1 + +# Example usage +print(count_overlap_optimized("08-15", "08-18", "08-16", "08-19")) # Output: 3 + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(1)$ +- since the overlap calculation involves a constant number of operations regardless of the date range. +- Space Complexity: $O(1)$ +- as it only requires a fixed amount of additional space for date comparisons and calculations. + + + + + +## Video Explanation of Given Problem + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
+ diff --git a/solutions/lc-solutions/2400-2499/2413-Smallest-Even-Multiple.md b/solutions/lc-solutions/2400-2499/2413-Smallest-Even-Multiple.md new file mode 100644 index 0000000..3e21015 --- /dev/null +++ b/solutions/lc-solutions/2400-2499/2413-Smallest-Even-Multiple.md @@ -0,0 +1,140 @@ +--- +id: smalllest-even-multiple +title: Smallest Even Multiple +sidebar_label: 2413-Smallest-Even-Multiple +tags: + - Math + - Number Theory +--- + +## Problem Description +Given a positive integer `n`, return the smallest positive integer that is a multiple of both `2` and `n`. + + +### Example + +**Example 1:** + + +``` +Input: n = 5 +Output: 10 +Explanation: The smallest multiple of both 5 and 2 is 10. +``` +**Example 2:** +``` +Input: n = 6 +Output: 6 +Explanation: The smallest multiple of both 6 and 2 is 6. Note that a number is a multiple of itself. + +``` +### Constraints + +- `1 <= n <= 150` + +## Solution Approach + +### Intuition: + +To efficiently determine the smallest even multiple +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + class Solution { + smallestEvenMultiple(n) { + for (let i = 1; i <= 2 * n; i++) { + const multiply = n * i; + if (multiply % 2 === 0) { + return multiply; + } + } + return -1; + } +} + + ``` + + + + + ```typescript + class Solution { + smallestEvenMultiple(n: number): number { + for (let i = 1; i <= 2 * n; i++) { + const multiply = n * i; + if (multiply % 2 === 0) { + return multiply; + } + } + return -1; + } +} + + ``` + + + + + ```python + class Solution: + def smallestEvenMultiple(self, n: int) -> int: + for i in range(1, 2 * n + 1): + multiply = n * i + if multiply % 2 == 0: + return multiply + return -1 + + ``` + + + + + ```java + public class Solution { + public int smallestEvenMultiple(int n) { + for (int i = 1; i <= 2 * n; i++) { + int multiply = n * i; + if (multiply % 2 == 0) { + return multiply; + } + } + return -1; + } +} + + ``` + + + + + ```cpp +class Solution { +public: + int smallestEvenMultiple(int n) { + for(int i=1; i<=2*n; i++){ + int multiply = n*i; + if(multiply%2==0) { + return multiply; + break; + + } + } + return -1; + } +}; +``` + + + +#### Complexity Analysis + +- Time Complexity: $$O(2*n)$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(2*n)$$ because we are iterating from 1 to 2*n. +- The space complexity is $$O(1)$$ because we are not using any extra space. + diff --git a/solutions/lc-solutions/2400-2499/2414-length-of-the-longest-alphabetical-continuous-substring.md b/solutions/lc-solutions/2400-2499/2414-length-of-the-longest-alphabetical-continuous-substring.md new file mode 100644 index 0000000..4c30c65 --- /dev/null +++ b/solutions/lc-solutions/2400-2499/2414-length-of-the-longest-alphabetical-continuous-substring.md @@ -0,0 +1,307 @@ +--- +id: length-of-the-longest-alphabetical-continuous-substring +title: Length of the Longest Alphabetical Continuous Substring +sidebar_label: 2414. Length of the Longest Alphabetical Continuous Substring +tags: +- string +description: "This is a solution to the Length of the Longest Alphabetical Continuous Substring problem on LeetCode." +--- + +## Problem Description +An alphabetical continuous string is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string "abcdefghijklmnopqrstuvwxyz". + +For example, "abc" is an alphabetical continuous string, while "acb" and "za" are not. +Given a string s consisting of lowercase letters only, return the length of the longest alphabetical continuous substring. + +### Examples + +**Example 1:** + +``` +Input: s = "abacaba" +Output: 2 +Explanation: There are 4 distinct continuous substrings: "a", "b", "c" and "ab". +"ab" is the longest continuous substring. +``` + +**Example 2:** +``` +Input: s = "abcde" +Output: 5 +Explanation: "abcde" is the longest continuous substring. +``` + +### Constraints + +- `1 <= s.length <= 10^5` + +## Solution for Frequency of the Longest Alphabetical Continuous Substring +### Approach +1. **Initialize Variables**: + - `len`: Current length of the contiguous substring. + - `maxLen`: Maximum length of the contiguous substring found so far. + - `prev`: ASCII value of the previous character. + - `i`: Current index in the string. + +2. **Edge Case**: + - If the string length is 1, return 1 because the longest contiguous substring is the string itself. + +3. **Iterate Through the String**: + - Use a `while` loop to iterate through the string. + - If `prev` is `-1` (indicating the start), set `prev` to the ASCII value of the current character and increment `i`. + - If the ASCII value of the current character minus `prev` equals 1, it means the characters are in consecutive order. + - Continue this check until the characters are no longer in consecutive order. + - Update `maxLen` with the length of the contiguous substring found. + - Reset `prev` to `-1` to start checking the next possible contiguous substring. + - If the characters are not in consecutive order, update `prev` to the ASCII value of the current character and increment `i`. + +4. **Return Result**: + - After iterating through the string, return `maxLen`. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + var longestContinuousSubstring = function(s) { + let len = 1; + let maxLen = 1; + let prev = -1; + let i = 0; + + if (s.length === 1) return 1; + + while (i < s.length) { + if (prev === -1) { + prev = s.charCodeAt(i); + i++; + } else if (s.charCodeAt(i) - prev === 1) { + let k = i; + while (i < s.length && s.charCodeAt(i) - prev === 1) { + prev = s.charCodeAt(i); + i++; + } + maxLen = Math.max(maxLen, i - k + 1); + prev = -1; + } else { + prev = s.charCodeAt(i); + i++; + } + } + + return maxLen; + }; + + const input = "abacaba" + + const output = longestContinuousSubstring(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(n) $ + - Space Complexity: $ O(1) $ + + ## Code in Different Languages + + + + ```javascript + var longestContinuousSubstring = function(s) { + let len = 1; + let maxLen = 1; + let prev = -1; + let i = 0; + + if (s.length === 1) return 1; + + while (i < s.length) { + if (prev === -1) { + prev = s.charCodeAt(i); + i++; + } else if (s.charCodeAt(i) - prev === 1) { + let k = i; + while (i < s.length && s.charCodeAt(i) - prev === 1) { + prev = s.charCodeAt(i); + i++; + } + maxLen = Math.max(maxLen, i - k + 1); + prev = -1; + } else { + prev = s.charCodeAt(i); + i++; + } + } + + return maxLen; +}; + + ``` + + + + + ```typescript + function longestContinuousSubstring(s: string): number { + let len = 1; + let maxLen = 1; + let prev: number | null = -1; + let i = 0; + + if (s.length === 1) return 1; + + while (i < s.length) { + if (prev === -1) { + prev = s.charCodeAt(i); + i++; + } else if (s.charCodeAt(i) - prev === 1) { + let k = i; + while (i < s.length && s.charCodeAt(i) - prev === 1) { + prev = s.charCodeAt(i); + i++; + } + maxLen = Math.max(maxLen, i - k + 1); + prev = -1; + } else { + prev = s.charCodeAt(i); + i++; + } + } + + return maxLen; +} + + ``` + + + + ```python + class Solution: + def longestContinuousSubstring(self, s: str) -> int: + len = 1 + maxLen = 1 + prev = -1 + i = 0 + + if len(s) == 1: + return 1 + + while i < len(s): + if prev == -1: + prev = ord(s[i]) + i += 1 + elif ord(s[i]) - prev == 1: + k = i + while i < len(s) and ord(s[i]) - prev == 1: + prev = ord(s[i]) + i += 1 + maxLen = max(maxLen, i - k + 1) + prev = -1 + else: + prev = ord(s[i]) + i += 1 + + return maxLen + + ``` + + + + + ```java + class Solution { + public int longestContinuousSubstring(String s) { + int len = 1; + int maxLen = 1; + int prev = -1; + int i = 0; + + if (s.length() == 1) return 1; + + while (i < s.length()) { + if (prev == -1) { + prev = s.charAt(i); + i++; + } else if (s.charAt(i) - prev == 1) { + int k = i; + while (i < s.length() && s.charAt(i) - prev == 1) { + prev = s.charAt(i); + i++; + } + maxLen = Math.max(maxLen, i - k + 1); + prev = -1; + } else { + prev = s.charAt(i); + i++; + } + } + + return maxLen; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + int longestContinuousSubstring(string s) { + int len = 1; + int maxLen = 1; + int prev = -1; + int i = 0; + + if (s.size() == 1) return 1; + + while (i < s.size()) { + if (prev == -1) { + prev = s[i]; + i++; + } else if (s[i] - prev == 1) { + int k = i; + while (i < s.size() && s[i] - prev == 1) { + prev = s[i]; + i++; + } + maxLen = max(maxLen, i - k + 1); + prev = -1; + } else { + prev = s[i]; + i++; + } + } + + return maxLen; + } +}; + + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Length of the Longest Alphabetical Continuous Substring](https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring/description/) + + diff --git a/solutions/lc-solutions/2400-2499/2418-sort-the-people.md b/solutions/lc-solutions/2400-2499/2418-sort-the-people.md new file mode 100644 index 0000000..f616e8a --- /dev/null +++ b/solutions/lc-solutions/2400-2499/2418-sort-the-people.md @@ -0,0 +1,136 @@ +--- +id: sort-the-people +title: Sort the People +sidebar_label: 2418-Sort the People +tags: + - Array + - Sorting + - String + +description: "This is a solution to the sort the people in leetcode" +--- + +## Problem Description + +You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n. + +For each index i, names[i] and heights[i] denote the name and height of the ith person. + +Return names sorted in descending order by the people's heights. + + + +### Examples + +**Example 1:** + +``` +Input: names = ["Mary","John","Emma"], heights = [180,165,170] +Output: ["Mary","Emma","John"] +Explanation: Mary is the tallest, followed by Emma and John. +``` +**Example 2:** +``` +Input: names = ["Alice","Bob","Bob"], heights = [155,185,150] +Output: ["Bob","Alice","Bob"] +Explanation: The first Bob is the tallest, followed by Alice and the second Bob. + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(n)$ + +*** Space Complexity:** $O(n)$ + +### Constraints + +- `n == names.length == heights.length` +- `1 <= n <= 103` +- `1 <= names[i].length <= 20` +- `1 <= heights[i] <= 105` + + +### Solution +## Approach +To solve the problem of sorting people by height in descending order while maintaining the association between names and heights, we can take the following approach: + +1. Pairing Heights with Names: First, create a list of pairs, where each pair consists of a height and the corresponding name's index. This pairing allows us to keep track of the original positions of the names. + +2. Sorting the Pairs: Sort the list of pairs in descending order based on heights. Since each pair contains the height and the index, sorting by the first element (height) ensures that the names will be ordered by height. + +3. Extracting the Sorted Names: After sorting the pairs, iterate through the sorted list to collect the names in the new order. Use the index from each pair to access the correct name from the original list. + +This method ensures that the names are sorted according to the heights in descending order, while keeping the names and heights correctly associated. The approach is efficient and straightforward, leveraging the ability to sort lists of pairs and then map back to the original names. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + std::vector sortPeople(std::vector& names, std::vector& heights) { + std::vector> combined; + for (int i = 0; i < names.size(); ++i) { + combined.push_back({heights[i], i}); + } + std::sort(combined.begin(), combined.end(), std::greater<>()); + + std::vector sortedNames; + for (const auto& pair : combined) { + sortedNames.push_back(names[pair.second]); + } + return sortedNames; + } +}; + + +``` + + + + +```java +class Solution { + public List sortPeople(String[] names, int[] heights) { + List combined = new ArrayList<>(); + for (int i = 0; i < names.length; i++) { + combined.add(new int[]{heights[i], i}); + } + combined.sort((a, b) -> Integer.compare(b[0], a[0])); + + List sortedNames = new ArrayList<>(); + for (int[] pair : combined) { + sortedNames.add(names[pair[1]]); + } + return sortedNames; + } +} +``` + + + + +```python +class Solution: + def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: + res=[] + for i in range(len(names)): + res.append( [heights[i],names[i]] ) + res.sort(reverse=True) + res1=[] + for i in range(len(names)): + res1.append(res[i][1]) + return res1 + +``` + + + +## References + +- **LeetCode Problem**: [Sort the People](https://leetcode.com/problems/sort-the-people/description/) + +- **Solution Link**: [Sort the People](https://leetcode.com/problems/sort-the-people/post-solution/?submissionId=1220299194) diff --git a/solutions/lc-solutions/2400-2499/2427-Number-Of-Common-Factors.md b/solutions/lc-solutions/2400-2499/2427-Number-Of-Common-Factors.md new file mode 100644 index 0000000..6bc5405 --- /dev/null +++ b/solutions/lc-solutions/2400-2499/2427-Number-Of-Common-Factors.md @@ -0,0 +1,147 @@ +--- +id: number-of-common-factors +title: Number of Common Factors +sidebar_label: 2427. Number of Common Factors +tags: +- Math +- Enumeration +- Number Theory +description: "This is a solution to the Number of Common Factors" +--- + +## Problem Description +Given two positive integers a and b, return the number of common factors of a and b. + +An integer x is a common factor of a and b if x divides both a and b. + + +### Examples + +**Example 1:** + +``` +Input: a = 12, b = 6 +Output: 4 +Explanation: The common factors of 12 and 6 are 1, 2, 3, 6. +``` + +**Example 2:** +``` +Input: a = 25, b = 30 +Output: 2 +Explanation: The common factors of 25 and 30 are 1, 5. +``` + +### Constraints + +- `1 <= a, b <= 1000` + + + #### Complexity Analysis + + - Time Complexity: $ O(min(a, b)) $ where a and b are the input numbers. This is because the algorithm iterates from 1 to the minimum of a and b, performing a constant amount of work for each iteration. + + - Space Complexity: $ O(1) $ as it only uses a fixed amount of space to store the variables cnt, mini, and i. The input numbers a and b are not modified, and no additional data structures are used. + + + + + + ## Code in Different Languages + + + + ```javascript + class Solution { + commonFactors(a, b) { + let cnt = 0; + let mini = Math.min(a, b); + for (let i = 1; i <= mini; i++) { + if (a % i === 0 && b % i === 0) { + cnt++; + } + } + return cnt; + } +} + + + ``` + + + + + ```typescript + class Solution { + commonFactors(a: number, b: number): number { + let cnt = 0; + let mini = Math.min(a, b); + for (let i = 1; i <= mini; i++) { + if (a % i === 0 && b % i === 0) { + cnt++; + } + } + return cnt; + } +} + + + ``` + + + + ```python + class Solution: + def commonFactors(self, a: int, b: int) -> int: + cnt = 0 + mini = min(a, b) + for i in range(1, mini + 1): + if a % i == 0 and b % i == 0: + cnt += 1 + return cnt + + + ``` + + + + + ```java + public class Solution { + public int commonFactors(int a, int b) { + int cnt = 0; + int mini = Math.min(a, b); + for (int i = 1; i <= mini; i++) { + if (a % i == 0 && b % i == 0) { + cnt++; + } + } + return cnt; + } +} + + + ``` + + + + + ```cpp + class Solution { +public: + int commonFactors(int a, int b) { + int cnt = 0; + int mini=min(a, b); + for(int i=1; i<=mini; i++){ + if(a%i==0 && b%i==0) cnt++; + } + return cnt; + } +}; + + ``` + + + + + \ No newline at end of file diff --git a/solutions/lc-solutions/2400-2499/2432-The-Employee-That-Worked-on-the-Longest-Task.md b/solutions/lc-solutions/2400-2499/2432-The-Employee-That-Worked-on-the-Longest-Task.md new file mode 100644 index 0000000..c4bd7d3 --- /dev/null +++ b/solutions/lc-solutions/2400-2499/2432-The-Employee-That-Worked-on-the-Longest-Task.md @@ -0,0 +1,300 @@ +--- +id: The-Employee-That-Worked-on-the-Longest-Task +title: The Employee That Worked on the Longest Task +sidebar_label: 2432-The Employee That Worked on the Longest Task +tags: [dsa, leetcode] +description: Problem solution of The Employee That Worked on the Longest Task +--- + +## Problem Statement + +### Problem Description + +There are n employees, each with a unique id from 0 to n - 1. + +You are given a 2D integer array logs where logs[i] = [idi, leaveTimei] where: + +idi is the id of the employee that worked on the ith task, and +leaveTimei is the time at which the employee finished the ith task. All the values leaveTimei are unique. +Note that the ith task starts the moment right after the (i - 1)th task ends, and the 0th task starts at time 0. + +Return the id of the employee that worked the task with the longest time. If there is a tie between two or more employees, return the smallest id among them. + + + + +### Examples + +#### Example 1 +``` +Input: n = 10, logs = [[0,3],[2,5],[0,9],[1,15]] +Output: 1 +Explanation: +Task 0 started at 0 and ended at 3 with 3 units of times. +Task 1 started at 3 and ended at 5 with 2 units of times. +Task 2 started at 5 and ended at 9 with 4 units of times. +Task 3 started at 9 and ended at 15 with 6 units of times. +The task with the longest time is task 3 and the employee with id 1 is the one that worked on it, so we return 1. +``` + +### Example 2 +``` +Input: n = 26, logs = [[1,1],[3,7],[2,12],[7,17]] +Output: 3 +Explanation: +Task 0 started at 0 and ended at 1 with 1 unit of times. +Task 1 started at 1 and ended at 7 with 6 units of times. +Task 2 started at 7 and ended at 12 with 5 units of times. +Task 3 started at 12 and ended at 17 with 5 units of times. +The tasks with the longest time is task 1. The employee that worked on it is 3, so we return 3. +``` + +### Example 3 +``` +Input: n = 2, logs = [[0,10],[1,20]] +Output: 0 +Explanation: +Task 0 started at 0 and ended at 10 with 10 units of times. +Task 1 started at 10 and ended at 20 with 10 units of times. +The tasks with the longest time are tasks 0 and 1. The employees that worked on them are 0 and 1, so we return the smallest id 0. +``` + +### Constraints + +- `2 <= n <= 500` +- `1 <= logs.length <= 500` +- `logs[i].length == 2` +- `0 <= idi <= n - 1` +- `1 <= leaveTimei <= 500` +- `idi != idi+1` +- `leaveTimei are sorted in a strictly increasing order.` + +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +Brute Force Approach: +- Initialize variables to keep track of the maximum time and the corresponding employee id. +- Iterate through the logs array. +- For each task, calculate the time taken. +- Compare the calculated time with the maximum time and update the variables accordingly. +- Return the employee id with the longest task time. +#### Codes in Different Languages + + + + + +```cpp +#include +#include +#include +using namespace std; + +int hardestWorker(int n, vector>& logs) { + int maxTime = INT_MIN; + int employeeId = INT_MAX; + + for (int i = 0; i < logs.size(); ++i) { + int time = (i == 0) ? logs[i][1] : logs[i][1] - logs[i-1][1]; + if (time > maxTime || (time == maxTime && logs[i][0] < employeeId)) { + maxTime = time; + employeeId = logs[i][0]; + } + } + return employeeId; +} + +``` + + + + +```java +import java.util.List; + +public class Solution { + public int hardestWorker(int n, List logs) { + int maxTime = Integer.MIN_VALUE; + int employeeId = Integer.MAX_VALUE; + + for (int i = 0; i < logs.size(); ++i) { + int time = (i == 0) ? logs.get(i)[1] : logs.get(i)[1] - logs.get(i - 1)[1]; + if (time > maxTime || (time == maxTime && logs.get(i)[0] < employeeId)) { + maxTime = time; + employeeId = logs.get(i)[0]; + } + } + return employeeId; + } +} + + + + + +``` + + + + + + +```python +def hardestWorker(n, logs): + max_time = float('-inf') + employee_id = float('inf') + + for i in range(len(logs)): + time = logs[i][1] if i == 0 else logs[i][1] - logs[i - 1][1] + if time > max_time or (time == max_time and logs[i][0] < employee_id): + max_time = time + employee_id = logs[i][0] + + return employee_id + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(n)$ +- We iterate through the logs array once, performing constant time operations for each log. +- Space Complexity: $O(1)$ +- We use a constant amount of extra space for variables. + + + + +### Approach 2: Optimized approach + +Optimized Approach: +- Initialize variables to keep track of the maximum time and the corresponding employee id. +- Iterate through the logs array. +- For each task, calculate the time taken directly using the leave times of consecutive tasks. +- Compare the calculated time with the maximum time and update the variables accordingly. +- Return the employee id with the longest task time. + +#### Code in Different Languages + + + + + +```cpp +#include +#include +#include +using namespace std; + +int hardestWorker(int n, vector>& logs) { + int maxTime = logs[0][1]; + int employeeId = logs[0][0]; + + for (int i = 1; i < logs.size(); ++i) { + int time = logs[i][1] - logs[i-1][1]; + if (time > maxTime || (time == maxTime && logs[i][0] < employeeId)) { + maxTime = time; + employeeId = logs[i][0]; + } + } + return employeeId; +} + + + +``` + + + + +```java +import java.util.List; + +public class Solution { + public int hardestWorker(int n, List logs) { + int maxTime = logs.get(0)[1]; + int employeeId = logs.get(0)[0]; + + for (int i = 1; i < logs.size(); ++i) { + int time = logs.get(i)[1] - logs.get(i - 1)[1]; + if (time > maxTime || (time == maxTime && logs.get(i)[0] < employeeId)) { + maxTime = time; + employeeId = logs.get(i)[0]; + } + } + return employeeId; + } +} + + + +``` + + + + + + +```python +def hardestWorker(n, logs): + max_time = logs[0][1] + employee_id = logs[0][0] + + for i in range(1, len(logs)): + time = logs[i][1] - logs[i - 1][1] + if time > max_time or (time == max_time and logs[i][0] < employee_id): + max_time = time + employee_id = logs[i][0] + + return employee_id + + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ +- We iterate through the logs array once, calculating task durations directly. +- Space Complexity: $O(1)$ +- We use a constant amount of extra space for variables. +- This approach is efficient and straightforward. + + + + + +## Video Explanation of Given Problem + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
+ diff --git a/solutions/lc-solutions/2400-2499/2437-Number-of-Valid-Clock-Times.md b/solutions/lc-solutions/2400-2499/2437-Number-of-Valid-Clock-Times.md new file mode 100644 index 0000000..7c8d450 --- /dev/null +++ b/solutions/lc-solutions/2400-2499/2437-Number-of-Valid-Clock-Times.md @@ -0,0 +1,341 @@ +--- +id: Number-of-Valid-Clock-Times +title: Number of Valid Clock Times +sidebar_label: 2437-Number of Valid Clock Times +tags: [dsa, leetcode] +description: Problem solution of Number of Valid Clock Times +--- + +## Problem Statement + +### Problem Description + +You are given a string of length 5 called time, representing the current time on a digital clock in the format "hh:mm". The earliest possible time is "00:00" and the latest possible time is "23:59". + +In the string time, the digits represented by the ? symbol are unknown, and must be replaced with a digit from 0 to 9. + +Return an integer answer, the number of valid clock times that can be created by replacing every ? with a digit from 0 to 9. + +### Examples + +#### Example 1 +``` +Input: time = "?5:00" +Output: 2 +Explanation: We can replace the ? with either a 0 or 1, producing "05:00" or "15:00". Note that we cannot replace it with a 2, since the time "25:00" is invalid. In total, we have two choices. +``` + +### Example 2 +``` +Input: time = "0?:0?" +Output: 100 +Explanation: Each ? can be replaced by any digit from 0 to 9, so we have 100 total choices. +``` + +### Example 3 +``` +Input: time = "??:??" +Output: 1440 +Explanation: There are 24 possible choices for the hours, and 60 possible choices for the minutes. In total, we have 24 * 60 = 1440 choices. + +``` + +### Constraints + +- `time is a valid string of length 5 in the format "hh:mm".` +- `"00" <= hh <= "23"` +- `"00" <= mm <= "59"` +- `Some of the digits might be replaced with '?' and need to be replaced with digits from 0 to 9.` + +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +Brute Force Approach: +- Generate all possible combinations by replacing each '?' with digits from 0 to 9. +- Check if the generated time string is valid (i.e., hours should be between 00 and 23, and minutes should be between 00 and 59). +- Count the number of valid times. +#### Codes in Different Languages + + + + + +```cpp +#include +#include + +using namespace std; + +bool isValidTime(const string& time) { + int hours = stoi(time.substr(0, 2)); + int minutes = stoi(time.substr(3, 2)); + return hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59; +} + +int countValidTimesBruteForce(string time) { + vector times; + times.push_back(time); + for (int i = 0; i < 5; ++i) { + if (time[i] == '?') { + int n = times.size(); + for (int j = 0; j < n; ++j) { + string current = times[j]; + for (int d = 0; d <= 9; ++d) { + current[i] = '0' + d; + times.push_back(current); + } + } + times.erase(times.begin(), times.begin() + n); + } + } + int validCount = 0; + for (const auto& t : times) { + if (isValidTime(t)) { + ++validCount; + } + } + return validCount; +} + + +``` + + + + +```java +import java.util.ArrayList; +import java.util.List; + +public class Solution { + private boolean isValidTime(String time) { + int hours = Integer.parseInt(time.substring(0, 2)); + int minutes = Integer.parseInt(time.substring(3, 5)); + return hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59; + } + + public int countValidTimesBruteForce(String time) { + List times = new ArrayList<>(); + times.add(time); + for (int i = 0; i < 5; ++i) { + if (time.charAt(i) == '?') { + int n = times.size(); + for (int j = 0; j < n; ++j) { + String current = times.get(j); + for (int d = 0; d <= 9; ++d) { + times.add(current.substring(0, i) + d + current.substring(i + 1)); + } + } + times = times.subList(n, times.size()); + } + } + int validCount = 0; + for (String t : times) { + if (isValidTime(t)) { + ++validCount; + } + } + return validCount; + } +} + + + + + +``` + + + + + + +```python +def is_valid_time(time): + hours = int(time[:2]) + minutes = int(time[3:]) + return 0 <= hours <= 23 and 0 <= minutes <= 59 + +def count_valid_times_brute_force(time): + times = [time] + for i in range(5): + if time[i] == '?': + n = len(times) + for j in range(n): + current = times[j] + for d in range(10): + times.append(current[:i] + str(d) + current[i+1:]) + times = times[n:] + valid_count = sum(1 for t in times if is_valid_time(t)) + return valid_count + + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(10^k)$ +- We generate and check all possible combinations, where k is the number of '?' characters. +- Space Complexity: $O(10^k)$ +- We store all possible combinations generated. + + + +### Approach 2: Optimized approach + +Optimized Approach: +- Analyze each position in the time string. +- Calculate the possible values for each '?' based on the - constraints for hours and minutes. +- Multiply the number of possibilities for each '?' to get the total number of valid times. +#### Code in Different Languages + + + + + +```cpp +#include + +using namespace std; + +int countValidTimesOptimized(string time) { + int possibleHours = 1; + int possibleMinutes = 1; + + if (time[0] == '?') { + possibleHours *= (time[1] == '?' || time[1] < '4') ? 3 : 2; + } else if (time[0] == '2') { + possibleHours *= (time[1] == '?') ? 4 : 1; + } else { + possibleHours *= (time[1] == '?') ? 10 : 1; + } + + if (time[1] == '?') { + possibleHours *= (time[0] == '2') ? 4 : 10; + } + + if (time[3] == '?') { + possibleMinutes *= 6; + } + if (time[4] == '?') { + possibleMinutes *= 10; + } + + return possibleHours * possibleMinutes; +} + + + +``` + + + + +```java +public class Solution { + public int countValidTimesOptimized(String time) { + int possibleHours = 1; + int possibleMinutes = 1; + + if (time.charAt(0) == '?') { + possibleHours *= (time.charAt(1) == '?' || time.charAt(1) < '4') ? 3 : 2; + } else if (time.charAt(0) == '2') { + possibleHours *= (time.charAt(1) == '?') ? 4 : 1; + } else { + possibleHours *= (time.charAt(1) == '?') ? 10 : 1; + } + + if (time.charAt(1) == '?') { + possibleHours *= (time.charAt(0) == '2') ? 4 : 10; + } + + if (time.charAt(3) == '?') { + possibleMinutes *= 6; + } + if (time.charAt(4) == '?') { + possibleMinutes *= 10; + } + + return possibleHours * possibleMinutes; + } +} + + +``` + + + + + + +```python +def count_valid_times_optimized(time): + possible_hours = 1 + possible_minutes = 1 + + if time[0] == '?': + possible_hours *= 3 if time[1] == '?' or time[1] < '4' else 2 + elif time[0] == '2': + possible_hours *= 4 if time[1] == '?' else 1 + else: + possible_hours *= 10 if time[1] == '?' else 1 + + if time[1] == '?': + possible_hours *= 4 if time[0] == '2' else 10 + + if time[3] == '?': + possible_minutes *= 6 + if time[4] == '?': + possible_minutes *= 10 + + return possible_hours * possible_minutes + + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(1)$ +- We perform constant-time calculations based on the positions of '?' in the string. +- Space Complexity: $O(1)$ +- We use a constant amount of extra space for variables. + + + + +## Video Explanation of Given Problem + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
+ diff --git a/solutions/lc-solutions/2400-2499/2446-Determine-if-Two-Events-Have-Conflict.md b/solutions/lc-solutions/2400-2499/2446-Determine-if-Two-Events-Have-Conflict.md new file mode 100644 index 0000000..6aba49a --- /dev/null +++ b/solutions/lc-solutions/2400-2499/2446-Determine-if-Two-Events-Have-Conflict.md @@ -0,0 +1,288 @@ +--- +id: Determine-if-Two-Events-Have-Conflict +title: Determine if Two Events Have Conflict +sidebar_label: 2446-Determine if Two Events Have Conflict +tags: [dsa, leetcode] +description: Problem solution of Count Days Spent Together +--- + +## Problem Statement + +### Problem Description + +You are given two arrays of strings that represent two inclusive events that happened on the same day, event1 and event2, where: + +event1 = [startTime1, endTime1] and +event2 = [startTime2, endTime2]. +Event times are valid 24 hours format in the form of HH:MM. + +A conflict happens when two events have some non-empty intersection (i.e., some moment is common to both events). + +Return true if there is a conflict between two events. Otherwise, return false + +### Examples + +#### Example 1 +``` +Input: event1 = ["01:15","02:00"], event2 = ["02:00","03:00"] +Output: true +Explanation: The two events intersect at time 2:00. +``` + +### Example 2 +``` +Input: event1 = ["01:00","02:00"], event2 = ["01:20","03:00"] +Output: true +Explanation: The two events intersect starting from 01:20 to 02:00. +``` + +### Example 3 +``` +Input: event1 = ["10:00","11:00"], event2 = ["14:00","15:00"] +Output: false +Explanation: The two events do not intersect. +``` + +### Constraints + +- `event1.length == event2.length == 2` +- `event1[i].length == event2[i].length == 5` +- `startTime1 <= endTime1` +- `startTime2 <= endTime2` +- `All the event times follow the HH:MM format.` + +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +Brute Force Approach: +- Convert the event times to minutes since midnight. +- Generate all the minutes for both events. +- Check if there is any common minute between the two sets. +#### Codes in Different Languages + + + + + +```cpp +#include +#include + +using namespace std; + +int toMinutes(const string& time) { + int hours = stoi(time.substr(0, 2)); + int minutes = stoi(time.substr(3, 2)); + return hours * 60 + minutes; +} + +bool haveConflictBruteForce(vector& event1, vector& event2) { + int start1 = toMinutes(event1[0]); + int end1 = toMinutes(event1[1]); + int start2 = toMinutes(event2[0]); + int end2 = toMinutes(event2[1]); + + for (int t1 = start1; t1 <= end1; ++t1) { + for (int t2 = start2; t2 <= end2; ++t2) { + if (t1 == t2) return true; + } + } + return false; +} + + +``` + + + + +```java +import java.util.List; + +public class Solution { + private int toMinutes(String time) { + int hours = Integer.parseInt(time.substring(0, 2)); + int minutes = Integer.parseInt(time.substring(3, 5)); + return hours * 60 + minutes; + } + + public boolean haveConflictBruteForce(List event1, List event2) { + int start1 = toMinutes(event1.get(0)); + int end1 = toMinutes(event1.get(1)); + int start2 = toMinutes(event2.get(0)); + int end2 = toMinutes(event2.get(1)); + + for (int t1 = start1; t1 <= end1; ++t1) { + for (int t2 = start2; t2 <= end2; ++t2) { + if (t1 == t2) return true; + } + } + return false; + } +} + + + + + + +``` + + + + + + +```python +def to_minutes(time): + hours, minutes = map(int, time.split(':')) + return hours * 60 + minutes + +def have_conflict_brute_force(event1, event2): + start1 = to_minutes(event1[0]) + end1 = to_minutes(event1[1]) + start2 = to_minutes(event2[0]) + end2 = to_minutes(event2[1]) + + return any(t1 == t2 for t1 in range(start1, end1 + 1) for t2 in range(start2, end2 + 1)) + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O((end1 - start1) * (end2 - start2))$ +- We generate and check all possible minute pairs within the intervals. +- Space Complexity: $O(1)$ +- We use a constant amount of extra space. + + + +### Approach 2: Optimized approach + +Optimized Approach: +- Convert the event times to minutes since midnight. +- Check if the start of one event is before the end of the other and vice versa. +#### Code in Different Languages + + + + + +```cpp +#include +#include + +using namespace std; + +int toMinutes(const string& time) { + int hours = stoi(time.substr(0, 2)); + int minutes = stoi(time.substr(3, 2)); + return hours * 60 + minutes; +} + +bool haveConflictOptimized(vector& event1, vector& event2) { + int start1 = toMinutes(event1[0]); + int end1 = toMinutes(event1[1]); + int start2 = toMinutes(event2[0]); + int end2 = toMinutes(event2[1]); + + return !(end1 < start2 || end2 < start1); +} + + +``` + + + + +```java +import java.util.List; + +public class Solution { + private int toMinutes(String time) { + int hours = Integer.parseInt(time.substring(0, 2)); + int minutes = Integer.parseInt(time.substring(3, 5)); + return hours * 60 + minutes; + } + + public boolean haveConflictOptimized(List event1, List event2) { + int start1 = toMinutes(event1.get(0)); + int end1 = toMinutes(event1.get(1)); + int start2 = toMinutes(event2.get(0)); + int end2 = toMinutes(event2.get(1)); + + return !(end1 < start2 || end2 < start1); + } +} + + +``` + + + + + + +```python +def to_minutes(time): + hours, minutes = map(int, time.split(':')) + return hours * 60 + minutes + +def have_conflict_optimized(event1, event2): + start1 = to_minutes(event1[0]) + end1 = to_minutes(event1[1]) + start2 = to_minutes(event2[0]) + end2 = to_minutes(event2[1]) + + return not (end1 < start2 or end2 < start1) + + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(1)$ +- We perform constant-time calculations and comparisons. +- Space Complexity: $O(1)$ +- We use a constant amount of extra space. + + + + + +## Video Explanation of Given Problem + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
+ diff --git a/solutions/lc-solutions/2400-2499/2455-Average-Value-of-Even-Numbers-That-Are-Divisible-by-Three.md b/solutions/lc-solutions/2400-2499/2455-Average-Value-of-Even-Numbers-That-Are-Divisible-by-Three.md new file mode 100644 index 0000000..a73ead6 --- /dev/null +++ b/solutions/lc-solutions/2400-2499/2455-Average-Value-of-Even-Numbers-That-Are-Divisible-by-Three.md @@ -0,0 +1,274 @@ +--- +id: Average-Value-of-Even-Numbers-That-Are-Divisible-by-Three +title: Average Value of Even Numbers That Are Divisible by Three +sidebar_label: 2455-Average Value of Even Numbers That Are Divisible by Three +tags: [dsa, leetcode] +description: Problem solution of Average Value of Even Numbers That Are Divisible by Three +--- + +## Problem Statement + +### Problem Description + +Given an integer array nums of positive integers, return the average value of all even integers that are divisible by 3. + +Note that the average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer. +### Examples + +#### Example 1 +``` +Input: nums = [1,3,6,10,12,15] +Output: 9 +Explanation: 6 and 12 are even numbers that are divisible by 3. (6 + 12) / 2 = 9. +``` + +### Example 2 +``` +Input: nums = [1,2,4,7,10] +Output: 0 +Explanation: There is no single number that satisfies the requirement, so return 0. +``` + + + +### Constraints + +- `1 <= nums.length <= 1000` +- `1 <= nums[i] <= 1000` + +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +Brute Force Approach: +Iterate through the nums array. +For each number, check if it is even and divisible by 3. +If it meets both conditions, add it to a running sum and increment a count. +If the count is greater than 0, calculate the average as the integer division of the sum by the count; otherwise, return 0. +#### Codes in Different Languages + + + + + +```cpp +#include +#include + +int averageValue(std::vector& nums) { + int sum = 0, count = 0; + + for (int num : nums) { + if (num % 6 == 0) { // Even and divisible by 3 means divisible by 6 + sum += num; + count++; + } + } + + return count > 0 ? sum / count : 0; +} + +int main() { + std::vector nums = {1, 3, 6, 10, 12, 15}; + std::cout << averageValue(nums) << std::endl; // Output: 9 + return 0; +} + + +``` + + + + +```java +public class AverageValue { + public static int averageValue(int[] nums) { + int sum = 0, count = 0; + + for (int num : nums) { + if (num % 6 == 0) { // Even and divisible by 3 means divisible by 6 + sum += num; + count++; + } + } + + return count > 0 ? sum / count : 0; + } + + public static void main(String[] args) { + int[] nums = {1, 3, 6, 10, 12, 15}; + System.out.println(averageValue(nums)); // Output: 9 + } +} + + +``` + + + + + + +```python +def average_value(nums): + total_sum = 0 + count = 0 + + for num in nums: + if num % 6 == 0: # Even and divisible by 3 means divisible by 6 + total_sum += num + count += 1 + + return total_sum // count if count > 0 else 0 + +nums = [1, 3, 6, 10, 12, 15] +print(average_value(nums)) # Output: 9 + + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(n)$ +- where n is the number of elements in nums. +- Space Complexity: $O(1)$ +- since we are only using a few extra variables. + + + +### Approach 2: Optimized approach + +Optimized Approach: +The brute force approach is already optimal with a time complexity of O(n). The logic can be further simplified by directly checking if the number is divisible by 6, which implicitly checks for both evenness and divisibility by 3. +#### Code in Different Languages + + + + + +```cpp +#include +#include + +int averageValue(std::vector& nums) { + int sum = 0, count = 0; + + for (int num : nums) { + if (num % 6 == 0) { // Divisible by 6 implies both even and divisible by 3 + sum += num; + count++; + } + } + + return count > 0 ? sum / count : 0; +} + +int main() { + std::vector nums = {1, 3, 6, 10, 12, 15}; + std::cout << averageValue(nums) << std::endl; // Output: 9 + return 0; +} + + +``` + + + + +```java +public class AverageValue { + public static int averageValue(int[] nums) { + int sum = 0, count = 0; + + for (int num : nums) { + if (num % 6 == 0) { // Divisible by 6 implies both even and divisible by 3 + sum += num; + count++; + } + } + + return count > 0 ? sum / count : 0; + } + + public static void main(String[] args) { + int[] nums = {1, 3, 6, 10, 12, 15}; + System.out.println(averageValue(nums)); // Output: 9 + } +} + + +``` + + + + + + +```python +public class AverageValue { + public static int averageValue(int[] nums) { + int sum = 0, count = 0; + + for (int num : nums) { + if (num % 6 == 0) { // Divisible by 6 implies both even and divisible by 3 + sum += num; + count++; + } + } + + return count > 0 ? sum / count : 0; + } + + public static void main(String[] args) { + int[] nums = {1, 3, 6, 10, 12, 15}; + System.out.println(averageValue(nums)); // Output: 9 + } +} + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ + +- Space Complexity: $O(1)$ + + + + + +## Video Explanation of Given Problem + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
+ diff --git a/solutions/lc-solutions/2400-2499/24551- Odd-String-Difference.md b/solutions/lc-solutions/2400-2499/24551- Odd-String-Difference.md new file mode 100644 index 0000000..6deabf4 --- /dev/null +++ b/solutions/lc-solutions/2400-2499/24551- Odd-String-Difference.md @@ -0,0 +1,330 @@ +--- +id: Odd-String-Difference +title: Odd String Difference Problem +sidebar_label: 2451-Odd String Difference +tags: [dsa, leetcode] +description: Problem solution of Odd String Difference Problem +--- + +## Problem Statement + +### Problem Description + +You are given an array of equal-length strings words. Assume that the length of each string is n. + +Each string words[i] can be converted into a difference integer array difference[i] of length n - 1 where difference[i][j] = words[i][j+1] - words[i][j] where 0 <= j <= n - 2. Note that the difference between two letters is the difference between their positions in the alphabet i.e. the position of 'a' is 0, 'b' is 1, and 'z' is 25. + +For example, for the string "acb", the difference integer array is [2 - 0, 1 - 2] = [2, -1]. +All the strings in words have the same difference integer array, except one. You should find that string. + +Return the string in words that has different difference integer array. +### Examples + +#### Example 1 +``` +Input: words = ["aaa","bob","ccc","ddd"] +Output: "bob" +Explanation: All the integer arrays are [0, 0] except for "bob", which corresponds to [13, -13]. +``` + +### Constraints + +- `3 <= words.length <= 100` +- `n == words[i].length` +- `2 <= n <= 20` +- `words[i] consists of lowercase English letters.` + +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +Brute Force Approach: +Convert each string in the words array to its corresponding difference integer array. +Compare the difference arrays to find the one that is different from the others. +#### Codes in Different Languages + + + + + +```cpp +#include +#include +#include + +std::vector getDifferenceArray(const std::string& word) { + std::vector difference; + for (int i = 0; i < word.length() - 1; ++i) { + difference.push_back(word[i + 1] - word[i]); + } + return difference; +} + +std::string oddStringOut(const std::vector& words) { + std::vector> differences; + for (const auto& word : words) { + differences.push_back(getDifferenceArray(word)); + } + + for (int i = 0; i < differences.size(); ++i) { + int count = 0; + for (int j = 0; j < differences.size(); ++j) { + if (differences[i] == differences[j]) { + count++; + } + } + if (count == 1) { + return words[i]; + } + } + return ""; +} + +int main() { + std::vector words = {"adc", "wzy", "abc"}; + std::cout << oddStringOut(words) << std::endl; // Output: "abc" + return 0; +} + +``` + + + + +```java +import java.util.*; + +public class OddStringOut { + public static List getDifferenceArray(String word) { + List difference = new ArrayList<>(); + for (int i = 0; i < word.length() - 1; i++) { + difference.add(word.charAt(i + 1) - word.charAt(i)); + } + return difference; + } + + public static String oddStringOut(String[] words) { + List> differences = new ArrayList<>(); + for (String word : words) { + differences.add(getDifferenceArray(word)); + } + + for (int i = 0; i < differences.size(); i++) { + int count = 0; + for (int j = 0; j < differences.size(); j++) { + if (differences.get(i).equals(differences.get(j))) { + count++; + } + } + if (count == 1) { + return words[i]; + } + } + return ""; + } + + public static void main(String[] args) { + String[] words = {"adc", "wzy", "abc"}; + System.out.println(oddStringOut(words)); // Output: "abc" + } +} + +``` + + + + + + +```python +def get_difference_array(word): + return [ord(word[i + 1]) - ord(word[i]) for i in range(len(word) - 1)] + +def odd_string_out(words): + differences = [get_difference_array(word) for word in words] + + for i in range(len(differences)): + count = sum(differences[i] == differences[j] for j in range(len(differences))) + if count == 1: + return words[i] + return "" + +words = ["adc", "wzy", "abc"] +print(odd_string_out(words)) # Output: "abc" + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(m*n)$ +- where m is the number of strings and n is the length of each string. +- Space Complexity: $O(m * (n-1))$ +- for storing the difference arrays. + + + +### Approach 2: Optimized approach + +Optimized Approach: +Calculate the difference arrays. +Identify the unique one by comparing with the first two arrays and using the majority principle. +Compare the first two difference arrays: +- If they are equal, then the different one must be different from this common difference array. +- If they are not equal, compare the third one to decide which of the first two is different. +Return the corresponding string. +#### Code in Different Languages + + + + + +```cpp +#include +#include +#include + +std::vector getDifferenceArray(const std::string& word) { + std::vector difference; + for (int i = 0; i < word.length() - 1; ++i) { + difference.push_back(word[i + 1] - word[i]); + } + return difference; +} + +std::string oddStringOut(const std::vector& words) { + auto diff1 = getDifferenceArray(words[0]); + auto diff2 = getDifferenceArray(words[1]); + + if (diff1 == diff2) { + for (int i = 2; i < words.size(); ++i) { + if (getDifferenceArray(words[i]) != diff1) { + return words[i]; + } + } + } else { + auto diff3 = getDifferenceArray(words[2]); + return (diff3 == diff1) ? words[1] : words[0]; + } + return ""; +} + +int main() { + std::vector words = {"adc", "wzy", "abc"}; + std::cout << oddStringOut(words) << std::endl; // Output: "abc" + return 0; +} + +``` + + + + +```java +import java.util.*; + +public class OddStringOut { + public static List getDifferenceArray(String word) { + List difference = new ArrayList<>(); + for (int i = 0; i < word.length() - 1; i++) { + difference.add(word.charAt(i + 1) - word.charAt(i)); + } + return difference; + } + + public static String oddStringOut(String[] words) { + List diff1 = getDifferenceArray(words[0]); + List diff2 = getDifferenceArray(words[1]); + + if (diff1.equals(diff2)) { + for (int i = 2; i < words.length; i++) { + if (!getDifferenceArray(words[i]).equals(diff1)) { + return words[i]; + } + } + } else { + List diff3 = getDifferenceArray(words[2]); + return diff3.equals(diff1) ? words[1] : words[0]; + } + return ""; + } + + public static void main(String[] args) { + String[] words = {"adc", "wzy", "abc"}; + System.out.println(oddStringOut(words)); // Output: "abc" + } +} + +``` + + + + + + +```python +def get_difference_array(word): + return [ord(word[i + 1]) - ord(word[i]) for i in range(len(word) - 1)] + +def odd_string_out(words): + diff1 = get_difference_array(words[0]) + diff2 = get_difference_array(words[1]) + + if diff1 == diff2: + for i in range(2, len(words)): + if get_difference_array(words[i]) != diff1: + return words[i] + else: + diff3 = get_difference_array(words[2]) + return words[1] if diff3 == diff1 else words[0] + return "" + +words = ["adc", "wzy", "abc"] +print(odd_string_out(words)) # Output: "abc" + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(m*n)$ +- where m is the number of strings and n is the length of each string. +- Space Complexity: $O(n)$ +- for storing the difference array temporarily. + + + + +## Video Explanation of Given Problem + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
+ diff --git a/solutions/lc-solutions/2400-2499/2460-Apply-Operations-to-an-Array.md b/solutions/lc-solutions/2400-2499/2460-Apply-Operations-to-an-Array.md new file mode 100644 index 0000000..2cd5676 --- /dev/null +++ b/solutions/lc-solutions/2400-2499/2460-Apply-Operations-to-an-Array.md @@ -0,0 +1,343 @@ +--- +id: Apply-Operations-to-an-Array +title: Apply Operations to an Array +sidebar_label: 2460-Apply Operations to an Array +tags: [dsa, leetcode] +description: Problem solution of Apply Operations to an Array +--- + +## Problem Statement + +### Problem Description + +You are given a 0-indexed array nums of size n consisting of non-negative integers. + +You need to apply n - 1 operations to this array where, in the ith operation (0-indexed), you will apply the following on the ith element of nums: + +If nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0. Otherwise, you skip this operation. +After performing all the operations, shift all the 0's to the end of the array. + +For example, the array [1,0,2,0,0,1] after shifting all its 0's to the end, is [1,2,1,0,0,0]. +Return the resulting array. + +Note that the operations are applied sequentially, not all at once. + +### Examples + +#### Example 1 +``` +Input: nums = [1,2,2,1,1,0] +Output: [1,4,2,0,0,0] +Explanation: We do the following operations: +- i = 0: nums[0] and nums[1] are not equal, so we skip this operation. +- i = 1: nums[1] and nums[2] are equal, we multiply nums[1] by 2 and change nums[2] to 0. The array becomes [1,4,0,1,1,0]. +- i = 2: nums[2] and nums[3] are not equal, so we skip this operation. +- i = 3: nums[3] and nums[4] are equal, we multiply nums[3] by 2 and change nums[4] to 0. The array becomes [1,4,0,2,0,0]. +- i = 4: nums[4] and nums[5] are equal, we multiply nums[4] by 2 and change nums[5] to 0. The array becomes [1,4,0,2,0,0]. +After that, we shift the 0's to the end, which gives the array [1,4,2,0,0,0]. + +``` + +### Example 2 +``` +Input: nums = [0,1] +Output: [1,0] +Explanation: No operation can be applied, we just shift the 0 to the end. + +``` +### Constraints + +- `2 <= nums.length <= 2000` +- `0 <= nums[i] <= 1000` + +## Solution of Given Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized Technique. + + + + +### Approach 1:Brute Force (Naive) + + +Brute Force Approach: +Iterate through the array and for each i, check if nums[i] is equal to nums[i + 1]. +If they are equal, multiply nums[i] by 2 and set nums[i + 1] to 0. +After all operations are performed, create a new array by collecting all non-zero elements followed by all zero elements. +#### Codes in Different Languages + + + + + +```cpp +#include +#include + +std::vector applyOperations(std::vector& nums) { + int n = nums.size(); + + for (int i = 0; i < n - 1; ++i) { + if (nums[i] == nums[i + 1]) { + nums[i] *= 2; + nums[i + 1] = 0; + } + } + + std::vector result; + for (int num : nums) { + if (num != 0) { + result.push_back(num); + } + } + while (result.size() < n) { + result.push_back(0); + } + + return result; +} + +int main() { + std::vector nums = {1, 2, 2, 1, 1, 0}; + std::vector result = applyOperations(nums); + for (int num : result) { + std::cout << num << " "; + } + std::cout << std::endl; // Output: 1 4 2 0 0 0 + return 0; +} + +``` + + + + +```java +import java.util.*; + +public class ApplyOperations { + public static int[] applyOperations(int[] nums) { + int n = nums.length; + + for (int i = 0; i < n - 1; i++) { + if (nums[i] == nums[i + 1]) { + nums[i] *= 2; + nums[i + 1] = 0; + } + } + + int[] result = new int[n]; + int idx = 0; + for (int num : nums) { + if (num != 0) { + result[idx++] = num; + } + } + + return result; + } + + public static void main(String[] args) { + int[] nums = {1, 2, 2, 1, 1, 0}; + int[] result = applyOperations(nums); + System.out.println(Arrays.toString(result)); // Output: [1, 4, 2, 0, 0, 0] + } +} + +``` + + + + + + +```python +def apply_operations(nums): + n = len(nums) + + for i in range(n - 1): + if nums[i] == nums[i + 1]: + nums[i] *= 2 + nums[i + 1] = 0 + + result = [num for num in nums if num != 0] + result.extend([0] * (n - len(result))) + + return result + +nums = [1, 2, 2, 1, 1, 0] +print(apply_operations(nums)) # Output: [1, 4, 2, 0, 0, 0] + +``` + + + + + +### Complexity Analysis + +- Time Complexity: $O(n)$ +- for the operations and for shifting zeros. +- Space Complexity: $O(n)$ +- for the additional array. + + + +### Approach 2: Optimized approach + +Optimized Approach: +Iterate through the array and perform the operations in place. +After performing all operations, use two pointers to move all non-zero elements to the front and fill the remaining elements with zeros. +#### Code in Different Languages + + + + + +```cpp +#include +#include + +std::vector applyOperations(std::vector& nums) { + int n = nums.size(); + + for (int i = 0; i < n - 1; ++i) { + if (nums[i] == nums[i + 1]) { + nums[i] *= 2; + nums[i + 1] = 0; + } + } + + int index = 0; + for (int i = 0; i < n; ++i) { + if (nums[i] != 0) { + nums[index++] = nums[i]; + } + } + + while (index < n) { + nums[index++] = 0; + } + + return nums; +} + +int main() { + std::vector nums = {1, 2, 2, 1, 1, 0}; + std::vector result = applyOperations(nums); + for (int num : result) { + std::cout << num << " "; + } + std::cout << std::endl; // Output: 1 4 2 0 0 0 + return 0; +} + +``` + + + + +```java +import java.util.*; + +public class ApplyOperations { + public static int[] applyOperations(int[] nums) { + int n = nums.length; + + for (int i = 0; i < n - 1; i++) { + if (nums[i] == nums[i + 1]) { + nums[i] *= 2; + nums[i + 1] = 0; + } + } + + int index = 0; + for (int i = 0; i < n; i++) { + if (nums[i] != 0) { + nums[index++] = nums[i]; + } + } + + while (index < n) { + nums[index++] = 0; + } + + return nums; + } + + public static void main(String[] args) { + int[] nums = {1, 2, 2, 1, 1, 0}; + int[] result = applyOperations(nums); + System.out.println(Arrays.toString(result)); // Output: [1, 4, 2, 0, 0, 0] + } +} + +``` + + + + + + +```python +def apply_operations(nums): + n = len(nums) + + for i in range(n - 1): + if nums[i] == nums[i + 1]: + nums[i] *= 2 + nums[i + 1] = 0 + + index = 0 + for i in range(n): + if nums[i] != 0: + nums[index] = nums[i] + index += 1 + + while index < n: + nums[index] = 0 + index += 1 + + return nums + +nums = [1, 2, 2, 1, 1, 0] +print(apply_operations(nums)) # Output: [1, 4, 2, 0, 0, 0] + + +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ +- for both operations and shifting. +- Space Complexity: $O(1)$ +- as no extra space is required. + + + + +## Video Explanation of Given Problem + + + +--- + +

Authors:

+ +
+{['AmruthaPariprolu'].map(username => ( + +))} +
+ diff --git a/solutions/lc-solutions/2400-2499/2469-Convert-The-Temperature.md b/solutions/lc-solutions/2400-2499/2469-Convert-The-Temperature.md new file mode 100644 index 0000000..11c7919 --- /dev/null +++ b/solutions/lc-solutions/2400-2499/2469-Convert-The-Temperature.md @@ -0,0 +1,126 @@ +--- +id: convert-the-temperature +title: Convert The Temperature +sidebar_label: 2469-Convert-The-Temperature +tags: + - Math +--- + +## Problem Description +You are given a non-negative floating point number rounded to two decimal places `celsius`, that denotes the temperature in Celsius. + +You should convert Celsius into Kelvin and Fahrenheit and return it as an array `ans = [kelvin, fahrenheit]`. + +Return the array `ans`. Answers within `10^(-5)` of the actual answer will be accepted. + + +### Example + +**Example 1:** + + +``` +Input: celsius = 36.50 +Output: [309.65000,97.70000] +Explanation: Temperature at 36.50 Celsius converted in Kelvin is 309.65 and converted in Fahrenheit is 97.70. +``` +**Example 2:** +``` +Input: celsius = 122.11 +Output: [395.26000,251.79800] +Explanation: Temperature at 122.11 Celsius converted in Kelvin is 395.26 and converted in Fahrenheit is 251.798. +``` +### Constraints + +- `0 <= celsius <= 1000` + +## Solution Approach + +### Intuition: + +To efficiently determine the Kelvin and Farenheit temperature. +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + +class Solution { + convertTemperature(celsius) { + const kelvin = celsius + 273.15; + const farenheit = (celsius * 1.80) + 32.00; + return [kelvin, farenheit]; + } +} + + + ``` + + + + + ```typescript + class Solution { + convertTemperature(celsius: number): number[] { + const kelvin: number = celsius + 273.15; + const farenheit: number = (celsius * 1.80) + 32.00; + return [kelvin, farenheit]; + } +} + + ``` + + + + + ```python + class Solution: + def convertTemperature(self, celsius: float) -> list[float]: + kelvin = celsius + 273.15 + farenheit = (celsius * 1.80) + 32.00 + return [kelvin, farenheit] + + + ``` + + + + + ```java + public class Solution { + public double[] convertTemperature(double celsius) { + double kelvin = celsius + 273.15; + double farenheit = (celsius * 1.80) + 32.00; + return new double[]{kelvin, farenheit}; + } +} + + + ``` + + + + + ```cpp +class Solution { +public: + vector convertTemperature(double celsius) { + double kelvin = celsius+273.15; + double farenheit = (celsius*1.80)+32.00; + + return {kelvin, farenheit}; + } +}; +``` + + + +#### Complexity Analysis + +- Time Complexity: $$O(1)$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(2*n)$$ because the function performs a fixed number of operations, regardless of the input size. +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/2400-2499/2487-remove-nodes-from-linked-list.md b/solutions/lc-solutions/2400-2499/2487-remove-nodes-from-linked-list.md new file mode 100644 index 0000000..6192323 --- /dev/null +++ b/solutions/lc-solutions/2400-2499/2487-remove-nodes-from-linked-list.md @@ -0,0 +1,162 @@ +--- +id: remove-nodes-from-linked-list +title: Remove Nodes from Linked List +level: medium +sidebar_label: Remove Nodes from Linked List +tags: + - Linked List + - Data Structures + - Java +description: "This document provides solutions for the Remove Nodes from Linked List problem." +--- + +## Problem Statement + +You are given the head of a linked list. + +Remove every node which has a node with a greater value anywhere to the right side of it. + +Return the head of the modified linked list. + +**Example 1:** + +Input: `head = [5,2,13,3,8]` + +Output: `[13,8]` + +Explanation: +- The nodes that should be removed are 5, 2 and 3. +- Node 13 is to the right of node 5. +- Node 13 is to the right of node 2. +- Node 8 is to the right of node 3. + +**Example 2:** + +Input: `head = [1,1,1,1]` + +Output: `[1,1,1,1]` + +Explanation: Every node has value 1, so no nodes are removed. + +**Constraints:** + +- The number of nodes in the given list is in the range `[1, 10^5]`. +- `1 <= Node.val <= 10^5` + +## Solutions + +### Approach + +To solve the problem, the idea is to traverse the linked list, reverse it, and then keep the nodes in non-increasing order. Here are the detailed steps: + +1. **Reverse the Linked List**: + - Start by reversing the given linked list. + +2. **Filter the Nodes**: + - Traverse the reversed linked list and build a new linked list consisting only of nodes which are greater than or equal to the previously added nodes. + +3. **Reverse the Linked List Again**: + - Reverse the filtered linked list to restore the original order with the required nodes removed. + +### Java + +```java +class Solution { + public ListNode removeNodes(ListNode head) { + if (head == null || head.next == null) { + return head; + } + + head = reverse(head); + + ListNode head2 = new ListNode(0); + ListNode temp2 = head2; + ListNode temp = head; + + while (temp != null) { + if (temp.val >= temp2.val) { + temp2.next = new ListNode(temp.val); + temp2 = temp2.next; + } + temp = temp.next; + } + + return reverse(head2.next); + } + + private ListNode reverse(ListNode head) { + ListNode prev = null; + while (head != null) { + ListNode next = head.next; + head.next = prev; + prev = head; + head = next; + } + return prev; + } + + public class ListNode { + int val; + ListNode next; + ListNode() {} + ListNode(int val) { this.val = val; } + ListNode(int val, ListNode next) { this.val = val; this.next = next; } + } +} +``` + + +### Python + +```Python +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +class Solution: + def removeNodes(self, head: ListNode) -> ListNode: + if not head or not head.next: + return head + + head = self.reverse(head) + head2 = ListNode(0) + temp2 = head2 + temp = head + + while temp: + if temp.val >= temp2.val: + temp2.next = ListNode(temp.val) + temp2 = temp2.next + temp = temp.next + + return self.reverse(head2.next) + + def reverse(self, head: ListNode) -> ListNode: + temp = None + while head.next: + temp2 = head.next + head.next = temp + temp = head + head = temp2 + head.next = temp + return head + +def print_list(node): + while node: + print(node.val, end=" -> ") + node = node.next + print("None") + +head = ListNode(1) +head.next = ListNode(2) +head.next.next = ListNode(3) +head.next.next.next = ListNode(4) +head.next.next.next.next = ListNode(5) + +sol = Solution() +new_head = sol.removeNodes(head) + +print_list(new_head) + +``` diff --git a/solutions/lc-solutions/2400-2499/_category_.json b/solutions/lc-solutions/2400-2499/_category_.json new file mode 100644 index 0000000..b0bd2e9 --- /dev/null +++ b/solutions/lc-solutions/2400-2499/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "2400-2499", + "position": 26, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (2400 - 2499)" + } +} diff --git a/solutions/lc-solutions/2500-2599/2535-difference-between-element-sum-and-digit-sum-of-an-array.md b/solutions/lc-solutions/2500-2599/2535-difference-between-element-sum-and-digit-sum-of-an-array.md new file mode 100644 index 0000000..387362f --- /dev/null +++ b/solutions/lc-solutions/2500-2599/2535-difference-between-element-sum-and-digit-sum-of-an-array.md @@ -0,0 +1,125 @@ +--- +id: difference-between-element-sum-and-digit-sum-of-an-array +title: Difference Between Element Sum and Digit Sum of an Array +sidebar_label: 2535 - Difference Between Element Sum and Digit Sum of an Array +tags: + - Array + - Math + - LeetCode +description: "This is a solution to the Difference Between Element Sum and Digit Sum of an Array problem on LeetCode." +--- + +## Problem Description + +You are given a positive integer array `nums`. + +1. The **element sum** is the sum of all the elements in `nums`. +2. The **digit sum** is the sum of all the digits (not necessarily distinct) that appear in `nums`. + +Return the absolute difference between the **element sum** and **digit sum** of `nums`. + +Note that the absolute difference between two integers `x` and `y` is defined as `|x - y|`. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,15,6,3] +Output: 9 +Explanation: +The element sum of nums is 1 + 15 + 6 + 3 = 25. +The digit sum of nums is 1 + 1 + 5 + 6 + 3 = 16. +The absolute difference between the element sum and digit sum is |25 - 16| = 9. + +``` + +**Example 2:** + +``` +Input: nums = [1,2,3,4] +Output: 0 +Explanation: +The element sum of nums is 1 + 2 + 3 + 4 = 10. +The digit sum of nums is 1 + 2 + 3 + 4 = 10. +The absolute difference between the element sum and digit sum is |10 - 10| = 0. + +``` + + +### Constraints + +- `1 <= nums.length <= 2000` +- `1 <= nums[i] <= 2000` + + +### Approach + + +To solve this problem, we follow these steps: + +1. **Initialization**: Initialize two variables, `element_sum` and `digit_sum`, to zero. +2. **Element Sum Calculation**: Iterate through the array and add each integer to `element_sum`. +3. **Digit Sum Calculation**: For each integer in the array, repeatedly extract its last digit using the modulo operation, add this digit to `digit_sum`, and remove the last digit by performing integer division by 10. +4. **Compute Absolute Difference**: After processing all integers, compute the absolute difference between `element_sum` and `digit_sum` using `Math.abs()` and return the result. + + +#### Python3 + +```python +class Solution: + def differenceOfSum(self, nums: List[int]) -> int: + element_sum = sum(nums) + digit_sum = sum(int(digit) for num in nums for digit in str(num)) + return abs(element_sum - digit_sum) +``` + +#### Java + +```java +class Solution { + public int differenceOfSum(int[] nums) { + int element_sum = 0; + int digit_sum = 0; + for(int i=0;i0){ + x = val%10; + digit_sum +=x; + val = val/10; + } + } + return Math.abs(element_sum - digit_sum); + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + int differenceOfSum(vector& nums) { + int element_sum = 0; + int digit_sum = 0; + for (int i = 0; i < nums.size(); i++) { + element_sum += nums[i]; + + int val = nums[i]; + int x; + + while (val > 0) { + x = val % 10; + digit_sum += x; + val = val / 10; + } + } + return abs(element_sum - digit_sum); + } +}; + +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2500-2599/2540-minimum-common-value.md b/solutions/lc-solutions/2500-2599/2540-minimum-common-value.md new file mode 100644 index 0000000..a6ba83a --- /dev/null +++ b/solutions/lc-solutions/2500-2599/2540-minimum-common-value.md @@ -0,0 +1,123 @@ +--- +id: minimum-common-value +title: Minimum Common Value +sidebar_label: 2540-Minimum Common Value +tags: + - Array + - HashTable + - Two Pointers + - Binary Search +description: "This is a solution to minimum common value in leetcode " +--- + +## Problem Description + +Given two integer arrays nums1 and nums2, sorted in non-decreasing order, return the minimum integer common to both arrays. If there is no common integer amongst nums1 and nums2, return -1. + +Note that an integer is said to be common to nums1 and nums2 if both arrays have at least one occurrence of that integer. + + + +### Examples + +**Example 1:** + +``` +Input: nums1 = [1,2,3], nums2 = [2,4] +Output: 2 +Explanation: The smallest element common to both arrays is 2, so we return 2. + +``` +**Example 2:** +``` +Input: nums1 = [1,2,3,6], nums2 = [2,3,4,5] +Output: 2 +Explanation: There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned. + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(m+n)$ + +*** Space Complexity:** $O(n)$ + +### Constraints + +- `1 <= nums1.length, nums2.length <= 105` +- `1 <= nums1[i], nums2[j] <= 109` + + +### Solution +## Approach +Given two sorted arrays, the most efficient approach to find the minimum common element is using the two-pointer technique. Initialize two pointers, one for each array, both starting at the beginning. Compare the elements at these pointers: if they are equal, return the element as it is the smallest common element due to the sorted order. If the element in the first array is smaller, increment the pointer in the first array; if the element in the second array is smaller, increment the pointer in the second array. Continue this process until a common element is found or one of the arrays is fully traversed. If no common element is found, return -1. This approach leverages the sorted property to efficiently find the smallest common element with a time complexity of O(n + m), where n and m are the lengths of the arrays. + +## Code in Different Languages + + + + + +```cpp + +class Solution { +public: + int getCommon(std::vector& nums1, std::vector& nums2) { + std::unordered_set nums1Set(nums1.begin(), nums1.end()); + for (int num : nums2) { + if (nums1Set.find(num) != nums1Set.end()) { + return num; + } + } + return -1; + } +}; + + + +``` + + + + +```java +public class Solution { + public int getCommon(int[] nums1, int[] nums2) { + Set nums1Set = new HashSet<>(); + for (int num : nums1) { + nums1Set.add(num); + } + for (int num : nums2) { + if (nums1Set.contains(num)) { + return num; + } + } + return -1; + } + +``` + + + + +```python +class Solution(object): + def getCommon(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: int + """ + nums1=set(nums1) + for i in nums2: + if i in nums1: + return i + return -1 +``` + + + +## References + +- **LeetCode Problem**: [Minimum Common Value](https://leetcode.com/problems/minimum-common-value/description/) + +- **Solution Link**: [Minimum Common Value](https://leetcode.com/problems/minimum-common-value/post-solution/?submissionId=1198589019) diff --git a/solutions/lc-solutions/2500-2599/2543 - Check if Point is Reachable.md b/solutions/lc-solutions/2500-2599/2543 - Check if Point is Reachable.md new file mode 100644 index 0000000..3060a96 --- /dev/null +++ b/solutions/lc-solutions/2500-2599/2543 - Check if Point is Reachable.md @@ -0,0 +1,120 @@ +--- +id: check-if-point-is-reachable +title: Check if Point is Reachable +sidebar_label: 2543 Check if Point is Reachable +tags: + - Number Theory + - Java + - gcd + - Math +description: "This document provides a solution where we need to reach the point (targetX, targetY) using a finite number of steps." +--- + +## Problem + +There exists an infinitely large grid. You are currently at point $(1, 1)$, and you need to reach the point $(targetX, targetY)$ using a finite number of steps. + +In one Step, you can move from point $(x, y)$ to any one of the following points: + +- $(x, y - x)$ + +- $(x - y, y)$ + +- $(2 * x, y)$ + +- $(x, 2 * y)$ + +Given two integers $targetX$ and $targetY$ representing the X-coordinate and Y-coordinate of your final position, return $true$ if you can reach the point from $(1, 1)$ using some number of steps, and $false$ otherwise. + +### Examples + +**Example 1:** + +``` +Input: targetX = 6, targetY = 9 + +Output: false + +Explanation: It is impossible to reach (6,9) from (1,1) using any sequence of moves, so false is returned. + +``` + +**Example 2:** + +``` +Input: targetX = 4, targetY = 7 + +Output: true + +Explanation: You can follow the path (1,1) -> (1,2) -> (1,4) -> (1,8) -> (1,7) -> (2,7) -> (4,7). + +``` + +### Constraints + +- `1 <= targetX, targetY <= 10^9` + +--- + +## Approach + +To solve the problem, we need to understand the nature of the allowed moves: + +1. $(x, y - x)$ + +2. $(x - y, y)$ + +3. $(2 * x, y)$ + +4. $(x, 2 * y)$ + +These moves suggest that if we can reach a certain point **'(x, y)'**, we can generate other points by specific transformations. By analyzing the moves: + +- The first two moves involve subtraction, reducing one coordinate. + +- The last two moves involve multiplication by $2$. + +We can reverse the logic to check whether we can reach $(1, 1)$ from $(targetX, targetY)$. This reversal involves: + +- Checking if $targetX$ or $targetY$ can be divided by $2$ (to reverse the multiplication). + +- Checking if one coordinate can be reduced by subtracting the other. + +By reversing the operations, we trace the problem back to whether $(targetX, targetY)$ can be reduced to $(1, 1)$. + +The key insight here is that we only need to check if **'gcd(targetX, targetY)'** is a power of $2$. This is because if both $targetX$ and $targetY$ share a common factor other than $2$, it won't be possible to reach $(1, 1)$. + +## Solution for Check if Point is Reachable + +The given problem involves reaching a target point $(targetX, targetY)$ from the starting point $(1, 1)$ using a set of allowed moves. The challenge is to determine whether it's possible to reach the target using these moves. + +#### Code in Java + +```java +class Solution { + public boolean isReachable(int targetX, int targetY) { + return Integer.bitCount(gcd(targetX, targetY)) == 1; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} + +``` + +### Complexity Analysis + +#### Time Complexity: $O(log(min(targetX, targetY)))$ + +> **Reason**: Calculating the gcd of two numbers takes $O(log(min(targetX, targetY)))$ time using the Euclidean algorithm. + +#### Space Complexity: $O(1)$ + +> **Reason**: The space complexity is $O(1)$ since we are using a constant amount of extra space for computation (ignoring the space used by the recursive stack of the gcd function, which is logarithmic in terms of the depth of the recursion). + +# References + +- **LeetCode Problem:** [Check if Point is Reachable](https://leetcode.com/problems/check-if-point-is-reachable/description/) +- **Solution Link:** [Check if Point is Reachable Solution on LeetCode](https://leetcode.com/problems/check-if-point-is-reachable/solutions/) +- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/vivekvardhan43862/) diff --git a/solutions/lc-solutions/2500-2599/2547- Minimum Cost to split array.md b/solutions/lc-solutions/2500-2599/2547- Minimum Cost to split array.md new file mode 100644 index 0000000..8daa537 --- /dev/null +++ b/solutions/lc-solutions/2500-2599/2547- Minimum Cost to split array.md @@ -0,0 +1,158 @@ +--- +id: minimum-cost-to-split-an-array +title: Minimum Cost to Split an Array +sidebar_label: 2547 Minimum Cost to Split an Array +tags: + - Array + - Maths + - LeetCode + - C++ +description: "This is a solution to the Minimum Cost to Split an Array problem on LeetCode." +--- + +## Problem Description + +You are given an integer array nums and an integer k. + +Split the array into some number of non-empty subarrays. The cost of a split is the sum of the importance value of each subarray in the split. + +Let trimmed(subarray) be the version of the subarray where all numbers which appear only once are removed. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,1,2,1,3,3], k = 2 +Output: 8 +Explanation: We split nums to have two subarrays: [1,2], [1,2,1,3,3] + +``` + +**Example 2:** + +``` +Input: nums = [1,2,1,2,1], k = 2 +Output: 6 +Explanation: We split nums to have two subarrays: [1,2], [1,2,1] + +``` + +### Constraints + +- `1 <= nums.length <= 1000` +- `0 <= nums[i] < nums.length` +- `1 <= k <= 109` + +### Approach + +We design a function $dfs(i)$, which represents the minimum cost of splitting from index $i$. So the answer is $dfs(0)$. + +The calculation process of the function $dfs(i)$ is as follows: + +If $i \ge n$, it means that the splitting has reached the end of the array, and $0$ is returned at this time. +Otherwise, we enumerate the end $j$ of the subarray. During the process, we use an array or hash table cnt to count the number of times each number appears in the subarray, and use a variable one to count the number of numbers in the subarray that appear once. So the importance of the subarray is $k + j - i + 1 - one$, and the cost of splitting is $k + j - i + 1 - one + dfs(j + 1)$. We enumerate all $j$ and take the minimum value as the return value of $dfs(i)$. +During the process, we can use memoization search, that is, use an array $f$ to memorize the return value of the function $dfs(i)$ to avoid repeated calculations. + +The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$. + +#### Python3 + +```python +class Solution: + def minCost(self, nums: List[int], k: int) -> int: + @cache + def dfs(i): + if i >= n: + return 0 + cnt = Counter() + one = 0 + ans = inf + for j in range(i, n): + cnt[nums[j]] += 1 + if cnt[nums[j]] == 1: + one += 1 + elif cnt[nums[j]] == 2: + one -= 1 + ans = min(ans, k + j - i + 1 - one + dfs(j + 1)) + return ans + + n = len(nums) + return dfs(0) +``` + +#### Java + +```java +class Solution { + private Integer[] f; + private int[] nums; + private int n, k; + + public int minCost(int[] nums, int k) { + n = nums.length; + this.k = k; + this.nums = nums; + f = new Integer[n]; + return dfs(0); + } + + private int dfs(int i) { + if (i >= n) { + return 0; + } + if (f[i] != null) { + return f[i]; + } + int[] cnt = new int[n]; + int one = 0; + int ans = 1 << 30; + for (int j = i; j < n; ++j) { + int x = ++cnt[nums[j]]; + if (x == 1) { + ++one; + } else if (x == 2) { + --one; + } + ans = Math.min(ans, k + j - i + 1 - one + dfs(j + 1)); + } + return f[i] = ans; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + int minCost(vector& nums, int k) { + int n = nums.size(); + int f[n]; + memset(f, 0, sizeof f); + function dfs = [&](int i) { + if (i >= n) { + return 0; + } + if (f[i]) { + return f[i]; + } + int cnt[n]; + memset(cnt, 0, sizeof cnt); + int one = 0; + int ans = 1 << 30; + for (int j = i; j < n; ++j) { + int x = ++cnt[nums[j]]; + if (x == 1) { + ++one; + } else if (x == 2) { + --one; + } + ans = min(ans, k + j - i + 1 - one + dfs(j + 1)); + } + return f[i] = ans; + }; + return dfs(0); + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2500-2599/2548-Maximum Price to Fill a Bag.md b/solutions/lc-solutions/2500-2599/2548-Maximum Price to Fill a Bag.md new file mode 100644 index 0000000..9634fe5 --- /dev/null +++ b/solutions/lc-solutions/2500-2599/2548-Maximum Price to Fill a Bag.md @@ -0,0 +1,111 @@ +--- +id: maximum-price-to-fill-a-bag +title: Maximum Price to Fill a Bag +sidebar_label: 2548 Maximum Price to Fill a Bag +tags: + - Array + - Maths + - sort + - LeetCode + - java +description: "This is a solution to the Maximum Price to Fill a Bag problem on LeetCode." +--- + +## Problem Description + +You are given a 2D integer array items where items[i] = [pricei, weighti] denotes the price and weight of the ith item, respectively. + +You are also given a positive integer capacity. + +Each item can be divided into two items with ratios part1 and part2, where part1 + part2 == 1. + +The weight of the first item is weighti _ part1 and the price of the first item is pricei _ part1. +Similarly, the weight of the second item is weighti _ part2 and the price of the second item is pricei _ part2. +Return the maximum total price to fill a bag of capacity capacity with given items. If it is impossible to fill a bag return -1. Answers within 10-5 of the actual answer will be considered accepted. + +### Examples + +**Example 1:** + +``` +Input: items = [[50,1],[10,8]], capacity = 5 +Output: 55.00000 +Explanation: +We divide the 2nd item into two parts with part1 = 0.5 and part2 = 0.5. + +``` + +**Example 2:** + +``` +Input: items = [[100,30]], capacity = 50 +Output: -1.00000 +Explanation: It is impossible to fill a bag with the given item. + +``` + +### Constraints + +- `1 <= items.length <= 105` +- `items[i].length == 2` +- `1 <= pricei, weighti <= 104` +- `1 <= capacity <= 109` + +### Approach + +We sort the items in descending order by unit price, and then take out the items one by one until the backpack is full. + +If the backpack is not full in the end, return $-1$, otherwise return the total price. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$, where $n$ is the number of items. + +#### Python3 + +```python +class Solution: + def maxPrice(self, items: List[List[int]], capacity: int) -> float: + ans = 0 + for p, w in sorted(items, key=lambda x: x[1] / x[0]): + v = min(w, capacity) + ans += v / w * p + capacity -= v + return -1 if capacity else ans + +``` + +#### Java + +```java +class Solution { + public double maxPrice(int[][] items, int capacity) { + Arrays.sort(items, (a, b) -> a[1] * b[0] - a[0] * b[1]); + double ans = 0; + for (var e : items) { + int p = e[0], w = e[1]; + int v = Math.min(w, capacity); + ans += v * 1.0 / w * p; + capacity -= v; + } + return capacity > 0 ? -1 : ans; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + double maxPrice(vector>& items, int capacity) { + sort(items.begin(), items.end(), [&](const auto& a, const auto& b) { return a[1] * b[0] < a[0] * b[1]; }); + double ans = 0; + for (auto& e : items) { + int p = e[0], w = e[1]; + int v = min(w, capacity); + ans += v * 1.0 / w * p; + capacity -= v; + } + return capacity > 0 ? -1 : ans; + } +}; +``` diff --git a/solutions/lc-solutions/2500-2599/2549-Count Distinct Numbers on Board.md b/solutions/lc-solutions/2500-2599/2549-Count Distinct Numbers on Board.md new file mode 100644 index 0000000..cd96fca --- /dev/null +++ b/solutions/lc-solutions/2500-2599/2549-Count Distinct Numbers on Board.md @@ -0,0 +1,95 @@ +--- +id: count-distinct-numbers-on-board +title: Count Distinct Numbers on Board +sidebar_label: 2544 Count Distinct Numbers on Board +tags: + - Array + - Hash Table + - LeetCode + - C++ +description: "This is a solution to the Count Distinct Numbers on Board problem on LeetCode." +--- + +## Problem Description + +You are given a positive integer n, that is initially placed on a board. Every day, for 109 days, you perform the following procedure: + +For each number x present on the board, find all numbers `1 <= i <= n` such that x % i == 1. +Then, place those numbers on the board. +Return the number of distinct integers present on the board after 109 days have elapsed. + +### Examples + +**Example 1:** + +``` + +Input: n = 5 +Output: 4 +Explanation: Initially, 5 is present on the board. + +``` + +**Example 2:** + +``` +Input: n = 3 +Output: 2 +Explanation: +Since 3 % 2 == 1, 2 will be added to the board. +``` + +### Constraints + +- `1 <= n <= 100` + +### Approach + +Since every operation on the number n on the desktop will also cause the number n-1 to appear on the desktop, the final numbers on the desktop are [2,...n], that is, n-1 numbers. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the given number. + +#### Python3 + +```python +class Solution: + def distinctIntegers(self, n: int) -> int: + return max(1, n - 1) +``` + +#### Java + +```java +class Solution { + public int distinctIntegers(int n) { + return Math.max(1, n - 1); + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + int distinctIntegers(int n) { + return max(1, n - 1); + } +}; +``` + +#### Go + +```go +func distinctIntegers(n int) int { + return max(1, n-1) +} +``` + +#### TypeScript + +```ts +function distinctIntegers(n: number): number { + return Math.max(1, n - 1); +} +``` diff --git a/solutions/lc-solutions/2500-2599/2550. Count Collisions of Monkeys on a Polygon.md b/solutions/lc-solutions/2500-2599/2550. Count Collisions of Monkeys on a Polygon.md new file mode 100644 index 0000000..f3b6c10 --- /dev/null +++ b/solutions/lc-solutions/2500-2599/2550. Count Collisions of Monkeys on a Polygon.md @@ -0,0 +1,104 @@ +--- +id: alternating-digit-sum +title: Count Collisions of Monkeys on a Polygonaximum +sidebar_label: 2550 Count Collisions of Monkeys on a Polygonaximum + - Array + - Recursion + - LeetCode + - C++ +description: "This is a solution to the Count Collisions of Monkeys on a Polygonaximum problem on LeetCode." +--- + +## Problem Description + +There is a regular convex polygon with n vertices. The vertices are labeled from 0 to n - 1 in a clockwise direction, and each vertex has exactly one monkey. The following figure shows a convex polygon of 6 vertices. + +Simultaneously, each monkey moves to a neighboring vertex. A collision happens if at least two monkeys reside on the same vertex after the movement or intersect on an edge. + +Return the number of ways the monkeys can move so that at least one collision happens. Since the answer may be very large, return it modulo 10^9 + 7. + +### Examples + +**Example 1:** + +``` +Input: n = 3 +Output: 6 +Explanation: +There are 8 total possible movements. + +``` + +**Example 2:** + +``` +Input: n = 4 +Output: 14 + +``` + +### Constraints + +- `3 <= n <= 10^9` + +### Approach + +According to the problem description, each monkey has two ways of moving, either clockwise or counterclockwise. Therefore, there are a total of $2^n$ ways to move. The non-collision ways of moving are only two, that is, all monkeys move clockwise or all monkeys move counterclockwise. Therefore, the number of collision ways of moving is $2^n - 2$. + +We can use fast power to calculate the value of $2^n$, then use $2^n - 2$ to calculate the number of collision ways of moving, and finally take the remainder of $10^9 + 7$. + +The time complexity is $O(\log n)$, where $n$ is the number of monkeys. The space complexity is $O(1)$. + +#### Python3 + +```python +class Solution: + def monkeyMove(self, n: int) -> int: + mod = 10**9 + 7 + return (pow(2, n, mod) - 2) % mod +``` + +#### Java + +```java +class Solution { + public int monkeyMove(int n) { + final int mod = (int) 1e9 + 7; + return (qpow(2, n, mod) - 2 + mod) % mod; + } + + private int qpow(long a, int n, int mod) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return (int) ans; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + int monkeyMove(int n) { + const int mod = 1e9 + 7; + using ll = long long; + auto qpow = [&](ll a, int n) { + ll ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + }; + return (qpow(2, n) - 2 + mod) % mod; + } +}; +``` diff --git a/solutions/lc-solutions/2500-2599/2551-Put Marbles in Bags.md b/solutions/lc-solutions/2500-2599/2551-Put Marbles in Bags.md new file mode 100644 index 0000000..8a576fc --- /dev/null +++ b/solutions/lc-solutions/2500-2599/2551-Put Marbles in Bags.md @@ -0,0 +1,133 @@ +--- +id: put-marble-in-bags +title: Put Marbles in Bags +sidebar_label: 2551 Put Marbles in Bags + +tags: + - Greedy + - Array + - Sorting + - Heap (Priority Queue) +description: "This is a solution to the Put Marbles in Bags + problem on LeetCode." +--- + +## Problem Description + +You have k bags. You are given a 0-indexed integer array weights where weights[i] is the weight of the ith marble. You are also given the integer k. + +Divide the marbles into the k bags according to the following rules: + +No bag is empty. +If the ith marble and jth marble are in a bag, then all marbles with an index between the ith and jth indices should also be in that same bag. +If a bag consists of all the marbles with an index from i to j inclusively, then the cost of the bag is weights[i] + weights[j]. +The score after distributing the marbles is the sum of the costs of all the k bags. + +### Examples + +**Example 1:** + +``` + +Input: weights = [1,3,5,1], k = 2 +Output: 4 +Explanation: +The distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6. +The distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10. +Thus, we return their difference 10 - 6 = 4. + +``` + +**Example 2:** + +``` +Input: weights = [1, 3], k = 2 +Output: 0 +Explanation: The only distribution possible is [1],[3]. +Since both the maximal and minimal score are the same, we return 0. +``` + + +### Constraints + +- `1 <= k <= weights.length <= 105` +- `1 <= weights[i] <= 109` + + +### Approach + +We can transform the problem into: dividing the array `weights` into $k$ consecutive subarrays, that is, we need to find $k-1$ splitting points, each splitting point's cost is the sum of the elements on the left and right of the splitting point. The difference between the sum of the costs of the largest $k-1$ splitting points and the smallest $k-1$ splitting points is the answer. + +Therefore, we can process the array `weights` and transform it into an array `arr` of length $n-1$, where `arr[i] = weights[i] + weights[i+1]`. Then we sort the array `arr`, and finally calculate the difference between the sum of the costs of the largest $k-1$ splitting points and the smallest $k-1$ splitting points. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array `weights`. + + +#### Python3 + +```python +class Solution: + def putMarbles(self, weights: List[int], k: int) -> int: + arr = sorted(a + b for a, b in pairwise(weights)) + return sum(arr[len(arr) - k + 1 :]) - sum(arr[: k - 1]) +``` + +#### Java + +```java +class Solution { + public long putMarbles(int[] weights, int k) { + int n = weights.length; + int[] arr = new int[n - 1]; + for (int i = 0; i < n - 1; ++i) { + arr[i] = weights[i] + weights[i + 1]; + } + Arrays.sort(arr); + long ans = 0; + for (int i = 0; i < k - 1; ++i) { + ans -= arr[i]; + ans += arr[n - 2 - i]; + } + return ans; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + long long putMarbles(vector& weights, int k) { + int n = weights.size(); + vector arr(n - 1); + for (int i = 0; i < n - 1; ++i) { + arr[i] = weights[i] + weights[i + 1]; + } + sort(arr.begin(), arr.end()); + long long ans = 0; + for (int i = 0; i < k - 1; ++i) { + ans -= arr[i]; + ans += arr[n - 2 - i]; + } + return ans; + } +}; +``` + +#### Go + +```go +func putMarbles(weights []int, k int) (ans int64) { + n := len(weights) + arr := make([]int, n-1) + for i, w := range weights[:n-1] { + arr[i] = w + weights[i+1] + } + sort.Ints(arr) + for i := 0; i < k-1; i++ { + ans += int64(arr[n-2-i] - arr[i]) + } + return +} +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2500-2599/2555-Maximize Win From Two Segments.md b/solutions/lc-solutions/2500-2599/2555-Maximize Win From Two Segments.md new file mode 100644 index 0000000..787f8d7 --- /dev/null +++ b/solutions/lc-solutions/2500-2599/2555-Maximize Win From Two Segments.md @@ -0,0 +1,128 @@ +--- +id: maximiz-win-from-two-segments +title: Maximize Win From Two Segments +sidebar_label: 2555 Maximize Win From Two Segments + +tags: + - Binary Search + - Array + - Sorting + - Greedy +description: "This is a solution to the Maximize Win From Two Segments + problem on LeetCode." +--- + +## Problem Description + +There are some prizes on the X-axis. You are given an integer array prizePositions that is sorted in non-decreasing order, where prizePositions[i] is the position of the ith prize. There could be different prizes at the same position on the line. You are also given an integer k. + +You are allowed to select two segments with integer endpoints. The length of each segment must be k. You will collect all prizes whose position falls within at least one of the two selected segments (including the endpoints of the segments). The two selected segments may intersect. + +For example if k = 2, you can choose segments [1, 3] and [2, 4], and you will win any prize i that satisfies `1 <= prizePositions[i] <= 3 or 2 <= prizePositions[i] <= 4` +Return the maximum number of prizes you can win if you choose the two segments optimally. + +### Examples + +**Example 1:** + +``` + +Input: prizePositions = [1,1,2,2,3,3,5], k = 2 +Output: 7 +Explanation: In this example, you can win all 7 prizes by selecting two segments [1, 3] and [3, 5]. + +``` + +**Example 2:** +``` +Input: prizePositions = [1,2,3,4], k = 0 +Output: 2 +Explanation: For this example, one choice for the segments is [3, 3] and [4, 4], and you will be able to get 2 prizes. + +``` + + +### Constraints + +- `1 <= prizePositions.length <= 10^5` +- `1 <= prizePositions[i] <= 10^9` + + +### Approach + +We define $f[i]$ as the maximum number of prizes that can be obtained by selecting a segment of length $k$ from the first $i$ prizes. Initially, $f[0] = 0$. We define the answer variable as $ans = 0$. + +Next, we enumerate the position $x$ of each prize, and use binary search to find the leftmost prize index $j$ such that $prizePositions[j] \geq x - k$. At this point, we update the answer $ans = \max(ans, f[j] + i - j)$, and update $f[i] = \max(f[i - 1], i - j)$. + +Finally, we return $ans$. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the number of prizes. + + + +#### Python3 + +```python +class Solution: + def maximizeWin(self, prizePositions: List[int], k: int) -> int: + n = len(prizePositions) + f = [0] * (n + 1) + ans = 0 + for i, x in enumerate(prizePositions, 1): + j = bisect_left(prizePositions, x - k) + ans = max(ans, f[j] + i - j) + f[i] = max(f[i - 1], i - j) + return ans +``` + +#### Java + +```java +class Solution { + public int maximizeWin(int[] prizePositions, int k) { + int n = prizePositions.length; + int[] f = new int[n + 1]; + int ans = 0; + for (int i = 1; i <= n; ++i) { + int x = prizePositions[i - 1]; + int j = search(prizePositions, x - k); + ans = Math.max(ans, f[j] + i - j); + f[i] = Math.max(f[i - 1], i - j); + } + return ans; + } + + private int search(int[] nums, int x) { + int left = 0, right = nums.length; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + int maximizeWin(vector& prizePositions, int k) { + int n = prizePositions.size(); + vector f(n + 1); + int ans = 0; + for (int i = 1; i <= n; ++i) { + int x = prizePositions[i - 1]; + int j = lower_bound(prizePositions.begin(), prizePositions.end(), x - k) - prizePositions.begin(); + ans = max(ans, f[j] + i - j); + f[i] = max(f[i - 1], i - j); + } + return ans; + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2500-2599/2556-Disconnect Path in a Binary Matrix by at Most One Flip.md b/solutions/lc-solutions/2500-2599/2556-Disconnect Path in a Binary Matrix by at Most One Flip.md new file mode 100644 index 0000000..23afa22 --- /dev/null +++ b/solutions/lc-solutions/2500-2599/2556-Disconnect Path in a Binary Matrix by at Most One Flip.md @@ -0,0 +1,142 @@ +--- +id: disconnect-path-in-a-binary-matrix-by-at-most-one-flip +title: Disconnect Path in a Binary Matrix by at Most One Flip +sidebar_label: 2556 Disconnect Path in a Binary Matrix by at Most One Flip + +tags: + - Binary Search + - Array + - Sorting + - Greedy +description: "This is a solution to the Disconnect Path in a Binary Matrix by at Most One Flip + problem on LeetCode." +--- + +## Problem Description + +You are given a 0-indexed m x n binary matrix grid. You can move from a cell (row, col) to any of the cells (row + 1, col) or (row, col + 1) that has the value 1. The matrix is disconnected if there is no path from (0, 0) to (m - 1, n - 1). + +You can flip the value of at most one (possibly none) cell. You cannot flip the cells (0, 0) and (m - 1, n - 1). + +Return true if it is possible to make the matrix disconnect or false otherwise. + +Note that flipping a cell changes its value from 0 to 1 or from 1 to 0. + + +### Examples + +**Example 1:** + +``` + +Input: grid = [[1,1,1],[1,0,0],[1,1,1]] +Output: true +Explanation: We can change the cell shown in the diagram above. There is no path from (0, 0) to (2, 2) in the resulting grid. + +``` + +**Example 2:** + +``` +Input: grid = [[1,1,1],[1,0,1],[1,1,1]] +Output: false +Explanation: It is not possible to change at most one cell such that there is not path from (0, 0) to (2, 2). + +``` + + +### Constraints + +- `m == grid.length` +- `n == grid[i].length` +- `1 <= m, n <= 1000` +- `grid[0][0] == grid[m - 1][n - 1] == 1` +- `grid[i][j] is either 0 or 1` + + +### Approach +First, we perform a DFS traversal to determine whether there is a path from $(0, 0)$ to $(m - 1, n - 1)$, and we denote the result as $a$. During the DFS process, we set the value of the visited cells to $0$ to prevent revisiting. + +Next, we set the values of $(0, 0)$ and $(m - 1, n - 1)$ to $1$, and perform another DFS traversal to determine whether there is a path from $(0, 0)$ to $(m - 1, n - 1)$, and we denote the result as $b$. During the DFS process, we set the value of the visited cells to $0$ to avoid revisiting. + +Finally, if both $a$ and $b$ are `true`, we return `false`, otherwise, we return `true`. + +The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Where $m$ and $n$ are the number of rows and columns of the matrix, respectively. + + +#### Python3 + +```python +class Solution: + def isPossibleToCutPath(self, grid: List[List[int]]) -> bool: + def dfs(i, j): + if i >= m or j >= n or grid[i][j] == 0: + return False + grid[i][j] = 0 + if i == m - 1 and j == n - 1: + return True + return dfs(i + 1, j) or dfs(i, j + 1) + + m, n = len(grid), len(grid[0]) + a = dfs(0, 0) + grid[0][0] = grid[-1][-1] = 1 + b = dfs(0, 0) + return not (a and b) +``` + +#### Java + +```java +class Solution { + private int[][] grid; + private int m; + private int n; + + public boolean isPossibleToCutPath(int[][] grid) { + this.grid = grid; + m = grid.length; + n = grid[0].length; + boolean a = dfs(0, 0); + grid[0][0] = 1; + grid[m - 1][n - 1] = 1; + boolean b = dfs(0, 0); + return !(a && b); + } + + private boolean dfs(int i, int j) { + if (i >= m || j >= n || grid[i][j] == 0) { + return false; + } + if (i == m - 1 && j == n - 1) { + return true; + } + grid[i][j] = 0; + return dfs(i + 1, j) || dfs(i, j + 1); + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + bool isPossibleToCutPath(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + function dfs = [&](int i, int j) -> bool { + if (i >= m || j >= n || grid[i][j] == 0) { + return false; + } + if (i == m - 1 && j == n - 1) { + return true; + } + grid[i][j] = 0; + return dfs(i + 1, j) || dfs(i, j + 1); + }; + bool a = dfs(0, 0); + grid[0][0] = grid[m - 1][n - 1] = 1; + bool b = dfs(0, 0); + return !(a && b); + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2500-2599/2557-Maximum Number of Integers to Choose From a Range II.md b/solutions/lc-solutions/2500-2599/2557-Maximum Number of Integers to Choose From a Range II.md new file mode 100644 index 0000000..36c6a3c --- /dev/null +++ b/solutions/lc-solutions/2500-2599/2557-Maximum Number of Integers to Choose From a Range II.md @@ -0,0 +1,157 @@ +--- +id: maximum-number-of-integers-to-choose-from-a-range-ii +title: Maximum Number of Integers to Choose From a Range II +sidebar_label: 2557 Maximum Number of Integers to Choose From a Range II + +tags: + - Binary Search + - Array + - Sorting + - Greedy +description: "This is a solution to the Maximum Number of Integers to Choose From a Range II + problem on LeetCode." +--- + +## Problem Description + +You are given an integer array banned and two integers n and maxSum. You are choosing some number of integers following the below rules: + +The chosen integers have to be in the range [1, n]. +Each integer can be chosen at most once. +The chosen integers should not be in the array banned. +The sum of the chosen integers should not exceed maxSum. +Return the maximum number of integers you can choose following the mentioned rules. + + + +### Examples + +**Example 1:** + +``` + +Input: banned = [1,4,6], n = 6, maxSum = 4 +Output: 1 +Explanation: You can choose the integer 3. +3 is in the range [1, 6], and do not appear in banned. The sum of the chosen integers is 3, which does not exceed maxSum. + +``` + +**Example 2:** + +``` +Input: banned = [4,3,5,6], n = 7, maxSum = 18 +Output: 3 +Explanation: You can choose the integers 1, 2, and 7. +All these integers are in the range [1, 7], all do not appear in banned, and their sum is 18, which does not exceed maxSum. + +``` + + +### Constraints + +- `1 <= banned.length <= 105` +- `1 <= banned[i] <= n <= 109` +- `1 <= maxSum <= 1015` + + +### Approach + +We can add $0$ and $n + 1$ to the array `banned`, then deduplicate and sort the array `banned`. + +Next, we enumerate every two adjacent elements $i$ and $j$ in the array `banned`. The range of selectable integers is $[i + 1, j - 1]$. We use binary search to enumerate the number of elements we can select in this range, find the maximum number of selectable elements, and then add it to $ans$. At the same time, we subtract the sum of these elements from `maxSum`. If `maxSum` is less than $0$, we break the loop. Return the answer. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array `banned`. + + +#### Python3 + +```python +class Solution: + def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: + banned.extend([0, n + 1]) + ban = sorted(set(banned)) + ans = 0 + for i, j in pairwise(ban): + left, right = 0, j - i - 1 + while left < right: + mid = (left + right + 1) >> 1 + if (i + 1 + i + mid) * mid // 2 <= maxSum: + left = mid + else: + right = mid - 1 + ans += left + maxSum -= (i + 1 + i + left) * left // 2 + if maxSum <= 0: + break + return ans +``` + +#### Java + +```java +class Solution { + public int maxCount(int[] banned, int n, long maxSum) { + Set black = new HashSet<>(); + black.add(0); + black.add(n + 1); + for (int x : banned) { + black.add(x); + } + List ban = new ArrayList<>(black); + Collections.sort(ban); + int ans = 0; + for (int k = 1; k < ban.size(); ++k) { + int i = ban.get(k - 1), j = ban.get(k); + int left = 0, right = j - i - 1; + while (left < right) { + int mid = (left + right + 1) >>> 1; + if ((i + 1 + i + mid) * 1L * mid / 2 <= maxSum) { + left = mid; + } else { + right = mid - 1; + } + } + ans += left; + maxSum -= (i + 1 + i + left) * 1L * left / 2; + if (maxSum <= 0) { + break; + } + } + return ans; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + int maxCount(vector& banned, int n, long long maxSum) { + banned.push_back(0); + banned.push_back(n + 1); + sort(banned.begin(), banned.end()); + banned.erase(unique(banned.begin(), banned.end()), banned.end()); + int ans = 0; + for (int k = 1; k < banned.size(); ++k) { + int i = banned[k - 1], j = banned[k]; + int left = 0, right = j - i - 1; + while (left < right) { + int mid = left + ((right - left + 1) / 2); + if ((i + 1 + i + mid) * 1LL * mid / 2 <= maxSum) { + left = mid; + } else { + right = mid - 1; + } + } + ans += left; + maxSum -= (i + 1 + i + left) * 1LL * left / 2; + if (maxSum <= 0) { + break; + } + } + return ans; + } +}; +``` diff --git a/solutions/lc-solutions/2500-2599/2559-Count Vowel Strings in Ranges.md b/solutions/lc-solutions/2500-2599/2559-Count Vowel Strings in Ranges.md new file mode 100644 index 0000000..2a4cdfa --- /dev/null +++ b/solutions/lc-solutions/2500-2599/2559-Count Vowel Strings in Ranges.md @@ -0,0 +1,134 @@ +--- +id: count-vowel-strings-in-ranges +title: Count Vowel Strings in Ranges +sidebar_label: 2559 Count Vowel Strings in Ranges +tags: + - Array + - String + - LeetCode + - Prefix Sum +description: "This is a solution to the Count Vowel Strings in Ranges problem on LeetCode." +--- + +## Problem Description + +You are given a 0-indexed array of strings words and a 2D array of integers queries. + +Each query queries[i] = [li, ri] asks us to find the number of strings present in the range li to ri (both inclusive) of words that start and end with a vowel. + +Return an array ans of size queries.length, where ans[i] is the answer to the ith query. + +Note that the vowel letters are 'a', 'e', 'i', 'o', and 'u'. + +### Examples + +**Example 1:** + +``` +Input: words = ["aba","bcb","ece","aa","e"], queries = [[0,2],[1,4],[1,1]] +Output: [2,3,0] +Explanation: The strings starting and ending with a vowel are "aba", "ece", "aa" and "e". +The answer to the query [0,2] is 2 (strings "aba" and "ece"). +to query [1,4] is 3 (strings "ece", "aa", "e"). +to query [1,1] is 0. +We return [2,3,0]. + +``` + +**Example 2:** + +``` +Input: words = ["a","e","i"], queries = [[0,2],[0,1],[2,2]] +Output: [3,2,1] +Explanation: Every string satisfies the conditions, so we return [3,2,1]. + +``` + + +### Constraints + +- `1 <= words.length <= 10^5` +- `1 <= words[i].length <= 40` +- `sum(words[i].length) <= 3 * 10^5` + + +### Approach +We can preprocess all the indices of the strings that start and end with a vowel, and record them in order in the array $nums$. + +Next, we iterate through each query $(l, r)$, and use binary search to find the first index $i$ in $nums$ that is greater than or equal to $l$, and the first index $j$ that is greater than $r$. Therefore, the answer to the current query is $j - i$. + +The time complexity is $O(n + m \times \log n)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of the arrays $words$ and $queries$, respectively. + + +#### Python3 + +```python +class Solution: + def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]: + vowels = set("aeiou") + nums = [i for i, w in enumerate(words) if w[0] in vowels and w[-1] in vowels] + return [bisect_right(nums, r) - bisect_left(nums, l) for l, r in queries] +``` + +#### Java + +```java +class Solution { + private List nums = new ArrayList<>(); + + public int[] vowelStrings(String[] words, int[][] queries) { + Set vowels = Set.of('a', 'e', 'i', 'o', 'u'); + for (int i = 0; i < words.length; ++i) { + char a = words[i].charAt(0), b = words[i].charAt(words[i].length() - 1); + if (vowels.contains(a) && vowels.contains(b)) { + nums.add(i); + } + } + int m = queries.length; + int[] ans = new int[m]; + for (int i = 0; i < m; ++i) { + int l = queries[i][0], r = queries[i][1]; + ans[i] = search(r + 1) - search(l); + } + return ans; + } + + private int search(int x) { + int l = 0, r = nums.size(); + while (l < r) { + int mid = (l + r) >> 1; + if (nums.get(mid) >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + vector vowelStrings(vector& words, vector>& queries) { + unordered_set vowels = {'a', 'e', 'i', 'o', 'u'}; + vector nums; + for (int i = 0; i < words.size(); ++i) { + char a = words[i][0], b = words[i].back(); + if (vowels.count(a) && vowels.count(b)) { + nums.push_back(i); + } + } + vector ans; + for (auto& q : queries) { + int l = q[0], r = q[1]; + int cnt = upper_bound(nums.begin(), nums.end(), r) - lower_bound(nums.begin(), nums.end(), l); + ans.push_back(cnt); + } + return ans; + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2500-2599/2560-House Robber IV.md b/solutions/lc-solutions/2500-2599/2560-House Robber IV.md new file mode 100644 index 0000000..944333d --- /dev/null +++ b/solutions/lc-solutions/2500-2599/2560-House Robber IV.md @@ -0,0 +1,140 @@ +--- +id: house-robber-IV +title: House Robber IV +sidebar_label: 2560 House Robber IV +tags: + - Array + - Binary Search + - LeetCode +description: "This is a solution to the House Robber IV problem on LeetCode." +--- + +## Problem Description + +There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he refuses to steal from adjacent homes. + +The capability of the robber is the maximum amount of money he steals from one house of all the houses he robbed. + +You are given an integer array nums representing how much money is stashed in each house. More formally, the ith house from the left has nums[i] dollars. + +You are also given an integer k, representing the minimum number of houses the robber will steal from. It is always possible to steal at least k houses. + +Return the minimum capability of the robber out of all the possible ways to steal at least k houses. + +### Examples + +**Example 1:** + +``` +Input: nums = [2,3,5,9], k = 2 +Output: 5 +Explanation: +There are three ways to rob at least 2 houses: +- Rob the houses at indices 0 and 2. Capability is max(nums[0], nums[2]) = 5. +- Rob the houses at indices 0 and 3. Capability is max(nums[0], nums[3]) = 9. +- Rob the houses at indices 1 and 3. Capability is max(nums[1], nums[3]) = 9. +Therefore, we return min(5, 9, 9) = 5. + +``` + +**Example 2:** + +``` +Input: nums = [2,7,9,3,1], k = 2 +Output: 2 +Explanation: There are 7 ways to rob the houses. The way which leads to minimum capability is to rob the house at index 0 and 4. Return max(nums[0], nums[4]) = 2. + +``` + + +### Constraints + +- `1 <= nums.length <= 10^5` +- `1 <= nums[i] <= 10^9` +- `1 <= k <= (nums.length + 1)/2` + + +### Approach +The problem is asking for the minimum stealing ability of the thief. We can use binary search to enumerate the stealing ability of the thief. For the enumerated ability $x$, we can use a greedy approach to determine whether the thief can steal at least $k$ houses. Specifically, we traverse the array from left to right. For the current house $i$ we are traversing, if $nums[i] \leq x$ and the difference between the index of $i$ and the last stolen house is greater than $1$, then the thief can steal house $i$. Otherwise, the thief cannot steal house $i$. We accumulate the number of stolen houses. If the number of stolen houses is greater than or equal to $k$, it means that the thief can steal at least $k$ houses, and at this time, the stealing ability $x$ of the thief might be the minimum. Otherwise, the stealing ability $x$ of the thief is not the minimum. + +The time complexity is $O(n \times \log m)$, and the space complexity is $O(1)$. Where $n$ and $m$ are the length of the array $nums$ and the maximum value in the array $nums$, respectively. + + +#### Python3 + +```python +class Solution: + def minCapability(self, nums: List[int], k: int) -> int: + def f(x): + cnt, j = 0, -2 + for i, v in enumerate(nums): + if v > x or i == j + 1: + continue + cnt += 1 + j = i + return cnt >= k + + return bisect_left(range(max(nums) + 1), True, key=f) +``` + +#### Java + +```java +class Solution { + public int minCapability(int[] nums, int k) { + int left = 0, right = (int) 1e9; + while (left < right) { + int mid = (left + right) >> 1; + if (f(nums, mid) >= k) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } + + private int f(int[] nums, int x) { + int cnt = 0, j = -2; + for (int i = 0; i < nums.length; ++i) { + if (nums[i] > x || i == j + 1) { + continue; + } + ++cnt; + j = i; + } + return cnt; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + int minCapability(vector& nums, int k) { + auto f = [&](int x) { + int cnt = 0, j = -2; + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] > x || i == j + 1) { + continue; + } + ++cnt; + j = i; + } + return cnt >= k; + }; + int left = 0, right = *max_element(nums.begin(), nums.end()); + while (left < right) { + int mid = (left + right) >> 1; + if (f(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` diff --git a/solutions/lc-solutions/2500-2599/2561-Rearranging Fruits.md b/solutions/lc-solutions/2500-2599/2561-Rearranging Fruits.md new file mode 100644 index 0000000..2038f00 --- /dev/null +++ b/solutions/lc-solutions/2500-2599/2561-Rearranging Fruits.md @@ -0,0 +1,150 @@ +--- +id: rearranging-fruits +title: Rearranging Fruits +sidebar_label: 2561 Rearranging Fruits +tags: + - Array + - String + - Greedy + - Hash Table +description: "This is a solution to the Rearranging Fruits problem on LeetCode." +--- + +## Problem Description +You have two fruit baskets containing n fruits each. You are given two 0-indexed integer arrays basket1 and basket2 representing the cost of fruit in each basket. You want to make both baskets equal. To do so, you can use the following operation as many times as you want: + +Chose two indices i and j, and swap the ith fruit of basket1 with the jth fruit of basket2. +The cost of the swap is min(basket1[i],basket2[j]). +Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets. + +Return the minimum cost to make both the baskets equal or -1 if impossible. + +### Examples + +**Example 1:** + +``` +Input: basket1 = [4,2,2,2], basket2 = [1,4,1,2] +Output: 1 +Explanation: Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal. +``` + +**Example 2:** + +``` +Input: basket1 = [2,3,4,1], basket2 = [3,2,5,1] +Output: -1 +Explanation: It can be shown that it is impossible to make both the baskets equal. + +``` + + +### Constraints + +- `basket1.length == basket2.length` +- `1 <= basket1.length <= 10^5` +- `1 <= basket1[i],basket2[i] <= 10^9` + + +### Approach +First, we can remove the common elements from both arrays. For the remaining numbers, the occurrence of each number must be even, otherwise, it is impossible to construct identical arrays. Let's denote the arrays after removing common elements as $a$ and $b$. + +Next, we consider how to perform the swaps. + +If we want to swap the smallest number in $a$, we need to find the largest number in $b$ to swap with it; similarly, if we want to swap the smallest number in $b$, we need to find the largest number in $a$ to swap with it. This can be achieved by sorting. + +However, there is another swapping scheme. We can use a smallest number $mi$ as a transition element, first swap the number in $a$ with $mi$, and then swap $mi$ with the number in $b$. In this way, the cost of swapping is $2 \times mi$. + +In the code implementation, we can directly merge arrays $a$ and $b$ into an array $nums$, and then sort the array $nums$. Next, we enumerate the first half of the numbers, calculate the minimum cost each time, and add it to the answer. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array. + + + +#### Python3 + +```python +class Solution: + def minCost(self, basket1: List[int], basket2: List[int]) -> int: + cnt = Counter() + for a, b in zip(basket1, basket2): + cnt[a] += 1 + cnt[b] -= 1 + mi = min(cnt) + nums = [] + for x, v in cnt.items(): + if v % 2: + return -1 + nums.extend([x] * (abs(v) // 2)) + nums.sort() + m = len(nums) // 2 + return sum(min(x, mi * 2) for x in nums[:m]) +``` + +#### Java + +```java +class Solution { + public long minCost(int[] basket1, int[] basket2) { + int n = basket1.length; + Map cnt = new HashMap<>(); + for (int i = 0; i < n; ++i) { + cnt.merge(basket1[i], 1, Integer::sum); + cnt.merge(basket2[i], -1, Integer::sum); + } + int mi = 1 << 30; + List nums = new ArrayList<>(); + for (var e : cnt.entrySet()) { + int x = e.getKey(), v = e.getValue(); + if (v % 2 != 0) { + return -1; + } + for (int i = Math.abs(v) / 2; i > 0; --i) { + nums.add(x); + } + mi = Math.min(mi, x); + } + Collections.sort(nums); + int m = nums.size(); + long ans = 0; + for (int i = 0; i < m / 2; ++i) { + ans += Math.min(nums.get(i), mi * 2); + } + return ans; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + long long minCost(vector& basket1, vector& basket2) { + int n = basket1.size(); + unordered_map cnt; + for (int i = 0; i < n; ++i) { + cnt[basket1[i]]++; + cnt[basket2[i]]--; + } + int mi = 1 << 30; + vector nums; + for (auto& [x, v] : cnt) { + if (v % 2) { + return -1; + } + for (int i = abs(v) / 2; i; --i) { + nums.push_back(x); + } + mi = min(mi, x); + } + sort(nums.begin(), nums.end()); + int m = nums.size(); + long long ans = 0; + for (int i = 0; i < m / 2; ++i) { + ans += min(nums[i], mi * 2); + } + return ans; + } +}; +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2500-2599/2582-Pass-The-Pillow.md b/solutions/lc-solutions/2500-2599/2582-Pass-The-Pillow.md new file mode 100644 index 0000000..5910ed7 --- /dev/null +++ b/solutions/lc-solutions/2500-2599/2582-Pass-The-Pillow.md @@ -0,0 +1,147 @@ +--- +id: pass-the-pillow +title: Pass the Pillow +sidebar_label: 2582. Pass the Pillow +tags: +- Math +- Simulation +description: "Solution to Leetcode 2582. Pass the Pillow " +--- + +## Problem Description + +There are n people standing in a line labeled from 1 to n. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the end of the line, the direction changes, and people continue passing the pillow in the opposite direction. + +For example, once the pillow reaches the nth person they pass it to the $(n-1)$ th person, then to the $(n-2)$ th person and so on. +Given the two positive integers n and time, return the index of the person holding the pillow after time seconds. + + +### Examples + +**Example 1:** + +``` +Input: n = 4, time = 5 +Output: 2 +Explanation: People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2. +After five seconds, the 2nd person is holding the pillow. +``` + +**Example 2:** + +``` +Input: n = 3, time = 2 +Output: 3 +Explanation: People pass the pillow in the following way: 1 -> 2 -> 3. +After two seconds, the 3rd person is holding the pillow. + +``` + + + +### Constraints +- `2 <= n <= 1000` +- `1 <= time <= 1000` + +### Approach +1. To understand how the pillow moves among the people in line, let understand the pattern of its movement. The pillow completes a full round when it travels from the first person to the last or vice versa. Each complete round takes $(n-1)$ seconds, where n is the total number of people. + +To determine how many complete rounds the pillow makes within a given time time, we divide time by $(n-1)$. This gives us fullRounds, representing the number of times the pillow moves from one end of the line to the other. The remainder of this division, extraTime = time % (n - 1), indicates the extra time left after completing these full rounds. + +Now, let's consider the direction of the pillow's movement: + +- If fullRounds is even, the pillow moves forward along the line. +- If fullRounds is odd, the pillow moves backward. This directional change occurs after each complete round. +- In the case of forward movement (fullRounds is even), the person holding the pillow after the extra time will be positioned at extraTime + 1 (since we start counting positions from one). Conversely, during backward movement (fullRounds is odd), the person holding the pillow will be at position n - extraTime + +### Complexity + +Time complexity: $O(1)$.Regardless of the size of the input, we always perform a fixed number of operations thus the time complexity is $O(1)$. + +Space complexity: $O(1)$.Regardless of the size of the input, we only use a fixed number of auxiliary variables, thus the space complexity is $O(1)$. + + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp +class Solution { +public: + int passThePillow(int n, int time) { + // Calculate the number of complete rounds of pillow passing + int fullRounds = time / (n - 1); + + // Calculate the remaining time after complete rounds + int extraTime = time % (n - 1); + + // Determine the position of the person holding the pillow + // If fullRounds is even, the pillow is moving forward. + // If fullRounds is odd, the pillow is moving backward. + if (fullRounds % 2 == 0) { + return extraTime + 1; // Position when moving forward + } else { + return n - extraTime; // Position when moving backward + } + } +}; + ``` + +#### JAVA + +```java +class Solution { + + public int passThePillow(int n, int time) { + // Calculate the number of complete rounds of pillow passing + int fullRounds = time / (n - 1); + + // Calculate the remaining time after complete rounds + int extraTime = time % (n - 1); + + // Determine the position of the person holding the pillow + // If fullRounds is even, the pillow is moving forward. + // If fullRounds is odd, the pillow is moving backward. + if (fullRounds % 2 == 0) { + return extraTime + 1; // Position when moving forward + } else { + return n - extraTime; // Position when moving backward + } + } +} +``` + +#### PYTHON + +```python +class Solution: + def passThePillow(self, n, time): + # Calculate the number of complete rounds of pillow passing + full_rounds = time // (n - 1) + + # Calculate the remaining time after complete rounds + extra_time = time % (n - 1) + + # Determine the position of the person holding the pillow + # If full_rounds is even, the pillow is moving forward. + # If full_rounds is odd, the pillow is moving backward. + if full_rounds % 2 == 0: + return extra_time + 1 # Position when moving forward + else: + return n - extra_time # Position when moving backward + +``` + + + +### Complexity Analysis + +- Time Complexity: $O(1)$ + +- Space Complexity: $O(1)$ + +### References + +- **LeetCode Problem**: Pass the Pillow \ No newline at end of file diff --git a/solutions/lc-solutions/2500-2599/_category_.json b/solutions/lc-solutions/2500-2599/_category_.json new file mode 100644 index 0000000..84f83cb --- /dev/null +++ b/solutions/lc-solutions/2500-2599/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "2500-2599", + "position": 27, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (2500 - 2599)" + } +} diff --git a/solutions/lc-solutions/2600-2699/2600-k-items-with-the-maximum-sum.md b/solutions/lc-solutions/2600-2699/2600-k-items-with-the-maximum-sum.md new file mode 100644 index 0000000..ea4a583 --- /dev/null +++ b/solutions/lc-solutions/2600-2699/2600-k-items-with-the-maximum-sum.md @@ -0,0 +1,147 @@ +--- +id: k-items-with-the-maximum-sum +title: K Items With the Maximum Sum +sidebar_label: 2600. K Items With the Maximum Sum +tags: +- Math +- Greedy +description: "Solution to Leetcode 2600. K Items With the Maximum Sum" +--- + +## Problem Description + +There is a bag that consists of items, each item has a number 1, 0, or -1 written on it. + +You are given four non-negative integers numOnes, numZeros, numNegOnes, and k. + +The bag initially contains: +- numOnes items with 1s written on them. +- numZeroes items with 0s written on them. +- numNegOnes items with -1s written on them. + + +We want to pick exactly k items among the available items. Return the maximum possible sum of numbers written on the items. + + +### Examples + +**Example 1:** + +``` +Input: numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2 +Output: 2 +Explanation: We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 2 items with 1 written on them and get a sum in a total of 2. +It can be proven that 2 is the maximum possible sum. +``` + +**Example 2:** + +``` +Input: numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4 +Output: 3 +Explanation: We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 3 items with 1 written on them, and 1 item with 0 written on it, and get a sum in a total of 3. +It can be proven that 3 is the maximum possible sum. + +``` + + + +### Constraints +- `0 <= numOnes, numZeros, numNegOnes <= 50` +- `0 <= k <= numOnes + numZeros + numNegOnes` + +### Approach +To get the maximum sum possible we first need to select number of 1's and then if k is still more then count of 1's then we need to select some 0's which will add 0 to our sum, after selecting 1's and 0's if k is still positive then we need to select -1's which will reduce our sum. + +### Complexity + +Time complexity: $O(1)$ +Space complexity: $O(1)$ + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp +class Solution { +public: + int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { + int total=0; + + int select=min(numOnes,k); //selecting ones + total+=select; //adding to sum + k-=select; // reducing k + + select=min(numZeros,k); // selecting 0's if k is non zero otherwise select will be 0 + k-=select; // reducing k if k is non zero + + select=min(numNegOnes,k); // selecting -1's if k is non zero otherwise select will be 0 + total-=select; //reducing the score by select because we selected select no of -1's in case of k =0 we will reduce 0 + + return total; + } +}; + ``` + +#### JAVA + +```java +class Solution { + public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { + + int max = 0; // the maximum sum + + // while we still need to select k numbers + while(k > 0){ + + // if we have at least one 1 left, add it to the sum + if(numOnes > 0){ + numOnes--; + max++; + k--; + } + // if we have at least one 0 left, skip it + else if(numZeros > 0){ + numZeros--; + k--; + } + // if we have at least one -1 left, add it to the sum + else{ + numNegOnes--; + max--; + k--; + } + } + // if we did not select k numbers, return the maximum sum anyway + return max; + } +} +``` + +#### PYTHON + +```python +class Solution: + def kItemsWithMaximumSum(self, numOnes: int, numZeros: int, numNegOnes: int, k: int) -> int: + if numOnes > k: + return k + rem = k - numOnes - numZeros + if rem <= 0: + return numOnes + return numOnes - rem + +``` + + + +### Complexity Analysis + +- Time Complexity: $O(1)$ + +- Space Complexity: $O(1)$ + +### References + +- **LeetCode Problem**: K Items With the Maximum Sum \ No newline at end of file diff --git a/solutions/lc-solutions/2600-2699/2605-form-smallest-number-from-two-digit-arrays.md b/solutions/lc-solutions/2600-2699/2605-form-smallest-number-from-two-digit-arrays.md new file mode 100644 index 0000000..909c776 --- /dev/null +++ b/solutions/lc-solutions/2600-2699/2605-form-smallest-number-from-two-digit-arrays.md @@ -0,0 +1,128 @@ +--- +id: form-smallest-number-from-two-digit-arrays +title: Form Smallest Number From Two Digit Arrays +sidebar_label: 2605. Form Smallest Number From Two Digit Arrays +tags: +- Array +- Hash Table +- Enumeration +description: "Solution to Leetcode 2605. Form Smallest Number From Two Digit Arrays" +--- + +## Problem Description + +Given two arrays of unique digits nums1 and nums2, return the smallest number that contains at least one digit from each array. + +### Examples + +**Example 1:** + +``` +Input: nums1 = [4,1,3], nums2 = [5,7] +Output: 15 +Explanation: The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It can be proven that 15 is the smallest number we can have. +``` + +**Example 2:** + +``` +Input: nums1 = [3,5,2,6], nums2 = [3,1,7] +Output: 3 +Explanation: The number 3 contains the digit 3 which exists in both arrays. + +``` + + + +### Constraints +- `1 <= nums1.length, nums2.length <= 9` +- `1 <= nums1[i], nums2[i] <= 9` + +### Approach +1. Sort both the Vectors. +2. Store the elements of nums1 into a map. +3. Now Traverse The map for each element in nums2 , if same element is found in both vectors return that element directly. +4. Simply return the nums1[0]*10 + nums2[0] if(nums1[0] < nums2[0]) +and nums2[0]*10 + nums1[0] if(nums1[0] > nums2[0]) + +### Complexity + +Time complexity: $O(n)$ + +Space complexity: $O(n)$ + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp +class Solution { +public: + int minNumber(vector &nums1, vector &nums2) { + int n1 = nums1.size(); + int n2 = nums2.size(); + sort(nums1.begin(), nums1.end()); + sort(nums2.begin(), nums2.end()); + mapmap; //Store the element of nums1 into a map. + for(int i=0;i int: + s1, s2 = set(nums1), set(nums2) + if s1 & s2: + return min(s1 & s2) + a, b = min(nums1), min(nums2) + return min(a, b) * 10 + max(a, b) + +``` + + + +### Complexity Analysis + +- Time Complexity: $O(n)$ + +- Space Complexity: $O(n)$ + +### References + +- **LeetCode Problem**: Form Smallest Number From Two Digit Arrays diff --git a/solutions/lc-solutions/2600-2699/2610- convert-an-array-into-a-2d-array-with-conditions.md b/solutions/lc-solutions/2600-2699/2610- convert-an-array-into-a-2d-array-with-conditions.md new file mode 100644 index 0000000..6246a68 --- /dev/null +++ b/solutions/lc-solutions/2600-2699/2610- convert-an-array-into-a-2d-array-with-conditions.md @@ -0,0 +1,107 @@ +--- +id: convert-an-array-into-a-2d-array-with-conditions +title: Convert an Array Into a 2D Array With Conditions +sidebar_label: 2610 Convert an Array Into a 2D Array With Conditions +tags: + - Array + - Hash Table + - LeetCode + - C++ +description: "This is a solution to the Convert an Array Into a 2D Array With Conditions problem on LeetCode." +--- + +## Problem Description + +You are given an integer array nums. You need to create a 2D array from nums satisfying the following conditions: + +- The 2D array should contain only the elements of the array nums. +- Each row in the 2D array contains distinct integers. +- The number of rows in the 2D array should be minimal. + Return the resulting array. If there are multiple answers, return any of them. + +Note that the 2D array can have a different number of elements on each row. + +### Examples + +**Example 1:** + +``` + +Input: nums = [1,2] +Output: 2 +``` + +**Example 2:** + +``` +Input: nums = [1,3,4,1,2,3,1] +Output: [[1,3,4,2],[1,3],[1]] +``` + +**Example 2:** + +``` +Input: nums = [1,2,3,4] +Output: [[4,3,2,1]] +``` + +### Constraints + +- $1 \leq \text{nums.length} \leq 200$. +- $1 \leq \text{nums[i]} \leq \text{nums.length}$. + +### Approach + +To solve this problem(convert an array into a 2d array with conditions)we simply have to use an unordered map which will keep track if we can insert a particular number in the row. we will process the elements in the array one by one in any order and only create a new row in the matrix when we cannot put it into the existing rows. + +#### Code in C++ + +```cpp +class Solution { +public: + vector> findMatrix(vector& nums) { + vector>a; + unordered_mapb; + int r=0; + for(int i=0;ir){ + r++; + a.push_back({nums[i]}); + } + else{ + a[b[nums[i]]-1].push_back(nums[i]); + } + } + return a; + } +}; +``` + +#### Code in Java + +```java +class Solution { + + public List> findMatrix(int[] nums) { + HashMap map = new HashMap(); + for (int n : nums) { + map.put(n, map.getOrDefault(n, 0) + 1); + } + + List> ll = new ArrayList(); + for (Map.Entry entry : map.entrySet()) { + int key = entry.getKey(); + int val = entry.getValue(); + for (int i = ll.size(); i < val; i++) ll.add(new ArrayList()); + int i = 0; + while (val-- > 0) { + ll.get(i++).add(key); + } + } + + return ll; + } +} + +``` diff --git a/solutions/lc-solutions/2600-2699/2614-prime-in-diagonal.md b/solutions/lc-solutions/2600-2699/2614-prime-in-diagonal.md new file mode 100644 index 0000000..f6429d0 --- /dev/null +++ b/solutions/lc-solutions/2600-2699/2614-prime-in-diagonal.md @@ -0,0 +1,151 @@ +--- +id: prime-in-diagonal +title: Prime In Diagonal +sidebar_label: 2614. Prime In Diagonal +tags: +- Array +- Math +- Matrix +- Number Theory +description: "Solution to Leetcode 2614. Prime In Diagonal" +--- + +## Problem Description + +You are given a 0-indexed two-dimensional integer array nums. + +Return the largest prime number that lies on at least one of the diagonals of nums. In case, no prime is present on any of the diagonals, return 0. + +### Examples + +**Example 1:** + +``` +Input: nums = [[1,2,3],[5,6,7],[9,10,11]] +Output: 11 +Explanation: The numbers 1, 3, 6, 9, and 11 are the only numbers present on at least one of the diagonals. Since 11 is the largest prime, we return 11. +``` + +**Example 2:** + +``` +Input: nums = [[1,2,3],[5,17,7],[9,11,10]] +Output: 17 +Explanation: The numbers 1, 3, 9, 10, and 17 are all present on at least one of the diagonals. 17 is the largest prime, so we return 17. + +``` + + + +### Constraints +- `1 <= nums.length <= 300` +- `nums.length == numsi.length` +- `1 <= nums[i][j] <= 4*106` + +### Approach +We use a helper function is_prime() to check if a number is prime or not. We then iterate over the main and secondary diagonal of the matrix using a for loop and check if each element on the diagonal is prime or not. If it is prime, we compare it with the largest prime found so far and update the largest prime accordingly. + +### Complexity + +Time complexity: $O(n^2)$ +Space complexity: $O(1)$ + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp +class Solution { +public: + bool isPrime(int n){ + if(n <= 1) return false; + for (int i = 2; i * i <= n; i++){ + if (n % i == 0)return false; + } + return true; + } + int diagonalPrime(vector>& v) { + int n = v.size(), ans = INT_MIN; + for(int i = 0; i < n; i++){ + if(isPrime(v[i][i])) ans = max(ans, v[i][i]); + if(isPrime(v[i][n - i - 1])) ans = max(ans, v[i][n - i - 1]); + } + return ans == INT_MIN ? 0 : ans; + } +}; + ``` + +#### JAVA + +```java +class Solution { + public int diagonalPrime(int[][] nums) { + int maxi=0; + for(int i=0;i int: + def is_prime(num): + if num <= 1: + return False + for i in range(2, int(num ** 0.5) + 1): + if num % i == 0: + return False + return True + + largest_prime = 0 + n = len(nums) + for i in range(n): + if is_prime(nums[i][i]): + largest_prime = max(largest_prime, nums[i][i]) + if is_prime(nums[i][n-i-1]): + largest_prime = max(largest_prime, nums[i][n-i-1]) + return largest_prime + +``` + + + +### Complexity Analysis + +- Time Complexity: $O(n^2)$ + +- Space Complexity: $O(1)$ + +### References + +- **LeetCode Problem**: Prime In Diagonal \ No newline at end of file diff --git a/solutions/lc-solutions/2600-2699/2615.-sum-of-distances.md b/solutions/lc-solutions/2600-2699/2615.-sum-of-distances.md new file mode 100644 index 0000000..99dc5a5 --- /dev/null +++ b/solutions/lc-solutions/2600-2699/2615.-sum-of-distances.md @@ -0,0 +1,188 @@ +--- +id: sum-of-distances +title: Sum of Distances +sidebar_label: 2615. Sum of Distances +tags: +- Array +- Hash Table +- Prefix Sum +description: "Solution to Leetcode 2615. Sum of Distances" +--- + +## Problem Description + +You are given a 0-indexed integer array nums. There exists an array arr of length nums.length, where arr[i] is the sum of |i - j| over all j such that nums[j] == nums[i] and j != i. If there is no such j, set arr[i] to be 0. + +Return the array arr. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,3,1,1,2] +Output: [5,0,3,4,0] +Explanation: +When i = 0, nums[0] == nums[2] and nums[0] == nums[3]. Therefore, arr[0] = |0 - 2| + |0 - 3| = 5. +When i = 1, arr[1] = 0 because there is no other index with value 3. +When i = 2, nums[2] == nums[0] and nums[2] == nums[3]. Therefore, arr[2] = |2 - 0| + |2 - 3| = 3. +When i = 3, nums[3] == nums[0] and nums[3] == nums[2]. Therefore, arr[3] = |3 - 0| + |3 - 2| = 4. +When i = 4, arr[4] = 0 because there is no other index with value 2. +``` + +**Example 2:** + +``` +Input: nums = [0,5,3] +Output: [0,0,0] +Explanation: Since each element in nums is distinct, arr[i] = 0 for all i. + +``` + + + +### Constraints +- `1 <= nums.length <= 10^5` +- `0 <= nums[i] <= 10^9` + +### Approach +- lets take a example [1,3,1,1,2,1,1] +- lets take value 1 +the arr formed for value 1 will be:[0,2,3,5,6] +- lets calculate ans for index 3: +- it will be divided into two part one which is on left and other on right +- for left: val1=(3-0)+(3-2) = (3+3)-(0+2) = 3*left_size-(sum upto i-1); +- for right: val2=(6-3)+(5-3) = (6+5)-3*2 = (sum from i+1)-(right_size * 3) +- now ans for 3 index=val1+val2; + +### Complexity + +Time complexity: $O(n*logn)$ +Space complexity: $O(n)$ + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp + + +class Solution { +public: + vector distance(vector& nums) { + unordered_map>mp; + for(int i=0;i>dp;//for storing prefix sum + + for(auto it:mp) + { + auto arr=it.second; + dp[it.first].push_back(arr[0]); + for(int i=1;ians(nums.size(),0); + + + for(auto it:mp) + { + auto arr1=it.second; + auto arr2=dp[it.first]; + + for(int i=arr1.size()-1;i>=0;i--) + { + int left=i; + int right=arr1.size()-i-1; + + long long sum1=i-1>=0?arr2[i-1]:0; + long long sum2=arr2[arr1.size()-1]-arr2[i]; + + long long val=(1ll*left*arr1[i]-sum1)+(sum2-1ll*right*arr1[i]); + ans[arr1[i]]=val; + } + } + return ans; + } +}; + ``` + +#### JAVA + +```java +class Solution { + public long[] distance(int[] nums) { + HashMap> hm = new HashMap<>(); + for(int i = 0; i < nums.length; i++) { + if(!hm.containsKey(nums[i])) { + hm.put(nums[i], new ArrayList<>()); + } + hm.get(nums[i]).add(i); + } + + long[] ans = new long[nums.length]; + for(ArrayList indices : hm.values()) { + int n = indices.size(); + long sum = 0; + for(int i = 0; i < n; i++) { + sum += indices.get(i); + } + long leftsum = 0; + long rightsum = sum; + long currsum = 0; + for(int i = 0; i < n; i++) { + currsum = 0; + currsum += (long)i*(long)indices.get(i) - leftsum; + currsum += rightsum - (long)(n-i)*(long)indices.get(i); + leftsum += (long)indices.get(i); + rightsum -= (long)indices.get(i); + ans[indices.get(i)] = currsum; + } + } + return ans; + } +} +``` + +#### PYTHON + +```python +class Solution: + def distance(self, nums: List[int]) -> List[int]: + num_indices = dict() + occ=dict() + for i, num in enumerate(nums): + if num not in num_indices: + num_indices[num] = i + occ[num]=1 + else: + num_indices[num]=num_indices[num]+i + occ[num]=occ[num]+1 + arr = [0] * len(nums) + n=len(nums) + for i in range(n): + arr[i] = num_indices[nums[i]] - occ[nums[i]]*i + num_indices[nums[i]]=num_indices[nums[i]]-2*i + occ[nums[i]]=occ[nums[i]]-2 + + return arr +``` + + + +### Complexity Analysis + +- Time Complexity: $O(n*logn)$ + +- Space Complexity: $O(n)$ + +### References + +- **LeetCode Problem**: Sum of Distances \ No newline at end of file diff --git a/solutions/lc-solutions/2600-2699/2616-minimize-the-maximum-difference-of-pairs.md b/solutions/lc-solutions/2600-2699/2616-minimize-the-maximum-difference-of-pairs.md new file mode 100644 index 0000000..a728030 --- /dev/null +++ b/solutions/lc-solutions/2600-2699/2616-minimize-the-maximum-difference-of-pairs.md @@ -0,0 +1,148 @@ +--- +id: minimize-the-maximum-difference-of-pairs +title: Minimize the Maximum Difference of Pairs +sidebar_label: 2616. Minimize the Maximum Difference of Pairs +tags: +- Array +- Binary Search +- Greedy +description: "Solution to Leetcode 2616. Minimize the Maximum Difference of Pairs" +--- + +## Problem Description + +You are given a 0-indexed integer array nums and an integer p. Find p pairs of indices of nums such that the maximum difference amongst all the pairs is minimized. Also, ensure no index appears more than once amongst the p pairs. + +Note that for a pair of elements at the index i and j, the difference of this pair is |nums[i] - nums[j]|, where |x| represents the absolute value of x. + +Return the minimum maximum difference among all p pairs. We define the maximum of an empty set to be zero. + +### Examples + +**Example 1:** + +``` +Input: nums = [10,1,2,7,1,3], p = 2 +Output: 1 +Explanation: The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. +The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1. +``` + +**Example 2:** + +``` +Input: nums = [4,2,1,2], p = 1 +Output: 0 +Explanation: Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain. + +``` + + + +### Constraints +- `1 <= nums.length <= 10^5` +- `0 <= nums[i] <= 10^9` +- `0 <= p <= (nums.length)/2` + +### Approach +- First we don't care the original order of A[i], we want to compare the difference, so we sort them. +- The result is in range of left = 0 and right = A[n - 1] - A[0] each iteration of search, we assume the minimum maximum differenceis mid = (left + right) / 2, then we check if we can have p pairs. +- We take pairs (A[i], A[i - 1]) greedily if A[i] - A[i - 1] <= mid. +- If we take this pair, we move to next availble pair (A[i + 2], A[i + 1]) +- If not, we move to next availble pair (A[i + 1], A[i]) +- In the end of each iteration, we check if we can have p pairs. +- If so, mid is big enough, right = mid +- If not, mid is too small, left = mid + 1. +- Finally we return the binary seach result left. + +### Complexity + +Time complexity: $O(nlog(max(A)) + nlogn)$ + +Space complexity: $O(logn)$ + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp +int minimizeMax(vector& A, int p) { + sort(A.begin(), A.end()); + int n = A.size(), left = 0, right = A[n - 1] - A[0]; + while (left < right) { + int mid = (left + right) / 2, k = 0; + for (int i = 1; i < n && k < p; ++i) { + if (A[i] - A[i - 1] <= mid) { + k++; + i++; + } + } + if (k >= p) + right = mid; + else + left = mid + 1; + } + return left; +} + + ``` + +#### JAVA + +```java +public int minimizeMax(int[] A, int p) { + Arrays.sort(A); + int n = A.length, left = 0, right = A[n - 1] - A[0]; + while (left < right) { + int mid = (left + right) / 2, k = 0; + for (int i = 1; i < n && k < p; ++i) { + if (A[i] - A[i - 1] <= mid) { + k++; + i++; + } + } + if (k >= p) + right = mid; + else + left = mid + 1; + } + return left; +} +``` + +#### PYTHON + +```python +def minimizeMax(self, A: List[int], p: int) -> int: + A.sort() + n = len(A) + left, right = 0, A[-1] - A[0] + while left < right: + mid = (left + right) // 2 + k = 0 + i = 1 + while i < n: + if A[i] - A[i - 1] <= mid: + k += 1 + i += 1 + i += 1 + if k >= p: + right = mid + else: + left = mid + 1 + return left +``` + + + +### Complexity Analysis + +- Time Complexity: $O(nlog(max(A)) + nlogn)$ + +- Space Complexity: $O(logn)$ + +### References + +- **LeetCode Problem**: Minimize the Maximum Difference of Pairs diff --git a/solutions/lc-solutions/2600-2699/2617-minimum-number-of-visited-cells-in-a-grid.md b/solutions/lc-solutions/2600-2699/2617-minimum-number-of-visited-cells-in-a-grid.md new file mode 100644 index 0000000..a201964 --- /dev/null +++ b/solutions/lc-solutions/2600-2699/2617-minimum-number-of-visited-cells-in-a-grid.md @@ -0,0 +1,183 @@ +--- +id: minimum-number-of-visited-cells-in-a-grid +title: Minimum Number of Visited Cells in a Grid +sidebar_label: 2617. Minimum Number of Visited Cells in a Grid +tags: +- Array +- Binary Search +- Greedy +description: "Solution to Leetcode 2617. Minimum Number of Visited Cells in a Grid" +--- + +## Problem Description + +You are given a 0-indexed m x n integer matrix grid. Your initial position is at the top-left cell (0, 0). + +Starting from the cell (i, j), you can move to one of the following cells: + +- Cells (i, k) with j < k <= grid[i][j] + j (rightward movement), or +- Cells (k, j) with i < k <= grid[i][j] + i (downward movement). + +Return the minimum number of cells you need to visit to reach the bottom-right cell (m - 1, n - 1). If there is no valid path, return -1. + +### Examples + +**Example 1:** + +``` +Input: grid = [[3,4,2,1],[4,2,3,1],[2,1,0,0],[2,4,0,0]] +Output: 4 +Explanation: The image above shows one of the paths that visits exactly 4 cells. +``` + +**Example 2:** + +``` +Input: grid = [[3,4,2,1],[4,2,1,1],[2,1,1,0],[3,4,1,0]] +Output: 3 +Explanation: The image above shows one of the paths that visits exactly 3 cells. + +``` + + + +### Constraints +- `m == grid.length` +- `n == grid[i].length` +- `1 <= m, n <= 10^5` +- `1 <= m * n <= 10^5` +- `0 <= grid[i][j] < m * n` +- `grid[m - 1][n - 1] == 0` + +### Approach +This code is using the breadth-first search algorithm to find the minimum number of cells that need to be visited to reach from the top-left cell of a given grid to the bottom-right cell. To avoid iterating over the entire grid again and again, it uses a Set/TreeSet/SortedList data structure to keep track of the visited nodes in the horizontal and vertical directions. This enables efficient iteration over the subset of cells that haven't been visited yet. + +During the for loop, the irange method of the SortedList object is used to iterate over the subset of cells that haven't been visited yet. Specifically, for the s0 list, it iterates over the columns that haven't been visited yet and are within the range of (j+1, min(j+1+grid[i][j], n) - 1). Similarly, for the s1 list, it iterates over the rows that haven't been visited yet and are within the range of (i+1, min(i+1+grid[i][j], m) - 1). This results in significant speed-ups when the grid is large or the values of grid[i][j] are large. + +### Complexity + +Time complexity: $O(mn * log(max(m, n)))$ + +Space complexity: $O(mn)$ + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp +int minimumVisitedCells(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector> s0(m), s1(n); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + s0[i].insert(j); + s1[j].insert(i); + } + } + queue> q; + q.push({0, 0, 1}); + + while (!q.empty()) { + auto cell = q.front(); q.pop(); + int i = cell[0], j = cell[1], d = cell[2]; + if (i == m - 1 && j == n - 1) return d; + + auto it = s0[i].lower_bound(j + 1); + while (it != s0[i].end() && *it <= j + grid[i][j]) { + q.push({i, *it, d + 1}); + s1[*it].erase(i); + s0[i].erase(it++); + } + it = s1[j].lower_bound(i + 1); + while (it != s1[j].end() && *it <= i + grid[i][j]) { + q.push({*it, j, d + 1}); + s0[*it].erase(j); + s1[j].erase(it++); + } + } + return -1; +} + ``` + +#### JAVA + +```java +public int minimumVisitedCells(int[][] grid) { + int m = grid.length, n = grid[0].length; + TreeSet[] s0 = new TreeSet[m], s1 = new TreeSet[n]; + for (int i = 0; i < m; i++) { + s0[i] = new TreeSet<>(); + for (int j = 0; j < n; j++) + s0[i].add(j); + } + for (int j = 0; j < n; j++) { + s1[j] = new TreeSet<>(); + for (int i = 0; i < m; i++) + s1[j].add(i); + } + Queue q = new LinkedList<>(); + q.offer(new int[]{0, 0, 1}); + + while (!q.isEmpty()) { + int[] cell = q.poll(); + int i = cell[0], j = cell[1], d = cell[2]; + if (i == m - 1 && j == n - 1) return d; + + Integer k = s0[i].ceiling(j+1); + while (k != null && k <= j + grid[i][j]) { + q.offer(new int[]{i, k.intValue(), d + 1}); + s0[i].remove(k); + s1[k.intValue()].remove(i); + k = s0[i].ceiling(j + 1); + } + k = s1[j].ceiling(i+1); + while (k != null && k <= i + grid[i][j]) { + q.offer(new int[]{k.intValue(), j, d + 1}); + s1[j].remove(k); + s0[k.intValue()].remove(j); + k = s1[j].ceiling(i + 1); + } + } + return -1; +} +``` + +#### PYTHON + +```python +from sortedcontainers import SortedList +class Solution: + def minimumVisitedCells(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + s0 = [SortedList(range(n)) for _ in range(m)] + s1 = [SortedList(range(m)) for _ in range(n)] + q = deque([(0, 0, 1)]) + + while q: + i, j, d = q.popleft() + if (i, j) == (m-1, n-1): + return d + for k in list(s0[i].irange(j+1, min(j+1+grid[i][j], n) - 1)): + q.append((i, k, d+1)) + s0[i].remove(k) + s1[k].remove(i) + for k in list(s1[j].irange(i+1, min(i+1+grid[i][j], m) - 1)): + q.append((k, j, d+1)) + s1[j].remove(k) + s0[k].remove(j) + return -1 +``` + + + +### Complexity Analysis + +- Time Complexity: $O(mn * log(max(m, n)))$ + +- Space Complexity: $O(mn)$ + +### References + +- **LeetCode Problem**: Minimum Number of Visited Cells in a Grid diff --git a/solutions/lc-solutions/2600-2699/2620-Counter.md b/solutions/lc-solutions/2600-2699/2620-Counter.md new file mode 100644 index 0000000..d3401e4 --- /dev/null +++ b/solutions/lc-solutions/2600-2699/2620-Counter.md @@ -0,0 +1,60 @@ +--- +id: counter +title: Counter +sidebar_label: 2620-Counter +--- + +## Problem Description +Given an integer `n`, return a `counter` function. This `counter` function initially returns `n` and then returns 1 more than the previous value every subsequent time it is called (`n`, `n + 1`, `n + 2`, etc). + + +### Example + +**Example 1:** + + +``` +n = 10 +["call","call","call"] +Output: [10,11,12] +Explanation: +counter() = 10 // The first time counter() is called, it returns n. +counter() = 11 // Returns 1 more than the previous time. +counter() = 12 // Returns 1 more than the previous time. +``` +**Example 2:** +``` +Input: +n = -2 +["call","call","call","call","call"] +Output: [-2,-1,0,1,2] +Explanation: counter() initially returns -2. Then increases after each sebsequent call. + +``` +### Constraints + +- `0 <= calls.length <= 1000` + +## Solution Approach + +### Intuition: + +To efficiently determine the counter + + +## Solution Implementation + +### Code : +```Javascript +/** + * @param {number} n + * @return {Function} counter + */ +var createCounter = function(n) { + + return function() { + return n++; + }; +}; + +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2600-2699/2639-find-the-width-of-columns-of-a-grid.md b/solutions/lc-solutions/2600-2699/2639-find-the-width-of-columns-of-a-grid.md new file mode 100644 index 0000000..a955283 --- /dev/null +++ b/solutions/lc-solutions/2600-2699/2639-find-the-width-of-columns-of-a-grid.md @@ -0,0 +1,123 @@ +--- +id: find-the-width-of-columns-of-a-grid +title: Find the Width of Columns of a Grid +sidebar_label: 2639. Find the Width of Columns of a Grid +tags: +- Array +- Matrix +description: "Solution to Leetcode 2639. Find the Width of Columns of a Grid" +--- + +## Problem Description + +You are given a 0-indexed m x n integer matrix grid. The width of a column is the maximum length of its integers. + +For example, if grid = [[-10], [3], [12]], the width of the only column is 3 since -10 is of length 3. +Return an integer array ans of size n where ans[i] is the width of the ith column. + +The length of an integer x with len digits is equal to len if x is non-negative, and len + 1 otherwise. + +### Examples + +**Example 1:** + +``` +Input: grid = [[1],[22],[333]] +Output: [3] +Explanation: In the 0th column, 333 is of length 3. +``` + +**Example 2:** + +``` +Input: grid = [[-15,1,3],[15,7,12],[5,6,-2]] +Output: [3,1,2] +Explanation: +In the 0th column, only -15 is of length 3. +In the 1st column, all integers are of length 1. +In the 2nd column, both 12 and -2 are of length 2. + +``` + + + +### Constraints +- `m == grid.length` +- `n == grid[i].length` +- `1 <= m, n <= 100` +- `(-10^9) <= grid[r][c] <= 10^9` + +### Approach +- To find the maximum length of any number we can just convert it to a string and find it length. +- In this way, we can easily find the maximum width of each column. + +### Complexity + +Time complexity: $O(n*n)$ + +Space complexity: $O(1)$ + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp +class Solution { +public: + vector findColumnWidth(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector ans(n); + + for(int j=0; j List[int]: + return [max(len(str(a)) for a in r) for r in zip(*A)] +``` + + + +### Complexity Analysis + +- Time Complexity: $O(n*m)$ + +- Space Complexity: $O(1)$ + +### References + +- **LeetCode Problem**: Find the Width of Columns of a Grid diff --git a/solutions/lc-solutions/2600-2699/2643-row-with-maximum-ones.md b/solutions/lc-solutions/2600-2699/2643-row-with-maximum-ones.md new file mode 100644 index 0000000..3036669 --- /dev/null +++ b/solutions/lc-solutions/2600-2699/2643-row-with-maximum-ones.md @@ -0,0 +1,138 @@ +--- +id: row-with-maximum-ones +title: Row With Maximum Ones +sidebar_label: 2643. Row With Maximum Ones +tags: +- Array +- Matrix +description: "Solution to Leetcode 2643. Row With Maximum Ones" +--- + +## Problem Description + +Given a m x n binary matrix mat, find the 0-indexed position of the row that contains the maximum count of ones, and the number of ones in that row. + +In case there are multiple rows that have the maximum count of ones, the row with the smallest row number should be selected. + +Return an array containing the index of the row, and the number of ones in it. + +### Examples + +**Example 1:** + +``` +Input: mat = [[0,1],[1,0]] +Output: [0,1] +Explanation: Both rows have the same number of 1's. So we return the index of the smaller row, 0, and the maximum count of ones (1). So, the answer is [0,1]. +``` + +**Example 2:** + +``` +Input: mat = [[0,0,0],[0,1,1]] +Output: [1,2] +Explanation: The row indexed 1 has the maximum count of ones (2). So we return its index, 1, and the count. So, the answer is [1,2]. +``` + + + +### Constraints +- `m == mat.length` +- `n == mat[i].length` +- `1 <= m, n <= 100` +- `mat[i][j] is either 0 or 1` + +### Approach +- To count the number of ones in a row, we simply iterate over all elements of the row and add up the ones. + +- Finally, we return the index of the row with the maximum count of ones, along with the count itself, as a vector of two integers. If there are multiple rows with the maximum count, we return the one with the smallest row number, which is the first one encountered in the loop. + +### Complexity + +Time complexity: $O(n*m)$ + +Space complexity: $O(1)$ + +### Solution + +#### Code in Different Languages + +#### C++ + + ```cpp +class Solution { +public: + vector rowAndMaximumOnes(vector>& mat) { + int m = mat.size(); + int n = mat[0].size(); + int maxCount = 0; + int maxRow = 0; + for (int i = 0; i < m; i++) { + int count = 0; + for (int j = 0; j < n; j++) { + count += mat[i][j]; + } + if (count > maxCount) { + maxCount = count; + maxRow = i; + } + } + return {maxRow, maxCount}; + } +}; + ``` + +#### JAVA + +```java +class Solution { + public int[] rowAndMaximumOnes(int[][] mat) { + int max=0,index=0; + for(int i=0;imax) + { + index=i; + max=val; + } + } + return new int[]{index,max}; + } +} +``` + +#### PYTHON + +```python +class Solution: + def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]: + ones = 0 + index = 0 + for it, row in enumerate(mat): + c = row.count(1) + if ones < c: + ones = c + index = it + + return [index,ones] +``` + + + +### Complexity Analysis + +- Time Complexity: $O(n*m)$ + +- Space Complexity: $O(1)$ + +### References + +- **LeetCode Problem**: Row With Maximum Ones diff --git a/solutions/lc-solutions/2600-2699/2652-sum-multiples.md b/solutions/lc-solutions/2600-2699/2652-sum-multiples.md new file mode 100644 index 0000000..12f9ed8 --- /dev/null +++ b/solutions/lc-solutions/2600-2699/2652-sum-multiples.md @@ -0,0 +1,104 @@ +--- +id: sum-multiples +title: Sum Multiples +sidebar_label: 2625 - Sum Multiples +tags: +- Mathematics +- Loops +- Conditions +- Basic Math +- Iteration +- Sum +- Multiples +- Number Theory +description: "This is a solution to the Sum Multiples problem on LeetCode." +--- + +## Problem Description + +Given a positive integer `n`, find the sum of all integers in the range `[1, n]` **inclusive** that are divisible by `3`, `5`, or `7`. + +Return an integer denoting the sum of all numbers in the given range satisfying the constraint. + +### Examples + +**Example 1:** + +``` +Input: n = 7 +Output: 21 +Explanation: Numbers in the range [1, 7] that are divisible by 3, 5, or 7 are 3, 5, 6, 7. The sum of these numbers is 21. + +``` + +**Example 2:** + +``` +Input: n = 10 +Output: 40 +Explanation: Numbers in the range [1, 10] that are divisible by 3, 5, or 7 are 3, 5, 6, 7, 9, 10. The sum of these numbers is 40. + +``` + +**Example 2:** + +``` +Input: n = 9 +Output: 30 +Explanation: Numbers in the range [1, 9] that are divisible by 3, 5, or 7 are 3, 5, 6, 7, 9. The sum of these numbers is 30. +``` + +### Constraints + +- `1 <= n <= 103` + +### Approach + +Traverse from 1 to n and check if they divide by 3 or 5 or 7 completely then add it to sum and return sum + +#### Python3 + +```python +class Solution: + def sumOfMultiples(self, n: int) -> int: + s = 0 + for i in range(1, n + 1): + if i % 3 == 0 or i % 5 == 0 or i % 7 == 0: + s += i + return s + +``` + +#### Java + +```java +class Solution { + public int sumOfMultiples(int n) { + int s=0; + for(int i=1;i<=n;i++) + { + if(i%3==0 || i%5==0 || i%7==0) + s = s+i; + } + return s; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + int sumOfMultiples(int n) { + int s = 0; + for (int i = 1; i <= n; ++i) { + if (i % 3 == 0 || i % 5 == 0 || i % 7 == 0) { + s += i; + } + } + return s; + } +}; + +``` diff --git a/solutions/lc-solutions/2600-2699/2653-sliding-subarray-beauty.md b/solutions/lc-solutions/2600-2699/2653-sliding-subarray-beauty.md new file mode 100644 index 0000000..46782bc --- /dev/null +++ b/solutions/lc-solutions/2600-2699/2653-sliding-subarray-beauty.md @@ -0,0 +1,492 @@ +--- +id: sliding-subarray-beauty +title: 2653. Sliding Subarray Beauty +sidebar_label: 2653. Sliding Subarray Beauty + + +tags: +- Array +- Sliding Window +- Hash Table + +description: "This is a solution to the 2653. Sliding Subarray Beauty + problem on LeetCode." +--- + +## Problem Description +Given an integer array nums containing n integers, find the beauty of each subarray of size k. + +The beauty of a subarray is the xth smallest integer in the subarray if it is negative, or 0 if there are fewer than x negative integers. + +Return an integer array containing n - k + 1 integers, which denote the beauty of the subarrays in order from the first index in the array. + +A subarray is a contiguous non-empty sequence of elements within an array. +### Examples +**Example 1:** + +``` +Input: nums = [1,-1,-3,-2,3], k = 3, x = 2 +Output: [-1,-2,-2] +Explanation: There are 3 subarrays with size k = 3. +The first subarray is [1, -1, -3] and the 2nd smallest negative integer is -1. +The second subarray is [-1, -3, -2] and the 2nd smallest negative integer is -2. +The third subarray is [-3, -2, 3] and the 2nd smallest negative integer is -2. +``` + +**Example 2:** +``` +Input: nums = [-1,-2,-3,-4,-5], k = 2, x = 2 +Output: [-1,-2,-3,-4] +Explanation: There are 4 subarrays with size k = 2. +For [-1, -2], the 2nd smallest negative integer is -1. +For [-2, -3], the 2nd smallest negative integer is -2. +For [-3, -4], the 2nd smallest negative integer is -3. +For [-4, -5], the 2nd smallest negative integer is -4. +``` + +### Constraints +- `n == nums.length` +- `1 <= n <= 10^5` +- `1 <= k <= n` +- `1 <= x <= k` +- `-50 <= nums[i] <= 50` +## Solution for2653. Sliding Subarray Beauty +1. **Initialize Data Structures:** + - A list `ans` to store the results. + - A map `mp` to keep track of the frequency of negative numbers in the current window. + - Two pointers `i` and `j` to define the sliding window. + +2. **Sliding Window Technique:** + - Iterate through the array using the `j` pointer to expand the window. + - If `nums[j]` is negative, increment its count in the map `mp`. + - Check the window size: + - If the window size is less than `k`, simply expand the window by incrementing `j`. + - If the window size is equal to `k`, calculate the beauty: + - Initialize a counter `cnt`. + - Iterate through the map `mp`: + - If the current key is negative, increment `cnt` by the frequency of the key. + - If `cnt` is greater than or equal to `x`, append the current key to `ans` and break the loop. + - If `cnt` is less than `x`, append `0` to `ans`. + - Expand the window by incrementing `j`. + - If the window size exceeds `k`, shrink the window from the left: + - If `nums[i]` is negative, decrement its count in the map `mp`. + - If the count of `nums[i]` becomes `0`, remove it from the map. + - Increment `i` to shrink the window. + - If the window size becomes equal to `k`, repeat the process of calculating the beauty. + +3. **Return the Result:** + - After processing all possible windows, return the list `ans`. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function getSubarrayBeauty(nums, k, x) { + const ans = []; + const mp = {}; + let i = 0; + let j = 0; + + while (j < nums.length) { + if (nums[j] < 0) { + mp[nums[j]] = (mp[nums[j]] || 0) + 1; + } + if (j - i + 1 < k) { + j++; + } else if (j - i + 1 === k) { + let cnt = 0; + const sortedKeys = Object.keys(mp).map(Number).sort((a, b) => a - b); + for (let key of sortedKeys) { + if (key < 0) { + cnt += mp[key]; + } + if (cnt >= x) { + ans.push(key); + break; + } + } + if (cnt < x) ans.push(0); + j++; + } else if (j - i + 1 > k) { + while (j - i + 1 > k) { + if (nums[i] < 0) { + mp[nums[i]]--; + if (mp[nums[i]] === 0) { + delete mp[nums[i]]; + } + } + i++; + } + if (j - i + 1 === k) { + let cnt = 0; + const sortedKeys = Object.keys(mp).map(Number).sort((a, b) => a - b); + for (let key of sortedKeys) { + if (key < 0) { + cnt += mp[key]; + } + if (cnt >= x) { + ans.push(key); + break; + } + } + if (cnt < x) ans.push(0); + } + j++; + } + } + + return ans; +} + const input =nums = [1,-1,-3,-2,3], k = 3, x = 2 + const output = getSubarrayBeauty(input , k , x) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(nlogn) $ + - Space Complexity: $ O(n)$ + + ## Code in Different Languages + + + + ```javascript + function getSubarrayBeauty(nums, k, x) { + const ans = []; + const mp = {}; + let i = 0; + let j = 0; + + while (j < nums.length) { + if (nums[j] < 0) { + mp[nums[j]] = (mp[nums[j]] || 0) + 1; + } + if (j - i + 1 < k) { + j++; + } else if (j - i + 1 === k) { + let cnt = 0; + const sortedKeys = Object.keys(mp).map(Number).sort((a, b) => a - b); + for (let key of sortedKeys) { + if (key < 0) { + cnt += mp[key]; + } + if (cnt >= x) { + ans.push(key); + break; + } + } + if (cnt < x) ans.push(0); + j++; + } else if (j - i + 1 > k) { + while (j - i + 1 > k) { + if (nums[i] < 0) { + mp[nums[i]]--; + if (mp[nums[i]] === 0) { + delete mp[nums[i]]; + } + } + i++; + } + if (j - i + 1 === k) { + let cnt = 0; + const sortedKeys = Object.keys(mp).map(Number).sort((a, b) => a - b); + for (let key of sortedKeys) { + if (key < 0) { + cnt += mp[key]; + } + if (cnt >= x) { + ans.push(key); + break; + } + } + if (cnt < x) ans.push(0); + } + j++; + } + } + + return ans; +} + ``` + + + + + ```typescript + class Solution { + getSubarrayBeauty(nums: number[], k: number, x: number): number[] { + const ans: number[] = []; + const mp: Map = new Map(); + let i = 0; + let j = 0; + + while (j < nums.length) { + if (nums[j] < 0) mp.set(nums[j], (mp.get(nums[j]) || 0) + 1); + if (j - i + 1 < k) { + j++; + } else if (j - i + 1 === k) { + let cnt = 0; + for (let [key, value] of mp) { + if (key < 0) { + cnt += value; + } + if (cnt >= x) { + ans.push(key); + break; + } + } + if (cnt < x) ans.push(0); + j++; + } else if (j - i + 1 > k) { + while (j - i + 1 > k) { + if (nums[i] < 0) { + mp.set(nums[i], mp.get(nums[i]) - 1); + if (mp.get(nums[i]) === 0) { + mp.delete(nums[i]); + } + } + i++; + } + if (j - i + 1 === k) { + let cnt = 0; + for (let [key, value] of mp) { + if (key < 0) { + cnt += value; + } + if (cnt >= x) { + ans.push(key); + break; + } + } + if (cnt < x) ans.push(0); + } + j++; + } + } + + return ans; + } +} + ``` + + + + ```python + from collections import defaultdict + +class Solution: + def getSubarrayBeauty(self, nums, k, x): + ans = [] + mp = defaultdict(int) + i = 0 + j = 0 + + while j < len(nums): + if nums[j] < 0: + mp[nums[j]] += 1 + if j - i + 1 < k: + j += 1 + elif j - i + 1 == k: + cnt = 0 + for key in sorted(mp.keys()): + if key < 0: + cnt += mp[key] + if cnt >= x: + ans.append(key) + break + if cnt < x: + ans.append(0) + j += 1 + elif j - i + 1 > k: + while j - i + 1 > k: + if nums[i] < 0: + mp[nums[i]] -= 1 + if mp[nums[i]] == 0: + del mp[nums[i]] + i += 1 + if j - i + 1 == k: + cnt = 0 + for key in sorted(mp.keys()): + if key < 0: + cnt += mp[key] + if cnt >= x: + ans.append(key) + break + if cnt < x: + ans.append(0) + j += 1 + + return ans + +# Example usage: +solution = Solution() +nums = [1, -1, -3, -2, 3] +k = 3 +x = 2 +print(solution.getSubarrayBeauty(nums, k, x)) # Output: [-1, -2] + + ``` + + + + + ```java + import java.util.*; + +class Solution { + public List getSubarrayBeauty(int[] nums, int k, int x) { + List ans = new ArrayList<>(); + TreeMap mp = new TreeMap<>(); + int i = 0; + int j = 0; + + while (j < nums.length) { + if (nums[j] < 0) mp.put(nums[j], mp.getOrDefault(nums[j], 0) + 1); + if (j - i + 1 < k) { + j++; + } else if (j - i + 1 == k) { + int cnt = 0; + for (Map.Entry entry : mp.entrySet()) { + if (entry.getKey() < 0) { + cnt += entry.getValue(); + } + if (cnt >= x) { + ans.add(entry.getKey()); + break; + } + } + if (cnt < x) ans.add(0); + j++; + } else if (j - i + 1 > k) { + while (j - i + 1 > k) { + if (nums[i] < 0) { + mp.put(nums[i], mp.get(nums[i]) - 1); + if (mp.get(nums[i]) == 0) { + mp.remove(nums[i]); + } + } + i++; + } + if (j - i + 1 == k) { + int cnt = 0; + for (Map.Entry entry : mp.entrySet()) { + if (entry.getKey() < 0) { + cnt += entry.getValue(); + } + if (cnt >= x) { + ans.add(entry.getKey()); + break; + } + } + if (cnt < x) ans.add(0); + } + j++; + } + } + + return ans; + } +} + +// Example usage: +public class Main { + public static void main(String[] args) { + Solution solution = new Solution(); + int[] nums = {1, -1, -3, -2, 3}; + int k = 3; + int x = 2; + System.out.println(solution.getSubarrayBeauty(nums, k, x)); // Output: [-1, -2] + } +} + + ``` + + + + + ```cpp +class Solution { +public: + vector getSubarrayBeauty(vector& nums, int k, int x) { + vector ans; + map mp; // smallest + int i = 0; + int j = 0; + while (j < nums.size()) { + if (nums[j] < 0) + mp[nums[j]]++; + if (j - i + 1 < k) { + j++; + } else if (j - i + 1 == k) { + int cnt = 0; + for (auto it : mp) { + if (it.first < 0) { + cnt += it.second; + } + if (cnt >= x) { + ans.push_back(it.first); + break; + } + } + if (cnt < x) + ans.push_back(0); + j++; + } else if (j - i + 1 > k) { + while (j - i + 1 > k) { + if (nums[i] < k) { + mp[nums[i]]--; + if (mp[nums[i]] == 0) { + mp.erase(nums[i]); + } + } + i++; + } + if (j - i + 1 == k) { + int cnt = 0; + for (auto it : mp) { + if (it.first < 0) { + cnt += it.second; + } + + if (cnt >= x) { + ans.push_back(it.first); + break; + } + } + if (cnt < x) + ans.push_back(0); + } + j++; + } + } + return ans; + } +}; + + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [2348. Number of Zero-Filled Subarrays](https://leetcode.com/problems/sliding-subarray-beauty/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/sliding-subarray-beauty/) + diff --git a/solutions/lc-solutions/2600-2699/2667-Create-Hello-World-Function.md b/solutions/lc-solutions/2600-2699/2667-Create-Hello-World-Function.md new file mode 100644 index 0000000..365811c --- /dev/null +++ b/solutions/lc-solutions/2600-2699/2667-Create-Hello-World-Function.md @@ -0,0 +1,134 @@ +--- +id: 2667-create-hello-world-function +title: Create Hello World Function +sidebar_label: 2667-Create-Hello-World-Function +tags: [none] +description: The problem is to create a Hello World function. +sidebar_position: 2667 +--- + +## Problem Statement + +### Problem Description + +Write a function `createHelloWorld`. It should return a new function that always returns `"Hello World"`. + +### Examples + +**Example 1:** + +``` +Input: args = [] +Output: "Hello World" +Explanation: +const f = createHelloWorld(); +f(); // "Hello World" + +The function returned by createHelloWorld should always return "Hello World". +``` + +**Example 2:** + +``` +Input: args = [{},null,42] +Output: "Hello World" +Explanation: +const f = createHelloWorld(); +f({}, null, 42); // "Hello World" + +Any arguments could be passed to the function but it should still always return "Hello World". +``` + +### Constraints + +- `0 <= args.length <= 10` + +## Solution of Given Problem + +### Intuition and Approach + +The function `createHelloWorld` should return a new function that always returns the string `"Hello World"`. The returned function can accept any number of arguments, but it should ignore them and always return `"Hello World"`. + +### Approaches + +The approach involves defining the function `createHelloWorld` which returns another function that ignores its arguments and returns `"Hello World"`. + +#### Codes in Different Languages + + + + + ```javascript + /** + * @return {Function} + */ + var createHelloWorld = function() { + return function(...args) { + return "Hello World"; + } + }; + ``` + + + + + ```typescript + function createHelloWorld(): (...args: any[]) => string { + return function(...args: any[]) { + return "Hello World"; + } + } + ``` + + + + + ```python + def create_hello_world(): + def hello_world(*args): + return "Hello World" + return hello_world + ``` + + + + + ```java + import java.util.concurrent.Callable; + + public class HelloWorldFactory { + public static Callable createHelloWorld() { + return () -> "Hello World"; + } + } + ``` + + + + ```cpp + #include + #include + + std::function create_hello_world() { + return []() { return "Hello World"; }; + } + ``` + + + +### Complexity Analysis + +- **Time Complexity**: O(1), which means it runs in constant time. This is because the function simply returns a new function, without performing any significant computations or iterations. + +- **Space Complexity**: O(1), which means it uses a constant amount of memory. This is because the function only returns a small, fixed-size function, without allocating any additional memory that scales with the input size. + + +--- + +

Authors:

+ +
+{['Ishitamukherjee2004'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/2600-2699/_category_.json b/solutions/lc-solutions/2600-2699/_category_.json new file mode 100644 index 0000000..7984750 --- /dev/null +++ b/solutions/lc-solutions/2600-2699/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "2600-2699", + "position": 28, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (2600 - 2699)" + } +} diff --git a/solutions/lc-solutions/2700-2799/2703-return-length-of-arguments-passed.md b/solutions/lc-solutions/2700-2799/2703-return-length-of-arguments-passed.md new file mode 100644 index 0000000..6bf122a --- /dev/null +++ b/solutions/lc-solutions/2700-2799/2703-return-length-of-arguments-passed.md @@ -0,0 +1,88 @@ +--- +id: return-length-of-arguments-passed +title: Return Length of Arguments Passed +sidebar_label: 2703 - Return Length of Arguments Passed +tags: + - Functions + - Arguments +description: Write a function that returns the count of arguments passed to it. +sidebar_position: 2703 +--- + +## Problem Statement +Write a function `argumentsLength` that returns the count of arguments passed to it. + +### Examples + +**Example 1:** + +``` +Input: args = [5] +Output: 1 +Explination: +argumentsLength(5); // 1 + +One value was passed to the function so it should return 1. +``` + +**Example 2:** + +``` +Input: args = [{}, null, "3"] +Output: 3 +Explination: +argumentsLength({}, null, "3"); // 3 + +Three values were passed to the function so it should return 3. +``` + + + +### Constraints + +- `args` is a valid JSON array +- `0 <= args.length <= 100` + +## Solution + +### Approach: + +The approach to solve this problem is straightforward. We need to write a function that simply returns the length of the arguments passed to it. + +#### Algorithm + +To solve the problem of returning the count of arguments passed to a function, we can use the following simple algorithm: + +#### Define the Function: +Create a function named argumentsLength that uses the rest parameter syntax (...args) to collect all the arguments passed to the function into an array named args. + +#### Return the Length: +Inside the function, return the length of the args array using the length property. This will give the count of the arguments passed to the function. + +#### Test the Function: +Write test cases to ensure the function works correctly for different inputs, including cases with one argument, multiple arguments, and no arguments. + +#### JavaScript Implementation + +```javascript +function argumentsLength(...args) { + return args.length; +} +``` + +#### TypeScript Implementation + +```typescript + function argumentsLength(...args: any[]): number { + return args.length; +} +``` + +### Complexity Analysis + +- **Time Complexity**: $O(1)$ - The time complexity is constant because the length of the arguments is determined in constant time. +- **Space Complexity**: $O(1)$ - The space complexity is constant as we are not using any additional data structures. + +### Conclusion + +The problem of determining the number of arguments passed to a function has been effectively solved using both JavaScript and TypeScript. The solutions leverage the rest parameter syntax (`...args`) to handle a variable number of arguments, making it versatile and easy to understand. diff --git a/solutions/lc-solutions/2700-2799/2706-Buy-Two-Chocolates.md b/solutions/lc-solutions/2700-2799/2706-Buy-Two-Chocolates.md new file mode 100644 index 0000000..8955fd3 --- /dev/null +++ b/solutions/lc-solutions/2700-2799/2706-Buy-Two-Chocolates.md @@ -0,0 +1,133 @@ +--- +id: buy-two-chocolates +title: Buy Two Chocolates +sidebar_label: 2706-Buy-Two-Chocolates +tags: + - Array + - Sorting + +description: "This is a solution to the 2706." +--- + +## Problem Description +You are given an integer array prices representing the `prices` of various chocolates in a store. You are also given a single integer `money`, which represents your initial amount of money. + +You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy. + +Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return `money`. Note that the leftover must be non-negative. + + +### Example + +**Example 1:** + + +``` +Input: prices = [1,2,2], money = 3 +Output: 0 +Explanation: Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0. +``` +**Example 2:** +``` +Input: prices = [3,2,3], money = 3 +Output: 3 +Explanation: You cannot buy 2 chocolates without going in debt, so we return 3. +``` +### Constraints + +- `2 <= prices.length <= 50` + +## Solution Approach + +### Intuition: + +To efficiently determine the amount of money you will have leftover after buying the two chocolates +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + class Solution { + buyChoco(prices, money) { + prices.sort((a, b) => a - b); + if (prices[0] + prices[1] > money) { + return money; + } else { + return money - prices[0] - prices[1]; + } + } +} + ``` + + + + + ```typescript + class Solution { + buyChoco(prices: number[], money: number): number { + prices.sort((a, b) => a - b); + if (prices[0] + prices[1] > money) { + return money; + } else { + return money - prices[0] - prices[1]; + } + } +} + ``` + + + + + ```python + +class Solution: + def buyChoco(self, prices: List[int], money: int) -> int: + prices.sort() + if prices[0] + prices[1] > money: + return money + else: + return money - prices[0] - prices[1] + ``` + + + + + ```java + public class Solution { + public int buyChoco(int[] prices, int money) { + Arrays.sort(prices); + if (prices[0] + prices[1] > money) { + return money; + } else { + return money - prices[0] - prices[1]; + } + } +} + + ``` + + + + + ```cpp + class Solution { +public: + int buyChoco(vector& prices, int money) { + sort(prices.begin(), prices.end()); + if(prices[0]+prices[1]>money) return money; + else return money-prices[0]-prices[1]; + } +}; + ``` + + + +#### Complexity Analysis + +- Time Complexity: $$O(n*log(n))$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(n*log(n))$$ where n is the length of the prices array. This is because the function sorts the prices array. +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/2700-2799/2717-Semi_ordered-Permutation.md b/solutions/lc-solutions/2700-2799/2717-Semi_ordered-Permutation.md new file mode 100644 index 0000000..488094a --- /dev/null +++ b/solutions/lc-solutions/2700-2799/2717-Semi_ordered-Permutation.md @@ -0,0 +1,193 @@ +--- +id: semi-ordered-permutation +title: Semi-Ordered Permutation +sidebar_label: 2717-Semi_ordered-Permutation +tags: + - Array + - Simulation + +description: "This is a solution to the 2717." +--- + +## Problem Description +You are given a 0-indexed permutation of `n` integers `nums`. + +A permutation is called semi-ordered if the first number equals `1` and the last number equals `n`. You can perform the below operation as many times as you want until you make `nums` a semi-ordered permutation: + +Pick two adjacent elements in `nums`, then swap them. +Return the minimum number of operations to make `nums` a semi-ordered permutation. + +A permutation is a sequence of integers from `1` to `n` of length `n` containing each number exactly once. + + +### Example + +**Example 1:** + + +``` +Input: nums = [2,1,4,3] +Output: 2 +Explanation: We can make the permutation semi-ordered using these sequence of operations: +1 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. +2 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. +It can be proved that there is no sequence of less than two operations that make nums a semi-ordered permutation. +``` +**Example 2:** +``` +Input: nums = [2,4,1,3] +Output: 3 +Explanation: We can make the permutation semi-ordered using these sequence of operations: +1 - swap i = 1 and j = 2. The permutation becomes [2,1,4,3]. +2 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3]. +3 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4]. +It can be proved that there is no sequence of less than three operations that make nums a semi-ordered permutation. +``` +### Constraints + +- `2 <= nums.length == n <= 50` + +## Solution Approach + +### Intuition: + +To efficiently determine the Semi-Ordered Permutation +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript +class Solution { + semiOrderedPermutation(nums) { + let n = nums.length; + let left = 0, right = n - 1; + let operations = 0; + while (left < right) { + if (nums[left] === left + 1) { + left++; + } else if (nums[right] === n - right) { + right--; + } else { + [nums[left], nums[right]] = [nums[right], nums[left]]; + operations++; + } + } + return operations; + } +} + + ``` + + + + + ```typescript + class Solution { + semiOrderedPermutation(nums: number[]): number { + let n = nums.length; + let left = 0, right = n - 1; + let operations = 0; + while (left < right) { + if (nums[left] === left + 1) { + left++; + } else if (nums[right] === n - right) { + right--; + } else { + [nums[left], nums[right]] = [nums[right], nums[left]]; + operations++; + } + } + return operations; + } +} + + ``` + + + + + ```python +class Solution: + def semiOrderedPermutation(self, nums: List[int]) -> int: + n = len(nums) + left, right = 0, n - 1 + operations = 0 + while left < right: + if nums[left] == left + 1: + left += 1 + elif nums[right] == n - right: + right -= 1 + else: + nums[left], nums[right] = nums[right], nums[left] + operations += 1 + return operations + + ``` + + + + + ```java + +public class Solution { + public int semiOrderedPermutation(int[] nums) { + int n = nums.length; + int left = 0, right = n - 1; + int operations = 0; + while (left < right) { + if (nums[left] == left + 1) { + left++; + } else if (nums[right] == n - right) { + right--; + } else { + int temp = nums[left]; + nums[left] = nums[right]; + nums[right] = temp; + operations++; + } + } + return operations; + } +} + + + ``` + + + + + ```cpp + class Solution { +public: + int semiOrderedPermutation(vector& nums) { + int n = nums.size(); + int left = 0, right = n - 1; + int operations = 0; + while (left < right) { + if (nums[left] == left + 1) { + left++; + } else if (nums[right] == n - right) { + right--; + } else { + swap(nums[left], nums[right]); + operations++; + } + } + + return operations; +} + +}; + ``` + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(n)$$ where n is the length of the input array nums. This is because the method iterates through the array once, performing a constant amount of work for each element. +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/2700-2799/2729-Check-If-The-Number-Is-Fascinating.md b/solutions/lc-solutions/2700-2799/2729-Check-If-The-Number-Is-Fascinating.md new file mode 100644 index 0000000..90446ed --- /dev/null +++ b/solutions/lc-solutions/2700-2799/2729-Check-If-The-Number-Is-Fascinating.md @@ -0,0 +1,145 @@ +--- +id: check-if-the-number-is-fascinating +title: Check if The Number is Fascinating +sidebar_label: 2729-Check-If-The-Number-Is-Fascinating +tags: + - Hash Table + - Math + +description: "This is a solution to the 2729." +--- + +## Problem Description +You are given an integer `n` that consists of exactly `3` digits. + +We call the number `n` fascinating if, after the following modification, the resulting number contains all the digits from `1` to `9` exactly once and does not contain any `0`'s: + +Concatenate `n` with the numbers `2 * n` and `3 * n`. +Return `true` if `n` is fascinating, or `false` otherwise. + +Concatenating two numbers means joining them together. For example, the concatenation of `121` and `371` is `121371`. + +### Example + +**Example 1:** + + +``` +Input: n = 192 +Output: true +Explanation: We concatenate the numbers n = 192 and 2 * n = 384 and 3 * n = 576. The resulting number is 192384576. This number contains all the digits from 1 to 9 exactly once. +``` +**Example 2:** +``` +Input: n = 100 +Output: false +Explanation: We concatenate the numbers n = 100 and 2 * n = 200 and 3 * n = 300. The resulting number is 100200300. This number does not satisfy any of the conditions. +``` +### Constraints + +- `100 <= n <= 999` + +## Solution Approach + +### Intuition: + +To efficiently Check if The Number is Fascinating + + +## Solution Implementation + +### Code In Different Languages: + + + + + + + ```javascript +class Solution { + isFascinating(n) { + let concat = `${n}${2 * n}${3 * n}`; + let sorted = [...concat].sort().join(''); + return sorted === '123456789'; + } +} + + ``` + + + + + ```typescript +class Solution { + isFascinating(n: number): boolean { + let concat = `${n}${2 * n}${3 * n}`; + let sorted = [...concat].sort().join(''); + return sorted === '123456789'; + } +} + + ``` + + + + + + + ```python + +class Solution: + def isFascinating(self, n: int) -> bool: + concat = str(n) + str(2 * n) + str(3 * n) + sorted_concat = ''.join(sorted(concat)) + return sorted_concat == '123456789' + + ``` + + + + + + ```java +public class Solution { + public boolean isFascinating(int n) { + String concat = n + "" + (2 * n) + (3 * n); + char[] chars = concat.toCharArray(); + Arrays.sort(chars); + return new String(chars).equals("123456789"); + } +} + + + ``` + + + + + + ```cpp + +class Solution { + public: + bool isFascinating(int n) { + string concat = to_string(n) + to_string(2 * n) + to_string(3 * n); + sort(concat.begin(), concat.end()); + return concat == "123456789"; + } +}; + + ``` + + + +#### Complexity Analysis + +- Time Complexity: $$O(n*log(n))$$ +- The concatenation of the strings takes O(n) time, where n is the number of digits in the result. +- The sorting of the string takes O(n log n) time, as it uses a comparison-based sorting algorithm (e.g., quicksort or mergesort). +- The comparison of the sorted string with the desired result takes O(n) time. + + + +- Space Complexity: $$O(n)$$ +- The concatenation of the strings requires additional space to store the resulting string, which has a length of 9 digits (for the input range of 1 to 100 million). +- The sorting algorithm may require additional space for temporary storage, depending on the implementation. diff --git a/solutions/lc-solutions/2700-2799/2733-neither-minimum-nor-maximum.md b/solutions/lc-solutions/2700-2799/2733-neither-minimum-nor-maximum.md new file mode 100644 index 0000000..add54b5 --- /dev/null +++ b/solutions/lc-solutions/2700-2799/2733-neither-minimum-nor-maximum.md @@ -0,0 +1,134 @@ +--- +id: neither-minimum-nor-maximum +title: Neither Minimum nor Maximum +sidebar_label: 2703 - Neither Minimum nor Maximum +tags: + - Array + - Sorting +description: "This is the solution to neither minimum nor maximum in LeetCode" +--- + +## Problem Statement + +Given an integer array `nums` containing distinct positive integers, find and return any number from the array that is neither the minimum nor the maximum value in the array, or -1 if there is no such number. + +Return the selected integer. + +### Examples + +**Example 1:** + +``` +Input: nums = [3,2,1,4] +Output: 2 +Explanation: In this example, the minimum value is 1 and the maximum value is 4. Therefore, either 2 or 3 can be valid answers. +``` + +**Example 2:** + +``` +Input: nums = [1,2] +Output: -1 +Explanation: Since there is no number in nums that is neither the maximum nor the minimum, we cannot select a number that satisfies the given condition. Therefore, there is no answer. +``` + +**Example 3:** + +``` +Input: nums = [2,1,3] +Output: 2 +Explanation: Since 2 is neither the maximum nor the minimum value in nums, it is the only valid answer. +``` + +### Constraints + +- `1 <= nums.length <= 100` +- `1 <= nums[i] <= 100` + +## Solution for Neither Minimum Nor Maximum + +### Approach + +The approach is simple as we need to find the element which is neither minimum nor maximum. We sort the array in ascending order then we iterate the array from index 1 to last index-1 as at index 0 we have the minimum value and at the last index we have the maximum. We store the array elements in an array list and we return the first element in the array list. +If the array size is 2, we have only minimum and maximum values, hence we return -1. + +#### Complexity Analysis + +- Time Complexity: $O(n \log n)$ due to sorting +- Space Complexity: $O(n)$ + +## Code in Different Languages + + + + + +```java +import java.util.ArrayList; +import java.util.Arrays; + +class Solution { + public int findNonMinOrMax(int[] nums) { + Arrays.sort(nums); + ArrayList arr = new ArrayList<>(); + for (int i = 1; i < nums.length - 1; i++) { + arr.add(nums[i]); + } + if (arr.size() == 0) { + return -1; + } else { + return arr.get(0); + } + } +} +``` + + + + + +```python +def find_non_min_or_max(nums): + nums.sort() + arr = [] + for i in range(1, len(nums) - 1): + arr.append(nums[i]) + + if len(arr) == 0: + return -1 + else: + return arr[0] +``` + + + + + +```c++ +#include +#include + +class Solution { +public: + int findNonMinOrMax(std::vector& nums) { + std::sort(nums.begin(), nums.end()); + std::vector arr; + for (int i = 1; i < nums.size() - 1; ++i) { + arr.push_back(nums[i]); + } + + if (arr.empty()) { + return -1; + } else { + return arr[0]; + } + } +}; +``` + + + +## References + +- **LeetCode Problem**: [Neither Minimum nor Maximum](https://leetcode.com/problems/neither-minimum-nor-maximum/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/neither-minimum-nor-maximum/post-solution/?submissionId=1293729812) diff --git a/solutions/lc-solutions/2700-2799/2769-Find-the-Maximum-Achievable-Number.md b/solutions/lc-solutions/2700-2799/2769-Find-the-Maximum-Achievable-Number.md new file mode 100644 index 0000000..42521b7 --- /dev/null +++ b/solutions/lc-solutions/2700-2799/2769-Find-the-Maximum-Achievable-Number.md @@ -0,0 +1,145 @@ +--- +id: find-the-maximum-achievable-number +title: Find the Maximum Achievable Number +sidebar_label: 2769-Find-the-Maximum-Achievable-Number +tags: + - Math + +description: "This is a solution to the 2769." +--- + +## Problem Description +Given two integers, `num` and `t`. A number is achievable if it can become equal to `num` after applying the following operation: + +Increase or decrease the number by `1`, and simultaneously increase or decrease `num` by `1`. +Return the maximum achievable number after applying the operation at most `t` times. + +### Example + +**Example 1:** + + +``` +Input: num = 4, t = 1 + +Output: 6 + +Explanation: + +Apply the following operation once to make the maximum achievable number equal to num: + +Decrease the maximum achievable number by 1, and increase num by 1. +``` +**Example 2:** +``` +Input: num = 3, t = 2 + +Output: 7 + +Explanation: + +Apply the following operation twice to make the maximum achievable number equal to num: + +Decrease the maximum achievable number by 1, and increase num by 1. +``` +### Constraints + +- `1 <= num, t <= 50` + +## Solution Approach + +### Intuition: + +To efficiently Find the Maximum Achievable Number + +### Aproach +1. Define the problem: Determine the maximum achievable X given num and t. +2. Understand the relationship: Recognize that X increases by 2t for every num. +3. Formulate the solution: Return num + 2*t to calculate the maximum achievable X. +4. Implement the solution: Write the code in the desired programming language (JavaScript, TypeScript, Python, or Java). +5. Test and verify: Check the code with various inputs to ensure it produces the correct output. + + + +## Solution Implementation + +### Code In Different Languages: + + + + + + + ```javascript +class Solution { + theMaximumAchievableX(num, t) { + return num + 2 * t; + } +} + + + ``` + + + + + ```typescript +class Solution { + theMaximumAchievableX(num: number, t: number): number { + return num + 2 * t; + } +} + + + ``` + + + + + + + ```python + +class Solution: + def theMaximumAchievableX(self, num: int, t: int) -> int: + return num + 2 * t + + ``` + + + + + + ```java +public class Solution { + public int theMaximumAchievableX(int num, int t) { + return num + 2 * t; + } +} + + + + ``` + + + + + + ```cpp + +class Solution { +public: + int theMaximumAchievableX(int num, int t) { + return num+2*t; + } +}; + + ``` + + + +#### Complexity Analysis + +- Time Complexity: $$O(1)$$, meaning it takes constant time, regardless of the input size. This is because the method performs a simple arithmetic operation that doesn't depend on the size of the input. + +- Space Complexity: $$O(1)$$, meaning the method uses a constant amount of space, regardless of the input size. This is because the method doesn't allocate any new memory that scales with the input size. diff --git a/solutions/lc-solutions/2700-2799/2778-Sum-Of-Square-Of-Special-Element.md b/solutions/lc-solutions/2700-2799/2778-Sum-Of-Square-Of-Special-Element.md new file mode 100644 index 0000000..ff51701 --- /dev/null +++ b/solutions/lc-solutions/2700-2799/2778-Sum-Of-Square-Of-Special-Element.md @@ -0,0 +1,157 @@ +--- +id: sum-of-square-of-special-element +title: Sum of Squares of Special Elements +sidebar_label: 2778-Sum-Of-Square-Of-Special-Element +tags: + - Array + - Enumeration + +description: "This is a solution to the 2778. Find Sum of Squares of Special Elements." +--- + +## Problem Description +You are given a 1-indexed integer array `nums` of length `n`. + +An element `nums[i]` of `nums` is called special if `i` divides `n`, i.e. `n % i == 0`. + +Return the sum of the squares of all special elements of `nums`. + + +### Example + +**Example 1:** + + +``` +Input: nums = [1,2,3,4] +Output: 21 +Explanation: There are exactly 3 special elements in nums: nums[1] since 1 divides 4, nums[2] since 2 divides 4, and nums[4] since 4 divides 4. +Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[4] * nums[4] = 1 * 1 + 2 * 2 + 4 * 4 = 21. +``` +**Example 2:** +``` +Input: nums = [2,7,1,19,18,3] +Output: 63 +Explanation: There are exactly 4 special elements in nums: nums[1] since 1 divides 6, nums[2] since 2 divides 6, nums[3] since 3 divides 6, and nums[6] since 6 divides 6. +Hence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[3] * nums[3] + nums[6] * nums[6] = 2 * 2 + 7 * 7 + 1 * 1 + 3 * 3 = 63. +``` +### Constraints + +- `1 <= nums.length == n <= 50` + +## Solution Approach + +### Intuition: + +To efficiently determine the sym of square of the special elements. +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + class Solution { + sumOfSquares(nums) { + let n = nums.length; + let sqr = 0; + for (let i = 0; i < n; i++) { + if (n % (i + 1) === 0) { + sqr += nums[i] * nums[i]; + } + } + return sqr; + } +} + + + + ``` + + + + + ```typescript + class Solution { + sumOfSquares(nums: number[]): number { + let n: number = nums.length; + let sqr: number = 0; + for (let i: number = 0; i < n; i++) { + if (n % (i + 1) === 0) { + sqr += nums[i] * nums[i]; + } + } + return sqr; + } +} + + ``` + + + + + ```python + +class Solution: + def sumOfSquares(self, nums: List[int]) -> int: + n = len(nums) + sqr = 0 + for i in range(n): + if n % (i + 1) == 0: + sqr += nums[i] * nums[i] + return sqr + + + + ``` + + + + + ```java + public class Solution { + public int sumOfSquares(int[] nums) { + int n = nums.length; + int sqr = 0; + for (int i = 0; i < n; i++) { + if (n % (i + 1) == 0) { + sqr += nums[i] * nums[i]; + } + } + return sqr; + } +} + + + + ``` + + + + + ```cpp + +class Solution { +public: + int sumOfSquares(vector& nums) { + int n = nums.size(); + int sqr = 0; + for(int i=0; i + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(n)$$ where n is the length of the input array nums. This is because the function iterates through the array once, performing a constant amount of work for each element. +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/2700-2799/2790 - Maximum Number of Groups With Increasing Length.md b/solutions/lc-solutions/2700-2799/2790 - Maximum Number of Groups With Increasing Length.md new file mode 100644 index 0000000..ad797a5 --- /dev/null +++ b/solutions/lc-solutions/2700-2799/2790 - Maximum Number of Groups With Increasing Length.md @@ -0,0 +1,179 @@ +--- +id: maximum-number-of-groups-with-increasing-length +title: Maximum Number of Groups With Increasing Length +sidebar_label: 2790 Maximum Number of Groups With Increasing Length +tags: +- Java +- Math +- Array +- Binary Search +- Greedy +- Sorting +description: "This document provides a solution where we Return an integer denoting the maximum number of groups you can create while satisfying these conditions." +--- + +## Problem + +You are given a **0-indexed** array $usageLimits$ of length $n$. + +Your task is to create **groups** using numbers from $0$ to $n - 1$, ensuring that each number, $i$, is used no more than $usageLimits[i]$ times in total **across all groups**. You must also satisfy the following conditions: + +- Each group must consist of **distinct** numbers, meaning that no duplicate numbers are allowed within a single group. + +- Each group (except the first one) must have a length **strictly greater** than the previous group. + +Return an integer denoting the **maximum** number of groups you can create while satisfying these conditions. + +### Examples + +**Example 1:** + +``` +Input: usageLimits = [1,2,5] + +Output: 3 + +Explanation: In this example, we can use 0 at most once, 1 at most twice, and 2 at most five times. + +One way of creating the maximum number of groups while satisfying the conditions is: + +Group 1 contains the number [2]. + +Group 2 contains the numbers [1,2]. + +Group 3 contains the numbers [0,1,2]. + +It can be shown that the maximum number of groups is 3. + +So, the output is 3. + +``` +**Example 2:** + +``` +Input: usageLimits = [2,1,2] + +Output: 2 + +Explanation: In this example, we can use 0 at most twice, 1 at most once, and 2 at most twice. + +One way of creating the maximum number of groups while satisfying the conditions is: + +Group 1 contains the number [0]. + +Group 2 contains the numbers [1,2]. + +It can be shown that the maximum number of groups is 2. + +So, the output is 2. + +``` + +**Example 3:** + +``` +Input: usageLimits = [1,1] + +Output: 1 + +Explanation: In this example, we can use both 0 and 1 at most once. + +One way of creating the maximum number of groups while satisfying the conditions is: + +Group 1 contains the number [0]. + +It can be shown that the maximum number of groups is 1. + +So, the output is 1. +``` + +### Constraints + +- $1 <= usageLimits.length <= 10^5$ +- $1 <= usageLimits[i] <= 10^9$ +--- + +## Approach + +To solve the problem, we need to understand the nature of the allowed moves: + +1. **Sort the Usage Limits**: + + - Start by sorting the **'usageLimits'** array. This helps in efficiently forming groups by using the smallest available numbers first, which maximizes the number of groups we can form. + +2. **Initialize Variables**: + + - **'groups'**: Keeps track of the number of groups formed. + + - **'currentGroupSize'**: Represents the required size for the next group to be formed, starting at 1. + + - **'availableNumbers'**: Tracks the total available slots from all numbers seen so far. + +3. **Form Groups**: + + - Iterate through the sorted **'usageLimits'**. + + - For each limit, add it to **'availableNumbers'**. + + - Check if **'availableNumbers'** is at least as large as **'currentGroupSize'**. + + - If true, it means we can form a new group of size **'currentGroupSize'**. + + - Increment the **'groups'** counter, decrement **'availableNumbers'** by **'currentGroupSize'**, and **'increase'** currentGroupSize by 1 for the next group. + +## Solution for Maximum Number of Groups With Increasing Length + +- The core idea is to maximize the number of groups by ensuring each group has a distinct set of numbers and each subsequent group is larger than the previous one. + +- By sorting the **'usageLimits'**, we can efficiently use the smallest available counts first to form valid groups. + +- This approach ensures that we can form as many groups as possible without exceeding the usage limits. + +#### Code in Java + +```java +import java.util.Collections; +import java.util.List; + +class Solution { + public int maxIncreasingGroups(List usageLimits) { + // Sort the usageLimits in ascending order + Collections.sort(usageLimits); + + // Initialize variables + int groups = 0; + int currentGroupSize = 1; // the size of the next group we want to form + long availableNumbers = 0; // to track the number of available slots across all numbers + + // Traverse the sorted usageLimits + for (int limit : usageLimits) { + availableNumbers += limit; // add the current limit to available slots + + // Check if we can form the next group + if (availableNumbers >= currentGroupSize) { + groups++; // form a new group + availableNumbers -= currentGroupSize; // reduce the used slots + currentGroupSize++; // increase the size requirement for the next group + } + } + + return groups; + } +} +``` + +### Complexity Analysis + +#### Time Complexity: $O(nlogn)$ + +> **Reason**: Time Complexity is $O(nlogn)$. Sorting the **'usageLimits'** takes $O(nlogn)$ time. Iterating through the sorted list takes $O(n)$ time. Therefore, the overall time complexity is $O(nlogn)$. + +#### Space Complexity: $O(1)$ + +> **Reason**: The space complexity is $O(1)$, Because the additional space (ignoring the space used by the input list and the space needed for sorting, which is $O(n)$). + +# References + +- **LeetCode Problem:** [Maximum Number of Groups With Increasing Length](https://leetcode.com/problems/maximum-number-of-groups-with-increasing-length/description/) +- **Solution Link:** [Maximum Number of Groups With Increasing Length Solution on LeetCode](https://leetcode.com/problems/maximum-number-of-groups-with-increasing-length/solutions/) +- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/vivekvardhan43862/) diff --git a/solutions/lc-solutions/2700-2799/2798-number-of-employees-who-met-the-target.md b/solutions/lc-solutions/2700-2799/2798-number-of-employees-who-met-the-target.md new file mode 100644 index 0000000..80b4838 --- /dev/null +++ b/solutions/lc-solutions/2700-2799/2798-number-of-employees-who-met-the-target.md @@ -0,0 +1,121 @@ +--- +id: number-of-employees-who-met-the-target +title: Number Of Employees Who Met the Target +sidebar_label: 2798-Number Of Employees Who Met the Target +tags: + - Array + +description: "This is a solution to the number of employees who met the target in a string in leetcode" +--- + +## Problem Description + +There are n employees in a company, numbered from 0 to n - 1. Each employee i has worked for hours[i] hours in the company. +The company requires each employee to work for at least target hours. +You are given a 0-indexed array of non-negative integers hours of length n and a non-negative integer target. +Return the integer denoting the number of employees who worked at least target hours. + + +### Examples + +**Example 1:** + +``` +Input: hours = [0,1,2,3,4], target = 2 +Output: 3 +Explanation: The company wants each employee to work for at least 2 hours. +- Employee 0 worked for 0 hours and didn't meet the target. +- Employee 1 worked for 1 hours and didn't meet the target. +- Employee 2 worked for 2 hours and met the target. +- Employee 3 worked for 3 hours and met the target. +- Employee 4 worked for 4 hours and met the target. +There are 3 employees who met the target. +``` +**Example 2:** +``` +Input: hours = [5,1,4,2,2], target = 6 +Output: 0 +Explanation: The company wants each employee to work for at least 6 hours. +There are 0 employees who met the target. + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(n)$ + +*** Space Complexity:** $O(n)$ + +### Constraints + +- `1 <= n == hours.length <= 50` +- `0 <= hours[i], target <= 105` + + + +### Solution +## Approach + +The goal is to determine the number of employees who have worked a number of hours greater than or equal to a specified target. To achieve this, the solution iterates through an array of integers, where each integer represents the number of hours worked by an employee. A counter variable is initialized to zero. As the loop progresses, each element of the array is checked to see if it meets or exceeds the target hours. If it does, the counter is incremented. After the loop has processed all elements, the counter, which now holds the number of employees who met or exceeded the target hours, is returned as the result. This approach ensures that every employee's hours are checked efficiently in a single pass through the array, making it both straightforward and efficient. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + int numberOfEmployeesWhoMetTarget(vector& hours, int target) { + int c = 0; + for (int hour : hours) { + if (hour >= target) { + c++; + } + } + return c; + } +}; + + +``` + + + + +```java +class Solution { + public int numberOfEmployeesWhoMetTarget(int[] hours, int target) { + int c=0; + for(int i:hours){ + if(i>=target){ + c++; + } + } + return c; + } +} + +``` + + + + +```python +class Solution: + def numberOfEmployeesWhoMetTarget(self, hours, target): + c = 0 + for hour in hours: + if hour >= target: + c += 1 + return c + +``` + + + +## References + +- **LeetCode Problem**: [Number Of Employees Who Met the Target](https://leetcode.com/problems/number-of-employees-who-met-the-target/description/) + +- **Solution Link**: [Number Of Employees Who Met the Target](https://leetcode.com/problems/number-of-employees-who-met-the-target/post-solution/?submissionId=1267320674) diff --git a/solutions/lc-solutions/2700-2799/_category_.json b/solutions/lc-solutions/2700-2799/_category_.json new file mode 100644 index 0000000..fcd95a5 --- /dev/null +++ b/solutions/lc-solutions/2700-2799/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "2700-2799", + "position": 29, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (2700 - 2799)" + } +} diff --git a/solutions/lc-solutions/2800-2899/2806-Account-Balance-After-Rounded-Purchase.md b/solutions/lc-solutions/2800-2899/2806-Account-Balance-After-Rounded-Purchase.md new file mode 100644 index 0000000..d3e21f9 --- /dev/null +++ b/solutions/lc-solutions/2800-2899/2806-Account-Balance-After-Rounded-Purchase.md @@ -0,0 +1,128 @@ +--- +id: account-balance-after-rounded-purchase +title: Account Balance After Rounded Purchase +sidebar_label: 2806. Account Balance After Rounded Purchase +tags: [Array, Simulation, C++, Python, Java] +description: "This is a solution to the Account Balance After Rounded Purchase problem on LeetCode." +--- + +## Problem Description + +Initially, you have a bank account balance of `100` dollars. + +You are given an integer purchaseAmount representing the amount you will spend on a purchase in dollars, in other words, its price. + +When making the purchase, first the purchaseAmount is rounded to the nearest multiple of `10`. Let us call this value roundedAmount. Then, roundedAmount dollars are removed from your bank account. + +Return an integer denoting your final bank account balance after this purchase. + +Notes: + +- 0 is considered to be a multiple of 10 in this problem. +- When rounding, 5 is rounded upward `(5 is rounded to 10, 15 is rounded to 20, 25 to 30, and so on)`. + +### Examples + +**Example 1:** + +``` +Input: purchaseAmount = 9 + +Output: 90 + +Explanation: + +The nearest multiple of 10 to 9 is 10. So your account balance becomes 100 - 10 = 90. + +``` + +**Example 2:** + +``` +Input: purchaseAmount = 15 + +Output: 80 + +Explanation: + +The nearest multiple of 10 to 15 is 20. So your account balance becomes 100 - 20 = 80. + +``` + +### Constraints + +- `0 <= purchaseAmount <= 100` + +## Solution for 1713. Account Balance After Rounded Purchase + +### Intuition +The problem is asking to find the nearest multiple of `10` to the given purchaseAmount and subtract that value from the initial account balance of `100` dollars. + +### Approach + +To find the nearest multiple of `10`, we can take the remainder of the purchaseAmount when divided by `10`. If the remainder is less than `5`, then the nearest multiple of `10` will be obtained by subtracting the remainder from the purchaseAmount. Otherwise, we need to add the difference between 10 and the remainder to the purchaseAmount to get the nearest multiple of `10`. + + +### Code in Different Languages + + + + + ```python + class Solution: + def accountBalanceAfterPurchase(self, purchaseAmount: int) -> int: + rem = purchaseAmount % 10 + if rem < 5: + purchaseAmount = purchaseAmount - rem + else: + purchaseAmount = purchaseAmount + (10 - rem) + + return 100 - purchaseAmount + + ``` + + + + ```java + public class Solution { + public int accountBalanceAfterPurchase(int purchaseAmount) { + int rem = purchaseAmount % 10; + if (rem < 5) + purchaseAmount = purchaseAmount - rem; + else + purchaseAmount = purchaseAmount + (10 - rem); + + return (100 - purchaseAmount); + } +}; + ``` + + + + ```cpp + class Solution { +public: + int accountBalanceAfterPurchase(int p) { + int rem=p%10; + if(rem<5) + p=p-rem; + else + p=p+(10-rem); + + return (100-p); + } +}; + +``` + + + +### Complexity Analysis + +- Time Complexity: $ O(1) $ +- Space Complexity: $ O(1)$ + +## References + +- **LeetCode Problem**: [Account Balance After Rounded Purchase](https://leetcode.com/problems/account-balance-after-rounded-purchase/description/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/account-balance-after-rounded-purchase/solutions/) diff --git a/solutions/lc-solutions/2800-2899/2807-insert-greatest-common-divisors-in-linked-list.md b/solutions/lc-solutions/2800-2899/2807-insert-greatest-common-divisors-in-linked-list.md new file mode 100644 index 0000000..0e0fdd7 --- /dev/null +++ b/solutions/lc-solutions/2800-2899/2807-insert-greatest-common-divisors-in-linked-list.md @@ -0,0 +1,87 @@ +--- +id: insert-greatest-common-divisors-in-linked-list +title: Insert Greatest Common Divisors in Linked List +sidebar_label: 2807 Insert Greatest Common Divisors in Linked List +tags: + - Linked List + - LeetCode + - C++ +description: "This is a solution to the Insert Greatest Common Divisors in Linked List problem on LeetCode." +--- + +## Problem Description + +Given the head of a linked list head, in which each node contains an integer value. + +Between every pair of adjacent nodes, insert a new node with a value equal to the greatest common divisor of them. + +Return the linked list after insertion. + +The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers. + +### Examples + +**Example 1:** + +``` + +Input: head = [18,6,10,3] +Output: [18,6,6,2,10,1,3] +``` + +**Example 2:** + +``` +Input: root = [7] +Output: [7] +``` + +### Constraints + +- The number of nodes in the list is in the range $[1, 5000]$. +- $-1 \leq \text{Node.val} \leq 1000$. + +### Approach + +To solve this problem(insert greatest common divisors in linked list) we will first store the nodes value of the linked list in vector and then find gcd of each adjacent pair and store it in another vector and then simply iterate the linked list and insert the gcd in the linked list as per the question. + +#### Code in C++ + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* insertGreatestCommonDivisors(ListNode* head) { + vectora,b; + ListNode* k=head; + while(head!=NULL){ + a.push_back(head->val); // store each node value of the given linked list + head=head->next; + } + for(int i=0;inext!=NULL){ // inserting gcd between the linked list + ListNode* temp=new ListNode(b[i]); + ListNode* next=k->next; + i++; + k->next=temp; + temp->next=next; + k=k->next->next; + } + return head; + } +}; +``` diff --git a/solutions/lc-solutions/2800-2899/2810-faulty-keyboard.md b/solutions/lc-solutions/2800-2899/2810-faulty-keyboard.md new file mode 100644 index 0000000..cae008d --- /dev/null +++ b/solutions/lc-solutions/2800-2899/2810-faulty-keyboard.md @@ -0,0 +1,143 @@ +--- +id: faulty-keyboard +title: Faulty Keyboard +sidebar_label: 2810. Faulty Keyboard +tags: [Array, Simulation, C++, Python, Java] +description: "This is a solution to the Faulty Keyboard problem on LeetCode." +--- + +## Problem Description + +Your laptop keyboard is faulty, and whenever you type a character `'i'` on it, it reverses the string that you have written. Typing other characters works as expected. + +You are given a 0-indexed string `s`, and you type each character of `s` using your faulty keyboard. + +Return the final string that will be present on your laptop screen. + +### Examples + +**Example 1:** + +``` +Input: s = "string" +Output: "rtsng" +Explanation: +After typing first character, the text on the screen is "s". +After the second character, the text is "st". +After the third character, the text is "str". +Since the fourth character is an 'i', the text gets reversed and becomes "rts". +After the fifth character, the text is "rtsn". +After the sixth character, the text is "rtsng". +Therefore, we return "rtsng". + +``` + +**Example 2:** + +``` +Input: s = "poiinter" +Output: "ponter" +Explanation: +After the first character, the text on the screen is "p". +After the second character, the text is "po". +Since the third character you type is an 'i', the text gets reversed and becomes "op". +Since the fourth character you type is an 'i', the text gets reversed and becomes "po". +After the fifth character, the text is "pon". +After the sixth character, the text is "pont". +After the seventh character, the text is "ponte". +After the eighth character, the text is "ponter". +Therefore, we return "ponter". + +``` + +### Constraints + +- `1 <= s.length <= 100` +- `s[0] != 'i'` + +## Solution for 1713. Faulty Keyboard + +### Intuition +The provided C++ code iterates through each character of the input string, reversing the accumulated result string if the current character is `'i'`, or appending the character otherwise. + +### Approach + +1. Initialization: The method starts by obtaining the size of the input string s and initializing an empty string res to accumulate the result. +2. Iteration: It iterates through each character of `s` using a for-loop. +3. Condition Check: Inside the loop, it checks if the current character is `'i'`. +3. If `true`, it reverses the res string using the reverse function from the Standard Template Library (STL), which directly manipulates the string in place. +4. If `false`, it appends the current character to res. +5. Return: After completing the iteration through all characters of `s`, it returns the modified res string. + + +### Code in Different Languages + + + + + ```python + class Solution: + def finalString(self, s: str) -> str: + res = "" + for char in s: + if char == 'i': + res = res[::-1] + else: + res += char + return res + + + ``` + + + + ```java + class Solution { + public String finalString(String s) { + int n = s.length(); + StringBuilder res = new StringBuilder(); + for (int i = 0; i < n; i++) { + if (s.charAt(i) == 'i') { + res.reverse(); + } else { + res.append(s.charAt(i)); + } + } + return res.toString(); + } +} + ``` + + + + ```cpp + class Solution { +public: + string finalString(string s) { + int n = s.size(); + string res = ""; + for (int i=0; i + + +### Complexity Analysis + +- Time Complexity: $ O(N*N) $ +- Space Complexity: $ O(N)$ + +## References + +- **LeetCode Problem**: [Faulty Keyboard](https://leetcode.com/problems/faulty-keyboard/description/) +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/faulty-keyboard/solutions/) diff --git a/solutions/lc-solutions/2800-2899/2811-check-if-it-is-possible-to-split-array.md b/solutions/lc-solutions/2800-2899/2811-check-if-it-is-possible-to-split-array.md new file mode 100644 index 0000000..0547886 --- /dev/null +++ b/solutions/lc-solutions/2800-2899/2811-check-if-it-is-possible-to-split-array.md @@ -0,0 +1,225 @@ +--- +id: check-if-it-is-possible-to-split-array +title: Check if it is Possible to Split Array +sidebar_label: 2824.Check if it is Possible to Split Array +tags: +- Array +- Dynammic Programming +- Greedy + +description: "This is a solution to Check if it is Possible to Split Array on LeetCode." +--- + +## Problem Description + +You are given an array `nums` of length n and an integer `m`. You need to determine if it is possible to split the array into n arrays of size 1 by performing a series of steps. + +An array is called good if: + +- The length of the array is one, or +- The sum of the elements of the array is greater than or equal to `m`. +In each step, you can select an existing array (which may be the result of previous steps) with a length of at least two and split it into two arrays, if both resulting arrays are good. + +Return `true` if you can split the given array into n arrays, otherwise return `false`. + +**Example 1:** +``` +Input: nums = [2, 2, 1], m = 4 + +Output: true + +Explanation: + +Split [2, 2, 1] to [2, 2] and [1]. The array [1] has a length of one, and the array [2, 2] has the sum of its elements equal to 4 >= m, so both are good arrays. +Split [2, 2] to [2] and [2]. both arrays have the length of one, so both are good arrays. + +``` + +**Example 2:** +``` +Input: nums = [2, 1, 3], m = 5 + +Output: false + +Explanation: + +The first move has to be either of the following: + +Split [2, 1, 3] to [2, 1] and [3]. The array [2, 1] has neither length of one nor sum of elements greater than or equal to m. +Split [2, 1, 3] to [2] and [1, 3]. The array [1, 3] has neither length of one nor sum of elements greater than or equal to m. +So as both moves are invalid (they do not divide the array into two good arrays), we are unable to split nums into n arrays of size 1. + +``` +**Example 3:** +``` +Input: nums = [2, 3, 3, 2, 3], m = 6 + +Output: true + +Explanation: + +Split [2, 3, 3, 2, 3] to [2] and [3, 3, 2, 3]. +Split [3, 3, 2, 3] to [3, 3, 2] and [3]. +Split [3, 3, 2] to [3, 3] and [2]. +Split [3, 3] to [3] and [3]. + +``` +### Constraints +- `1 <= n == nums.length <= 100` +- `1 <= nums[i] <= 100` +- `1 <= m <= 200` + +## Approach + +1. If length of arrays is 1 or 2 then we can split the array according to condition 1 hence returns True +2. Else traverse the array and if any two adjacent elements has sum greater than or equal to m, then we can further split that two elements subarray into two subarrays each of length 1 +3. This satisfies condition 1 so we will return True +4. If neither of above conditions satisfy then we will return False + + + #### Python3 + +```python +class Solution: + def canSplitArray(self, nums: List[int], m: int) -> bool: + if len(nums) <= 2: + return True + for i in range(len(nums)-1): + if nums[i] + nums[i+1] >= m: + return True + return False +``` + +#### Java + +```java +class Solution { + public boolean canSplitArray(List nums, int m) { + boolean ans=false; + int size=nums.size(); + if((size==1 && m>=1) || size == 2) + { + return true; + } + for(int i=0;i=m) + { + ans=true; + } + } + return ans; + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + + int dp[101][101]; + + int solve(int i, int j, vector& presum, vector& nums, int m, int n){ + + if(j-i<=1) return 1; + + if(dp[i][j]!=-1) return dp[i][j]; + + int sum1; + if(i>0){ + sum1 = presum[j-1] - presum[i-1]; + } + else sum1 = presum[j-1]; + + int sum2 = presum[j] - presum[i]; + + int ans = 0; + + if(sum1>=m){ + ans |= solve(i, j-1, presum, nums, m, n); + } + if(sum2>=m){ + ans |= solve(i+1, j, presum, nums, m, n); + } + + return dp[i][j] = ans; + + } + + bool canSplitArray(vector& nums, int m) { + int n=nums.size(); + + vector presum(n, 0); + presum[0]=nums[0]; + for(int i=1; i 1: + numbers.sort(reverse=True) + max_sum = max(max_sum, numbers[0] + numbers[1]) + + return max_sum + +``` + +### Explanation + +1. **Helper Function `largest_digit(num)`**: This function identifies the largest digit in a given number by converting it to a string and finding the maximum digit. +2. **Grouping Numbers**: We use a `defaultdict` to group numbers by their largest digit. +3. **Finding the Maximum Sum**: We sort each group and check for pairs, computing the sum of the two largest numbers in each group. We track the maximum sum encountered. +4. **Result**: The function returns the highest sum of pairs or -1 if no such pairs exist. + +This approach ensures efficient calculation of the required maximum sum while handling the constraints effectively. diff --git a/solutions/lc-solutions/2800-2899/2824-count-pairs-whose-sum-is-less-then-target.md b/solutions/lc-solutions/2800-2899/2824-count-pairs-whose-sum-is-less-then-target.md new file mode 100644 index 0000000..e6925e9 --- /dev/null +++ b/solutions/lc-solutions/2800-2899/2824-count-pairs-whose-sum-is-less-then-target.md @@ -0,0 +1,187 @@ +--- +id: count-pairs-whose-sum-is-less-than-target +title: Count Pairs Whose Sum is Less than Target +sidebar_label: 2824. Count Pairs Whose Sum is Less than Target +tags: +- Array +- Two Pointers +- Sorting +- Greedy +- Binary Search (optional, if you consider advanced optimization) + +description: "This is a solution to count the pairs whose sum is less than target on LeetCode." +--- + +## Problem Description + +Given a **0-indexed** integer array `nums` of length `n` and an integer `target`, return the number of pairs `(i, j)` where `0 <= i < j < n` and `nums[i] + nums[j] < target`. + +**Example 1:** +``` +Input: nums = [-1,1,2,3,1], target = 2 +Output: 3 +Explination: There are 3 pairs of indices that satisfy the conditions in the statement: +- (0, 1) since 0 < 1 and nums[0] + nums[1] = 0 < target +- (0, 2) since 0 < 2 and nums[0] + nums[2] = 1 < target +- (0, 4) since 0 < 4 and nums[0] + nums[4] = 0 < target +Note that (0, 3) is not counted since nums[0] + nums[3] is not strictly less than the target. +``` + +**Example 2:** +``` +Input: nums = [-6,2,5,-2,-7,-1,3], target = -2 +Output: 10 +Explination: There are 10 pairs of indices that satisfy the conditions in the statement: +- (0, 1) since 0 < 1 and nums[0] + nums[1] = -4 < target +- (0, 3) since 0 < 3 and nums[0] + nums[3] = -8 < target +- (0, 4) since 0 < 4 and nums[0] + nums[4] = -13 < target +- (0, 5) since 0 < 5 and nums[0] + nums[5] = -7 < target +- (0, 6) since 0 < 6 and nums[0] + nums[6] = -3 < target +- (1, 4) since 1 < 4 and nums[1] + nums[4] = -5 < target +- (3, 4) since 3 < 4 and nums[3] + nums[4] = -9 < target +- (3, 5) since 3 < 5 and nums[3] + nums[5] = -3 < target +- (4, 5) since 4 < 5 and nums[4] + nums[5] = -8 < target +- (4, 6) since 4 < 6 and nums[4] + nums[6] = -4 < target +``` + +### Constraints +- `1 <= nums.length == n <= 50` +- `50 <= nums[i], target <= 50` + +## Approach + +**1. Sort the List:** + +- First, sort the list `nums`. Sorting allows us to use the two-pointer technique effectively. + +**2. Initialize Variables:** + +- Initialize `count` to keep track of the number of valid pairs. +- Initialize two pointers, `left` at the start (index 0) and `right` at the end (index `nums.size() - 1`) of the list. + +**3. Two-Pointer Technique:** + +- Use a `while` loop to iterate as long as `left` is less than `right`. +- Within the loop: + - If the sum of the elements at the `left` and `right` pointers (`nums.get(left) + nums.get(right)`) is less than `target`, it means all pairs `(left, left + 1)`, `(left, left + 2)`, ..., `(left, right)` are valid. This is because the array is sorted, and any number between `left` and `right` added to `nums[left]` will still be less than `target`. + - Increment `count` by `right - left` to account for all these pairs, and move the `left` pointer to the right `(left++)`. + - If the sum is greater than or equal to target, decrement the `right` pointer `(right--)` to try smaller numbers with the current `nums[left]`. + + + #### Python3 + +```python +class Solution: + def count_pairs(nums, target): + nums.sort() + count = 0 + left = 0 + right = len(nums) - 1 + + while left < right: + if nums[left] + nums[right] < target: + count += right - left + left += 1 + else: + right -= 1 + + return count +``` + +#### Java + +```java +class Solution { + public int countPairs(List nums, int target) { + Collections.sort(nums); + int count = 0; + int left = 0; + int right = nums.size() - 1; + + while (left < right) { + if (nums.get(left) + nums.get(right) < target) { + count += right - left; + left++; + } else { + right--; + } + } + + return count; + } + +} +``` + +#### C++ + +```cpp +class Solution { +public: + int countPairs(std::vector& nums, int target) { + std::sort(nums.begin(), nums.end()); + int count = 0; + int left = 0; + int right = nums.size() - 1; + + while (left < right) { + if (nums[left] + nums[right] < target) { + count += right - left; + left++; + } else { + right--; + } + } + + return count; + } +}; +``` + +#### JavaScript + +```js + countPairs(nums, target) { + nums.sort((a, b) => a - b); + let count = 0; + let left = 0; + let right = nums.length - 1; + + while (left < right) { + if (nums[left] + nums[right] < target) { + count += right - left; + left++; + } else { + right--; + } + } + + return count; + } +``` + +#### TypeScript + +```ts + countPairs(nums: number[], target: number): number { + nums.sort((a, b) => a - b); + let count = 0; + let left = 0; + let right = nums.length - 1; + + while (left < right) { + if (nums[left] + nums[right] < target) { + count += right - left; + left++; + } else { + right--; + } + } + + return count; + } +``` + +# References + +- **LeetCode Problem:** [Count Pairs Whose Sum is Less than Target](https://leetcode.com/problems/count-pairs-whose-sum-is-less-than-target/description/) \ No newline at end of file diff --git a/solutions/lc-solutions/2800-2899/2880-select-data.md b/solutions/lc-solutions/2800-2899/2880-select-data.md new file mode 100644 index 0000000..8434cbb --- /dev/null +++ b/solutions/lc-solutions/2800-2899/2880-select-data.md @@ -0,0 +1,63 @@ +--- +id: select-data-from-a-dataframe +title: Select Data from a DataFrame +sidebar_label: 2880 - Select Data Leetcode +tags: + - LeetCode + - Python + - Data Science +description: "This is a solution to the Select Data question from the Leetcode 2880 question" +--- + +## Problem Description + +Write a solution to select the name and age of the student with student_id = 101. + +## Examples + +Example 1: + +Input: +```plaintext ++------------+---------+-----+ +| student_id | name | age | ++------------+---------+-----+ +| 101 | Ulysses | 13 | +| 53 | William | 10 | +| 128 | Henry | 6 | +| 3 | Henry | 11 | ++------------+---------+-----+ +``` + +Output: + +```plaintext ++---------+-----+ +| name | age | ++---------+-----+ +| Ulysses | 13 | ++---------+-----+ +``` + +## Intuition + +We can use the `loc` method of the DataFrame to select the rows where the student_id is 101 and then select the columns "name" and "age". + +### Solution Code + + + + + ```Python + import pandas as pd + + def selectData(students: pd.DataFrame) -> pd.DataFrame: + return students.loc[students['student_id'] == 101, ["name", "age"]] + ``` + + + + +## References + +- **Leetcode Problem :** [Select Data](https://leetcode.com/problems/select-data/) diff --git a/solutions/lc-solutions/2800-2899/2881-create-a-new-column.md b/solutions/lc-solutions/2800-2899/2881-create-a-new-column.md new file mode 100644 index 0000000..9c4b46d --- /dev/null +++ b/solutions/lc-solutions/2800-2899/2881-create-a-new-column.md @@ -0,0 +1,74 @@ +--- +id : create-a-new-column +title : Create a New column +sidebar_label: 2881 - Create a new column Leetcode +tags: + - LeetCode + - Python + - Data Science +description: "This is a solution for the leetcode 2881 problem which is to create a new column.This problem uses pandas which is a python library for solving" +--- + +## Problem Description + +A company plans to provide its employees with a bonus. +Write a solution to create a new column name bonus that contains the doubled values of the salary column. + +## Examples + +Input: + +```plaintext +DataFrame employees ++---------+--------+ +| name | salary | ++---------+--------+ +| Piper | 4548 | +| Grace | 28150 | +| Georgia | 1103 | +| Willow | 6593 | +| Finn | 74576 | +| Thomas | 24433 | ++---------+--------+ +``` + +Output: + +```plaintext ++---------+--------+--------+ +| name | salary | bonus | ++---------+--------+--------+ +| Piper | 4548 | 9096 | +| Grace | 28150 | 56300 | +| Georgia | 1103 | 2206 | +| Willow | 6593 | 13186 | +| Finn | 74576 | 149152 | +| Thomas | 24433 | 48866 | ++---------+--------+--------+ +``` + +Explanation: + +A new column bonus is created by doubling the value in the column salary. + +## Intuition + +I will use the pandas library to solve this problem. I will create a new column bonus by multiplying the salary column by 2. + +### Solution Code + + + + + ```Python + import pandas as pd + + def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame: + employees['bonus'] = employees['salary']*2 + return employees + ``` + + + +## References +- **Leetcode Problem :** [Create a new column](https://leetcode.com/problems/create-a-new-column/) \ No newline at end of file diff --git a/solutions/lc-solutions/2800-2899/2882-drop-duplicate-rows.md b/solutions/lc-solutions/2800-2899/2882-drop-duplicate-rows.md new file mode 100644 index 0000000..d267e6a --- /dev/null +++ b/solutions/lc-solutions/2800-2899/2882-drop-duplicate-rows.md @@ -0,0 +1,77 @@ +--- +id : drop-duplicate-rows +title : Drop Duplicate Rows +sidebar_label: 2882 - Drop Duplicate Rows +tags: + - LeetCode + - Python + - Data Science +description: "This is a solution for the Leetcode problem 2882 which asks to drop duplicate rows and keep only the first occurence. +This Problem is solved with the help of python library Pandas. " +--- + +## Problem Description + +There are some duplicate rows in the DataFrame based on the email column. +Write a solution to remove these duplicate rows and keep only the first occurrence. +The result format is in the following example. + +## Examples + +Example 1: + +Input: + +```plaintext ++-------------+---------+---------------------+ +| customer_id | name | email | ++-------------+---------+---------------------+ +| 1 | Ella | emily@example.com | +| 2 | David | michael@example.com | +| 3 | Zachary | sarah@example.com | +| 4 | Alice | john@example.com | +| 5 | Finn | john@example.com | +| 6 | Violet | alice@example.com | ++-------------+---------+---------------------+ +``` + +Output: + +```plaintext ++-------------+---------+---------------------+ +| customer_id | name | email | ++-------------+---------+---------------------+ +| 1 | Ella | emily@example.com | +| 2 | David | michael@example.com | +| 3 | Zachary | sarah@example.com | +| 4 | Alice | john@example.com | +| 6 | Violet | alice@example.com | ++-------------+---------+---------------------+ +``` + +## Explanation: + +Alic (customer_id = 4) and Finn (customer_id = 5) both use john@example.com, so only the first occurrence of this email is retained. + +## Intuition + +I will use the pandas library to solve this problem. I will use the drop_duplicates method to remove the duplicate rows based on the email column and keep only the first occurrence. + +### Solution Code + + + + + ```Python + import pandas as pd + + def dropDuplicateEmails(customers: pd.DataFrame) -> pd.DataFrame: + customers.drop_duplicates(subset='email',keep='first',inplace = True) + return customers + ``` + + + +## References + +- **Leetcode Problem :** [Drop Duplicate Rows](https://leetcode.com/problems/drop-duplicate-rows/description/) diff --git a/solutions/lc-solutions/2800-2899/2883-Drop-Missing-Data.md b/solutions/lc-solutions/2800-2899/2883-Drop-Missing-Data.md new file mode 100644 index 0000000..8ae1b2d --- /dev/null +++ b/solutions/lc-solutions/2800-2899/2883-Drop-Missing-Data.md @@ -0,0 +1,91 @@ +--- +id: Drop-Missing-Data +title: Drop Missing Data Solution +sidebar_label: 2883 - Drop Missing Data +tags: + - LeetCode + - Python +description: "This is a solution to the Drop Missing Data problem on LeetCode." +sidebar_position: 1 +--- + +In this tutorial, we will solve the Drop Missing Data problem. We will provide the implementation of the solution in Python. + +## Problem Description + +```plaintext +DataFrame students ++-------------+--------+ +| Column Name | Type | ++-------------+--------+ +| student_id | int | +| name | object | +| age | int | ++-------------+--------+ +``` + +There are some rows having missing values in the name column. + +Write a solution to remove the rows with missing values. + +### Examples + +**Example 1:** + +```plaintext +Input: ++------------+---------+-----+ +| student_id | name | age | ++------------+---------+-----+ +| 32 | Piper | 5 | +| 217 | None | 19 | +| 779 | Georgia | 20 | +| 849 | Willow | 14 | ++------------+---------+-----+ + +Output: ++------------+---------+-----+ +| student_id | name | age | ++------------+---------+-----+ +| 32 | Piper | 5 | +| 779 | Georgia | 20 | +| 849 | Willow | 14 | ++------------+---------+-----+ + +Explanation: +Student with id 217 havs empty value in the name column, so it will be removed. +``` + +### Constraints + +- You have to solve using python pandas only. + +--- + +## Solution for Drop Missing Data + +```py +import pandas as pd + +def dropMissingData(students: pd.DataFrame) -> pd.DataFrame: + return students[students['name'].notnull()] +``` + +### Complexity Analysis + +- **Time Complexity:** $O(n)$ +- **Space Complexity:** $O(n)$ +- **Iterating over the DataFrame:** The notnull() function on the 'name' column performs an O(n) operation, iterating through each row of the DataFrame, where n is the number of rows. +- **Boolean indexing:** Usually an O(n) process, this involves building a new DataFrame from the boolean mask (the output of notnull()). +- **New DataFrame:** To hold the filtered data, the function builds a new DataFrame. The number of rows with complete "name" values determines the size of this new DataFrame, and in the worst scenario, that number may reach n. + As a result, O(n) is also the space complexity. + +--- + +

Authors:

+ +
+{['avdhut-pailwan'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/2800-2899/2894-Diivisible-And-Nondivisible-Sums-Difference.md b/solutions/lc-solutions/2800-2899/2894-Diivisible-And-Nondivisible-Sums-Difference.md new file mode 100644 index 0000000..ef31f9e --- /dev/null +++ b/solutions/lc-solutions/2800-2899/2894-Diivisible-And-Nondivisible-Sums-Difference.md @@ -0,0 +1,164 @@ +--- +id: divisible-and-nondivisible-sums-difference +title: Divisible and Non-divisible Sums Difference +sidebar_label: 2894-Diivisible-And-Nondivisible-Sums-Difference +tags: + - Math + +description: "This is a solution to the 2894. Find difference of divisible and nondivisible sums." +--- + +## Problem Description +You are given positive integers `n` and `m`. + +Define two integers, `num1` and `num2`, as follows: + +`num1`: The sum of all integers in the range `[1, n]` that are not divisible by `m`. +`num2`: The sum of all integers in the range `[1, n]` that are divisible by `m`. +Return the integer `num1 - num2`. + + +### Example + +**Example 1:** + + +``` +Input: n = 10, m = 3 +Output: 19 +Explanation: In the given example: +- Integers in the range [1, 10] that are not divisible by 3 are [1,2,4,5,7,8,10], num1 is the sum of those integers = 37. +- Integers in the range [1, 10] that are divisible by 3 are [3,6,9], num2 is the sum of those integers = 18. +We return 37 - 18 = 19 as the answer. +``` +**Example 2:** +``` +Input: n = 5, m = 6 +Output: 15 +Explanation: In the given example: +- Integers in the range [1, 5] that are not divisible by 6 are [1,2,3,4,5], num1 is the sum of those integers = 15. +- Integers in the range [1, 5] that are divisible by 6 are [], num2 is the sum of those integers = 0. +We return 15 - 0 = 15 as the answer. +``` +### Constraints + +- `1 <= n, m <= 1000` + +## Solution Approach + +### Intuition: + +To efficiently determine the difference of divisible and nondivisible sums. +## Solution Implementation + +### Code In Different Languages: + + + + + ```javascript + class Solution { + differenceOfSums(n, m) { + let num1 = 0; + let num2 = 0; + for (let i = 1; i <= n; i++) { + if (i % m !== 0) { + num1 += i; + } else { + num2 += i; + } + } + return num1 - num2; + } +} + + + + + ``` + + + + + ```typescript + class Solution { + differenceOfSums(n: number, m: number): number { + let num1: number = 0; + let num2: number = 0; + for (let i: number = 1; i <= n; i++) { + if (i % m !== 0) { + num1 += i; + } else { + num2 += i; + } + } + return num1 - num2; + } +} + + + ``` + + + + + ```python + +class Solution: + def differenceOfSums(self, n: int, m: int) -> int: + num1 = 0 + num2 = 0 + for i in range(1, n + 1): + if i % m != 0: + num1 += i + else: + num2 += i + return num1 - num2 + ``` + + + + + ```java + public class Solution { + public int differenceOfSums(int n, int m) { + int num1 = 0; + int num2 = 0; + for (int i = 1; i <= n; i++) { + if (i % m != 0) { + num1 += i; + } else { + num2 += i; + } + } + return num1 - num2; + } +} + ``` + + + + + ```cpp + class Solution { +public: + int differenceOfSums(int n, int m) { + int num1 = 0; + int num2 = 0; + for(int i=1; i<=n; i++){ + if(i%m!=0) num1+=i; + else num2+=i; + } + return num1-num2; + } +}; + ``` + + + +#### Complexity Analysis + +- Time Complexity: $$O(n)$$ +- Space Complexity: $$O(1)$$ +- The time complexity is $$O(n)$$ where n input. This is because the function iterates from 1 to n once, performing a constant amount of work for each element. +- The space complexity is $$O(1)$$ because we are not using any extra space. \ No newline at end of file diff --git a/solutions/lc-solutions/2800-2899/_category_.json b/solutions/lc-solutions/2800-2899/_category_.json new file mode 100644 index 0000000..35ae8d7 --- /dev/null +++ b/solutions/lc-solutions/2800-2899/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "2800-2899", + "position": 30, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (2800 - 2899)" + } +} diff --git a/solutions/lc-solutions/2900-2999/2900-longest-unequal-adjacent-groups-subsequence-i.md b/solutions/lc-solutions/2900-2999/2900-longest-unequal-adjacent-groups-subsequence-i.md new file mode 100644 index 0000000..e3e14d0 --- /dev/null +++ b/solutions/lc-solutions/2900-2999/2900-longest-unequal-adjacent-groups-subsequence-i.md @@ -0,0 +1,154 @@ +--- +id: longest-unequal-adjacent-groups-subsequence-i +title: Longest Unequal Adjacent Groups Subsequence I +sidebar_label: 2900 Longest Unequal Adjacent Groups Subsequence I +tags: + - Array + - Greedy + - LeetCode + - C++ + - Java + - Python +description: "This is a solution to the Longest Unequal Adjacent Groups Subsequence I problem on LeetCode." +sidebar_position: 2900 +--- + +## Problem Description + +You are given a string array `words` and a binary array `groups`, both of length `n`, where `words[i]` is associated with `groups[i]`. + +Your task is to select the longest alternating subsequence from `words`. A subsequence of `words` is alternating if for any two consecutive strings in the sequence, their corresponding elements in the binary array `groups` differ. Essentially, you are to choose strings such that adjacent elements have non-matching corresponding bits in the `groups` array. + +Formally, you need to find the longest subsequence of an array of indices `[0, 1, ..., n - 1]` denoted as `[i0, i1, ..., ik-1]`, such that `groups[ij] != groups[ij+1]` for each `0 <= j < k - 1` and then find the words corresponding to these indices. + +Return the selected subsequence. If there are multiple answers, return any of them. + +Note: The elements in `words` are distinct. + +### Examples + +**Example 1:** + +``` +Input: words = ["e","a","b"], groups = [0,0,1] +Output: ["e","b"] +Explanation: A subsequence that can be selected is ["e","b"] because groups[0] != groups[2]. Another subsequence that can be selected is ["a","b"] because groups[1] != groups[2]. It can be demonstrated that the length of the longest subsequence of indices that satisfies the condition is 2. +``` + +**Example 2:** + +``` +Input: words = ["a","b","c","d"], groups = [1,0,1,1] +Output: ["a","b","c"] +Explanation: A subsequence that can be selected is ["a","b","c"] because groups[0] != groups[1] and groups[1] != groups[2]. Another subsequence that can be selected is ["a","b","d"] because groups[0] != groups[1] and groups[1] != groups[3]. It can be shown that the length of the longest subsequence of indices that satisfies the condition is 3. +``` + +### Constraints + +- `1 ≀ n == words.length == groups.length ≀ 100` +- `1 ≀ words[i].length ≀ 10` +- `groups[i]` is either 0 or 1. +- `words` consists of distinct strings. +- `words[i]` consists of lowercase English letters. + +### Approach + +To solve this problem, we can use a greedy approach to construct the longest alternating subsequence. The idea is to start with the first element and then continue adding elements to the subsequence only if the current element has a different group value than the previous element in the subsequence. + +This approach ensures that we build the longest possible alternating subsequence in a single pass through the array, making it both simple and efficient. + +### Time Complexity + +The time complexity is $O(n)$. where `n` is the length of the `words` array. This is because we are iterating through the array once. + +### Code Implementation + + + + + + ```cpp + class Solution { + public: + vector getLongestSubsequence(vector& words, vector& groups) { + vector result; + int n = words.size(); + if (n == 0) return result; + + result.push_back(words[0]); + for (int i = 1; i < n; ++i) { + if (groups[i] != groups[i - 1]) { + result.push_back(words[i]); + } + } + return result; + } + }; + ``` + + + + + + ```java + class Solution { + public List getLongestSubsequence(String[] words, int[] groups) { + List result = new ArrayList<>(); + int n = words.length; + if (n == 0) return result; + + result.add(words[0]); + for (int i = 1; i < n; ++i) { + if (groups[i] != groups[i - 1]) { + result.add(words[i]); + } + } + return result; + } + } + ``` + + + + + + ```python + class Solution: + def getLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]: + result = [] + n = len(words) + if n == 0: + return result + + result.append(words[0]) + for i in range(1, n): + if groups[i] != groups[i - 1]: + result.append(words[i]) + + return result + + # Example usage + if __name__ == "__main__": + solution = Solution() + print(solution.getLongestSubsequence(["a", "b", "c", "d"], [1, 0, 1, 1])) # Expected output: ["a", "b", "c"] + print(solution.getLongestSubsequence(["e", "a", "b"], [0, 0, 1])) # Expected output: ["e", "b"] + ``` + + + + +## Solution Logic + +1. A number `n` is a power of 2 if it has exactly one bit set in its binary representation. +2. To check this, you can use the property: `n & (n - 1) == 0`. +3. This expression is true only for powers of 2. + +## Time Complexity +- The function operates in constant time, $O(1)$. + +## Space Complexity +- The function uses constant space, $O(1)$. + +## References +- LeetCode Problem: [Longest Unequal Adjacent Groups Subsequence I](#) +- Greedy Algorithm: [GeeksforGeeks Greedy Algorithm](#) diff --git a/solutions/lc-solutions/2900-2999/2901-longest-unequal-adjacent-groups-subsequence-ii.md b/solutions/lc-solutions/2900-2999/2901-longest-unequal-adjacent-groups-subsequence-ii.md new file mode 100644 index 0000000..da49105 --- /dev/null +++ b/solutions/lc-solutions/2900-2999/2901-longest-unequal-adjacent-groups-subsequence-ii.md @@ -0,0 +1,149 @@ +--- +id: longest-unequal-adjacent-groups-subsequence-ii +title: Longest Unequal Adjacent Groups Subsequence II +sidebar_label: 2901 Longest Unequal Adjacent Groups Subsequence II +tags: + - Array + - Dynamic Programming + - LeetCode + - C++ +description: "This is a solution to the Longest Unequal Adjacent Groups Subsequence II problem on LeetCode." +sidebar_position: 2901 +--- + +## Problem Description + +You are given a string array `words`, and an array `groups`, both arrays having length `n`. + +The Hamming distance between two strings of equal length is the number of positions at which the corresponding characters are different. + +You need to select the longest subsequence from an array of indices `[0, 1, ..., n - 1]`, such that for the subsequence denoted as `[i0, i1, ..., ik-1]` having length `k`, the following holds: + +1. For adjacent indices in the subsequence, their corresponding groups are unequal, i.e., `groups[ij] != groups[ij+1]`, for each `j` where `0 < j + 1 < k`. +2. `words[ij]` and `words[ij+1]` are equal in length, and the Hamming distance between them is 1, where `0 < j + 1 < k`, for all indices in the subsequence. + +Return a string array containing the words corresponding to the indices (in order) in the selected subsequence. If there are multiple answers, return any of them. + +**Note**: strings in `words` may be unequal in length. + +### Examples + +**Example 1:** + +``` +Input: words = ["bab","dab","cab"], groups = [1,2,2] + +Output: ["bab","cab"] + +Explanation: A subsequence that can be selected is [0,2]. + +groups[0] != groups[2] +words[0].length == words[2].length, and the hamming distance between them is 1. +So, a valid answer is [words[0],words[2]] = ["bab","cab"]. + +Another subsequence that can be selected is [0,1]. + +groups[0] != groups[1] +words[0].length == words[1].length, and the hamming distance between them is 1. +So, another valid answer is [words[0],words[1]] = ["bab","dab"]. + +It can be shown that the length of the longest subsequence of indices that satisfies the conditions is 2. +``` + +**Example 2:** + +``` +Input: words = ["a","b","c","d"], groups = [1,2,3,4] + +Output: ["a","b","c","d"] + +Explanation: We can select the subsequence [0,1,2,3]. + +It satisfies both conditions. + +Hence, the answer is [words[0],words[1],words[2],words[3]] = ["a","b","c","d"]. + +It has the longest length among all subsequences of indices that satisfy the conditions. + +Hence, it is the only answer. +``` + +### Constraints +- `1 <= n == words.length == groups.length <= 1000` +- `1 <= words[i].length <= 10` +- `1 <= groups[i] <= n` +- `words consists of distinct strings.` +- `words[i] consists of lowercase English letters.` + +### Approach + +To solve this problem, we can use a greedy approach to construct the longest alternating subsequence. The idea is to start with the first element and then continue adding elements to the subsequence only if the current element has a different group value than the previous element in the subsequence. + +This approach ensures that we build the longest possible alternating subsequence in a single pass through the array, making it both simple and efficient. + +### Complexity + +- **Time complexity**: $O(n)$, where `n` is the length of the `words` array. This is because we are iterating through the array once. +- **Space complexity**: $O(n)$, for storing the result subsequence. + +#### C++ + +```cpp +class Solution { +public: + + bool isGood(string &s1, string &s2) + { + int diff = 0; + for(int i=0; s1[i]; i++) + { + if(s1[i] != s2[i]) + { + if(diff) + return false; + diff++; + } + } + return true; + } + + vector getWordsInLongestSubsequence(int n, vector& words, vector& groups) { + vector res; + vector lis(n, 1), parent(n); + int mx_index = 0; + + for(int i=0; i=0; j--) + { + if(groups[j] != groups[i] && sz == (int)words[j].size() && isGood(words[i], words[j]) ) + { + if(lis[j] + 1 > lis[i]) + { + lis[i] = lis[j] + 1; + parent[i] = j; + } + } + } + if(lis[i] > lis[mx_index]) + mx_index = i; + + //cout << lis[i] <<" "; + } + //cout << endl; + + int cur = mx_index; + while(parent[cur] != cur) + { + res.push_back(words[cur]); + cur = parent[cur]; + } + res.push_back(words[cur]); + + reverse(res.begin(), res.end()); + return res; + } +}; +``` diff --git a/solutions/lc-solutions/2900-2999/2902-count-of-sub-multisets-with-bounded-sum.md b/solutions/lc-solutions/2900-2999/2902-count-of-sub-multisets-with-bounded-sum.md new file mode 100644 index 0000000..ef66469 --- /dev/null +++ b/solutions/lc-solutions/2900-2999/2902-count-of-sub-multisets-with-bounded-sum.md @@ -0,0 +1,123 @@ +--- +id: count-of-sub-multisets-with-bounded-sum +title: Count of Sub-Multisets With Bounded Sum +sidebar_label: 2902 Count of Sub-Multisets With Bounded Sum +tags: + - Array + - Dynamic Programming + - LeetCode + - C++ +description: "This is a solution to the Count of Sub-Multisets With Bounded Sum problem on LeetCode." +sidebar_position: 2902 +--- + +## Problem Description + +You are given a 0-indexed array `nums` of non-negative integers, and two integers `l` and `r`. + +Return the count of sub-multisets within `nums` where the sum of elements in each subset falls within the inclusive range of `[l, r]`. + +Since the answer may be large, return it modulo 10^9 + 7. + +A sub-multiset is an unordered collection of elements of the array in which a given value x can occur 0, 1, ..., occ[x] times, where `occ[x]` is the number of occurrences of x in the array. + +Note that: + +- Two sub-multisets are the same if sorting both sub-multisets results in identical multisets. +- The sum of an empty multiset is 0. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,2,3], l = 6, r = 6 +Output: 1 +Explanation: The only subset of nums that has a sum of 6 is {1, 2, 3}. +``` + +**Example 2:** + +``` +Input: nums = [2,1,4,2,7], l = 1, r = 5 +Output: 7 +Explanation: The subsets of nums that have a sum within the range [1, 5] are {1}, {2}, {4}, {2, 2}, {1, 2}, {1, 4}, and {1, 2, 2}. +``` + +**Example 3:** + +``` +Input: nums = [1,2,1,3,5,2], l = 3, r = 5 +Output: 9 +Explanation: The subsets of nums that have a sum within the range [3, 5] are {3}, {5}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {1, 1, 2}, {1, 1, 3}, and {1, 2, 2}. +``` +### Constraints +- `1 <= nums.length <= 2 * 10^4` +- `0 <= nums[i] <= 2 * 10^4` +- `Sum of nums does not exceed 2 * 10^4.` +- `0 <= l <= r <= 2 * 10^4` + +### Approach + +dp[i] is the number of unique sorted multisets of sum i lets say that we use a new number, a that occurs c times within the array we can add a 1 to c times to every multiset to create new ones, so the dp transition will look like dp[i] += dp[i - a] + dp[i - a * 2] + ... + dp[i - a * c] + +Since the sum of c across all a is n, doing dp like this will result in n^2 time complexity. We can speed up the update for each pair of a, c by using sliding window. We do this by +we want to add to dp[i] dp[i - a] + dp[i - a * 2] + ... + dp[i - a * c]. + +Note that the stuff we add to dp[i - a] is very similar: dp[i - a * 2] + dp[i - a * 3] + ... + dp[i - a * (c + 1)] dp[i - a] got removed, and dp[i - a * (c + 1)] got added once you know the amount to add for dp[i], it takes constant time to compute the amount to add for dp[i - a]. + +I claim that when sped up, each pair will only take O(n) time to process and since the number of unique a is at most 200. + + +#### C++ + +```cpp +typedef long long ll; +const ll MOD = 1e9 + 7; + +class Solution { +public: + int countSubMultisets(vector& nums, int l, int r) { + const ll N = 2e4; + vector dp(N + 1); + map m; + dp[0] = 1; + m[0] = 1; + for(auto x : nums) { + m[x]++; + } + ll mult = m[0]; m.erase(0); + for(auto x : m) { + //{a, c} + ll a = x.first; + ll c = x.second; + vector help(N + 1); + for(int i = 1; i <= N; i++) { + ll sum = 0; + if(i - a >= 0) { + sum += dp[i-a]; + sum += help[i-a]; + } + if(i - a * (c + 1) >= 0) { + sum -= dp[i - a * (c + 1)]; + } + help[i] = (sum + MOD) % MOD; + } + for(int i = 0; i <= N; i++) { + dp[i] += help[i]; + if(dp[i] >= MOD) dp[i] -= MOD; + } + } + ll sum = 0; + for(int i = l; i <= r; i++) { + sum += dp[i]; + if(sum >= MOD) sum -= MOD; + } + return sum * mult % MOD; + } +}; +``` + +### Complexity +- Time complexity: $O(200n)$ +- Space complexity: $O(200n)$ \ No newline at end of file diff --git a/solutions/lc-solutions/2900-2999/2909-minimum-sum-of-mountain-triplets-ii.md b/solutions/lc-solutions/2900-2999/2909-minimum-sum-of-mountain-triplets-ii.md new file mode 100644 index 0000000..f546a52 --- /dev/null +++ b/solutions/lc-solutions/2900-2999/2909-minimum-sum-of-mountain-triplets-ii.md @@ -0,0 +1,166 @@ +--- +id: minimum-sum-of-mountain-triplets-ii +title: Minimum Sum of Mountain Triplets II +sidebar_label: 2902 Minimum Sum of Mountain Triplets II +tags: + - Array + - Dynamic Programming + - LeetCode + - C++ +description: "This is a solution to the Minimum Sum of Mountain Triplets II problem on LeetCode." +sidebar_position: 2902 +--- + +## Problem Description + +You are given a 0-indexed array `nums` of integers. + +A triplet of indices `(i, j, k)` is a mountain if: + +1. `i < j < k` +2. `nums[i] < nums[j]` and `nums[k] < nums[j]` + +Return the minimum possible sum of a mountain triplet of `nums`. If no such triplet exists, return `-1`. + +### Examples + +**Example 1:** + +``` +Input: nums = [8,6,1,5,3] +Output: 9 + +Explanation: Triplet (2, 3, 4) is a mountain triplet of sum 9 since: + +2 < 3 < 4 +nums[2] < nums[3] and nums[4] < nums[3] +And the sum of this triplet is nums[2] + nums[3] + nums[4] = 9. It can be shown that there are no mountain triplets with a sum of less than 9. + +``` + + +**Example 2:** + +``` +Input: nums = [5,4,8,7,10,2] +Output: 13 + +Explanation: Triplet (1, 3, 5) is a mountain triplet of sum 13 since: + +1 < 3 < 5 +nums[1] < nums[3] and nums[5] < nums[3] +And the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown that there are no mountain triplets with a sum of less than 13. +``` + +**Example 3:** +``` +Input: nums = [6,5,4,3,4,5] +Output: -1 + +Explanation: It can be shown that there are no mountain triplets in nums. + +``` + + +### Constraints +- `3 <= nums.length <= 10^5` +- `1 <= nums[i] <= 10^8` + +### Approach + +To solve this problem, we can use a dynamic programming approach. We will maintain two arrays, `left` and `right`, where `left[i]` contains the minimum value of `nums[l]` for `l < i` such that `nums[l] < nums[i]`, and `right[i]` contains the minimum value of `nums[r]` for `r > i` such that `nums[r] < nums[i]`. + +We will iterate through the array `nums` and calculate the possible minimum sum for each valid triplet `(i, j, k)`, updating the minimum sum as we go. + +### Complexity + +- **Time complexity**: $O(n)$, where `n` is the length of the `nums` array. This is because we are iterating through the array a constant number of times. +- **Space complexity**: $O(n)$, for storing the `left` and `right` arrays. + +#### C++ + +```cpp +class Solution { +public: + int minimumSumOfMountainTriplets(vector& nums) { + int n = nums.size(); + if (n < 3) return -1; + + vector leftMin(n, INT_MAX); + vector rightMin(n, INT_MAX); + + // Calculate leftMin array + int minLeft = INT_MAX; + for (int i = 1; i < n; ++i) { + if (nums[i - 1] < nums[i]) { + minLeft = min(minLeft, nums[i - 1]); + } + leftMin[i] = minLeft; + } + + // Calculate rightMin array + int minRight = INT_MAX; + for (int i = n - 2; i >= 0; --i) { + if (nums[i + 1] < nums[i]) { + minRight = min(minRight, nums[i + 1]); + } + rightMin[i] = minRight; + } + + int minSum = INT_MAX; + + // Find the minimum sum of a valid mountain triplet + for (int j = 1; j < n - 1; ++j) { + if (leftMin[j] != INT_MAX && rightMin[j] != INT_MAX && nums[j] > leftMin[j] && nums[j] > rightMin[j]) { + minSum = min(minSum, leftMin[j] + nums[j] + rightMin[j]); + } + } + + return minSum == INT_MAX ? -1 : minSum; + } +}; +``` +#### Java + +```java +class Solution { + public int minimumSumOfMountainTriplets(int[] nums) { + int n = nums.length; + if (n < 3) return -1; + + int[] leftMin = new int[n]; + int[] rightMin = new int[n]; + Arrays.fill(leftMin, Integer.MAX_VALUE); + Arrays.fill(rightMin, Integer.MAX_VALUE); + + // Calculate leftMin array + int minLeft = Integer.MAX_VALUE; + for (int i = 1; i < n; i++) { + if (nums[i - 1] < nums[i]) { + minLeft = Math.min(minLeft, nums[i - 1]); + } + leftMin[i] = minLeft; + } + + // Calculate rightMin array + int minRight = Integer.MAX_VALUE; + for (int i = n - 2; i >= 0; i--) { + if (nums[i + 1] < nums[i]) { + minRight = Math.min(minRight, nums[i + 1]); + } + rightMin[i] = minRight; + } + + int minSum = Integer.MAX_VALUE; + + // Find the minimum sum of a valid mountain triplet + for (int j = 1; j < n - 1; j++) { + if (leftMin[j] != Integer.MAX_VALUE && rightMin[j] != Integer.MAX_VALUE && nums[j] > leftMin[j] && nums[j] > rightMin[j]) { + minSum = Math.min(minSum, leftMin[j] + nums[j] + rightMin[j]); + } + } + + return minSum == Integer.MAX_VALUE ? -1 : minSum; + } +} +``` diff --git a/solutions/lc-solutions/2900-2999/2942-find-words-containing-character.md b/solutions/lc-solutions/2900-2999/2942-find-words-containing-character.md new file mode 100644 index 0000000..6de3bc0 --- /dev/null +++ b/solutions/lc-solutions/2900-2999/2942-find-words-containing-character.md @@ -0,0 +1,153 @@ +--- +id: find-words-containing-character +title: Find Words Containing Character +sidebar_label: 2942-Find Words Containing Character +tags: + - Array + - String +description: Write a function that returns the count of arguments passed to it. +sidebar_position: 2942 +--- + +## Problem Statement +You are given a **0-indexed** array of strings words and a character `x`. + +Return an **array of indices** representing the words that contain the character `x`. + +**Note** that the returned array may be in **any** order. + +### Examples + +**Example 1:** + +``` +Input: words = ["leet","code"], x = "e" +Output: [0,1] +Explination: "e" occurs in both words: "leet", and "code". Hence, we return indices 0 and 1. +``` + +**Example 2:** + +``` +Input: words = ["abc","bcd","aaaa","cbc"], x = "a" +Output: [0,2] +Explination: "a" occurs in "abc", and "aaaa". Hence, we return indices 0 and 2. +``` + +**Example 3:** + +``` +Input: words = ["abc","bcd","aaaa","cbc"], x = "z" +Output: [] +Explination: "z" does not occur in any of the words. Hence, we return an empty array. +``` + + + +### Constraints + +- `1 <= words.length <= 50` +- `1 <= words[i].length <= 50` +- `x` is a lowercase English letter. +- `words[i]` consists only of lowercase English letters. + +## Solution + +### Approach: + +- **Initialize a Result List:** Create an empty list to store the indices of the words containing the character `x`. +- **Iterate Through the Array:** Loop through each word in the words array. +- **Check for Character:** Use the indexOf method to check if the character `x` is present in the word. If found, add the current index to the result list. +- **Return the Result:** Return the list of indices. + +#### Java Implementation + +```java +class Solution { + public List findWordsContaining(String[] words, char x) { + List result = new ArrayList<>(); + + for (int i = 0; i < words.length; i++) { + if (words[i].indexOf(x) != -1) { + result.add(i); + } + } + + return result; + } +} +``` + +#### C++ Implementation + +```cpp + class Solution { +public: + vector findWordsContaining(vector& words, char x) { + std::vector result; + + for (int i = 0; i < words.size(); ++i) { + if (words[i].find(x) != std::string::npos) { + result.push_back(i); + } + } + + return result; + } +}; +``` +#### Python Implementation +```python +class Solution: + def findWordsContaining(self, words: List[str], x: str) -> List[int]: + result = [] + + for i in range(len(words)): + if x in words[i]: + result.append(i) + + return result +``` + +#### JavaScript Implementation + +```javascript +class Solution { + findWordsContaining(words, x) { + const result = []; + + for (let i = 0; i < words.length; i++) { + if (words[i].includes(x)) { + result.push(i); + } + } + + return result; + } +} + +``` + +#### TypeScript Implementation + +```typescript +class Solution { + findWordsContaining(words: string[], x: string): number[] { + const result: number[] = []; + + for (let i = 0; i < words.length; i++) { + if (words[i].includes(x)) { + result.push(i); + } + } + + return result; + } +} + +``` + +### Complexity Analysis + +- **Time Complexity**: O(n * m), where n is the number of words and m is the average length of the words. This is because each word is checked for the character `x`. +- **Space Complexity**: O(n), for storing the indices in the result list. diff --git a/solutions/lc-solutions/2900-2999/2944-Minimum-Number-Of-Coins-For-Fruits.md b/solutions/lc-solutions/2900-2999/2944-Minimum-Number-Of-Coins-For-Fruits.md new file mode 100644 index 0000000..57f218c --- /dev/null +++ b/solutions/lc-solutions/2900-2999/2944-Minimum-Number-Of-Coins-For-Fruits.md @@ -0,0 +1,235 @@ +--- +id: minimum-number-of-coins-for-fruits +title: Minimum Number of Coins for Fruits +sidebar_label: 2944-Minimum-Number-Of-Coins-For-Fruits +tags: + - Array + - Dynamic Programming + - Queue + - Heap + - Monotonic Queue +description: The problem is 2944. The problem is to find the Minimum Number of Coins for Fruits + +sidebar_position: 2944 +--- + +## Problem Statement +You are given an integer array `prices` where `prices[i]` denotes the number of coins needed to purchase the `ith` fruit. + +The fruit market has the following reward for each fruit: + +If you purchase the `ith` fruit at `prices[i]` coins, you can get any number of the next `(i + 1)` fruits for free. +Note that even if you can take fruit `j` for free, you can still purchase it for `prices[j]` coins to receive its reward. + +Return the minimum number of coins needed to acquire all the fruits. + + + +### Examples + +**Example 1:** + +``` +Input: prices = [3,1,2] + +Output: 4 + +Explanation: + +Purchase the 1st fruit with prices[0] = 3 coins, you are allowed to take the 2nd fruit for free. +Purchase the 2nd fruit with prices[1] = 1 coin, you are allowed to take the 3rd fruit for free. +Take the 3rd fruit for free. +Note that even though you could take the 2nd fruit for free as a reward of buying 1st fruit, you purchase it to receive its reward, which is more optimal. +``` + +**Example 2:** + +``` +Input: prices = [1,10,1,1] + +Output: 2 + +Explanation: + +Purchase the 1st fruit with prices[0] = 1 coin, you are allowed to take the 2nd fruit for free. +Take the 2nd fruit for free. +Purchase the 3rd fruit for prices[2] = 1 coin, you are allowed to take the 4th fruit for free. +Take the 4th fruit for free. +``` + +**Example 3:** + +``` +Input: prices = [26,18,6,12,49,7,45,45] + +Output: 39 + +Explanation: + +Purchase the 1st fruit with prices[0] = 26 coin, you are allowed to take the 2nd fruit for free. +Take the 2nd fruit for free. +Purchase the 3rd fruit for prices[2] = 6 coin, you are allowed to take the 4th, 5th and 6th (the next three) fruits for free. +Take the 4th fruit for free. +Take the 5th fruit for free. +Purchase the 6th fruit with prices[5] = 7 coin, you are allowed to take the 8th and 9th fruit for free. +Take the 7th fruit for free. +Take the 8th fruit for free. +Note that even though you could take the 6th fruit for free as a reward of buying 3rd fruit, you purchase it to receive its reward, which is more optimal. +``` + + + +### Constraints + +- `1 <= prices.length <= 1000` +- `1 <= prices[i] <= 10^5` + +## Solution + +#### Java Implementation + +```java +public class Solution { + public int minimumCoins(int[] prices) { + int n = prices.length; + int[][] dp = new int[n + 1][n + 1]; + for (int i = 0; i <= n; i++) { + for (int j = 0; j <= n; j++) { + dp[i][j] = -1; + } + } + return solve(0, n, prices, 0, dp); + } + + private int solve(int currentIndex, int n, int[] prices, int remainingOffer, int[][] dp) { + if (currentIndex == n) return 0; + if (currentIndex > n) return 1e8; + if (dp[currentIndex][remainingOffer] != -1) return dp[currentIndex][remainingOffer]; + if (remainingOffer > 0) { + return dp[currentIndex][remainingOffer] = Math.min( + prices[currentIndex] + solve(currentIndex + 1, n, prices, currentIndex + 1, dp), + solve(currentIndex + 1, n, prices, remainingOffer - 1, dp) + ); + } + return dp[currentIndex][remainingOffer] = prices[currentIndex] + solve(currentIndex + 1, n, prices, currentIndex + 1, dp); + } +} + +``` + +#### C++ Implementation + +```cpp + int solve(int currentIndex, int n, const std::vector& prices, int remainingOffer, std::vector>& dp) { + if (currentIndex == n) + return 0; + if (currentIndex > n) + return 1e8; + + if (dp[currentIndex][remainingOffer] != -1) + return dp[currentIndex][remainingOffer]; + + + if (remainingOffer) { + return dp[currentIndex][remainingOffer] = std::min( + prices[currentIndex] + solve(currentIndex + 1, n, prices, currentIndex + 1, dp), + solve(currentIndex + 1, n, prices, remainingOffer - 1, dp) + ); + } + + + return dp[currentIndex][remainingOffer] = prices[currentIndex] + solve(currentIndex + 1, n, prices, currentIndex + 1, dp); + } +class Solution{ +public: + int minimumCoins(std::vector& prices) { + int n = prices.size(); + std::vector> dp(n + 1, std::vector(n + 1, -1)); + + return solve(0, n, prices, 0, dp); + } +}; +``` +#### Python Implementation +```python +def solve(currentIndex, n, prices, remainingOffer, dp): + if currentIndex == n: + return 0 + if currentIndex > n: + return 1e8 + if dp[currentIndex][remainingOffer] != -1: + return dp[currentIndex][remainingOffer] + if remainingOffer: + return dp[currentIndex][remainingOffer] = min( + prices[currentIndex] + solve(currentIndex + 1, n, prices, currentIndex + 1, dp), + solve(currentIndex + 1, n, prices, remainingOffer - 1, dp) + ) + return dp[currentIndex][remainingOffer] = prices[currentIndex] + solve(currentIndex + 1, n, prices, currentIndex + 1, dp) + +class Solution: + def minimumCoins(self, prices): + n = len(prices) + dp = [[-1] * (n + 1) for _ in range(n + 1)] + return solve(0, n, prices, 0, dp) + +``` + +#### JavaScript Implementation + +```javascript +function solve(currentIndex, n, prices, remainingOffer, dp) { + if (currentIndex == n) return 0; + if (currentIndex > n) return 1e8; + if (dp[currentIndex][remainingOffer] != -1) return dp[currentIndex][remainingOffer]; + if (remainingOffer) { + return dp[currentIndex][remainingOffer] = Math.min( + prices[currentIndex] + solve(currentIndex + 1, n, prices, currentIndex + 1, dp), + solve(currentIndex + 1, n, prices, remainingOffer - 1, dp) + ); + } + return dp[currentIndex][remainingOffer] = prices[currentIndex] + solve(currentIndex + 1, n, prices, currentIndex + 1, dp); +} + +class Solution { + minimumCoins(prices) { + const n = prices.length; + const dp = new Array(n + 1).fill(-1).map(() => new Array(n + 1).fill(-1)); + return solve(0, n, prices, 0, dp); + } +} + + +``` + +#### TypeScript Implementation + +```typescript +function solve(currentIndex: number, n: number, prices: number[], remainingOffer: number, dp: number[][]): number { + if (currentIndex == n) return 0; + if (currentIndex > n) return 1e8; + if (dp[currentIndex][remainingOffer] != -1) return dp[currentIndex][remainingOffer]; + if (remainingOffer) { + return dp[currentIndex][remainingOffer] = Math.min( + prices[currentIndex] + solve(currentIndex + 1, n, prices, currentIndex + 1, dp), + solve(currentIndex + 1, n, prices, remainingOffer - 1, dp) + ); + } + return dp[currentIndex][remainingOffer] = prices[currentIndex] + solve(currentIndex + 1, n, prices, currentIndex + 1, dp); +} + +class Solution { + minimumCoins(prices: number[]): number { + const n = prices.length; + const dp: number[][] = new Array(n + 1).fill(-1).map(() => new Array(n + 1).fill(-1)); + return solve(0, n, prices, 0, dp); + } +} + + +``` + +### Complexity Analysis + +- **Time Complexity**: O(n^2),where n is the length of the input array prices. This is because the algorithm uses a nested loop to iterate over the array, and the solve function is called recursively with different parameters. + +- **Space Complexity**: O(n^2), as the dp array is used to store the results of subproblems, and its size grows quadratically with the size of the input array prices. \ No newline at end of file diff --git a/solutions/lc-solutions/2900-2999/2999-count-the-number-of-powerful-integers.md b/solutions/lc-solutions/2900-2999/2999-count-the-number-of-powerful-integers.md new file mode 100644 index 0000000..7bd2153 --- /dev/null +++ b/solutions/lc-solutions/2900-2999/2999-count-the-number-of-powerful-integers.md @@ -0,0 +1,121 @@ +--- +id: count-the-number-of-powerful-integers +title: Count the Number of Powerful Integers +sidebar_label: 2999 Count the Number of Powerful Integers +tags: + - Array + - String + - LeetCode + - C++ +description: "This is a solution to the Count the Number of Powerful Integers problem on LeetCode." +sidebar_position: 2999 +--- + +## Problem Description + +You are given three integers `start`, `finish`, and `limit`. You are also given a 0-indexed string `s` representing a positive integer. + +A positive integer `x` is called powerful if it ends with `s` (in other words, `s` is a suffix of `x`) and each digit in `x` is at most `limit`. + +Return the total number of powerful integers in the range `[start..finish]`. + +A string `x` is a suffix of a string `y` if and only if `x` is a substring of `y` that starts from some index (including 0) in `y` and extends to the index `y.length - 1`. For example, 25 is a suffix of 5125 whereas 512 is not. + +### Examples + +**Example 1:** + +``` +Input: start = 1, finish = 6000, limit = 4, s = "124" +Output: 5 +Explanation: The powerful integers in the range [1..6000] are 124, 1124, 2124, 3124, and, 4124. All these integers have each digit <= 4, and "124" as a suffix. Note that 5124 is not a powerful integer because the first digit is 5 which is greater than 4. +``` + + +**Example 2:** + +``` +Input: start = 15, finish = 215, limit = 6, s = "10" +Output: 2 +Explanation: The powerful integers in the range [15..215] are 110 and 210. All these integers have each digit <= 6, and "10" as a suffix. +``` + + +**Example 3:** + +``` +Input: start = 1000, finish = 2000, limit = 4, s = "3000" +Output: 0 +Explanation: All integers in the range [1000..2000] are smaller than 3000, hence "3000" cannot be a suffix of any integer in this range. +``` + + +### Constraints + +- `1 <= start <= finish <= 10^15` +- `1 <= limit <= 9` +- `1 <= s.length <= floor(log10(finish)) + 1` +- `s` only consists of numeric digits which are at most limit. +- `s` does not have leading zeros. + +### Approach + +To solve this problem, we will iterate through all integers in the range `[start..finish]`. For each integer, we will check if it ends with the suffix `s` and if all its digits are at most `limit`. If both conditions are met, we count it as a powerful integer. + +### Complexity + +- **Time complexity**: $O((finish - start + 1) \cdot L)$, where `L` is the length of the longest integer in the range when converted to a string. +- **Space complexity**: $O(1)$, as we are only using a few variables to store the count and current number. + +### Solution + +#### C++ + +```cpp +class Solution { +public: + int countPowerfulIntegers(long long start, long long finish, int limit, string s) { + int count = 0; + for (long long i = start; i <= finish; ++i) { + string num = to_string(i); + if (num.size() < s.size()) continue; + if (num.substr(num.size() - s.size()) == s) { + bool isPowerful = true; + for (char c : num) { + if (c - '0' > limit) { + isPowerful = false; + break; + } + } + if (isPowerful) ++count; + } + } + return count; + } +}; +``` + +#### Java + +``` java +class Solution { + public int countPowerfulIntegers(long start, long finish, int limit, String s) { + int count = 0; + for (long i = start; i <= finish; i++) { + String num = Long.toString(i); + if (num.length() < s.length()) continue; + if (num.substring(num.length() - s.length()).equals(s)) { + boolean isPowerful = true; + for (char c : num.toCharArray()) { + if (c - '0' > limit) { + isPowerful = false; + break; + } + } + if (isPowerful) count++; + } + } + return count; + } +} +``` \ No newline at end of file diff --git a/solutions/lc-solutions/2900-2999/_category_.json b/solutions/lc-solutions/2900-2999/_category_.json new file mode 100644 index 0000000..f357d17 --- /dev/null +++ b/solutions/lc-solutions/2900-2999/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "2900-2999", + "position": 31, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (2900 - 2999)" + } +} diff --git a/solutions/lc-solutions/3000-3099/3000-maximum-area-of-diagonal-rectangle.md b/solutions/lc-solutions/3000-3099/3000-maximum-area-of-diagonal-rectangle.md new file mode 100644 index 0000000..d646a2a --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3000-maximum-area-of-diagonal-rectangle.md @@ -0,0 +1,113 @@ +--- +id: 3000-maximum-area-of-diagonal-rectangle +title: Maximum area of longest diagonal rectangle (Leetcode) +sidebar_label: 3000-Maximum area of longest diagonal rectangle +description: Solution of Maximum area of longest diagonal rectangle +--- + + +## Problem Description + +You are given a 2D 0-indexed integer array dimensions. + +For all indices i,`0 <= i < dimensions.length`, dimensions[i][0] represents the length and dimensions[i][1] represents the width of the rectangle i. + +Return the area of the rectangle having the longest diagonal. If there are multiple rectangles with the longest diagonal, return the area of the rectangle having the maximum area. + +### Examples + +#### Example 1 + +- **Input:** $dimensions = [[9,3],[8,6]]$ +- **Output:** $48$ +- **Explanation:** For index = $0$, $\text{length} = 9$ and width = $3$. $\text{Diagonal length} = sqrt(9 \times 9 + 3 \times 3) = sqrt(90) β‰ˆ 9.487$. + For $\text{index} = 1$, $length = 8$ and $\text{width} = 6$. $\text{Diagonal length} = sqrt(8 \times 8 + 6 \times 6) = sqrt(100) = 10$. + So, the rectangle at index 1 has a greater diagonal length therefore we return $area = 8 \times 6 = 48..$ + +#### Example 2 + +- **Input:** $dimensions = [[3,4],[4,3]]$ +- **Output:** $12$ +- **Explanation:**$ Length of diagonal is the same for both which is 5, so maximum area = 12$. + +### Constraints + +- $1 \leq dimensions.length \leq 100$ +- $dimensions[i].length == 2$ +- $1 <= dimensions[i][0], dimensions[i][1] <= 100$ + +### Intuition + +The problem requires finding the rectangle with the maximum diagonal length and, in case of a tie, returning the one with the maximum area. +To achieve this, we need to calculate the diagonal length for each rectangle and compare it with the current maximum diagonal length. +If the diagonal length is greater or equal (in case of a tie), we update the maximum diagonal length and check if the area of the current rectangle is greater than the maximum area. If so, we update the maximum area as well. + +### Approach + +The code uses a loop to iterate through each rectangle in the given dimensions vector. +It calculates the square of the diagonal length for each rectangle and compares it with the previous maximum diagonal length (diag). +If the current rectangle has a longer or equal diagonal length, it updates the maximum area (area) accordingly. +The area variable keeps track of the maximum area among rectangles with the longest diagonal. +Finally, the function returns the maximum area among rectangles with the longest diagonal. + +### Solution Code + +#### Python + +```py + class Solution: + def areaOfMaxDiagonal(self, dimensions: List[List[int]]) -> int: + a,b = max(dimensions, key = lambda x: (x[0]*x[0]+x[1]*x[1], (x[0]*x[1]))) + return a*b +``` + +#### Java + +```java + + public int areaOfMaxDiagonal(int[][] dimensions) { + int diagSq = 0, area = 0; + for (int[] d : dimensions) { + int ds = d[0] * d[0] + d[1] * d[1]; + int ar = d[0] * d[1]; + if (ds > diagSq) { + area = ar; + diagSq = ds; + } + else if (ds == diagSq && ar > area) area = ar; + } + return area; + } +``` + +#### C++ + +```cpp +class Solution { +public: + int areaOfMaxDiagonal(vector>& dimensions) { + + double max_diagonal = 0; + int max_area = 0; + + for (const auto& rectangle : dimensions) { + int length = rectangle[0]; + int width = rectangle[1]; + + double diagonal_length = sqrt(pow(length, 2) + pow(width, 2)); + + if (diagonal_length > max_diagonal || (diagonal_length == max_diagonal && length * width > max_area)) { + max_diagonal = diagonal_length; + max_area = length * width; + } + } + + return max_area; + + } +}; +``` + +### Conclusion + +At last we can say that we can calculate maximum area of diagonal rectangle using timecomplexity of $o(n)$ and spacecomplexity of $o(1)$ using a simple for loop and some variable diff --git a/solutions/lc-solutions/3000-3099/3001-Minimum-Moves-To-Capture-The-Queen.md b/solutions/lc-solutions/3000-3099/3001-Minimum-Moves-To-Capture-The-Queen.md new file mode 100644 index 0000000..ff86d24 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3001-Minimum-Moves-To-Capture-The-Queen.md @@ -0,0 +1,152 @@ +--- +id: minimum-moves-to-capture-the-queen +title: Minimum Moves to Capture the Queen (Leetcode) +sidebar_label: 3000-Minimum Moves to Capture the Queen +description: Solution for Minimum Moves to Capture the Queen on a Chessboard +--- + +## Problem Description + +You are given a 1-indexed 8 x 8 chessboard containing 3 pieces. + +You are given 6 integers ( a, b, c, d, e, f ) where: +- ((a, b)) denotes the position of the white rook. +- ((c, d)) denotes the position of the white bishop. +- ((e, f)) denotes the position of the black queen. + +Given that you can only move the white pieces, return the minimum number of moves required to capture the black queen. + +**Note:** +- Rooks can move any number of squares either vertically or horizontally, but cannot jump over other pieces. +- Bishops can move any number of squares diagonally, but cannot jump over other pieces. +- A rook or a bishop can capture the queen if it is located in a square that they can move to. +- The queen does not move. + +### Examples + +#### Example 1 + +- **Input:** ( a = 1, b = 1, c = 8, d = 8, e = 2, f = 3 ) +- **Output:** 2 +- **Explanation:** We can capture the black queen in two moves by moving the white rook to (1, 3) then to (2, 3). It is impossible to capture the black queen in less than two moves since it is not being attacked by any of the pieces at the beginning. + +#### Example 2 + +- **Input:** $a = 5, b = 3, c = 3, d = 4, e = 5, f = 2$ +- **Output:** 1 +- **Explanation:** We can capture the black queen in a single move by doing one of the following: + - Move the white rook to $(5, 2)$. + - Move the white bishop to $(5, 2)$. + +### Constraints + +- $1 \leq a, b, c, d, e, f \leq 8$ +- No two pieces are on the same square. + +## Solution + +To solve this problem, we need to determine the minimum number of moves required for either the white rook or the white bishop to capture the black queen on an 8x8 chessboard. We'll use a breadth-first search (BFS) approach to explore the board and find the shortest path to capture the queen. + +### Approach + +1. **Define the possible moves:** + - **Rook**: The rook can move vertically or horizontally any number of squares. + - **Bishop**: The bishop can move diagonally any number of squares. + +2. **Breadth-First Search (BFS):** + - Use BFS to explore the board from the initial positions of the rook and the bishop. + - Track the positions we've already visited to avoid processing the same position multiple times. + +3. **Initial Setup:** + - Use a queue to store the positions of the rook and the bishop along with the move count. + - Use a set to track visited positions. + +4. **Capture Conditions:** + - If either the rook or the bishop can move to the queen's position in the current step, return the move count. + +### Solution Code + +#### Python + +```python +from collections import deque + +def minMovesToCaptureTheQueen(rookX, rookY, bishopX, bishopY, queenX, queenY): + rookDirections = [(0, 1), (1, 0), (0, -1), (-1, 0)] + + bishopDirections = [(1, 1), (1, -1), (-1, 1), (-1, -1)] + queue = deque([(rookX, rookY, 0, 0), (bishopX, bishopY, 0, 1)]) + + visited = set() + visited.add((rookX, rookY, 0)) + visited.add((bishopX, bishopY, 1)) + + while queue: + x, y, moves, pieceType = queue.popleft() + + if (x, y) == (queenX, queenY): + return moves + +``` +#### Java +```Java +import java.util.*; + +class Solution { + public int minMovesToCaptureTheQueen(int rookX, int rookY, int bishopX, int bishopY, int queenX, int queenY) { + int[][] rookDirections = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + int[][] bishopDirections = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; + + Queue queue = new LinkedList<>(); + queue.offer(new int[]{rookX, rookY, 0, 0}); + queue.offer(new int[]{bishopX, bishopY, 0, 1}); + + Set visited = new HashSet<>(); + visited.add(rookX + "," + rookY + ",0"); + visited.add(bishopX + "," + bishopY + ",1"); + + while (!queue.isEmpty()) { + int[] current = queue.poll(); + int x = current[0]; + int y = current[1]; + int moves = current[2]; + int pieceType = current[3]; + + if (x == queenX && y == queenY) { + return moves; + } + + int[][] directions = pieceType == 0 ? rookDirections : bishopDirections; + + for (int[] dir : directions) { + int newX = x; + int newY = y; + + while (true) { + newX += dir[0]; + newY += dir[1]; + + if (newX < 1 || newX > 8 || newY < 1 || newY > 8) { + break; + } + + String newPositionKey = newX + "," + newY + "," + pieceType; + + if (!visited.contains(newPositionKey)) { + queue.offer(new int[]{newX, newY, moves + 1, pieceType}); + visited.add(newPositionKey); + } + } + } + } + + return -1; + } +} + +``` + +### Conclusion + +This solution ensures that we find the minimum number of moves needed for either the rook or the bishop to capture the queen using BFS. The approach efficiently explores all possible moves and returns the shortest path to capture the queen \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3002-maximum-size-of-a-set-after-removals.md b/solutions/lc-solutions/3000-3099/3002-maximum-size-of-a-set-after-removals.md new file mode 100644 index 0000000..1ae5c7e --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3002-maximum-size-of-a-set-after-removals.md @@ -0,0 +1,153 @@ +--- +id: maximum-size-of-a-set-after-removals +title: Maximum Size of a Set After Removals +sidebar_label: 3002 -Maximum Size of a Set After Removals +tags: + - Array + - Hash Table + - Greedy +description: "This is a solution to the Maximum Size of a Set After Removals problem on LeetCode." +--- + +## Problem Description + +You are given two 0-indexed integer arrays nums1 and nums2 of even length n. + +You must remove n / 2 elements from nums1 and n / 2 elements from nums2. After the removals, you insert the remaining elements of nums1 and nums2 into a set s. + +Return the maximum possible size of the set s. + +### Examples + +**Example 1:** + +``` +Input: nums1 = [1,2,1,2], nums2 = [1,1,1,1] +Output: 2 +Explanation: We remove two occurences of 1 from nums1 and nums2. After the removals, the arrays become equal to nums1 = [2,2] and nums2 = [1,1]. Therefore, s = {1,2}. +It can be shown that 2 is the maximum possible size of the set s after the removals. + +``` + +**Example 2:** + +``` +Input: nums1 = [1,2,3,4,5,6], nums2 = [2,3,2,3,2,3] +Output: 5 +Explanation: We remove 2, 3, and 6 from nums1, as well as 2 and two occurrences of 3 from nums2. After the removals, the arrays become equal to nums1 = [1,4,5] and nums2 = [2,3,2]. Therefore, s = {1,2,3,4,5}. +It can be shown that 5 is the maximum possible size of the set s after the removals. + +``` + +**Example 3:** + +``` +Input: nums1 = [1,1,2,2,3,3], nums2 = [4,4,5,5,6,6] +Output: 6 +Explanation: We remove 1, 2, and 3 from nums1, as well as 4, 5, and 6 from nums2. After the removals, the arrays become equal to nums1 = [1,2,3] and nums2 = [4,5,6]. Therefore, s = {1,2,3,4,5,6}. +It can be shown that 6 is the maximum possible size of the set s after the removals. +``` + +### Constraints + +- `n == nums1.length == nums2.length` +- `1 <= n <= 2 * 104` +- `n is even` +- `1 <= nums1[i], nums2[i] <= 109` + +## Solution for Minimum Moves to Capture The Queen Problem + +### Intuition + +To solve this problem, we can use a greedy approach. We aim to maximize the size of the set s after removing elements from nums1 and nums2. We can achieve this by removing elements that appear the most in both arrays. Additionally, we may need to remove elements from one array to balance the removals between the two arrays. + +### Approach + +Initialize variables length, n1, and n2. length represents half the length of the input arrays, while n1 and n2 are sets of unique elements from nums1 and nums2, respectively. + +Calculate the number of elements common to both n1 and n2 and store it in inter_num. + +Calculate the difference between the lengths of n1 and n2 and length, representing the excess elements in each array. + +Determine the maximum possible difference between the lengths of n1 and n2 and length, or the number of elements common to both arrays. Store this maximum difference in max_diff. + +Return the sum of the lengths of n1 and n2 minus max_diff, which represents the maximum possible size of the set s. + +### Solution Code + +#### Python + +```py +class Solution: + def maximumSetSize(self, nums1: list[int], nums2: list[int]) -> int: + length, n1, n2 = len(nums1) // 2, set(nums1), set(nums2) + inter_num = len(n1.intersection(n2)) + diff = 0 + + diff += len(n1) - length if len(n1) >= length else 0 + diff += len(n2) - length if len(n2) >= length else 0 + + max_diff=max(diff,inter_num) + + return (len(n1)+len(n2))-max_diff + +``` + +#### Java + +```java +class Solution { + public int maximumSetSize(int[] nums1, int[] nums2) { + int i,j,n=nums1.length; + Set set1=new HashSet<>(); + Set set2=new HashSet<>(); + Set set3=new HashSet<>(); + for(int x:nums1) + { + set1.add(x); + set3.add(x); + } + for(int x:nums2) + { + set2.add(x); + set3.add(x); + } + int common=set1.size()+set2.size()-set3.size(); + int n1=set1.size(),n2=set2.size(); + int ans=Math.min(n/2,n1-common); + ans+=Math.min(n/2,n2-common); + ans+=common; + ans=Math.min(n,ans); + return ans; + } +} + +``` + +#### C++ + +```cpp +class Solution { +public: + int maximumSetSize(vector& nums1, vector& nums2) { + set s1, s2, s; + int n = nums1.size(); + for (int x : nums1) { + s1.insert(x); + s.insert(x); + } + for (int x : nums2) { + s2.insert(x); + s.insert(x); + } + int ans = min(min(n/2, (int)s1.size()) + min(n/2, (int)s2.size()),(int) s.size()); + + return ans; + } +}; +``` + +#### Complexity Analysis + +- Time complexity: $O(n)$, where n is the total number of elements in both nums1 and nums2. Calculating the set intersection and differences takes linear time. +- Space complexity: $O(n)$ , where n is the total number of elements in both nums1 and nums2. The space complexity is dominated by the sets n1 and n2, which store unique elements from the input arrays. diff --git a/solutions/lc-solutions/3000-3099/3003-maximize-the-number -of-partitions-after-operations.md b/solutions/lc-solutions/3000-3099/3003-maximize-the-number -of-partitions-after-operations.md new file mode 100644 index 0000000..58c7189 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3003-maximize-the-number -of-partitions-after-operations.md @@ -0,0 +1,264 @@ +--- +id: maximize-the-number-of-partitions-after-operations +title: Maximize-the-Number-of-Partitions-After-Operations +sidebar_label: 3003 -Maximize the Number of Partitions After Operations +tags: + - String + - Dynammic Programming + - BitManipulation +description: "This is a solution to the Maximize the Number of Partitions After Operations problem on LeetCode." +--- + +## Problem Description +You are given a 0-indexed string `s` and an integer `k`. + +You are to perform the following partitioning operations until `s` is empty: + +- Choose the longest prefix of `s` containing at most `k` distinct characters. +- Delete the prefix from `s` and increase the number of partitions by one. The remaining characters (if any) in `s` maintain their initial order. +Before the operations, you are allowed to change at most one index in `s` to another lowercase English letter. + +Return an integer denoting the maximum number of resulting partitions after the operations by optimally choosing at most one index to change. + +### Examples + +**Example 1:** + +``` +Input: s = "accca", k = 2 +Output: 3 +Explanation: In this example, to maximize the number of resulting partitions, s[2] can be changed to 'b'. +s becomes "acbca". +The operations can now be performed as follows until s becomes empty: +- Choose the longest prefix containing at most 2 distinct characters, "acbca". +- Delete the prefix, and s becomes "bca". The number of partitions is now 1. +- Choose the longest prefix containing at most 2 distinct characters, "bca". +- Delete the prefix, and s becomes "a". The number of partitions is now 2. +- Choose the longest prefix containing at most 2 distinct characters, "a". +- Delete the prefix, and s becomes empty. The number of partitions is now 3. +Hence, the answer is 3. +It can be shown that it is not possible to obtain more than 3 partitions. + +``` + +**Example 2:** + +``` +Input: s = "aabaab", k = 3 +Output: 1 +Explanation: In this example, to maximize the number of resulting partitions we can leave s as it is. +The operations can now be performed as follows until s becomes empty: +- Choose the longest prefix containing at most 3 distinct characters, "aabaab". +- Delete the prefix, and s becomes empty. The number of partitions becomes 1. +Hence, the answer is 1. +It can be shown that it is not possible to obtain more than 1 partition. + +``` + +### Constraints + +- `1 <= s.length <= 10^4` +- `1 <= k <= 26` + +## Solution for Maximize the Number of Partitions After Operations + +### Intuition + +Considering the constraints a dynamic programming approach will work. + +A bitset can represent the presence or absence of each english letter, simplifying the process of tracking distinct characters in a given substring. With the help of bit manipulation such as bitwise OR operations, we can update the bitset efficiently as the algorithm iterates through the string. + +The DP function simulates the process of choosing prefixes and determining the resulting partitions. The function takes into account the current index in the string, the current set of distinct characters, and a flag indicating whether a character change is still allowed. The base case of the recursion is when the end of the string is reached. + +The logic within the DP function involves updating the set of distinct characters with the current character and evaluating whether the current partition violates the constraint. If the constraint is violated, the function explores the possibility of starting a new partition or considering the option to change a character at the current index. This consideration of character change is important in optimizing the number of partitions. The function explores all possible character changes when the option is available. + +### Approach + +1. Define a helper function `dp(index, current_set, can_change)` for dynamic programming, where: + + - index represents the current index in the string s. + - current_set is a bitmask to track the set of distinct characters encountered so far. + - can_change is a boolean indicating whether one index can be changed or not. + +2. If the index has reached the end of the string `(index == len(s))`, return 0 as no further partitions can be made. + +3. Calculate the index of the character at the current position `(character_index = ord(s[index]) - ord('a'))`. + +4. Update the current_set by adding the current character to it `(current_set_updated = current_set | (1 << character_index))`. + +5. Calculate the number of distinct characters in the updated set `(distinct_count = current_set_updated.bit_count())`. + +6. Check if the distinct count exceeds the limit k: + + - If yes, set result to 1 plus the result of the recursive call with the next index and a new set + containing only the current character. + - If no, set result to the result of the recursive call with the updated set and the next index. + - If can_change is True, explore the possibility of changing the current character: + +7. Iterate over all possible characters `(26 lowercase English letters)`. +8. Update the set with the new character `(new_set = current_set | (1 << new_character_index))`. +9. Calculate the distinct count for the new set. +10. If the distinct count exceeds `k`: + - Update result to the maximum of its current value and 1 plus the recursive call with the next + index and a new set containing only the new character. + - If not, update result to the maximum of its current value and the recursive call with the updated set and the next index. +11. Return the final result, which is the result of the initial call to the `dp` function with initial parameters (starting from the first character, an empty set, and the ability to change one index). + + + +### Solution Code + +#### Python + +```py +class Solution: + def maxPartitionsAfterOperations(self, s: str, k: int) -> int: + @cache + def dp(index, current_set, can_change): + if index == len(s): + return 0 + character_index = ord(s[index]) - ord('a') + + current_set_updated = current_set | (1 << character_index) + distinct_count = current_set_updated.bit_count() + + if distinct_count > k: + res = 1 + dp(index + 1, 1 << character_index, can_change) + else: + res = dp(index + 1, current_set_updated, can_change) + + if can_change: + for new_char_index in range(26): + new_set = current_set | (1 << new_char_index) + new_distinct_count = new_set.bit_count() + + if new_distinct_count > k: + res = max(res, 1 + dp(index + 1, 1 << new_char_index, False)) + else: + res = max(res, dp(index + 1, new_set, False)) + return res + + return dp(0, 0, True) + 1 + + +``` + +#### Java + +```java +class Solution { + private HashMap cache; + private String s; + private int k; + + public int maxPartitionsAfterOperations(String s, int k) { + this.cache = new HashMap<>(); + this.s = s; + this.k = k; + return dp(0, 0, true) + 1; + } + + private int dp(int index, int currentSet, boolean canChange) { + long key = ((long) index << 27) + | ((long) currentSet << 1) + | (canChange ? 1 : 0); + + if (cache.containsKey(key)) { + return cache.get(key); + } + + if (index == s.length()) { + return 0; + } + + int characterIndex = s.charAt(index) - 'a'; + int currentSetUpdated = currentSet | (1 << characterIndex); + int distinctCount = Integer.bitCount(currentSetUpdated); + + int res; + if (distinctCount > k) { + res = 1 + dp(index + 1, 1 << characterIndex, canChange); + } else { + res = dp(index + 1, currentSetUpdated, canChange); + } + + if (canChange) { + for (int newCharIndex = 0; newCharIndex < 26; newCharIndex++) { + int newSet = currentSet | (1 << newCharIndex); + int newDistinctCount = Integer.bitCount(newSet); + + if (newDistinctCount > k) { + res = Math.max(res, 1 + dp(index + 1, 1 << newCharIndex, false)); + } else { + res = Math.max(res, dp(index + 1, newSet, false)); + } + } + } + + cache.put(key, res); + return res; + } +} + +``` + +#### C++ + +```cpp +class Solution { +public: + unordered_map cache; + string s; + int k; + + int maxPartitionsAfterOperations(string s, int k) { + this->s = s; + this->k = k; + return dp(0, 0, true) + 1; + } + +private: + int dp(long long index, long long currentSet, bool canChange) { + long long key = (index << 27) | (currentSet << 1) | canChange; + + if (cache.count(key)) { + return cache[key]; + } + + if (index == s.size()) { + return 0; + } + + int characterIndex = s[index] - 'a'; + int currentSetUpdated = currentSet | (1 << characterIndex); + int distinctCount = __builtin_popcount(currentSetUpdated); + + int res; + if (distinctCount > k) { + res = 1 + dp(index + 1, 1 << characterIndex, canChange); + } else { + res = dp(index + 1, currentSetUpdated, canChange); + } + + if (canChange) { + for (int newCharIndex = 0; newCharIndex < 26; ++newCharIndex) { + int newSet = currentSet | (1 << newCharIndex); + int newDistinctCount = __builtin_popcount(newSet); + + if (newDistinctCount > k) { + res = max(res, 1 + dp(index + 1, 1 << newCharIndex, false)); + } else { + res = max(res, dp(index + 1, newSet, false)); + } + } + } + + return cache[key] = res; + } +}; +``` + +#### Complexity Analysis + +- Time complexity: $O(n*26)$, where n is the total number of elements in nums +- Space complexity:$O(n)$, where n is the total number of elements in nums diff --git a/solutions/lc-solutions/3000-3099/3005-count-elements-with-maximum-frequency.md b/solutions/lc-solutions/3000-3099/3005-count-elements-with-maximum-frequency.md new file mode 100644 index 0000000..1c8565e --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3005-count-elements-with-maximum-frequency.md @@ -0,0 +1,148 @@ +--- +id: count-elements-with-maximum-frequency +title: Count Elements With Maximum Frequency +sidebar_label: 3005 -Count Elements With Maximum Frequency +tags: + - Array + - Hash Table + - Counting +description: "This is a solution to the Count Elements With Maximum Frequency problem on LeetCode." +--- + +## Problem Description + +You are given an array nums consisting of positive integers. + +Return the total frequencies of elements in nums such that those elements all have the maximum frequency. + +The frequency of an element is the number of occurrences of that element in the array. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,2,3,1,4] +Output: 4 +Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array. +So the number of elements in the array with maximum frequency is 4. + +``` + +**Example 2:** + +``` +Input: nums = [1,2,3,4,5] +Output: 5 +Explanation: All elements of the array have a frequency of 1 which is the maximum. +So the number of elements in the array with maximum frequency is 5. + +``` + +### Constraints + +- `1 <= nums.length <= 100` +- `1 <= nums[i] <= 100` + +## Solution for Count Elements With Maximum Frequency + +### Intuition + +To solve this problem, we can use a HashMap to count the frequency of each element in the given array. Then, we iterate through the values of the HashMap to find the maximum frequency. Finally, we iterate through the values again to count the total number of elements with the maximum frequency. + +### Approach + +Initialize a vector freq of size 101 to store the frequency of each number. This assumes that the numbers in the input vector are in the range [0, 100]. + +Iterate through the input vector and update the frequency of each number in the freq vector. + +Initialize variables ans and temp to keep track of the maximum frequency and the current frequency, respectively. + +Iterate through the freq vector from index 1 to 100. + +If the frequency at the current index is equal to temp, add it to the answer (ans). + +If the frequency at the current index is greater than temp, update ans to be the current frequency and update temp. +Return the final answer. + +### Solution Code + +#### Python + +```py +class Solution: + def maxFrequencyElements(self, nums: List[int]) -> int: + di=defaultdict(int) + m,c=0,0 + for i in nums: + di[i]+=1 + if di[i]>m: + m=di[i] + c=0 + if di[i]==m: + c+=1 + return m*c + + +``` + +#### Java + +```java +class Solution { + public int maxFrequencyElements(int[] nums) { + HashMap map = new HashMap(); + int mf = 0, m = -1; + for (Integer c : nums) { + if (map.containsKey(c)) map.put(c, map.get(c) + 1); + else map.put(c, 1); + } + for(Integer t: map.values()){ + if(t>m){ + m = t; + mf = 1; + }else if(t==m) mf++; + } + return mf*m; + } +} + +``` + +#### C++ + +```cpp +class Solution +{ +public: + int maxFrequencyElements(vector &nums) + { + vector freq(101, 0); + + for (int i = 0; i < nums.size(); i++) + { + freq[nums[i]]++; + } + + int ans = 0; + int temp = 0; + + for (int i = 1; i < 101; i++) + { + if (freq[i] == temp) { + ans += freq[i]; + } else if (freq[i] > temp) { + ans = freq[i]; + temp = freq[i]; + } + } + + return ans; + } +}; +``` + +#### Complexity Analysis + +- Time complexity: $O(nlog(n))$, where n is the total number of elements in nums +- Space complexity:$O(nlog(n))$, where n is the total number of elements in nums diff --git a/solutions/lc-solutions/3000-3099/3006-find-beautiful-indices-in-the-given-array-i.md b/solutions/lc-solutions/3000-3099/3006-find-beautiful-indices-in-the-given-array-i.md new file mode 100644 index 0000000..36b3053 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3006-find-beautiful-indices-in-the-given-array-i.md @@ -0,0 +1,182 @@ +--- +id: find-beautiful-indices-in-the-given-array-i +title: Find Beautiful Indices in the Given Array I +sidebar_label: 3006 -Find Beautiful Indices in the Given Array I +tags: + - Two pointer + - String + - Binary Search + - Rolling Hash + - String Matching + - Hash Function +description: "This is a solution to the Find Beautiful Indices in the Given Array I problem on LeetCode." +--- + +## Problem Description + +You are given a 0-indexed string s, a string a, a string b, and an integer k. + +An index i is beautiful if: + +- $0 \leq i \leq \text{s.length} - \text{a.length}$ +- $s[i..(i + \text{a.length} - 1)] == a$ +- There exists an index j such that: +- $0 \leq j \leq \text{s.length} - \text{b.length}$ +- $s[j..(j + \text{b.length} - 1)] == b$ +- $|j - i| \leq k$ + Return the array that contains beautiful indices in sorted order from smallest to largest. + +### Examples + +**Example 1:** + +``` +Input: s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15 +Output: [16,33] +Explanation: There are 2 beautiful indices: [16,33]. +- The index 16 is beautiful as s[16..17] == "my" and there exists an index 4 with s[4..11] == "squirrel" and |16 - 4| <= 15. +- The index 33 is beautiful as s[33..34] == "my" and there exists an index 18 with s[18..25] == "squirrel" and |33 - 18| <= 15. +Thus we return [16,33] as the result. + +``` + +**Example 2:** + +``` +Input: s = "abcd", a = "a", b = "a", k = 4 +Output: [0] +Explanation: There is 1 beautiful index: [0]. +- The index 0 is beautiful as s[0..0] == "a" and there exists an index 0 with s[0..0] == "a" and |0 - 0| <= 4. +Thus we return [0] as the result. + +``` + +### Constraints + +- `1 <= k <= s.length <= 105` +- `1 <= a.length, b.length <= 10` + +## Solution For the Problem Find Beautiful Indices in the Given Array I + +### Intuition + +Basically the problem statement suggest that we need to find the index of string a matching in string s and then check if there is any index j which is matching with b in s and `abs(i - j) <= k`. +So to find the matching index need calculate the longest prefix which is suffix array ( LPS array ) and in that if the lps[i] matches with pattern string length then we found a match - KMP algo. +If you don't know KMP algo for pattern matching then first go through it then come back to solution. + +### Approach + +Get index of the matched pattern for the string a - lets call it v1 +Get index of the matched pattern for the string b - lets call it v2 +Check for possible combination of i & j in the v1 and v2. +to do so we need to check if the abs(i - j). If so then simple add it to answer. +If `v1[i] > v2[j]&& abs( i- j) > k` then keep moving pointer j till `v1[i] > v2[j]` +Check again if abs(i - j) or not. If it is less, then add it to ans + +### Solution Code + +#### Python + +```py + class Solution: + def beautifulIndices(self, s: str, a: str, b: str, k: int) -> List[int]: + f1=[] + i=0 + j=0 + while(i v){ + String t = a + "@" + s; + List lps = new ArrayList<>(); + lps.add(0); + for(int i = 1; i < t.length(); ++i){ + int ind = lps.get(i - 1); + while(ind > 0 && t.charAt(ind) != t.charAt(i)) { ind = lps.get(ind - 1); } + lps.add((t.charAt(ind) == t.charAt(i))?ind + 1 : 0); + } + for(int i = 0; i < lps.size(); ++i){ + if(lps.get(i) == a.length()) v.add(i - 2*a.length()); + } +} + +public List beautifulIndices(String s, String a, String b, int k) { + List ans = new ArrayList<>(); + List v1 = new ArrayList<>(); + List v2 = new ArrayList<>(); + getPatternMatchingIndex(s, a, v1); + getPatternMatchingIndex(s, b, v2); + for(int i = 0, j = 0; i < v1.size(); ++i){ + while(j < v2.size() && v1.get(i) > v2.get(j) && Math.abs(v1.get(i) - v2.get(j)) > k) j++; + if(j < v2.size() && Math.abs(v1.get(i) - v2.get(j)) <= k) ans.add(v1.get(i)); + } + return ans; +} + +``` + +#### C++ + +```cpp +void getPatternMatchingIndex(string& s, string& a, vector& v){ + string t = a + "@" + s; + vector lps(1, 0); + for(int i = 1; i < t.size(); ++i){ + int ind = lps[i-1]; + while(ind > 0 && t[ind] != t[i]) { ind = lps[ind-1]; } + lps.push_back((t[ind] == t[i])?ind + 1 : 0); + } + for(int i = 0; i < lps.size(); ++i){ + if(lps[i] == a.size()) v.push_back(i - 2*a.size()); + } +} + +vector beautifulIndices(string s, string a, string b, int k) { + vector ans, v1, v2; + getPatternMatchingIndex(s, a, v1); + getPatternMatchingIndex(s, b, v2); + for(int i = 0, j = 0; i < v1.size(); ++i){ + while(j < v2.size() && v1[i] > v2[j] && abs(v1[i] - v2[j]) > k) j++; + if(j < v2.size() && abs(v1[i] - v2[j]) <= k) ans.push_back(v1[i]); + } + return ans; +} +``` + +#### Complexity Analysis + +- Time complexity: $O(n)$, where n is the length of the string +- Space complexity: $O(n)$, where n is the length of the string diff --git a/solutions/lc-solutions/3000-3099/3010-divide-an-array-into-subarrays-with-minimum-cost-i.md b/solutions/lc-solutions/3000-3099/3010-divide-an-array-into-subarrays-with-minimum-cost-i.md new file mode 100644 index 0000000..724b7c5 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3010-divide-an-array-into-subarrays-with-minimum-cost-i.md @@ -0,0 +1,151 @@ +--- +id: divide-an-array-into-subarrays-with-minimum-cost-i +title: Divide an Array Into Subarrays With Minimum Cost I +sidebar_label: 3010 -Divide an Array Into Subarrays With Minimum Cost I +tags: + - Array + - Sorting + - Enumeration +description: "This is a solution to the Divide an Array Into Subarrays With Minimum Cost I problem on LeetCode." +--- + +## Problem Description + +You are given an array of integers nums of length n. + +The cost of an array is the value of its first element. For example, the cost of [1,2,3] is 1 while the cost of [3,4,1] is 3. + +You need to divide nums into 3 disjoint contiguous subarrays. + +Return the minimum possible sum of the cost of these subarrays. + +### Examples + +**Example 1:** + +``` +Input: nums = [1,2,3,12] +Output: 6 +Explanation: The best possible way to form 3 subarrays is: [1], [2], and [3,12] at a total cost of 1 + 2 + 3 = 6. +The other possible ways to form 3 subarrays are: +- [1], [2,3], and [12] at a total cost of 1 + 2 + 12 = 15. +- [1,2], [3], and [12] at a total cost of 1 + 3 + 12 = 16. + +``` + +**Example 2:** + +``` +Input: nums = [5,4,3] +Output: 12 +Explanation: The best possible way to form 3 subarrays is: [5], [4], and [3] at a total cost of 5 + 4 + 3 = 12. +It can be shown that 12 is the minimum cost achievable. + +``` + +**Example 3:** + +``` +Input: nums = [10,3,1,1] +Output: 12 +Explanation: The best possible way to form 3 subarrays is: [10,3], [1], and [1] at a total cost of 10 + 1 + 1 = 12. +It can be shown that 12 is the minimum cost achievable. + +``` + +### Constraints + +- `3 <= n <= 50` +- `1 <= nums[i] <= 50` + +## Solution For the Problem Divide an Array Into Subarrays With Minimum Cost I + +### Intuition + +cost = nums[0] + smallest + 2nd smallest + +Explanation +You have to divide array in 3 parts think of making 2 slice/cuts in array. No matter how you cut the array, first part of array will always come, cost of 1st part will be nums[0] and it will always be added. So nums[0]is fixed. +Now if you make other 2 cuts in the 'remaining array' at smallest element and 2nd smallest element then total cost will be: +cost = nums[0] + smallest ele + 2nd smallest ele + +example +[1 , 2 , 3 , 4 , 5 , 6 ,7 , 8] +1 is fixed +In remaining array smallest is 2 and next smallest is 3 +[1] +[2] +[3 , 4 , 5 , 6 ,7 , 8] + +### Approach + +Just iterate array from i=1 to end and find smallest and 2nd smallest elements and store them in a and b. + +return nums[0]+a+b. + +### Solution Code + +#### Python + +```py +class Solution(object): + def minimumCost(self, nums): + sum = nums[0] + nums = nums[1:] + nums.sort() + return sum + nums[0] + nums[1] + +``` + +#### Java + +```java + +class Solution { + public int minimumCost(int[] nums) { + int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE; + + for (int x = 1; x < nums.length; x++) { + int curr = nums[x]; + + if (curr < first) { + second = first; + first = curr; + continue; + } + if (curr < second) { + second = curr; + } + } + return nums[0] + first + second; + } +} + +``` + +#### C++ + +```cpp +class Solution { +public: + int minimumCost(vector& nums) { + int x = nums[0]; + int a = nums[1] ,b = nums[2]; + for(int i = 2;inums[i]){ + b = a; + a = nums[i]; + } + else if(b>nums[i]) b = nums[i]; + + } + return x+a+b; + } +}; +``` + +#### Complexity Analysis + +- Time complexity: $O(n)$ We only traverse through the array once + +- Space complexity: $O(1)$ Since we just have 2 pointers diff --git a/solutions/lc-solutions/3000-3099/3014-minimum-number-of-pushes-to-type-word-I.md b/solutions/lc-solutions/3000-3099/3014-minimum-number-of-pushes-to-type-word-I.md new file mode 100644 index 0000000..7ce6d95 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3014-minimum-number-of-pushes-to-type-word-I.md @@ -0,0 +1,232 @@ +--- +id: Minimum-Number-of-Pushes-to-Type-Word-I +title: Minimum Number of Pushes to Type Word I +sidebar_label: 3014 - Minimum Number of Pushes to Type Word I +tags: [greedy, mapping, string] +description: Find the minimum number of pushes needed to type a string word after remapping keys on a telephone keypad. +sidebar_position: 1 +--- + +## Problem Statement + +### Problem Description + +Given a string `word` containing distinct lowercase English letters, telephone keypads have keys mapped with distinct collections of lowercase English letters, which can be used to form words by pushing them. For example, the key 2 is mapped with ["a","b","c"], we need to push the key one time to type "a", two times to type "b", and three times to type "c". + +It is allowed to remap the keys numbered 2 to 9 to distinct collections of letters. The keys can be remapped to any amount of letters, but each letter must be mapped to exactly one key. You need to find the minimum number of times the keys will be pushed to type the string word. + +Return the minimum number of pushes needed to type `word` after remapping the keys. + +### Examples + +#### Example 1: + +Input: word = "abcde" +Output: 5 +Explanation: +The remapped keypad given in the image provides the minimum cost. +"a" -> one push on key 2 +"b" -> one push on key 3 +"c" -> one push on key 4 +"d" -> one push on key 5 +"e" -> one push on key 6 +Total cost is 1 + 1 + 1 + 1 + 1 = 5. +It can be shown that no other mapping can provide a lower cost. + +#### Example 2: + +Input: word = "xycdefghij" +Output: 12 +Explanation: +The remapped keypad given in the image provides the minimum cost. +"x" -> one push on key 2 +"y" -> two pushes on key 2 +"c" -> one push on key 3 +"d" -> two pushes on key 3 +"e" -> one push on key 4 +"f" -> one push on key 5 +"g" -> one push on key 6 +"h" -> one push on key 7 +"i" -> one push on key 8 +"j" -> one push on key 9 +Total cost is 1 + 2 + 1 + 2 + 1 + 1 + 1 + 1 + 1 + 1 = 12. +It can be shown that no other mapping can provide a lower cost. + +### Constraints + +1. `1 <= word.length <= 26` +2. `word` consists of lowercase English letters. +3. All letters in `word` are distinct. + +## Solution of Given Problem + +### Intuition and Approach + +To minimize the number of pushes, we should map the letters such that frequently used letters are mapped to the keys requiring fewer pushes. Since all letters in the `word` are distinct, we can simply sort the letters and map them sequentially to minimize the number of pushes. + +### Approaches + +We will solve this problem using a greedy approach. First, we sort the letters of the `word` to ensure that we map the most frequent letters to the keys with the least number of pushes. Then we compute the total number of pushes required. + +#### Codes in Different Languages + + + + + ```javascript + function minPushes(word) { + const keys = Array(9).fill().map(() => []); + const sortedWord = word.split('').sort(); + + let index = 0; + for (let i = 0; i < 9; i++) { + while (keys[i].length < 3 && index < sortedWord.length) { + keys[i].push(sortedWord[index++]); + } + } + + let totalPushes = 0; + for (let ch of word) { + for (let i = 0; i < 9; i++) { + if (keys[i].includes(ch)) { + totalPushes += keys[i].indexOf(ch) + 1; + break; + } + } + } + + return totalPushes; + } + + // Example usage: + console.log(minPushes("abcde")); // Output: 5 + console.log(minPushes("xycdefghij")); // Output: 12 + ``` + + + + + ```python + def min_pushes(word): + keys = [[] for _ in range(9)] + sorted_word = sorted(word) + + index = 0 + for i in range(9): + while len(keys[i]) < 3 and index < len(sorted_word): + keys[i].append(sorted_word[index]) + index += 1 + + total_pushes = 0 + for ch in word: + for i in range(9): + if ch in keys[i]: + total_pushes += keys[i].index(ch) + 1 + break + + return total_pushes + + # Example usage: + print(min_pushes("abcde")) # Output: 5 + print(min_pushes("xycdefghij")) # Output: 12 + ``` + + + + + ```java + import java.util.*; + + public class MinPushes { + public static int minPushes(String word) { + List> keys = new ArrayList<>(9); + for (int i = 0; i < 9; i++) { + keys.add(new ArrayList<>()); + } + + char[] sortedWord = word.toCharArray(); + Arrays.sort(sortedWord); + + int index = 0; + for (int i = 0; i < 9; i++) { + while (keys.get(i).size() < 3 && index < sortedWord.length) { + keys.get(i).add(sortedWord[index++]); + } + } + + int totalPushes = 0; + for (char ch : word.toCharArray()) { + for (int i = 0; i < 9; i++) { + if (keys.get(i).contains(ch)) { + totalPushes += keys.get(i).indexOf(ch) + 1; + break; + } + } + } + + return totalPushes; + } + + // Example usage: + public static void main(String[] args) { + System.out.println(minPushes("abcde")); // Output: 5 + System.out.println(minPushes("xycdefghij")); // Output: 12 + } + } + ``` + + + + + ```cpp + #include + #include + #include + + int minPushes(std::string word) { + std::vector> keys(9); + std::sort(word.begin(), word.end()); + + int index = 0; + for (int i = 0; i < 9; ++i) { + while (keys[i].size() < 3 && index < word.size()) { + keys[i].push_back(word[index++]); + } + } + + int totalPushes = 0; + for (char ch : word) { + for (int i = 0; i < 9; ++i) { + auto it = std::find(keys[i].begin(), keys[i].end(), ch); + if (it != keys[i].end()) { + totalPushes += std::distance(keys[i].begin(), it) + 1; + break; + } + } + } + + return totalPushes; + } + + // Example usage: + int main() { + std::cout << minPushes("abcde") << std::endl; // Output: 5 + std::cout << minPushes("xycdefghij") << std::endl; // Output: 12 + return 0; + } + ``` + + + + +### Complexity Analysis + +The time complexity of this solution is O(n log n) due to the sorting step, where `n` is the length of the word. The space complexity is O(1) as the additional space used is constant and does not depend on the input size. + +--- + +

Authors:

+ +
+ +
diff --git a/solutions/lc-solutions/3000-3099/3019-Number-of-Changing-Keys.md b/solutions/lc-solutions/3000-3099/3019-Number-of-Changing-Keys.md new file mode 100644 index 0000000..41e69bf --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3019-Number-of-Changing-Keys.md @@ -0,0 +1,113 @@ +--- +id: number-of-changing-keys +title: Number of Changing Keys (LeetCode) +sidebar_label: 3019-NumberOfChangingKeys +tags: + - String + - Simulation +description: Determine the number of times a user has to change the key when typing a given string. +sidebar_position: 3019 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Number of Changing Keys](https://leetcode.com/problems/number-of-changing-keys/) | [Number of Changing Keys Solution on LeetCode](https://leetcode.com/problems/number-of-changing-keys/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +You are given a 0-indexed string `s` typed by a user. Changing a key is defined as using a key different from the last used key. For example, `s = "ab"` has a change of a key while `s = "bBBb"` does not have any. + +Return the number of times the user had to change the key. + +Note: Modifiers like shift or caps lock won't be counted in changing the key that is if a user typed the letter 'a' and then the letter 'A' then it will not be considered as a changing of key. + +### Example 1 + +- **Input:** `s = "aAbBcC"` +- **Output:** `2` +- **Explanation:** + - From `s[0] = 'a'` to `s[1] = 'A'`, there is no change of key as caps lock or shift is not counted. + - From `s[1] = 'A'` to `s[2] = 'b'`, there is a change of key. + - From `s[2] = 'b'` to `s[3] = 'B'`, there is no change of key as caps lock or shift is not counted. + - From `s[3] = 'B'` to `s[4] = 'c'`, there is a change of key. + - From `s[4] = 'c'` to `s[5] = 'C'`, there is no change of key as caps lock or shift is not counted. + +### Example 2 + +- **Input:** `s = "AaAaAaaA"` +- **Output:** `0` +- **Explanation:** There is no change of key since only the letters 'a' and 'A' are pressed which does not require change of key. + +### Constraints + +- `1 <= s.length <= 100` +- `s` consists of only upper case and lower case English letters. + +## Approach + +To solve this problem, we need to traverse the string and count the number of times the current character is different from the previous character when case is ignored. Here are the steps: + +1. Initialize a counter to keep track of the number of key changes. +2. Traverse the string from the second character to the end. +3. For each character, compare it with the previous character (case insensitive). +4. If they are different, increment the counter. + +### Solution Code + +#### Python + +```python +class Solution: + def countKeyChanges(self, s: str) -> int: + count = 0 + for i in range(1, len(s)): + if s[i].lower() != s[i-1].lower(): + count += 1 + return count +``` + +#### C++ + +```c++ +#include +#include +using namespace std; + +class Solution { +public: + int countKeyChanges(string s) { + int count = 0; + for (int i = 1; i < s.length(); ++i) { + if (tolower(s[i]) != tolower(s[i-1])) { + count++; + } + } + return count; + } +}; + +``` + +#### Java + +```java +class Solution { + public int countKeyChanges(String s) { + int count = 0; + for (int i = 1; i < s.length(); ++i) { + if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(i-1))) { + count++; + } + } + return count; + } +} + +``` + +### Conclusion +The solutions traverse the string and count the number of times the key changes based on +case-insensitive character comparison. This ensures that the problem is solved in a straightforward +and efficient manner across different programming languages. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3021-Alice-and-Bob-Playing-Flower-Game.md b/solutions/lc-solutions/3000-3099/3021-Alice-and-Bob-Playing-Flower-Game.md new file mode 100644 index 0000000..11e2c27 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3021-Alice-and-Bob-Playing-Flower-Game.md @@ -0,0 +1,85 @@ +--- +id: alice-and-bob-playing-flower-game +title: Alice and Bob Playing Flower Game (LeetCode) +sidebar_label: 3021-AliceAndBobPlayingFlowerGame +tags: + - Game Theory + - Simulation +description: Compute the number of possible pairs (x, y) of flowers that satisfy the game conditions for Alice and Bob. +sidebar_position: 3021 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Alice and Bob Playing Flower Game](https://leetcode.com/problems/alice-and-bob-playing-flower-game/) | [Alice and Bob Playing Flower Game Solution on LeetCode](https://leetcode.com/problems/alice-and-bob-playing-flower-game/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +Alice and Bob are playing a turn-based game on a circular field surrounded by flowers. The circle represents the field, and there are `x` flowers in the clockwise direction between Alice and Bob, and `y` flowers in the anti-clockwise direction between them. + +The game proceeds as follows: + +- Alice takes the first turn. +- In each turn, a player must choose either the clockwise or anti-clockwise direction and pick one flower from that side. +- At the end of the turn, if there are no flowers left at all, the current player captures their opponent and wins the game. + +Given two integers, `x` and `y`, representing the number of flowers in the clockwise and anti-clockwise directions respectively, determine if Alice can win the game if both players play optimally. + +### Example 1 + +- **Input:** `x = 3`, `y = 5` +- **Output:** `true` +- **Explanation:** Alice can always choose the optimal direction to pick flowers and win the game. + +### Example 2 + +- **Input:** `x = 1`, `y = 1` +- **Output:** `false` +- **Explanation:** Since both players play optimally, Bob will always be the one to win in this case. + +### Constraints + +- `1 <= x, y <= 1000` + +## Approach + +To determine if Alice can win the game if both players play optimally, we need to consider the following: + +1. If either `x` or `y` is `0`, Alice wins by default since Bob cannot make a move. +2. If `x` and `y` are both greater than `0`, the game becomes a variant of the classic "Nim" game where the player to take the last flower wins. +3. The game's result can be determined using the principles of game theory, specifically the Grundy number for the game states. + +### Solution Code + +#### Python + +```python +class Solution: + def canAliceWin(self, n: int, m: int) -> bool: + return (n*m)//2 +``` + +#### C++ + +```c++ +long long flowerGame(int n, int m) { + return (long long)n * m / 2; +} +``` + +#### Java + +```java +class Solution { + public boolean canAliceWin(int x, int y) { + return (n*m)/2; + } +} +``` + +### Conclusion +The solutions use the properties of the XOR operation to determine if Alice can win the game. This +ensures that the problem is solved in a straightforward and efficient manner across different +programming languages. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3024-Type-of-Triangle.md b/solutions/lc-solutions/3000-3099/3024-Type-of-Triangle.md new file mode 100644 index 0000000..e273a3f --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3024-Type-of-Triangle.md @@ -0,0 +1,132 @@ +--- +id: type-of-triangle +title: Type of Triangle (LeetCode) +sidebar_label: 3024-TypeOfTriangle +tags: + - Triangle + - Array +description: Determine the type of triangle that can be formed by an array of integers representing the sides of the triangle. +sidebar_position: 3024 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Type of Triangle](https://leetcode.com/problems/type-of-triangle/) | [Type of Triangle Solution on LeetCode](https://leetcode.com/problems/type-of-triangle/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +You are given a 0-indexed integer array nums of size 3 which can form the sides of a triangle. + +A triangle is called equilateral if it has all sides of equal length. +A triangle is called isosceles if it has exactly two sides of equal length. +A triangle is called scalene if all its sides are of different lengths. +Return a string representing the type of triangle that can be formed or "none" if it cannot form a triangle. + +### Example 1 + +- **Input:** `nums = [3,3,3]` +- **Output:** `"equilateral"` +- **Explanation:** Since all the sides are of equal length, therefore, it will form an equilateral triangle. + +### Example 2 + +- **Input:** `nums = [3,4,5]` +- **Output:** `"scalene"` +- **Explanation:** + - `nums[0] + nums[1] = 3 + 4 = 7`, which is greater than `nums[2] = 5`. + - `nums[0] + nums[2] = 3 + 5 = 8`, which is greater than `nums[1] = 4`. + - `nums[1] + nums[2] = 4 + 5 = 9`, which is greater than `nums[0] = 3`. + Since the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle. + As all the sides are of different lengths, it will form a scalene triangle. + +### Constraints + +- `nums.length == 3` +- `1 <= nums[i] <= 100` + +## Approach + +To determine the type of triangle that can be formed by the given sides, we need to: + +1. Check if the given sides can form a valid triangle using the triangle inequality theorem. +2. If the sides form a valid triangle, check if the triangle is equilateral, isosceles, or scalene based on the lengths of the sides. + +### Solution Code + +#### Python + +```python +class Solution: + def triangleType(self, nums: List[int]) -> str: + a, b, c = sorted(nums) + + if a + b <= c: + return "none" + if a == b == c: + return "equilateral" + if a == b or b == c or a == c: + return "isosceles" + + return "scalene" +``` + +#### C++ +```c++ +#include +#include +#include +using namespace std; + +class Solution { +public: + string triangleType(vector& nums) { + sort(nums.begin(), nums.end()); + int a = nums[0], b = nums[1], c = nums[2]; + + if (a + b <= c) { + return "none"; + } + if (a == b && b == c) { + return "equilateral"; + } + if (a == b || b == c || a == c) { + return "isosceles"; + } + + return "scalene"; + } +}; + +``` + +#### Java +```java +import java.util.Arrays; + +class Solution { + public String triangleType(int[] nums) { + Arrays.sort(nums); + int a = nums[0], b = nums[1], c = nums[2]; + + if (a + b <= c) { + return "none"; + } + if (a == b && b == c) { + return "equilateral"; + } + if (a == b || b == c || a == c) { + return "isosceles"; + } + + return "scalene"; + } +} + +``` + +### Conclusion +The solutions use a simple sorting approach to determine the type of triangle that can be formed by +the given sides. This ensures that the problem is solved in a straightforward and efficient manner +across different programming languages. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3028-Ant-on-the-Boundary.md b/solutions/lc-solutions/3000-3099/3028-Ant-on-the-Boundary.md new file mode 100644 index 0000000..d4d00aa --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3028-Ant-on-the-Boundary.md @@ -0,0 +1,138 @@ +--- +id: ant-on-the-boundary +title: Ant on the Boundary (LeetCode) +sidebar_label: 3028-AntOnTheBoundary +tags: + - Array + - Simulation + - Boundary Conditions +description: Determine how many times an ant returns to the boundary after reading an array of non-zero integers and moving according to their values. +sidebar_position: 3028 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Ant on the Boundary](https://leetcode.com/problems/ant-on-the-boundary/) | [Ant on the Boundary Solution on LeetCode](https://leetcode.com/problems/ant-on-the-boundary/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +An ant is on a boundary. It sometimes goes left and sometimes right. + +You are given an array of non-zero integers `nums`. The ant starts reading `nums` from the first element of it to its end. At each step, it moves according to the value of the current element: + +- If `nums[i] < 0`, it moves left by `-nums[i]` units. +- If `nums[i] > 0`, it moves right by `nums[i]` units. + +Return the number of times the ant returns to the boundary. + +### Notes: +- There is infinite space on both sides of the boundary. +- We check whether the ant is on the boundary only after it has moved `|nums[i]|` units. In other words, if the ant crosses the boundary during its movement, it does not count. + +### Example 1 +- **Input:** `nums = [2,3,-5]` +- **Output:** `1` +- **Explanation:** + - After the first step, the ant is 2 steps to the right of the boundary. + - After the second step, the ant is 5 steps to the right of the boundary. + - After the third step, the ant is on the boundary. + - So the answer is 1. + +### Example 2 +- **Input:** `nums = [3,2,-3,-4]` +- **Output:** `0` +- **Explanation:** + - After the first step, the ant is 3 steps to the right of the boundary. + - After the second step, the ant is 5 steps to the right of the boundary. + - After the third step, the ant is 2 steps to the right of the boundary. + - After the fourth step, the ant is 2 steps to the left of the boundary. + - The ant never returned to the boundary, so the answer is 0. + +### Constraints +- `1 <= nums.length <= 100` +- `-10 <= nums[i] <= 10` +- `nums[i] != 0` + +## Approach + +To determine how many times the ant returns to the boundary, we can use a simple simulation approach. Here's the approach: + +1. Initialize a variable `position` to keep track of the ant's current position relative to the boundary. +2. Initialize a counter `boundary_count` to keep track of the number of times the ant returns to the boundary. +3. Iterate through each element in `nums`: + - Update the `position` based on the value of the current element. + - Check if the `position` is zero (i.e., the ant is back at the boundary). + - If the ant is back at the boundary, increment the `boundary_count`. +4. Return the `boundary_count`. + +### Solution Code + +#### Python + +```python +class Solution: + def returnToBoundaryCount(self, nums: List[int]) -> int: + position = 0 + boundary_count = 0 + + for num in nums: + position += num + if position == 0: + boundary_count += 1 + + return boundary_count +``` + +#### C++ +```c++ +#include +using namespace std; + +class Solution { +public: + int returnToBoundaryCount(vector& nums) { + int position = 0; + int boundary_count = 0; + + for (int num : nums) { + position += num; + if (position == 0) { + boundary_count += 1; + } + } + + return boundary_count; + } +}; + +``` + +#### Java +```java +class Solution { + public int returnToBoundaryCount(int[] nums) { + int position = 0; + int boundary_count = 0; + + for (int num : nums) { + position += num; + if (position == 0) { + boundary_count += 1; + } + } + + return boundary_count; + } +} + +``` + +### Conclusion +The problem of determining how many times an ant returns to the boundary can be effectively solved +using a straightforward simulation approach. By keeping track of the ant's position as it moves +according to the values in the array, and counting each time the position returns to zero, we can +determine the desired result. The provided solutions in Python, C++, and Java demonstrate this +approach, ensuring the solution is efficient and easy to understand across different programming +languages. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3030 - Find the Grid of Region Average.md b/solutions/lc-solutions/3000-3099/3030 - Find the Grid of Region Average.md new file mode 100644 index 0000000..c5a5773 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3030 - Find the Grid of Region Average.md @@ -0,0 +1,152 @@ +--- +id: find-the-grid-of-region-average +title: Find the Grid of Region Average +sidebar_label: Find the Grid of Region Average +tags: [Array, Matrix, Graph, BFS, DFS, Python, C++, Java] +description: Calculate the m x n grid result, where result[i][j] is the average intensity of the regions to which image[i][j] belongs, rounded down to the nearest integer. +--- + +## Problem Statement + +### Problem Description + +You are given an $m \times n$ grid `image` which represents a grayscale image, where `image[i][j]` represents a pixel with intensity in the range $[0, 255]$. You are also given a non-negative integer `threshold`. + +Two pixels are adjacent if they share an edge. + +A region is a $3 \times 3$ subgrid where the absolute difference in intensity between any two adjacent pixels is less than or equal to `threshold`. + +All pixels in a region belong to that region; note that a pixel can belong to multiple regions. + +You need to calculate an $m \times n$ grid `result`, where `result[i][j]` is the average intensity of the regions to which `image[i][j]` belongs, rounded down to the nearest integer. If `image[i][j]` belongs to multiple regions, `result[i][j]` is the average of the rounded-down average intensities of these regions, rounded down to the nearest integer. If `image[i][j]` does not belong to any region, `result[i][j]` is equal to `image[i][j]`. + +Return the grid `result`. + +### Examples + +**Example 1:** +``` +Input: image = [[5,6,7,10],[8,9,10,10],[11,12,13,10]], threshold = 3 +Output: [[9,9,9,9],[9,9,9,9],[9,9,9,9]] +``` +**Explanation:** + +There are two regions as illustrated above. The average intensity of the first region is 9, while the average intensity of the second region is 9.67 which is rounded down to 9. The average intensity of both of the regions is (9 + 9) / 2 = 9. As all the pixels belong to either region 1, region 2, or both of them, the intensity of every pixel in the result is 9. + + +### Constraints + +- $3 \leq n, m \leq 500$ +- $0 \leq image[i][j] \leq 255$ +- $0 \leq threshold \leq 255$ + +## Solution + +### Intuition + +To solve this problem, we need to identify all valid $3 \times 3$ regions, calculate their average intensities, and then determine the regions to which each pixel belongs. For each pixel, we then compute the required average intensity based on the regions it belongs to. + +### Time Complexity and Space Complexity Analysis + +- **Time Complexity**: $O(m \times n)$, where $m$ and $n$ are the dimensions of the grid. This complexity arises from the need to process each pixel and its regions. +- **Space Complexity**: $O(m \times n)$, required to store the resulting grid and any auxiliary data structures. + +### Code + +#### Python + +```python +def findRegionAverages(image, threshold): + m, n = len(image), len(image[0]) + result = [[image[i][j] for j in range(n)] for i in range(m)] + + def is_valid_region(i, j): + region = [] + for x in range(i, i+3): + for y in range(j, j+3): + region.append(image[x][y]) + for x in range(i, i+3): + for y in range(j, j+3): + if x > i and abs(image[x][y] - image[x-1][y]) > threshold: + return False + if y > j and abs(image[x][y] - image[x][y-1]) > threshold: + return False + return region + + for i in range(m-2): + for j in range(n-2): + region = is_valid_region(i, j) + if region: + avg = sum(region) // 9 + for x in range(i, i+3): + for y in range(j, j+3): + if result[x][y] == image[x][y]: + result[x][y] = avg + else: + result[x][y] = (result[x][y] + avg) // 2 + + return result +``` + +#### C++ +```cpp +#include +#include + +using namespace std; + +vector> findRegionAverages(vector>& image, int threshold) { + int m = image.size(); + int n = image[0].size(); + vector> result(m, vector(n, 0)); + + auto is_valid_region = [&](int i, int j) -> bool { + vector region; + for (int x = i; x < i + 3; ++x) { + for (int y = j; y < j + 3; ++y) { + region.push_back(image[x][y]); + } + } + for (int x = i; x < i + 3; ++x) { + for (int y = j; y < j + 3; ++y) { + if (x > i && abs(image[x][y] - image[x-1][y]) > threshold) { + return false; + } + if (y > j && abs(image[x][y] - image[x][y-1]) > threshold) { + return false; + } + } + } + return true; + }; + + for (int i = 0; i < m - 2; ++i) { + for (int j = 0; j < n - 2; ++j) { + if (is_valid_region(i, j)) { + int sum = 0; + for (int x = i; x < i + 3; ++x) { + for (int y = j; y < j + 3; ++y) { + sum += image[x][y]; + } + } + int avg = sum / 9; + for (int x = i; x < i + 3; ++x) { + for (int y = j; y < j + 3; ++y) { + result[x][y] = (result[x][y] == 0) ? avg : (result[x][y] + avg) / 2; + } + } + } + } + } + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (result[i][j] == 0) { + result[i][j] = image[i][j]; + } + } + } + + return result; +} +``` diff --git a/solutions/lc-solutions/3000-3099/3031 - Minimum Time to Revert Word to Initial State II.md b/solutions/lc-solutions/3000-3099/3031 - Minimum Time to Revert Word to Initial State II.md new file mode 100644 index 0000000..2e62a5d --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3031 - Minimum Time to Revert Word to Initial State II.md @@ -0,0 +1,113 @@ +--- +id: minimum-time-to-revert-word-to-initial-state-ii +title: Minimum Time to Revert Word to Initial State II +sidebar_label: Minimum Time to Revert Word to Initial State II +tags: [String, Simulation, C++, Python, Java] +description: Solve the problem of finding the minimum time required for a word to revert to its initial state after performing specific operations. +--- + +## Problem Statement + +### Problem Description + +You are given a 0-indexed string `word` and an integer `k`. + +At every second, you must perform the following operations: + +1. Remove the first `k` characters of `word`. +2. Add any `k` characters to the end of `word`. + +Note that you do not necessarily need to add the same characters that you removed. However, you must perform both operations at every second. + +Return the minimum time greater than zero required for `word` to revert to its initial state. + +### Examples + +**Example 1:** +``` +Input: word = "abacaba", k = 3 +Output: 2 +``` +**Explanation:** +- At the 1st second, we remove characters "aba" from the prefix of `word`, and add characters "bac" to the end of `word`. Thus, `word` becomes "cababac". +- At the 2nd second, we remove characters "cab" from the prefix of `word`, and add "aba" to the end of `word`. Thus, `word` becomes "abacaba" and reverts to its initial state. +- It can be shown that 2 seconds is the minimum time greater than zero required for `word` to revert to its initial state. + +**Example 2:** +``` +Input: word = "abacaba", k = 4 +Output: 1 +``` +**Explanation:** +- At the 1st second, we remove characters "abac" from the prefix of `word`, and add characters "caba" to the end of `word`. Thus, `word` becomes "abacaba" and reverts to its initial state. +- It can be shown that 1 second is the minimum time greater than zero required for `word` to revert to its initial state. + +### Constraints + +- $1 \leq \text{word.length} \leq 10^6$ +- $1 \leq k \leq \text{word.length}$ +- `word` consists only of lowercase English letters. + +## Solution + +### Intuition + +To find the minimum time required for the word to revert to its initial state, we can simulate the process of removing and adding characters. We aim to identify when the word returns to its original configuration after `k` characters have been shifted `n` times. + +### Time Complexity and Space Complexity Analysis + +- **Time Complexity**: The solution requires simulating the shifting process, which has a worst-case complexity of $O(n^2)$. This is because, in the worst-case scenario, we might need to simulate `n` shifts, each of which could involve comparing `n` characters. +- **Space Complexity**: The space complexity is $O(n)$, where `n` is the length of the string `word`. + +### Code + +#### C++ + +```cpp +class Solution { +public: + int minimumTimeToRevert(string word, int k) { + string original = word; + int n = word.size(); + for (int i = 1; i <= n; ++i) { + string prefix = word.substr(0, k); + word = word.substr(k) + prefix; + if (word == original) { + return i; + } + } + return n; // Default case, should never hit due to problem constraints + } +}; +``` + +#### Python +```python +class Solution: + def minimumTimeToRevert(self, word: str, k: int) -> int: + original = word + n = len(word) + for i in range(1, n + 1): + prefix = word[:k] + word = word[k:] + prefix + if word == original: + return i + return n # Default case, should never hit due to problem constraints +``` +#### Java +```java +class Solution { + public int minimumTimeToRevert(String word, int k) { + String original = word; + int n = word.length(); + for (int i = 1; i <= n; ++i) { + String prefix = word.substring(0, k); + word = word.substring(k) + prefix; + if (word.equals(original)) { + return i; + } + } + return n; // Default case, should never hit due to problem constraints + } +} +``` diff --git a/solutions/lc-solutions/3000-3099/3033-Modify-the-Matrix.md b/solutions/lc-solutions/3000-3099/3033-Modify-the-Matrix.md new file mode 100644 index 0000000..23d74d7 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3033-Modify-the-Matrix.md @@ -0,0 +1,138 @@ +--- +id: modify-the-matrix +title: Modify the Matrix (LeetCode) +sidebar_label: 3033-ModifyTheMatrix +tags: + - Matrix + - Array +description: Modify a matrix by replacing each element with the value -1 with the maximum element in its respective column. +sidebar_position: 3033 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Modify the Matrix](https://leetcode.com/problems/modify-the-matrix/) | [Modify the Matrix Solution on LeetCode](https://leetcode.com/problems/modify-the-matrix/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +Given a 0-indexed m x n integer matrix matrix, create a new 0-indexed matrix called answer. Make answer equal to matrix, then replace each element with the value -1 with the maximum element in its respective column. + +Return the matrix answer. + +### Example 1 + +- **Input:** `matrix = [[1,2,-1],[4,-1,6],[7,8,9]]` +- **Output:** `[[1,2,9],[4,8,6],[7,8,9]]` +- **Explanation:** The diagram above shows the elements that are changed (in blue). + - We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8. + - We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9. + +### Example 2 + +- **Input:** `matrix = [[3,-1],[5,2]]` +- **Output:** `[[3,2],[5,2]]` +- **Explanation:** The diagram above shows the elements that are changed (in blue). + +### Constraints + +- `m == matrix.length` +- `n == matrix[i].length` +- `2 <= m, n <= 50` +- `-1 <= matrix[i][j] <= 100` +- The input is generated such that each column contains at least one non-negative integer. + +## Approach + +To solve this problem, we need to replace each occurrence of `-1` in the matrix with the maximum value in its respective column. Here are the steps: + +1. Traverse each column of the matrix to find the maximum value. +2. Traverse the matrix again to replace each `-1` with the corresponding column maximum value. + +### Solution Code + +#### Python + +```python +class Solution: + def modifiedMatrix(self, matrix: List[List[int]]) -> List[List[int]]: + m, n = len(matrix), len(matrix[0]) + col_max = [max(matrix[i][j] for i in range(m) if matrix[i][j] != -1) for j in range(n)] + + for i in range(m): + for j in range(n): + if matrix[i][j] == -1: + matrix[i][j] = col_max[j] + + return matrix +``` + +#### C++ +```c++ +#include +#include +using namespace std; + +class Solution { +public: + vector> modifiedMatrix(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + vector colMax(n, INT_MIN); + + for (int j = 0; j < n; ++j) { + for (int i = 0; i < m; ++i) { + if (matrix[i][j] != -1) { + colMax[j] = max(colMax[j], matrix[i][j]); + } + } + } + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (matrix[i][j] == -1) { + matrix[i][j] = colMax[j]; + } + } + } + + return matrix; + } +}; + +``` + +#### Java +```java +class Solution { + public int[][] modifiedMatrix(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + int[] colMax = new int[n]; + Arrays.fill(colMax, Integer.MIN_VALUE); + + for (int j = 0; j < n; ++j) { + for (int i = 0; i < m; ++i) { + if (matrix[i][j] != -1) { + colMax[j] = Math.max(colMax[j], matrix[i][j]); + } + } + } + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (matrix[i][j] == -1) { + matrix[i][j] = colMax[j]; + } + } + } + + return matrix; + } +} + +``` + +### Conclusion +The solutions traverse the matrix twice to efficiently find the maximum values for each column and +then replace the -1 values. This approach ensures that the problem is solved in a straightforward +and efficient manner across different programming languages. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3034-Number-of-Subarrays-That-Match-a-Pattern-I.md b/solutions/lc-solutions/3000-3099/3034-Number-of-Subarrays-That-Match-a-Pattern-I.md new file mode 100644 index 0000000..97ec261 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3034-Number-of-Subarrays-That-Match-a-Pattern-I.md @@ -0,0 +1,147 @@ +--- +id: number-of-subarrays-that-match-a-pattern-i +title: Number of Subarrays That Match a Pattern I (LeetCode) +sidebar_label: 3034-NumberOfSubarraysThatMatchAPatternI +tags: + - Array + - Pattern + - Sliding Window +description: Count the number of subarrays in an integer array that match a given pattern. +sidebar_position: 3034 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Number of Subarrays That Match a Pattern I](https://leetcode.com/problems/number-of-subarrays-that-match-a-pattern-i/) | [Number of Subarrays That Match a Pattern I Solution on LeetCode](https://leetcode.com/problems/number-of-subarrays-that-match-a-pattern-i/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +You are given a 0-indexed integer array nums of size n, and a 0-indexed integer array pattern of size m consisting of integers -1, 0, and 1. + +A subarray nums[i..j] of size m + 1 is said to match the pattern if the following conditions hold for each element pattern[k]: + +- `nums[i + k + 1] > nums[i + k]` if `pattern[k] == 1`. +- `nums[i + k + 1] == nums[i + k]` if `pattern[k] == 0`. +- `nums[i + k + 1] < nums[i + k]` if `pattern[k] == -1`. + +Return the count of subarrays in nums that match the pattern. + +### Example 1 + +- **Input:** `nums = [1,2,3,4,5,6]`, `pattern = [1,1]` +- **Output:** `4` +- **Explanation:** The pattern `[1,1]` indicates that we are looking for strictly increasing subarrays of size 3. In the array `nums`, the subarrays `[1,2,3]`, `[2,3,4]`, `[3,4,5]`, and `[4,5,6]` match this pattern. + Hence, there are 4 subarrays in `nums` that match the pattern. + +### Example 2 + +- **Input:** `nums = [1,4,4,1,3,5,5,3]`, `pattern = [1,0,-1]` +- **Output:** `2` +- **Explanation:** Here, the pattern `[1,0,-1]` indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array `nums`, the subarrays `[1,4,4,1]`, and `[3,5,5,3]` match this pattern. + Hence, there are 2 subarrays in `nums` that match the pattern. + +### Constraints + +- `2 <= n == nums.length <= 100` +- `1 <= nums[i] <= 10^9` +- `1 <= m == pattern.length < n` +- `-1 <= pattern[i] <= 1` + +## Approach + +To solve this problem, we can use a sliding window approach to efficiently count the number of subarrays that match the given pattern. Here's the approach: + +1. Iterate through the array with a sliding window of size `m+1`. +2. For each window, check if the subarray matches the pattern. +3. Increment the count if the subarray matches the pattern. + +### Solution Code + +#### Python + +```python +class Solution: + def countMatchingSubarrays(self, nums: List[int], pattern: List[int]) -> int: + n, m = len(nums), len(pattern) + count = 0 + + for i in range(n - m): + match = True + for k in range(m): + if (pattern[k] == 1 and nums[i + k + 1] <= nums[i + k]) or \ + (pattern[k] == 0 and nums[i + k + 1] != nums[i + k]) or \ + (pattern[k] == -1 and nums[i + k + 1] >= nums[i + k]): + match = False + break + if match: + count += 1 + + return count +``` + +#### C++ + +```c++ +#include +using namespace std; + +class Solution { +public: + int countMatchingSubarrays(vector& nums, vector& pattern) { + int n = nums.size(), m = pattern.size(); + int count = 0; + + for (int i = 0; i <= n - m - 1; ++i) { + bool match = true; + for (int k = 0; k < m; ++k) { + if ((pattern[k] == 1 && nums[i + k + 1] <= nums[i + k]) || + (pattern[k] == 0 && nums[i + k + 1] != nums[i + k]) || + (pattern[k] == -1 && nums[i + k + 1] >= nums[i + k])) { + match = false; + break; + } + } + if (match) { + count++; + } + } + + return count; + } +}; +``` + +#### Java + +```java +class Solution { + public int countMatchingSubarrays(int[] nums, int[] pattern) { + int n = nums.length, m = pattern.length; + int count = 0; + + for (int i = 0; i <= n - m - 1; ++i) { + boolean match = true; + for (int k = 0; k < m; ++k) { + if ((pattern[k] == 1 && nums[i + k + 1] <= nums[i + k]) || + (pattern[k] == 0 && nums[i + k + 1] != nums[i + k]) || + (pattern[k] == -1 && nums[i + k + 1] >= nums[i + k])) { + match = false; + break; + } + } + if (match) { + count++; + } + } + + return count; + } +} +``` + +### Conclusion +The solutions use a sliding window approach to efficiently count the number of subarrays that match +the given pattern. This ensures an efficient and straightforward way to solve the problem across +different programming languages. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3035-Maximum-Palindromes-After-Operations.md b/solutions/lc-solutions/3000-3099/3035-Maximum-Palindromes-After-Operations.md new file mode 100644 index 0000000..a3b04f1 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3035-Maximum-Palindromes-After-Operations.md @@ -0,0 +1,151 @@ +--- +id: maximum-palindromes-after-operations +title: Maximum Palindromes After Operations (LeetCode) +sidebar_label: 3035-MaximumPalindromesAfterOperations +tags: + - Array + - String + - Greedy +description: Determine the maximum number of palindromes that can be formed from an array of strings after performing some operations. +sidebar_position: 3035 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Maximum Palindromes After Operations](https://leetcode.com/problems/maximum-palindromes-after-operations/) | [Maximum Palindromes After Operations Solution on LeetCode](https://leetcode.com/problems/maximum-palindromes-after-operations/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +- You are given a 0-indexed string array words having length n and containing 0-indexed strings. + +- You are allowed to perform the following operation any number of times (including zero): + +- Choose integers i, j, x, and y such that `0 <= i`, `j < n`, `0 <= x < words[i].length`, `0 <= y < words[j].length`, and swap the characters words[i][x] and words[j][y]. + +- Return an integer denoting the maximum number of palindromes words can contain, after performing some operations. + +- Note: i and j may be equal during an operation. + +### Example 1 + +- **Input:** `words = ["abbb","ba","aa"]` +- **Output:** `3` +- **Explanation:** In this example, one way to get the maximum number of palindromes is: + Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes ["bbbb","aa","aa"]. + All strings in words are now palindromes. + Hence, the maximum number of palindromes achievable is 3. + +### Example 2 + +- **Input:** `words = ["abc","ab"]` +- **Output:** `2` +- **Explanation:** In this example, one way to get the maximum number of palindromes is: + Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes ["aac","bb"]. + Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes ["aca","bb"]. + Both strings are now palindromes. + Hence, the maximum number of palindromes achievable is 2. + +### Example 3 + +- **Input:** `words = ["cd","ef","a"]` +- **Output:** `1` +- **Explanation:** In this example, there is no need to perform any operation. + There is one palindrome in words "a". + It can be shown that it is not possible to get more than one palindrome after any number of operations. + Hence, the answer is 1. + +### Constraints + +- `1 <= words.length <= 1000` +- `1 <= words[i].length <= 100` +- `words[i]` consists only of lowercase English letters. + +## Approach + +To solve this problem, we can use a greedy approach to determine the maximum number of palindromes that can be formed after performing some operations. Here's the approach: + +1. Identify characters that can be swapped to form palindromes. +2. Use a frequency map to count the occurrences of each character. +3. Calculate the maximum number of palindromes by ensuring each palindrome has at most one odd-frequency character. + +### Solution Code + +#### Python + +```python +from collections import Counter + +class Solution: + def maxPalindromesAfterOperations(self, words: List[str]) -> int: + char_count = Counter() + for word in words: + char_count.update(word) + + odd_count = sum(1 for count in char_count.values() if count % 2 != 0) + + return len(words) - odd_count // 2 +``` + +#### C++ + +```c++ +#include +#include +#include +using namespace std; + +class Solution { +public: + int maxPalindromesAfterOperations(vector& words) { + unordered_map char_count; + for (const string& word : words) { + for (char c : word) { + char_count[c]++; + } + } + + int odd_count = 0; + for (const auto& pair : char_count) { + if (pair.second % 2 != 0) { + odd_count++; + } + } + + return words.size() - odd_count / 2; + } +}; +``` + +#### Java + +```java +import java.util.HashMap; +import java.util.Map; + +class Solution { + public int maxPalindromesAfterOperations(String[] words) { + Map charCount = new HashMap<>(); + for (String word : words) { + for (char c : word.toCharArray()) { + charCount.put(c, charCount.getOrDefault(c, 0) + 1); + } + } + + int oddCount = 0; + for (int count : charCount.values()) { + if (count % 2 != 0) { + oddCount++; + } + } + + return words.length - oddCount / 2; + } +} +``` + +### Conclusion +The solutions use a greedy approach to determine the maximum number of palindromes that can be +formed by leveraging a frequency map to count character occurrences. This ensures an efficient and +straightforward way to solve the problem across different programming languages. diff --git a/solutions/lc-solutions/3000-3099/3038-Maximum-Number-of-Operations-With-the-Same-Scrore1.md b/solutions/lc-solutions/3000-3099/3038-Maximum-Number-of-Operations-With-the-Same-Scrore1.md new file mode 100644 index 0000000..2d231b7 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3038-Maximum-Number-of-Operations-With-the-Same-Scrore1.md @@ -0,0 +1,125 @@ +--- +id: maximum-number-of-operations-with-the-same-score-i +title: Maximum Number of Operations With the Same Score I (LeetCode) +sidebar_label: 3038-MaximumNumberOfOperationsWithTheSameScoreI +tags: + - Array + - Greedy +description: Find the maximum number of operations with the same score that can be performed on an array of integers. +sidebar_position: 3038 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Maximum Number of Operations With the Same Score I](https://leetcode.com/problems/maximum-number-of-operations-with-the-same-score-i/) | [Maximum Number of Operations With the Same Score I Solution on LeetCode](https://leetcode.com/problems/maximum-number-of-operations-with-the-same-score-i/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +Given an array of integers called nums, you can perform the following operation while nums contains at least 2 elements: + +Choose the first two elements of nums and delete them. +The score of the operation is the sum of the deleted elements. + +Your task is to find the maximum number of operations that can be performed, such that all operations have the same score. + +Return the maximum number of operations possible that satisfy the condition mentioned above. + +### Example 1 + +- **Input:** `nums = [3,2,1,4,5]` +- **Output:** `2` +- **Explanation:** We perform the following operations: + - Delete the first two elements, with score 3 + 2 = 5, nums = [1,4,5]. + - Delete the first two elements, with score 1 + 4 = 5, nums = [5]. + We are unable to perform any more operations as nums contain only 1 element. + +### Example 2 + +- **Input:** `nums = [3,2,6,1,4]` +- **Output:** `1` +- **Explanation:** We perform the following operations: + - Delete the first two elements, with score 3 + 2 = 5, nums = [6,1,4]. + We are unable to perform any more operations as the score of the next operation isn't the same as the previous one. + +### Constraints + +- `2 <= nums.length <= 100` +- `1 <= nums[i] <= 1000` + +## Approach + +To solve this problem, we can use a greedy approach to find the maximum number of operations with the same score. Here's the approach: + +1. Use a frequency map to count the sum of pairs of the first two elements. +2. Identify the most common pair sum that can be repeated the maximum number of times. + +### Solution Code + +#### Python + +```python +from collections import Counter + +class Solution: + def maxOperations(self, nums: List[int]) -> int: + if len(nums) < 2: + return 0 + + freq = Counter(nums[i] + nums[i+1] for i in range(0, len(nums)-1, 2)) + return freq.most_common(1)[0][1] if freq else 0 +``` + +#### Java +```java +import java.util.HashMap; + +class Solution { + public int maxOperations(int[] nums) { + if (nums.length < 2) return 0; + + HashMap freq = new HashMap<>(); + for (int i = 0; i < nums.length - 1; i += 2) { + int sum = nums[i] + nums[i+1]; + freq.put(sum, freq.getOrDefault(sum, 0) + 1); + } + + int max_operations = 0; + for (int count : freq.values()) { + max_operations = Math.max(max_operations, count); + } + return max_operations; + } +} +``` + +#### C++ +```c++ +#include +#include +using namespace std; + +class Solution { +public: + int maxOperations(vector& nums) { + if (nums.size() < 2) return 0; + + unordered_map freq; + for (int i = 0; i < nums.size() - 1; i += 2) { + freq[nums[i] + nums[i+1]]++; + } + + int max_operations = 0; + for (auto& pair : freq) { + max_operations = max(max_operations, pair.second); + } + return max_operations; + } +}; +``` + +### Conclusion +The solutions use a greedy approach to find the maximum number of operations with the same score by +leveraging a frequency map. This ensures an efficient and straightforward way to solve the problem +across different programming languages. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3040 - Maximum Number of Operations With the Same Score II.md b/solutions/lc-solutions/3000-3099/3040 - Maximum Number of Operations With the Same Score II.md new file mode 100644 index 0000000..4962eb7 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3040 - Maximum Number of Operations With the Same Score II.md @@ -0,0 +1,141 @@ +--- +id: maximum-number-of-operations-with-the-same-score-ii +title: Maximum Number of Operations With the Same Score II +sidebar_label: 3040 - Maximum Number of Operations With the Same Score II +tags: [Array, Greedy] +description: Find the maximum number of operations with the same score on an array of integers using specific deletion operations. +--- + +## Problem Statement + +### Problem Description + +Given an array of integers called `nums`, you can perform any of the following operations while `nums` contains at least 2 elements: + +1. Choose the first two elements of `nums` and delete them. +2. Choose the last two elements of `nums` and delete them. +3. Choose the first and the last elements of `nums` and delete them. + +The score of the operation is the sum of the deleted elements. + +Your task is to find the maximum number of operations that can be performed, such that all operations have the same score. + +Return the maximum number of operations possible that satisfy the condition mentioned above. + +### Example + +**Example 1:** +``` +Input: nums = [3,2,1,2,3,4] +Output: 3 +``` +**Explanation:** We perform the following operations: + +- Delete the first two elements, with score 3 + 2 = 5, nums = [1,2,3,4]. +- Delete the first and the last elements, with score 1 + 4 = 5, nums = [2,3]. +- Delete the first and the last elements, with score 2 + 3 = 5, nums = []. +- We are unable to perform any more operations as nums is empty. + + +### Constraints + +- 2 ≀ `nums.length` ≀ 2000 +- 1 ≀ `nums[i]` ≀ 1000 + +## Solution + +### Intuition + +To solve this problem, we need to identify how many operations can be performed with the same score. We can use the following approach: + +1. **Calculate Possible Scores:** Compute possible scores for each operation type (first two elements, last two elements, first and last elements). +2. **Count Operations for Each Score:** Use a dictionary to count the number of times each score can be achieved by applying each operation type. +3. **Find the Maximum Valid Score:** Determine the maximum count of operations where all operations yield the same score. + +### Time and Space Complexity + +- **Time Complexity:** The time complexity is $O(n)$, where $n$ is the length of `nums`. This includes calculating possible scores and counting their frequencies. + +- **Space Complexity:** The space complexity is $O(n)$ due to the use of a dictionary to store score counts. + +### Code + +#### C++ + +```cpp +class Solution { +public: + int maxOperations(vector& nums) { + int n = nums.size(); + unordered_map scoreCount; + + int maxOps = 0; + for (int i = 0; i < n / 2; ++i) { + int score1 = nums[i] + nums[i + 1]; + int score2 = nums[n - 1 - i] + nums[n - 2 - i]; + int score3 = nums[i] + nums[n - 1 - i]; + + scoreCount[score1]++; + scoreCount[score2]++; + scoreCount[score3]++; + + maxOps = max(maxOps, max({scoreCount[score1], scoreCount[score2], scoreCount[score3]})); + } + + return maxOps; + } +}; +``` + +#### Java +```java +import java.util.HashMap; +import java.util.Map; + +class Solution { + public int maxOperations(int[] nums) { + int n = nums.length; + Map scoreCount = new HashMap<>(); + + int maxOps = 0; + for (int i = 0; i < n / 2; ++i) { + int score1 = nums[i] + nums[i + 1]; + int score2 = nums[n - 1 - i] + nums[n - 2 - i]; + int score3 = nums[i] + nums[n - 1 - i]; + + scoreCount.put(score1, scoreCount.getOrDefault(score1, 0) + 1); + scoreCount.put(score2, scoreCount.getOrDefault(score2, 0) + 1); + scoreCount.put(score3, scoreCount.getOrDefault(score3, 0) + 1); + + maxOps = Math.max(maxOps, Math.max(scoreCount.get(score1), Math.max(scoreCount.get(score2), scoreCount.get(score3)))); + } + + return maxOps; + } +} +``` + +#### Python +```python +class Solution: + def maxOperations(self, nums: List[int]) -> int: + from collections import defaultdict + + n = len(nums) + score_count = defaultdict(int) + + max_ops = 0 + for i in range(n // 2): + score1 = nums[i] + nums[i + 1] + score2 = nums[n - 1 - i] + nums[n - 2 - i] + score3 = nums[i] + nums[n - 1 - i] + + score_count[score1] += 1 + score_count[score2] += 1 + score_count[score3] += 1 + + max_ops = max(max_ops, score_count[score1], score_count[score2], score_count[score3]) + + return max_ops +``` + diff --git a/solutions/lc-solutions/3000-3099/3042-Count-Prefix-and-Suffix-Pairs-I.md b/solutions/lc-solutions/3000-3099/3042-Count-Prefix-and-Suffix-Pairs-I.md new file mode 100644 index 0000000..4fda0ad --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3042-Count-Prefix-and-Suffix-Pairs-I.md @@ -0,0 +1,136 @@ +--- +id: count-prefix-and-suffix-pairs +title: Count Prefix and Suffix Pairs (LeetCode) +sidebar_label: 3042-CountPrefixAndSuffixPairs +tags: + - String + - Prefix + - Suffix + - Pair Counting +description: Count pairs of indices where one string is both a prefix and suffix of another string. +sidebar_position: 3042 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Count Prefix and Suffix Pairs](https://leetcode.com/problems/count-prefix-and-suffix-pairs/) | [Count Prefix and Suffix Pairs Solution on LeetCode](https://leetcode.com/problems/count-prefix-and-suffix-pairs/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +You are given a 0-indexed string array `words`. + +Let's define a boolean function `isPrefixAndSuffix` that takes two strings, `str1` and `str2`: + +- `isPrefixAndSuffix(str1, str2)` returns `true` if `str1` is both a prefix and a suffix of `str2`, and `false` otherwise. + +For example, `isPrefixAndSuffix("aba", "ababa")` is `true` because "aba" is a prefix of "ababa" and also a suffix, but `isPrefixAndSuffix("abc", "abcd")` is `false`. + +Return an integer denoting the number of index pairs `(i, j)` such that `i < j`, and `isPrefixAndSuffix(words[i], words[j])` is `true`. + +### Example 1 + +- **Input:** `words = ["a","aba","ababa","aa"]` +- **Output:** `4` +- **Explanation:** In this example, the counted index pairs are: + - `i = 0` and `j = 1` because `isPrefixAndSuffix("a", "aba")` is `true`. + - `i = 0` and `j = 2` because `isPrefixAndSuffix("a", "ababa")` is `true`. + - `i = 0` and `j = 3` because `isPrefixAndSuffix("a", "aa")` is `true`. + - `i = 1` and `j = 2` because `isPrefixAndSuffix("aba", "ababa")` is `true`. + +### Example 2 + +- **Input:** `words = ["pa","papa","ma","mama"]` +- **Output:** `2` +- **Explanation:** In this example, the counted index pairs are: + - `i = 0` and `j = 1` because `isPrefixAndSuffix("pa", "papa")` is `true`. + - `i = 2` and `j = 3` because `isPrefixAndSuffix("ma", "mama")` is `true`. + +### Example 3 + +- **Input:** `words = ["abab","ab"]` +- **Output:** `0` +- **Explanation:** In this example, the only valid index pair is `i = 0` and `j = 1`, and `isPrefixAndSuffix("abab", "ab")` is `false`. + +### Constraints + +- `1 <= words.length <= 50` +- `1 <= words[i].length <= 10` +- `words[i]` consists only of lowercase English letters. + +## Approach + +To solve this problem, we need to check for each pair `(i, j)` if `words[i]` is both a prefix and a suffix of `words[j]`. We can do this by iterating over all pairs and checking the conditions for each pair. + +### Solution Code + +#### Python + +```python +class Solution: + def isPrefixAndSuffix(self, str1, str2): + return str2.startswith(str1) and str2.endswith(str1) + + def countPrefixAndSuffixPairs(self, words): + count = 0 + for i in range(len(words)): + for j in range(i + 1, len(words)): + if self.isPrefixAndSuffix(words[i], words[j]): + count += 1 + return count +``` + +#### C++ +```c++ +#include +#include +using namespace std; + +class Solution { +public: + bool isPrefixAndSuffix(const string& str1, const string& str2) { + return str2.compare(0, str1.size(), str1) == 0 && str2.compare(str2.size() - str1.size(), str1.size(), str1) == 0; + } + + int countPrefixAndSuffixPairs(vector& words) { + int count = 0; + for (int i = 0; i < words.size(); i++) { + for (int j = i + 1; j < words.size(); j++) { + if (isPrefixAndSuffix(words[i], words[j])) { + count++; + } + } + } + return count; + } +}; + +``` + +#### Java +```java +class Solution { + private boolean isPrefixAndSuffix(String str1, String str2) { + return str2.startsWith(str1) && str2.endsWith(str1); + } + + public int countPrefixAndSuffixPairs(String[] words) { + int count = 0; + for (int i = 0; i < words.length; i++) { + for (int j = i + 1; j < words.length; j++) { + if (isPrefixAndSuffix(words[i], words[j])) { + count++; + } + } + } + return count; + } +} + +``` + +### Conclusion +The above solutions iterate over all pairs of strings in the input list and check if the first +string in the pair is both a prefix and a suffix of the second string. The count of such valid pairs +is returned as the result. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3046-Split-the-Array.md b/solutions/lc-solutions/3000-3099/3046-Split-the-Array.md new file mode 100644 index 0000000..8fc9289 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3046-Split-the-Array.md @@ -0,0 +1,134 @@ +--- +id: split-the-array +title: Split the Array (LeetCode) +sidebar_label: 3046-SplitTheArray +tags: + - Array + - Sorting + - Greedy +description: Determine if it's possible to split an array into two parts with distinct elements. +sidebar_position: 3046 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Split the Array](https://leetcode.com/problems/split-the-array/) | [Split the Array Solution on LeetCode](https://leetcode.com/problems/split-the-array/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +You are given an integer array `nums` of even length. You have to split the array into two parts `nums1` and `nums2` such that: + +- `nums1.length == nums2.length == nums.length / 2`. +- `nums1` should contain distinct elements. +- `nums2` should also contain distinct elements. + +Return `true` if it is possible to split the array, and `false` otherwise. + +### Example 1 + +- **Input:** `nums = [1,1,2,2,3,4]` +- **Output:** `true` +- **Explanation:** One of the possible ways to split `nums` is `nums1 = [1,2,3]` and `nums2 = [1,2,4]`. + +### Example 2 + +- **Input:** `nums = [1,1,1,1]` +- **Output:** `false` +- **Explanation:** The only possible way to split `nums` is `nums1 = [1,1]` and `nums2 = [1,1]`. Both `nums1` and `nums2` do not contain distinct elements. Therefore, we return `false`. + +### Constraints + +- `1 <= nums.length <= 100` +- `nums.length % 2 == 0` +- `1 <= nums[i] <= 100` + +## Approach + +To determine if it is possible to split the array into two parts where each part contains distinct elements, we can use the following approach: + +1. **Count Frequencies**: + - Use a dictionary or array to count the frequency of each element in the input array. + +2. **Check Feasibility**: + - If any element appears more than `nums.length / 2` times, it is impossible to split the array as required. + - Otherwise, we can always split the array by distributing the elements between `nums1` and `nums2`. + +### Solution Code + +#### Python + +```python +from collections import Counter + +class Solution: + def splitArray(self, nums): + n = len(nums) // 2 + freq = Counter(nums) + + for count in freq.values(): + if count > n: + return False + + return True +``` + +#### C++ +```c++ +#include +#include +using namespace std; + +class Solution { +public: + bool splitArray(vector& nums) { + int n = nums.size() / 2; + unordered_map freq; + + for (int num : nums) { + freq[num]++; + } + + for (const auto& [num, count] : freq) { + if (count > n) { + return false; + } + } + + return true; + } +}; + +``` + +#### Java +```java +import java.util.HashMap; +import java.util.Map; + +class Solution { + public boolean splitArray(int[] nums) { + int n = nums.length / 2; + Map freq = new HashMap<>(); + + for (int num : nums) { + freq.put(num, freq.getOrDefault(num, 0) + 1); + } + + for (int count : freq.values()) { + if (count > n) { + return false; + } + } + + return true; + } +} + +``` + +### Conclusion +The provided solutions use a frequency counter to determine if any element appears more than `nums. +length / 2 times`. If such an element exists, it is impossible to split the array into two parts +with distinct elements. Otherwise, it is always possible to perform the split as required. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3069-distribute-elements-into-two-arrays-I.md b/solutions/lc-solutions/3000-3099/3069-distribute-elements-into-two-arrays-I.md new file mode 100644 index 0000000..df3e062 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3069-distribute-elements-into-two-arrays-I.md @@ -0,0 +1,163 @@ +--- +id: distribute-elements-into-two-arrays-I +title: Distribute Elements Into Two Arrays I +sidebar_label: 3069-Distribute Elements Into Two Arrays I +tags: + - Array + - simulation + +description: "This is a solution to the Distribute Elements Into Two Arrays I in leetcode" +--- + +## Problem Description + +You are given a 1-indexed array of distinct integers nums of length n. + +You need to distribute all the elements of nums between two arrays arr1 and arr2 using n operations. In the first operation, append nums[1] to arr1. In the second operation, append nums[2] to arr2. Afterwards, in the ith operation: + +If the last element of arr1 is greater than the last element of arr2, append nums[i] to arr1. Otherwise, append nums[i] to arr2. +The array result is formed by concatenating the arrays arr1 and arr2. For example, if arr1 == [1,2,3] and arr2 == [4,5,6], then result = [1,2,3,4,5,6]. + +Return the array result. + + + + +### Examples + +**Example 1:** + +``` +Input: nums = [2,1,3] +Output: [2,3,1] +Explanation: After the first 2 operations, arr1 = [2] and arr2 = [1]. +In the 3rd operation, as the last element of arr1 is greater than the last element of arr2 (2 > 1), append nums[3] to arr1. +After 3 operations, arr1 = [2,3] and arr2 = [1]. +Hence, the array result formed by concatenation is [2,3,1]. + +``` +**Example 2:** +``` +Input: nums = [5,4,3,8] +Output: [5,3,4,8] +Explanation: After the first 2 operations, arr1 = [5] and arr2 = [4]. +In the 3rd operation, as the last element of arr1 is greater than the last element of arr2 (5 > 4), append nums[3] to arr1, hence arr1 becomes [5,3]. +In the 4th operation, as the last element of arr2 is greater than the last element of arr1 (4 > 3), append nums[4] to arr2, hence arr2 becomes [4,8]. +After 4 operations, arr1 = [5,3] and arr2 = [4,8]. +Hence, the array result formed by concatenation is [5,3,4,8]. + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(n)$ + +*** Space Complexity:** $O(n)$ + +### Constraints + +- `3 <= n <= 50` +- `1 <= nums[i] <= 100` +- All elements in `nums` are distinct. + + + +### Solution +## Approach +The approach involves creating two lists, arr1 and arr2, to segregate the elements from the input list nums based on a comparison of the last elements in arr1 and arr2. Initially, the first two elements of nums are added to arr1 and arr2 respectively. For each subsequent element in nums, the algorithm compares the last element of arr1 with the last element of arr2. If the element in arr1 is greater, the current element is appended to arr1; otherwise, it is appended to arr2. After processing all elements, the two lists are concatenated, with arr2 being appended to the end of arr1. This approach ensures that the final list contains elements from arr1 followed by elements from arr2, based on the specified condition. + +## Code in Different Languages + + + + + +```cpp + +class Solution { +public: + vector resultArray(vector& nums) { + vector arr1; + vector arr2; + + if (nums.empty()) return arr1; + + arr1.push_back(nums[0]); + if (nums.size() > 1) { + arr2.push_back(nums[1]); + } + + for (size_t i = 2; i < nums.size(); ++i) { + if (arr1.back() > arr2.back()) { + arr1.push_back(nums[i]); + } else { + arr2.push_back(nums[i]); + } + } + + arr1.insert(arr1.end(), arr2.begin(), arr2.end()); + return arr1; + } +}; + + +``` + + + + +```java + +class Solution { + public List resultArray(List nums) { + List arr1 = new ArrayList<>(); + List arr2 = new ArrayList<>(); + + if (nums.isEmpty()) return arr1; // Return empty if input is empty + + arr1.add(nums.get(0)); + if (nums.size() > 1) { + arr2.add(nums.get(1)); + } + + for (int i = 2; i < nums.size(); i++) { + if (arr1.get(arr1.size() - 1) > arr2.get(arr2.size() - 1)) { + arr1.add(nums.get(i)); + } else { + arr2.add(nums.get(i)); + } + } + + arr1.addAll(arr2); + return arr1; + } +} + + +``` + + + + +```python +class Solution: + def resultArray(self, nums: List[int]) -> List[int]: + arr1=[] + arr2=[] + arr1.append(nums[0]) + arr2.append(nums[1]) + for i in range(2,len(nums)): + if arr1[-1]>arr2[-1]: + arr1.append(nums[i]) + else: + arr2.append(nums[i]) + return arr1+arr2 + +``` + + + +## References + +- **LeetCode Problem**: [Distribute Elements Into Two Arrays I](https://leetcode.com/problems/distribute-elements-into-two-arrays-i/description/) + +- **Solution Link**: [Distribute Elements Into Two Arrays I](https://leetcode.com/problems/distribute-elements-into-two-arrays-i/post-solution/?submissionId=1192661489) diff --git a/solutions/lc-solutions/3000-3099/3074-Apple-Redistribution-into-Boxes.md b/solutions/lc-solutions/3000-3099/3074-Apple-Redistribution-into-Boxes.md new file mode 100644 index 0000000..7ac89fc --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3074-Apple-Redistribution-into-Boxes.md @@ -0,0 +1,136 @@ +--- +id: apple-redistribution-into-boxes +title: Apple Redistribution into Boxes (LeetCode) +sidebar_label: 3074-AppleRedistributionIntoBoxes +tags: + - Array + - Greedy +description: Calculate the minimum number of boxes needed to redistribute packs of apples into boxes. +sidebar_position: 3074 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Apple Redistribution into Boxes](https://leetcode.com/problems/apple-redistribution-into-boxes/) | [Apple Redistribution into Boxes Solution on LeetCode](https://leetcode.com/problems/apple-redistribution-into-boxes/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +You are given an array `apple` of size `n` and an array `capacity` of size `m`. + +There are `n` packs where the `i-th` pack contains `apple[i]` apples. There are `m` boxes as well, and the `i-th` box has a capacity of `capacity[i]` apples. + +Return the minimum number of boxes you need to select to redistribute these `n` packs of apples into boxes. + +Note that apples from the same pack can be distributed into different boxes. + +### Example 1 + +- **Input:** `apple = [1,3,2]`, `capacity = [4,3,1,5,2]` +- **Output:** `2` +- **Explanation:** We will use boxes with capacities `4` and `5`. It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples. + +### Example 2 + +- **Input:** `apple = [5,5,5]`, `capacity = [2,4,2,7]` +- **Output:** `4` +- **Explanation:** We will need to use all the boxes. + +### Constraints + +- `1 <= n == apple.length <= 50` +- `1 <= m == capacity.length <= 50` +- `1 <= apple[i], capacity[i] <= 50` +- The input is generated such that it's possible to redistribute packs of apples into boxes. + +## Approach + +To solve this problem, follow these steps: + +1. Calculate the total number of apples. +2. Sort the `capacity` array in descending order. +3. Select boxes starting from the largest capacity until the total capacity of selected boxes is greater than or equal to the total number of apples. +4. Return the number of boxes selected. + +### Solution Code + +#### Python + +```python +class Solution: + def minBoxes(self, apple: List[int], capacity: List[int]) -> int: + total_apples = sum(apple) + capacity.sort(reverse=True) + + current_capacity = 0 + box_count = 0 + + for cap in capacity: + current_capacity += cap + box_count += 1 + if current_capacity >= total_apples: + break + + return box_count +``` + +#### C++ +```c++ +#include +#include +using namespace std; + +class Solution { +public: + int minBoxes(vector& apple, vector& capacity) { + int total_apples = accumulate(apple.begin(), apple.end(), 0); + sort(capacity.rbegin(), capacity.rend()); + + int current_capacity = 0; + int box_count = 0; + + for (int cap : capacity) { + current_capacity += cap; + box_count++; + if (current_capacity >= total_apples) { + break; + } + } + + return box_count; + } +}; + +``` + +#### Java +```java +import java.util.Arrays; + +class Solution { + public int minBoxes(int[] apple, int[] capacity) { + int totalApples = Arrays.stream(apple).sum(); + Arrays.sort(capacity); + + int currentCapacity = 0; + int boxCount = 0; + + for (int i = capacity.length - 1; i >= 0; i--) { + currentCapacity += capacity[i]; + boxCount++; + if (currentCapacity >= totalApples) { + break; + } + } + + return boxCount; + } +} + +``` + +### Conclusion +The solutions provided demonstrate how to calculate the minimum number of boxes needed to +redistribute packs of apples into boxes using a greedy algorithm. By selecting boxes with the +largest capacities first, we can minimize the number of boxes required efficiently. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3075-maximize-happiness-of-selected-children.md b/solutions/lc-solutions/3000-3099/3075-maximize-happiness-of-selected-children.md new file mode 100644 index 0000000..d2b57f9 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3075-maximize-happiness-of-selected-children.md @@ -0,0 +1,153 @@ +--- + +id: maximize happiness of selected children +title: Maximize Happiness of Selected Children +sidebar_label: 3075-maximize happiness of selected children +tags: +- Array +- Greedy +- Sorting +- Java +- Cpp +- Python +description: "Given an array of happiness values, return the maximum sum of happiness values by selecting k children." +--- + +## Problem Description + +You are given an array happiness of length n, and a positive integer k. + +There are n children standing in a queue, where the i-th child has a happiness value happiness[i]. You want to select k children from these n children in k turns. + +In each turn, when you select a child, the happiness value of all the children that have not been selected till now decreases by 1. Note that the happiness value cannot become negative and gets decremented only if it is positive. + +Return the maximum sum of the happiness values of the selected children you can achieve by selecting k children. + +### Examples + +**Example 1:** +``` +Input: happiness = [1, 2, 3], k = 2 +Output: 4 +Explanation: +We can pick 2 children in the following way: +- Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0, 1]. +- Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0. +The sum of the happiness values of the selected children is 3 + 1 = 4. +``` + +**Example 2:** +``` +Input: happiness = [1, 1, 1, 1], k = 2 +Output: 1 +Explanation: +We can pick 2 children in the following way: +- Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0, 0, 0]. +- Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0, 0]. +The sum of the happiness values of the selected children is 1 + 0 = 1. +``` +**Example 3:** + +``` +Input: happiness = [2, 3, 4, 5], k = 1 +Output: 5 +Explanation: +We can pick 1 child in the following way: +- Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1, 2, 3]. +The sum of the happiness values of the selected children is 5. +``` + +### Constraints + +- `1 <= n == happiness.length <= 200,000` +- `1 <= happiness[i] <= 100,000,000` +- `1 <= k <= n` + + +## Approach + +To maximize the sum of happiness values of the selected children, we need to adopt a greedy approach by selecting the children with the highest current happiness values first. Each time a child is selected, the happiness values of the remaining children will decrease by 1, but they cannot go below 0. Sorting the array helps us efficiently pick the highest values while considering the decrement effect. + +### Steps: + +1. **Sort the Array:** Sort the array in ascending order so that the highest values can be accessed from the end. +2. **Iterate and Select Children:** Initialize a variable `ans` to store the sum of selected happiness values. Iterate `k` times, selecting the highest available happiness value and considering the decrement effect on remaining children. +3. **Sum the Values:** For each selection, add the current maximum value (adjusted for the decrements) to `ans`. +4. **Break Condition:** If the adjusted happiness value of the current selection is non-positive, break out of the loop as selecting further would not contribute to the sum. + +## Solution + +#### Java Solution + +```java +import java.util.Arrays; + +class Solution { + public long maximumHappinessSum(int[] happiness, int k) { + long ans = 0; + Arrays.sort(happiness); // Step 1: Sort the array + for (int i = 0; i < k; i++) { + int currentHappiness = happiness[happiness.length - 1 - i] - i; // Step 2: Adjust for decrement + if (currentHappiness > 0) { + ans += currentHappiness; // Step 3: Add to the answer + } else { + break; // Step 4: Break if no positive happiness value + } + } + return ans; + } +} +``` + +#### C++ Solution + +```cpp +class Solution { +public: + long long maximumHappinessSum(vector& happiness, int k) { + long long ans = 0; + std::sort(happiness.begin(), happiness.end()); // Step 1: Sort the array + for (int i = 0; i < k; i++) { + int currentHappiness = happiness[happiness.size() - 1 - i] - i; // Step 2: Adjust for decrement + if (currentHappiness > 0) { + ans += currentHappiness; // Step 3: Add to the answer + } else { + break; // Step 4: Break if no positive happiness value + } + } + return ans; + } +}; +``` + +#### Python Solution + +```python +class Solution(object): + def maximumHappinessSum(self, happiness, k): + """ + :type happiness: List[int] + :type k: int + :rtype: int + """ + happiness.sort() # Step 1: Sort the array + ans = 0 + for i in range(k): + current_happiness = happiness[-1 - i] - i # Step 2: Adjust for decrement + if current_happiness > 0: + ans += current_happiness # Step 3: Add to the answer + else: + break # Step 4: Break if no positive happiness value + return ans +``` + +### Complexity Analysis + +**Time Complexity:** O(n log n) +> Sorting the array takes O(n log n) time, and iterating over the array to calculate the sum of happiness values takes O(k), which is dominated by the sorting step. + +**Space Complexity:** O(1) +> The algorithm uses a constant amount of extra space beyond the input array. + +### References +**LeetCode Problem:** Maximize Happiness of Selected Children diff --git a/solutions/lc-solutions/3000-3099/3079-Find-the-Sum-of-Encrypted-Integers.md b/solutions/lc-solutions/3000-3099/3079-Find-the-Sum-of-Encrypted-Integers.md new file mode 100644 index 0000000..2e6661c --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3079-Find-the-Sum-of-Encrypted-Integers.md @@ -0,0 +1,120 @@ +--- +id: find-the-sum-of-encrypted-integers +title: Find the Sum of Encrypted Integers (LeetCode) +sidebar_label: 3079-FindTheSumOfEncryptedIntegers +tags: + - Array + - Math +description: Calculate the sum of encrypted integers by replacing each digit in the integer with the largest digit in the integer. +sidebar_position: 3079 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Find the Sum of Encrypted Integers](https://leetcode.com/problems/find-the-sum-of-encrypted-integers/) | [Find the Sum of Encrypted Integers Solution on LeetCode](https://leetcode.com/problems/find-the-sum-of-encrypted-integers/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +You are given an integer array `nums` containing positive integers. We define a function `encrypt` such that `encrypt(x)` replaces every digit in `x` with the largest digit in `x`. For example, `encrypt(523) = 555` and `encrypt(213) = 333`. + +Return the sum of encrypted elements. + +### Example 1 + +- **Input:** `nums = [1,2,3]` +- **Output:** `6` +- **Explanation:** The encrypted elements are `[1,2,3]`. The sum of encrypted elements is `1 + 2 + 3 = 6`. + +### Example 2 + +- **Input:** `nums = [10,21,31]` +- **Output:** `66` +- **Explanation:** The encrypted elements are `[11,22,33]`. The sum of encrypted elements is `11 + 22 + 33 = 66`. + +### Constraints + +- `1 <= nums.length <= 50` +- `1 <= nums[i] <= 1000` + +## Approach + +To solve this problem, follow these steps: + +1. Define the `encrypt` function that takes an integer `x` and returns an integer where every digit of `x` is replaced by the largest digit in `x`. +2. For each integer in `nums`, apply the `encrypt` function. +3. Calculate the sum of all encrypted integers. +4. Return the sum. + +### Solution Code + +#### Python + +```python +class Solution: + def findTheSumOfEncryptedIntegers(self, nums: List[int]) -> int: + def encrypt(x: int) -> int: + max_digit = max(str(x)) + return int(max_digit * len(str(x))) + + return sum(encrypt(num) for num in nums) +``` + +#### C++ + +```c++ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findTheSumOfEncryptedIntegers(vector& nums) { + auto encrypt = [](int x) { + string s = to_string(x); + char max_digit = *max_element(s.begin(), s.end()); + return stoi(string(s.size(), max_digit)); + }; + + int sum = 0; + for (int num : nums) { + sum += encrypt(num); + } + return sum; + } +}; + +``` + +#### Java + +```java +class Solution { + public int findTheSumOfEncryptedIntegers(int[] nums) { + int sum = 0; + for (int num : nums) { + sum += encrypt(num); + } + return sum; + } + + private int encrypt(int x) { + char[] digits = Integer.toString(x).toCharArray(); + char maxDigit = '0'; + for (char digit : digits) { + if (digit > maxDigit) { + maxDigit = digit; + } + } + return Integer.parseInt(new String(new char[digits.length]).replace('\0', maxDigit)); + } +} + +``` + +### Conclusion +The solutions provided demonstrate how to encrypt each integer by replacing its digits with the +largest digit found in the integer, and then summing these encrypted integers. This approach ensures +the problem is solved efficiently across different programming languages. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3080-Mark-Elements-on-Array-by-Performing-Queries.md b/solutions/lc-solutions/3000-3099/3080-Mark-Elements-on-Array-by-Performing-Queries.md new file mode 100644 index 0000000..615bc34 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3080-Mark-Elements-on-Array-by-Performing-Queries.md @@ -0,0 +1,247 @@ +--- +id: mark-elements-on-array-by-performing-queries +title: Mark Elements on Array by Performing Queries (LeetCode) +sidebar_label: 3080-MarkElementsOnArrayByPerformingQueries +tags: + - Array + - Queries + - Sorting +description: Apply queries on an array to mark elements and calculate the sum of unmarked elements. +sidebar_position: 3080 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Mark Elements on Array by Performing Queries](https://leetcode.com/problems/mark-elements-on-array-by-performing-queries/) | [Mark Elements on Array by Performing Queries Solution on LeetCode](https://leetcode.com/problems/mark-elements-on-array-by-performing-queries/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +You are given a 0-indexed array `nums` of size `n` consisting of positive integers. + +You are also given a 2D array `queries` of size `m` where `queries[i] = [indexi, ki]`. + +Initially, all elements of the array are unmarked. + +You need to apply `m` queries on the array in order, where on the `i-th` query you do the following: + +- Mark the element at index `indexi` if it is not already marked. +- Then mark `ki` unmarked elements in the array with the smallest values. If multiple such elements exist, mark the ones with the smallest indices. If less than `ki` unmarked elements exist, then mark all of them. + +Return an array `answer` of size `m` where `answer[i]` is the sum of unmarked elements in the array after the `i-th` query. + +### Example 1 + +- **Input:** `nums = [1,2,2,1,2,3,1]`, `queries = [[1,2],[3,3],[4,2]]` +- **Output:** `[8,3,0]` +- **Explanation:** + - We do the following queries on the array: + 1. Mark the element at index 1, and 2 of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are `nums = [1,2,2,1,2,3,1]`. The sum of unmarked elements is `2 + 2 + 3 + 1 = 8`. + 2. Mark the element at index 3, since it is already marked we skip it. Then we mark 3 of the smallest unmarked elements with the smallest indices, the marked elements now are `nums = [1,2,2,1,2,3,1]`. The sum of unmarked elements is `3`. + 3. Mark the element at index 4, since it is already marked we skip it. Then we mark 2 of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are `nums = [1,2,2,1,2,3,1]`. The sum of unmarked elements is `0`. + +### Example 2 + +- **Input:** `nums = [1,4,2,3]`, `queries = [[0,1]]` +- **Output:** `[7]` +- **Explanation:** + - We do one query which is mark the element at index 0 and mark the smallest element among unmarked elements. The marked elements will be `nums = [1,4,2,3]`, and the sum of unmarked elements is `4 + 3 = 7`. + +### Constraints + +- `n == nums.length` +- `m == queries.length` +- `1 <= m <= n <= 10^5` +- `1 <= nums[i] <= 10^5` +- `queries[i].length == 2` +- `0 <= indexi, ki <= n - 1` + +## Approach + +To solve this problem, we can use the following approach: + +1. **Track Marked Elements**: + - Use a set to track the indices of marked elements. + - Use a min-heap to efficiently find and mark the smallest unmarked elements. + +2. **Process Each Query**: + - For each query, mark the specified index if not already marked. + - Extract `ki` smallest elements from the min-heap and mark them. + - Calculate the sum of unmarked elements after each query. + +### Solution Code + +#### Python + +```python +from heapq import heappush, heappop + +class Solution: + def markElements(self, nums, queries): + n = len(nums) + m = len(queries) + + # Initializing the result array + answer = [0] * m + + # To keep track of marked elements + marked = set() + + # Min-heap to get the smallest unmarked elements + min_heap = [(nums[i], i) for i in range(n)] + min_heap.sort() + + total_sum = sum(nums) + + for i, (index, k) in enumerate(queries): + # Mark the element at index indexi if not already marked + if index not in marked: + marked.add(index) + total_sum -= nums[index] + + # Mark k smallest unmarked elements + to_mark = [] + while min_heap and len(to_mark) < k: + val, idx = heappop(min_heap) + if idx not in marked: + marked.add(idx) + total_sum -= val + to_mark.append((val, idx)) + + # Push the elements back that were popped but not marked + for val, idx in to_mark: + heappush(min_heap, (val, idx)) + + # Store the sum of unmarked elements after this query + answer[i] = total_sum + + return answer +``` + +#### C++ +```c++ +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector markElements(vector& nums, vector>& queries) { + int n = nums.size(); + int m = queries.size(); + + vector answer(m); + + unordered_set marked; + + priority_queue, vector>, greater>> minHeap; + for (int i = 0; i < n; ++i) { + minHeap.emplace(nums[i], i); + } + + int totalSum = 0; + for (int num : nums) { + totalSum += num; + } + + for (int i = 0; i < m; ++i) { + int index = queries[i][0]; + int k = queries[i][1]; + + if (marked.find(index) == marked.end()) { + marked.insert(index); + totalSum -= nums[index]; + } + + vector> toMark; + while (!minHeap.empty() && toMark.size() < k) { + auto minElem = minHeap.top(); + minHeap.pop(); + int val = minElem.first; + int idx = minElem.second; + if (marked.find(idx) == marked.end()) { + marked.insert(idx); + totalSum -= val; + toMark.push_back(minElem); + } + } + + for (const auto& elem : toMark) { + minHeap.push(elem); + } + + answer[i] = totalSum; + } + + return answer; + } +}; + +``` + +#### Java +```java +import java.util.*; + +class Solution { + public int[] markElements(int[] nums, int[][] queries) { + int n = nums.length; + int m = queries.length; + + int[] answer = new int[m]; + + Set marked = new HashSet<>(); + + PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); + for (int i = 0; i < n; i++) { + minHeap.offer(new int[]{nums[i], i}); + } + + int totalSum = 0; + for (int num : nums) { + totalSum += num; + } + + for (int i = 0; i < m; i++) { + int index = queries[i][0]; + int k = queries[i][1]; + + if (!marked.contains(index)) { + marked.add(index); + totalSum -= nums[index]; + } + + List toMark = new ArrayList<>(); + while (!minHeap.isEmpty() && toMark.size() < k) { + int[] minElem = minHeap.poll(); + int val = minElem[0]; + int idx = minElem[1]; + if (!marked.contains(idx)) { + marked.add(idx); + totalSum -= val; + toMark.add(minElem); + } + } + + for (int[] elem : toMark) { + minHeap.offer(elem); + } + + answer[i] = totalSum; + } + + return answer; + } +} + +``` + +### Conclusion +The provided solutions use a set to track marked elements and a min-heap to efficiently mark the +smallest unmarked elements. This approach ensures that queries are processed in an optimal manner. +Adjustments for different languages and constraints are handled to ensure robustness across +different inputs. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3083-Existence-of-a-Substring-in-a-String-and-Its-Reverse.md b/solutions/lc-solutions/3000-3099/3083-Existence-of-a-Substring-in-a-String-and-Its-Reverse.md new file mode 100644 index 0000000..298aa52 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3083-Existence-of-a-Substring-in-a-String-and-Its-Reverse.md @@ -0,0 +1,140 @@ +--- +id: existence-of-substring-in-string-and-reverse +title: Existence of a Substring in a String and Its Reverse (LeetCode) +sidebar_label: 3083-ExistenceOfSubstringInStringAndReverse +tags: + - String + - Two Pointers +description: Check if any substring of length 2 in a string is also present in its reverse. +sidebar_position: 3083 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Existence of a Substring in a String and Its Reverse](https://leetcode.com/problems/existence-of-a-substring-in-a-string-and-its-reverse/) | [Existence of a Substring in a String and Its Reverse Solution on LeetCode](https://leetcode.com/problems/existence-of-a-substring-in-a-string-and-its-reverse/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +Given a string `s`, find any substring of length 2 which is also present in the reverse of `s`. + +Return `true` if such a substring exists, and `false` otherwise. + +### Example 1 + +- **Input:** `s = "leetcode"` +- **Output:** `true` +- **Explanation:** Substring "ee" is of length 2 which is also present in reverse(s) == "edocteel". + +### Example 2 + +- **Input:** `s = "abcba"` +- **Output:** `true` +- **Explanation:** All of the substrings of length 2 "ab", "bc", "cb", "ba" are also present in reverse(s) == "abcba". + +### Example 3 + +- **Input:** `s = "abcd"` +- **Output:** `false` +- **Explanation:** There is no substring of length 2 in `s`, which is also present in the reverse of `s`. + +### Constraints + +- `1 <= s.length <= 100` +- `s` consists only of lowercase English letters. + +## Approach + +To solve this problem, we can use a set to keep track of all substrings of length 2 in the original string `s` and check if any of these substrings exist in the reverse of `s`. + +1. **Generate Substrings**: + - Iterate through the string and generate all substrings of length 2. + - Store these substrings in a set. + +2. **Check in Reverse**: + - Generate the reverse of the string. + - Iterate through the reversed string and check if any substring of length 2 exists in the set. + +### Solution Code + +#### Python + +```python +class Solution: + def existsInReverse(self, s: str) -> bool: + substrings = set() + + for i in range(len(s) - 1): + substrings.add(s[i:i+2]) + + reversed_s = s[::-1] + + for i in range(len(reversed_s) - 1): + if reversed_s[i:i+2] in substrings: + return true + + return false +``` + +#### C++ +```c++ +#include +#include +#include + +class Solution { +public: + bool existsInReverse(string s) { + unordered_set substrings; + + for (int i = 0; i < s.length() - 1; ++i) { + substrings.insert(s.substr(i, 2)); + } + + reverse(s.begin(), s.end()); + + for (int i = 0; i < s.length() - 1; ++i) { + if (substrings.find(s.substr(i, 2)) != substrings.end()) { + return true; + } + } + + return false; + } +}; + +``` + +#### Java +```java +import java.util.HashSet; +import java.util.Set; + +class Solution { + public boolean existsInReverse(String s) { + Set substrings = new HashSet<>(); + + for (int i = 0; i < s.length() - 1; i++) { + substrings.add(s.substring(i, i + 2)); + } + + String reversedS = new StringBuilder(s).reverse().toString(); + + for (int i = 0; i < reversedS.length() - 1; i++) { + if (substrings.contains(reversedS.substring(i, i + 2))) { + return true; + } + } + + return false; + } +} + +``` + +### Conclusion +The provided solutions use a set to store substrings of length 2 and check if these substrings exist +in the reverse of the string. This approach ensures efficient checking and handles edge cases +effectively. Adjustments for different languages and constraints are handled to ensure robustness +across different inputs. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3084-Count-Substrings-Starting-and-Ending-with-Given-Character.md b/solutions/lc-solutions/3000-3099/3084-Count-Substrings-Starting-and-Ending-with-Given-Character.md new file mode 100644 index 0000000..3ce4633 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3084-Count-Substrings-Starting-and-Ending-with-Given-Character.md @@ -0,0 +1,109 @@ +--- +id: count-substrings-starting-and-ending-with-given-character +title: Count Substrings Starting and Ending with Given Character (LeetCode) +sidebar_label: 3084-CountSubstringsStartingAndEndingWithGivenCharacter +tags: + - String + - Sliding Window +description: Return the total number of substrings of a string that start and end with a given character. +sidebar_position: 3084 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Count Substrings Starting and Ending with Given Character](https://leetcode.com/problems/count-substrings-starting-and-ending-with-given-character/) | [Count Substrings Starting and Ending with Given Character Solution on LeetCode](https://leetcode.com/problems/count-substrings-starting-and-ending-with-given-character/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +You are given a string `s` and a character `c`. Return the total number of substrings of `s` that start and end with `c`. + +### Example 1 + +- **Input:** `s = "abada"`, `c = "a"` +- **Output:** `6` +- **Explanation:** Substrings starting and ending with "a" are: "a", "ada", "a", "ada", "a", "ada". + +### Example 2 + +- **Input:** `s = "zzz"`, `c = "z"` +- **Output:** `6` +- **Explanation:** There are a total of 6 substrings in `s` and all start and end with "z". + +### Constraints + +- `1 <= s.length <= 10^5` +- `s` and `c` consist only of lowercase English letters. + +## Approach + +To solve this problem, we can iterate through the string and track the positions of the character `c`. For each occurrence of `c`, we can count the number of valid substrings that start and end with `c` using the positions tracked so far. Here's the approach: + +1. **Tracking Positions**: + - Use a list to store the indices of the occurrences of `c`. + +2. **Counting Substrings**: + - For each occurrence of `c`, calculate the number of valid substrings that can be formed with the previously recorded positions. + +### Solution Code + +#### Python + +```python +class Solution: + def countSubstrings(self, s: str, c: str) -> int: + positions = [] + count = 0 + + for i in range(len(s)): + if s[i] == c: + positions.append(i) + count += len(positions) + + return count +``` + +#### C++ +```c++ +class Solution { +public: + int countSubstrings(string s, char c) { + int count = 0; + int positions = 0; + + for (int i = 0; i < s.length(); ++i) { + if (s[i] == c) { + ++positions; + count += positions; + } + } + + return count; + } +}; +``` + +#### Java +```java +class Solution { + public int countSubstrings(String s, char c) { + int count = 0; + int positions = 0; + + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == c) { + positions++; + count += positions; + } + } + + return count; + } +} +``` + +### Conclusion +The provided solutions use a single-pass approach to count the substrings starting and ending with +the given character efficiently. Adjustments for different languages and edge cases are handled to +ensure robustness across different inputs. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3095-Shortest-Subarray-With-OR-at-Least-K-I.md b/solutions/lc-solutions/3000-3099/3095-Shortest-Subarray-With-OR-at-Least-K-I.md new file mode 100644 index 0000000..69738f8 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3095-Shortest-Subarray-With-OR-at-Least-K-I.md @@ -0,0 +1,136 @@ +--- +id: shortest-subarray-with-or-at-least-k +title: Shortest Subarray With OR at Least K (LeetCode) +sidebar_label: 3095-ShortestSubarrayWithORAtLeastK +tags: + - Array + - Bitwise Operations + - Sliding Window +description: Find the length of the shortest special subarray where the bitwise OR is at least k. +sidebar_position: 3095 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Shortest Subarray With OR at Least K](https://leetcode.com/problems/shortest-subarray-with-or-at-least-k/) | [Shortest Subarray With OR at Least K Solution on LeetCode](https://leetcode.com/problems/shortest-subarray-with-or-at-least-k/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +You are given an array `nums` of non-negative integers and an integer `k`. + +An array is called special if the bitwise OR of all of its elements is at least `k`. + +Return the length of the shortest special non-empty subarray of `nums`, or return `-1` if no special subarray exists. + +### Example 1 + +- **Input:** `nums = [1,2,3]`, `k = 2` +- **Output:** `1` +- **Explanation:** The subarray `[3]` has OR value of 3. Hence, we return 1. + +### Example 2 + +- **Input:** `nums = [2,1,8]`, `k = 10` +- **Output:** `3` +- **Explanation:** The subarray `[2,1,8]` has OR value of 11. Hence, we return 3. + +### Example 3 + +- **Input:** `nums = [1,2]`, `k = 0` +- **Output:** `1` +- **Explanation:** The subarray `[1]` has OR value of 1. Hence, we return 1. + +### Constraints + +- `1 <= nums.length <= 50` +- `0 <= nums[i] <= 50` +- `0 <= k < 64` + +## Approach + +To solve this problem, we can use a sliding window approach to find the shortest subarray with the desired properties. The idea is to maintain a window that keeps track of the OR of its elements and check if it meets the condition. Here's the approach: + +1. **Sliding Window**: + - Use two pointers (`left` and `right`) to represent the current window. + - Move the `right` pointer to expand the window and calculate the OR of the current window. + - Once the OR of the current window is at least `k`, move the `left` pointer to find the shortest subarray. + +2. **Bitwise OR Calculation**: + - Continuously calculate the OR value of the elements in the current window. + +3. **Edge Cases**: + - Handle cases where no subarray meets the condition. + +### Solution Code + +#### Python + +```python +class Solution: + def shortestSubarrayWithORAtLeastK(self, nums: List[int], k: int) -> int: + n = len(nums) + min_length = float('inf') + + for i in range(n): + current_or = 0 + for j in range(i, n): + current_or |= nums[j] + if current_or >= k: + min_length = min(min_length, j - i + 1) + break + return min_length if min_length != float('inf') else -1 +``` + +#### C++ +```c++ +class Solution { +public: + int shortestSubarrayWithORAtLeastK(vector& nums, int k) { + int n = nums.size(); + int minLength = INT_MAX; + + for (int i = 0; i < n; ++i) { + int currentOr = 0; + for (int j = i; j < n; ++j) { + currentOr |= nums[j]; + if (currentOr >= k) { + minLength = min(minLength, j - i + 1); + break; + } + } + } + + return minLength == INT_MAX ? -1 : minLength; + } +}; +``` + +#### Java +```java +class Solution { + public int shortestSubarrayWithORAtLeastK(int[] nums, int k) { + int n = nums.length; + int minLength = Integer.MAX_VALUE; + + for (int i = 0; i < n; i++) { + int currentOr = 0; + for (int j = i; j < n; j++) { + currentOr |= nums[j]; + if (currentOr >= k) { + minLength = Math.min(minLength, j - i + 1); + break; + } + } + } + + return minLength == Integer.MAX_VALUE ? -1 : minLength; + } +} +``` + +### Conclusion +The provided solutions use a nested loop approach to find the shortest subarray that meets the +condition. Adjustments for different languages and edge cases are handled to ensure robustness +across different inputs. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3096-Minimum-Levels-to-Gain-More-Points.md b/solutions/lc-solutions/3000-3099/3096-Minimum-Levels-to-Gain-More-Points.md new file mode 100644 index 0000000..6d2614c --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3096-Minimum-Levels-to-Gain-More-Points.md @@ -0,0 +1,209 @@ +--- +id: minimum-levels-to-gain-more-points +title: Minimum Levels to Gain More Points (LeetCode) +sidebar_label: 3096-MinimumLevelsToGainMorePoints +tags: + - Array + - Greedy + - Two Pointers +description: Determine the minimum number of levels Alice should play to gain more points than Bob, given that some levels are impossible to clear. +sidebar_position: 3096 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Minimum Levels to Gain More Points](https://leetcode.com/problems/minimum-levels-to-gain-more-points/) | [Minimum Levels to Gain More Points Solution on LeetCode](https://leetcode.com/problems/minimum-levels-to-gain-more-points/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +You are given a binary array `possible` of length `n`. + +Alice and Bob are playing a game that consists of `n` levels. Some of the levels in the game are impossible to clear while others can always be cleared. In particular, if `possible[i] == 0`, then the ith level is impossible to clear for both players. A player gains 1 point on clearing a level and loses 1 point if the player fails to clear it. + +At the start of the game, Alice will play some levels in the given order starting from the 0th level, after which Bob will play for the rest of the levels. + +Alice wants to know the minimum number of levels she should play to gain more points than Bob, if both players play optimally to maximize their points. + +Return the minimum number of levels Alice should play to gain more points. If this is not possible, return -1. + +Note that each player must play at least 1 level. + +### Example 1 + +- **Input:** `possible = [1,0,1,0]` +- **Output:** `1` +- **Explanation:** + - If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has -1 + 1 - 1 = -1 point. + - If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 0 points, while Bob has 0 points. + - If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 1 point, while Bob has -1 point. + - Alice must play a minimum of 1 level to gain more points. + +### Example 2 + +- **Input:** `possible = [1,1,1,1,1]` +- **Output:** `3` +- **Explanation:** + - If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has 4 points. + - If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 2 points, while Bob has 3 points. + - If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 3 points, while Bob has 2 points. + - If Alice plays till level 3 and Bob plays the rest of the levels, Alice has 4 points, while Bob has 1 point. + - Alice must play a minimum of 3 levels to gain more points. + +### Example 3 + +- **Input:** `possible = [0,0]` +- **Output:** `-1` +- **Explanation:** The only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points, Alice can't gain more points than Bob. + +### Constraints + +- `2 <= n == possible.length <= 10^5` +- `possible[i]` is either `0` or `1`. + +## Approach + +To solve this problem, we can use a greedy approach combined with a two-pointer technique: + +1. Traverse through the `possible` array and determine the total number of levels that can be played (`total_possible_levels`). +2. Initialize two pointers: `alice_played` and `bob_played` to simulate both players playing optimally. +3. Start by considering `alice_played` from 1 level up to `total_possible_levels - 1`. +4. Calculate the points for Alice and Bob after Alice plays `alice_played` levels and Bob plays the rest. +5. Track the minimum number of levels Alice needs to play to have more points than Bob. +6. Return the result based on the tracked minimum number of levels or `-1` if it's not possible for Alice to gain more points. + +### Solution Code + +#### Python + +```python +class Solution: + def minLevelsToGainMorePoints(self, possible: List[int]) -> int: + n = len(possible) + total_possible_levels = sum(possible) + + if total_possible_levels < 2: + return -1 + + alice_played = 0 + min_levels = float('inf') + + alice_points = 0 + bob_points = 0 + + for i in range(n): + if possible[i] == 1: + bob_points += 1 + + for i in range(n): + if possible[i] == 1: + alice_played += 1 + alice_points += 1 + bob_points -= 1 + + if alice_played >= 1 and alice_points > bob_points: + min_levels = min(min_levels, alice_played) + + return min_levels if min_levels != float('inf') else -1 +``` + +#### C++ +```c++ +#include +using namespace std; + +class Solution { +public: + int minLevelsToGainMorePoints(vector& possible) { + int n = possible.size(); + int total_possible_levels = 0; + + for (int i = 0; i < n; ++i) { + total_possible_levels += possible[i]; + } + + if (total_possible_levels < 2) { + return -1; + } + + int alice_played = 0; + int min_levels = INT_MAX; + + int alice_points = 0; + int bob_points = 0; + + for (int i = 0; i < n; ++i) { + if (possible[i] == 1) { + bob_points++; + } + } + + for (int i = 0; i < n; ++i) { + if (possible[i] == 1) { + alice_played++; + alice_points++; + bob_points--; + } + + if (alice_played >= 1 && alice_points > bob_points) { + min_levels = min(min_levels, alice_played); + } + } + + return min_levels != INT_MAX ? min_levels : -1; + } +}; + +``` + +#### Java +```java +class Solution { + public int minLevelsToGainMorePoints(int[] possible) { + int n = possible.length; + int total_possible_levels = 0; + + for (int i = 0; i < n; ++i) { + total_possible_levels += possible[i]; + } + + if (total_possible_levels < 2) { + return -1; + } + + int alice_played = 0; + int min_levels = Integer.MAX_VALUE; + + int alice_points = 0; + int bob_points = 0; + + for (int i = 0; i < n; ++i) { + if (possible[i] == 1) { + bob_points++; + } + } + + for (int i = 0; i < n; ++i) { + if (possible[i] == 1) { + alice_played++; + alice_points++; + bob_points--; + } + + if (alice_played >= 1 && alice_points > bob_points) { + min_levels = Math.min(min_levels, alice_played); + } + } + + return min_levels != Integer.MAX_VALUE ? min_levels : -1; + } +} + +``` + +### Conclusion +The provided solutions utilize a greedy approach combined with a two-pointer technique to determine +the minimum number of levels Alice should play to gain more points than Bob. By iterating through +possible levels Alice can play and computing the resultant points for both players, we can +efficiently determine the solution to this problem. \ No newline at end of file diff --git a/solutions/lc-solutions/3000-3099/3099-Harshad-Number.md b/solutions/lc-solutions/3000-3099/3099-Harshad-Number.md new file mode 100644 index 0000000..b79a33e --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3099-Harshad-Number.md @@ -0,0 +1,133 @@ +--- +id: Harshad-Number +title: Harshad-Number +sidebar_label: 3099 -Harshad-Number +tags: + - Array + - Sorting + - Enumeration +description: "This is a solution to the Harshad Number problem on LeetCode." +--- + +## Problem statement: + +An integer divisible by the sum of its digits is said to be a Harshad number. You are given an integer x. Return the sum of the digits of x if x is a Harshad number, otherwise, return -1. + +**Example 1:** + +Input: x = 18 +Output: 9 + +Explanation: +The sum of digits of x is 9. 18 is divisible by 9. So 18 is a Harshad number and the answer is 9. + +**Example 2:** + +Input: x = 23 +Output: -1 + +Explanation: +The sum of digits of x is 5. 23 is not divisible by 5. So 23 is not a Harshad number and the answer is -1. + +Constraints: +`1 <= x <= 100` + +## Solutions: + +### Intuition + +When faced with the problem of identifying whether a number is a Harshad number (also known as a Niven number), the initial thought is to break down the number into its individual digits, sum those digits, and then check if the original number is divisible by the sum of its digits without a remainder. This process involves basic arithmetic operations and iterating over each digit of the number. + +### Approach + + 1. **Summing the Digits**: First, we need a method to sum the digits of the given number. This can be done by repeatedly dividing the number by 10 and adding the remainder to a sum variable until the number becomes `0`. + + 2. **Checking Divisibility**: Once we have the sum of the digits, we check if the original number is divisible by this sum. If the modulus (%) operation of the number divided by the sum of its digits equals 0, it is a Harshad number; otherwise, it is not. + + 3. **Returning the Result**: If the number is a Harshad number, we return the sum of its digits as specified in the problem statement. If it's not, we return -1 (or an appropriate value indicating it's not a Harshad number). + +## Code + + + + + ```cpp + class Solution { + public: + int sumOfTheDigitsOfHarshadNumber(int x) { + int sum = 0; + int n = x; + + while(n != 0){ + sum = sum + n % 10; + n = n/10; + } + + if(x % sum == 0){ + return sum; + } + return -1; + } + }; + ``` + + + + ```java + class Solution { + public int sumOfTheDigitsOfHarshadNumber(int x) { + int sum = 0; + int a = x; + while (a > 0) { + sum += a % 10; + a /= 10; + } + if (x % sum == 0) + return sum; + return -1; + } + } + ``` + + + + ```python + class Solution(object): + def sumOfTheDigitsOfHarshadNumber(self, x): + sum_number = 0 + temp = x + while temp > 0: + sum_number += temp % 10 + temp //= 10 + if x % sum_number == 0: + return sum_number + return -1 + ``` + + + + ```c + int sumOfTheDigitsOfHarshadNumber(int x) { + int sumNumber = 0; + int temp = x; + while (temp) { + sumNumber += temp % 10; + temp /= 10; + } + if (x % sumNumber == 0) + return sumNumber; + return -1; + } + ``` + + + +## Complexity + +### Time complexity: + +The time complexity is $O(k)$, where k is the number of digits in the number. This is because we need to iterate over each digit to sum them, and the number of iterations is proportional to the number of digits in the number. + +### Space complexity: + +The space complexity is $O(1)$, as the space required does not grow with the input size. We only need a fixed amount of variables to store the sum of the digits, the temporary value of the number as we reduce it, and possibly the original number if we need to return the sum of its digits. diff --git a/solutions/lc-solutions/3000-3099/3163-string-compression-III.md b/solutions/lc-solutions/3000-3099/3163-string-compression-III.md new file mode 100644 index 0000000..4525848 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/3163-string-compression-III.md @@ -0,0 +1,241 @@ +--- +id: string-compression +title: String Compression Solution +sidebar_label: String Compression +tags: + - String Compression + - Brute Force + - Optimized + - LeetCode + - Java + - Python + - C++ +description: "This is a solution to the String Compression problem on LeetCode." +sidebar_position: 2 +--- + +In this tutorial, we will solve the String Compression problem using two different approaches: brute force and optimized. We will provide the implementation of the solution in C++, Java, and Python. + +## Problem Description + +Given a string `word`, compress it using the following algorithm: + +Begin with an empty string `comp`. While `word` is not empty, use the following operation: +Remove a maximum length prefix of `word` made of a single character `c` repeating at most 9 times. +Append the length of the prefix followed by `c` to `comp`. + +Return the string `comp`. + +### Examples + +**Example 1:** + +``` +Input: word = "abcde" +Output: "1a1b1c1d1e" +``` + +**Example 2:** + +``` +Input: word = "aaaaaaaaaaaaaabb" +Output: "9a5a2b" +``` + +### Constraints + +- `1 <= word.length <= 2 * 105` +- `word` consists only of lowercase English letters. + +--- + +## Solution for String Compression Problem + +### Intuition and Approach + +The problem can be solved using a brute force approach or an optimized approach. The brute force approach directly iterates through the string and constructs the result, while the optimized approach efficiently handles consecutive characters. + + + + +### Approach 1: Brute Force (Naive) + +The brute force approach iterates through each character of the string, counts consecutive characters up to 9, and appends the count followed by the character to the result string. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + string compressString(string word) { + string comp; + int i = 0; + while (i < word.length()) { + char c = word[i]; + int count = 0; + while (i < word.length() && word[i] == c && count < 9) { + count++; + i++; + } + comp += to_string(count) + c; + } + return comp; + } +}; +``` + + + + + +```java +class Solution { + public String compressString(String word) { + StringBuilder comp = new StringBuilder(); + int i = 0; + while (i < word.length()) { + char c = word.charAt(i); + int count = 0; + while (i < word.length() && word.charAt(i) == c && count < 9) { + count++; + i++; + } + comp.append(count).append(c); + } + return comp.toString(); + } +} +``` + + + + + +```python +class Solution: + def compressString(self, word: str) -> str: + comp = [] + i = 0 + while i < len(word): + c = word[i] + count = 0 + while i < len(word) and word[i] == c and count < 9: + count += 1 + i += 1 + comp.append(f"{count}{c}") + return ''.join(comp) +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ +- Space Complexity: $O(n)$ +- Where `n` is the length of `word`. +- The time complexity is $O(n)$ because we iterate through the string once. +- The space complexity is $O(n)$ because we store the result in a new string. + + + + +### Approach 2: Optimized Approach + +The optimized approach is similar to the brute force but handles the prefix length more efficiently, ensuring it counts up to 9 characters in each iteration. + +#### Code in Different Languages + + + + + +```cpp +class Solution { +public: + string compressString(string word) { + string comp; + int i = 0; + while (i < word.length()) { + char c = word[i]; + int count = 1; + while (i + count < word.length() && word[i + count] == c && count < 9) { + count++; + } + comp += to_string(count) + c; + i += count; + } + return comp; + } +}; +``` + + + + + +```java +class Solution { + public String compressString(String word) { + StringBuilder comp = new StringBuilder(); + int i = 0; + while (i < word.length()) { + char c = word.charAt(i); + int count = 1; + while (i + count < word.length() && word.charAt(i + count) == c && count < 9) { + count++; + } + comp.append(count).append(c); + i += count; + } + return comp.toString(); + } +} +``` + + + + + +```python +class Solution: + def compressString(self, word: str) -> str: + comp = [] + i = 0 + while i < len(word): + c = word[i] + count = 1 + while i + count < len(word) and word[i + count] == c and count < 9: + count += 1 + comp.append(f"{count}{c}") + i += count + return ''.join(comp) +``` + + + + +#### Complexity Analysis + +- Time Complexity: $O(n)$ +- Space Complexity: $O(n)$ +- Where `n` is the length of `word`. +- The time complexity is $O(n)$ because we iterate through the string once. +- The space complexity is $O(n)$ because we store the result in a new string. + + + + +--- + +

Authors:

+ +
+{['ImmidiSivani'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/3000-3099/_category_.json b/solutions/lc-solutions/3000-3099/_category_.json new file mode 100644 index 0000000..3992e91 --- /dev/null +++ b/solutions/lc-solutions/3000-3099/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "3000-3099", + "position": 32, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (3000 - 3099)" + } +} diff --git a/solutions/lc-solutions/3100-3199/3100-Water-Bottles-II.md b/solutions/lc-solutions/3100-3199/3100-Water-Bottles-II.md new file mode 100644 index 0000000..cd14171 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3100-Water-Bottles-II.md @@ -0,0 +1,215 @@ +--- +id: water-bottles-II +title: Water-Bottles-II +level: hard +sidebar_label: 3100-Water-Bottles-II +tags: + - Dynamic Programming + - Bit Manipulation + - C++ + - Java + - Python +description: "This document provides solutions for Water-bottles-II solution of leetcode questions" +--- + +## Problem statement: + +You are given two integers numBottles and numExchange. + +numBottles represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations: + + 1. Drink any number of full water bottles turning them into empty bottles. + 2. Exchange numExchange empty bottles with one full water bottle. Then, increase numExchange by one. + +Note that you cannot exchange multiple batches of empty bottles for the same value of numExchange. For example, if numBottles == 3 and numExchange == 1, you cannot exchange 3 empty water bottles for 3 full bottles. + +Return the maximum number of water bottles you can drink. + +Example 1: + + ![alt text](image.png) + +Input: numBottles = 13, numExchange = 6 +Output: 15 +Explanation: The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. + +Example 2: + + ![alt text](image-1.png) + +Input: numBottles = 10, numExchange = 3 +Output: 13 +Explanation: The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. + +Constraints: + + `1 <= numBottles <= 100` + `1 <= numExchange <= 100` + +## Solutions: + +### Intuition + +The key to maximizing the number of water bottles drunk is to strategically utilize the exchange mechanic. We can think of this problem in terms of maximizing the total number of "drinking opportunities." + +### Approach + + 1. **Greedy Strategy:** + + We want to prioritize drinking full bottles whenever possible. Since drinking a full bottle directly translates to an extra opportunity to exchange empty bottles, it's the most efficient use of a full bottle. + + 2. **Iterative Exchange:** + + As long as we have enough empty bottles (at least numExchange), we can perform an exchange. Each exchange grants one new full bottle and increases the exchange cost (numExchange) by one. + + 3. **Stopping Condition:** + + The exchange process becomes inefficient once we don't have enough empty bottles (less than numExchange) to trigger an exchange. At this point, we simply drink any remaining full bottles. + +### Implementation + + The provided code effectively implements the greedy approach with an iterative loop. Here's a breakdown: + + - int maxBottlesDrunk(int numBottles, int numExchange): This function takes the initial number of bottles (numBottles) and the exchange cost (numExchange) as input. + + - int ans = numBottles: Initializes two variables: + + - ans: Tracks the current number of full bottles we can potentially drink (including potential gains from exchange). + + - ans2 (not shown explicitly in the provided code snippet): Stores the final maximum number of bottles drunk. + + - while(ans>=numExchange): A loop that continues as long as we have enough empty bottles (represented by ans) to trigger an exchange. + + - ans-=numExchange: Subtract the exchange cost from the current full bottles (ans). This simulates performing the exchange and using numExchange empty bottles. + + - ans++: Since the exchange grants one new full bottle, we increment ans to represent this gain. + + - ans2++: Increment ans2 to track the total number of bottles drunk so far (including the newly gained bottle). + + - numExchange++: Increase the exchange cost by one, reflecting the updated requirement for future exchanges. + + - return ans2: After the loop exits (when we don't have enough empty bottles to exchange), ans2 holds the maximum number of bottles drunk, which is returned. + +## Code: + + + + + ```cpp + #include + + class Solution { + public: + int maxBottlesDrunk(int numBottles, int numExchange) { + int totalDrunk = numBottles; + int emptyBottles = numBottles; + + while (emptyBottles >= numExchange) { + int newBottles = emptyBottles / numExchange; + totalDrunk += newBottles; + emptyBottles = emptyBottles % numExchange + newBottles; + } + + return totalDrunk; + } + }; + + // Driver code + int main() { + Solution sol; + int numBottles = 9; + int numExchange = 3; + std::cout << sol.maxBottlesDrunk(numBottles, numExchange) << std::endl; // Output: 13 + return 0; + } + ``` + + + + ```java + public class Solution { + public int maxBottlesDrunk(int numBottles, int numExchange) { + int totalDrunk = numBottles; + int emptyBottles = numBottles; + + while (emptyBottles >= numExchange) { + int newBottles = emptyBottles / numExchange; + totalDrunk += newBottles; + emptyBottles = emptyBottles % numExchange + newBottles; + } + + return totalDrunk; + } + + // Driver code + public static void main(String[] args) { + Solution sol = new Solution(); + int numBottles = 9; + int numExchange = 3; + System.out.println(sol.maxBottlesDrunk(numBottles, numExchange)); // Output: 13 + } + } + ``` + + + + ```python + class Solution: + def maxBottlesDrunk(self, numBottles: int, numExchange: int) -> int: + total_drunk = numBottles + empty_bottles = numBottles + + while empty_bottles >= numExchange: + new_bottles = empty_bottles // numExchange + total_drunk += new_bottles + empty_bottles = empty_bottles % numExchange + new_bottles + + return total_drunk + + # Driver code + if __name__ == "__main__": + sol = Solution() + numBottles = 9 + numExchange = 3 + print(sol.maxBottlesDrunk(numBottles, numExchange)) # Output: 13 + ``` + + + + ```c + #include + + int maxBottlesDrunk(int numBottles, int numExchange) { + int totalDrunk = numBottles; + int emptyBottles = numBottles; + + while (emptyBottles >= numExchange) { + int newBottles = emptyBottles / numExchange; + totalDrunk += newBottles; + emptyBottles = emptyBottles % numExchange + newBottles; + } + + return totalDrunk; + } + + // Driver code + int main() { + int numBottles = 9; + int numExchange = 3; + printf("%d\n", maxBottlesDrunk(numBottles, numExchange)); // Output: 13 + return 0; + } + ``` + + + + +## Complexity + +**Time complexity:** $O(numBottles)$ + +In the worst case, we might need to perform an exchange for every initial bottle (numBottles) if the exchange cost (numExchange) is low. The loop iterates proportionally to the number of bottles. + +**Space complexity:** $O(1)$ + +The code uses a constant amount of extra space for variables like ans and ans2, which doesn't depend on the input size (numBottles or numExchange). diff --git a/solutions/lc-solutions/3100-3199/3101-count-alternating-subarrays.md b/solutions/lc-solutions/3100-3199/3101-count-alternating-subarrays.md new file mode 100644 index 0000000..18fba86 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3101-count-alternating-subarrays.md @@ -0,0 +1,254 @@ +--- +id: Count-Alternating-subarrays +title: Count-Alternating-subarrays +level: hard +sidebar_label: 3101-Count-Alternating-subarrays +tags: + - Dynamic Programming + - Bit Manipulation + - C++ + - Java + - Python +description: "This document provides solutions for Count-Alternating-subarrays solution of leetcode questions" +--- + +## Problem statement: + +You are given a binary array nums. + +We call a subarray alternating if no two adjacent elements in the subarray have the same value. + +Return the number of alternating subarrays in nums. + +**Example 1:** + +Input: nums = [0,1,1,1] +Output: 5 + +Explanation: +The following subarrays are alternating: [0], [1], [1], [1], and [0,1]. + +**Example 2:** + +Input: nums = [1,0,1,0] +Output: 10 + +Explanation: +Every subarray of the array is alternating. There are 10 possible subarrays that we can choose. + +Constraints: + + - `1 <= nums.length <= 105` + - `nums[i] is either 0 or 1.` + +## Solutions: + +### Intuition + + - An alternating subarray has no consecutive elements with the same value. We can iterate through the array and keep track of the current subarray length while checking if adjacent elements differ. If they differ, we can increment the subarray length. Once we encounter two consecutive elements with the same value, we've reached the end of the current subarray. + + - There's an interesting fact about counting the number of subarrays of a certain length: the number of subarrays of length k is equal to the sum of 1 + 2 + ... + k. This formula captures the idea that we can choose any starting index within the subarray of length k. + +### Approach + +1. **Sliding Window:** + + - We use a sliding window approach with two pointers (left and right) to track the current subarray. + +2. **Iterate and Check:** + + - As we iterate through the array using right, we check if the current element (nums[right]) is different from the next element (nums[right + 1]). + + - If they differ, it's part of an alternating subarray, so we increment right to extend the subarray. + +3. **Calculate and Update:** + + - Once we encounter two consecutive elements with the same value, we've reached the end of the current subarray. + + - We calculate the number of subarrays within the current subarray length using the formula (length \* (length + 1)) / 2. This leverages the fact mentioned in the intuition. + + - We add this count to the overall count of alternating subarrays. + + - We update the left pointer to right to start a new subarray from the next element. + +### Implementation + +The provided code effectively implements the sliding window approach with the mentioned formula. Here's a breakdown: + +1. int countAlternatingSubarrays(vector& nums): This function takes the binary array nums as input. + +2. int n = nums.size();: Gets the size of the array n. + +3. long long count = 0;: Initializes a variable count to store the total number of alternating subarrays. + +4. int left = 0;: Initializes left and right pointers, both starting at index 0. + + - int right = 0; + +5. while (right < n): A loop that continues as long as right hasn't reached the end of the array. + + - while (right < n - 1 && nums[right] != nums[right + 1]): This inner loop extends the current subarray as long as adjacent elements differ. + +6. It checks if right is within bounds and if the elements at right and right + 1 are different. + +7. If they differ, we increment right to include the next element in the subarray. + long long length = right - left + 1;: Calculates the length of the current subarray (right - left + 1). + +8. count += static_cast(length \* (length + 1)) / 2;: Calculates the number of subarrays within the current subarray length and adds it to the count. + +9. The casting to long long ensures we don't overflow for larger length values. + + - right++;: Moves the right pointer forward to start a new subarray from the next element. + + - left = right;: Updates the left pointer to the same position as right, effectively starting a new subarray. + +10. return count;: After the loop finishes iterating through the entire array, count holds the total number of alternating subarrays, which is returned + +## Code + + + + + ```cpp + class Solution { + public: + long long countAlternatingSubarrays(vector& nums) { + int n = nums.size(); + long long count = 0; + + int left = 0; + int right = 0; + + while (right < n) { + while (right < n - 1 && nums[right] != nums[right + 1]) { + right++; + } + + long long length = right - left + 1; + + count += static_cast(length * (length + 1)) / 2; + + right++; + left = right; + } + + return count; + } + }; + ``` + + + + ```java + public class Solution { + public long countAlternatingSubarrays(int[] nums) { + int n = nums.length; + long count = 0; + + int left = 0; + int right = 0; + + while (right < n) { + while (right < n - 1 && nums[right] != nums[right + 1]) { + right++; + } + + long length = right - left + 1; + + count += (length * (length + 1)) / 2; + + right++; + left = right; + } + + return count; + } + + // Driver code + public static void main(String[] args) { + Solution sol = new Solution(); + int[] nums = {1, 0, 1, 0, 1}; + System.out.println(sol.countAlternatingSubarrays(nums)); // Output: 9 + } + } + ``` + + + + ```python + class Solution: + def countAlternatingSubarrays(self, nums): + n = len(nums) + count = 0 + + left = 0 + right = 0 + + while right < n: + while right < n - 1 and nums[right] != nums[right + 1]: + right += 1 + + length = right - left + 1 + + count += (length * (length + 1)) // 2 + + right += 1 + left = right + + return count + + # Driver code + if __name__ == "__main__": + sol = Solution() + nums = [1, 0, 1, 0, 1] + print(sol.countAlternatingSubarrays(nums)) # Output: 9 + ``` + + + + ```c + #include + + long long countAlternatingSubarrays(int* nums, int n) { + long long count = 0; + + int left = 0; + int right = 0; + + while (right < n) { + while (right < n - 1 && nums[right] != nums[right + 1]) { + right++; + } + + long long length = right - left + 1; + + count += (length * (length + 1)) / 2; + + right++; + left = right; + } + + return count; + } + + // Driver code + int main() { + int nums[] = {1, 0, 1, 0, 1}; + int n = sizeof(nums) / sizeof(nums[0]); + printf("%lld\n", countAlternatingSubarrays(nums, n)); // Output: 9 + return 0; + } + ``` + + + + +## Complexity + +### Time complexity: $O(n)$ + +The code iterates through the array at most twice (once in the outer loop and potentially once in the inner loop for each element). This results in a linear time complexity of $O(n)$. + +### Space complexity: $O(1)$ + +The code uses a constant amount of extra space for variables like count, left, and right, which doesn't depend on the input size n. diff --git a/solutions/lc-solutions/3100-3199/3102-Minimize Manhattan Distance.md b/solutions/lc-solutions/3100-3199/3102-Minimize Manhattan Distance.md new file mode 100644 index 0000000..e3c0b6c --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3102-Minimize Manhattan Distance.md @@ -0,0 +1,326 @@ +--- +id: Minimize-Manhattan-Distances +title: Minimize Manhattan Distances +level: hard +sidebar_label: 3102-Minimize Manhattan Distances +tags: + - Dynamic Programming + - Bit Manipulation + - C++ + - Java + - Python +description: "This document provides solutions for Minimize Manhattan Distances using dynamic implemented in C++, Java, and Python." +--- + +## Problem Statement + +You are given a array points representing integer coordinates of some points on a 2D plane, where points`[i] = [xi, yi]`. + +The distance between two points is defined as their Manhattan distance. + +Return the minimum possible value for maximum distance between any two points by removing exactly one point. + +**Example 1:** + +Input: points = [[3,10],[5,15],[10,2],[4,4]] +Output: 12 + +Explanation: +The maximum distance after removing each point is the following: + +- After removing the 0th point the maximum distance is between points (5, 15) and (10, 2), which is |5 - 10| + |15 - 2| = 18. + +- After removing the 1st point the maximum distance is between points (3, 10) and (10, 2), which is |3 - 10| + |10 - 2| = 15. + +- After removing the 2nd point the maximum distance is between points (5, 15) and (4, 4), which is |5 - 4| + |15 - 4| = 12. + +- After removing the 3rd point the maximum distance is between points (5, 15) and (10, 2), which is |5 - 10| + |15 - 2| = 18. + +- 12 is the minimum possible maximum distance between any two points after removing exactly one point. + +**Example 2:** + +Input: points = [[1,1],[1,1],[1,1]] +Output: 0 + +Explanation: +Removing any of the points results in the maximum distance between any two points of 0. + +Constraints: +`3 <= points.length <= 105` +`points[i].length == 2` +`1 <= points[i][0], points[i][1] <= 108` + +## Solutions: + +### Approach + +1. Manhattan Distance between any two points `(x1,y1) & (x2,y2)` is: + + `|x1–x2|+|y1–y2|=max(x1–x2-y1+y2,-x1+x2+y1–y2,-x1+x2–y1+y2,x1–x2+y1–y2)` + +2. The above expression can also be formulated as: + `|x1–x2|+|y1–y2|=max((x1–y1)–(x2–y2),(-x1+y1)–(-x2+y2),(-x1–y1)–(-x2–y2),(x1+y1)–(x2+y2))` + +3. From the above expression, it's apparent that the Maximum Manhattan Distance can be determined by storing the sums and differences of the coordinates. + +4. Consider 2 set of pairs st1,st2 where st1 will store the sum of X,Y coordinate along with the index of the point & st2 will store the difference of X,Y coordinates along with the index of the point + +5. Now, iterate over the Points again, & Calculate the sum x + y and difference x - y for the current element. + +6. Check if these calculated sums and differences exist in the sets. If they do, erase them. + +7. To compute the maximum manhattan distance (maxi) after removing each point: + + `maxi=max(maxsum-minsum,maxdiff-mindiff);` + + - Now, find the values of minsum, maxsum, mindiff, maxdiff + + - `minsum=st1.begin(), maxsum=--st1.end()` + + - `mindiff=st2.begin(), maxdiff=--st2.end()` + + `Note:- st.end() denotes an iterator pointing to the position + just after the last element that's why we have taken --st.end()` + + 8. After finding the maximum value upon removal of the current sum and difference, store the minimum computed so far in variable mini which holds the minimum of all Manhattan Distance found so far. + + 9. Add the removed sum and differences to the sets st1 and st2 to consider the next sum and differnce. + + 10. Finally after iterating over all the points return minimum of all computed values. + +## code: + + + + + ```cpp + #include + #include + #include + using namespace std; + + class Solution { + public: + int minimumDistance(vector>& A) { + set> st1, st2; + for (int i = 0; i < A.size(); i++) { + st1.insert({A[i][0] + A[i][1], i}); + st2.insert({A[i][0] - A[i][1], i}); + } + + int mini = INT_MAX; + for (int i = 0; i < A.size(); i++) { + int t1 = A[i][0] + A[i][1]; + int t2 = A[i][0] - A[i][1]; + if (st1.find({t1, i}) != st1.end()) st1.erase({t1, i}); + if (st2.find({t2, i}) != st2.end()) st2.erase({t2, i}); + + int minsum = st1.begin()->first; + int maxsum = (--st1.end())->first; + int mindiff = st2.begin()->first; + int maxdiff = (--st2.end())->first; + int maxi = max(maxsum - minsum, maxdiff - mindiff); + mini = min(mini, maxi); + + st1.insert({t1, i}); + st2.insert({t2, i}); + } + + return mini; + } + }; + ``` + + + + ```java + import java.util.*; + + public class Solution { + public int minimumDistance(List> A) { + Set> st1 = new TreeSet<>(); + Set> st2 = new TreeSet<>(); + for (int i = 0; i < A.size(); i++) { + st1.add(new Pair<>(A.get(i).get(0) + A.get(i).get(1), i)); + st2.add(new Pair<>(A.get(i).get(0) - A.get(i).get(1), i)); + } + + int mini = Integer.MAX_VALUE; + for (int i = 0; i < A.size(); i++) { + int t1 = A.get(i).get(0) + A.get(i).get(1); + int t2 = A.get(i).get(0) - A.get(i).get(1); + st1.remove(new Pair<>(t1, i)); + st2.remove(new Pair<>(t2, i)); + + int minsum = st1.iterator().next().getKey(); + int maxsum = ((TreeSet>) st1).last().getKey(); + int mindiff = st2.iterator().next().getKey(); + int maxdiff = ((TreeSet>) st2).last().getKey(); + int maxi = Math.max(maxsum - minsum, maxdiff - mindiff); + mini = Math.min(mini, maxi); + + st1.add(new Pair<>(t1, i)); + st2.add(new Pair<>(t2, i)); + } + + return mini; + } + } + + class Pair { + private K key; + private V value; + + public Pair(K key, V value) { + this.key = key; + this.value = value; + } + + public K getKey() { + return key; + } + + public V getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Pair pair = (Pair) o; + return Objects.equals(key, pair.key) && Objects.equals(value, pair.value); + } + + @Override + public int hashCode() { + return Objects.hash(key, value); + } + } + ``` + + + + ```python + from typing import List + from sortedcontainers import SortedList + + class Solution: + def minimumDistance(self, A: List[List[int]]) -> int: + st1 = SortedList((x + y, i) for i, (x, y) in enumerate(A)) + st2 = SortedList((x - y, i) for i, (x, y) in enumerate(A)) + + mini = float('inf') + for i, (x, y) in enumerate(A): + t1 = x + y + t2 = x - y + st1.remove((t1, i)) + st2.remove((t2, i)) + + minsum = st1[0][0] + maxsum = st1[-1][0] + mindiff = st2[0][0] + maxdiff = st2[-1][0] + maxi = max(maxsum - minsum, maxdiff - mindiff) + mini = min(mini, maxi) + + st1.add((t1, i)) + st2.add((t2, i)) + + return mini + ``` + + + + ```c + #include + #include + #include + + typedef struct { + int first; + int second; + } Pair; + + int cmpPair(const void *a, const void *b) { + return ((Pair *)a)->first - ((Pair *)b)->first; + } + + int minimumDistance(int A[][2], int n) { + Pair *st1 = (Pair *)malloc(n * sizeof(Pair)); + Pair *st2 = (Pair *)malloc(n * sizeof(Pair)); + for (int i = 0; i < n; i++) { + st1[i].first = A[i][0] + A[i][1]; + st1[i].second = i; + st2[i].first = A[i][0] - A[i][1]; + st2[i].second = i; + } + + qsort(st1, n, sizeof(Pair), cmpPair); + qsort(st2, n, sizeof(Pair), cmpPair); + + int mini = INT_MAX; + for (int i = 0; i < n; i++) { + int t1 = A[i][0] + A[i][1]; + int t2 = A[i][0] - A[i][1]; + int idx1 = -1, idx2 = -1; + for (int j = 0; j < n; j++) { + if (st1[j].second == i) { + idx1 = j; + break; + } + } + for (int j = 0; j < n; j++) { + if (st2[j].second == i) { + idx2 = j; + break; + } + } + for (int j = idx1; j < n - 1; j++) { + st1[j] = st1[j + 1]; + } + for (int j = idx2; j < n - 1; j++) { + st2[j] = st2[j + 1]; + } + + int minsum = st1[0].first; + int maxsum = st1[n - 2].first; + int mindiff = st2[0].first; + int maxdiff = st2[n - 2].first; + int maxi = max(maxsum - minsum, maxdiff - mindiff); + mini = min(mini, maxi); + + for (int j = n - 1; j > idx1; j--) { + st1[j] = st1[j - 1]; + } + for (int j = n - 1; j > idx2; j--) { + st2[j] = st2[j - 1]; + } + st1[idx1].first = t1; + st1[idx1].second = i; + st2[idx2].first = t2; + st2[idx2].second = i; + } + + free(st1); + free(st2); + return mini; + } + + int main() { + int A[][2] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}; + int n = sizeof(A) / sizeof(A[0]); + printf("%d\n", minimumDistance(A, n)); + return 0; + } + ``` + + + + +## Complexity + +Time complexity: $O(nlogn)$ + +Space complexity: $O(n)$ diff --git a/solutions/lc-solutions/3100-3199/3105-Longest Strictly Increasing or Strictly Decreasing Subarray.md b/solutions/lc-solutions/3100-3199/3105-Longest Strictly Increasing or Strictly Decreasing Subarray.md new file mode 100644 index 0000000..e1fcdbe --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3105-Longest Strictly Increasing or Strictly Decreasing Subarray.md @@ -0,0 +1,174 @@ +--- +id: longest-strictly-subarray +title: Longest Strictly Increasing or Strictly Decreasing Subarray +sidebar_label: 3105-LongestStrictlySubarray +tags: + - Array + - Dynamic Programming +description: Return the length of the longest subarray of nums which is either strictly increasing or strictly decreasing. +sidebar_position: 3105 +--- + +## Problem Description + +You are given an array of integers `nums`. Return the length of the longest subarray of `nums` which is either strictly increasing or strictly decreasing. + +### Example 1 + +- **Input:** `nums = [1,4,3,3,2]` +- **Output:** `2` +- **Explanation:** + - The strictly increasing subarrays of nums are [1], [2], [3], [3], [4], and [1,4]. + - The strictly decreasing subarrays of nums are [1], [2], [3], [3], [4], [3,2], and [4,3]. + - Hence, we return 2. + +### Example 2 + +- **Input:** `nums = [3,3,3,3]` +- **Output:** `1` +- **Explanation:** + - The strictly increasing subarrays of nums are [3], [3], [3], and [3]. + - The strictly decreasing subarrays of nums are [3], [3], [3], and [3]. + - Hence, we return 1. + +### Example 3 + +- **Input:** `nums = [3,2,1]` +- **Output:** `3` +- **Explanation:** + - The strictly increasing subarrays of nums are [3], [2], and [1]. + - The strictly decreasing subarrays of nums are [3], [2], [1], [3,2], [2,1], and [3,2,1]. + - Hence, we return 3. + +### Constraints + +- `1 <= nums.length <= 50` +- `1 <= nums[i] <= 50` + +## Approach + +To solve this problem, we can use a dynamic programming approach: + +1. **Dynamic Programming Array**: + - Use two arrays `inc` and `dec` to store the lengths of the longest strictly increasing and strictly decreasing subarrays ending at each index `i` in `nums`. + - Traverse through the array from left to right to populate `inc`. + - Traverse through the array from right to left to populate `dec`. + - The maximum value from `inc` and `dec` arrays will give us the length of the longest subarray that is either strictly increasing or strictly decreasing. + +### Solution Code + +#### Python + +```python +class Solution: + def longestMonotonicSubarray(self, nums: List[int]) -> int: + n = len(nums) + if n <= 1: + return n + + inc = [1] * n # Length of longest strictly increasing subarray ending at index i + dec = [1] * n # Length of longest strictly decreasing subarray ending at index i + + # Fill inc array + for i in range(1, n): + if nums[i] > nums[i - 1]: + inc[i] = inc[i - 1] + 1 + + # Fill dec array + for i in range(n - 2, -1, -1): + if nums[i] > nums[i + 1]: + dec[i] = dec[i + 1] + 1 + + # Find the maximum length of strictly increasing or strictly decreasing subarray + max_len = 1 # At least a single element subarray is valid + for i in range(n): + max_len = max(max_len, inc[i], dec[i]) + + return max_len +``` + +#### C++ + +```c++ +class Solution { +public: + int longestMonotonicSubarray(vector& nums) { + int n = nums.size(); + if (n <= 1) { + return n; + } + + vector inc(n, 1); // Length of longest strictly increasing subarray ending at index i + vector dec(n, 1); // Length of longest strictly decreasing subarray ending at index i + + // Fill inc array + for (int i = 1; i < n; i++) { + if (nums[i] > nums[i - 1]) { + inc[i] = inc[i - 1] + 1; + } + } + + // Fill dec array + for (int i = n - 2; i >= 0; i--) { + if (nums[i] > nums[i + 1]) { + dec[i] = dec[i + 1] + 1; + } + } + + // Find the maximum length of strictly increasing or strictly decreasing subarray + int maxLen = 1; // At least a single element subarray is valid + for (int i = 0; i < n; i++) { + maxLen = max(maxLen, max(inc[i], dec[i])); + } + + return maxLen; + } +}; + +``` + +#### Java + +```java +class Solution { + public int longestMonotonicSubarray(int[] nums) { + int n = nums.length; + if (n <= 1) { + return n; + } + + int[] inc = new int[n]; // Length of longest strictly increasing subarray ending at index i + int[] dec = new int[n]; // Length of longest strictly decreasing subarray ending at index i + + // Fill inc array + Arrays.fill(inc, 1); + for (int i = 1; i < n; i++) { + if (nums[i] > nums[i - 1]) { + inc[i] = inc[i - 1] + 1; + } + } + + // Fill dec array + Arrays.fill(dec, 1); + for (int i = n - 2; i >= 0; i--) { + if (nums[i] > nums[i + 1]) { + dec[i] = dec[i + 1] + 1; + } + } + + // Find the maximum length of strictly increasing or strictly decreasing subarray + int maxLen = 1; // At least a single element subarray is valid + for (int i = 0; i < n; i++) { + maxLen = Math.max(maxLen, Math.max(inc[i], dec[i])); + } + + return maxLen; + } +} + +``` + +### Comclusion +The above solutions use dynamic programming to find the length of the longest subarray in nums that +is either strictly increasing or strictly decreasing. They ensure efficient computation within the +given constraints, providing robust solutions across different inputs. \ No newline at end of file diff --git a/solutions/lc-solutions/3100-3199/3106- Lexicographically Smallest String After Operations With Constraint.md b/solutions/lc-solutions/3100-3199/3106- Lexicographically Smallest String After Operations With Constraint.md new file mode 100644 index 0000000..e7b6bab --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3106- Lexicographically Smallest String After Operations With Constraint.md @@ -0,0 +1,129 @@ +--- +id: Lexicographically-Smallest-String-After-Operations-With-Constraint +title: Lexicographically Smallest String After Operations With Constraint +sidebar_label: 3106. Lexicographically Smallest String After Operations With Constraint +tags: +- Java +- Greedy +- String +description: "This document provides a solution where we Return a string denoting the +lexicographically smallest + string t" +--- + +## Problem + +You are given a string `s` and an integer `k`. + +Define a function `distance(s1, s2)` between two strings `s1` and `s2` of the same length `n` as: + +The **sum** of the **minimum distance** between `s1[i]` and `s2[i]` when the characters from `'a'` to `'z'` are placed in a **cyclic** order, for all `i` in the range `[0, n - 1]`. +For example, `distance("ab", "cd") == 4`, and `distance("a", "z") == 1`. + +You can **change** any letter of `s` to **any** other lowercase English letter, **any** number of times. + +Return a string denoting the +lexicographically smallest +string `t` you can get after some changes, such that `distance(s, t) <= k`. + +### Examples + +**Example 1:** + +**Input:** `s = "zbbz"`, `k = 3` + +**Output:** "aaaz" + +**Explanation:** + +Change s to "aaaz". The distance between "zbbz" and "aaaz" is equal to `k = 3`. + +**Example 2:** + +**Input:** `s = "xaxcd"`, `k = 4` + +**Output:** "aawcd" + +**Explanation:** + +The distance between "xaxcd" and "aawcd" is equal to `k = 4`. + + +### Constraints + +- $1 <= s.length <= 100$ +- $0 <= k <= 2000$ +- `s` consists only of lowercase English letters. + +--- + +## Approach + +## 1. Conversion to Character Array: + +char[] `result = s.toCharArray()`;: This line converts the input string s into a character array named result. This array will hold the modified string. + +## 2. Iterating Through Characters: + +The function uses an outer for loop to iterate through each character i in the original string s. + +## 3. Finding the Best Replacement Character: + +An inner for loop iterates through all lowercase letters `char c = 'a'; c <= 'z'; c++`. + +`Inside the inner loop:` +- **distance(s.charAt(i), c):** +This calculates the distance between the current character s[i] and the candidate replacement character c using a separate distance function (assumed to be defined elsewhere). + +- **if `(distance(s.charAt(i), c) <= k):`** This checks if changing the current character to c is allowed within the k limit based on the distance. + +**If the distance is less than or equal to k:** +- `result[i] = c`;: The character in the result array at position i is updated with the new character c. +- `k -= distance(s.charAt(i), c)`;: The remaining allowed changes (k) are decremented by the distance used for this replacement. +- break;: The inner loop exits as a suitable replacement has been found within the limit. + +## 4. Returning the Modified String: + +return new String(result);: This line converts the modified character array result back into a String object and returns it. + +## Solution + +#### Code in Java + +```java +class Solution { + public int distance(char s1, char s2) { + int diff = Math.abs(s1 - s2); + return Math.min(diff, 26 - diff); + } + public String getSmallestString(String s, int k) { + char[] result = s.toCharArray(); + for (int i = 0; i < s.length(); i++) { + for (char c = 'a'; c <= 'z'; c++) { + if (distance(s.charAt(i), c) <= k) { + result[i] = c; + k -= distance(s.charAt(i), c); + break; + } + } + } + return new String(result); + + } +} +``` + +### Complexity Analysis + +#### Time Complexity: $O(n * k)$ + +> **Reason**: In the worst case, the inner loop runs completely for every character in the outer loop (if all characters need to be replaced). This leads to a total of n * k iterations. + +#### Space Complexity: $O(n)$ + +> **Reason**: The space complexity of the provided code is dominated by the character array result used to store the modified string. + +# References + +- **LeetCode Problem:** [Lexicographically Smallest String After Operations With Constraint](https://leetcode.com/problems/lexicographically-smallest-string-after-operations-with-constraint/description/) +- **Solution Link:** [Lexicographically Smallest String After Operations With Constraint on LeetCode](https://leetcode.com/problems/lexicographically-smallest-string-after-operations-with-constraint/solutions/) diff --git a/solutions/lc-solutions/3100-3199/3107-Minimum-opration-to-make-median-of-array-equal-to-k.md b/solutions/lc-solutions/3100-3199/3107-Minimum-opration-to-make-median-of-array-equal-to-k.md new file mode 100644 index 0000000..f4d4ef7 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3107-Minimum-opration-to-make-median-of-array-equal-to-k.md @@ -0,0 +1,193 @@ +--- +id: Minimum-operation-to-make-median-of-array-equal-to-k +title: Minimum-operation-to-make-median-of-array-equal-to-k +sidebar_label: 3107-Minimum-operation-to-make-median-of-array-equal-to-k +tags: + - Java + - Greedy + - String +description: "This document provides a solution of Minimum-operation-to-make-median-of-array-equal-to-k" +--- + +## Problem statement: + +You are given an integer array nums and a non-negative integer k. In one operation, you can increase or decrease any element by 1. + +Return the minimum number of operations needed to make the median of nums equal to k. + +The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken. + +**Example 1:** + +Input: nums = [2,5,6,8,5], k = 4 +Output: 2 + +Explanation: +We can subtract one from nums[1] and nums[4] to obtain [2, 4, 6, 8, 4]. The median of the resulting array is equal to k. + +**Example 2:** + +Input: nums = [2,5,6,8,5], k = 7 +Output: 3 + +Explanation: +We can add one to nums[1] twice and add one to nums[2] once to obtain [2, 7, 7, 8, 5]. + +**Example 3:** + +Input: nums = [1,2,3,4,5,6], k = 4 +Output: 0 + +Explanation: +The median of the array is already equal to k. + +Constraints: + +`1 <= nums.length <= 2 * 105` +`1 <= nums[i] <= 109` +`1 <= k <= 109` + +## Solutions: + +### Intuition + +-> Plot the intial points and the expected points of the given array on a graph. +-> To find the expected median 'k' the expected graph should coincide with the inital graph. +-> Find minimum number of steps to coincide them. + +### Approach + +consider: nums = [2,5,6,8,5], k = 4 + + ![alt text](image-2.png) + +1. till the n/2th element-> all elements to the left of expected graph should be merged with the expected graph and those on the right wouldn't affect the median so no need to add in answer. + +2. for n/2th element it should be same for both graphs, so take difference and add. + +3. for elements after n/2-> the element to the left of expected graph wouldn't affect the median however those on the right will, so shift them so that they coincide and add the cost of shifting as well. + +### Observation: + +To make both the graphs coincide: + +1. For elements less than the median (i < n / 2): calculate the difference between the current element nums[i] and the target value k. If this difference is positive (i.e., nums[i] is greater than k), add this difference to ans. Otherwise, add 0(already conincided). + +2. For the median element itself (i == n / 2): calculate the absolute difference between the current element nums[i] and k and add it to ans. This ensures that regardless of whether k is greater or smaller than the median, its distance is considered. + +3. For elements greater than the median (i > n / 2): calculate the difference between k and the current element nums[i]. If this difference is positive (i.e., nums[i] is less than k), add this difference to ans. Otherwise, add 0(already coincided). + +## code: + + + + + ```cpp + #include + #include + using namespace std; + + class Solution { + public: + long long minOperationsToMakeMedianK(vector& nums, int k) { + int n = nums.size(); + sort(nums.begin(), nums.end()); + long long ans = 0; + for (int i = 0; i < n; i++) { + if (i < n / 2) + ans += max(0, nums[i] - k); // 1st case + else if (i == n / 2) + ans += abs(nums[i] - k); // 2nd case + else + ans += max(0, k - nums[i]); // 3rd case + } + return ans; + } + }; + ``` + + + + ```java + import java.util.*; + + public class Solution { + public long minOperationsToMakeMedianK(List nums, int k) { + int n = nums.size(); + Collections.sort(nums); + long ans = 0; + for (int i = 0; i < n; i++) { + if (i < n / 2) + ans += Math.max(0, nums.get(i) - k); // 1st case + else if (i == n / 2) + ans += Math.abs(nums.get(i) - k); // 2nd case + else + ans += Math.max(0, k - nums.get(i)); // 3rd case + } + return ans; + } + } + ``` + + + + ```python + from typing import List + + class Solution: + def minOperationsToMakeMedianK(self, nums: List[int], k: int) -> int: + n = len(nums) + nums.sort() + ans = 0 + for i in range(n): + if i < n // 2: + ans += max(0, nums[i] - k) # 1st case + elif i == n // 2: + ans += abs(nums[i] - k) # 2nd case + else: + ans += max(0, k - nums[i]) # 3rd case + return ans + ``` + + + + ```c + #include + #include + #include + + int cmp(const void* a, const void* b) { + return (*(int*)a - *(int*)b); + } + + long long minOperationsToMakeMedianK(int* nums, int numsSize, int k) { + qsort(nums, numsSize, sizeof(int), cmp); + long long ans = 0; + for (int i = 0; i < numsSize; i++) { + if (i < numsSize / 2) + ans += nums[i] > k ? nums[i] - k : 0; // 1st case + else if (i == numsSize / 2) + ans += abs(nums[i] - k); // 2nd case + else + ans += nums[i] < k ? k - nums[i] : 0; // 3rd case + } + return ans; + } + + int main() { + int nums[] = {1, 3, 2, 5, 4}; + int numsSize = sizeof(nums) / sizeof(nums[0]); + int k = 3; + printf("%lld\n", minOperationsToMakeMedianK(nums, numsSize, k)); + return 0; + } + ``` + + + + +## Complexity + +Time complexity: $O(nlogn)$ + +Space complexity: $O(1)$ diff --git a/solutions/lc-solutions/3100-3199/3108-Minimum-cost-walk-in-weighted-graph.md b/solutions/lc-solutions/3100-3199/3108-Minimum-cost-walk-in-weighted-graph.md new file mode 100644 index 0000000..92dcc75 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3108-Minimum-cost-walk-in-weighted-graph.md @@ -0,0 +1,382 @@ +--- +id: Minimum-cost-walk-in-weighted-graph +title: Minimum-cost-walk-in-weighted-graph +sidebar_label: 3108-Minimum-cost-walk-in-weighted-graph +tags: + - Java + - Greedy + - String +description: "This document provides a solution of Minimum-cost-walk-in-weighted-graph" +--- + +## Problem Statement: + +There is an undirected weighted graph with n vertices labeled from 0 to n - 1. + +You are given the integer n and an array edges, where edges[i] = [ui, vi, wi] indicates that there is an edge between vertices ui and vi with a weight of wi. + +A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It's important to note that a walk may visit the same edge or vertex more than once. + +The cost of a walk starting at node u and ending at node v is defined as the bitwise AND of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is w0, w1, w2, ..., wk, then the cost is calculated as w0 & w1 & w2 & ... & wk, where & denotes the bitwise AND operator. + +You are also given a 2D array query, where query[i] = [si, ti]. For each query, you need to find the minimum cost of the walk starting at vertex si and ending at vertex ti. If there exists no such walk, the answer is -1. + +Return the array answer, where answer[i] denotes the minimum cost of a walk for query i. + +**Example 1:** + +Input: n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]] +Output: [1,-1] + +Explanation: + + ![alt text](image-3.png) + +To achieve the cost of 1 in the first query, we need to move on the following edges: 0->1 (weight 7), 1->2 (weight 1), 2->1 (weight 1), 1->3 (weight 7). + +In the second query, there is no walk between nodes 3 and 4, so the answer is -1. + +**Example 2:** + +Input: n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]] +Output: [0] + +Explanation: +![alt text](image-4.png) + +To achieve the cost of 0 in the first query, we need to move on the following edges: 1->2 (weight 1), 2->1 (weight 6), 1->2 (weight 1). + +**Constraints:** + + `2 <= n <= 105` + `0 <= edges.length <= 105` + `edges[i].length == 3` + `0 <= ui, vi <= n - 1` + `ui != vi` + `0 <= wi <= 105` + `1 <= query.length <= 105` + `query[i].length == 2` + `0 <= si, ti <= n - 1` + `si != ti` + +## Solutions: + +### Intuition + +The problem requires finding the minimum cost of a walk in an undirected weighted graph where the cost is defined as the bitwise AND of the weights of the edges traversed during the walk. We need to handle multiple queries for different starting and ending vertices. + +### Approach + + 1. Construct the adjacency list representation of the graph and initialize the cost array c. + + 2. For each edge, update the cost array c by performing bitwise AND with the edge weight. + + 3. Use a breadth-first search (BFS) traversal to find connected components in the graph and update the cost array c for each component. + + 4. For each query, check if the starting and ending vertices belong to the same connected component. If they do, return the minimum cost of the connected component; otherwise, return -1. + +## code: + + + + + ```cpp + #include + #include + #include + using namespace std; + + class Solution { + public: + vector minimumCost(int N, vector>& edges, vector>& queries) { + vector> adj(N); // Adjacency list + vector c(N, INT_MAX); // Cost array, initialized with maximum possible value + + // Construct adjacency list and update cost array + for (vector edge : edges) { + int u = edge[0], v = edge[1], k = edge[2]; + adj[u].push_back(v); + adj[v].push_back(u); + c[u] = c[u] & k; // Update cost with bitwise AND + c[v] = c[v] & k; + } + + // BFS to find connected components and update cost array for each component + queue q; + vector group(N, -1); // Group array to store component group of each vertex + for (int i = 0; i < N; i++) { + if (group[i] == -1) { + group[i] = i; // Assign component group ID + q.push(i); + while (!q.empty()) { + int u = q.front(); q.pop(); + c[i] = c[i] & c[u]; // Update cost with bitwise AND of all vertices in the component + for (int v : adj[u]) { + if (group[v] == -1) { + group[v] = i; + q.push(v); + } + } + } + } + } + + // Process queries + vector res; + for (vector query : queries) { + int s = query[0], t = query[1]; + if (s == t) { + res.push_back(0); // Same starting and ending vertex + } else { + if (group[s] == group[t]) { + res.push_back(c[group[s]]); // Same connected component + } else { + res.push_back(-1); // Different connected components + } + } + } + return res; + } + }; + ``` + + + + ```java + import java.util.*; + + public class Solution { + public List minimumCost(int N, List> edges, List> queries) { + List> adj = new ArrayList<>(N); // Adjacency list + for (int i = 0; i < N; i++) adj.add(new ArrayList<>()); + int[] c = new int[N]; // Cost array, initialized with maximum possible value + Arrays.fill(c, Integer.MAX_VALUE); + + // Construct adjacency list and update cost array + for (List edge : edges) { + int u = edge.get(0), v = edge.get(1), k = edge.get(2); + adj.get(u).add(v); + adj.get(v).add(u); + c[u] &= k; // Update cost with bitwise AND + c[v] &= k; + } + + // BFS to find connected components and update cost array for each component + Queue q = new LinkedList<>(); + int[] group = new int[N]; // Group array to store component group of each vertex + Arrays.fill(group, -1); + for (int i = 0; i < N; i++) { + if (group[i] == -1) { + group[i] = i; // Assign component group ID + q.offer(i); + while (!q.isEmpty()) { + int u = q.poll(); + c[i] &= c[u]; // Update cost with bitwise AND of all vertices in the component + for (int v : adj.get(u)) { + if (group[v] == -1) { + group[v] = i; + q.offer(v); + } + } + } + } + } + + // Process queries + List res = new ArrayList<>(); + for (List query : queries) { + int s = query.get(0), t = query.get(1); + if (s == t) { + res.add(0); // Same starting and ending vertex + } else { + if (group[s] == group[t]) { + res.add(c[group[s]]); // Same connected component + } else { + res.add(-1); // Different connected components + } + } + } + return res; + } + } + ``` + + + + ```python + from typing import List + from collections import deque + + class Solution: + def minimumCost(self, N: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]: + adj = [[] for _ in range(N)] # Adjacency list + c = [float('inf')] * N # Cost array, initialized with maximum possible value + + # Construct adjacency list and update cost array + for u, v, k in edges: + adj[u].append(v) + adj[v].append(u) + c[u] &= k # Update cost with bitwise AND + c[v] &= k + + # BFS to find connected components and update cost array for each component + q = deque() + group = [-1] * N # Group array to store component group of each vertex + for i in range(N): + if group[i] == -1: + group[i] = i # Assign component group ID + q.append(i) + while q: + u = q.popleft() + c[i] &= c[u] # Update cost with bitwise AND of all vertices in the component + for v in adj[u]: + if group[v] == -1: + group[v] = i + q.append(v) + + # Process queries + res = [] + for s, t in queries: + if s == t: + res.append(0) # Same starting and ending vertex + else: + if group[s] == group[t]: + res.append(c[group[s]]) # Same connected component + else: + res.append(-1) # Different connected components + return res + ``` + + + + ```c + #include + #include + #include + #include + #include + + typedef struct { + int* data; + int front; + int rear; + int size; + int capacity; + } Queue; + + Queue* createQueue(int capacity) { + Queue* queue = (Queue*)malloc(sizeof(Queue)); + queue->capacity = capacity; + queue->front = queue->size = 0; + queue->rear = capacity - 1; + queue->data = (int*)malloc(queue->capacity * sizeof(int)); + return queue; + } + + bool isFull(Queue* queue) { + return (queue->size == queue->capacity); + } + + bool isEmpty(Queue* queue) { + return (queue->size == 0); + } + + void enqueue(Queue* queue, int item) { + if (isFull(queue)) + return; + queue->rear = (queue->rear + 1) % queue->capacity; + queue->data[queue->rear] = item; + queue->size = queue->size + 1; + } + + int dequeue(Queue* queue) { + if (isEmpty(queue)) + return INT_MIN; + int item = queue->data[queue->front]; + queue->front = (queue->front + 1) % queue->capacity; + queue->size = queue->size - 1; + return item; + } + + int* minimumCost(int N, int edges[][3], int edgesSize, int** queries, int queriesSize, int* queriesColSize, int* returnSize) { + int* adj[N]; + int adjSize[N]; + int* c = (int*)malloc(N * sizeof(int)); + int* group = (int*)malloc(N * sizeof(int)); + int* res = (int*)malloc(queriesSize * sizeof(int)); + *returnSize = queriesSize; + + for (int i = 0; i < N; i++) { + adj[i] = (int*)malloc(N * sizeof(int)); + adjSize[i] = 0; + c[i] = INT_MAX; + group[i] = -1; + } + + // Construct adjacency list and update cost array + for (int i = 0; i < edgesSize; i++) { + int u = edges[i][0], v = edges[i][1], k = edges[i][2]; + adj[u][adjSize[u]++] = v; + adj[v][adjSize[v]++] = u; + c[u] &= k; + c[v] &= k; + } + + // BFS to find connected components and update cost array for each component + Queue* q = createQueue(N); + for (int i = 0; i < N; i++) { + if (group[i] == -1) { + group[i] = i; + enqueue(q, i); + while (!isEmpty(q)) { + int u = dequeue(q); + c[i] &= c[u]; + for (int j = 0; j < adjSize[u]; j++) { + int v = adj[u][j]; + if (group[v] == -1) { + group[v] = i; + enqueue(q, v); + } + } + } + } + } + + // Process queries + for (int i = 0; i < queriesSize; i++) { + int s = queries[i][0], t = queries[i][1]; + if (s == t) { + res[i] = 0; + } else { + if (group[s] == group[t]) { + res[i] = c[group[s]]; + } else { + res[i] = -1; + } + } + } + + return res; + } + ``` + + + + +## Complexity + +**Time complexity:** + + 1. Constructing the adjacency list: $O(E)$, where E is the number of edges. + 2. BFS traversal: $O(V + E)$, where V is the number of vertices. + 3. Processing queries: $O(Q)$, where `Q` is the number of queries. + 4. Overall time complexity: $O(V + E + Q)$. + +**Space complexity:** + + 1. Space for the adjacency list: $O(E)$. + 2. Space for the cost array c: $O(V)$. + 3. Space for the queue and group array during BFS: $O(V)$. + 4. Overall space complexity: $O(V + E)$. + + diff --git a/solutions/lc-solutions/3100-3199/3109- Find the Index of Permutation.md b/solutions/lc-solutions/3100-3199/3109- Find the Index of Permutation.md new file mode 100644 index 0000000..7fb86cb --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3109- Find the Index of Permutation.md @@ -0,0 +1,141 @@ +--- +id: find-the-index-of-permutation +title: 3109-Find the Index of Permutation +sidebar_label: 3109 Find the Index of Permutation +tags: + - Array + - Maths + - LeetCode + - C++ +description: "This is a solution to the Find the Index of Permutation problem on LeetCode." +--- + +## Problem Description + +Given an array perm of length n which is a permutation of [1, 2, ..., n], return the index of perm in the lexicographically sorted array of all of the permutations of [1, 2, ..., n]. + +Since the answer may be very large, return it modulo 109 + 7. + +### Examples + +**Example 1:** + +``` +Input: s = "cbadabacg", p = "abc" +Output: 0 +Explanation: The first occurrence of a permutation of "abc" is "cba" which starts at index 0. + +``` + +**Example 2:** + +``` +Input: s = "eidbaooo", p = "ab" +Output: 3 +Explanation: The first occurrence of a permutation of "ab" is "ba" which starts at index 3. + +``` + +### Constraints + +- `1 <= n == perm.length <= 105` + +### Approach + +According to the problem requirements, we need to find out how many permutations are lexicographically smaller than the given permutation. + +We consider how to calculate the number of permutations that are lexicographically smaller than the given permutation. There are two situations: + +- The first element of the permutation is less than $perm[0]$, there are $(perm[0] - 1) \times (n-1)!$ permutations. +- The first element of the permutation is equal to $perm[0]$, we need to continue to consider the second element, and so on. +- The sum of all situations is the answer. + +We can use a binary indexed tree to maintain the number of elements that are smaller than the current element in the traversed elements. For the $i$-th element of the given permutation, the number of remaining elements that are smaller than it is $perm[i] - 1 - tree.query(perm[i])$, and the number of permutation types is $(perm[i] - 1 - tree.query(perm[i])) \times (n-i-1)!$, which is added to the answer. Then we update the binary indexed tree and add the current element to the binary indexed tree. Continue to traverse the next element until all elements are traversed. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the permutation. + +#### Python3 + +```python +class BinaryIndexedTree: + __slots__ = "n", "c" + + def __init__(self, n: int): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x: int, delta: int) -> None: + while x <= self.n: + self.c[x] += delta + x += x & -x + + def query(self, x: int) -> int: + s = 0 + while x: + s += self.c[x] + x -= x & -x + return s + + +class Solution: + def getPermutationIndex(self, perm: List[int]) -> int: + mod = 10**9 + 7 + ans, n = 0, len(perm) + tree = BinaryIndexedTree(n + 1) + f = [1] * n + for i in range(1, n): + f[i] = f[i - 1] * i % mod + for i, x in enumerate(perm): + cnt = x - 1 - tree.query(x) + ans += cnt * f[n - i - 1] % mod + tree.update(x, 1) + return ans % mod +``` + +#### Java + +```java +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + this.c = new int[n + 1]; + } + + public void update(int x, int delta) { + for (; x <= n; x += x & -x) { + c[x] += delta; + } + } + + public int query(int x) { + int s = 0; + for (; x > 0; x -= x & -x) { + s += c[x]; + } + return s; + } +} + +class Solution { + public int getPermutationIndex(int[] perm) { + final int mod = (int) 1e9 + 7; + long ans = 0; + int n = perm.length; + BinaryIndexedTree tree = new BinaryIndexedTree(n + 1); + long[] f = new long[n]; + f[0] = 1; + for (int i = 1; i < n; ++i) { + f[i] = f[i - 1] * i % mod; + } + for (int i = 0; i < n; ++i) { + int cnt = perm[i] - 1 - tree.query(perm[i]); + ans = (ans + cnt * f[n - i - 1] % mod) % mod; + tree.update(perm[i], 1); + } + return (int) ans; + } +} +``` diff --git a/solutions/lc-solutions/3100-3199/3110-score-of-a-string.md b/solutions/lc-solutions/3100-3199/3110-score-of-a-string.md new file mode 100644 index 0000000..7a2328f --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3110-score-of-a-string.md @@ -0,0 +1,182 @@ +--- +id: score-of-a-string +title: Score of a string +sidebar_label: 3110 - Score of a string + + +description: "This is a solution to the Two Score of a string on LeetCode." +--- + +In this page, we will solve the LeetCode Problem 3110, titled `Score of a String`, using three different approaches: brute force, sliding window, and optimized iteration technique. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. + +## Problem Description + +You are given a string `s`. The **score** of a string is defined as the sum of the absolute difference between the **ASCII** values of adjacent characters. + +### Examples + +**Example 1:** + +```plaintext +Input: s = "hello" +Output: 13 +``` + +**Example 2:** + +```plaintext +Input: "zaz" +Output: 50 +``` + + +### Constraints + +- `2 <= s.length <= 100` +- `s` consists only of lowercase English letters. + + +--- + +## Solution for Two Sum Problem + +### Intuition and Approach + + +To solve the problem, `Score of a String`, we can use a straightforward approach where you iterate through the string and calculate the absolute difference between the ASCII values of adjacent characters, then sum these differences. This approach is efficient and straightforward. Below is a step-by-step approach: + + + + +### Approach 1: Brute Force (Naive) + +The brute force approach for the `Score of a String` problem is straightforward. We iterate through each character `s[i]` of the string s and compute the absolute difference with the next character `s[i + 1]`. We then sum these differences to get the total score of the string. + +#### Implementation + +```jsx live +function scoreOfStringProblem() { + const s = "hello"; // Example input string + const scoreOfString = function (s) { + let score = 0; + for (let i = 0; i < s.length - 1; i++) { + score += Math.abs(s.charCodeAt(i) - s.charCodeAt(i + 1)); + } + return score; + }; + + const result = scoreOfString(s); + return ( +
+

+ Input: s = "{s}" +

+

+ Output: {result} +

+
+ ); +} + +``` + +#### Codes in Different Languages + + + + + ```javascript + function scoreOfString(s) { + let score = 0; + for (let i = 0; i < s.length - 1; i++) { + score += Math.abs(s.charCodeAt(i) - s.charCodeAt(i + 1)); + } + return score; +} + ``` + + + + + ```typescript + function scoreOfString(s: string): number { + let score = 0; + for (let i = 0; i < s.length - 1; i++) { + score += Math.abs(s.charCodeAt(i) - s.charCodeAt(i + 1)); + } + return score; +} + ``` + + + + + ```python + class Solution: + def score_of_string(s): + score = 0 + for i in range(len(s) - 1): + score += abs(ord(s[i]) - ord(s[i + 1])) + return score + ``` + + + + + ```java + class Solution { + public int scoreOfString(String s) { + int score = 0; + for (int i = 0; i < s.length() - 1; i++) { + score += Math.abs(s.charAt(i) - s.charAt(i + 1)); + } + return score; + } + + } + ``` + + + + + ```cpp + class Solution { + public: + int scoreOfString(const std::string& s) { + int score = 0; + for (size_t i = 0; i < s.length() - 1; ++i) { + score += std::abs(s[i] - s[i + 1]); + } + return score; +} + }; + ``` + + + + +#### Complexity Analysis + +- Time Complexity: O(n) +- Space Complexity : O(n) +- Where `n` is the length of the input string `s`. +- The time complexity is 𝑂(𝑛) because we are iterating through the string once. +- The space complexity is 𝑂(1) because we are not using any extra space beyond a few variables. +- This approach is efficient and can handle large input strings effectively. + + +
+ + +
+ +:::tip Note + + +To efficiently calculate the score of a string based on the absolute differences between adjacent characters, you can iterate through the string once and accumulate the differences. This approach ensures that you compute the score in linear time, O(n), where n is the length of the string. Avoiding nested loops or unnecessary computations will lead to a more efficient solution. + +::: + +## References + +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/score-of-a-string/) diff --git a/solutions/lc-solutions/3100-3199/3111-Minimum-rectangle-to-cover-point.md b/solutions/lc-solutions/3100-3199/3111-Minimum-rectangle-to-cover-point.md new file mode 100644 index 0000000..161f57a --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3111-Minimum-rectangle-to-cover-point.md @@ -0,0 +1,149 @@ +--- +id: minimum-rectangle-to-cover-point +title: minimum-rectangle-to-cover-point +sidebar_label: 3111-minimum-rectangle-to-cover-point +tags: + - Java + - Greedy + - String +description: "This document provides a solution of minimum-rectangle-to-cover-point" +--- + +## Problem statement: + +You are given a 2D integer array points, where `points[i] = [xi, yi]`. You are also given an integer w. Your task is to cover all the given points with rectangles. + +Each rectangle has its lower end at some point `(x1, 0)` and its upper end at some point `(x2, y2)`, where `x1 <= x2`, `y2 >= 0`, and the condition `x2 - x1 <= w` must be satisfied for each rectangle. + +A point is considered covered by a rectangle if it lies within or on the boundary of the rectangle. + +Return an integer denoting the minimum number of rectangles needed so that each point is covered by at least one rectangle. + +Note: A point may be covered by more than one rectangle. + +**Example 1:** +![alt text](image-3.png) + +Input: points = [[2,1],[1,0],[1,4],[1,8],[3,5],[4,6]], w = 1 +Output: 2 + +Explanation: +The image above shows one possible placement of rectangles to cover the points: + +`A rectangle with a lower end at (1, 0) and its upper end at (2, 8)` +`A rectangle with a lower end at (3, 0) and its upper end at (4, 8)` + +**Example 2:** +![alt text](image-4.png) + +Input: points = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6]], w = 2 +Output: 3 + +Explanation: +The image above shows one possible placement of rectangles to cover the points: + +`A rectangle with a lower end at (0, 0) and its upper end at (2, 2)` +`A rectangle with a lower end at (3, 0) and its upper end at (5, 5)` +`A rectangle with a lower end at (6, 0) and its upper end at (6, 6)` + +**Example 3:** +![alt text](image-5.png) + +Input: points = [[2,3],[1,2]], w = 0 +Output: 2 + +Explanation: +The image above shows one possible placement of rectangles to cover the points: + +`A rectangle with a lower end at (1, 0) and its upper end at (1, 2)` +`A rectangle with a lower end at (2, 0) and its upper end at (2, 3)` + +**Constraints:** + + -`1 <= points.length <= 105` + -`points[i].length == 2` + -`0 <= xi == points[i][0] <= 109` + -`0 <= yi == points[i][1] <= 109` + -`0 <= w <= 109` + -`All pairs (xi, yi) are distinct.` + +## Solutions: + +### Binary search Approch: + +**Intuition** +Consider only the x-coordinates. Sorting them, then use binary search to find the index which is the beginning for the next cover + +**Approach** 1. Set array x 2. Sort x 3. Use while loop to proceed the binary searching (C++ upper_bound) for the beginning index for the next cover + +```cpp + class Solution { + public: + int minRectanglesToCoverPoints(vector>& points, int w) { + int n=points.size(); + vector x(n,-1); + for(int i=0; i>& points, int w) { + + + map mp; + + for(auto point : points) { + mp[point[0]]++; + } + + auto it = mp.begin(); + int prev = it->first; + + int count = 0; + + for(auto it : mp) { + if(it.first - prev > w) { + count++; + prev = it.first; + } + } + + return count+1; + + + } +}; +``` + +**Complexity** + +Time complexity: $O(nlogn)$ diff --git a/solutions/lc-solutions/3100-3199/3115.maximum-prime-difference.md b/solutions/lc-solutions/3100-3199/3115.maximum-prime-difference.md new file mode 100644 index 0000000..b16af44 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3115.maximum-prime-difference.md @@ -0,0 +1,321 @@ +--- +id: maximum-prime-difference +title: 3115. Maximum Prime Difference +sidebar_label: 3115. Maximum Prime Difference + + +tags: +- Array +- Math +- Number Theory + +description: "This is a solution to the 3115. Maximum Prime Difference + problem on LeetCode." +--- + +## Problem Description +You are given an integer array nums. + +Return an integer that is the maximum distance between the indices of two (not necessarily different) prime numbers in nums. +### Examples +**Example 1:** + +``` +Input: nums = [4,2,9,5,3] + +Output: 3 + +Explanation: nums[1], nums[3], and nums[4] are prime. So the answer is |4 - 1| = 3. + +``` + +**Example 2:** +``` +Input: nums = [4,8,2,8] + +Output: 0 + +Explanation: nums[2] is prime. Because there is just one prime number, the answer is |2 - 2| = 0. + + +``` + +### Constraints +- `1 <= nums.length <= 3 * 10^5` +- `1 <= nums[i] <= 100` +- `The input is generated such that the number of prime numbers in the nums is at least one.` + +## Solution for3115. Maximum Prime Difference +## 1. Sieve of Eratosthenes +- Use the Sieve of Eratosthenes to generate a list of prime numbers up to the maximum number in the array. + +## 2. Find Prime Indices +- Iterate through the array and record the indices of all prime numbers. + +## 3. Calculate Maximum Difference +- Sort the list of indices and find the difference between the maximum and minimum indices. + +## Detailed Steps in Code + +1. **Sieve of Eratosthenes**: + - Initialize a boolean array `prime` where `prime[i]` indicates whether `i` is a prime number. + - Set all values in `prime` to `true`, except for `prime[0]` and `prime[1]` which are set to `false`. + - For each number `p` from 2 to the square root of `n`, mark all multiples of `p` as `false`. + +2. **Find Prime Indices**: + - Iterate through the array `nums` and store the indices of prime numbers in a list `p`. + +3. **Calculate Maximum Difference**: + - Sort the list `p` of indices. + - The maximum difference is the difference between the last and first elements in the sorted list `p`. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function SieveOfEratosthenes(n) { + let prime = Array(n + 1).fill(true); + prime[0] = prime[1] = false; + + for (let p = 2; p * p <= n; p++) { + if (prime[p]) { + for (let i = p * p; i <= n; i += p) { + prime[i] = false; + } + } + } + + return prime; + } + + function maximumPrimeDifference(nums) { + let maxi = Math.max(...nums); + let prime = SieveOfEratosthenes(maxi); + let p = []; + + for (let i = 0; i < nums.length; i++) { + if (prime[nums[i]]) { + p.push(i); + } + } + + p.sort((a, b) => a - b); + + return p[p.length - 1] - p[0]; + } + + const input = [4,2,9,5,3] + const output = maximumPrimeDifference(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(nlogn) $ + - Space Complexity: $ O(n)$ + + ## Code in Different Languages + + + + ```javascript + function SieveOfEratosthenes(n) { + let prime = Array(n + 1).fill(true); + prime[0] = prime[1] = false; + + for (let p = 2; p * p <= n; p++) { + if (prime[p]) { + for (let i = p * p; i <= n; i += p) { + prime[i] = false; + } + } + } + + return prime; +} + +function maximumPrimeDifference(nums) { + let maxi = Math.max(...nums); + let prime = SieveOfEratosthenes(maxi); + let p = []; + + for (let i = 0; i < nums.length; i++) { + if (prime[nums[i]]) { + p.push(i); + } + } + + p.sort((a, b) => a - b); + + return p[p.length - 1] - p[0]; +} + + + ``` + + + + + ```typescript + function SieveOfEratosthenes(n: number): boolean[] { + let prime: boolean[] = Array(n + 1).fill(true); + prime[0] = prime[1] = false; + + for (let p = 2; p * p <= n; p++) { + if (prime[p]) { + for (let i = p * p; i <= n; i += p) { + prime[i] = false; + } + } + } + + return prime; +} + +function maximumPrimeDifference(nums: number[]): number { + let maxi: number = Math.max(...nums); + let prime: boolean[] = SieveOfEratosthenes(maxi); + let p: number[] = []; + + for (let i = 0; i < nums.length; i++) { + if (prime[nums[i]]) { + p.push(i); + } + } + + p.sort((a, b) => a - b); + + return p[p.length - 1] - p[0]; +} + + ``` + + + + ```python + class Solution: + def __init__(self): + self.prime = [True] * 1000001 + + def SieveOfEratosthenes(self, n: int) -> None: + self.prime[0] = self.prime[1] = False + + for p in range(2, int(n**0.5) + 1): + if self.prime[p]: + for i in range(p * p, n + 1, p): + self.prime[i] = False + + def maximumPrimeDifference(self, nums: List[int]) -> int: + maxi = max(nums) + self.SieveOfEratosthenes(maxi) + p = [] + + for i in range(len(nums)): + if self.prime[nums[i]]: + p.append(i) + + p.sort() + + return p[-1] - p[0] + + + ``` + + + + + ```java + import java.util.*; + +class Solution { + boolean[] prime = new boolean[1000001]; + + void SieveOfEratosthenes(int n) { + Arrays.fill(prime, true); + prime[0] = prime[1] = false; + + for (int p = 2; p * p <= n; p++) { + if (prime[p]) { + for (int i = p * p; i <= n; i += p) { + prime[i] = false; + } + } + } + } + + public int maximumPrimeDifference(int[] nums) { + int maxi = Arrays.stream(nums).max().orElse(0); + SieveOfEratosthenes(maxi); + List p = new ArrayList<>(); + + for (int i = 0; i < nums.length; i++) { + if (prime[nums[i]]) { + p.add(i); + } + } + + Collections.sort(p); + + return p.get(p.size() - 1) - p.get(0); + } +} + + ``` + + + + + ```cpp +class Solution { +public: + bool prime[1000001]; + void SieveOfEratosthenes(int n) { + memset(prime, true, sizeof(prime)); + prime[0] = prime[1] = false; + for (int p = 2; p * p <= n; p++) { + if (prime[p] == true) { + for (int i = p * p; i <= n; i += p) + prime[i] = false; + } + } + } + int maximumPrimeDifference(vector& nums) { + int maxi = *max_element(nums.begin(), nums.end()); + SieveOfEratosthenes(maxi); + vector p; + for (int i = 0; i < nums.size(); i++) { + if (prime[nums[i]]) { + p.push_back(i); + } + } + sort(p.begin(), p.end()); + return p[p.size() - 1] - p[0]; + } +}; + + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [2348. Number of Zero-Filled Subarrays](https://leetcode.com/problems/maximum-prime-difference/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/maximum-prime-difference/) + diff --git a/solutions/lc-solutions/3100-3199/3116 - Kth Smallest Amount With Single Denomination Combination.md b/solutions/lc-solutions/3100-3199/3116 - Kth Smallest Amount With Single Denomination Combination.md new file mode 100644 index 0000000..be2ce35 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3116 - Kth Smallest Amount With Single Denomination Combination.md @@ -0,0 +1,137 @@ +--- +id: Kth-smallest-amount-with-single-denomination-combination +title: Kth Smallest Amount With Single Denomination Combination +sidebar_label: 3116 Kth Smallest Amount With Single Denomination Combination +tags: +- Java +- Math +- Array +- Binary Search +- Bit Manipulation +- Combinatorics +- Number Theory +description: "This document provides a solution where we Return the $k^th$ smallest amount that can be made using these coins." +--- + +## Problem + +You are given an integer array $coins$ representing coins of different denominations and an integer $k$. + +You have an infinite number of coins of each denomination. However, you are **not allowed** to combine coins of different denominations. + +Return the $k^{\text{th}}$ smallest amount that can be made using these coins. + +### Examples + +**Example 1:** + +``` +Input: coins = [3,6,9], k = 3 + +Output: 9 + +Explanation: The given coins can make the following amounts: +Coin 3 produces multiples of 3: 3, 6, 9, 12, 15, etc. +Coin 6 produces multiples of 6: 6, 12, 18, 24, etc. +Coin 9 produces multiples of 9: 9, 18, 27, 36, etc. +All of the coins combined produce: 3, 6, 9, 12, 15, etc. + +``` +**Example 2:** + +``` +Input: coins = [5,2], k = 7 + +Output: 12 + +Explanation: The given coins can make the following amounts: +Coin 5 produces multiples of 5: 5, 10, 15, 20, etc. +Coin 2 produces multiples of 2: 2, 4, 6, 8, 10, 12, etc. +All of the coins combined produce: 2, 4, 5, 6, 8, 10, 12, 14, 15, etc. + +``` + +### Constraints + +- $1 <= coins.length <= 15$ +- $1 <= coins[i] <= 25$ +- $1 <= k <= 2 * 10^9$ +- $coins$ contains pairwise distinct integers. +--- + +## Approach + +To solve the problem, we need to understand the nature of the allowed moves: + +1. **Binary Search Initialization**: + + - The main function **'findKthSmallest'** initializes a binary search range (**'left'** and **'right'**). + + - The left bound starts from **'k'** and the right bound is set to a large number (**'50000000000L'**) to encompass the possible values. + +2. **Binary Search Execution**: + + - The binary search iteratively narrows down the range. + + - For each midpoint value (**'mid'**), it calculates how many values up to **'mid'** can be formed using the given coins using the helper function **'findKthSmallest'**. + +3. **Counting Function (findKthSmallest)**: + + - This recursive function employs the inclusion-exclusion principle to count how many numbers up to **'k'** can be formed using the multiples of the coins: + + - The function considers each coin and its combinations recursively. + + - It uses the greatest common divisor (GCD) to avoid counting duplicate values. + + - Depending on whether the current subset of coins being considered has an odd or even number of elements, it either adds or subtracts from the count. + +4. **Updating the Search Range**: + + - Based on the count returned by the helper function, the binary search range (left and right) is updated until convergence. + +## Solution for Kth Smallest Amount With Single Denomination Combination + +- The goal is to find the k-th smallest amount that can be made using the given coins without combining different denominations. + +- It uses a binary search approach combined with a mathematical method (inclusion-exclusion principle) to efficiently determine the k-th smallest amount. + +#### Code in Java + +```java +import java.math.BigInteger; + +class Solution { + public long findKthSmallest(int[] coins, int k) { + long left = k, right = 50000000000L; + while (left < right) { + long mid = (left + right) / 2; + if (findKthSmallest(coins, mid, 1, 0, 0) < k) { + left = mid + 1; + } else { + right = mid; + } + } + return left; + } + + private long findKthSmallest(int[] coins, long k, long v, int index, int flag) { + return index < coins.length ? findKthSmallest(coins, k, v, index + 1, flag) + findKthSmallest(coins, k, v * coins[index] / BigInteger.valueOf(v).gcd(BigInteger.valueOf(coins[index])).longValue(), index + 1, flag + 1) : flag > 0 ? flag % 2 > 0 ? k / v : -k / v : 0; + } +} +``` + +### Complexity Analysis + +#### Time Complexity: $O(2^n log n)$ + +> **Reason**: The binary search operates in $O(log n)$. And The inclusion-exclusion calculation involves iterating through subsets of coins, resulting in $O(2^n)$ complexity for the recursive function where n is the number of coins. Overall Time Complexity is $O(2^n log n)$ + +#### Space Complexity: $O(2^n)$ + +> **Reason**: The space complexity is $O(2^n)$, Because as it uses The primary space usage comes from the recursion stack of the helper function. + +# References + +- **LeetCode Problem:** [Kth Smallest Amount With Single Denomination Combination](https://leetcode.com/problems/kth-smallest-amount-with-single-denomination-combination/description/) +- **Solution Link:** [Kth Smallest Amount With Single Denomination Combination Solution on LeetCode](https://leetcode.com/problems/kth-smallest-amount-with-single-denomination-combination/solutions/) +- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/vivekvardhan43862/) diff --git a/solutions/lc-solutions/3100-3199/3131-Find-The-Integer-Added-To-Array-1.md b/solutions/lc-solutions/3100-3199/3131-Find-The-Integer-Added-To-Array-1.md new file mode 100644 index 0000000..84d7404 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3131-Find-The-Integer-Added-To-Array-1.md @@ -0,0 +1,129 @@ +--- +id: find-integer-added-to-array +title: Find the Integer Added to Array I (LeetCode) +sidebar_label: 3131-FindIntegerAddedToArray +tags: + - Array + - Math +description: Given two arrays of equal length, nums1 and nums2, find the integer that has been added to each element of nums1 to obtain nums2. +sidebar_position: 3131 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Find the Integer Added to Array I](https://leetcode.com/problems/find-the-integer-added-to-array-i/) | [Find the Integer Added to Array I Solution on LeetCode](https://leetcode.com/problems/find-the-integer-added-to-array-i/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) | + +## Problem Description + +You are given two arrays of equal length, `nums1` and `nums2`. + +Each element in `nums1` has been increased (or decreased in the case of negative) by an integer, represented by the variable `x`. + +As a result, `nums1` becomes equal to `nums2`. Two arrays are considered equal when they contain the same integers with the same frequencies. + +Return the integer `x`. + +### Example 1 + +- **Input:** `nums1 = [2, 6, 4], nums2 = [9, 7, 5]` +- **Output:** `3` +- **Explanation:** The integer added to each element of `nums1` is `3`. + +### Example 2 + +- **Input:** `nums1 = [10], nums2 = [5]` +- **Output:** `-5` +- **Explanation:** The integer added to each element of `nums1` is `-5`. + +### Example 3 + +- **Input:** `nums1 = [1, 1, 1, 1], nums2 = [1, 1, 1, 1]` +- **Output:** `0` +- **Explanation:** The integer added to each element of `nums1` is `0`. + +### Constraints + +- `1 <= nums1.length == nums2.length <= 100` +- `0 <= nums1[i], nums2[i] <= 1000` +- The test cases are generated in a way that there is an integer `x` such that `nums1` can become equal to `nums2` by adding `x` to each element of `nums1`. + +## Approach + +To find the integer `x` that was added to each element of `nums1` to obtain `nums2`, we can use the following approach: + +1. Iterate through the arrays `nums1` and `nums2`. +2. Calculate the difference `x` for the first pair of elements from `nums1` and `nums2`. +3. Ensure that the calculated `x` is consistent for all elements. + +### Solution Code + +#### Python + +```python +def find_integer_added_to_array(nums1, nums2): + if len(nums1) != len(nums2): + return None # Inconsistent input lengths + + x = nums2[0] - nums1[0] + + for i in range(1, len(nums1)): + if nums2[i] - nums1[i] != x: + return None # Inconsistent difference found + + return x +``` + +#### C++ + +```c++ +#include +#include +using namespace std; + +class Solution { +public: + int findIntegerAddedToArray(vector& nums1, vector& nums2) { + if (nums1.size() != nums2.size()) { + return INT_MIN; // Inconsistent input lengths + } + + int x = nums2[0] - nums1[0]; + + for (size_t i = 1; i < nums1.size(); ++i) { + if (nums2[i] - nums1[i] != x) { + return INT_MIN; // Inconsistent difference found + } + } + + return x; + } +}; + +``` + +#### Java + +```java +class Solution { + public Integer findIntegerAddedToArray(int[] nums1, int[] nums2) { + if (nums1.length != nums2.length) { + return null; // Inconsistent input lengths + } + + int x = nums2[0] - nums1[0]; + + for (int i = 1; i < nums1.length; i++) { + if (nums2[i] - nums1[i] != x) { + return null; // Inconsistent difference found + } + } + + return x; + } +``` +#### Conclusion +The above solutions determine the integer x that was added to each element of nums1 to obtain nums2. +By ensuring consistency across the entire array, we validate the difference and return the result. +Adjustments for different languages and edge cases ensure robustness across various inputs. diff --git a/solutions/lc-solutions/3100-3199/3139 - Minimum Cost to Equalize Array.md b/solutions/lc-solutions/3100-3199/3139 - Minimum Cost to Equalize Array.md new file mode 100644 index 0000000..ef92c4d --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3139 - Minimum Cost to Equalize Array.md @@ -0,0 +1,175 @@ +--- +id: minimum-cost-to-equalize-array +title: Minimum Cost to Equalize Array +sidebar_label: 3139 Minimum Cost to Equalize Array +tags: +- Java +- Array +- Greedy +- Enumeration +description: "This document provides a solution where we Return the minimum cost required to make all elements in the array equal." +--- + +## Problem + +You are given an integer array $nums$ and two integers $cost1$ and $cost2$. You are allowed to perform either of the following operations any number of times: + +- Choose an index $i$ from nums and increase $nums[i]$ by $1$ for a cost of $cost1$. + +- Choose two different indices $i$, $j$, from nums and increase $nums[i]$ and $nums[j]$ by $1$ for a cost of $cost2$. + +### Examples + +**Example 1:** + +``` +Input: nums = [4,1], cost1 = 5, cost2 = 2 + +Output: 15 + +Explanation: + +The following operations can be performed to make the values equal: + +Increase nums[1] by 1 for a cost of 5. nums becomes [4,2]. + +Increase nums[1] by 1 for a cost of 5. nums becomes [4,3]. + +Increase nums[1] by 1 for a cost of 5. nums becomes [4,4]. + +The total cost is 15. +``` + +**Example 2:** + +``` +Input: nums = [2,3,3,3,5], cost1 = 2, cost2 = 1 + +Output: 6 + +Explanation: + +The following operations can be performed to make the values equal: + +Increase nums[0] and nums[1] by 1 for a cost of 1. nums becomes [3,4,3,3,5]. + +Increase nums[0] and nums[2] by 1 for a cost of 1. nums becomes [4,4,4,3,5]. + +Increase nums[0] and nums[3] by 1 for a cost of 1. nums becomes [5,4,4,4,5]. + +Increase nums[1] and nums[2] by 1 for a cost of 1. nums becomes [5,5,5,4,5]. + +Increase nums[3] by 1 for a cost of 2. nums becomes [5,5,5,5,5] + +The total cost is 6. +``` + +**Example 3:** + +``` +Input: nums = [3,5,3], cost1 = 1, cost2 = 3 + +Output: 4 + +Explanation: + +The following operations can be performed to make the values equal: + +Increase nums[0] by 1 for a cost of 1. nums becomes [4,5,3]. + +Increase nums[0] by 1 for a cost of 1. nums becomes [5,5,3]. + +Increase nums[2] by 1 for a cost of 1. nums becomes [5,5,4]. + +Increase nums[2] by 1 for a cost of 1. nums becomes [5,5,5]. + +The total cost is 4. +``` + +### Constraints + +- $1 <= nums.length <= 10^5$ +- $1 <= nums[i] <= 10^6$ +- $1 <= cost1 <= 10^6$ +- $1 <= cost2 <= 10^6$ +--- + +## Approach + +To solve the problem, we need to understand the nature of the allowed moves: + +1. **Initial Checks**: + + - If **'cost1$ * 2 <= $cost2'** or the array length is less than 3, always using the single increment operation is more efficient because the double increment operation is not cost-effective or there aren't enough elements to pair up effectively. + +2. **Target Value Calculation**: + + - Calculate the total sum of the array. + + - Determine the range of possible target values. The target values are from the current maximum element to just below twice the maximum element. This ensures we consider a broad enough range to find the minimal cost. + +3. **Gap Calculation**: + + - For each potential target value, compute the total gap, which is the sum of the differences between the target and each element in the array. + + - Calculate the maximum possible gap for a single element in the array, given the current minimum element. + +4. **Cost Calculation**: + + - Determine the number of pairs that can be used efficiently without exceeding the total gap. + + - Calculate the minimal cost using a combination of single and double increment operations. + +5. **Optimization**: + + - Iterate through possible target values to find the minimal cost and return it modulo $10^9$ + 7. + +## Solution for Minimum Cost to Equalize Array + +The problem involves to minimize the total cost of increasing elements, compare the efficiency of using single increments at cost1 versus double increments at cost2. Use double increments whenever cost2 is less than twice cost1 for cost-effectiveness. + +#### Code in Java + +```java +class Solution { + public int minCostToEqualizeArray(int[] nums, int cost1, int cost2) { + final int kMod = 1_000_000_007; + final int n = nums.length; + final int minNum = Arrays.stream(nums).min().getAsInt(); + final int maxNum = Arrays.stream(nums).max().getAsInt(); + final long sum = Arrays.stream(nums).asLongStream().sum(); + long ans = Long.MAX_VALUE; + + if (cost1 * 2 <= cost2 || n < 3) { + final long totalGap = 1L * maxNum * n - sum; + return (int) ((cost1 * totalGap) % kMod); + } + + for (int target = maxNum; target < 2 * maxNum; ++target) { + final int maxGap = target - minNum; + final long totalGap = 1L * target * n - sum; + final long pairs = Math.min(totalGap / 2, totalGap - maxGap); + ans = Math.min(ans, cost1 * (totalGap - 2 * pairs) + cost2 * pairs); + } + + return (int) (ans % kMod); + } +} + +``` + +### Complexity Analysis + +#### Time Complexity: $O(n)$ + +> **Reason**: For Finding the minimum, maximum, and sum of the array takes $O(𝑛)$. + +#### Space Complexity: $O(1)$ + +> **Reason**: The space complexity is $O(1)$ since we only use a constant amount of extra space beyond the input array. + +# References + +- **LeetCode Problem:** [Minimum Cost to Equalize Array](https://leetcode.com/problems/minimum-cost-to-equalize-array/description/) +- **Solution Link:** [Minimum Cost to Equalize Array Solution on LeetCode](https://leetcode.com/problems/minimum-cost-to-equalize-array/solutions/) +- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/vivekvardhan43862/) diff --git a/solutions/lc-solutions/3100-3199/3143 - Maximum Points Inside the Square.md b/solutions/lc-solutions/3100-3199/3143 - Maximum Points Inside the Square.md new file mode 100644 index 0000000..91ca272 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3143 - Maximum Points Inside the Square.md @@ -0,0 +1,158 @@ +--- +id: maximum-points-inside-square +title: Maximum Points Inside the Square (LeetCode) +sidebar_label: 3143-MaximumPointsInsideSquare +tags: + - Dynamic Programming + - Geometry + - Sorting + - Sliding Window +description: Given an array of points in the XY-plane, find the maximum number of points that can be inside a square with side length K. +sidebar_position: 3143 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :---------------- | :------------ | :--------------- | +| [Maximum Points Inside Square](https://leetcode.com/problems/maximum-points-inside-square/) | [Maximum Points Inside Square Solution on LeetCode](https://leetcode.com/problems/maximum-points-inside-square/solutions/) | [vaishu_1904](https://leetcode.com/vaishu_1904/) | + +## Problem Description + +Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer K, return the maximum number of points inside a square of side length K that can be formed with any of the points. + +### Example 1 + +- **Input:** `points = [[1,3],[1,4],[-1,0],[4,1],[0,3],[4,4],[1,0],[1,1],[1,2],[2,2],[3,0],[2,-1],[0,1],[1,-1],[2,0]], K = 2` +- **Output:** `4` +- **Explanation:** The maximum number of points inside a square of side length 2 is 4, as shown in the image below. + + +### Example 2 + +- **Input:** `points = [[0,1],[2,1],[1,2],[1,0],[2,2]], K = 2` +- **Output:** `1` +- **Explanation:** Only 1 square can be formed with side length 2. + +### Constraints + +- `1 <= points.length <= 1000` +- `points[i].length == 2` +- `-10^4 <= xi, yi <= 10^4` +- `1 <= K <= 10^4` + +## Approach + +To solve this problem efficiently, we can use a combination of sorting and sliding window techniques: + +1. **Sorting**: Sort the points based on their X and Y coordinates. +2. **Sliding Window**: Use a sliding window of size K to check how many points can fit inside a square of side length K at any given position. + +### Detailed Steps + +- **Sorting**: Sort points primarily by X coordinates and secondarily by Y coordinates. +- **Sliding Window**: + - Traverse through the sorted list of points. + - For each point, consider it as the top-left corner of a square. + - Use a sliding window to count how many points lie within the square of side length K formed with the current point as the top-left corner. + - Update the maximum count of points inside any such square encountered. + +### Solution Code + +#### Python + +```python +class Solution: + def maxPointsInsideSquare(self, points: List[List[int]], s: str) -> int: + minLens = {} + secondMin = float('inf') + + for point, char in zip(points, s): + size = max(abs(point[0]), abs(point[1])) + + if char not in minLens: + minLens[char] = size + elif size < minLens[char]: + secondMin = min(minLens[char], secondMin) + minLens[char] = size + else: + secondMin = min(size, secondMin) + + count = 0 + for len in minLens.values(): + if len < secondMin: + count += 1 + + return count +``` + +#### C++ + +```c++ +class Solution { +public: + int maxPointsInsideSquare(vector>& points, string s) { + unordered_map minLens; + int secondMin = INT_MAX, count = 0; + + for(size_t i = 0; i < points.size(); ++i) { + int len = max(abs(points[i][0]), abs(points[i][1])); + char c = s[i]; + + if(minLens.find(c) == minLens.end()) { + minLens[c] = len; + } else if(len < minLens[c]) { + secondMin = min(secondMin, minLens[c]); + minLens[c] = len; + } else { + secondMin = min(secondMin, len); + } + } + + for(auto& pair : minLens) { + if(pair.second < secondMin) { + count++; + } + } + + return count; + } +}; +``` + +#### Java +```java +class Solution { + public int maxPointsInsideSquare(int[][] points, String s) { + HashMap minLens = new HashMap<>(); + int secondMin = Integer.MAX_VALUE, count = 0; + + for (int i = 0; i < points.length; ++i) { + int len = Math.max(Math.abs(points[i][0]), Math.abs(points[i][1])); + char c = s.charAt(i); + + if (!minLens.containsKey(c)) { + minLens.put(c, len); + } else if (len < minLens.get(c)) { + secondMin = Math.min(minLens.get(c), secondMin); + minLens.put(c, len); + } else { + secondMin = Math.min(len, secondMin); + } + } + + for(int len : minLens.values()) { + if(len < secondMin) { + count++; + } + } + + return count; + } +} +``` + +### Conclusion +The solutions provided utilize sorting and a sliding window approach to efficiently determine the +maximum number of points that can be inside a square of side length K. These solutions ensure +correctness and handle edge cases within the given constraints effectively. \ No newline at end of file diff --git a/solutions/lc-solutions/3100-3199/3144-minimum-substring-partition-of-equal-character-frequency.md b/solutions/lc-solutions/3100-3199/3144-minimum-substring-partition-of-equal-character-frequency.md new file mode 100644 index 0000000..14bde01 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3144-minimum-substring-partition-of-equal-character-frequency.md @@ -0,0 +1,252 @@ +--- +id: minimum-substring-partition-of-equal-charater-frequency +title: Minimum-substring-partition-of-equal-charater-frequency (LeetCode) +sidebar_label: 3144-minimum-substring-partition-of-equal-charater-frequency +tags: + - Dynamic Programming + - Geometry + - Sorting + - Sliding Window +description: this discription is for the solution of minimum-substring-partition-of-equal-charater-frequency +sidebar_position: 3144 +--- + +## Problem Satement + +Given a string s, you need to partition it into one or more balanced +substrings +Substring +A substring is a contiguous sequence of characters within a string. + +. For example, if `s == "ababcc"` then `("abab", "c", "c")`, `("ab", "abc", "c")`, and `("ababcc")` are all valid partitions, but `("a", "bab", "cc")`, `("aba", "bc", "c")`, and `("ab", "abcc")` are not. The unbalanced substrings are bolded. + +Return the minimum number of substrings that you can partition s into. + +Note: A balanced string is a string where each character in the string occurs the same number of times. + +**Example 1:** + +Input: s = "fabccddg" +Output: 3 + +Explanation: +We can partition the string s into 3 substrings in one of the following ways: ("fab, "ccdd", "g"), or ("fabc", "cd", "dg"). + +**Example 2:** + +Input: s = "abababaccddb" +Output: 2 + +Explanation: +We can partition the string s into 2 substrings like so: ("abab", "abaccddb"). + +**Constraints:** + + - `1 <= s.length <= 1000` + - `s consists only of English lowercase letters.` + +## Solutions: + +### Intuition + +The problem requires partitioning a string such that each substring is balanced. A substring is balanced if each character appears with the same frequency within that substring. The challenge is to minimize the number of these substrings. This problem can be addressed by understanding the distribution of character frequencies and leveraging dynamic programming to minimize partitions while ensuring that each segment conforms to the balanced condition. + +### Approach + + - **Character Frequency Calculation:** + - Calculate the maximum frequency for each character in the entire string. This will help determine if a substring can potentially be balanced, as every character in a balanced substring must appear at least as many times as its maximum frequency across the string. + + - **Dynamic Programming Initialization:** + - Use a DP array dp where dp[i] represents the minimum number of partitions needed for the first i characters of the string. Initialize dp[0] to 0 because no partitions are needed for an empty string. + + - **Sliding Window for Substrings:** + - For each position i in the string, consider every possible substring ending at i and starting from any j (where j ranges from 1 to i). This forms a sliding window from j to i. + + - For each window, maintain a frequency count of characters and determine the maximum frequency in the current window. + + - **Validation and DP Update:** + - Validate each window by checking if all characters that appear have the frequency equal to the maximum frequency observed in that window. If the substring formed by the window is balanced, then update dp[i] to be the minimum of its current value or dp[j-1] + 1. + + - This ensures that dp[i] reflects the minimum partitions up to i including possibly ending a new balanced substring at i. + + - **Result Extraction:** + - After processing all characters, dp[length of string] contains the minimum number of partitions for the entire string. + +## code: + + + + + ```cpp + public: + int minimumSubstringsInPartition(string s) { + vector maxFrequency(26, 0); + for (char ch : s) { + maxFrequency[ch - 'a']++; + } + + vector dp(s.length() + 1, INT_MAX); + dp[0] = 0; // Base case: no characters, no partitions needed + + for (int i = 1; i <= s.length(); i++) { + vector freq(26, 0); + int maxInWindow = 0; + + for (int j = i; j > 0; j--) { + int index = s[j - 1] - 'a'; + freq[index]++; + maxInWindow = max(maxInWindow, freq[index]); + + bool valid = true; + for (int k = 0; k < 26; k++) { + if (freq[k] > 0 && freq[k] < maxInWindow) { + valid = false; + break; + } + } + + if (valid) { + dp[i] = min(dp[i], dp[j - 1] + 1); + } + } + } + return dp[s.length()]; + } + ``` + + + + ```java + public int minimumSubstringsInPartition(String s) { + // Initialize an array to store the maximum frequency of each character + int[] maxFrequency = new int[26]; // Array to hold maximum frequency of each character 'a' to 'z' + for (int i = 0; i < s.length(); i++) { + maxFrequency[s.charAt(i) - 'a']++; // Increment frequency of character at position i + } + + // dp[i] represents the minimum number of partitions needed for the first i characters + int[] dp = new int[s.length() + 1]; // Array to hold the minimum partitions needed for each prefix of s + dp[0] = 0; // Base case: no characters, no partitions needed + + for (int i = 1; i <= s.length(); i++) { + dp[i] = Integer.MAX_VALUE; // Initialize dp[i] with a large number + int[] freq = new int[26]; // Array to keep track of character frequencies in the current window + int maxInWindow = 0; // Variable to store the maximum frequency in the current window + + // Check all substrings that end at position i + for (int j = i; j > 0; j--) { + char c = s.charAt(j - 1); // Get character in the string at position j-1 + freq[c - 'a']++; // Increment frequency of that character in the current window + maxInWindow = Math.max(maxInWindow, freq[c - 'a']); // Update maxInWindow if current frequency is higher + + // Check if the current window can form a balanced substring + boolean isValid = true; // Flag to check if the window is valid + for (int k = 0; k < 26; k++) { + if (freq[k] > 0 && freq[k] < maxInWindow) { + isValid = false; // Set valid to false if any character frequency is less than maxInWindow + break; // Exit the loop as the substring is not valid + } + } + + if (isValid) { // If the window is valid + dp[i] = Math.min(dp[i], dp[j - 1] + 1); // Update dp[i] with the minimum partitions found + } + } + } + return dp[s.length()]; // Return the minimum number of partitions for the entire string + } + ``` + + + + ```python + def minimumSubstringsInPartition(self, s): + # Initialize an array to store the maximum frequency of each character + max_frequency = [0] * 26 + for char in s: + max_frequency[ord(char) - ord('a')] += 1 + + # dp[i] represents the minimum number of partitions needed for the first i characters + dp = [float('inf')] * (len(s) + 1) + dp[0] = 0 # Base case: no characters, no partitions needed + + for i in range(1, len(s) + 1): + freq = [0] * 26 + max_in_window = 0 + + # Check all substrings that end at position i + for j in range(i, 0, -1): + index = ord(s[j - 1]) - ord('a') + freq[index] += 1 + max_in_window = max(max_in_window, freq[index]) + + # Check if the current window can form a balanced substring + valid = True + for k in range(26): + if freq[k] > 0 and freq[k] < max_in_window: + valid = False + break + + if valid: + dp[i] = min(dp[i], dp[j - 1] + 1) + + return dp[len(s)] + ``` + + + + ```c + int minimumSubstringsInPartition(char* s) { + int len = strlen(s); + int maxFrequency[26] = {0}, dp[len + 1], freq[26], i, j, k, maxInWindow; + for (i = 0; s[i]; i++) { + maxFrequency[s[i] - 'a']++; + } + + dp[0] = 0; // Base case + for (i = 1; i <= len; i++) { + dp[i] = INT_MAX; + memset(freq, 0, sizeof(freq)); + maxInWindow = 0; + + for (j = i; j > 0; j--) { + char c = s[j - 1]; + freq[c - 'a']++; + if (freq[c - 'a'] > maxInWindow) maxInWindow = freq[c - 'a']; + + int valid = 1; + for (k = 0; k < 26; k++) { + if (freq[k] > 0 && freq[k] < maxInWindow) { + valid = 0; + break; + } + } + + if (valid) { + if (dp[j - 1] + 1 < dp[i]) dp[i] = dp[j - 1] + 1; + } + } + } + + return dp[len]; + + } + ``` + + + + + +## Complexity + +**Time complexity:** $O(n^3)$ - The solution involves three nested loops: The outermost loop runs for each character i in the string. For each i, the middle loop considers every possible starting point j for substrings ending at i, and the innermost loop iterates through all 26 characters to ensure the substring from j to i is balanced. + + -This results in a time complexity proportional to `n^2` multiplied by a constant factor (26), simplifying to $O(n^3)$. + +**Space complexity:** $O(n + 26)$ + + - $O(n)$ for the dynamic programming array dp which stores the minimum partitions for each substring ending at each position. + + - $O(26)$ (constant space) for the frequency array used in each sliding window to keep track of character counts. This part is constant since the number of characters (English lowercase letters) does not scale with n. + +This algorithm efficiently handles smaller strings and provides a clear method to determine minimal partitions, but it might be computationally intensive for very large strings due to its cubic time complexity. diff --git a/solutions/lc-solutions/3100-3199/3145-find-product-of-element-of-big-array.md b/solutions/lc-solutions/3100-3199/3145-find-product-of-element-of-big-array.md new file mode 100644 index 0000000..1633b38 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3145-find-product-of-element-of-big-array.md @@ -0,0 +1,540 @@ +--- +id: find-product-of-element-of-big-array +title: Find Product Of Element Of Big Array (LeetCode) +sidebar_label: 3145-find-product-of-element-of-big-array +tags: + - Dynamic Programming + - Geometry + - Sorting + - Sliding Window +description: this discription is for the solution of find-product-of-element-of-big-array +sidebar_position: 3145 +--- + +## Problem Statement: + +A powerful array for an integer `x` is the shortest sorted array of powers of two that sum up to `x`. For example, the powerful array for 11 is `[1, 2, 8]`. + +The array big_nums is created by concatenating the powerful arrays for every positive integer i in ascending order: 1, 2, 3, and so forth. Thus, big_nums starts as `[1, 2, 1, 2, 4, 1, 4, 2, 4, 1, 2, 4, 8, ...]`. + +You are given a 2D integer matrix `queries`, where for `queries[i] = [fromi, toi, modi]` you should calculate `(big_nums[fromi] * big_nums[fromi + 1] * ... * big_nums[toi])` `%` `modi`. + +Return an integer array answer such that `answer[i]` is the answer to the `ith` query. + +**Example 1:** + +Input: queries = [[1,3,7]] +Output: [4] + +Explanation: +There is one query. +big_nums[1..3] = [2,1,2]. The product of them is 4. The remainder of 4 under 7 is 4. + +**Example 2:** + +Input: queries = [[2,5,3],[7,7,4]] +Output: [2,2] + +Explanation: +There are two queries. +First query: big_nums[2..5] = [1,2,4,1]. The product of them is 8. The remainder of 8 under 3 is 2. +Second query: big_nums[7] = 2. The remainder of 2 under 4 is 2. + +**Constraints:** + + - `1 <= queries.length <= 500` + - `queries[i].length == 3` + - `0 <= queries[i][0] <= queries[i][1] <= 1015` + - `1 <= queries[i][2] <= 105` + +## Solutions: + +### Intuition + +The problem requires finding products of elements within a certain range modulo a given number. To efficiently solve this problem, we can use dynamic programming to calculate the number of bits required to represent a number, perform binary search to find the maximum number within a given range, and calculate the summation of bits within the range. + +## Approach + +**Dynamic Programming for Number of Bits:** + + Utilize dynamic programming to calculate the number of bits required to represent a number. + Store the calculated number of bits for each number in a map to avoid redundant computations. + +**Binary Search for Maximum Number:** + + Perform a binary search to find the maximum number within a given range. + Utilize the previously calculated number of bits to determine if a number falls within the range. + +**Summation of Bits:** + + Calculate the summation of bits within a given range. + Iterate through each bit position, calculating the contribution of ones in complete blocks and any remaining bits. + +**Main Function to Compute Result:** + + Combine the above calculations to compute the final result for a given range. + Calculate the sum of bits within the range and adjust for any remaining bits. + +**Power Function and Modular Arithmetic:** + + Compute the result for each query using the previously defined functions. + Utilize a power function to efficiently compute powers modulo the given number. + +## code: + + + + + ```cpp + #include + #include + using namespace std; + + class Solution { + private: + unordered_map dp; + + long long power(long long n, long long expo, long long mod) { + long long ans = 1; + while (expo) { + if (expo % 2) + ans = ans * n % mod; + n = n * n % mod; + expo /= 2; + } + return ans; + } + + long long getNumBits(long long n) { + if (n == 0) + return 0; + + if (dp.count(n)) + return dp[n]; + + long long ans = 0, num = n + 1; + for (int i = 60; i >= 0; i--) + if ((1LL << i) < num) { + ans = getNumBits((1LL << i) - 1); + long long rem = num - (1LL << i); + ans += getNumBits(rem - 1) + rem; + break; + } + return dp[n] = ans; + } + + long long getMaxNum(long long n) { + long long left = 1, right = 1e15, ans = 0; + while (left <= right) { + long long mid = (left + right) / 2; + long long placesOccupied = getNumBits(mid); + if (placesOccupied <= n) + ans = mid, left = mid + 1; + else + right = mid - 1; + } + return ans; + } + + long long getSum(long long n) { + long long res = 0; + for (int i = 1; i < 50; i++) { + long long blockSize = (1LL << (i + 1)); + long long onesInBlock = blockSize / 2; + long long completeBlocks = n / blockSize; + res += completeBlocks * onesInBlock * i; + long long rem = n % blockSize; + res += max(0LL, rem + 1 - onesInBlock) * i; + } + return res; + } + + long long func(long long n) { + if (n == 0) + return 0; + + long long maxNum = getMaxNum(n); + long long placesOccupied = getNumBits(maxNum); + long long ans = getSum(maxNum); + maxNum++; + long long rem = n - placesOccupied; + for (int i = 0; rem > 0; i++) + if (maxNum & (1LL << i)) { + rem--; + ans += i; + } + return ans; + } + + int solve(vector &query) { + long long L = query[0], R = query[1], mod = query[2]; + return power(2, func(R + 1) - func(L), mod) % mod; + } + public: + vector findProductsOfElements(vector>& queries) { + vector res; + for (auto q: queries) + res.push_back(solve(q)); + return res; + } + }; + ``` + + + + ```java + import java.util.*; + + public class Solution { + private Map dp = new HashMap<>(); + + private long power(long n, long expo, long mod) { + long ans = 1; + while (expo > 0) { + if (expo % 2 != 0) + ans = ans * n % mod; + n = n * n % mod; + expo /= 2; + } + return ans; + } + + private long getNumBits(long n) { + if (n == 0) + return 0; + + if (dp.containsKey(n)) + return dp.get(n); + + long ans = 0; + long num = n + 1; + for (int i = 60; i >= 0; i--) { + if ((1L << i) < num) { + ans = getNumBits((1L << i) - 1); + long rem = num - (1L << i); + ans += getNumBits(rem - 1) + rem; + break; + } + } + dp.put(n, ans); + return ans; + } + + private long getMaxNum(long n) { + long left = 1, right = (long) 1e15, ans = 0; + while (left <= right) { + long mid = (left + right) / 2; + long placesOccupied = getNumBits(mid); + if (placesOccupied <= n) { + ans = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return ans; + } + + private long getSum(long n) { + long res = 0; + for (int i = 1; i < 50; i++) { + long blockSize = (1L << (i + 1)); + long onesInBlock = blockSize / 2; + long completeBlocks = n / blockSize; + res += completeBlocks * onesInBlock * i; + long rem = n % blockSize; + res += Math.max(0, rem + 1 - onesInBlock) * i; + } + return res; + } + + private long func(long n) { + if (n == 0) + return 0; + + long maxNum = getMaxNum(n); + long placesOccupied = getNumBits(maxNum); + long ans = getSum(maxNum); + maxNum++; + long rem = n - placesOccupied; + for (int i = 0; rem > 0; i++) { + if ((maxNum & (1L << i)) != 0) { + rem--; + ans += i; + } + } + return ans; + } + + private int solve(List query) { + long L = query.get(0), R = query.get(1), mod = query.get(2); + return (int) (power(2, func(R + 1) - func(L), mod) % mod); + } + + public List findProductsOfElements(List> queries) { + List res = new ArrayList<>(); + for (List q : queries) { + res.add(solve(q)); + } + return res; + } + } + ``` + + + + ```python + from typing import List + from collections import defaultdict + + class Solution: + def __init__(self): + self.dp = defaultdict(int) + + def power(self, n: int, expo: int, mod: int) -> int: + ans = 1 + while expo: + if expo % 2: + ans = ans * n % mod + n = n * n % mod + expo //= 2 + return ans + + def get_num_bits(self, n: int) -> int: + if n == 0: + return 0 + + if n in self.dp: + return self.dp[n] + + ans = 0 + num = n + 1 + for i in range(60, -1, -1): + if (1 << i) < num: + ans = self.get_num_bits((1 << i) - 1) + rem = num - (1 << i) + ans += self.get_num_bits(rem - 1) + rem + break + self.dp[n] = ans + return ans + + def get_max_num(self, n: int) -> int: + left, right, ans = 1, int(1e15), 0 + while left <= right: + mid = (left + right) // 2 + places_occupied = self.get_num_bits(mid) + if places_occupied <= n: + ans = mid + left = mid + 1 + else: + right = mid - 1 + return ans + + def get_sum(self, n: int) -> int: + res = 0 + for i in range(1, 50): + block_size = (1 << (i + 1)) + ones_in_block = block_size // 2 + complete_blocks = n // block_size + res += complete_blocks * ones_in_block * i + rem = n % block_size + res += max(0, rem + 1 - ones_in_block) * i + return res + + def func(self, n: int) -> int: + if n == 0: + return 0 + + max_num = self.get_max_num(n) + places_occupied = self.get_num_bits(max_num) + ans = self.get_sum(max_num) + max_num += 1 + rem = n - places_occupied + for i in range(50): + if rem <= 0: + break + if max_num & (1 << i): + rem -= 1 + ans += i + return ans + + def solve(self, query: List[int]) -> int: + L, R, mod = query + return self.power(2, self.func(R + 1) - self.func(L), mod) % mod + + def findProductsOfElements(self, queries: List[List[int]]) -> List[int]: + res = [] + for q in queries: + res.append(self.solve(q)) + return res + ``` + + + + ```c + #include + #include + #include + #include + + typedef struct { + long long key; + long long value; + } HashNode; + + typedef struct { + HashNode *nodes; + int size; + int capacity; + } HashMap; + + HashMap* createHashMap(int capacity) { + HashMap *map = (HashMap *)malloc(sizeof(HashMap)); + map->nodes = (HashNode *)malloc(capacity * sizeof(HashNode)); + map->size = 0; + map->capacity = capacity; + return map; + } + + void put(HashMap *map, long long key, long long value) { + for (int i = 0; i < map->size; i++) { + if (map->nodes[i].key == key) { + map->nodes[i].value = value; + return; + } + } + if (map->size == map->capacity) { + map->capacity *= 2; + map->nodes = (HashNode *)realloc(map->nodes, map->capacity * sizeof(HashNode)); + } + map->nodes[map->size].key = key; + map->nodes[map->size].value = value; + map->size++; + } + + int get(HashMap *map, long long key, long long *value) { + for (int i = 0; i < map->size; i++) { + if (map->nodes[i].key == key) { + *value = map->nodes[i].value; + return 1; + } + } + return 0; + } + + long long power(long long n, long long expo, long long mod) { + long long ans = 1; + while (expo) { + if (expo % 2) + ans = ans * n % mod; + n = n * n % mod; + expo /= 2; + } + return ans; + } + + long long getNumBits(HashMap *dp, long long n) { + if (n == 0) + return 0; + + long long value; + if (get(dp, n, &value)) + return value; + + long long ans = 0, num = n + 1; + for (int i = 60; i >= 0; i--) { + if ((1LL << i) < num) { + ans = getNumBits(dp, (1LL << i) - 1); + long long rem = num - (1LL << i); + ans += getNumBits(dp, rem - 1) + rem; + break; + } + } + put(dp, n, ans); + return ans; + } + + long long getMaxNum(HashMap *dp, long long n) { + long long left = 1, right = 1e15, ans = 0; + while (left <= right) { + long long mid = (left + right) / 2; + long long placesOccupied = getNumBits(dp, mid); + if (placesOccupied <= n) { + ans = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return ans; + } + + long long getSum(long long n) { + long long res = 0; + for (int i = 1; i < 50; i++) { + long long blockSize = (1LL << (i + 1)); + long long onesInBlock = blockSize / 2; + long long completeBlocks = n / blockSize; + res += completeBlocks * onesInBlock * i; + long long rem = n % blockSize; + res += (rem + 1 > onesInBlock ? rem + 1 - onesInBlock : 0) * i; + } + return res; + } + + long long func(HashMap *dp, long long n) { + if (n == 0) + return 0; + + long long maxNum = getMaxNum(dp, n); + long long placesOccupied = getNumBits(dp, maxNum); + long long ans = getSum(maxNum); + maxNum++; + long long rem = n - placesOccupied; + for (int i = 0; rem > 0; i++) { + if (maxNum & (1LL << i)) { + rem--; + ans += i; + } + } + return ans; + } + + int solve(HashMap *dp, long long L, long long R, long long mod) { + return power(2, func(dp, R + 1) - func(dp, L), mod) % mod; + } + + int* findProductsOfElements(int N, long long** queries, int queriesSize, int* queriesColSize, int* returnSize) { + int* res = (int*)malloc(queriesSize * sizeof(int)); + *returnSize = queriesSize; + HashMap *dp = createHashMap(100); + + for (int i = 0; i < queriesSize; i++) { + res[i] = solve(dp, queries[i][0], queries[i][1], queries[i][2]); + } + + free(dp->nodes); + free(dp); + return res; + } + ``` + + + + +## Complexity: + +**Time complexity:** +$O(QlogN)$, where Q is the number of queries and N is the maximum number in the queries. + +**Space complexity:** +$O(logN)$, due to dynamic programming and additional space for storing intermediate results. + +## Video lecture + + diff --git a/solutions/lc-solutions/3100-3199/3146-permutation-difference-between-two-string.md b/solutions/lc-solutions/3100-3199/3146-permutation-difference-between-two-string.md new file mode 100644 index 0000000..45167ed --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3146-permutation-difference-between-two-string.md @@ -0,0 +1,211 @@ +--- +id: permutation-difference-between-two-string +title: Permutation-Difference-Between-Two-String (LeetCode) +sidebar_label: 3146-permutation-difference-between-two-string +tags: + - Dynamic Programming + - Geometry + - Sorting + - Sliding Window +description: this discription is for the solution of permutation-difference-between-two-string +sidebar_position: 3146 +--- + +## Problem Statement: + +You are given two strings `s` and `t` such that every character occurs at most once in `s` and `t` is a permutation of `s`. + +The permutation difference between `s` and `t` is defined as the sum of the absolute difference between the index of the occurrence of each character in `s` and the index of the occurrence of the same character in `t`. + +Return the permutation difference between `s` and `t`. + +**Example 1:** + +Input: s = "abc", t = "bac" +Output: 2 + +Explanation: + +1. For `s = "abc"` and `t = "bac"`, the permutation difference of `s` and `t` is equal to the sum of: + +2. The absolute difference between the index of the occurrence of "a" in `s` and the index of the occurrence of "a" in `t`. + +3. The absolute difference between the index of the occurrence of "b" in `s` and the index of the occurrence of "b" in `t``. + +4. The absolute difference between the index of the occurrence of "c" in `s` and the index of the occurrence of "c" in `t`. + +5. That is, the permutation difference between s and t is equal to `|0 - 1| + |2 - 2| + |1 - 0| = 2`. + +**Example 2:** + +Input: s = "abcde", t = "edbac" +Output: 12 + +Explanation: The permutation difference between s and t is equal to `|0 - 3| + |1 - 2| + |2 - 4| + |3 - 1| + |4 - 0| = 12.` + +**Constraints:** + + `1 <= s.length <= 26` + `Each character occurs at most once in s`. + `t is a permutation of s.` + `s consists only of lowercase English letters.` + +## Solutions: + +### Intuition + +To solve this problem, we need to determine the **"distance"** between the characters of the string t in terms of their positions in the string s. Specifically, for each character in t, we calculate the absolute difference between its position in s and its position in t, and then sum up these differences. + +### Approach + +**Initialization:** Start with a variable sum to accumulate the total difference. + +**Iteration:** Loop through each character in the string t. + +**Calculation:** +a. Find the index of the current character in the string s. +b. Calculate the absolute difference between this index and the current index in t. +c. Add this difference to the sum. + +**Return Result:** After processing all characters, return the accumulated sum. + +## code: + + + + + ```typescript + function findPermutationDifference(s: string, t: string): number { + let sum: number = 0; + for (let i = 0; i < t.length; i++) { + sum += Math.abs(s.indexOf(t.charAt(i)) - i); + } + return sum; + } + ``` + + + + ```java + public class Solution { + public int findPermutationDifference(String s, String t) { + int sum = 0; + for (int i = 0; i < t.length(); i++) { + sum += Math.abs(s.indexOf(t.charAt(i)) - i); + } + return sum; + } + } + ``` + + + + ```python + class Solution: + def findPermutationDifference(self, s: str, t: str) -> int: + sum_diff = 0 + for i in range(len(t)): + sum_diff += abs(s.index(t[i]) - i) + return sum_diff + ``` + + + + ```csharp + public class Solution { + public int FindPermutationDifference(string s, string t) { + int sum = 0; + for (int i = 0; i < t.Length; i++) { + sum += Math.Abs(s.IndexOf(t[i]) - i); + } + return sum; + } + } + ``` + + + + ```cpp + #include + #include + + class Solution { + public: + int findPermutationDifference(const std::string& s, const std::string& t) { + int sum = 0; + for (int i = 0; i < t.size(); ++i) { + sum += std::abs(s.find(t[i]) - i); + } + return sum; + } + }; + ``` + + + + ```go + package main + + import ( + "math" + "strings" + ) + + func findPermutationDifference(s string, t string) int { + sum := 0 + for i := 0; i < len(t); i++ { + sum += int(math.Abs(float64(strings.IndexByte(s, t[i]) - i))) + } + return sum + } + ``` + + + + ```rust + pub fn find_permutation_difference(s: &str, t: &str) -> i32 { + let mut sum = 0; + for (i, c) in t.chars().enumerate() { + sum += (s.find(c).unwrap() as i32 - i as i32).abs(); + } + sum + } + ``` + + + + ```c + #include + #include + #include + #include + + int findPermutationDifference(char* s, char* t) { + int sum = 0; + for (int i = 0; i < strlen(t); i++) { + char* pos = strchr(s, t[i]); + if (pos) { + sum += abs((int)(pos - s) - i); + } + } + return sum; + } + ``` + + + + +## Complexity + +**Time complexity:** $O(nβˆ—m)$ ,where n is the length of t and m is the average length to search in s. + +**Space complexity:** The space complexity is $O(1)$, since we are only using a constant amount of extra space for the variable sum. + +## video lecture: + + diff --git a/solutions/lc-solutions/3100-3199/3147-taking-maximum-energy-from-the-mystic-dungeon.md b/solutions/lc-solutions/3100-3199/3147-taking-maximum-energy-from-the-mystic-dungeon.md new file mode 100644 index 0000000..cf867cc --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3147-taking-maximum-energy-from-the-mystic-dungeon.md @@ -0,0 +1,365 @@ +--- +id: Taking-Maximum-Energy-From-the-Mystic-Dungeon +title: Taking Maximum Energy From the Mystic Dungeon (LeetCode) +sidebar_label: 3147-Taking Maximum Energy From the Mystic Dungeon +tags: + - Dynamic Programming + - Geometry + - Sorting + - Sliding Window +description: this discription is for the solution of Taking Maximum Energy From the Mystic Dungeon +sidebar_position: 3147 +--- + +## Problem statement: + +In a mystic dungeon, `n` magicians are standing in a line. Each magician has an attribute that gives you energy. Some magicians can give you negative energy, which means taking energy from you. + +You have been cursed in such a way that after absorbing energy from magician `i`, you will be instantly transported to magician `(i + k)`. This process will be repeated until you reach the magician where `(i + k)` does not exist. + +In other words, you will choose a starting point and then teleport with `k` jumps until you reach the end of the magicians' sequence, absorbing all the energy during the journey. + +You are given an array energy and an integer `k`. Return the maximum possible energy you can gain. + +**Example 1:** + +Input: energy = [5,2,-10,-5,1], k = 3 +Output: 3 + +Explanation: We can gain a total energy of 3 by starting from magician 1 absorbing 2 + 1 = 3. + +**Example 2:** + +Input: energy = [-2,-3,-1], k = 2 +Output: -1 + +Explanation: We can gain a total energy of -1 by starting from magician 2. + +**Constraints:** + + - `1 <= energy.length <= 105` + - `-1000 <= energy[i] <= 1000` + - `1 <= k <= energy.length - 1` + +## Solutions: + +### Approch 1: + +There will be `k` non-overlapping sets of integers that the `energy` array can be partitioned into. With adjacent elements in any given partition being `k`-index positions apart in the original input. + +Additionally, since we're always moving from left to right, that means any energies that occur more to the right will need to be absorbed if we start to their left; while energies occuring towards the left may be skipped if we simply choose to start at an index position to the right of those. Thus keeping track of suffix-sums of partitioned energies, while iterating from right to left, will be our strategy to solving this. + +## code: + + + + + ```python + class Solution: + def maximumEnergy(self, energy: List[int], k: int) -> int: + res, n = -math.inf, len(energy) + + # iterate through every possible starting position + for p in range(k): + acc_energy = 0 + + # iterate from the right to left, in k-steps + for i in range(n - p - 1, -1, -k): + acc_energy += energy[i] + res = max(res, acc_energy) + + return res + ``` + + + + ```java + import java.util.*; + + public class Solution { + public int maximumEnergy(List energy, int k) { + int res = Integer.MIN_VALUE; + int n = energy.size(); + + // iterate through every possible starting position + for (int p = 0; p < k; p++) { + int accEnergy = 0; + + // iterate from the right to left, in k-steps + for (int i = n - p - 1; i >= 0; i -= k) { + accEnergy += energy.get(i); + res = Math.max(res, accEnergy); + } + } + + return res; + } + } + ``` + + + + ```cpp + #include + #include + #include + + class Solution { + public: + int maximumEnergy(std::vector& energy, int k) { + int res = -std::numeric_limits::max(); + int n = energy.size(); + + // iterate through every possible starting position + for (int p = 0; p < k; ++p) { + int accEnergy = 0; + + // iterate from the right to left, in k-steps + for (int i = n - p - 1; i >= 0; i -= k) { + accEnergy += energy[i]; + res = std::max(res, accEnergy); + } + } + + return res; + } + }; + ``` + + + + ```csharp + using System; + using System.Collections.Generic; + + public class Solution { + public int MaximumEnergy(List energy, int k) { + int res = int.MinValue; + int n = energy.Count; + + // iterate through every possible starting position + for (int p = 0; p < k; p++) { + int accEnergy = 0; + + // iterate from the right to left, in k-steps + for (int i = n - p - 1; i >= 0; i -= k) { + accEnergy += energy[i]; + res = Math.Max(res, accEnergy); + } + } + + return res; + } + } + ``` + + + + ```javascript + function maximumEnergy(energy, k) { + let res = -Infinity; + const n = energy.length; + + // iterate through every possible starting position + for (let p = 0; p < k; p++) { + let accEnergy = 0; + + // iterate from the right to left, in k-steps + for (let i = n - p - 1; i >= 0; i -= k) { + accEnergy += energy[i]; + res = Math.max(res, accEnergy); + } + } + + return res; + } + ``` + + + + ```go + package main + + import ( + "math" + ) + + func maximumEnergy(energy []int, k int) int { + res := math.MinInt64 + n := len(energy) + + // iterate through every possible starting position + for p := 0; p < k; p++ { + accEnergy := 0 + + // iterate from the right to left, in k-steps + for i := n - p - 1; i >= 0; i -= k { + accEnergy += energy[i] + if accEnergy > res { + res = accEnergy + } + } + } + + return res + } + ``` + + + + +## Complexity + +**Time complexity:** $O(kβˆ—n/k)$ = $O(n)$ + +**Space complexity:** $O(1)$ + +## Approch 2: + +**Intuition** + + - Need to focus - you can start from any point and need to take all till end + - We need to iterate from end and take the max of all intermidiate sum + +**Approach** + + - Iterate i over 0 to k, and fix the start point as end - i + - Again start iterate over array and keep traking the max value + +**code** + + + + + ```cpp + #include + #include + #include + + class Solution { + public: + int maximumEnergy(std::vector& energy, int k) { + int ans = INT_MIN; + for (int i = 0; i < k; ++i) { + for (int j = energy.size() - 1 - i, sum = 0; j >= 0; j -= k) { + sum += energy[j]; + ans = std::max(ans, sum); + } + } + return ans; + } + }; + ``` + + + + ```python + class Solution: + def maximumEnergy(self, energy: List[int], k: int) -> int: + ans = float('-inf') + for i in range(k): + sum = 0 + for j in range(len(energy) - 1 - i, -1, -k): + sum += energy[j] + ans = max(ans, sum) + return ans + ``` + + + + ```java + import java.util.*; + + public class Solution { + public int maximumEnergy(List energy, int k) { + int ans = Integer.MIN_VALUE; + for (int i = 0; i < k; ++i) { + int sum = 0; + for (int j = energy.size() - 1 - i; j >= 0; j -= k) { + sum += energy.get(j); + ans = Math.max(ans, sum); + } + } + return ans; + } + } + ``` + + + + ```csharp + using System; + using System.Collections.Generic; + + public class Solution { + public int MaximumEnergy(List energy, int k) { + int ans = int.MinValue; + for (int i = 0; i < k; ++i) { + int sum = 0; + for (int j = energy.Count - 1 - i; j >= 0; j -= k) { + sum += energy[j]; + ans = Math.Max(ans, sum); + } + } + return ans; + } + } + ``` + + + + ```javascript + function maximumEnergy(energy, k) { + let ans = -Infinity; + for (let i = 0; i < k; ++i) { + let sum = 0; + for (let j = energy.length - 1 - i; j >= 0; j -= k) { + sum += energy[j]; + ans = Math.max(ans, sum); + } + } + return ans; + } + ``` + + + + ```go + package main + + import ( + "math" + ) + + func maximumEnergy(energy []int, k int) int { + ans := math.MinInt64 + for i := 0; i < k; i++ { + sum := 0 + for j := len(energy) - 1 - i; j >= 0; j -= k { + sum += energy[j] + if sum > ans { + ans = sum + } + } + } + return ans + } + ``` + + + + +## Complexity + +Time complexity: $O(N)$ + +Space complexity: $O(1)$ + +## Video lecture: + + diff --git a/solutions/lc-solutions/3100-3199/3152- Special-Array-II.md b/solutions/lc-solutions/3100-3199/3152- Special-Array-II.md new file mode 100644 index 0000000..d81e609 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3152- Special-Array-II.md @@ -0,0 +1,158 @@ +--- +id: Special-Array_II +level: Medium +title: Special Array II +sidebar_label: 3152-Special Array II +tags: [Arrays, Data Structure, C++, Java, Python] +description: "This document provides solutions to this problem implemented in C++, Java, and Python." +--- + +## Problem Description + +An array is considered special if every pair of its adjacent elements contains two numbers with different parity. + +You are given an array of integer nums and a 2D integer matrix queries, where for queries[i] = [fromi, toi] your task is to check that +subarray nums[fromi..toi] is special or not. + +Return an array of booleans answer such that answer[i] is true if nums[fromi..toi] is special. + + +### Examples + +**Example 1:** + +``` +Input: nums = [3,4,1,2,6], queries = [[0,4]] + +Output: [false] + +Explanation: + +The subarray is [3,4,1,2,6]. 2 and 6 are both even. + +``` + +**Example 2:** +``` +Input: nums = [4,3,1,6], queries = [[0,2],[2,3]] + +Output: [false,true] + +Explanation: + +The subarray is [4,3,1]. 3 and 1 are both odd. So the answer to this query is false. +The subarray is [1,6]. There is only one pair: (1,6) and it contains numbers with different parity. So the answer to this query is true. +``` + +### Constraints +- `1 <= nums.length <= 105` +- `1 <= nums[i] <= 105` +- `1 <= queries.length <= 105` +- `queries[i].length == 2` +- `0 <= queries[i][0] <= queries[i][1] <= nums.length - 1` + +## Code in Different Languages + +### C++ + +```cpp +#include +#include + +using namespace std; + +vector checkSpecialSubarray(vector& nums, vector>& queries) { + vector answer; + for (const auto& query : queries) { + int from = query[0]; + int to = query[1]; + bool isSpecial = true; + for (int i = from; i < to; ++i) { + if (nums[i] % 2 == nums[i + 1] % 2) { + isSpecial = false; + break; + } + } + answer.push_back(isSpecial); + } + return answer; +} + +int main() { + vector nums = {3, 4, 1, 2, 6}; + vector> queries = {{0, 4}}; + vector result = checkSpecialSubarray(nums, queries); + + for (bool res : result) { + cout << (res ? "true" : "false") << " "; + } + + return 0; +} + +``` + +### Java + +```java +import java.util.ArrayList; +import java.util.List; + +public class SpecialSubarray { + public static List checkSpecialSubarray(int[] nums, int[][] queries) { + List answer = new ArrayList<>(); + for (int[] query : queries) { + int from = query[0]; + int to = query[1]; + boolean isSpecial = true; + for (int i = from; i < to; i++) { + if (nums[i] % 2 == nums[i + 1] % 2) { + isSpecial = false; + break; + } + } + answer.add(isSpecial); + } + return answer; + } + + public static void main(String[] args) { + int[] nums = {3, 4, 1, 2, 6}; + int[][] queries = {{0, 4}}; + List result = checkSpecialSubarray(nums, queries); + + for (boolean res : result) { + System.out.print(res + " "); + } + } +} + +``` + +### Python + +```python +def check_special_subarray(nums, queries): + result = [] + for query in queries: + from_idx, to_idx = query + is_special = True + for i in range(from_idx, to_idx): + if nums[i] % 2 == nums[i + 1] % 2: + is_special = False + break + result.append(is_special) + return result + +# Example usage +nums = [3, 4, 1, 2, 6] +queries = [[0, 4]] +print(check_special_subarray(nums, queries)) # Output: [False] + +``` + +## Complexity Analysis +- **Time Complexity:** $O(q*n)$ where q is no of queries and n is array length. + > **Reason:** iterating throught the array takes $O(n)$ we do it 'q' times so $O(q*n)$ +- **Space Complexity:** $O(q)$ + > **Reason:** space required to store array of size q. diff --git a/solutions/lc-solutions/3100-3199/3161-Block Placement Queries.md b/solutions/lc-solutions/3100-3199/3161-Block Placement Queries.md new file mode 100644 index 0000000..96ca7b9 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3161-Block Placement Queries.md @@ -0,0 +1,253 @@ +--- +id: fenwick-tree-solution +level: Hard +title: Fenwick Tree Solution +sidebar_label: Fenwick Tree Solution +tags: +- Fenwick Tree +- Data Structure +- C++ +- Java +- Python +description: "This document provides solutions to a problem using the Fenwick Tree (Binary Indexed Tree) data structure, implemented in C++, Java, and Python." +--- + +## Problem +The problem requires efficiently processing a series of queries that involve updating and retrieving maximum values within a range. The solution uses the Fenwick Tree (Binary Indexed Tree) data structure to achieve this efficiently. + +## Solution +A Fenwick Tree is used to keep track of the maximum values in the range. Each query is processed in constant or logarithmic time, making the solution efficient for large inputs. + +### Fenwick Tree Structure +The Fenwick Tree is implemented with the following methods: +- `update(int i, int val)`: Updates the tree with the value `val` at index `i`. +- `get(int i)`: Retrieves the maximum value from the start to index `i`. + +### Steps: +1. **Initialization**: Initialize the Fenwick Tree and a sorted set to keep track of obstacles. +2. **Update Queries**: Process update queries to add obstacles. +3. **Compute Intervals**: Compute intervals between obstacles and update the tree. +4. **Result Queries**: Process result queries to check if the interval length is sufficient. + +## Code in Different Languages + +### C++ +```cpp +#include +#include +#include +#include + +using namespace std; + +class FenwickTree { + public: + FenwickTree(int n) : vals(n + 1) {} + + void update(int i, int val) { + while (i < vals.size()) { + vals[i] = max(vals[i], val); + i += lowbit(i); + } + } + + int get(int i) const { + int res = 0; + while (i > 0) { + res = max(res, vals[i]); + i -= lowbit(i); + } + return res; + } + + private: + vector vals; + + static int lowbit(int i) { + return i & -i; + } +}; + +class Solution { + public: + vector getResults(vector>& queries) { + const int n = min(50000, static_cast(queries.size()) * 3); + vector ans; + FenwickTree tree(n + 1); + set obstacles{0, n}; // sentinel values + + for (const vector& query : queries) { + const int type = query[0]; + if (type == 1) { + const int x = query[1]; + obstacles.insert(x); + } + } + + for (auto it = obstacles.begin(); std::next(it) != obstacles.end(); ++it) { + const int x1 = *it; + const int x2 = *std::next(it); + tree.update(x2, x2 - x1); + } + + for (int i = queries.size() - 1; i >= 0; --i) { + const int type = queries[i][0]; + const int x = queries[i][1]; + if (type == 1) { + const auto it = obstacles.find(x); + if (next(it) != obstacles.end()) // x is not the last element. + tree.update(*next(it), *next(it) - *prev(it)); + obstacles.erase(it); + } else { + const int sz = queries[i][2]; + const auto it = obstacles.upper_bound(x); + const int prev = *std::prev(it); + ans.push_back(tree.get(prev) >= sz || x - prev >= sz); + } + } + + return {ans.rbegin(), ans.rend()}; + } +}; +``` +### Java +```java +import java.util.*; + +class FenwickTree { + private int[] vals; + + public FenwickTree(int n) { + vals = new int[n + 1]; + } + + public void update(int i, int val) { + while (i < vals.length) { + vals[i] = Math.max(vals[i], val); + i += lowbit(i); + } + } + + public int get(int i) { + int res = 0; + while (i > 0) { + res = Math.max(res, vals[i]); + i -= lowbit(i); + } + return res; + } + + private static int lowbit(int i) { + return i & -i; + } +} + +class Solution { + public List getResults(int[][] queries) { + final int n = Math.min(50000, queries.length * 3); + List ans = new ArrayList<>(); + FenwickTree tree = new FenwickTree(n + 1); + TreeSet obstacles = new TreeSet<>(Arrays.asList(0, n)); // sentinel values + + for (int[] query : queries) { + final int type = query[0]; + if (type == 1) { + final int x = query[1]; + obstacles.add(x); + } + } + + Iterator it = obstacles.iterator(); + int x1 = it.next(); + while (it.hasNext()) { + final int x2 = it.next(); + tree.update(x2, x2 - x1); + x1 = x2; + } + + for (int i = queries.length - 1; i >= 0; --i) { + final int type = queries[i][0]; + final int x = queries[i][1]; + if (type == 1) { + final Integer next = obstacles.higher(x); + final Integer prev = obstacles.lower(x); + if (next != null) + tree.update(next, next - prev); + obstacles.remove(x); + } else { + final int sz = queries[i][2]; + final int prev = obstacles.floor(x); + ans.add(tree.get(prev) >= sz || x - prev >= sz); + } + } + + Collections.reverse(ans); + return ans; + } +} +``` +### Python +```python +from sortedcontainers import SortedList +from typing import List +import itertools + +class FenwickTree: + def __init__(self, n: int): + self.vals = [0] * (n + 1) + + def update(self, i: int, val: int) -> None: + while i < len(self.vals): + self.vals[i] = max(self.vals[i], val) + i += FenwickTree.lowtree(i) + + def get(self, i: int) -> int: + res = 0 + while i > 0: + res = max(res, self.vals[i]) + i -= FenwickTree.lowtree(i) + return res + + @staticmethod + def lowtree(i: int) -> int: + return i & -i + +class Solution: + def getResults(self, queries: List[List[int]]) -> List[bool]: + n = min(50000, len(queries) * 3) + ans = [] + tree = FenwickTree(n + 1) + obstacles = SortedList([0, n]) # sentinel values + + for query in queries: + type = query[0] + if type == 1: + x = query[1] + obstacles.add(x) + + for x1, x2 in itertools.pairwise(obstacles): + tree.update(x2, x2 - x1) + + for query in reversed(queries): + type = query[0] + x = query[1] + if type == 1: + i = obstacles.index(x) + next = obstacles[i + 1] + prev = obstacles[i - 1] + obstacles.remove(x) + tree.update(next, next - prev) + else: + sz = query[2] + i = obstacles.bisect_right(x) + prev = obstacles[i - 1] + ans.append(tree.get(prev) >= sz or x - prev >= sz) + + return ans[::-1] +``` + +# Complexity Analysis +## Time Complexity: $O(log N)$ for update and get methods. +### Reason: Each update or get operation involves a logarithmic number of steps due to the nature of the Fenwick Tree. +# Space Complexity: $O(N)$ +### Reason: We store values in the Fenwick Tree and maintain a sorted list of obstacles. diff --git a/solutions/lc-solutions/3100-3199/3162-Find-the-number-of-good-pairs-1.md b/solutions/lc-solutions/3100-3199/3162-Find-the-number-of-good-pairs-1.md new file mode 100644 index 0000000..d19d817 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3162-Find-the-number-of-good-pairs-1.md @@ -0,0 +1,125 @@ +--- +id: Find-the-number-of-good-pairs-1 +title: Find the Number of Good Pairs 1 +sidebar_label: 3162-Find the Number of Good Pairs 1 +tags: + - Array + - HashTable +description: "This is a solution to the Find the number of good pairs 1 in leetcode" +--- + +## Problem Description + +You are given 2 integer arrays nums1 and nums2 of lengths n and m respectively. You are also given a positive integer k. +A pair (i, j) is called good if nums1[i] is divisible by nums2[j] * k (`0 <= i <= n - 1, 0 <= j <= m - 1`). + +Return the total number of good pairs. + + + +### Examples + +**Example 1:** + +``` +Input: nums1 = [1,3,4], nums2 = [1,3,4], k = 1 +Output: 5 +Explanation: +The 5 good pairs are (0, 0), (1, 0), (1, 1), (2, 0), and (2, 2). +``` +**Example 2:** +``` +Input: nums1 = [1,2,4,12], nums2 = [2,4], k = 3 + +Output: 2 + +Explanation: + +The 2 good pairs are (3, 0) and (3, 1). + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(n*m)$ + +*** Space Complexity:** $O(1)$ + +### Constraints + +- `1 <= n, m <= 50` +- `1 <= nums1[i], nums2[j] <= 50` +- `1 <= k <= 50` + + +### Solution +## Approach +To solve the problem of finding the number of good pairs ((i, j)) where nums1[i] is divisible by nums2[j] * k, we can use a brute-force approach. We start by initializing a counter to zero. Then, we iterate through each element in 'nums1' using an outer loop and each element in 'nums2' using an inner loop, resulting in all possible pairs of indices (i, j). For each pair, we check if nums1[i] is divisible by nums2[j] * k. If the condition is satisfied, we increment the counter. After iterating through all pairs, we return the counter, which represents the total number of good pairs. This approach ensures that we examine every possible combination of elements from both arrays. The time complexity of this method is O(n * m), where n and m are the lengths of 'nums1' and 'nums2', respectively. Gi this approach is efficient and feasible. + +## Code in Different Languages + + + + + +```cpp +#include +class Solution { +public: + int numberOfPairs(std::vector& nums1, std::vector& nums2, int k) { + int c = 0; + for(int i = 0; i < nums1.size(); i++) { + for(int j = 0; j < nums2.size(); j++) { + if(nums1[i] % (nums2[j] * k) == 0) { + c++; + } + } + } + return c; + } +}; + +``` + + + + +```java +class Solution { + public int numberOfPairs(int[] nums1, int[] nums2, int k) { + int c=0; + for(int i=0;i + + + +```python +class Solution: + def numberOfPairs(self, nums1, nums2, k): + c = 0 + for i in range(len(nums1)): + for j in range(len(nums2)): + if nums1[i] % (nums2[j] * k) == 0: + c += 1 + return c + + +``` + + + +## References + +- **LeetCode Problem**: [Find the Number of Good Pairs 1](https://leetcode.com/problems/find-the-number-of-good-pairs-i/description/) + +- **Solution Link**: [Find the Number of Good Pairs 1](https://leetcode.com/problems/find-the-number-of-good-pairs-i/post-solution/?submissionId=1268097249) diff --git a/solutions/lc-solutions/3100-3199/3169-count-days-without-meetings.md b/solutions/lc-solutions/3100-3199/3169-count-days-without-meetings.md new file mode 100644 index 0000000..948e87a --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3169-count-days-without-meetings.md @@ -0,0 +1,288 @@ +--- +id: count-days-without-meetings +title: Count Days Without Meetings +sidebar_label: 3169. Count Days Without Meetings +tags: +- Array +- Sorting +description: "This is a solution to the Count Days Without Meetings problem on LeetCode." +--- + +## Problem Description +You are given a positive integer days representing the total number of days an employee is available for work (starting from day 1). You are also given a 2D array meetings of size n where, `meetings[i] = [start_i, end_i]` represents the starting and ending days of meeting i (inclusive). + +Return the count of days when the employee is available for work but no meetings are scheduled. + +Note: The meetings may overlap. +### Examples + +**Example 1:** + +``` +Input: days = 10, meetings = [[5,7],[1,3],[9,10]] + +Output: 2 + +Explanation: + +There is no meeting scheduled on the 4th and 8th days. + +``` + +**Example 2:** +``` +Input: days = 5, meetings = [[2,4],[1,3]] + +Output: 1 + +Explanation: + +There is no meeting scheduled on the 5th day. +``` +**Example 3:** +``` +Input: days = 6, meetings = [[1,6]] + +Output: 0 + +Explanation: + +Meetings are scheduled for all working days. +``` + +### Constraints +- `1 <= days <= 10^9` +- `1 <= meetings.length <= 10^5` +- `meetings[i].length == 2` +- `1 <= meetings[i][0] <= meetings[i][1] <= days` + +## Solution for Find the N-th Value After K Seconds Problem +### Prerequisite - Do Merge Interval Question On Leetcode +### Approach +To solve the problem of counting non-working days given a list of intervals that denote working days, we can break down the solution into the following steps: + +- Merge Intervals: Given a list of intervals representing working days, merge any overlapping intervals to consolidate the total working days. This step ensures that we account for continuous working periods without duplication. + +- Count Working Days: After merging the intervals, calculate the total number of working days by summing up the lengths of all the merged intervals. + +- Calculate Non-Working Days: Subtract the total number of working days from the total number of days to get the number of non-working days. + +### Detailed Steps +#### Merge Intervals: + +- Sort the intervals based on the start day. +- Iterate through the intervals and merge them if they overlap. +- Maintain a list of merged intervals. +#### Count Working Days: + +- For each merged interval, calculate the length of the interval (end day - start day + 1). +- Sum up the lengths to get the total number of working days. + +#### Calculate Non-Working Days: +- Subtract the total number of working days from the total number of days given. + + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function merge(intervals) { + intervals.sort((a, b) => a[0] - b[0]); + const output = []; + for (let interval of intervals) { + if (output.length === 0 || output[output.length - 1][1] < interval[0]) { + output.push(interval); + } else { + output[output.length - 1][1] = Math.max(output[output.length - 1][1], interval[1]); + } + } + return output; + } + + function countDays(days, meetings) { + const ans = merge(meetings); + for (let [st, end] of ans) { + days -= (end - st + 1); + } + return days; + } + const input = [[5,7],[1,3],[9,10]]; + const days = 10 + const output = countDays(days , input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(nlogn) $ + - Space Complexity: $ O(1) $ + ## Code in Different Languages + + + + ```javascript + function merge(intervals) { + intervals.sort((a, b) => a[0] - b[0]); + const output = []; + for (let interval of intervals) { + if (output.length === 0 || output[output.length - 1][1] < interval[0]) { + output.push(interval); + } else { + output[output.length - 1][1] = Math.max(output[output.length - 1][1], interval[1]); + } + } + return output; + } + + function countDays(days, meetings) { + const ans = merge(meetings); + for (let [st, end] of ans) { + days -= (end - st + 1); + } + return days; + } + ``` + + + + + ```typescript + class Solution { + merge(intervals: number[][]): number[][] { + intervals.sort((a, b) => a[0] - b[0]); + const output: number[][] = []; + for (const interval of intervals) { + if (output.length === 0 || output[output.length - 1][1] < interval[0]) { + output.push(interval); + } else { + output[output.length - 1][1] = Math.max(output[output.length - 1][1], interval[1]); + } + } + return output; + } + + countDays(days: number, meetings: number[][]): number { + const ans = this.merge(meetings); + for (const [st, end] of ans) { + days -= (end - st + 1); + } + return days; + } +} + + ``` + + + + ```python + class Solution: + def merge(self, intervals): + intervals.sort() + output = [] + for interval in intervals: + if not output or output[-1][1] < interval[0]: + output.append(interval) + else: + output[-1][1] = max(output[-1][1], interval[1]) + return output + + def count_days(self, days, meetings): + ans = self.merge(meetings) + for st, end in ans: + days -= (end - st + 1) + return days + + ``` + + + + ```java + import java.util.*; + +public class Solution { + public List merge(List intervals) { + int n = intervals.size(); + intervals.sort((a, b) -> a[0] - b[0]); + List output = new ArrayList<>(); + for (int[] interval : intervals) { + if (output.isEmpty() || output.get(output.size() - 1)[1] < interval[0]) { + output.add(interval); + } else { + output.get(output.size() - 1)[1] = Math.max(output.get(output.size() - 1)[1], interval[1]); + } + } + return output; + } + + public int countDays(int days, List meetings) { + List ans = merge(meetings); + for (int[] i : ans) { + int st = i[0]; + int end = i[1]; + days -= (end - st + 1); + } + return days; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + vector> merge(vector>& intervals) { + int n = intervals.size(); + sort(intervals.begin(), intervals.end()); + vector> output; + for(auto interval : intervals){ + if(output.empty() || output.back()[1] < interval[0]){ + output.push_back(interval); + } + else{ + output.back()[1] = max(output.back()[1], interval[1]); + } + } + return output; + } + int countDays(int days, vector>& meetings) { + vector>ans = merge(meetings); + sort(begin(ans) , end(ans)); + for(auto i:ans) + { + int st = i[0]; + int end = i[1]; + + days -=(end -st +1); + } + return days; + } +}; + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Count Days Without Meetings](https://leetcode.com/problems/count-days-without-meetings/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/count-days-without-meetings/solutions/) + diff --git a/solutions/lc-solutions/3100-3199/3170-lexicographically-minimum-string-after-removing-stars.md b/solutions/lc-solutions/3100-3199/3170-lexicographically-minimum-string-after-removing-stars.md new file mode 100644 index 0000000..6ad707d --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3170-lexicographically-minimum-string-after-removing-stars.md @@ -0,0 +1,308 @@ +--- +id: lexicographically-minimum-string-after-removing-stars +title: Lexicographically Minimum String After Removing Stars +sidebar_label: 3170 . Lexicographically Minimum String After Removing Stars +tags: +- Hash Table +- String +- Stack +- Greedy +- Heap (Priority Queue) +description: "This is a solution to the Lexicographically Minimum String After Removing Stars problem on LeetCode." +--- + +## Problem Description +You are given a string s. It may contain any number of '*' characters. Your task is to remove all '*' characters. + +While there is a '*', do the following operation: + +Delete the leftmost '*' and the smallest non-'*' character to its left. If there are several smallest characters, you can delete any of them. +Return the lexicographically smallest resulting string after removing all '*' characters. + +### Examples + +**Example 1:** + +``` +Input: s = "aaba*" + +Output: "aab" + +Explanation: + +We should delete one of the 'a' characters with '*'. If we choose s[3], s becomes the lexicographically smallest. +``` + +**Example 2:** +``` +Input: s = "abc" + +Output: "abc" + +Explanation: + +There is no '*' in the string. +``` + +### Constraints + +- `1 <= s.length <= 10^5` +- `s consists only of lowercase English letters and '*'.` +- `The input is generated such that it is possible to delete all '*' characters.` + +## Solution for Lexicographically Minimum String After Removing Stars Problem +### Approach + +#### Initialization: + +- We initialize two sets: +- st: A set to store pairs of (character value, negative index). This helps us quickly identify and remove the leftmost character when we encounter a star. +- del: A set to keep track of the indices of characters that need to be deleted (either because they are stars or they were removed by stars). +#### Traversing the String: +- We iterate over the string from left to right. +#### For each character: +- If the character is a star (*): +- We identify the leftmost character in the set st by taking the smallest element (due to the ordering by character value and then by index). +- We remove this leftmost character from the set st. +- We record the indices of this leftmost character and the star itself in the del set. +- If the character is not a star: +- We add a pair of (character value, negative index) to the set st. +#### Building the Result: + +- We initialize an empty string ans to store the result. +- We iterate over the original string again. +- For each character: +- If the index of the character is not in the del set (i.e., it hasn't been marked for deletion), we append it to ans. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + var clearStars = function(s) { + const mp = new Map(); + const n = s.length; + const v = new Array(n).fill(0); + + for (let i = 0; i < n; i++) { + if (s[i] !== '*') { + if (!mp.has(s[i])) { + mp.set(s[i], []); + } + mp.get(s[i]).push(i); + } else { + v[i] = 1; + const sortedEntries = Array.from(mp.entries()).sort((a, b) => a[0].localeCompare(b[0])); + for (let [key, indices] of sortedEntries) { + const m = indices.length; + v[indices[m - 1]] = 1; + indices.pop(); + if (indices.length === 0) { + mp.delete(key); + } + break; + } + } + } + + let ans = ""; + for (let i = 0; i < n; i++) { + if (v[i] !== 1) { + ans += s[i]; + } + } + return ans; +}; + const input = "aaba*" + const output =clearStars(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(nlogn) $ because of Nested Loops + - Space Complexity: $ O(n) $ because of prefix array + + ## Code in Different Languages + + + + ```javascript +var clearStars = function(s) { + const mp = new Map(); + const n = s.length; + const v = new Array(n).fill(0); + + for (let i = 0; i < n; i++) { + if (s[i] !== '*') { + if (!mp.has(s[i])) { + mp.set(s[i], []); + } + mp.get(s[i]).push(i); + } else { + v[i] = 1; + const sortedEntries = Array.from(mp.entries()).sort((a, b) => a[0].localeCompare(b[0])); + for (let [key, indices] of sortedEntries) { + const m = indices.length; + v[indices[m - 1]] = 1; + indices.pop(); + if (indices.length === 0) { + mp.delete(key); + } + break; + } + } + } + + let ans = ""; + for (let i = 0; i < n; i++) { + if (v[i] !== 1) { + ans += s[i]; + } + } + return ans; +}; + ``` + + + + + ```typescript + function clearStars(s: string): string { + const n = s.length; + const st: Set<[number, number]> = new Set(); + const del: Set = new Set(); + for (let i = 0; i < n; i++) { + if (s[i] === '*') { + const first = Array.from(st)[0]; + st.delete(first); + del.add(-first[1]); + del.add(i); + } else { + st.add([s.charCodeAt(i) - 'a'.charCodeAt(0), -i]); + } + } + + let ans = ''; + for (let i = 0; i < n; i++) { + if (!del.has(i)) ans += s[i]; + } + return ans; +} + + ``` + + + + ```python + def clearStars(s: str) -> str: + n = len(s) + st = set() + del_set = set() + + for i in range(n): + if s[i] == '*': + first = min(st) + st.remove(first) + del_set.add(-first[1]) + del_set.add(i) + else: + st.add((ord(s[i]) - ord('a'), -i)) + + ans = ''.join(s[i] for i in range(n) if i not in del_set) + return ans + + ``` + + + + ```java + import java.util.*; + +public class Solution { + public String clearStars(String s) { + int n = s.length(); + TreeSet st = new TreeSet<>((a, b) -> a.first == b.first ? a.second - b.second : a.first - b.first); + Set del = new HashSet<>(); + + for (int i = 0; i < n; i++) { + if (s.charAt(i) == '*') { + Pair first = st.first(); + st.remove(first); + del.add(-first.second); + del.add(i); + } else { + st.add(new Pair(s.charAt(i) - 'a', -i)); + } + } + + StringBuilder ans = new StringBuilder(); + for (int i = 0; i < n; i++) { + if (!del.contains(i)) ans.append(s.charAt(i)); + } + return ans.toString(); + } + + class Pair { + int first, second; + + Pair(int first, int second) { + this.first = first; + this.second = second; + } + } +} + + ``` + + + + + ```cpp + class Solution { +public: + string clearStars(string s) { + int n = s.size(); + set>st; + set del; + for (int i = 0; i < n; i++) { + if (s[i] == '*') { + auto first = *st.begin(); + st.erase(st.begin()); + del.insert(-first.second); + del.insert(i); + } else { + st.insert({s[i]-'a' , -i}); + } + } + + string ans = ""; + for (int i = 0; i < n; i++) if (!del.count(i)) ans += s[i]; + return ans; + } +}; + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [ Lexicographically Minimum String After Removing Stars](https://leetcode.com/problems/lexicographically-minimum-string-after-removing-stars/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/lexicographically-minimum-string-after-removing-stars/solutions) + diff --git a/solutions/lc-solutions/3100-3199/3171. Find Subarray With Bitwise OR Closest to K.md b/solutions/lc-solutions/3100-3199/3171. Find Subarray With Bitwise OR Closest to K.md new file mode 100644 index 0000000..8650a5e --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3171. Find Subarray With Bitwise OR Closest to K.md @@ -0,0 +1,121 @@ +--- +id: Find-Subarray-With-Bitwise-OR-Closest-to-K +title: Find Subarray With Bitwise OR Closest to K (LeetCode) +level: hard +sidebar_label: 3171-Find Subarray With Bitwise OR Closest to K +tags: + - Dynamic Programming + - Bit Manipulation + - Sliding Window + - Hash Set +description: This description is for the solution of Find Subarray With Bitwise OR Closest to K +sidebar_position: 3171 +--- + +## Problem statement: + +Given an array of integers `arr` and an integer `k`, return the maximum possible bitwise OR of a subarray of `arr` that is closest to `k`. + +The bitwise OR of an array of numbers is defined as `a1 | a2 | ... | an`, where `|` denotes the bitwise OR operator. + +**Example 1:** + +Input: arr = [5,6,7,8,9], k = 10 +Output: 10 + +Explanation: The subarray [6,7] has bitwise OR = 6 | 7 = 7, which is closest to 10. + +**Example 2:** + +Input: arr = [1,2,4,8,16], k = 32 +Output: 31 + +Explanation: The subarray [1,2,4,8,16] has bitwise OR = 1 | 2 | 4 | 8 | 16 = 31, which is closest to 32. + +**Constraints:** + +- `1 <= arr.length <= 10^5` +- `1 <= arr[i], k <= 10^9` + +## Solutions: + +### Approach 1: Sliding Window with Bitmasking + +```python +class Solution: + def closestToTarget(self, arr: List[int], k: int) -> int: + ans = float('inf') + current = set() + + for num in arr: + current = {num & val for val in current} | {num} + for val in current: + ans = min(ans, abs(val - k)) + + return ans +``` + +### Approach 2: Efficient Bitmasking with Set Operations + +```python +class Solution: + def closestToTarget(self, arr: List[int], k: int) -> int: + ans = float('inf') + current = set() + next_set = set() + + for num in arr: + next_set = {num & val for val in current} | {num} + for val in next_set: + ans = min(ans, abs(val - k)) + current = next_set + + return ans +``` + +### Approach 3: Optimized Sliding Window with Prefix Bitmasking + +```python +class Solution: + def closestToTarget(self, arr: List[int], k: int) -> int: + ans = float('inf') + current = set() + + for num in arr: + new_current = {num} + for val in current: + new_current.add(val | num) + current = new_current + for val in current: + ans = min(ans, abs(val - k)) + + return ans +``` +## Complexity Analysis: + +### Approach 1: Sliding Window with Bitmasking + +- **Time Complexity:** $O(nβ‹…log(max_element))$ + - Where \( n \) is the number of elements in the array `arr`, and `max_element` is the maximum element in `arr`. + - The logarithmic factor comes from the bitwise operations and set operations involved. + +- **Space Complexity:** $O(log(max_element))$ + - Space used by the set `current` to store intermediate bitwise OR values. + +### Approach 2: Efficient Bitmasking with Set Operations + +- **Time Complexity:** $O(nβ‹…log(max_element))$ + - Same as Approach 1, due to similar operations on sets. + +- **Space Complexity:** $O(log(max_element))$ + - Similar to Approach 1, space used by the sets `current` and `next_set`. + +### Approach 3: Optimized Sliding Window with Prefix Bitmasking + +- **Time Complexity:** $O(nβ‹…log(max_element))$ + - Same as Approach 1 and 2, as it involves bitwise OR operations and set updates. + +- **Space Complexity:** $O(log(max_element))$ + - Space used by the set `current` to store intermediate bitwise OR values. + +Here, `max_element` refers to the maximum element present in the array `arr`, which affects the logarithmic factor in the time and space complexities due to bitwise operations and set operations involved in each approach. diff --git a/solutions/lc-solutions/3100-3199/3174-clear-digits.md b/solutions/lc-solutions/3100-3199/3174-clear-digits.md new file mode 100644 index 0000000..3b8959e --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3174-clear-digits.md @@ -0,0 +1,131 @@ +--- +id: clear-digits +title: Clear Digits +sidebar_label: 3174-Clear Digits +tags: + - String + - HashTable + - Stimulation + +description: "This is a solution to clear digits in leetcode " +--- + +## Problem Description + +You are given a string s. + +Your task is to remove all digits by doing this operation repeatedly: + +1. Delete the first digit and the closest non-digit character to its left. +Return the resulting string after removing all digits. + + + +### Examples + +**Example 1:** + +``` +Input: s = "abc" +Output: "abc" +Explanation: +There is no digit in the string. + +``` +**Example 2:** +``` +Input: s = "cb34" +Output: "" +Explanation: +First, we apply the operation on s[2], and s becomes "c4". +Then we apply the operation on s[1], and s becomes "". + + + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(n**2)$ + +*** Space Complexity:** $O(n)$ + +### Constraints + +- `1 <= s.length <= 100` +- `s` consists only of lowercase English letters and digits. + + +### Solution +## Approach +To remove all digits from a string, iterate through the string, checking each character. If a digit is found, remove it and reset the index to the beginning of the string to ensure all digits are considered, even those that may shift positions after removal. Continue this process until the end of the string is reached, ensuring all digits are removed. Return the modified string without any digits. +## Code in Different Languages + + + + + +```cpp + +class Solution { +public: + std::string clearDigits(std::string s) { + for (int i = 0; i < s.length(); ) { + if (isdigit(s[i])) { + s.erase(i, 1); + i = 0; + } else { + i++; + } + } + return s; + } +}; + +``` + + + + +```java +class Solution { + public String clearDigits(String s) { + for(int i=0;i + + + +```python +class Solution: + def clearDigits(self, s: str) -> str: + i = 0 + while i < len(s): + if s[i].isdigit(): + s = s[:i] + s[i+1:] + i = 0 + else: + i += 1 + return s +``` + + + +## References + +- **LeetCode Problem**: [Clear Digits](https://leetcode.com/problems/clear-digits/description/) + +- **Solution Link**: [Clear Digits](https://leetcode.com/problems/clear-digits/post-solution/?submissionId=1281655904) diff --git a/solutions/lc-solutions/3100-3199/3175. Find The First Player to win K Games in a Row.md b/solutions/lc-solutions/3100-3199/3175. Find The First Player to win K Games in a Row.md new file mode 100644 index 0000000..9cecde0 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3175. Find The First Player to win K Games in a Row.md @@ -0,0 +1,126 @@ +--- +id: Find-The-First-Player-to-Win-K-Games-in-a-Row +title: Find The First Player to Win K Games in a Row (LeetCode) +sidebar_label: 3175-Find The First Player to Win K Games in a Row +tags: + - Array + - Simulation +description: Solution for finding the first player to win K games in a row. +sidebar_position: 3175 +--- + +## Problem statement: + +You are given an array `skills` of integers, where `skills[i]` represents the skill level of the `i-th` player. Players are standing in a line and starting from the first player, each player competes with the next player. The player with the higher skill level wins the game. If two players have the same skill level, the first player wins. + +A player who wins the game continues to compete with the next player in the line. The first player to win `k` consecutive games is declared the winner. If no player wins `k` consecutive games, return the player with the highest skill level at the end of the line. + +You are asked to determine the index of the first player who wins `k` consecutive games. + +**Example 1:** + +Input: skills = [2, 1, 3, 5, 4, 6, 7], k = 2 +Output: 5 + +Explanation: Player at index 5 wins 2 consecutive games (6 vs 4 and 6 vs 7). + +**Example 2:** + +Input: skills = [3, 2, 1], k = 10 +Output: 0 + +Explanation: No player wins 10 consecutive games, so return the index of the player with the highest skill level (index 0). + +**Constraints:** + +- `1 <= skills.length <= 10^5` +- `1 <= skills[i] <= 10^9` +- `1 <= k <= skills.length` + +## Solutions: + +### Approach: + +We will simulate the process where each player competes with the next player in the array. We keep track of the number of consecutive wins for the current player. If the number of wins for the current player reaches `k`, we return the index of the current player. + +## Code: + + + + + ```python + class Solution: + # Similar to 1535. Find the Winner of an Array Game + def findWinningPlayer(self, skills: List[int], k: int) -> int: + ans = 0 + wins = 0 + + i = 1 + while i < len(skills) and wins < k: + if skills[i] > skills[ans]: + ans = i + wins = 1 + else: + wins += 1 + i += 1 + + return ans + ``` + + + + + ```java + class Solution { + // Similar to 1535. Find the Winner of an Array Game + public int findWinningPlayer(int[] skills, int k) { + int ans = 0; + int wins = 0; + + for (int i = 1; i < skills.length && wins < k; ++i) + if (skills[i] > skills[ans]) { + ans = i; + wins = 1; + } else { + ++wins; + } + + return ans; + } + } + ``` + + + + ```cpp + class Solution { + public: + // Similar to 1535. Find the Winner of an Array Game + int findWinningPlayer(vector& skills, int k) { + int ans = 0; + int wins = 0; + + for (int i = 1; i < skills.size() && wins < k; ++i) + if (skills[i] > skills[ans]) { + ans = i; + wins = 1; + } else { + ++wins; + } + + return ans; + } + }; + ``` + + + +## Complexity Analysis: + +**Time Complexity:** + +The time complexity of this approach is $O(n)$, where $n$ is the number of players in the `skills` array. This is because each player is compared once. + +**Space Complexity:** + +The space complexity of this approach is $O(1)$ since we are using a constant amount of extra space. diff --git a/solutions/lc-solutions/3100-3199/3178. Find the Child Who Has the Ball After K Seconds.md b/solutions/lc-solutions/3100-3199/3178. Find the Child Who Has the Ball After K Seconds.md new file mode 100644 index 0000000..278128c --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3178. Find the Child Who Has the Ball After K Seconds.md @@ -0,0 +1,104 @@ +--- +id: Find-the-Child-Who-Has-the-Ball-After-K-Seconds +title: Find the Child Who Has the Ball After K Seconds (LeetCode) +sidebar_label: 3178-Find the Child Who Has the Ball After K Seconds +tags: + - Simulation + - Math +description: Solution for finding the child who has the ball after K seconds. +sidebar_position: 3178 +--- + +## Problem statement: + +In a game, `n` children stand in a circle and pass a ball to each other. The child at position `i` passes the ball to the child at position `(i + 1) % n` after 1 second, and the child at position `0` starts with the ball. + +You are given the number of children `n` and the number of seconds `k`. Return the index of the child who has the ball after `k` seconds. + +**Example 1:** + +Input: n = 5, k = 7 +Output: 2 + +Explanation: The ball will be at child 2 after 7 seconds. + +**Example 2:** + +Input: n = 3, k = 4 +Output: 1 + +Explanation: The ball will be at child 1 after 4 seconds. + +**Constraints:** + +- `1 <= n <= 10^9` +- `1 <= k <= 10^9` + +## Solutions: + +### Approach 1: + +**Intuition** + +The ball passes from one child to the next every second. When the ball reaches the last child (at position `n-1`), it returns to the first child (at position `0`). This forms a repeating cycle of length `n`. + +**Approach** + +Calculate the position of the ball after `k` seconds by taking the remainder of `k` divided by `n`. This will give the current position in the cycle. + +## Code: + + + + +```cpp + +class Solution { + public: + int numberOfChild(int n, int k) { + // the time for the ball to return to 0 + const int roundTime = 2 * (n - 1); + const int pos = k % roundTime; + return pos < n ? pos : roundTime - pos; + } +}; +``` + + + + +```java + +class Solution { + public int numberOfChild(int n, int k) { + // the time for the ball to return to 0 + final int roundTime = 2 * (n - 1); + final int pos = k % roundTime; + return pos < n ? pos : roundTime - pos; + } +} +``` + + + + +```python +class Solution: + def numberOfChild(self, n: int, k: int) -> int: + # the time for the ball to return to 0 + roundTime = 2 * (n - 1) + pos = k % roundTime + return pos if pos < n else roundTime - pos +``` + + + +# Complexity Analysis: +## Approach 1: +### Time Complexity: $O(1)$ + +The time complexity is constant because we only need to perform a few arithmetic operations regardless of the size of $n$ and $k$. + +### Space Complexity: $O(1)$ + +The space complexity is also constant because we are only using a fixed amount of extra space for the calculation. diff --git a/solutions/lc-solutions/3100-3199/3179-find-the-n-th-value-after-k-seconds.md b/solutions/lc-solutions/3100-3199/3179-find-the-n-th-value-after-k-seconds.md new file mode 100644 index 0000000..f17d27a --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3179-find-the-n-th-value-after-k-seconds.md @@ -0,0 +1,235 @@ +--- +id: find-the-n-th-value-after-k-seconds +title: Find the N-th Value After K Seconds +sidebar_label: 3179. Find the N-th Value After K Seconds +tags: +- Array +- Math +- Simulation +- Combinatorics +- Prefix Sum +description: "This is a solution to the Find the N-th Value After K Seconds problem on LeetCode." +--- + +## Problem Description +You are given two integers n and k. + +Initially, you start with an array a of n integers where `a[i] = 1 for all 0 <= i <= n - 1`. After each second, you simultaneously update each element to be the sum of all its preceding elements plus the element itself. For example, after one second, a[0] remains the same, a[1] becomes a[0] + a[1], a[2] becomes a[0] + a[1] + a[2], and so on. + +Return the value of a[n - 1] after k seconds. + +Since the answer may be very large, return it modulo 109 + 7. + +### Examples + +**Example 1:** + +``` +Input: n = 4, k = 5 + +Output: 56 + +Explanation: + +Second State After +0 [1,1,1,1] +1 [1,2,3,4] +2 [1,3,6,10] +3 [1,4,10,20] +4 [1,5,15,35] +5 [1,6,21,56] + + +``` + +**Example 2:** +``` +Input: n = 5, k = 3 + +Output: 35 + +Explanation: + +Second State After +0 [1,1,1,1,1] +1 [1,2,3,4,5] +2 [1,3,6,10,15] +3 [1,4,10,20,35] + +``` + +### Constraints + +- `1 <= n, k <= 1000` + +## Solution for Find the N-th Value After K Seconds Problem +### Approach +The problem essentially involves calculating the prefix sum of an array iteratively over a given number of seconds K. Each element in the array represents a value that is derived from summing up all previous elements in the array (including itself) from the previous iteration. The goal is to determine the value of the N-th element in the array after K seconds. +### Steps +- Start with an array of size N where all elements are initialized to 1. This represents the array at time t=0. +- For each second from 1 to K, update the array by calculating the prefix sum for each element. This means that each element at position i (0-indexed) will be updated to the sum of all elements from position 0 to i of the previous iteration. +- After K seconds, return the value of the N-th element in the array. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function valueAfterKSeconds(n, k) { + let arr = new Array(n).fill(1); + const mod = 1000000007; + + for (let i = 1; i <= k; i++) { + let prefix = new Array(n).fill(0); + prefix[0] = arr[0] % mod; + for (let j = 1; j < n; j++) { + prefix[j] = (prefix[j - 1] + arr[j]) % mod; + } + arr = prefix; + } + return arr[n - 1]; + } + const input = 4; + const k = 5 + const output = valueAfterKSeconds(input , k) ; + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(N*K) $ because of Nested Loops + - Space Complexity: $ O(N) $ because of prefix array + + ## Code in Different Languages + + + + ```javascript + function valueAfterKSeconds(n, k) { + let arr = new Array(n).fill(1); + const mod = 1000000007; + + for (let i = 1; i <= k; i++) { + let prefix = new Array(n).fill(0); + prefix[0] = arr[0] % mod; + for (let j = 1; j < n; j++) { + prefix[j] = (prefix[j - 1] + arr[j]) % mod; + } + arr = prefix; + } + return arr[n - 1]; + } + + ``` + + + + + ```typescript + class Solution { + valueAfterKSeconds(n: number, k: number): number { + let arr: number[] = new Array(n).fill(1); + const mod: number = 1000000007; + + for (let i = 1; i <= k; i++) { + let prefix: number[] = new Array(n).fill(0); + prefix[0] = arr[0] % mod; + for (let j = 1; j < n; j++) { + prefix[j] = (prefix[j - 1] + arr[j]) % mod; + } + arr = prefix; + } + return arr[n - 1]; + } +} + + ``` + + + + ```python + class Solution: + def value_after_k_seconds(self, n: int, k: int) -> int: + arr = [1] * n + mod = 10**9 + 7 + + for i in range(1, k + 1): + prefix = [0] * n + prefix[0] = arr[0] % mod + for j in range(1, n): + prefix[j] = (prefix[j - 1] + arr[j]) % mod + arr = prefix + + return arr[n - 1] + ``` + + + + ```java + import java.util.Arrays; + +public class Solution { + public int valueAfterKSeconds(int n, int k) { + int[] arr = new int[n]; + Arrays.fill(arr, 1); + int mod = 1000000007; + + for (int i = 1; i <= k; i++) { + int[] prefix = new int[n]; + prefix[0] = arr[0] % mod; + for (int j = 1; j < n; j++) { + prefix[j] = (prefix[j - 1] + arr[j]) % mod; + } + arr = prefix; + } + return arr[n - 1]; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + int valueAfterKSeconds(int n, int k) { + vector arr(n, 1); + int mod = 1e9 + 7; + for (int i = 1; i <= k; i++) { + vector prefix(n, 0); + prefix[0] = arr[0]%mod; + for (int j = 1; j < n; j++) { + prefix[j] = (prefix[j - 1] + arr[j]) % mod; + } + arr = prefix; + } + return arr[n-1]; + } +}; + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Find the N-th Value After K Seconds](https://leetcode.com/problems/find-the-n-th-value-after-k-seconds/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/find-the-n-th-value-after-k-seconds/solutions) + diff --git a/solutions/lc-solutions/3100-3199/3181-Maximum total rewards using rewards II.md b/solutions/lc-solutions/3100-3199/3181-Maximum total rewards using rewards II.md new file mode 100644 index 0000000..853a311 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3181-Maximum total rewards using rewards II.md @@ -0,0 +1,105 @@ +--- +id: 3181-max-total-reward +title: Maximum Total Reward Using Operations +level: hard +sidebar_label: Max Total Reward +tags: +- Dynamic Programming +- Bit Manipulation +- C++ +- Java +- Python +description: "This document provides solutions for finding the maximum total reward using dynamic programming and bit manipulation, implemented in C++, Java, and Python." +--- + +## Problem +Given a list of reward values, the goal is to determine the maximum total reward that can be achieved using a series of operations. + +## Solution +The problem is solved using dynamic programming and bit manipulation. The approach involves maintaining a bitset or similar data structure to track achievable reward values and iterating through the sorted reward values to update this structure. + +## Code in Different Languages + +### C++ +```cpp +#include +#include +#include +#include +using namespace std; + +class Solution { + public: + int maxTotalReward(vector& rewardValues) { + constexpr int kPossibleRewards = 100000; + bitset dp; + dp[0] = true; + + sort(rewardValues.begin(), rewardValues.end()); + + for (const int num : rewardValues) { + bitset newBits = dp; + newBits <<= kPossibleRewards - num; + newBits >>= kPossibleRewards - num; + dp |= newBits << num; + } + + for (int ans = kPossibleRewards - 1; ans >= 0; --ans) + if (dp[ans]) + return ans; + + throw runtime_error("Solution not found"); + } +}; +``` + +### Java +```java +import java.math.BigInteger; +import java.util.Arrays; + +class Solution { + public int maxTotalReward(int[] rewardValues) { + BigInteger one = BigInteger.ONE; + BigInteger dp = one; // the possible rewards (initially, 0 is achievable) + + Arrays.sort(rewardValues); + + for (final int num : rewardValues) { + BigInteger maskBitsLessThanNum = one.shiftLeft(num).subtract(one); + BigInteger bitsLessThanNum = dp.and(maskBitsLessThanNum); + dp = dp.or(bitsLessThanNum.shiftLeft(num)); + } + + return dp.bitLength() - 1; + } +} +``` + +### Python +```python +from typing import List + +class Solution: + def maxTotalReward(self, rewardValues: List[int]) -> int: + dp = 1 # the possible rewards (initially, 0 is achievable) + + for num in sorted(rewardValues): + smallerNums = dp & ((1 << num) - 1) + dp |= smallerNums << num + + return dp.bit_length() - 1 + +# Example usage +sol = Solution() +rewardValues = [1, 2, 3, 5] +print(sol.maxTotalReward(rewardValues)) # Output: 10 +``` + +# Complexity Analysis +## Time Complexity: +$O(n * k)$, where n is the number of reward values and k is the maximum possible reward value. Sorting the reward values takes O(n log n) time, and each bit manipulation operation is efficient. + +## Space Complexity: +$O(k)$ +Reason: The bitset or similar structure requires space proportional to the maximum possible reward value. diff --git a/solutions/lc-solutions/3100-3199/3184-count-pairs-that-form-a-complete-day-i.md b/solutions/lc-solutions/3100-3199/3184-count-pairs-that-form-a-complete-day-i.md new file mode 100644 index 0000000..270f07d --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3184-count-pairs-that-form-a-complete-day-i.md @@ -0,0 +1,147 @@ +--- +id: search-in-a-binary-search-tree +title: Count Pairs That Form a Complete Day I +sidebar_label: 3184 - Count Pairs That Form a Complete Day I +tags: + - Array + - Hashtable + - Counting +description: "This is a solution to the Search in a Binary Search Tree problem on LeetCode." +--- +## Problem Description + +Given an integer array `hours` representing times in hours, return an integer denoting the number of pairs `(i, j)` where `i < j` and `hours[i] + hours[j]` forms a complete day. A complete day is defined as a time duration that is an exact multiple of 24 hours. + +### Example + +**Example 1:** + +``` +Input: hours = [12, 12, 30, 24, 24] +Output: 2 + +Explanation: +The pairs of indices that form a complete day are (0, 1) and (3, 4). +``` + +**Example 2:** + +``` +Input: hours = [72, 48, 24, 3] +Output: 3 + +Explanation: +The pairs of indices that form a complete day are (0, 1), (0, 2), and (1, 2). +``` + +### Constraints + +- `1 <= hours.length <= 100` +- `1 <= hours[i] <= 10^9` + +## Solution Approach + +### Intuition + +To efficiently find pairs of hours that sum up to a multiple of 24, we can utilize a hash map to keep track of the remainders when the hours are divided by 24. This allows us to quickly check if there exists a previous hour that complements the current hour to form a complete day. + +### Algorithm + +1. Initialize a hash map to keep track of remainders and their counts. +2. For each hour in the array: + - Compute its remainder when divided by 24. + - The target remainder needed to form a complete day with the current hour is `(24 - remainder) % 24`. + - Check if this target remainder exists in the hash map and count the valid pairs. + - Update the hash map with the current remainder. +3. Return the total count of valid pairs. + +### Complexity + +- Time Complexity: $O(N)$, where N is the number of hours. +- Space Complexity: $O(1)$, as the hash map will have at most 24 entries. + +## Solution Implementation + +### Code (Python): + +```python +from collections import defaultdict + +def countCompleteDayPairs(hours): + remainder_count = defaultdict(int) + complete_day_pairs = 0 + + for hour in hours: + remainder = hour % 24 + target_remainder = (24 - remainder) % 24 + complete_day_pairs += remainder_count[target_remainder] + remainder_count[remainder] += 1 + + return complete_day_pairs + +``` + +### Code (C++): + +```cpp +#include +#include +using namespace std; + +int countCompleteDayPairs(vector& hours) { + unordered_map remainder_count; + int complete_day_pairs = 0; + + for (int hour : hours) { + int remainder = hour % 24; + int target_remainder = (24 - remainder) % 24; + complete_day_pairs += remainder_count[target_remainder]; + remainder_count[remainder]++; + } + + return complete_day_pairs; +} + +``` + +### Code (Java): + +```java +import java.util.HashMap; +import java.util.Map; + +public class CompleteDayPairs { + public int countCompleteDayPairs(int[] hours) { + Map remainderCount = new HashMap<>(); + int completeDayPairs = 0; + + for (int hour : hours) { + int remainder = hour % 24; + int targetRemainder = (24 - remainder) % 24; + completeDayPairs += remainderCount.getOrDefault(targetRemainder, 0); + remainderCount.put(remainder, remainderCount.getOrDefault(remainder, 0) + 1); + } + + return completeDayPairs; + } +} +``` + +### Code (JavaScript): + +```javascript +function countCompleteDayPairs(hours) { + const remainderCount = new Map(); + let completeDayPairs = 0; + + for (const hour of hours) { + const remainder = hour % 24; + const targetRemainder = (24 - remainder) % 24; + completeDayPairs += (remainderCount.get(targetRemainder) || 0); + remainderCount.set(remainder, (remainderCount.get(remainder) || 0) + 1); + } + + return completeDayPairs; +} + +``` diff --git a/solutions/lc-solutions/3100-3199/3185-Count Pairs That Form a Complete Day II.md b/solutions/lc-solutions/3100-3199/3185-Count Pairs That Form a Complete Day II.md new file mode 100644 index 0000000..4fb35a8 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3185-Count Pairs That Form a Complete Day II.md @@ -0,0 +1,49 @@ +--- +id: 3185-Count-Pairs-That-Form-a-Complete-Day-II +title: Count Pairs That Form a Complete Day II +sidebar_label: Count Pairs That Form a Complete Day II +tags: + - Bit Manipulation + - C++ + - Java + - Python +description: "This document provides solutions for finding the maximum total reward using dynamic programming and bit manipulation, implemented in C++, Java, and Python." +--- + +## Problem + +Given an integer array hours representing times in hours, return an integer denoting the number of pairs i, j where i < j and hours[i] + hours[j] forms a complete day. +A complete day is defined as a time duration that is an exact multiple of 24 hours. +For example, 1 day is 24 hours, 2 days is 48 hours, 3 days is 72 hours, and so on. + +## Solution + +Use hours % 24 to get the remainder of each hour value when divided by 24. Then, calculate the complement of the remainder by subtracting it from 24. + +## Code in Different Languages + +### Python + +```python +class Solution: + def countCompleteDayPairs(self, h: List[int]) -> int: + rc = [0] * 24 + count = 0 + for hour in h: + r = hour % 24 + c = (24 - r) % 24 + count += rc[c] + rc[r] += 1 + return count +``` + +# Complexity Analysis + +## Time Complexity: + +$O(n \times k)$, where hour is the number of reward values and k is the maximum possible reward value. Sorting the reward values takes O(n log n) time, and each bit manipulation operation is efficient. + +## Space Complexity: + +$O(n log n)$ +Reason: hours % 24 will have at most 24 different values, so the size of the rc array is constant. diff --git a/solutions/lc-solutions/3100-3199/3190-find-minimum-operations-to-make-all-elements-divisible-by-three.md b/solutions/lc-solutions/3100-3199/3190-find-minimum-operations-to-make-all-elements-divisible-by-three.md new file mode 100644 index 0000000..4e4f38b --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3190-find-minimum-operations-to-make-all-elements-divisible-by-three.md @@ -0,0 +1,92 @@ +--- +id: minimum-operations-to-make-all-elements-divisible-by-three +title: Find Minimum Operations to Make All Elements Divisible by Three +level: medium +sidebar_label: Minimum Operations to Make All Elements Divisible by Three +tags: + - Array + - Math + - Java + - Python +description: "This document provides solutions for the Find Minimum Operations to Make All Elements Divisible by Three problem." +--- + +## Problem Statement + +You are given an integer array `nums`. In one operation, you can add or subtract 1 from any element of `nums`. + +Return the minimum number of operations to make all elements of `nums` divisible by 3. + +**Example 1:** + +Input: `nums = [1, 2, 3, 4]` +Output: `3` + +Explanation: +All array elements can be made divisible by 3 using 3 operations: +- Subtract 1 from 1. +- Add 1 to 2. +- Subtract 1 from 4. + +**Example 2:** + +Input: `nums = [3, 6, 9]` +Output: `0` + +**Constraints:** + +- `1 <= nums.length <= 50` +- `1 <= nums[i] <= 50` + +## Solutions + +### Intuition + +To make all elements divisible by 3, we need to adjust each element by either adding or subtracting 1 until its remainder when divided by 3 is zero. Each adjustment operation (either adding or subtracting 1) counts as one operation. + +### Approach + +1. Iterate through each element in the array. +2. For each element, check its remainder when divided by 3. +3. If the remainder is 1 or 2, it means we need one operation to make it divisible by 3 (subtract 1 if the remainder is 1, or add 1 if the remainder is 2). +4. Sum up the number of operations required for each element. + +### Implementation + +The provided code effectively implements the above approach. Here's the breakdown: + +1. **Iteration and Remainder Check:** + - Iterate through each element in the `nums` array. + - Check the remainder of each element when divided by 3. + - Increment the operations counter based on the remainder. + +### Java + +```java +class Solution { + public int minimumOperations(int[] nums) { + int operations = 0; + for (int n : nums) { + if (n % 3 == 1 || n % 3 == 2) { + operations++; + } + } + return operations; + } +} +``` +### Python + +```Python +class Solution: + def minimumOperations(self, nums: List[int]) -> int: + operations = 0 + for n in nums: + if n % 3 == 1 or n % 3 == 2: + operations += 1 + return operations + +``` + +### Conclusion +This implementation efficiently computes the minimum operations required to make all elements of nums divisible by 3 by iterating through the array and counting adjustments needed based on remainders. diff --git a/solutions/lc-solutions/3100-3199/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-I.md b/solutions/lc-solutions/3100-3199/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-I.md new file mode 100644 index 0000000..a9050cb --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3191-minimum-operations-to-make-binary-array-elements-equal-to-one-I.md @@ -0,0 +1,151 @@ +--- +id: minimum-operations-to-make-binary-array-elements-equal-to-one-I +title: Minimum Operations to Make Binary Array Elements Equal to One I +sidebar_label: 3191-Minimum Operations to Make Binary Array Elements Equal to One I +tags: + - Array + - Sliding Window + - Prefix Sum + +description: "This is a solution to the Minimum Operations to Make Binary Array Elements Equal to One I in leetcode" +--- + +## Problem Description + +You are given a binary array nums. + +You can do the following operation on the array any number of times (possibly zero): + +- Choose any 3 consecutive elements from the array and flip all of them. +Flipping an element means changing its value from 0 to 1, and from 1 to 0. + +Return the minimum number of operations required to make all elements in nums equal to 1. If it is impossible, return -1. + + + +### Examples + +**Example 1:** + +``` +Input: nums = [0,1,1,1,0,0] +Output: 3 +Explanation: +We can do the following operations: +Choose the elements at indices 0, 1 and 2. The resulting array is nums = [1,0,0,1,0,0]. +Choose the elements at indices 1, 2 and 3. The resulting array is nums = [1,1,1,0,0,0]. +Choose the elements at indices 3, 4 and 5. The resulting array is nums = [1,1,1,1,1,1]. + +``` +**Example 2:** +``` +Input: nums = [0,1,1,1] + +Output: -1 + +Explanation: +It is impossible to make all elements equal to 1. + + + ``` +## Complexity Analysis + +*** Time Complexity:** $O(n)$ + +*** Space Complexity:** $O(1)$ + +### Constraints + +- `3 <= nums.length <= 105` +- `3 <= nums.length <= 105` + + + +### Solution +## Approach +The approach involves iterating through the array and flipping segments of three consecutive elements whenever a 0 is encountered, starting from the beginning. For each 0 at index "i", the elements at "i", "i+1", and "i+2" are flipped (0 to 1, and 1 to 0), and an operation counter is incremented. After processing up to the third last element, the array is checked from the third last to the last element to ensure no 0s remain. If any 0s are found, return -1, indicating it is impossible to make all elements 1; otherwise, return the counter representing the number of operations performed. + +## Code in Different Languages + + + + + +```cpp +class Solution { +public: + int minOperations(std::vector& nums) { + int c = 0; + for (int i = 0; i <= nums.size() - 3; ++i) { + if (nums[i] == 0) { + nums[i] = 1 - nums[i]; + nums[i + 1] = 1 - nums[i + 1]; + nums[i + 2] = 1 - nums[i + 2]; + c++; + } + } + for (int i = nums.size() - 3; i < nums.size(); ++i) { + if (nums[i] == 0) + return -1; + } + return c; + } +}; + + +``` + + + + +```java +class Solution { + public int minOperations(int[] nums) { + int c=0; + for(int i=0;i<=nums.length-3;++i){ + if(nums[i]==0){ + nums[i]=1-nums[i]; + nums[i+1]=1-nums[i+1]; + nums[i+2]=1-nums[i+2]; + c++; + } + } + for(int i=nums.length-3;i + + + +```python +class Solution: + def minOperations(self, nums: list[int]) -> int: + c = 0 + for i in range(len(nums) - 2): + if nums[i] == 0: + nums[i] = 1 - nums[i] + nums[i + 1] = 1 - nums[i + 1] + nums[i + 2] = 1 - nums[i + 2] + c += 1 + + for i in range(len(nums) - 3, len(nums)): + if nums[i] == 0: + return -1 + + return c + + +``` + + + +## References + +- **LeetCode Problem**: [Minimum Operations to Make Binary Array Elements Equal to One I](https://leetcode.com/problems/minimum-operations-to-make-binary-array-elements-equal-to-one-i/description/) + +- **Solution Link**: [Minimum Operations to Make Binary Array Elements Equal to One I](https://leetcode.com/problems/minimum-operations-to-make-binary-array-elements-equal-to-one-i/post-solution/?submissionId=1296819334) diff --git a/solutions/lc-solutions/3100-3199/3192-minimum-operations-to-make-binary-array-elements-equal-to-one-ii.md b/solutions/lc-solutions/3100-3199/3192-minimum-operations-to-make-binary-array-elements-equal-to-one-ii.md new file mode 100644 index 0000000..74b4417 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3192-minimum-operations-to-make-binary-array-elements-equal-to-one-ii.md @@ -0,0 +1,138 @@ +--- +id: minimum-operations-to-make-binary-array-elements-equal-to-one-ii +title: Minimum Operations to Make Binary Array Elements Equal to One II +sidebar_label: Minimum Operations II +tags: + - Array + - Two Pointers + - Greedy + - C++ + - Java + - Python +description: "This document provides solutions for the Minimum Operations to Make Binary Array Elements Equal to One II problem on LeetCode." +--- + +## Problem Statement + +You are given a binary array `nums`. + +You can perform the following operation any number of times: choose two indices `L` and `R` such that `0 <= L, R < nums.length` and flip every `0` to `1` and every `1` to `0` in the subarray `nums[L...R]` (inclusive). + +Return the minimum number of operations needed to make `nums` contain only `1`s. + +**Example 1:** + +Input: `nums = [1,1,0,1]` +Output: `1` + +Explanation: Flip the element at index 2 (0-indexed) to get `[1,1,1,1]`. + +**Example 2:** + +Input: `nums = [0,1,1,0]` +Output: `2` + +Explanation: Flip the elements at index 0 and 3 (0-indexed) to get `[1,1,1,1]`. + +Constraints: +- `1 <= nums.length <= 10^5` +- `nums[i]` is either `0` or `1`. + +## Solutions + +### Approach + +The goal is to minimize the number of operations required to convert all elements of the array `nums` to `1`. The operations allowed involve flipping subarrays of `nums`. + +#### Intuition + +To achieve this efficiently: +1. **Prefix Sum Calculation**: Compute the prefix sums of `nums` such that `prefix[i]` represents the number of `0`s in `nums[0...i-1]`. + +2. **Two Pointers Technique**: Use two pointers (`left` and `right`) to determine the range `[L, R]` where flipping would be most effective. This involves: + - Calculating the total number of `0`s in `nums` initially. + - Iteratively adjusting the range `[L, R]` to minimize the number of `0`s. + +#### Steps + +1. **Initialization**: Initialize `left` and `right` pointers at the start of the array. Compute the initial count of `0`s in `nums`. + +2. **Iterative Adjustment**: Iterate through possible ranges `[L, R]`: + - Update the count of `0`s by including `nums[right]` and excluding `nums[left]`. + - Update the minimum operations required based on the count of `0`s. + +3. **Edge Cases**: Handle arrays where all elements are initially `1`. + +#### Complexity + +- **Time Complexity**: `O(n)` where `n` is the length of `nums`. This is because we iterate through the array with two pointers. +- **Space Complexity**: `O(1)` extra space for variables. + +### Implementation (Java) + +```java +class Solution { + public int minOperations(int[] nums) { + int n = nums.length; + int left = 0, right = 0; + int countZeros = 0; + int minOps = Integer.MAX_VALUE; + + for (int num : nums) { + if (num == 0) { + countZeros++; + } + } + + int currentOps = countZeros; + + while (right < n) { + if (nums[right] == 0) { + countZeros--; + } + right++; + + while (countZeros * 2 <= right - left) { + if (nums[left] == 0) { + countZeros++; + } + left++; + } + + minOps = Math.min(minOps, currentOps); + } + + return minOps == Integer.MAX_VALUE ? 0 : minOps; + } +} +``` + +### Implementation (Python) + +```python +class Solution: + def minOperations(self, nums): + n = len(nums) + left = 0 + right = 0 + countZeros = sum(1 for num in nums if num == 0) + minOps = float('inf') + currentOps = countZeros + + while right < n: + if nums[right] == 0: + countZeros -= 1 + right += 1 + + while countZeros * 2 <= right - left: + if nums[left] == 0: + countZeros += 1 + left += 1 + + minOps = min(minOps, currentOps) + + return minOps if minOps != float('inf') else 0 +``` + +## Conclusion +This implementation efficiently calculates the minimum operations required to convert the binary array nums into an array containing only 1s using a two-pointer technique. Adjustments can be made according to specific platform requirements or further customization needs. diff --git a/solutions/lc-solutions/3100-3199/3194-minimum-average-of-smallest-and-largest-elements.md b/solutions/lc-solutions/3100-3199/3194-minimum-average-of-smallest-and-largest-elements.md new file mode 100644 index 0000000..5de81b1 --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3194-minimum-average-of-smallest-and-largest-elements.md @@ -0,0 +1,103 @@ +--- +id: minimum-average-of-smallest-and-largest-elements +title: Minimum Average of Smallest and Largest Elements +sidebar_label: Minimum Average of Smallest and Largest Elements +tags: + - Array + - Sorting + - Two Pointers + - Java + - Python +description: "This document provides solutions for the Minimum Average of Smallest and Largest Elements problem." +--- + +## Problem Statement + +Given an integer array `nums`, find the minimum possible average of any sublist of `nums` after sorting the array in non-decreasing order. + +**Example:** + +Input: `nums = [3, 1, 2, 4, 3]` +Output: `3.0` + +Explanation: +Sort the array to get `[1, 2, 3, 3, 4]`. +Sublists with minimum average: + +``` +- [1, 2, 3] -> Average = (1 + 2 + 3) / 3 = 2.0 +- [2, 3, 3] -> Average = (2 + 3 + 3) / 3 = 2.67 +- [3, 3, 4] -> Average = (3 + 3 + 4) / 3 = 3.33 +``` + +The minimum average is `2.0`. + +**Constraints:** + +- `1 <= nums.length <= 100` +- `-10^5 <= nums[i] <= 10^5` + +## Solutions + +### Intuition + +To find the minimum average of any sublist after sorting, we can leverage the property that the sublist with the minimum average will consist of the smallest and largest elements from the sorted array. + +### Approach + +1. **Sort the Array:** + - Sort the given array `nums` in non-decreasing order. + +2. **Two Pointers Technique:** + - Use two pointers `left` starting at the beginning (`0`) and `right` at the end (`nums.length - 1`) of the sorted array. + - Calculate the average of `nums[left]` and `nums[right]`. + - Update the minimum average if the current average is smaller. + - Move `left` pointer to the right and `right` pointer to the left to consider the next pair of smallest and largest elements. + +3. **Compute Minimum Average:** + - Iterate until `left` is less than `right`. + - The minimum average found during iterations is the desired result. + +### Java + +```java +import java.util.Arrays; + +class Solution { + public double minimumAverage(int[] nums) { + Arrays.sort(nums); + int left = 0, right = nums.length - 1; + double minAvg = Double.MAX_VALUE; + + while (left < right) { + double avg = (double) (nums[left] + nums[right]) / 2; + minAvg = Math.min(minAvg, avg); + left++; + right--; + } + + return minAvg; + } +} +``` + +### Python + +```Python +class Solution: + def minimumAverage(self, nums: List[int]) -> float: + nums.sort() + left, right = 0, len(nums) - 1 + min_avg = float('inf') + + while left < right: + avg = (nums[left] + nums[right]) / 2.0 + min_avg = min(min_avg, avg) + left += 1 + right -= 1 + + return min_avg +``` + +## Conclusion +The above implementations in Java and Python effectively find the minimum possible average of any sublist of nums after sorting using the two pointers technique, ensuring efficient computation. diff --git a/solutions/lc-solutions/3100-3199/3195-find-the-minimum-area-to-cover-all-ones-i.md b/solutions/lc-solutions/3100-3199/3195-find-the-minimum-area-to-cover-all-ones-i.md new file mode 100644 index 0000000..54f6ebf --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3195-find-the-minimum-area-to-cover-all-ones-i.md @@ -0,0 +1,302 @@ +--- +id: find-the-minimum-area-to-cover-all-ones-i +title: Find the Minimum Area to Cover All Ones I +sidebar_label: 3195. Find the Minimum Area to Cover All Ones I +tags: +- Array +- Matrix + + +description: "This is a solution to the Find the Minimum Area to Cover All Ones I problem on LeetCode." +--- + +## Problem Description +You are given a 2D binary array grid. Find a rectangle with horizontal and vertical sides with the smallest area, such that all the 1's in grid lie inside this rectangle. + +Return the minimum possible area of the rectangle. + + +### Examples + +**Example 1:** + +![image](https://assets.leetcode.com/uploads/2024/05/08/examplerect0.png) +``` +Input: grid = [[0,1,0],[1,0,1]] + +Output: 6 + +``` + +**Example 2:** +``` +Input: grid = [[1,0],[0,0]] + +Output: 1 +``` + +### Constraints + +- `1 <= grid.length, grid[i].length <= 1000` +-`grid[i][j] is either 0 or 1.` +- `The input is generated such that there is at least one 1 in grid.` + +## Solution for Find the Minimum Area to Cover All Ones I Problem +### Approach + +1. **Initialization**: + - Use four variables `st`, `end`, `top`, and `bottom` to track the minimum and maximum column and row indices of the 1's in the grid: + - `st`: The leftmost column index containing a 1 (initialized to infinity). + - `end`: The rightmost column index containing a 1 (initialized to negative infinity). + - `top`: The topmost row index containing a 1 (initialized to infinity). + - `bottom`: The bottommost row index containing a 1 (initialized to negative infinity). + +2. **Iterate Through the Grid**: + - Loop through each cell in the grid. For each cell that contains a 1: + - Update `st` to be the minimum of `st` and the current column index `j`. + - Update `end` to be the maximum of `end` and the current column index `j`. + - Update `top` to be the minimum of `top` and the current row index `i`. + - Update `bottom` to be the maximum of `bottom` and the current row index `i`. + +3. **Check for Edge Case**: + - After iterating through the grid, if `st` is still infinity (no 1's were found), return 0. This indicates that there are no 1's in the grid. + +4. **Calculate the Area**: + - Compute the height of the rectangle as `bottom - top + 1`. + - Compute the width of the rectangle as `end - st + 1`. + - Return the area as `height * width`. + + + + + #### Implementation + ```jsx live + function Solution(arr) { + function minimumArea(grid) { + let st = Infinity; + let end = -Infinity; + let top = Infinity; + let bottom = -Infinity; + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + if (grid[i][j] === 1) { + st = Math.min(st, j); + end = Math.max(end, j); + top = Math.min(top, i); + bottom = Math.max(bottom, i); + } + } + } + + if (st === Infinity || end === -Infinity || top === Infinity || bottom === -Infinity) { + return 0; + } + + const height = bottom - top + 1; + const width = end - st + 1; + + return height * width; + } + const input =[[0,1,0],[1,0,1]] + const output = minimumArea(input) ; + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $ O(n^2) $ because of sorting, where n is the size of array + - Space Complexity: $ O(1) $ + + ## Code in Different Languages + + + + ```javascript + class Solution { + minimumArea(grid) { + let st = Infinity; + let end = -Infinity; + let top = Infinity; + let bottom = -Infinity; + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + if (grid[i][j] === 1) { + st = Math.min(st, j); + end = Math.max(end, j); + top = Math.min(top, i); + bottom = Math.max(bottom, i); + } + } + } + + if (st === Infinity || end === -Infinity || top === Infinity || bottom === -Infinity) { + return 0; + } + + const height = bottom - top + 1; + const width = end - st + 1; + + return height * width; + } +} + + ``` + + + + + ```typescript + class Solution { + minimumArea(grid: number[][]): number { + let st = Infinity; + let end = -Infinity; + let top = Infinity; + let bottom = -Infinity; + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + if (grid[i][j] === 1) { + st = Math.min(st, j); + end = Math.max(end, j); + top = Math.min(top, i); + bottom = Math.max(bottom, i); + } + } + } + + if (st === Infinity || end === -Infinity || top === Infinity || bottom === -Infinity) { + return 0; + } + + const height = bottom - top + 1; + const width = end - st + 1; + + return height * width; + } +} + + ``` + + + + ```python + class Solution: + def minimumArea(self, grid: List[List[int]]) -> int: + st = float('inf') + end = float('-inf') + top = float('inf') + bottom = float('-inf') + + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] == 1: + st = min(st, j) + end = max(end, j) + top = min(top, i) + bottom = max(bottom, i) + + if st == float('inf') or end == float('-inf') or top == float('inf') or bottom == float('-inf'): + return 0 + + height = bottom - top + 1 + width = end - st + 1 + + return height * width + + ``` + + + + + ```java + public class Solution { + public int minimumArea(int[][] grid) { + int st = Integer.MAX_VALUE; + int end = Integer.MIN_VALUE; + int top = Integer.MAX_VALUE; + int bottom = Integer.MIN_VALUE; + + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + if (grid[i][j] == 1) { + st = Math.min(st, j); + end = Math.max(end, j); + top = Math.min(top, i); + bottom = Math.max(bottom, i); + } + } + } + + if (st == Integer.MAX_VALUE || end == Integer.MIN_VALUE || top == Integer.MAX_VALUE || bottom == Integer.MIN_VALUE) { + return 0; + } + + int height = bottom - top + 1; + int width = end - st + 1; + + return height * width; + } +} + + ``` + + + + + ```cpp + class Solution { +public: + int minimumArea(vector>& grid) { + int st = INT_MAX; + int end = INT_MIN; + int top = INT_MAX; + int bottom = INT_MIN; + + for (int i = 0; i < grid.size(); i++) { + for (int j = 0; j < grid[0].size(); j++) { + if (grid[i][j] == 1) { + st = min(st, j); + end = max(end, j); + top = min(top, i); + bottom = max(bottom, i); + } + } + } + + if (st == INT_MAX || end == INT_MIN || top == INT_MAX || bottom == INT_MIN) { + return 0; + } + + int height = bottom - top + 1; + int width = end - st + 1; + + return height * width; + } +}; + + ``` + + + +
+
+ +## References + +- **LeetCode Problem**: [Find the Minimum Area to Cover All Ones I](https://leetcode.com/problems/find-the-minimum-area-to-cover-all-ones-i/description/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/find-the-minimum-area-to-cover-all-ones-i/description/) + diff --git a/solutions/lc-solutions/3100-3199/3199- Maximum Number of Potholes That Can Be Fixed.md b/solutions/lc-solutions/3100-3199/3199- Maximum Number of Potholes That Can Be Fixed.md new file mode 100644 index 0000000..3978c7b --- /dev/null +++ b/solutions/lc-solutions/3100-3199/3199- Maximum Number of Potholes That Can Be Fixed.md @@ -0,0 +1,83 @@ +--- +id: maximum-number-of-potholes-that-can-be-fixed +title: maximum number of potholes that can be fixed +sidebar_label: 3119. maximum number of potholes that can be fixed +tags: +- String +- Greedy +- Sorting +description: "The given Solution class uses a greedy approach to maximize the number of potholes repaired within the given budget by prioritizing the repair of larger contiguous pothole segments first." +--- + + + +## Problem + +You are given an integer array $nums$ and two integers $cost1$ and $cost2$. You are allowed to perform either of the following operations any number of times: + +- Choose an index $i$ from nums and increase $nums[i]$ by $1$ for a cost of $cost1$. + +- Choose two different indices $i$, $j$, from nums and increase $nums[i]$ and $nums[j]$ by $1$ for a cost of $cost2$. + + +### Constraints + +- `1 <= road.length <= 105` +- `1 <= budget <= 105 + 1` +- oad consists only of characters '.' and 'x' +--- + +## Approach + +Approach: Greedy Algorithm +Identify Pothole Segments: + +The getSortedPotholeLengths method processes the input string road, which represents a road with potholes as segments of characters other than '.'. +This method splits the road string by the character '.', which separates the potholes, and calculates the length of each pothole segment. +It then sorts these lengths in descending order to prioritize repairing the largest potholes first. +Prioritize Larger Potholes: + +By sorting the pothole lengths in descending order, the algorithm ensures that it considers the largest potholes first. This is a key part of the greedy strategy, aiming to get the maximum immediate benefit from the budget. +Budget Management: + +The main method maxPotholes iterates over the sorted pothole lengths. +For each pothole length, it calculates the maximum number of potholes that can be repaired given the remaining budget. Specifically, for each pothole segment, the cost to repair it is the length of the segment plus one (the cost of repairing the segment plus a fixed cost for starting the repair process). +If the current pothole segment can be fully repaired within the remaining budget, the algorithm repairs it and updates the budget accordingly. +If the current pothole segment cannot be fully repaired within the remaining budget, the algorithm calculates how many potholes can be repaired with the remaining budget and returns the total number of potholes repaired so far. + +## Maximum Number of Potholes That Can Be Fixed +The greedy approach focuses on repairing the largest potholes first to maximize the number of potholes that can be repaired within the given budget. The sorted list of pothole lengths allows the algorithm to quickly determine the most cost-effective repairs at each step, ensuring that the budget is utilized efficiently. + +#### Code in Java + +```java +class Solution { + public int maxPotholes(String road, int budget) { + int ans = 0; + + for (final int length : getSortedPotholeLengths(road)) { + final int canRepair = Math.max(0, budget - 1); + if (length > canRepair) + return ans + canRepair; + ans += length; + budget -= length + 1; + } + + return ans; + } + + private List getSortedPotholeLengths(final String road) { + List potholeLengths = new ArrayList<>(); + for (String pothole : road.split("\\.")) + potholeLengths.add(pothole.length()); + Collections.sort(potholeLengths, Collections.reverseOrder()); + return potholeLengths; + } +} + +### Complexity Analysis + +#### Time Complexity: $𝑂(n)$ + +#### Space Complexity: O(n) + diff --git a/solutions/lc-solutions/3100-3199/_category_.json b/solutions/lc-solutions/3100-3199/_category_.json new file mode 100644 index 0000000..048195d --- /dev/null +++ b/solutions/lc-solutions/3100-3199/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "3100-3199", + "position": 33, + "link": { + "type": "generated-index", + "description": "Solutions categorised by Problem IDs (3100 - 3199)" + } +} diff --git a/solutions/lc-solutions/3100-3199/image-1.png b/solutions/lc-solutions/3100-3199/image-1.png new file mode 100644 index 0000000..1d8fdea Binary files /dev/null and b/solutions/lc-solutions/3100-3199/image-1.png differ diff --git a/solutions/lc-solutions/3100-3199/image-2.png b/solutions/lc-solutions/3100-3199/image-2.png new file mode 100644 index 0000000..80d58c2 Binary files /dev/null and b/solutions/lc-solutions/3100-3199/image-2.png differ diff --git a/solutions/lc-solutions/3100-3199/image-3.png b/solutions/lc-solutions/3100-3199/image-3.png new file mode 100644 index 0000000..f8f1895 Binary files /dev/null and b/solutions/lc-solutions/3100-3199/image-3.png differ diff --git a/solutions/lc-solutions/3100-3199/image-4.png b/solutions/lc-solutions/3100-3199/image-4.png new file mode 100644 index 0000000..9f6e80c Binary files /dev/null and b/solutions/lc-solutions/3100-3199/image-4.png differ diff --git a/solutions/lc-solutions/3100-3199/image-5.png b/solutions/lc-solutions/3100-3199/image-5.png new file mode 100644 index 0000000..a37d998 Binary files /dev/null and b/solutions/lc-solutions/3100-3199/image-5.png differ diff --git a/solutions/lc-solutions/3100-3199/image.png b/solutions/lc-solutions/3100-3199/image.png new file mode 100644 index 0000000..c7dd14a Binary files /dev/null and b/solutions/lc-solutions/3100-3199/image.png differ diff --git a/solutions/lc-solutions/3200-3299/3211-generate-binary-strings-without-adjacent-zeros.md b/solutions/lc-solutions/3200-3299/3211-generate-binary-strings-without-adjacent-zeros.md new file mode 100644 index 0000000..e7d2609 --- /dev/null +++ b/solutions/lc-solutions/3200-3299/3211-generate-binary-strings-without-adjacent-zeros.md @@ -0,0 +1,162 @@ +--- +id: generate-binary-strings-without-adjacent-zeros +title: 3211. Generate Binary Strings Without Adjacent Zeros +sidebar_label: 3211. Generate Binary Strings Without Adjacent Zeros +tags: +- String +- Bit Manipulation +- Recursion + +description: "This is a solution to the 3211. Generate Binary Strings Without Adjacent Zeros." +--- + +## Problem Description +You are given a positive integer n. +A binary string x is valid if all +substrings + of x of length 2 contain at least one "1". + +Return all valid strings with length n, in any order. + ### Examples +**Example 1:** +``` +Input: n = 3 + +Output: ["010","011","101","110","111"] + +Explanation: + +The valid strings of length 3 are: "010", "011", "101", "110", and "111". +``` + +**Example 2:** +``` +Input: n = 1 + +Output: ["0","1"] + +Explanation: + +The valid strings of length 1 are: "0" and "1". +``` + +### Constraints +- `1 <= n <= 18` +## Solution for 3211. Generate Binary Strings Without Adjacent Zeros + +To solve this problem, we can use DFS to check recursively all possible solutions. + +## Approach + +1. Start with an empty string and begin at position `i = 0`. +2. For each position `i` in the binary string of length `n`, consider two possible values: `0` and `1`. +3. +3.1. If you choose `0`, ensure the previous character (at position `i-1`) is `1` to maintain validity (i.e., avoid consecutive 00). +3.2. If valid, recursively move to the next position. +4. If you choose `1`, it’s always valid. Recursively move to the next position. +5. When you reach the end of the string (length `n`), add the valid string to the result. +6. Continue until all valid strings of length `n` are generated. +7. Collect and return all the valid strings. + +### Code in Different Languages + + + + + +```cpp +class Solution { +public: + vector validStrings(int n) { + vector ans; + string t; + auto dfs = [&](auto&& dfs, int i) { + if (i >= n) { + ans.emplace_back(t); + return; + } + for (int j = 0; j < 2; ++j) { + if ((j == 0 && (i == 0 || t[i - 1] == '1')) || j == 1) { + t.push_back('0' + j); + dfs(dfs, i + 1); + t.pop_back(); + } + } + }; + dfs(dfs, 0); + return ans; + } +}; +``` + + + +```java +class Solution { + private List ans = new ArrayList<>(); + private StringBuilder t = new StringBuilder(); + private int n; + + public List validStrings(int n) { + this.n = n; + dfs(0); + return ans; + } + + private void dfs(int i) { + if (i >= n) { + ans.add(t.toString()); + return; + } + for (int j = 0; j < 2; ++j) { + if ((j == 0 && (i == 0 || t.charAt(i - 1) == '1')) || j == 1) { + t.append(j); + dfs(i + 1); + t.deleteCharAt(t.length() - 1); + } + } + } +} +``` + + + + + + +```python +class Solution: + def validStrings(self, n: int) -> List[str]: + def dfs(i: int): + if i >= n: + ans.append("".join(t)) + return + for j in range(2): + if (j == 0 and (i == 0 or t[i - 1] == "1")) or j == 1: + t.append(str(j)) + dfs(i + 1) + t.pop() + + ans = [] + t = [] + dfs(0) + return ans +``` + + + + +#### Complexity Analysis + +- **Time Complexity**: The time complexity is $O(n \times 2^n)$ , where n is the length of the string. +- **Space Complexity**: Ignoring the space consumption of the answer array, the space complexity is $O(n)$ . + +--- + +

Authors:

+ +
+{['nagalakshmi08'].map(username => ( + +))} +
diff --git a/solutions/lc-solutions/3200-3299/3216-lexicographically-smallest-string-after-a-swap.md b/solutions/lc-solutions/3200-3299/3216-lexicographically-smallest-string-after-a-swap.md new file mode 100644 index 0000000..5c9298e --- /dev/null +++ b/solutions/lc-solutions/3200-3299/3216-lexicographically-smallest-string-after-a-swap.md @@ -0,0 +1,181 @@ +--- +id: lexicographically-smallest-string-after-a-swap +title: 3216. Lexicographically Smallest String After a Swap +sidebar_label: 3216. Lexicographically Smallest String After a Swap +tags: +- String + +description: "This is a solution to the 3216. Lexicographically Smallest String After a Swap problem on LeetCode." +--- + +## Problem Description +Given a string s containing only digits, return the +lexicographically smallest string + that can be obtained after swapping adjacent digits in s with the same parity at most once. + +Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not. + ### Examples +**Example 1:** +``` +Input: s = "45320" + +Output: "43520" + +Explanation: + +s[1] == '5' and s[2] == '3' both have the same parity, and swapping them results in the lexicographically smallest string. +``` + +### Constraints +- `1 <= s.length <= 10^5` +## Solution for 3216. Lexicographically Smallest String After a Swap + + + + + #### Implementation + ```jsx live + function Solution(arr) { + var getSmallestString = function(s) { + let ans = s; + let charArray = s.split(''); + + for (let i = 0; i < charArray.length - 1; i++) { + let a = charArray[i].charCodeAt(0) - '0'.charCodeAt(0); + let b = charArray[i + 1].charCodeAt(0) - '0'.charCodeAt(0); + + if ((a & 1) === (b & 1)) { + swap(charArray, i, i + 1); + let temp = charArray.join(''); + if (temp < ans) { + ans = temp; + } + swap(charArray, i, i + 1); + } + } + return ans; +}; + +function swap(array, i, j) { + let temp = array[i]; + array[i] = array[j]; + array[j] = temp; +} + + const input = "45320" + const output = getSmallestString(input) + return ( +
+

+ Input: + {JSON.stringify(input)} +

+

+ Output: {output.toString()} +

+
+ ); + } + ``` + + #### Complexity Analysis + + - Time Complexity: $O(n) $ + - Space Complexity: $ O(1)$ + + ## Code in Different Languages + + + + ```python + class Solution: + def getSmallestString(self, s: str) -> str: + ans = s + s = list(s) + + for i in range(len(s) - 1): + a = int(s[i]) + b = int(s[i + 1]) + + if (a & 1) == (b & 1): + s[i], s[i + 1] = s[i + 1], s[i] + temp = ''.join(s) + if temp < ans: + ans = temp + s[i], s[i + 1] = s[i + 1], s[i] + + return ans + + ``` + + + + + ```java +public class Solution { + public String getSmallestString(String s) { + String ans = s; + char[] charArray = s.toCharArray(); + + for (int i = 0; i < charArray.length - 1; i++) { + int a = charArray[i] - '0'; + int b = charArray[i + 1] - '0'; + + if ((a & 1) == (b & 1)) { + swap(charArray, i, i + 1); + String temp = new String(charArray); + if (temp.compareTo(ans) < 0) { + ans = temp; + } + swap(charArray, i, i + 1); + } + } + return ans; + } + + private void swap(char[] array, int i, int j) { + char temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } +} + + ``` + + + + + + ```cpp + class Solution { +public: + string getSmallestString(string s) { + string ans = s; + for (int i = 0; i < s.size() - 1; i++) { + int a = s[i] - '0'; + int b = s[i + 1] - '0'; + + if ((a & 1) == (b & 1)) { + swap(s[i], s[i + 1]); + if (s < ans) { + ans = s; + } + swap(s[i], s[i + 1]); + } + } + return ans; + } +}; +``` + + + +
+
+ +## References + +- **LeetCode Problem**: [3216. Lexicographically Smallest String After a Swap](https://leetcode.com/problems/lexicographically-smallest-string-after-a-swap/) + +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/lexicographically-smallest-string-after-a-swap/) + diff --git a/solutions/lc-solutions/990 - Satisfiability of Equality Equations.md b/solutions/lc-solutions/990 - Satisfiability of Equality Equations.md new file mode 100644 index 0000000..3581d68 --- /dev/null +++ b/solutions/lc-solutions/990 - Satisfiability of Equality Equations.md @@ -0,0 +1,130 @@ +--- +id: satisfiability-of-equality-equations +title: Satisfiability of Equality Equations +sidebar_label: Satisfiability of Equality Equations +tags: [Graph, Union Find, Array, String, C++, Python, Java] +description: Determine if it is possible to assign integers to variable names to satisfy all given equality and inequality equations. +--- + +## Problem Statement + +### Problem Description + +You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length 4 and takes one of two different forms: `"xi==yi"` or `"xi!=yi"`. Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names. + +Return `true` if it is possible to assign integers to variable names so as to satisfy all the given equations, or `false` otherwise. + +### Example + +**Example 1:** +``` +Input: equations = ["a==b","b!=a"] +Output: false +``` +**Explanation:** If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second. There is no way to assign the variables to satisfy both equations. + + +### Constraints + +- $1 \leq \text{equations.length} \leq 500$ +- `equations[i].length == 4` +- `equations[i][0]` is a lowercase letter. +- `equations[i][1]` is either `'='` or `'!'`. +- `equations[i][2]` is `'='`. +- `equations[i][3]` is a lowercase letter. + +## Solution + +### Intuition + +The problem can be solved using Union-Find (Disjoint Set Union) data structure. The idea is to first process all equality equations to form connected components (sets of variables that must be equal). Then, we check all inequality equations to ensure that no two variables in an inequality equation belong to the same connected component. + +### Time Complexity and Space Complexity Analysis + +- **Time Complexity**: $O(n \log n)$, where $n$ is the number of equations. The Union-Find operations (union and find) are almost constant time due to path compression and union by rank. +- **Space Complexity**: $O(1)$, aside from the space used for storing the equations and Union-Find data structure. + +### Code + +#### C++ + +```cpp +class Solution { +public: + bool equationsPossible(vector& equations) { + vector parent(26); + iota(parent.begin(), parent.end(), 0); + + function find = [&](int x) { + return parent[x] == x ? x : parent[x] = find(parent[x]); + }; + + for (const auto& eq : equations) { + if (eq[1] == '=') { + parent[find(eq[0] - 'a')] = find(eq[3] - 'a'); + } + } + + for (const auto& eq : equations) { + if (eq[1] == '!' && find(eq[0] - 'a') == find(eq[3] - 'a')) { + return false; + } + } +``` +#### Python +```python +class Solution: + def equationsPossible(self, equations: List[str]) -> bool: + parent = list(range(26)) + + def find(x): + if parent[x] != x: + parent[x] = find(parent[x]) + return parent[x] + + for eq in equations: + if eq[1] == '=': + parent[find(ord(eq[0]) - ord('a'))] = find(ord(eq[3]) - ord('a')) + + for eq in equations: + if eq[1] == '!' and find(ord(eq[0]) - ord('a')) == find(ord(eq[3]) - ord('a')): + return False + + return True +``` +#### Java +```java +class Solution { + public boolean equationsPossible(String[] equations) { + int[] parent = new int[26]; + for (int i = 0; i < 26; ++i) { + parent[i] = i; + } + + for (String eq : equations) { + if (eq.charAt(1) == '=') { + parent[find(parent, eq.charAt(0) - 'a')] = find(parent, eq.charAt(3) - 'a'); + } + } + + for (String eq : equations) { + if (eq.charAt(1) == '!' && find(parent, eq.charAt(0) - 'a') == find(parent, eq.charAt(3) - 'a')) { + return false; + } + } + + return true; + } + + private int find(int[] parent, int x) { + if (parent[x] != x) { + parent[x] = find(parent, parent[x]); + } + return parent[x]; + } +} +``` + + return true; + } +}; diff --git a/solutions/lc-solutions/997 - Find the Town Judge.md b/solutions/lc-solutions/997 - Find the Town Judge.md new file mode 100644 index 0000000..3a9aa49 --- /dev/null +++ b/solutions/lc-solutions/997 - Find the Town Judge.md @@ -0,0 +1,123 @@ +--- +id: find-the-town-judge +title: Find the Town Judge +sidebar_label: Find the Town Judge +tags: [Graph, Array, C++, Python, Java] +description: Identify the town judge based on trust relationships in a town. +--- + +## Problem Statement + +### Problem Description + +In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge. + +If the town judge exists, then: + +1. The town judge trusts nobody. +2. Everybody (except for the town judge) trusts the town judge. +3. There is exactly one person that satisfies properties 1 and 2. + +You are given an array `trust` where `trust[i] = [a_i, b_i]` representing that the person labeled `a_i` trusts the person labeled `b_i`. If a trust relationship does not exist in `trust` array, then such a trust relationship does not exist. + +Return the label of the town judge if the town judge exists and can be identified, or return `-1` otherwise. + +### Example + +**Example 1:** +``` +Input: n = 2, trust = [[1,2]] +Output: 2 +``` +**Example 2:** +``` +Input: n = 3, trust = [[1,3],[2,3]] +Output: 3 +``` + +### Constraints + +- $1 \leq n \leq 1000$ +- $0 \leq \text{trust.length} \leq 10^4$ +- `trust[i].length == 2` +- All the pairs of trust are unique. +- $a_i \ne b_i$ +- $1 \leq a_i, b_i \leq n$ + +## Solution + +### Intuition + +To identify the town judge, we can use an array to keep track of the trust scores for each person. The trust score is increased by 1 for each person who trusts them and decreased by 1 for each person they trust. + +The town judge should have a trust score of `n-1` because they are trusted by everyone except themselves and they trust nobody. + +### Time Complexity and Space Complexity Analysis + +- **Time Complexity**: $O(n + \text{trust.length})$, where $n$ is the number of people and $\text{trust.length}$ is the number of trust relationships. +- **Space Complexity**: $O(n)$, for the trust score array. + +### Code + +#### C++ + +```cpp +class Solution { +public: + int findJudge(int n, vector>& trust) { + vector trustScores(n + 1, 0); + + for (const auto& t : trust) { + trustScores[t[0]]--; + trustScores[t[1]]++; + } + + for (int i = 1; i <= n; ++i) { + if (trustScores[i] == n - 1) { + return i; + } + } + + return -1; + } +}; +``` + +#### Python +```python +class Solution: + def findJudge(self, n: int, trust: List[List[int]]) -> int: + trust_scores = [0] * (n + 1) + + for a, b in trust: + trust_scores[a] -= 1 + trust_scores[b] += 1 + + for i in range(1, n + 1): + if trust_scores[i] == n - 1: + return i + + return -1 +``` + +#### Java +```java +class Solution { + public int findJudge(int n, int[][] trust) { + int[] trustScores = new int[n + 1]; + + for (int[] t : trust) { + trustScores[t[0]]--; + trustScores[t[1]]++; + } + + for (int i = 1; i <= n; i++) { + if (trustScores[i] == n - 1) { + return i; + } + } + + return -1; + } +} +``` diff --git a/solutions/lc-solutions/_category_.json b/solutions/lc-solutions/_category_.json new file mode 100644 index 0000000..ca76890 --- /dev/null +++ b/solutions/lc-solutions/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "LeetCode Solutions", + "position": 3, + "link": { + "type": "generated-index", + "description": "All LeetCode solutions in one place. Sorted by difficulty level, and by topics With problem description, solution, and explanation." + } + } \ No newline at end of file diff --git a/src/components/AdsComponent/index.tsx b/src/components/AdsComponent/index.tsx new file mode 100644 index 0000000..806123a --- /dev/null +++ b/src/components/AdsComponent/index.tsx @@ -0,0 +1,40 @@ +import React, { useEffect } from "react"; +import Head from "@docusaurus/Head"; + +declare global { + interface Window { + adsbygoogle: any[]; + } +} + +const AdsComponent: React.FC = () => { + useEffect(() => { + try { + (window.adsbygoogle = window.adsbygoogle || []).push({}); + } + catch (err) { + console.error(err); + } + }, []); + return ( + <> + +