leetgo

leetgo

命令行 LeetCode 刷题助手

leetgo 是一个命令行 LeetCode 工具,能自动生成代码框架和测试用例,支持本地测试和调试。它可实时生成竞赛题目,兼容多种编程语言,让用户无需离开终端即可完成 LeetCode 练习。该工具还提供自定义模板和编辑器集成功能,提升刷题效率。

Leetgo命令行工具LeetCode代码生成本地测试Github开源项目

简体中文 | English

Leetgo

Go Report Card CI GitHub downloads PRs Welcome Twitter Follow <img align="right" height=150 src="https://github.com/j178/leetgo/assets/10510431/4dbe3a58-6c64-4b54-a695-78c7d8c8de39" />

leetgo is a command-line tool for LeetCode that provides almost all the functionality of LeetCode, allowing you to do all of your LeetCode exercises without leaving the terminal. It can automatically generate skeleton code and test cases, support local testing and debugging, and you can use any IDE you like to solve problems.

And leetgo also supports real-time generation of contest questions, submitting all questions at once, so your submissions are always one step ahead!

Quick Start

  1. Install leetgo
  2. Initialize leetgo: leetgo init -t <us or cn> -l <lang>
  3. Edit leetgo config file: leetgo.yaml
  4. Pick a question: leetgo pick <id or name or today>
  5. Test your code: leetgo test last -L
  6. Submit your code: leetgo submit last

You can test and submit in one command: leetgo test last -L -s

You can edit the question file in your favorite editor: leetgo edit last

Demo

demo

Features

  • Generate description, skeleton code and testing code for a question
  • Customize the code template for generated code, use modifiers to pre-process code
  • Execute test cases on your local machine
  • Wait and generate contest questions just in time, test and submit all at once
  • Support for both leetcode.com and leetcode.cn
  • Automatically read cookies from browser, no need to enter password
  • Automatically open question files in your favourite editor
  • Use OpenAI to automatically discover and fix issues in the code (Experimental)

Language support

leetgo supports code generation for most languages, and local testing for some languages.

In the Go language, running leetgo pick 257 will generate the following code:

// Omitted some code... // @lc code=begin func binaryTreePaths(root *TreeNode) (ans []string) { return } // @lc code=end func main() { stdin := bufio.NewReader(os.Stdin) root := Deserialize[*TreeNode](ReadLine(stdin)) ans := binaryTreePaths(root) fmt.Println("output: " + Serialize(ans)) }

This is a complete and runnable program. You can run it directly, input the test cases, and compare the results. leetgo test -L will automatically run this program with the test cases in testcases.txt and compare the results.

Local testing means that you can run the test cases on your local machine, so you can use a debugger to debug your code.

Local testing requires more work to implement for each language, so not all languages are supported. Below is the current support matrix:

<!-- BEGIN MATRIX -->
GenerationLocal testing
Go:white_check_mark::white_check_mark:
Python:white_check_mark::white_check_mark:
C++:white_check_mark::white_check_mark:
Rust:white_check_mark::white_check_mark:
Java:white_check_mark:Not yet
JavaScript:white_check_mark:Not yet
TypeScript:white_check_mark:Not yet
PHP:white_check_mark:Not yet
C:white_check_mark:Not yet
C#:white_check_mark:Not yet
Ruby:white_check_mark:Not yet
Swift:white_check_mark:Not yet
Kotlin:white_check_mark:Not yet
Bash:white_check_mark:Not yet
MySQL:white_check_mark:Not yet
MSSQL:white_check_mark:Not yet
Oracle:white_check_mark:Not yet
Erlang:white_check_mark:Not yet
Racket:white_check_mark:Not yet
Scala:white_check_mark:Not yet
Elixir:white_check_mark:Not yet
Dart:white_check_mark:Not yet
<!-- END MATRIX -->

Welcome to help us implement local testing for more languages!

Installation

You can download the latest binary from the release page.

Install via HomeBrew on macOS/Linux

brew install j178/tap/leetgo

Install via Scoop on Windows

scoop bucket add j178 https://github.com/j178/scoop-bucket.git scoop install j178/leetgo

Install on ArchLinux

yay -S leetgo-bin

Install via installer script on macOS/Linux

curl -fsSL https://raw.githubusercontent.com/j178/leetgo/master/scripts/install.sh | bash

Install from source via go install

go install github.com/j178/leetgo@latest

Usage

<!-- BEGIN USAGE -->
Usage:
  leetgo [command]

