- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 45 lines of C++ from the credited upstream file count-number-of-trapezoids-ii.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 2 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6private:7 struct TupleHash {8 template <typename... T>9 std::size_t operator()(const std::tuple<T...>& t) const {10 return apply([](const auto&... args) {11 std::size_t seed = 0;12 ((seed ^= std::hash<std::decay_t<decltype(args)>>{}(args) + 13 0x9e3779b9 + (seed << 6) + (seed >> 2)), ...);14 return seed;15 }, t);16 }17 };18 19public:20 int countTrapezoids(vector<vector<int>>& points) {21 unordered_map<tuple<int, int>, int, TupleHash> lookup_slope;22 unordered_map<tuple<int, int, int>, int, TupleHash> lookup_line;23 unordered_map<tuple<int, int, int>, int, TupleHash> lookup_slope_length;24 unordered_map<tuple<int, int, int, int>, int, TupleHash> lookup_line_length;25 int result = 0, same = 0;26 for (int i = 0; i < size(points); ++i) {27 const int x1 = points[i][0], y1 = points[i][1];28 for (int j = 0; j < i; ++j) {29 const int x2 = points[j][0], y2 = points[j][1];30 const int dx = x2 - x1, dy = y2 - y1;31 const auto& g = gcd(dx, dy);32 int a = dx / g, b = dy / g;33 if (a < 0 || (a == 0 && b < 0)) {34 a = -a, b = -b;35 }36 const int c = b * x1 - a * y1;37 result += lookup_slope[tuple(a, b)]++ - lookup_line[tuple(a, b, c)]++;38 const int l = dx * dx + dy * dy;39 same += lookup_slope_length[tuple(a, b, l)]++ - lookup_line_length[tuple(a, b, c, l)]++;40 }41 }42 return result - same / 2;43 }44};45