Grokking Data Structures & Algorithms for Coding Interviews
Vote

0% completed

Divide Array Into Arrays With Max Difference (medium)

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!
P P

P P

· 5 months ago

One of the critical test case is missing:

Input: nums = [2,4,2,2,5,2], k = 2

Output: []

As a result even the incomplete solution passing:

public List<List<Integer>> divideArray(int[] nums, int k) { List<List<Integer>> result = new ArrayList<>(); Arrays.sort(nums);

System.out.println(Arrays.toString(nums));

ArrayList<Integer> subArr = new ArrayList<>();

for (int i = 0; i < nums.length; i++) { if (subArr.isEmpty() || Math.abs(subArr.get(0) - nums[i]) <= k) { subArr.add(nums[i]); }

if (subArr.size() == 3) { result.add(subArr); subArr = new ArrayList<>(); } }

return result; }

Hasnain Zeeshan

Hasnain Zeeshan

· 2 months ago

I don't understand what the issue is:

def divideArray(self, nums, k):



    if len(nums) < 3:

        return []

    

    nums.sort()



    res = []



    i = 0



    while i <= len(nums)-3:

        j = i+1

        count = 1

        size = 1

        while size != 3:

            if nums[j] - nums[j-1] <= k:



                j += 1

                count += 1

            size += 1



        if count == 3:

            res.append(nums[i:i+3])

            i += 3

        else:

            i += 1





    

    return res

WrongAnswer

0.068 s

Your Input

[1, 2, 4, 5, 9, 10]

2

Output

[[1,2,4]]

Expected

[]

Do ALL elements in the array NEED to be subdivided into subarrays oth