Amazon Interview Question
Software EngineersCountry: United States
Interview Type: In-Person
you could create a map of sets. the keys are variables, the set is all the variables it's equal to. then run through each non-equal equation and verify the lhs is not in the rhs's equivalency set, and vice versa.
public static boolean validateFunctions(String[][] equals, String[][] notEquals) {
Map<String, Set<String>> equivalencyMap = new HashMap<>();
// Assume print 2xN matrix where row 0 = lhs and row 1 = rhs
final int lhs = 0;
final int rhs = 1;
for(int i = 0; i<equals.length; i++) {
// Store lhs equivalence
String l = equals[lhs][i];
String r = equals[rhs][i];
addToMap(equivalencyMap, l, r);
addToMap(equivalencyMap, r, l);
}
for(int i = 0; i<equals.length; i++) {
// Store lhs equivalence
String l = notEquals[lhs][i];
String r = notEquals[rhs][i];
if(checkMap(equivalencyMap, l, r))
return false;
if (checkMap(equivalencyMap, r, l))
return false;
}
return true;
}
public class Pair{
char first;
char last;
}
//Using Disjoint sets.
public boolean isValid(Pair[] pairs, Pair[] unequals){
Map<Character,Character> ds = new HashMap<Character,Character>();
for(char x = 'A'; x <= 'Z'; x++){
ds.put(x,x);
}
for(Pair p: pairs){
char parent1 = find(ds,p.first);
char parent2 = find(ds,p.sec);
if(parent1 != parent2){
if(parent1 < parent2){
ds.put(parent2, parent1);
}else{
ds.put(parent1, parent2);
}
}
}
for(Pair p: unequals){
char parent1 = find(ds,p.first);
char parent2 = find(ds,p.sec);
if(parent1 == parent2){
return false;
}
}
return true;
}
private char find(Map<Character,Character> ds, char x){
char r = ds.get(x);
if(r == x){
return r;
}
r = find(ds,x);
ds.put(x,r);
return r;
}
That's a bit tricky question.
There several way how we can implement the UnionFind approach.
First of all we should not consider equation like a character, approach should be more general.
Moreover, It is really depends on how much items in first sequence we will have and how mush items in the second one. Depends of that you can modify your algorithm.
In general, one of operations can cost you O(n) and another one O(1).
We can solve this using union and find.
1) For the first set of equation: whenever you see something like A=C, do union of A and C. When you see A!=C, do nothing.
2) For the second set of equations:
When you find A=C. Go to the data structure built from first step and see root (or parent) of A and C are same, if so we are good. If not, then set of equations is not compatible.
Similarly when you see A!=C, you want to make sure root of A and C in data structure built from first step are not the same.
Its Called Bucket Mapping where we put all code in different bucket and if there is another set which is equal to same bucket, wew dont change bucket insted we define same bucket value, So all the char representing same bucket automatially equals to another bucket.
May be I left any edge case but that can be covered using if else
public class ValidateBooleanStatements {
private HashMap<Character, Integer> storage= new HashMap<Character, Integer>();
private HashMap<Integer, Integer> bucketMapper= new HashMap<>();
public int getRandomId(){
Random random= new Random();
return random.nextInt();
}
public void validateStatements(List<Pair> equals, List<Pair> unequal) throws Exception{
for(Pair pair:equals){
int randomNumber= getRandomId();
Integer aa=storage.get(pair.a);
Integer bb=storage.get(pair.b);
// case: where a and b both are same
if(pair.a==pair.b){
if(aa==null){// it doesnt exist, add it first time
storage.put(pair.a,randomNumber);
bucketMapper.put(randomNumber, randomNumber);
}
}else{//case: where both are different
if(aa!=null && bb!=null){// where both have already entry
if(aa!=bb){// where both arent equal yet
//change bucket
bucketMapper.remove(bb);
bucketMapper.put(bb, bucketMapper.get(aa));// now in bucket mapper both have same source where in storage they have diffrent bucket ID
}// if aa==bb they already are in same bucket and equal
}else if(aa!=null){
storage.put(pair.b, storage.get(pair.a));
// if a has already entry than put it in the same bucket
}else if(bb!=null){
storage.put(pair.a, storage.get(pair.b));
//if b has already an entry, put a in same bucket
}else if(aa==null && bb==null){
storage.put(pair.a, randomNumber);
storage.put(pair.b, randomNumber);
bucketMapper.put(randomNumber, randomNumber);
}
}
}
// we are just validating unequals not entering in storage.
for(Pair pair: unequal){
if(bucketMapper.get(storage.get(pair.a)) == bucketMapper.get(storage.get(pair.b))){
System.out.println(pair.a+"-"+pair.b+" Error");
}
}
}
public static void main(String[] args) throws Exception{
List<Pair> equal= new ArrayList<>();
List<Pair> unequal= new ArrayList<>();
equal.add(new Pair('A', 'B'));
equal.add(new Pair('B', 'D'));
equal.add(new Pair('C', 'D'));
equal.add(new Pair('F', 'G'));
equal.add(new Pair('G', 'H'));
equal.add(new Pair('H', 'C'));
unequal.add(new Pair('A', 'C'));
new ValidateBooleanStatements().validateStatements(equal, unequal);
}
}
class Pair{
Character a;
Character b;
Pair(Character a, Character b){
this.a=a;
this.b=b;
}
}
Its Called Bucket Mapping where we put all code in different bucket and if there is another set which is equal to same bucket, wew dont change bucket insted we define same bucket value, So all the char representing same bucket automatially equals to another bucket.
May be I left any edge case but that can be covered using if else
public class ValidateBooleanStatements {
private HashMap<Character, Integer> storage= new HashMap<Character, Integer>();
private HashMap<Integer, Integer> bucketMapper= new HashMap<>();
public int getRandomId(){
Random random= new Random();
return random.nextInt();
}
public void validateStatements(List<Pair> equals, List<Pair> unequal) throws Exception{
for(Pair pair:equals){
int randomNumber= getRandomId();
Integer aa=storage.get(pair.a);
Integer bb=storage.get(pair.b);
// case: where a and b both are same
if(pair.a==pair.b){
if(aa==null){// it doesnt exist, add it first time
storage.put(pair.a,randomNumber);
bucketMapper.put(randomNumber, randomNumber);
}
}else{//case: where both are different
if(aa!=null && bb!=null){// where both have already entry
if(aa!=bb){// where both arent equal yet
//change bucket
bucketMapper.remove(bb);
bucketMapper.put(bb, bucketMapper.get(aa));// now in bucket mapper both have same source where in storage they have diffrent bucket ID
}// if aa==bb they already are in same bucket and equal
}else if(aa!=null){
storage.put(pair.b, storage.get(pair.a));
// if a has already entry than put it in the same bucket
}else if(bb!=null){
storage.put(pair.a, storage.get(pair.b));
//if b has already an entry, put a in same bucket
}else if(aa==null && bb==null){
storage.put(pair.a, randomNumber);
storage.put(pair.b, randomNumber);
bucketMapper.put(randomNumber, randomNumber);
}
}
}
// we are just validating unequals not entering in storage.
for(Pair pair: unequal){
if(bucketMapper.get(storage.get(pair.a)) == bucketMapper.get(storage.get(pair.b))){
System.out.println(pair.a+"-"+pair.b+" Error");
}
}
}
public static void main(String[] args) throws Exception{
List<Pair> equal= new ArrayList<>();
List<Pair> unequal= new ArrayList<>();
equal.add(new Pair('A', 'B'));
equal.add(new Pair('B', 'D'));
equal.add(new Pair('C', 'D'));
equal.add(new Pair('F', 'G'));
equal.add(new Pair('G', 'H'));
equal.add(new Pair('H', 'C'));
unequal.add(new Pair('A', 'C'));
new ValidateBooleanStatements().validateStatements(equal, unequal);
}
}
class Pair{
Character a;
Character b;
Pair(Character a, Character b){
this.a=a;
this.b=b;
}
}
Try below if could help
public class DS {
public static boolean checkEq(List<Equation> list1, List<Equation> list2)
{
for(Equation eq1: list1)
{
for(Equation eq2: list2)
{
if(eq1.var1.equals(eq2.var1) && eq1.var2.equals(eq2.var2))
{
if(eq1.isEqual != eq2.isEqual)
return false;
}
}
}
return true;
}
public static void main(String[] args) {
List<Equation> list1 = new ArrayList<>();
List<Equation> list2 = new ArrayList<>();
Equation eq1 = new Equation("A","B",true);
Equation eq2 = new Equation("A","C",true);
Equation eq3 = new Equation("C","D",true);
Equation eq4 = new Equation("A","C",false);
Equation eq5 = new Equation("A","B",true);
list1.add(eq1);
list1.add(eq2);
list1.add(eq3);
list2.add(eq4);
list2.add(eq5);
System.out.println(checkEq(list1, list2));
}
where Equation is a class check below
public class Equation {
public String var1;
public String var2;
public boolean isEqual;
public Equation(String firstVar, String secondVar, boolean isEqual) {
var1 = firstVar;
var2 = secondVar;
this.isEqual = isEqual;
}
}
Try below if it could help
public class DS {
public static boolean checkEq(List<Equation> list1, List<Equation> list2)
{
for(Equation eq1: list1)
{
for(Equation eq2: list2)
{
if(eq1.var1.equals(eq2.var1) && eq1.var2.equals(eq2.var2))
{
if(eq1.isEqual != eq2.isEqual)
return false;
}
}
}
return true;
}
public static void main(String[] args) {
List<Equation> list1 = new ArrayList<>();
List<Equation> list2 = new ArrayList<>();
Equation eq1 = new Equation("A","B",true);
Equation eq2 = new Equation("A","C",true);
Equation eq3 = new Equation("C","D",true);
Equation eq4 = new Equation("A","C",false);
Equation eq5 = new Equation("A","B",true);
list1.add(eq1);
list1.add(eq2);
list1.add(eq3);
list2.add(eq4);
list2.add(eq5);
System.out.println(checkEq(list1, list2));
}
}
public class Equation {
public String var1;
public String var2;
public boolean isEqual;
public Equation(String firstVar, String secondVar, boolean isEqual) {
var1 = firstVar;
var2 = secondVar;
this.isEqual = isEqual;
}
}
Here is my solution in c++:
#include <iostream>
#include <vector>
using namespace std;
void fv(vector<int>&v)
{
unsigned int i = 0;
while(i<=v.size()) {
if(v[i]==-1) {
++i;
continue;
}
for(unsigned int j=i+1;j<=v.size();j++ ) {
if(v[i]==v[j])
v[j]=-1;
}
++i;
}
}
void pv(vector<int>&v){
for(vector<int>::iterator it=v.begin();it!=v.end();it++)
cout<<*it<<" ";
}
vector<int> merge(vector<int>&v1, vector<int>&v2) {
for(unsigned int i=0;i<=v1.size();i++)
for(unsigned int j=0;j<=v2.size();j++)
{
if(v1[i]==v2[j])
v2[j]=-1;
}
vector<int>v3;
unsigned int i;
if(v1.size()>v2.size())
i=v1.size();
else
i=v2.size();
for(unsigned int j = 0; j<i; j++){
if(v1.size()>j && v1[j]!=-1)
v3.push_back(v1[j]);
if(v2.size()>j && v2[j]!=-1)
v3.push_back(v2[j]);
}
return v3;
}
int main()
{
vector<int> v1 = {1,1,1,2,5};
vector<int> v2 = {2,2,2,5,9,11,19};
fv(v1);
fv(v2);
vector<int>v3 = merge(v1, v2);
pv(v3);
}
class Equation:
visited= list()
series1=['A = B', 'B = D', 'C = D', 'F = G', 'E = H', 'H = C']
series2=['A != C', 'D != H', 'F != A']
def GetEquivalentValue(self,mychar):
resultlist=list()
for equ in self.series1:
if equ[0] not in self.visited and equ[-1] not in self.visited:
if mychar.strip() in equ[0]:
resultlist.append(equ[-1].strip())
elif mychar.strip() in equ[-1]:
resultlist.append(equ[0].strip())
self.visited.append(mychar)
if len(resultlist) == 0:
return False,""
return resultlist
def EvaluateEquations(self,val1,val2):
resultlist = self.GetEquivalentValue(val1)
if not resultlist[0]:
return
if val2 in resultlist:
return True
for result in resultlist:
flag=self.EvaluateEquations(result,val2)
if flag == True:
return True
return False
if __name__ == "__main__":
eq= Equation()
for subseries in eq.series2:
flag=eq.EvaluateEquations(subseries[0].strip(),subseries[-1].strip())
if flag:
print "Invalid"
elif not flag:
print "Valid"
eq.visited=[]
Assuming the only operation appearing in the equations are != and =, we can use a graph. We can parse the first set of equation and for each e.g. A=B create an edge from A to B and B to A.
Now during validation an equation with "=" means there should be a path from left operand to right and "!=" means no path should exist.
Why can we just keep a list of all the characters which are equal something like if we have A=B, B=C, C=D. Keep a list (or Set) {A,B,C,D). Now when you are evaluating not equal cases like A!=B just make sure that LHS and RHS don't simultaneously appear in the set for a single evaluation. If all != satisfy the constraints then entire set of equations would be consistent otherwise not.
Its Called Bucket Mapping where we put all code in different bucket and if there is another set which is equal to same bucket, wew dont change bucket insted we define same bucket value, So all the char representing same bucket automatially equals to another bucket.
May be I left any edge case but that can be covered using if else
public class ValidateBooleanStatements {
private HashMap<Character, Integer> storage= new HashMap<Character, Integer>();
private HashMap<Integer, Integer> bucketMapper= new HashMap<>();
public int getRandomId(){
Random random= new Random();
return random.nextInt();
}
public void validateStatements(List<Pair> equals, List<Pair> unequal) throws Exception{
for(Pair pair:equals){
int randomNumber= getRandomId();
Integer aa=storage.get(pair.a);
Integer bb=storage.get(pair.b);
// case: where a and b both are same
if(pair.a==pair.b){
if(aa==null){// it doesnt exist, add it first time
storage.put(pair.a,randomNumber);
bucketMapper.put(randomNumber, randomNumber);
}
}else{//case: where both are different
if(aa!=null && bb!=null){// where both have already entry
if(aa!=bb){// where both arent equal yet
//change bucket
bucketMapper.remove(bb);
bucketMapper.put(bb, bucketMapper.get(aa));// now in bucket mapper both have same source where in storage they have diffrent bucket ID
}// if aa==bb they already are in same bucket and equal
}else if(aa!=null){
storage.put(pair.b, storage.get(pair.a));
// if a has already entry than put it in the same bucket
}else if(bb!=null){
storage.put(pair.a, storage.get(pair.b));
//if b has already an entry, put a in same bucket
}else if(aa==null && bb==null){
storage.put(pair.a, randomNumber);
storage.put(pair.b, randomNumber);
bucketMapper.put(randomNumber, randomNumber);
}
}
}
// we are just validating unequals not entering in storage.
for(Pair pair: unequal){
if(bucketMapper.get(storage.get(pair.a)) == bucketMapper.get(storage.get(pair.b))){
System.out.println(pair.a+"-"+pair.b+" Error");
}
}
}
public static void main(String[] args) throws Exception{
List<Pair> equal= new ArrayList<>();
List<Pair> unequal= new ArrayList<>();
equal.add(new Pair('A', 'B'));
equal.add(new Pair('B', 'D'));
equal.add(new Pair('C', 'D'));
equal.add(new Pair('F', 'G'));
equal.add(new Pair('G', 'H'));
equal.add(new Pair('H', 'C'));
unequal.add(new Pair('A', 'C'));
new ValidateBooleanStatements().validateStatements(equal, unequal);
}
}
class Pair{
Character a;
Character b;
Pair(Character a, Character b){
this.a=a;
this.b=b;
}
}
This is a 'merge set' question. Given a graph, figure out which nodes belong to the same connected component and put them into a set.
Since the input comes in as an edge set, UNION FIND will be a good way to solve this.
Initially every node sources to itself. As we read the statement X = Y, we point the source of Y to the source of X so that they join the same set. After all connected components are sorted out. We check the unequal statements X != Y. If any of the X, Y pairs do share the same source, then X != Y contradicts with the equal statements.
Looking for interview questions sharing and mentors? Visit A++ Coding Bootcamp at aonecode.com (select english at the top right corner).
- aonecoding January 27, 2017We provide ONE TO ONE courses that cover everything in an interview from the latest interview questions, coding, algorithms, system design to mock interviews. All classes are given by experienced engineers/interviewers from FB, Google and Uber. Help you close the gap between school and work. Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Welcome to email us with any questions.