Skip to content

Commit 134de00

Browse files
Create README.md
1 parent 8781478 commit 134de00

File tree

1 file changed

+69
-0
lines changed
  • Medium/2966. Divide Array Into Arrays With Max Difference

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+
# 2966. Divide Array Into Arrays With Max Difference
2+
3+
## 🧠 Problem Summary
4+
5+
You are given:
6+
- An integer array `nums` of size `n` (where `n` is a multiple of 3)
7+
- A positive integer `k`
8+
9+
Your task is to **divide `nums` into `n / 3` arrays of size 3**, such that:
10+
11+
- The **difference between any two elements** in a group is **less than or equal to `k`**
12+
13+
Return:
14+
- A 2D array containing valid groups
15+
- Or `[]` if no such division is possible
16+
17+
> If multiple answers exist, any of them is accepted.
18+
19+
---
20+
21+
## 🧪 Examples
22+
23+
### Example 1
24+
**Input:**
25+
`nums = [1,3,4,8,7,9,3,5,1]`, `k = 2`
26+
**Output:**
27+
`[[1,1,3],[3,4,5],[7,8,9]]`
28+
29+
### Example 2
30+
**Input:**
31+
`nums = [2,4,2,2,5,2]`, `k = 2`
32+
**Output:**
33+
`[]`
34+
**Explanation:**
35+
Any valid division forces 5 and 2 in same group → diff = 3 > k → invalid.
36+
37+
---
38+
39+
## ✅ Constraints
40+
41+
- `1 <= n <= 10^5`
42+
- `n % 3 == 0`
43+
- `1 <= nums[i] <= 10^5`
44+
- `1 <= k <= 10^5`
45+
46+
---
47+
48+
## 🧩 Approach
49+
50+
1. **Sort** the array to group close elements.
51+
2. Iterate through the array in **steps of 3**.
52+
3. Check that each triplet has a **max-min difference ≤ k**.
53+
4. If not, return `[]`. Otherwise, collect groups.
54+
55+
---
56+
### ⏱ Time Complexity
57+
+ Sorting: `O(n log n)`
58+
59+
+ Grouping: `O(n)`
60+
61+
+ Total: Efficient for up to `10^5` elements
62+
63+
----
64+
65+
### 🙌 Contributed by
66+
Muawiya – [Coding Moves](https://www.youtube.com/@Coding_Moves)
67+
Let's move with logic. 🚀
68+
69+
---

0 commit comments

Comments
 (0)