Question is here: https://leetcode.com/discuss/interview-question/570407/salesforce-oa-hackerrank
Approach:
String interpolate(int n, int[] instances, float[] prices)
- Basic edge cases,
- if n > instances[instances.count-1] , interpolate based on last 2 points
- Same way, if n < instances[0], interpolate based on first 2 points.
- otherwise, find index, such that n < instances[index] (Optimization, use Binary seach to find index, instead of linear scan as instances array is already sorted)
- when you have index, extrapolate based on instances[index] and instances[index-1]
What does interpolate mean based on 2 points??
- essentially, get a slope of line., here instances = X axis, Prices = Y axis
- For this problem, say , find first index so that instancex[index] > n,
- Numerator = prices[index-1]-prices[index]
- Denominator = instance[index]-instances[index-1]
- Slope = Numerator/Denominator
- Now, use Slope to figure out for given n,
- diffential_value_price = (n-instance[index-1]) * slope
- Final value = prices[index-1] + differntial_value
Refer to sample test cases given in the link above, it will all make sense. Hope it helps someone in future.