Algorithms in LeetCode by Benhao
After clone this repo, add a .env file to tell where to locate your problems and solutions (locally).
For remote GitHub Action, add COOKIE
(LeetCode cookie), PUSH_KEY
(PushDeer notification), PROBLEM_FOLDER
(where to
add problems), USER
(LeetCode personal page uri).
Notice: If you want more than just python3, add LANGUAGES="python3,golang"
(and so on in .env)
Example .env file:
PROBLEM_FOLDER="problems"
PUSH_KEY="***[key from PushDeer]"
COOKIE="***[cookie from LeetCode graphql]"
LANGUAGES="python3,golang,java,cpp,typescript"
USER="himymben"
install python3.12 requirements:
pip install -r python/requirements.txt
To directly submit Solution to LeetCode, try any language below:
python python/scripts/submit.py -h
# usage: submit.py [-h] [-id ID] {go,py,ts,js,c++,java,golang,python3,typescript,javascript,cpp}
python python/scripts/submit.py python3 -id=1
python python/scripts/submit.py -id=2 py
python python/scripts/submit.py py
python python/scripts/submit.py golang -id=2
python python/scripts/submit.py cpp -id=1
python python/scripts/submit.py java -id=2
python python/scripts/submit.py typescript -id=1
To get any problem you want, try:
python python/scripts/get_problem.py -h
# usage: get_problem.py [-h] [-id PROBLEM_ID] [-slug PROBLEM_SLUG] [-cate PROBLEM_CATEGORY] [-f] [-all] [-pm] [-debug DEBUG_FILE] [-change] [-sl]
python python/scripts/get_problem.py -id=1
To generate daily problems, try:
python python/scripts/daily_auto.py
To fetch daily submits from LeetCode (requires .env
COOKIE or USER to be ready), try:
python python/scripts/daily_submission.py
Check Python3 README
Check Golang README
Check Java README
Check Cpp README
Check TypeScript README
Clone your own forked repo
Notice: create your own branch and set it as repo default, and keep master!
Open the code project and installed languages environments as needed.
Test your environment by running languages test, for instance: if you are facing errors here, contact the author.
Find a cookie from LeetCode (monthly update)
Create your own .env file (Notice: better to use a problem folder other than exists as the author is using them, there will be a lot of conflicts):
PROBLEM_FOLDER=demo
COOKIE="***[cookie from LeetCode graphql]"
LANGUAGES="golang,java"
Create the folder 'demo' based on your own .env
Run scripts to fetch problems, run tests and submit your solution.
If you get problem like this, it will add the problem and change the tests of your languages as below:
In VsCode,
add launch.json under .vscode
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Typescript Test",
"type": "node",
"request": "launch",
"preLaunchTask": "typescript-test",
},
{
"name": "Typescript Tests",
"type": "node",
"request": "launch",
"preLaunchTask": "typescript-tests",
},
{
"name": "Python Test",
"type": "node",
"request": "launch",
"preLaunchTask": "python-test",
},
{
"name": "Python Tests",
"type": "node",
"request": "launch",
"preLaunchTask": "python-tests",
},
{
"name": "Golang Test",
"type": "node",
"request": "launch",
"preLaunchTask": "golang-test",
},
{
"name": "Golang Tests",
"type": "node",
"request": "launch",
"preLaunchTask": "golang-tests",
},
{
"name": "C++ Test",
"type": "node",
"request": "launch",
"preLaunchTask": "cpp-test",
},
{
"name": "C++ Tests",
"type": "node",
"request": "launch",
"preLaunchTask": "cpp-tests",
},
{
"name": "Java Test",
"type": "node",
"request": "launch",
"preLaunchTask": "java-test",
},
{
"name": "Java Tests",
"type": "node",
"request": "launch",
"preLaunchTask": "java-tests",
}
]
}
and tasks.json under .vscode
{
"version": "2.0.0",
"tasks": [
{
"label": "typescript-test",
"command": "npm",
"args": ["test", "--alwaysStric", "--strictBindCallApply", "--strictFunctionTypes", "--target", "ES2022", "typescript/test.ts"],
"type": "shell"
},
{
"label": "typescript-tests",
"command": "npm",
"args": ["test", "--alwaysStric", "--strictBindCallApply", "--strictFunctionTypes", "--target", "ES2022", "typescript/problems.test.ts"],
"type": "shell"
},
{
"label": "python-test",
"command": "python",
"args": ["python/test.py"],
"type": "shell"
},
{
"label": "python-tests",
"command": "python",
"args": ["python/tests.py"],
"type": "shell"
},
{
"label": "golang-test",
"command": "go",
"args": ["test", "golang/solution_test.go", "golang/test_basic.go", "-test.timeout", "3s"],
"type": "shell"
},
{
"label": "golang-tests",
"command": "go",
"args": ["test", "golang/problems_test.go", "golang/test_basic.go", "-test.timeout", "10s"],
"type": "shell"
},
{
"label": "cpp-test",
"command": "bazel",
"args": ["test", "--cxxopt=-std=c++20", "--test_timeout=3", "--test_output=all", "//cpp:solution_test"],
"type": "shell"
},
{
"label": "cpp-tests",
"command": "bazel",
"args": ["test", "--cxxopt=-std=c++20", "--test_timeout=10", "--test_output=all", "//cpp/tests:all"],
"type": "shell"
},
{
"label": "java-test",
"command": "mvn",
"args": ["test", "-Dtest=\"qubhjava.test.TestMain\""],
"type": "shell"
},
{
"label": "java-tests",
"command": "mvn",
"args": ["test", "-Dtest=\"qubhjava.test.ProblemsTest\""],
"type": "shell"
}
]
}
If you want to write c++ in idea better, load this CMakeLists.txt
. But still, run test in bazel.
cmake_minimum_required(VERSION 3.28)
project(LeetCodeCpp)
set(CMAKE_CXX_STANDARD 20)
include(FetchContent)
# googletest
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG release-1.10.0 # Specify the version you need
)
FetchContent_MakeAvailable(googletest)
# nlohmann_json
FetchContent_Declare(
json
GIT_REPOSITORY https://github.com/nlohmann/json.git
GIT_TAG v3.9.1 # Specify the version you need
)
FetchContent_MakeAvailable(json)
include_directories(LeetCode)
file(GLOB_RECURSE COMMON_SOURCE LeetCode/cpp/*.cpp LeetCode/cpp/*.h)
file(GLOB_RECURSE PROBLEM_SOLUTIONS LeetCode/problems/*.cpp)
file(GLOB_RECURSE PREMIUMS_SOLUTIONS LeetCode/premiums/*.cpp)
add_executable(LeetCodeCpp
${COMMON_SOURCE}
${PROBLEM_SOLUTIONS}
${PREMIUMS_SOLUTIONS}
)
target_link_libraries(LeetCodeCpp
gtest_main
gmock_main
nlohmann_json::nlohmann_json
)
Solve your problem and enjoy!
Feel free to ask the author and add issues, discussions on GitHub.
Config GitHub Action Secrets for daily auto scripts. {SECRETS: TOKEN}
Add values similar to you .env, for example,
Notice: Add PROBLEM_FOLDER for actions to work properly.
1431.Kids With the Greatest Number of Candies
1342.Number of Steps to Reduce a Number to Zero
1365.How Many Numbers Are Smaller Than the Current Number
1281.Subtract the Product and Sum of Digits of an Integer
1313.Decompress Run-Length Encoded List
1614.Maximum Nesting Depth of the Parentheses
1389.Create Target Array in the Given Order
1486.XOR Operation in an Array
1221.Split a String in Balanced Strings
1662.Check If Two String Arrays are Equivalent
1290.Convert Binary Number in a Linked List to Integer
1588.Sum of All Odd Length Subarrays
104.Maximum Depth of Binary Tree Solution
83.Remove Duplicates from Sorted List
897.Increasing Order Search Tree
1678.Goal Parser Interpretation
944.Delete Columns to Make Sorted
26.Remove Duplicates from Sorted Array
1684.Count the Number of Consistent Strings
1688.Count of Matches in Tournament
1030.Matrix Cells in Distance Order
1700.Number of Students Unable to Eat Lunch
1704.Determine if String Halves Are Alike
121.Best Time to Buy and Sell Stock
122.Best Time to Buy and Sell Stock II
1640.Check Array Formation Through Concatenation
1539.Kth Missing Positive Number
1716.Calculate Money in Leetcode Bank
1646.Get Maximum in Generated Array
1725.Number Of Rectangles That Can Form The Largest Square
1732.Find the Highest Altitude
1736.Latest Time by Replacing Hidden Digits
1437.Check If All 1's Are at Least Length K Places Away
1742.Maximum Number of Balls in a Box
594.Longest Harmonious Subsequence
1752.Check if Array Is Sorted and Rotated
821.Shortest Distance to a Character
1758.Minimum Changes To Make Alternating Binary String
1337.The K Weakest Rows in a Matrix
1768.Merge Strings Alternately
1773.Count Items Matching a Rule
303.Range Sum Query - Immutable
232.Implement Queue using Stacks
1779.Find Nearest Point That Has the Same X or Y Coordinate
1784.Check if Binary String Has at Most One Segment of Ones
1047.Remove All Adjacent Duplicates In String
1790.Check if One String Swap Can Make Strings Equal
1796.Second Largest Digit in a String
1800.Maximum Ascending Subarray Sum
1805.Number of Different Integers in a String
1812.Determine Color of a Chessboard Square
1822.Sign of the Product of an Array
783.Minimum Distance Between BST Nodes
530.Minimum Absolute Difference in BST
1827.Minimum Operations to Make the Array Increasing
1832.Check if the Sentence Is Pangram
1844.Replace All Digits with Characters
1848.Minimum Distance to the Target Element
1863.Sum of All Subset XOR Totals
1869.Longer Contiguous Segments of Ones than Zeros
1668.Maximum Repeating Substring
1876.Substrings of Size Three with Distinct Characters
1880.Check if Word Equals Summation of Two Words
160.Intersection of Two Linked Lists
203.Remove Linked List Elements
1886.Determine Whether Matrix Can Be Obtained By Rotation
1893.Check if All the Integers in a Range Are Covered
1897.Redistribute Characters to Make All Strings Equal
374.Guess Number Higher or Lower
852.Peak Index in a Mountain Array
1903.Largest Odd Number in String
1909.Remove One Element to Make the Array Strictly Increasing
1913.Maximum Product Difference Between Two Pairs
1920.Build Array from Permutation
225.Implement Stack using Queues
1935.Maximum Number of Words You Can Type
1941.Check if All Characters Have Equal Number of Occurrences
1945.Sum of Digits of String After Convert
671.Second Minimum Node In a Binary Tree
1957.Delete Characters to Make Fancy String
1961.Check If String Is a Prefix of Array
1967.Number of Strings That Appear as Substrings in Word
551.Student Attendance Record I
345.Reverse Vowels of a String
646.Maximum Length of Pair Chain
1680.Concatenation of Consecutive Binary Numbers
1679.Max Number of K-Sum Pairs
117.Populating Next Right Pointers in Each Node II
1010.Pairs of Songs With Total Durations Divisible by 60
592.Fraction Addition and Subtraction
801.Minimum Swaps To Make Sequences Increasing
173.Binary Search Tree Iterator
406.Queue Reconstruction by Height
80.Remove Duplicates from Sorted Array II
1382.Balance a Binary Search Tree
865.Smallest Subtree with all the Deepest Nodes
19.Remove Nth Node From End of List
1685.Sum of Absolute Differences in a Sorted Array
1689.Partitioning Into Minimum Number Of Deci-Binary Numbers
98.Validate Binary Search Tree
116.Populating Next Right Pointers in Each Node
334.Increasing Triplet Subsequence
1124.Longest Well-Performing Interval
144.Binary Tree Preorder Traversal
1702.Maximum Binary String After Change
1705.Maximum Number of Eaten Apples
309.Best Time to Buy and Sell Stock with Cooldown
714.Best Time to Buy and Sell Stock with Transaction Fee
1457.Pseudo-Palindromic Paths in a Binary Tree
1391.Check if There is a Valid Path in a Grid
1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree
1712.Ways to Split Array Into Three Subarrays
82.Remove Duplicates from Sorted List II
3.Longest Substring Without Repeating Characters
1717.Maximum Score From Removing Substrings
1718.Construct the Lexicographically Largest Valid Sequence
1721.Swapping Nodes in a Linked List
1722.Minimize Hamming Distance After Swap Operations
1658.Minimum Operations to Reduce X to Zero
215.Kth Largest Element in an Array
470.Implement Rand10() Using Rand7()
1727.Largest Submatrix With Rearrangements
1641.Count Sorted Vowel Strings
5.Longest Palindromic Substring
1673.Find the Most Competitive Subsequence
1657.Determine if Two Strings Are Close
1329.Sort the Matrix Diagonally
1733.Minimum Number of People to Teach
1738.Find Kth Largest XOR Coordinate Value
1737.Change Minimum Characters to Satisfy One of Three Conditions
1663.Smallest String With A Given Numeric Value
1743.Restore the Array From Adjacent Pairs
1744.Can You Eat Your Favorite Candy on Your Favorite Day?
199.Binary Tree Right Side View
1749.Maximum Absolute Sum of Any Subarray
1750.Minimum Length of String After Deleting Similar Ends
1753.Maximum Score From Removing Stones
1754.Largest Merge Of Two Strings
538.Convert BST to Greater Tree
1038.Binary Search Tree to Greater Sum Tree
138.Copy List with Random Pointer
1091.Shortest Path in Binary Matrix
1759.Count Number of Homogenous Substrings
1760.Minimum Limit of Balls in a Bag
1249.Minimum Remove to Make Valid Parentheses
1764.Form Array by Concatenating Subarrays of Another Array
1769.Minimum Number of Operations to Move All Balls to Each Box
1770.Maximum Score from Performing Multiplication Operations
524.Longest Word in Dictionary through Deleting
581.Shortest Unsorted Continuous Subarray
1775.Equal Sum Arrays With Minimum Number of Operations
304.Range Sum Query 2D - Immutable
1780.Check if Number is a Sum of Powers of Three
1781.Sum of Beauty of All Substrings
1785.Minimum Elements to Add to Form a Given Sum
1786.Number of Restricted Paths From First to Last Node
331.Verify Preorder Serialization of a Binary Tree
1791.Find Center of Star Graph
1792.Maximum Average Pass Ratio
150.Evaluate Reverse Polish Notation
1797.Design Authentication Manager
1798.Maximum Number of Consecutive Values You Can Make
1801.Number of Orders in the Backlog
1802.Maximum Value at a Given Index in a Bounded Array
341.Flatten Nested List Iterator
1806.Minimum Number of Operations to Reinitialize a Permutation
1807.Evaluate the Bracket Pairs of a String
1143.Longest Common Subsequence
1814.Count Nice Pairs in an Array
1817.Finding the Users Active Minutes
1818.Minimum Absolute Sum Difference
81.Search in Rotated Sorted Array II
153.Find Minimum in Rotated Sorted Array
1823.Find the Winner of the Circular Game
208.Implement Trie (Prefix Tree)
1828.Queries on Number of Points Inside a Circle
1829.Maximum XOR for Each Query
1838.Frequency of the Most Frequent Element
1839.Longest Substring Of All Vowels in Order
1011.Capacity To Ship Packages Within D Days
1846.Maximum Element After Decreasing and Rearranging
1849.Splitting a String Into Descending Consecutive Values
1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number
17.Letter Combinations of a Phone Number
1482.Minimum Number of Days to Make m Bouquets
1855.Maximum Distance Between a Pair of Values
1856.Maximum Subarray Min-Product
1310.XOR Queries of a Subarray
1674.Minimum Moves to Make Array Complementary
421.Maximum XOR of Two Numbers in an Array
1864.Minimum Number of Swaps to Make the Binary String Alternating
1865.Finding Pairs With a Certain Sum
1442.Count Triplets That Can Form Two Arrays of Equal XOR
1870.Minimum Speed to Arrive on Time
1190.Reverse Substrings Between Each Pair of Parentheses
1669.Merge In Between Linked Lists
1670.Design Front Middle Back Queue
1664.Ways to Make a Fair Array
1877.Minimize Maximum Pair Sum in Array
1878.Get Biggest Three Rhombus Sums in a Grid
1881.Maximum Value after Insertion
1882.Process Tasks Using Servers
1642.Furthest Building You Can Reach
1653.Minimum Deletions to Make String Balanced
1887.Reduction Operations to Make the Array Elements Equal
1888.Minimum Number of Flips to Make the Binary String Alternating
1894.Find the Student that Will Replace the Chalk
1898.Maximum Number of Removable Characters
1899.Merge Triplets to Form Target Triplet
1239.Maximum Length of a Concatenated String with Unique Characters
1904.The Number of Full Rounds You Have Played
1906.Minimum Absolute Difference Queries
1647.Minimum Deletions to Make Character Frequencies Unique
1648.Sell Diminishing-Valued Colored Balls
1910.Remove All Occurrences of a Substring
1911.Maximum Alternating Subsequence Sum
1914.Cyclically Rotating a Grid
1915.Number of Wonderful Substrings
451.Sort Characters By Frequency
1921.Eliminate Maximum Number of Monsters
1418.Display Table of Food Orders in a Restaurant
981.Time Based Key-Value Store
1926.Nearest Exit from Entrance in Maze
1930.Unique Length-3 Palindromic Subsequences
1936.Add Minimum Number of Rungs
1937.Maximum Number of Points with Cost
1942.The Number of the Smallest Unoccupied Chair
1946.Largest Number After Mutating Substring
1947.Maximum Compatibility Score Sum
863.All Nodes Distance K in Binary Tree
1104.Path In Zigzag Labelled Binary Tree
1953.Maximum Number of Weeks for Which You Can Work
1954.Minimum Garden Perimeter to Collect Enough Apples
1959.Minimum Total Space Wasted With K Resizing Operations
1962.Remove Stones to Minimize the Total
1963.Minimum Number of Swaps to Make the String Balanced
516.Longest Palindromic Subsequence
1968.Array With Elements Not Equal to Average of Neighbors
1969.Minimum Non-Zero Product of the Array Elements
787.Cheapest Flights Within K Stops
797.All Paths From Source to Target
1240.Tiling a Rectangle with the Fewest Squares
188.Best Time to Buy and Sell Stock IV
1687.Delivering Boxes from Storage to Ports
1691.Maximum Height by Stacking Cuboids
132.Palindrome Partitioning II
1697.Checking Existence of Edge Length Limited Paths
1703.Minimum Adjacent Swaps for K Consecutive Ones
1707.Maximum XOR With an Element From Array
123.Best Time to Buy and Sell Stock III
84.Largest Rectangle in Histogram
1713.Minimum Operations to Make a Subsequence
1719.Number Of Ways To Reconstruct A Tree
1723.Find Minimum Time to Finish All Jobs
1649.Create Sorted Array through Instructions
1735.Count Ways to Make Array With Product
987.Vertical Order Traversal of a Binary Tree
1675.Minimize Deviation in Array
1745.Palindrome Partitioning IV
1751.Maximum Number of Events That Can Be Attended II
1761.Minimum Degree of a Connected Trio in a Graph
1771.Maximize Palindrome Length From Subsequences
1793.Maximum Score of a Good Subarray
1787.Make the XOR of All Segments Equal to Zero
1799.Maximize Score After N Operations
1803.Count Pairs With XOR in a Range
1808.Maximize Number of Nice Divisors
42.Trapping Rain Water42. Trapping Rain Water
154.Find Minimum in Rotated Sorted Array II
1835.Find XOR Sum of All Pairs Bitwise AND
363.Max Sum of Rectangle No Larger Than K
1851.Minimum Interval to Include Each Query
1857.Largest Color Value in a Directed Graph
1815.Maximum Number of Groups Getting Fresh Donuts
1819.Number of Different Subsequences GCDs
1269.Number of Ways to Stay in the Same Place After Some Steps
1866.Number of Ways to Rearrange Sticks With K Sticks Visible
1671.Minimum Number of Removals to Make Mountain Array
1665.Minimum Initial Energy to Finish Tasks
1074.Number of Submatrices That Sum to Target
1879.Minimum XOR Sum of Two Arrays
1883.Minimum Skips to Arrive at Meeting On Time
1643.Kth Smallest Instructions
1889.Minimum Space Wasted From Packaging
1655.Distribute Repeating Integers
1449.Form Largest Integer With Digits That Add up to Target
1896.Minimum Cost to Change the Final Value of Expression
1900.The Earliest and Latest Rounds Where Players Compete
1912.Design Movie Rental System
1916.Count Ways to Build Rooms in an Ant Colony
297.Serialize and Deserialize Binary Tree
1928.Minimum Cost to Reach Destination in Time
1931.Painting a Grid With Three Different Colors
1932.Merge BSTs to Create Single BST
1938.Maximum Genetic Difference Query
1944.Number of Visible People in a Queue
1948.Delete Duplicate Folders in System
1955.Count Number of Special Subsequences
847.Shortest Path Visiting All Nodes
1964.Find the Longest Valid Obstacle Course at Each Position
446.Arithmetic Slices II - Subsequence
1970.Last Day Where You Can Still Cross
552.Student Attendance Record II
295.Find Median from Data Stream