A full-featured Leetcode API on Rust language

Overview

LeetCode API Rust Library

This Rust library provides a convenient way to interact with the LeetCode API, allowing you to programmatically access LeetCode problems, submit solutions, and retrieve submission results.

Features

  • Retrieve a list of LeetCode problems.
  • Fetch problem details, including the problem description, constraints, and examples.
  • Submit solutions to LeetCode problems.
  • Check submission results, including status, runtime, and memory usage.

Installation

Add the following line to your Cargo.toml file:

[dependencies]
leetcoderustapi = "1.0.4"

Usage

Authentication

To use the LeetCode API, you need to obtain an authentication token. Follow the instructions provided by LeetCode to obtain your token.

Example: Action with problems

use leetcoderustapi::{problem_build::{Tags, Category, Difficulty, Status}, UserApi, ProgrammingLanguage,};

#[tokio::main]
async fn main() {
    // Set cookie from leetcode
    let token = std::env::var("COOKIE").expect("cookie doesn't set");

    // Create a new LeetCode client
    let api = UserApi::new(&token).await.unwrap();

    // Show found problems by keyword and show 5 notes
    let show_problems = api.show_problm_list("sum", 5).await.unwrap();

    // Find problems by properties with creating problem builder
    let problems_builder = api
        .problem_builder()
        .set_category(Category::Algorithms)
        .set_difficulty(Difficulty::Easy)
        .set_keyword("sum")
        //max show notes limit is 2763; default is 5
        .set_note_limit(3)
        .set_status(Status::Solved)
        //max tags over 50+
        .set_tags(vec![
            Tags::Array,
            Tags::BinarySearch,
        ])
        .build()
        .await
        .unwrap();

    // Fetch the full data for a specific problem
    let problem_info = api.set_problem("two sum").await.unwrap();

    // Retrieve previous submissions to this problem
    let my_submissions = problem_info.my_submissions().await.unwrap();

    // Retrieve code snippets
    let code_snippets = problem_info.code_snippets().unwrap();

    // Retrieve solution info
    let solution_info = problem_info.solution_info().unwrap();

    // Retrieve related topics
    let related_topics = problem_info.related_topics();

    // Retrieve similar questions
    let similar_questions = problem_info.similar_questions().unwrap();

    // Retrieve stats
    let stats = problem_info.stats().unwrap();

    // Retrieve hints
    let hints = problem_info.hints();

    // Retrieve description
    let description = problem_info.description().unwrap();

    // Retrieve difficulty
    let difficulty = problem_info.difficulty();

    // Retrieve likes and dislikes
    let likes = problem_info.rating().unwrap();

    // Retrieve category
    let category = problem_info.category();

    // We also can send submissions and tests
    // Need to specify a lang and provided code
    let subm_response = problem_info
        .send_subm(ProgrammingLanguage::Rust, "impl Solution { fn two_sum() {}}")
        .await
        .unwrap();
    let test_response = problem_info
        .send_test(ProgrammingLanguage::Rust, "impl Solution { fn two_sum() {}}")
        .await
        .unwrap();
}

Example: Actions with Self profile

#[tokio::main]
async fn main() {
    // Set cookie from leetcode
    let token = std::env::var("COOKIE").expect("cookie doesn't set");

    // Create a new LeetCode client
    let api = UserApi::new(&token).await.unwrap();

    // Create interaction with profile
    let user_profile = api.my_profile().await.unwrap();

    // Create empty list of the problems with provided name
    user_profile
        .create_fav_list("my_new_favorite_list")
        .await
        .unwrap();

    // Rename list
    user_profile
        .rename_fav_list("my_new_favorite_list", "hard_problems")
        .await
        .unwrap();

    // Set list puplic
    user_profile.set_public("hard_problems").await.unwrap();

    // Set list private
    user_profile.set_private("hard_problems").await.unwrap();

    // Get link to the list if it is a public
    let share_list_url = user_profile.get_share_url("hard_problems").await.unwrap();

    // Show existing lists
    let lists = user_profile.show_lists();

    // Delete list with provided name
    user_profile
        .delete_list("hard_problems")
        .await
        .unwrap();

    // Show users last 10 notification
    let notifications = user_profile.get_notifications().await.unwrap();
}

Example: Actions with Public user profile

#[tokio::main]
async fn main() {
    // Set cookie from leetcode
    let token = std::env::var("COOKIE").expect("cookie doesn't set");

    // Create a new LeetCode client
    let api = UserApi::new(&token).await.unwrap();

    // Find public user
    let user = api
        .find_profile("1101-1")
        .await;

    // Check public user common stats
    let user_stats = user.
        user_stats()
        .await
        .unwrap();

    // Check what langs used user
    let lang_stats = user
        .language_stats()
        .await
        .unwrap();
    
    // Check what problems (by tags) solve user
    let skill_stats = user
        .skill_stats()
        .await
        .unwrap();

    // Show rating by beating problems
    let beat_stats = ser
        .problem_beat_stats()
        .await
        .unwrap();

     // Show recent submissons of user
    let beat_stats = ser
        .recent_subm_list()
        .await
        .unwrap();
}