Available Commands:
  init                    Init a leetcode workspace
  pick                    Generate a new question
  info                    Show question info
  test                    Run question test cases
  submit                  Submit solution
  fix                     Use ChatGPT API to fix your solution code (just for fun)
  edit                    Open solution in editor
  contest                 Generate contest questions
  cache                   Manage local questions cache
  debug                   Show debug info
  open                    Open one or multiple question pages in a browser
  help                    Help about any command

Flags:
  -v, --version       version for leetgo
  -l, --lang string   language of code to generate: cpp, go, python ...
      --site string   leetcode site: cn, us
  -y, --yes           answer yes to all prompts
  -h, --help          help for leetgo

Use "leetgo [command] --help" for more information about a command.
<!-- END USAGE -->

Question Identifier

Many leetgo commands rely on qid to find the leetcode question. qid is a simplified question identifier defined by leetgo, which includes the following forms (using the two-sum problem as an example):

leetgo pick two-sum # `two-sum` is the question slug leetgo pick 1 # `1` is the question id leetgo pick today # `today` means daily question leetgo pick yesterday # `yesterday` means the question of yesterday leetgo pick today-1 # `today-1` means the question of yesterday, same as `yesterday`. `today-2`, `today-3` etc are also supported. leetgo contest weekly100 # `weekly100` means the 100th weekly contest leetgo test last # `last` means the last generated question leetgo test weekly100/1 # `weekly100/1` means the first question of the 100th weekly contest leetgo submit b100/2 # `b100/2` means the second question of the 100th biweekly contest leetgo submit w99/ # `w99/` means all questions of the 99th biweekly contest (must keep the trailing slash) leetgo test last/1 # `last/1` means the first question of the last generated contest leetgo test last/ # `last/` means all questions of the last generated contest (must keep the trailing slash)

Configuration

[!WARNING] Since v1.4, leetgo no longer reads the global ~/.config/leetgo/config.yaml file, please put all configurations in the project's leetgo.yaml file.

leetgo init generates a leetgo.yaml file in the current directory, which contains all the configurations of leetgo. You can modify this file according to your needs.

The directory where leetgo.yaml is located is considered as the root directory of a leetgo project, and leetgo will generate all code files undeer this directory. leetgo will look for the leetgo.yaml file in the current directory. If it is not found, it will recursively search upwards until a leetgo.yaml file is found or the root directory of the file system is reached.

Below is the demonstration of a complete configuration:

<details> <summary>Click to expand</summary> <!-- BEGIN CONFIG -->
# Your name author: Bob # Language of the question description: 'zh' (Simplified Chinese) or 'en' (English). language: zh code: # Language of code generated for questions: go, cpp, python, java... # (will be overridden by command line flag -l/--lang). lang: go # The default template to generate filename (without extension), e.g. {{.Id}}.{{.Slug}} # Available attributes: Id, Slug, Title, Difficulty, Lang, SlugIsMeaningful # (Most questions have descriptive slugs, but some consist of random characters. The SlugIsMeaningful boolean indicates whether a slug is meaningful.) # Available functions: lower, upper, trim, padWithZero, toUnderscore, group. filename_template: '{{ .Id | padWithZero 4 }}{{ if .SlugIsMeaningful }}.{{ .Slug }}{{ end }}' # Generate question description into a separate question.md file, otherwise it will be embed in the code file. separate_description_file: true # Default modifiers for all languages. modifiers: - name: removeUselessComments go: # Base directory to put generated questions, defaults to the language slug, e.g. go, python, cpp. out_dir: go # Functions that modify the generated code. modifiers: - name: removeUselessComments - name: changeReceiverName - name: addNamedReturn - name: addMod python3: # Base directory to put generated questions, defaults to the language slug, e.g. go, python, cpp. out_dir: python # Path to the python executable that creates the venv. executable: python3 cpp: # Base directory to put generated questions, defaults to the language slug, e.g. go, python, cpp. out_dir: cpp # C++ compiler cxx: g++ # C++ compiler flags (our Leetcode I/O library implementation requires C++17). cxxflags: -O2 -std=c++17 rust: # Base directory to put generated questions, defaults to the language slug, e.g. go, python, cpp. out_dir: rust java: # Base directory to put generated questions, defaults to the language slug, e.g. go, python, cpp. out_dir: java leetcode: # LeetCode site, https://leetcode.com or https://leetcode.cn site: https://leetcode.cn # Credentials to access LeetCode. credentials: # How to provide credentials: browser, cookies, password or none. from: browser # Browsers to get cookies from: chrome, safari, edge or firefox. If empty, all browsers will be tried. Only used when 'from' is 'browser'. browsers: [] contest: # Base directory to put generated contest questions. out_dir: contest # Template to generate filename of the question. filename_template: '{{ .ContestShortSlug }}/{{ .Id }}{{ if .SlugIsMeaningful }}.{{ .Slug }}{{ end }}' # Open the contest page in browser after generating. open_in_browser: true # Editor settings to open generated files. editor: # Use a predefined editor: vim, vscode, goland # Set to 'none' to disable, set to 'custom' to provide your own command and args. use: none # Custom command to open files. command: "" # Arguments to your custom command. # String contains {{.CodeFile}}, {{.TestFile}}, {{.DescriptionFile}}, {{.TestCasesFile}} will be replaced with corresponding file path. # {{.Folder}} will be substituted with the output directory. # {{.Files}} will be substituted with the list of all file paths. args: ""
<!-- END CONFIG --> </details>

