Salesforce interview question

Find Pairs with least absolute difference in an given unsorted array,

Interview Answers

Anonymous

22 Jan 2016

1. Sort the array - O(nlogn) 2. Run through the loop to get the minimum difference

6

Anonymous

2 Mar 2016

there is better approach: build a tree, and each time you insert a value to the tree, compute difference with all elements you compare with this element. The whole complexity will be O(NlogN)

Anonymous

14 Mar 2016

Time O(n), Space O(n), n is length of integer. List> findPairNubmer(int[] nums, int target) { List> result = new ArrayList(); if(nums.length == 0 ) return result; HashSet set = new HashSet(); for(int i : nums) { set.add(i); } for(int i = 0; i pair = new ArrayList(); pair.add(nums[i]); pair.add(nums[i] + target); result.add(pair); } } return result; }