Skip to content

1925. Count Square Sum Triples 👍

  • Time: $O(n^2)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int countTriples(int n) {
    int ans = 0;
    unordered_set<int> squared;

    for (int i = 1; i <= n; ++i)
      squared.insert(i * i);

    for (const int a : squared)
      for (const int b : squared)
        if (squared.contains(a + b))
          ++ans;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int countTriples(int n) {
    int ans = 0;
    Set<Integer> squared = new HashSet<>();

    for (int i = 1; i <= n; ++i)
      squared.add(i * i);

    for (final int a : squared)
      for (final int b : squared)
        if (squared.contains(a + b))
          ++ans;

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def countTriples(self, n: int) -> int:
    ans = 0
    squared = set()

    for i in range(1, n + 1):
      squared.add(i * i)

    for a in squared:
      for b in squared:
        if a + b in squared:
          ans += 1

    return ans