Skip to content

Commit 993a573

Browse files
authored
Create 1995-count-special-quadruplets.java
1 parent d15818f commit 993a573

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/**
2+
* LeetCode Problem: 1995. Count Special Quadruplets
3+
*
4+
* Difficulty: Easy
5+
*
6+
* Problem Statement:
7+
* You are given a 0-indexed integer array nums. Return the number of distinct quadruplets (a, b, c, d) such that:
8+
*
9+
* - nums[a] + nums[b] + nums[c] == nums[d], and
10+
* - a < b < c < d
11+
*
12+
* Example 1:
13+
* Input: nums = [1,2,3,6]
14+
* Output: 1
15+
* Explanation: The only quadruplet is (0,1,2,3) because 1 + 2 + 3 == 6.
16+
*
17+
* Example 2:
18+
* Input: nums = [3,3,6,4,5]
19+
* Output: 0
20+
* Explanation: No such quadruplet exists.
21+
*
22+
* Example 3:
23+
* Input: nums = [1,1,1,3,5]
24+
* Output: 4
25+
* Explanation: The quadruplets are (0,1,2,3), (0,1,2,4), (0,2,1,3), (0,2,1,4).
26+
*
27+
* Constraints:
28+
* - 4 <= nums.length <= 50
29+
* - 1 <= nums[i] <= 100
30+
*
31+
* Approach:
32+
* We need to count all ordered quadruplets (a, b, c, d) where:
33+
* nums[a] + nums[b] + nums[c] == nums[d] and a < b < c < d
34+
*
35+
* Brute force solution:
36+
* - Iterate through all possible quadruplets using 4 nested loops.
37+
* - For each (i, j, k, l), compute sum = nums[i] + nums[j] + nums[k].
38+
* - If sum == nums[l], increment the count.
39+
*
40+
* Optimization:
41+
* - Since nums[i] <= 100, if sum > 100 we can break early (small pruning).
42+
* - This helps avoid unnecessary checks.
43+
*
44+
* Complexity:
45+
* - Time Complexity: O(n^4) in the worst case (since we check all quadruplets).
46+
* With n <= 50, this is acceptable (50^4 = 6.25 million iterations).
47+
* - Space Complexity: O(1) since we only use a counter.
48+
*/
49+
50+
class Solution {
51+
public int countQuadruplets(int[] nums) {
52+
int count = 0;
53+
for (int i = 0; i < nums.length; i++) {
54+
for (int j = i + 1; j < nums.length; j++) {
55+
for (int k = j + 1; k < nums.length; k++) {
56+
int sum = nums[i] + nums[j] + nums[k];
57+
// small pruning: since nums[d] ≤ 100, skip if sum > 100
58+
if (sum > 100) continue;
59+
for (int l = k + 1; l < nums.length; l++) {
60+
if (sum == nums[l]) {
61+
count++;
62+
}
63+
}
64+
}
65+
}
66+
}
67+
return count;
68+
}
69+
}

0 commit comments

Comments
 (0)