Skip to content

david-alvarez-rosa/CppPlayground

Repository files navigation

C++ Playground

This repository will be used as a playground for C++.

Leetcode Problems

Instructions for solving Leetcode problems.

Usage

Pre-requisite

Install GoogleTest C++ testing framework on your machine:

pacman -S gtest  # Arch Linux
apt-get install libgmock-dev libgtest-dev  # Debian-based
brew install googletest  # MacOS

Also, make sure that the bits/stdc++.h header is present on your machine. If not, you can download and install it manually. See for example how to do it in MacOS:

sudo cp -r bits /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/

Setup

Only setup required is for CMake (just needed once)

cmake -DCMAKE_BUILD_TYPE=Debug -B build

Usage

Write your solution for the Leetcode problem, build and run

cmake --build build  # build
./build/cpp_leetcode  # run

which can be combined

cmake --build build && ./build/cpp_leetcode

For running a specific tests, the following commands are useful

./build/cpp_leetcode --help
./build/cpp_leetcode --gtest_list_tests
./build/cpp_leetcode --gtest_filter='*.<matcher>'

Debug

Problem can be debugged with GDB or LLDB

lldb ./build/cpp_leetcode
gdb ./build/cpp_leetcode

Example

Solution for Leetcode 1 problem twoSum.

#include <bits/stdc++.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>

using namespace std;
using namespace testing;

class Solution {
 public:
  vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int, int> mp;  // (nums[i], i)
    for (int i{0}; i < nums.size(); i++) {
      const auto complement = target - nums[i];
      if (mp.contains(complement)) return {i, mp[complement]};
      mp[nums[i]] = i;
    }
    return {0, 0};
  }
};

TEST(SolutionTest, Test1) {
  Solution solution;
  vector<int> nums{2, 7, 11, 15};
  EXPECT_THAT(solution.twoSum(nums, 9), UnorderedElementsAre(0, 1));
}

TEST(SolutionTest, Test2) {
  Solution solution;
  vector<int> nums{3, 2, 4};
  EXPECT_THAT(solution.twoSum(nums, 6), UnorderedElementsAre(1, 2));
}

TEST(SolutionTest, Test3) {
  Solution solution;
  vector<int> nums{3, 3};
  EXPECT_THAT(solution.twoSum(nums, 6), UnorderedElementsAre(0, 1));
}

Contributions

Feel free to raise a PR for improvements / suggestions :)

Author

David Álvarez Rosa

Releases

No releases published

Packages

No packages published

Languages