LeetCode Credentials

leetgo uses LeetCode's GraphQL API to retrieve questions and submit solutions. leetgo needs your LeetCode cookies to access the authenticated API.

There are three ways to make cookies available to leetgo:

  • Read cookies from browser automatically.

    Currently, leetgo supports Chrome, FireFox, Safari1, Edge.

    leetcode: credentials: from: browser
  • Provide cookies.

    You can get your cookies named LEETCODE_SESSION and csrftoken from browser's developer tools, and set the LEETCODE_SESSION and LEETCODE_CSRFTOKEN environment variables. If you are using leetcode.com, LEETCODE_CFCLEARANCE should also be set to the value of the cf_clearance cookie.

    leetcode: credentials: from: cookies
  • Provide username and password through LEETCODE_USERNAME and LEETCODE_PASSWORD environment variables.

    leetcode: credentials: from: password

[!NOTE] Password authentication is not recommended, and it is not supported by leetcode.com.

You can put environment variables in a .env file in the project's root directory, and leetgo will automatically read them.

Advanced Usage

testcases.txt

testcasts.txt is generated by leetgo and contains all the test cases of the question.

You can add a new test case by specifying only the input and leaving the output blank. When you run leetgo test (without -L), the expected output will be retrieved from the remote server. For example:

input:
[3,3]
6
output:

input:
[1,2,3,4]
7
output:

Templates

Several fields in leetgo's config file support templating. These fields are often suffixed with _template. You can use custom template to generate your own filename, code, etc.

Blocks

A code file is composed of different blocks, you can overwrite some of them to provide your own snippets.

Available blocks
header
description
title
beforeMarker
beforeCode
code
afterCode
afterMarker

For example:

code: lang: cpp cpp: blocks: - name: beforeCode template: | #include <iostream> using namespace std; - name: afterMarker template: | int main() {}

Scripting

leetgo supports providing a JavaScript function to handle the code before generation, for example:

code: lang: cpp cpp: modifiers: - name: removeUselessComments - script: | function modify(code) { return "// hello world\n" + code; }

FAQ

If you encounter any problems, please run your command with the DEBUG environment variable set to 1, copy the command output, and open an issue.

Some common problems can be found in the Q&A page.

Contributions welcome!

Good First Issues are a good place to start, and you can also check out some Help Wanted issues.

If you want to add local testing support for a new language, please refer to #112.

Before submitting a PR, please run golangci-lint run --fix to fix lint errors.

Credits

Here are some awesome projects that inspired me to create this project:

Also thanks to JetBrains for providing free licenses to support this project.

JetBrains Logo

Footnotes

  1. For Safari on macOS, you may need to grant Full Disk Access privilege to your terminal app which you would like to run

编辑推荐精选

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

openai-agents-python

openai-agents-python

OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。

openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。

Hunyuan3D-2

Hunyuan3D-2

高分辨率纹理 3D 资产生成

Hunyuan3D-2 是腾讯开发的用于 3D 资产生成的强大工具,支持从文本描述、单张图片或多视角图片生成 3D 模型,具备快速形状生成能力,可生成带纹理的高质量 3D 模型,适用于多个领域,为 3D 创作提供了高效解决方案。

3FS

3FS

一个具备存储、管理和客户端操作等多种功能的分布式文件系统相关项目。

3FS 是一个功能强大的分布式文件系统项目,涵盖了存储引擎、元数据管理、客户端工具等多个模块。它支持多种文件操作,如创建文件和目录、设置布局等,同时具备高效的事件循环、节点选择和协程池管理等特性。适用于需要大规模数据存储和管理的场景,能够提高系统的性能和可靠性,是分布式存储领域的优质解决方案。

下拉加载更多