educative.io

Educative

Test from a problem doesn't give the same result as when I run on my machine

My solution for the findSum problem was:

// Return 2 elements of arr that sum to the given value
int *findSum(int arr[], int value, int size) {
  // Sorting function is prepended as sort(arr, low, high)
  // Write your code here

  sort(arr, 0, size);

  int i = 0;
  int j = size - 1;

  while (i < size && j != 0) {
    if (i == j)
      break;

    int sum = arr[i] + arr[j];
    if (sum == value)
      return new int[2]{arr[i], arr[j]};

    if (sum < value)
      i++;
    else
      j--;
  }

  return arr;
}

The first tests says that it returns incorrect value for findSum([2,-4,6,7,-8,9], 16, 6);

But I tested on my machine and it returns the correct values:
(setting a sort function)
#include
#include

int *sort(int *arr, int from, int to) {
  std::sort(arr + from, arr + to);
  return arr;
}

(testing)
int main(int argc, const char **argv) {
int arr[] = {2, -4, 6, 7, -8, 9};
auto value = findSum(arr, 16, 6);

  for (int i = 0; i < 2; i++)
    std::cout << value[I] << " "; // result: 7   9

  return 0;
}

Course: Data Structures for Coding Interviews in C++ - Learn Interactively
Lesson: Challenge 3: Find Two Numbers that Add up to "value" - Data Structures for Coding Interviews in C++

Thanks @Vitor_Figueiredo_Mar for pointing this out. We’ve fixed it