0

I am solving a coding challenge and my code failed in test cases with large number of inputs due to timeout.

I am using a nested for loop to find the minimum difference in an array of integers with respect to their order (sorting isn't an option). For example: minimum difference in this array: {20, 7, 8, 2, 5} is (7 - 5 = 2) not (8 - 7 = 1).

I know that using nested for loops are bad when it comes to execution time. I've searched a lot for an alternative to using nested for loops in this case and failed to find any.

Is there a way to implement this algorithm without using nested for loop?

4
  • could you provide the data set range ? Commented Nov 20, 2016 at 8:43
  • try using merge sort or quick sort rather than using convention sorting algorithm it will cost you 0(n2) Commented Nov 20, 2016 at 8:45
  • Why is sorting not an option? Think about what obstacles make you say sorting is not an option, then figure out how to get around the obstacle. Commented Nov 20, 2016 at 8:54
  • Sorting isn't an option because the challenge requires order to be taken in consideration. For example: minimum difference in this array: {20, 7, 8, 2, 5} is (7 - 5 = 2) not (8 - 7 = 1) Commented Jan 16, 2018 at 15:29

1 Answer 1

1

Efficient: O(n Log n)

The idea is to use sorting. Below are steps.

1) Sort array in ascending order. This step takes O(n Log n) time if you are using merge or quick sort.

2) Initialize difference as infinite. This step takes O(1) time.

3) Compare all adjacent pairs in sorted array and keep track of minimum difference. This step takes O(n) time

#include <bits/stdc++.h>
using namespace std;


int MinDiff(int arr[], int n)
{
   // Sort array in non-decreasing order
   sort(arr, arr+n);

   // Initialize difference as infinite
   int diff = INT_MAX;

   // Find the min diff by comparing adjacent
   // pairs in sorted array
   for (int i=0; i<n-1; i++)
      if (arr[i+1] - arr[i] < diff)
          diff = arr[i+1] - arr[i];


   return diff;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.