Skip to content

Automated LeetCode problem solver using Puppeteer browser automation. Bulk submit coding solutions in Python, Java, C++, JavaScript. Educational tool for demonstrating web automation techniques.

License

Notifications You must be signed in to change notification settings

CPT-Dawn/LeetCode-Grinder

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🚀 LeetCode Grinder

License: MIT Node.js Version Version

"When your professor assigns 300 LeetCode problems due tomorrow at 9 AM, and it's already 11 PM..."
— Every CS Student Ever

LeetCode Grinder is your emergency response system for those totally reasonable academic situations where you need to demonstrate completion of hundreds of coding problems overnight. Built with Node.js and Puppeteer, it automates the submission process so you can focus on actually learning... or getting some sleep. 😴


📑 Table of Contents


⚠️ Legal & Ethical Disclaimer

Caution

READ THIS BEFORE USING THIS TOOL

🎓 Educational Purpose Only

This tool is created strictly for educational and project demonstration purposes. It showcases automation techniques, browser control, and software architecture patterns.

🚨 Emergency Use Only

This tool should ONLY be used in extreme situations such as:

  • Your institution assigns 300+ problems to be completed in 24 hours (because that's totally pedagogically sound 🙄)
  • You're demonstrating the capabilities of browser automation for a project
  • You're testing the robustness of your problem database
  • Your professor thinks sleep is optional and learning happens through quantity over quality

⚖️ Legal Considerations

  • LeetCode Terms of Service: This tool may violate LeetCode's Terms of Service. Use at your own risk.
  • Academic Integrity: Consult your institution's academic integrity policies before use.
  • No Warranty: This software is provided "as is" without any warranties (see MIT License).
  • Responsibility: The authors and contributors are not responsible for any consequences resulting from the use of this tool.

🌟 The Right Way to Use LeetCode

We strongly encourage you to:

  • Actually solve problems manually to build genuine problem-solving skills
  • Use LeetCode as a learning tool, not a checkbox exercise
  • Focus on understanding concepts rather than completing quantities
  • Give yourself adequate time to learn and practice

Remember: The goal is to become a better programmer, not to game a broken system. This tool exists to highlight how unreasonable some requirements can be, not to encourage academic dishonesty.


✨ Features

🔐 Automated Authentication

  • Seamless LeetCode login with session persistence
  • Beautiful in-browser UI with step-by-step instructions
  • Handles Cloudflare verification quirks automatically
  • Chrome profile caching for quick re-authentication

🎯 Intelligent Problem Solver

  • Automatically submits solutions from your problem database
  • Fisher-Yates shuffle for randomized problem order (looks more human 🕵️)
  • Multi-language support (Python, Java, C++, JavaScript, and more)
  • Smart language selection and editor detection

📊 Progress Tracking

  • Maintains a persistent record of solved problems
  • Skips already-completed problems to save time
  • In-memory caching for blazing-fast duplicate checks
  • JSON-based storage for easy inspection

🎨 Professional Terminal UI

  • Color-coded logging with Chalk
  • Clean, informative progress messages
  • Minimalist output (no spam, just essentials)
  • Real-time status updates

🧠 Smart Caching

  • Chrome profile persistence (no re-login needed)
  • Solved problems cache to avoid redundant submissions
  • Session data stored locally for reliability

🛡️ Error Handling

  • Graceful failure recovery
  • Detailed error messages for debugging
  • Automatic retry mechanisms
  • Safe cleanup on exit

🎯 Overview

What Does This Tool Do?

LeetCode Grinder automates the entire workflow of solving LeetCode problems:

  1. Launch Browser: Opens Chrome with your persistent profile
  2. Authenticate: Guides you through login (just once!)
  3. Load Solutions: Reads pre-written solutions from the Solutions/ directory
  4. Submit: For each problem:
    • Navigates to the problem page
    • Checks if already solved (skips if yes)
    • Selects the correct programming language
    • Pastes the solution code
    • Submits and waits for "Accepted" status
  5. Track Progress: Maintains a record in SolvedProblems.json

Workflow Diagram

graph TD
    A[Start Application] --> B[Launch Chrome Browser]
    B --> C[Navigate to LeetCode Login]
    C --> D{Already Logged In?}
    D -->|Yes| F[Load Problems from Solutions/]
    D -->|No| E[Display Login Instructions]
    E --> E1[User Logs In]
    E1 --> F
    F --> G[Shuffle Problems Randomly]
    G --> H{More Problems?}
    H -->|Yes| I[Navigate to Problem Page]
    I --> J{Already Solved?}
    J -->|Yes| H
    J -->|No| K[Select Language]
    K --> L[Paste Solution Code]
    L --> M[Click Submit]
    M --> N{Result?}
    N -->|Accepted| O[Save to Solved List]
    N -->|Error| P[Log Error]
    O --> H
    P --> H
    H -->|No| Q[Close Browser]
    Q --> R[Exit]
Loading

🏗️ Architecture

Clean Architecture Principles

This project follows professional software engineering practices:

LeetCode-Grinder/
├── src/                          # Source code
│   ├── config/                   # Configuration files
│   │   └── environment.js        # Environment variables & paths
│   ├── core/                     # Core business logic
│   │   ├── authenticator/
│   │   │   └── Authenticator.js  # LeetCode authentication
│   │   └── solver/
│   │       └── Solver.js         # Problem solving logic
│   ├── services/                 # External service integrations
│   │   └── browser/
│   │       └── BrowserService.js # Puppeteer browser management
│   ├── managers/                 # Resource managers
│   │   └── file/
│   │       └── FileManager.js    # File operations
│   ├── utils/                    # Utility functions
│   │   ├── logger.js             # Logging utility
│   │   └── helpers.js            # Helper functions
│   └── constants/                # Application constants
│       └── messages.js           # UI messages & ASCII art
├── data/                         # Data storage
│   └── user-data/                # User-specific data
│       └── {email}/
│           ├── ProfileData/      # Chrome profile
│           └── LeetCodeGrinderData/
│               ├── ScrapedSolutions/
│               └── SolvedProblems.json
├── Solutions/                    # Problem solutions (2500+)
│   ├── two-sum.json
│   ├── reverse-linked-list.json
│   └── ...
├── index.js                      # Application entry point
├── package.json                  # Dependencies
└── README.md                     # You are here! 📍

Technology Stack

Technology Purpose
Node.js (≥18) Runtime environment
Puppeteer Browser automation (headless Chrome)
Chalk Terminal styling and colors
Clipboardy Clipboard operations
dotenv Environment variable management

Component Responsibilities

graph LR
    A[index.js<br/>Entry Point] --> B[Authenticator<br/>Login Handler]
    A --> C[Solver<br/>Problem Submission]
    B --> D[BrowserService<br/>Puppeteer Control]
    C --> D
    C --> E[FileManager<br/>Data Persistence]
    D --> F[Chrome Browser]
    E --> G[Solutions/<br/>SolvedProblems.json]
Loading
  • Authenticator: Manages LeetCode login, displays beautiful in-browser instructions
  • Solver: Core problem-solving logic, handles submission workflow
  • BrowserService: Singleton for managing Puppeteer browser instance
  • FileManager: Handles all file I/O, caching, and data persistence
  • Logger: Provides color-coded, formatted console output
  • Helpers: Utility functions (sleep, element selection, keyboard shortcuts)

📋 Prerequisites

Before you begin, ensure you have the following installed:

Required

  • Node.js (version 18 or higher)

    • Download from nodejs.org
    • Verify installation: node --version
  • Google Chrome (latest version recommended)

    • Download from google.com/chrome
    • Important: Puppeteer requires Chrome to be installed

Optional

  • LeetCode Account
    You'll need to log in during first run (the tool will guide you)

  • Git (for cloning the repository)


📦 Installation

Step 1: Clone the Repository

git clone https://github.com/CPT-Dawn/LeetCode-Grinder.git
cd LeetCode-Grinder

Step 2: Install Dependencies

npm install

This will install:

  • puppeteer (downloads Chromium automatically)
  • chalk, clipboardy, dotenv

Step 3: (Optional) Configure Environment Variables

Create a .env file in the project root:

# Your email for session management
USER_EMAIL=your-email@example.com

# Chrome executable path (optional, auto-detected if not specified)
GOOGLE_CHROME_EXECUTABLE_PATH=C:/Program Files/Google/Chrome/Application/chrome.exe

Notes:

  • If USER_EMAIL is not set, defaults to temp@temp.com
  • If GOOGLE_CHROME_EXECUTABLE_PATH is not set, uses default Windows path
  • Chrome profile data will be stored in data/user-data/{USER_EMAIL}/

Common Installation Issues

Issue Solution
npm install fails Try npm install --legacy-peer-deps
Puppeteer download fails Check internet connection, try npm install puppeteer --force
Permission errors on Windows Run terminal as Administrator
Chrome not found Set GOOGLE_CHROME_EXECUTABLE_PATH in .env

🎮 Usage

Starting the Application

npm start

First-Time Setup

When you run the application for the first time:

  1. Chrome Opens Automatically
    A browser window will launch with a beautiful custom UI

  2. Login Instructions Appear
    You'll see a styled instruction panel overlay on the LeetCode login page

  3. Follow the 3-Step Process:

    Step 1: Enter your LeetCode credentials (email and password)

    Step 2: Click the Cloudflare "I'm not a robot" checkbox
    (Don't panic when it fails — this is expected behavior! 😄)

    Step 3: Click "Sign In"
    (Yes, even though Cloudflare "failed," the Sign In button works perfectly. Internet magic! ✨)

  4. Grab Coffee
    Once logged in, the bot takes over. You'll see progress in the terminal as problems are solved.

What You'll See

╔═══════════════════════════════════════════════════════════════╗
║     LeetCode Grinder - Automate your LeetCode grind fast      ║
╠═══════════════════════════════════════════════════════════════╣
║  Developer: CPT Dawn                                          ║
║  GitHub: https://github.com/CPT-Dawn/LeetCode-Grinder         ║
╚═══════════════════════════════════════════════════════════════╝

━━━ Authenticating ━━━

✓ Already logged in

━━━ Authentication Complete ━━━

━━━ Starting Problem Solver ━━━

Total Problems found 2517
→ 2517 problems queued (random order)

→ Solving: two-sum
✓ Accepted: two-sum
✓ Previously Solved: reverse-linked-list
→ Solving: valid-parentheses
✓ Accepted: valid-parentheses
...

Stopping the Process

  • Graceful Stop: Press Ctrl+C in the terminal
  • Force Quit: Close the terminal window (not recommended)
  • The application will save progress before exiting

Subsequent Runs

On future runs:

  • ✅ You won't need to log in again (session persists via Chrome profile)
  • ✅ Previously solved problems are automatically skipped
  • ✅ The application picks up where you left off

⚙️ Configuration

Environment Variables

Variable Default Description
USER_EMAIL temp@temp.com Email for session management (used in folder naming)
GOOGLE_CHROME_EXECUTABLE_PATH C:/Program Files/Google/Chrome/Application/chrome.exe Path to Chrome executable

Data Storage Locations

All user data is stored in the data/user-data/{USER_EMAIL}/ directory:

data/user-data/your-email@example.com/
├── ProfileData/              # Chrome profile data
│   ├── Default/
│   └── ...
└── LeetCodeGrinderData/      # Application data
    ├── ScrapedSolutions/     # (Reserved for future use)
    └── SolvedProblems.json   # List of completed problems

Solutions Database

Place your problem solutions in the Solutions/ directory as JSON files:

Format:

{
  "problemName": "two-sum",
  "language": "python3",
  "code": "class Solution:\n    def twoSum(self, nums: List[int], target: int) -> List[int]:\n        seen = {}\n        for i, num in enumerate(nums):\n            complement = target - num\n            if complement in seen:\n                return [seen[complement], i]\n            seen[num] = i"
}

Supported Languages:

  • python, python3, java, cpp, c, csharp, javascript, typescript, go, rust, php, swift, kotlin, ruby, scala, and more!

Customization Options

Want to solve problems in a specific order?
Modify Solver.js line 345:

// Current: Random order
const randomizedProblems = this.#shuffleArray(allProblemsName);

// Change to: Sequential order
const randomizedProblems = allProblemsName;

Want to limit the number of problems?
Modify Solver.js line 346:

const limitedProblems = randomizedProblems.slice(0, 100); // Solve only 100
await this.#solveProblems(limitedProblems);

🔧 Troubleshooting

Common Issues and Solutions

❌ "Chrome executable not found"

Problem: Puppeteer can't locate Google Chrome

Solutions:

  1. Install Google Chrome from google.com/chrome
  2. Set the path in .env:
    GOOGLE_CHROME_EXECUTABLE_PATH=C:/Program Files/Google/Chrome/Application/chrome.exe
  3. On macOS: /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
  4. On Linux: /usr/bin/google-chrome

❌ "Login timeout" or "Unable to authenticate"

Problem: The 100-minute login timer expired

Solutions:

  1. Restart the application: npm start
  2. Log in within the time limit (100 minutes is generous!)
  3. Check your internet connection
  4. Try clearing the Chrome profile:
    # Windows
    rmdir /s /q data\user-data
    
    # Mac/Linux
    rm -rf data/user-data

❌ "Submit button not found" or "Solution failed"

Problem: LeetCode's UI changed or network issues

Solutions:

  1. Check your internet connection
  2. Verify the problem exists on LeetCode
  3. Check if LeetCode is down: status.leetcode.com (if it exists)
  4. Try re-running the specific problem manually
  5. Report the issue on GitHub Issues

❌ "Wrong Answer" or "Runtime Error" for a problem

Problem: The solution code in Solutions/ is incorrect

Solutions:

  1. Verify the solution code in the JSON file
  2. Test the solution manually on LeetCode
  3. Check that the language field matches the code
  4. Ensure code formatting is correct (escape special characters in JSON)

❌ Browser crashes or freezes

Problem: Chrome ran out of memory or encountered a bug

Solutions:

  1. Close other Chrome instances
  2. Restart the application
  3. Check available system memory
  4. Update Chrome to the latest version

❌ "Network error" or "Timeout"

Problem: Slow internet or LeetCode server issues

Solutions:

  1. Check your internet connection speed
  2. Try again in a few minutes
  3. Increase timeouts in Solver.js (line 47, 269):
    timeout: 120000, // Increase from 60000 to 120000 (2 minutes)

Data Corruption Recovery

If SolvedProblems.json becomes corrupted:

  1. Backup (if possible):

    copy data\user-data\{email}\LeetCodeGrinderData\SolvedProblems.json SolvedProblems.backup.json
  2. Reset:

    echo [] > data\user-data\{email}\LeetCodeGrinderData\SolvedProblems.json
  3. Restart the application (it will rebuild the list)


Debug Mode

To see more detailed logs, modify src/utils/logger.js to add timestamps:

console.log(`[${new Date().toISOString()}] ${log}`);

🐛 Error Reporting

Found a bug? We'd love to hear about it! Here's how to report issues effectively:

Before Reporting

  1. Check existing issues: GitHub Issues
  2. Try troubleshooting steps above
  3. Reproduce the issue (can you make it happen again?)

What to Include

Create a new issue on GitHub with:

  1. Clear Title
    ✅ Good: "Submit button not found on problem X"
    ❌ Bad: "Not working"

  2. Environment Details

    • Operating System (Windows 11, macOS 14, Ubuntu 22.04, etc.)
    • Node.js version (node --version)
    • Chrome version (chrome://version/)
    • LeetCode Grinder version (1.0.1)
  3. Steps to Reproduce

    1. Run `npm start`
    2. Log in to LeetCode
    3. Wait for problem 'two-sum' to load
    4. Error occurs: "Submit button not found"
    
  4. Expected vs Actual Behavior

    • Expected: Solution should be submitted successfully
    • Actual: Error message appears: "Submit button not found"
  5. Error Messages
    Copy the full error output from the terminal

  6. Screenshots (if relevant)
    Especially helpful for UI-related issues

Example Good Bug Report

**Title**: Timeout error when solving "longest-palindromic-substring"

**Environment**:
- OS: Windows 11
- Node.js: v20.10.0
- Chrome: 120.0.6099.109
- LeetCode Grinder: v1.0.1

**Steps to Reproduce**:
1. Start application with `npm start`
2. Application navigates to "longest-palindromic-substring"
3. After 30 seconds, timeout error occurs

**Expected**: Solution should be submitted
**Actual**: Error: "Timeout waiting for result"

**Error Log**:

✗ Failed: longest-palindromic-substring - Timeout waiting for result


**Additional Context**:
This happens consistently with this specific problem, but other problems work fine.

Community Support

  • GitHub Discussions: Ask questions, share tips
  • Issues: Report bugs, request features
  • Pull Requests: Contribute fixes and improvements!

🤝 Contributing

Contributions are welcome! Here's how you can help make LeetCode Grinder even better:

Ways to Contribute

  • 🐛 Report Bugs: See Error Reporting
  • 💡 Suggest Features: Open a GitHub issue with the enhancement label
  • 📝 Improve Documentation: Fix typos, add examples, clarify instructions
  • 🔧 Submit Code: Fix bugs, add features, improve performance

Development Setup

  1. Fork the repository on GitHub

  2. Clone your fork:

    git clone https://github.com/YOUR_USERNAME/LeetCode-Grinder.git
    cd LeetCode-Grinder
  3. Create a branch:

    git checkout -b feature/your-feature-name
  4. Install dependencies:

    npm install
  5. Make your changes
    Follow the existing code style and architecture

  6. Test your changes:

    npm start
  7. Commit your changes:

    git add .
    git commit -m "Add: your feature description"
  8. Push to GitHub:

    git push origin feature/your-feature-name
  9. Create a Pull Request on GitHub

Code Style Guidelines

  • ES6+ syntax: Use modern JavaScript features
  • Async/await: Prefer async/await over promises
  • Comments: Document complex logic
  • Modularity: Keep functions small and focused
  • Error handling: Always use try-catch for async operations

Pull Request Guidelines

  • One feature per PR: Keep changes focused
  • Descriptive title: Explain what the PR does
  • Documentation: Update README if needed
  • Testing: Verify your changes work as expected

❓ FAQ

General Questions

Q: Is this legal?
A: This tool is for educational purposes only. Using automation on LeetCode may violate their Terms of Service. Use at your own risk. See our Legal Disclaimer.

Q: Will I get banned from LeetCode?
A: Potentially, yes. LeetCode may detect and ban accounts using automation. We recommend using this tool only for educational purposes or in situations where you have no other choice.

Q: Can I use this to cheat on interviews?
A: Absolutely not. This tool should never be used for dishonest purposes. It's designed to highlight unreasonable academic requirements, not to facilitate cheating.

Technical Questions

Q: Why does Cloudflare verification "fail" but login still works?
A: Cloudflare's verification interacts oddly with automated browsers. The checkbox fails, but the Sign In button still functions. It's quirky, but it works! 🤷

Q: How many problems can this solve?
A: Currently ships with 2500+ problems in the Solutions/ directory. You can add more by creating JSON files in the same format.

Q: Does this work on macOS/Linux?
A: Yes! The code is cross-platform. Just make sure to:

  • Install Node.js (≥18)
  • Install Google Chrome
  • Update GOOGLE_CHROME_EXECUTABLE_PATH in .env if needed

Q: Can I use this with other coding platforms?
A: The code is specifically designed for LeetCode. Adapting it for other platforms (HackerRank, CodeForces, etc.) would require significant modifications.

Q: How fast does it solve problems?
A: Approximately 10-15 seconds per problem (navigation + submission + validation). So 300 problems would take about 45-75 minutes.

Q: Why is the problem order randomized?
A: To appear more human-like. Solving problems in perfect sequential order looks suspicious. The Fisher-Yates shuffle adds randomness.

Usage Questions

Q: Can I pause and resume?
A: Yes! Solved problems are saved to SolvedProblems.json. If you stop and restart, already-solved problems are skipped automatically.

Q: Can I solve only specific problems?
A: Yes! Modify the Solutions/ directory to include only the problems you want, or edit Solver.js to filter by name.

Q: What if a solution is wrong?
A: The tool will log the error (e.g., "Wrong Answer") and move to the next problem. You'll need to manually fix incorrect solutions in the Solutions/ directory.


📄 License

This project is licensed under the MIT License.

MIT License

Copyright (c) 2026 CPT Dawn

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.

See the full license in the LICENSE file.


🙏 Acknowledgments

Technologies

  • Node.js: JavaScript runtime that makes this possible
  • Puppeteer: The amazing headless Chrome automation library
  • Chalk: Making terminal output beautiful since forever
  • Clipboardy: Cross-platform clipboard access
  • dotenv: Environment variable management made easy

Inspiration

  • Every CS student who's ever received an unreasonable assignment deadline
  • The countless hours spent grinding LeetCode (we feel your pain 😢)
  • The desire to showcase clean software architecture and automation techniques

Special Thanks

  • ChatGPT & AI Communities: For assistance in brainstorming and refining ideas
  • Open Source Community: For building the amazing tools this project relies on
  • YOU: For reading this README to the end! You're awesome! 🌟

🎯 Final Reminders

Warning

Use Responsibly

This tool is a protest against unreasonable academic requirements, not a license to cheat. Use it wisely, use it ethically, and most importantly — actually learn to code.

LeetCode is a valuable learning resource when used properly. Don't let automation rob you of the opportunity to become a better programmer.

When You Should Actually Use This Tool:

✅ Demonstrating browser automation techniques
✅ Testing your problem solution database
Extreme emergency (300 problems due tomorrow at 9 AM)
✅ Highlighting flaws in educational systems

When You Should NOT Use This Tool:

❌ Job interviews
❌ Coding assessments
❌ Competitive programming contests
❌ As a substitute for learning


Made with 💻 and ☕ by CPT Dawn

GitHub Project

"May your code compile on the first try and your tests pass without debugging."
— Ancient Developer Proverb


Disclaimer (Again, Because It's Important): This software is provided for educational purposes only. The authors are not responsible for any misuse or consequences resulting from the use of this tool. Always respect platform terms of service and academic integrity policies.

Releases

No releases published

Packages

No packages published