Coder's Cat

LeetCode: Find Positive Integer Solution for a Given Equation

2020-12-18

Given a function  f(x, y) and a value z, return all positive integer pairs x and y where f(x,y) == z.

The function is constantly increasing, i.e.:

f(x, y) < f(x + 1, y)
f(x, y) < f(x, y + 1)

The function interface is defined like this: 

interface CustomFunction {
public:
  // Returns positive integer f(x, y) for any given positive integer x and y.
  int f(int x, int y);
};

For custom testing purposes you’re given an integer function_id and a target z as input, where function_id represent one function from an secret internal list, on the examples you’ll know only two functions from the list.  

You may return the solutions in any order.

Example 1:

Input: function_id = 1, z = 5
Output: [[1,4],[2,3],[3,2],[4,1]]

Explanation: function_id = 1 means that f(x, y) = x + y

Brute force Solution

Enumerate all the pairs of x and y, add the pair into final answer if the result is ‘z’.

class Solution {
public:
vector<vector<int>> findSolution(CustomFunction& customfunction, int z) {
vector<vector<int>> res;
for(int i=1; i<=1000; i++) {
for(int j=1; j<=1000; j++) {
int r = customfunction.f(i, j);
if(r == z) {
vector<int> t{i, j};
res.push_back(t);
} else if(r > z) break;
}
}
return res;
}
};

Binary-search Solution

Notice the precondition: The function is constantly increasing:

f(x, y) < f(x + 1, y)
f(x, y) < f(x, y + 1)

We can set x to 1 and y to 1000, this is the middle of all possible results, then we adjust x and y according to the result.
This solution is an algorithm of binary-search.

class Solution {
public:
vector<vector<int>> findSolution(CustomFunction& customfunction, int z) {
vector<vector<int>> res;
int x = 1;
int y = 1000;
while (x <= 1000 && y >= 1) {
int r = customfunction.f(x, y);
if(r == z) {
vector<int> vect{x, y};
res.push_back(vect);
x++;
y--;
} else if(r < z) x++;
else y--;
}
return res;
}
};

Preparing for an interview? Checkout this!

Join my Email List for more insights, It's Free!😋