<p>Given four integer arrays <code>nums1</code>, <code>nums2</code>, <code>nums3</code>, and <code>nums4</code> all of length <code>n</code>, return the number of tuples <code>(i, j, k, l)</code> such that:</p>

<ul>
	<li><code>0 &lt;= i, j, k, l &lt; n</code></li>
	<li><code>nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0</code></li>
</ul>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
The two tuples are:
1. (0, 0, 0, 1) -&gt; nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -&gt; nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
<strong>Output:</strong> 1
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == nums1.length</code></li>
	<li><code>n == nums2.length</code></li>
	<li><code>n == nums3.length</code></li>
	<li><code>n == nums4.length</code></li>
	<li><code>1 &lt;= n &lt;= 200</code></li>
	<li><code>-2<sup>28</sup> &lt;= nums1[i], nums2[i], nums3[i], nums4[i] &lt;= 2<sup>28</sup></code></li>
</ul>

#include <unordered_map>
#include <vector>

class Solution {
 public:
  int fourSumCount(
      std::vector<int>& nums1, std::vector<int>& nums2,
      std::vector<int>& nums3, std::vector<int>& nums4) {
    std::unordered_map<long long, int> countsOfTwoPairs{};

    std::unordered_map<int, int> countsOfThreePairs{};
    for (const auto num : nums4) {
      const auto it = countsOfThreePairs.find(-num);
      if (it != countsOfThreePairs.end()) {
        ++it->second;
      } else {
        countsOfThreePairs.emplace(-num, 1);
      }
    }

    int count{0};
    for (const auto i : nums1) {
      for (const auto j : nums2) {
        const auto twoPairsSum = static_cast<long long>(i) + j;
        auto it = countsOfTwoPairs.find(twoPairsSum);
        if (it == countsOfTwoPairs.end()) {
          int count{0};
          for (const auto k : nums3) {
            const auto threePairsSum = twoPairsSum + k;
            const auto it = countsOfThreePairs.find(threePairsSum);
            if (it != countsOfThreePairs.end()) count += it->second;
          }
          it = countsOfTwoPairs.emplace(twoPairsSum, count).first;
        }
        count += it->second;
      }
    }

    return count;
  }
};

30200