Important

Replace "COOKIE" with your actual LeetCode authentication cookie.

For example format in .env file:

COOKIE="csrftoken=gN3mmFEKoBFHLZuiHEvZYupqirq7brDmi845GhUK8xBa9u3SUVkgTPFTPsLFuAzR; _ga_CDRWKZTDEX=GS1.1.1688568040.1.1.1688568081.19.0.0; _ga=GA1.1.2048740381.1688568040; _dd_s=rum=0&expire=1688568980299; NEW_PROBLEMLIST_PAGE=1"

License

This library is licensed under the MIT License.

You might also like...
K-dimensional tree in Rust for fast geospatial indexing and lookup

kdtree K-dimensional tree in Rust for fast geospatial indexing and nearest neighbors lookup Crate Documentation Usage Benchmark License Usage Add kdtr

Roaring bitmap implementation for Rust

RoaringBitmap This is not yet production ready. The API should be mostly complete now. This is a Rust port of the Roaring bitmap data structure, initi

Rust Persistent Data Structures

Rust Persistent Data Structures Rust Persistent Data Structures provides fully persistent data structures with structural sharing. Setup To use rpds a

Rust crate to extend io::Read & io::Write types with progress callbacks

progress-streams Rust crate to provide progress callbacks for types which implement io::Read or io::Write. Examples Reader extern crate progress_strea

Parameterized routing for generic resources in Rust

Usher Usher provides an easy way to construct parameterized routing trees in Rust. The nodes of these trees is naturally generic, allowing Usher to le

RiteLinked - LinkedHashMap & LinkedHashSet in Rust

RiteLinked -- HashMap-like containers that hold their key-value pairs in a user controllable order RiteLinked provides more up to date versions of Lin

A proof of concept implementation of cyclic data structures in stable, safe, Rust.

A proof of concept implementation of cyclic data structures in stable, safe, Rust. This demonstrates the combined power of the static-rc crate and the

Doubly-Linked List Implementation in Rust

Doubly-Linked List Implementation in Rust Purely for educational and recreational purposes. For real world production please use std::collections::Lin

Rust library for string parsing of basic data structures.

afmt Simple rust library for parsing basic data structures from strings. Usage You can specify string formats to any strucute, via the use of the fmt

Use Rust to solve questions on Leetcode.

Rust for Leetcode 本仓库用于记录我使用Rust刷Leetcode的代码,尽量做到日更。 题目列表 编号 名称 题目类型 题解 678 有效的括号字符串 栈 valid-parenthesis-string.rs 461 汉明距离 位运算 hamming-distance.rs 62

Rui Li 1 Mar 3, 2022
my leetcode solutions in rust

My Leetcode Solution in Rust Run cargo run {id} to initialize the template submission file of "question #id". Run cargo test test_{id} to test the sol

Aylei 598 Jan 1, 2023
The solutions for Leetcode's problem

Leetcode The solutions for Leetcode's problem # Ttitle Solution Diffculty 1 Two Sum Rust, TypeScript Easy 5 Longest Palindromic Substring Rust, TypeSc

Eleven 2 Jul 21, 2022
Rust data structures and client for the PubChem REST API

pubchem.rs Rust data structures and client for the PubChem REST API. ?? Usage ?? Compound Create a Compound to query the PubChem API for a single comp

Martin Larralde 2 Jan 18, 2022
Coding-challenge - Algorithms and Data-structures, problems and solutions in Rust language using cargo-workspaces

Coding Challenge LeetCode/Hackerrank e.t.c Using this as an opportunity to improve my knowledge of rust lang If you found this repo useful to you, add

Tolumide Shopein 17 Apr 24, 2022
Rust-algorithm-club - Learn algorithms and data structures with Rust

Rust Algorithm Club ?? ?? This repo is under construction. Most materials are written in Chinese. Check it out here if you are able to read Chinese. W

Weihang Lo 360 Dec 28, 2022
Ternary search tree collection in rust

tst Ternary search tree collection in rust with similar API to std::collections as it possible. Ternary search tree is a type of trie (sometimes calle

Alexey Pervushin 20 Dec 7, 2022
Array helpers for Rust's Vector and String types

array_tool Array helpers for Rust. Some of the most common methods you would use on Arrays made available on Vectors. Polymorphic implementations for

Daniel P. Clark 69 Dec 9, 2022
Generic array types in Rust

generic-array This crate implements generic array types for Rust. Requires minumum Rust version of 1.36.0, or 1.41.0 for From<[T; N]> implementations

Bartłomiej Kamiński 325 Dec 25, 2022
A priority queue for Rust with efficient change function.

PriorityQueue This crate implements a Priority Queue with a function to change the priority of an object. Priority and items are stored in an IndexMap

null 139 Dec 30, 2022