Grokking Data Structures & Algorithms for Coding Interviews

0% completed

Solution: Divide Array Into Arrays With Max Difference

Problem Statement

You are given an array nums containing n integers and a positive integer k.

Divide the nums into arrays of size 3 such that it satisfies the below conditions:

  • Each element of nums should be in exactly one array.
  • The difference between any two elements of a single array should be less than or equal to k.

Return a 2D array of these subarrays. If no such division is possible, return an empty array.

Examples

Example 1:

  • Input: nums = [2, 6, 4, 9, 3, 7, 3, 4, 1], k = 3
  • Expected Output: [[1,2,3],[3,4,4],[6,7,9]]

.....

.....

.....

Like the course? Get enrolled and start learning!
Divyam Rawat

Divyam Rawat

· 8 months ago

When nums = [10, 20, 25, 30, 90, 100] and k =10. Shouldn't the output be [[20, 25, 30]], but with the given solution empty list is coming.

I think the loop should be:

for (int i = 0; i < nums.length - 2; i++) { if (nums[i + 2] - nums[i] <= k) { result.add(List.of(nums[i], nums[i + 1], nums[i + 2])); i += 2; } }