Minimum difference between values in an array with factors 1 to M
Given an array of nums of length N and an integer M, the task is to find the minimum difference between two elements of nums such that the numbers coming between these two integers (including the selected numbers) have all factors 1, 2, 3, …, M. Return the minimum difference if it does not exist then return -1.
Input: N = 5, M = 7, nums = [6, 4, 5, 3, 7]
Explanation: First number will be 4 and the second will be 7, so the numbers between 4 and 7 are: [4, 5, 7]
Factors of 4 –> (1, 2, 4)
Factors of 5 –> (1, 5)
Factors of 7 –> (1, 7)
So, it contains every number from 1, 2, 3, 4, 5, 6, 7(as M = 7)
Input: N = 4, M = 2, nums = [3, 7, 2, 9]
Explanation: First number will be 2 and Second number is also 2
Factors of 2 –> (1, 2)
So it contains 1, 2(as M = 2)
Input: N = 3, M = 4, nums = [1, 3, 7]
Approach: To solve the problem follow the below-given steps:
- Sort the given array in a non-decreasing array
- Find factors of every number present in the given array.
- Now we will use two pointer approach to solve the problem and we will keep track of factors in Hash Map factorFreq.
- Start from the 0th index for both the ith and jth pointer.
- Now while factorFreq size is less than M, we will keep incrementing the jth pointer.
- If the size of factorFreq is equal to M then compare the difference between the jth value and ith value and increment the ith value, make sure you don’t forget to update the factorFreq.
- Return the min value if exist.
Below is the implementation of the above approach:
Time Complexity: O(N* sqrt(N))
Auxiliary Space: O(N * sqrt(N))
Please Login to comment...