Yelp | OA 2020 | Detect and Order Business
Anonymous User
4295

I recently applied for a SWE internship position at Yelp in the EMEA region. I got a reponse pretty quickly which contained a Hackerrank Test. I got the standard Recommend Business problem but I was unable to complete it and informed the recruiter. She responded the next day with another Hackerrank Test.

Apparently Yelp has a thing for modelling their questions based on Businesses.

This problem deals with Chain Businesses i.e businesses that operate in multiple locations.

The problem was given a list of Buisnesses which are C and a target location return a sorted (ascending) list of Chains. The chains are ordered based on the frequency of occurence. The list can contain duplicate business chains i.e same business name, id and location appearing more than once. We break frequency ties by ordering the chain names alphabetically.

My approach was to use a Set to keep track of chains I had seen before, a Map to hold the business name to Chain/Frequency relationship and finally a Priority Queue to help with the ordering.

The classes and my solution are below:

static class Business {
       String name;
       String location;
       String id;

       Business(String name, String location, String id) {
           this.name = name;
           this.location = location;
           this.id = id;
       }
   }
   
   static class Chain {
       String name;
       Integer frequency;

       Chain(String name, Integer frequency) {
           this.name = name;
           this.frequency = frequency;
       }
   }
   
   public static List<Chain> detectAndOrderChainBusiness(List<Business> businesses, String location) {

       Set<String> seen = new HashSet<>();
       HashMap<String, Chain> chains = new HashMap<>();

       for (Business business : businesses) {
           if (business.location.equals(location) && !seen.contains(business.name + business.id)) {
               seen.add(business.name + business.id);
               if (chains.containsKey(business.name)) {
                   chains.get(business.name).frequency++;
               } else {
                   chains.put(business.name, new Chain(business.name, 1));
               }
           }
       }

       PriorityQueue<Chain> chain = new PriorityQueue<>(new CompareChain());

       for (Map.Entry<String, Chain> entry : chains.entrySet()) {
           chain.add(entry.getValue());
       }

       ArrayList<Chain> chains1 = new ArrayList<>();

       while (!chain.isEmpty()) {
           chains1.add(chain.poll());
       }

       return chains1;

   }

   static class CompareChain implements Comparator<Chain> {
       public int compare(Chain one, Chain two) {
           if (one.frequency.equals(two.frequency)) {
               return one.name.compareTo(two.name);
           }
           return Integer.compare(one.frequency, two.frequency);
       }
   }
   
   
   
Comments (12)