Skip to content

Closest Numbers

Moustafa Attia edited this page Dec 28, 2017 · 1 revision

This wiki to show my solution for HackerRank problem Closest Numbers

Solution steps:

  • first, I need to find the smallest difference between each pair
  • to find this smallest difference pair, I will sort the array and then iterate from (1 … arr size) in each iteration find abs(arr[i]-arr[i-1]) and store the value to find the minimum one
  • then create vector p of pair <int,int>, this vector will store each element with it’s adjacent pair difference, for example:
  • p[x].first = arr[y]
  • p[x].second = abs(arr[y]-arr[y-1])
  • finally iterate over this vector p and if find p[x].second = the minimum difference, push it’s first part (p[x].first) in result vector
  • return result vector sorted

Solution in C++:

vector <int> closestNumbers(vector <int> arr) {
	vector<int> res;
	vector<pair<int,int>> p;
	int m = INT_MAX;
	int j = 0;
	sort(arr.begin(), arr.end());
	for (int i = 1; i < arr.size(); i++){
		int diff = abs(arr[i] - arr[i - 1]);
		m = min(m, diff);
                // -1 is an arbitrary value
		p.push_back(pair<int, int>(-1, -1));
		p.push_back(pair<int, int>(-1, -1));
		p[j].first = arr[i];
		p[j+1].first = arr[i - 1];
		p[j].second = diff;
		p[j+1].second = diff;
                // add 2 to jump twice, so each element will have two values in pair vector, the first with its front 
                // adjacent and the second for its back adjacent 
                j++; j++;
	}

	for (int i = 0; i < p.size(); i++)
	{
		if (p[i].second == m) {
			res.push_back(p[i].first);
		}
	}
	sort(res.begin(), res.end());
	return res;
}

Clone this wiki locally