DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

1

Count Special Quadruplets

Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:

  • nums[a] + nums[b] + nums[c] == nums[d], and
  • a < b < c < d

Example 1:

Input: nums = [1,2,3,6]
Output: 1
Explanation: The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.

Example 2:

Input: nums = [3,3,6,4,5]
Output: 0
Explanation: There are no such quadruplets in [3,3,6,4,5].

Example 3:

Input: nums = [1,1,1,3,5]
Output: 4
Explanation: The 4 quadruplets that satisfy the requirement are:

  • (0, 1, 2, 3): 1 + 1 + 1 == 3
  • (0, 1, 3, 4): 1 + 1 + 3 == 5
  • (0, 2, 3, 4): 1 + 1 + 3 == 5
  • (1, 2, 3, 4): 1 + 1 + 3 == 5

Constraints:

  • 4 <= nums.length <= 50
  • 1 <= nums[i] <= 100

SOLUTION:

class Solution:
    def countQuadruplets(self, nums: List[int]) -> int:
        n = len(nums)
        ctr = 0
        exists = {}
        for i, num in enumerate(nums):
            exists[num] = exists.get(num, []) + [i]
        for i in range(n):
            for j in range(i + 1, n):
                for k in range(j + 1, n):
                    val = nums[i] + nums[j] + nums[k]
                    if val in exists:
                        for p in exists[val]:
                            if p > k:
                                ctr += 1
        return ctr
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay