DEV Community


Posted on

Run Leetcode locally in Python and C++

Being able to run tests locally is very important. Leetcode server can be slow and the editor sub-optimal. Writing your code locally is more efficient and you can keep an archive of your test and problems for future references.

To test your code locally, you need to understand the concept of class. Leetcode questions are set up in a way that your solution function is a method in the solution class. Regardless of the language you use, to call your solution method, you need to create an object of the solution class and call you solution function through that object.

Here is an example in python, suppose this is a file called

class Solution(object):
  #your implementation

foo = Solution()
Enter fullscreen mode Exit fullscreen mode

Then you can run the python in the terminal to see your solution

Enter fullscreen mode Exit fullscreen mode

Note that sometimes the dependencies can be more complicated, you would need to import libraries for your code to work. Following is a c++ example, where you need to import a few libraries.

#include <iostream>
#include <unordered_map>
#include <string> 

using namespace std;
class Solution  {
    int lengthOfLongestSubstring(string s) {
    "your solution here"

int main() {

    Solution foo = Solution();
    int num = foo.lengthOfLongestSubstring("abcdcdefghcde");
    int num1 = foo.lengthOfLongestSubstring("");
    int num2 = foo.lengthOfLongestSubstring("aaaaaa");

    std::cout<<"out put "<<num<<" "<<num1<<" "<<num2<<std::endl;
    return 0;
Enter fullscreen mode Exit fullscreen mode

To run the code, compile and run the file(sol.cpp) in terminal:

g++ sol.cpp
Enter fullscreen mode Exit fullscreen mode

Discussion (0)