Tuesday, June 14, 2016

Design a Parking Lot [CCIB]

Data Structure Design:

Solution:
Cracking the coding interview Book - Page 323 - 6th edition

OO Design:
1. https://xmruibi.gitbooks.io/interview-preparation-notes/content/OOD/DesignExamples/ParkingLot.html





  • The parking lot has multiple slots.
  • The parking lot can park motorcycles, cars, and buses.
  • The parking lot has small slots, compact slots, and large slots.
  • A motorcycle can park in any slot.
  • A car can park in either a single compact slot or a single large slot.
  • A bus can park only in a single large slot.

  • ?
    1
    2
    3
    abstract class Vehicle {
         
    }
    ?
    1
    2
    3
    class Motorcycle extends Vehicle{
         
    }
    ?
    1
    2
    3
    class Car extends Vehicle {
         
    }
    ?
    1
    2
    3
    class Bus extends Vehicle {
         
    }
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    abstract class Slot {
         
        private boolean isOccupied;   
        private int slotNumber;
         
         
        Slot(int slotNumber) {
            isOccupied = false;
            this.slotNumber = slotNumber;   
        }
         
        boolean isOccupied() {
            return isOccupied;
        }
         
        int getSlotNumber() {
            return slotNumber;
        }
         
        void park() {
            isOccupied = true;
        }
         
        void unPark() {
           isOccupied = false;
        }
         
        @Override
        public boolean equals(Object o) {
            return (((Slot) o).slotNumber == this.slotNumber);
        }
        @Override
        public int hashCode() {
            int hash = 5;
            hash = 53 * hash + this.slotNumber;
            return hash;
        } 
       
    }
    ?
    1
    2
    3
    4
    5
    6
    class SmallSlot extends Slot {
         
        SmallSlot(int slotNumber){
            super(slotNumber);
        }
    }
    ?
    1
    2
    3
    4
    5
    6
    class CompactSlot extends Slot {
         
        CompactSlot(int slotNumber) {
            super(slotNumber);
        }
    }
    ?
    1
    2
    3
    4
    5
    6
    class LargeSlot extends Slot {
        LargeSlot(int slotNumber)  {
            super(slotNumber);
        }
    }
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    public class ParkingLot {
        private static final int NUMBER_OF_SMALL_SLOTS = 10;
        private static final int NUMBER_OF_COMPACT_SLOTS = 10;
        private static final int NUMBER_OF_LARGE_SLOTS = 10;
        public Map<Long, Slot> occupiedSlots;
        private List<Slot> smallSlots;
        private List<Slot> compactSlots;
        private List<Slot> largeSlots;
        public ParkingLot() {
            smallSlots = new ArrayList<>(NUMBER_OF_SMALL_SLOTS);
            compactSlots = new ArrayList<>(NUMBER_OF_COMPACT_SLOTS);
            largeSlots = new ArrayList<>(NUMBER_OF_LARGE_SLOTS);
            createSlots();
            occupiedSlots = new HashMap<>();
        }
        private void createSlots() {
            for (int i = 1; i <= NUMBER_OF_SMALL_SLOTS; i++) {
                smallSlots.add(new SmallSlot(i));
            }
            for (int i = 1; i <= NUMBER_OF_COMPACT_SLOTS; i++) {
                compactSlots.add(new CompactSlot(i));
            }
            for (int i = 1; i <= NUMBER_OF_LARGE_SLOTS; i++) {
                largeSlots.add(new LargeSlot(i));
            }
        }
        public long park(Vehicle vehicle) {
            Slot slot;
            long uniqueToken = -1;
            if (vehicle instanceof Motorcycle) {
                if ((slot = getFirstEmptySlot(smallSlots)) != null) {
                    uniqueToken = parkHelper(slot, vehicle);
                } else if ((slot = getFirstEmptySlot(compactSlots)) != null) {
                    uniqueToken = parkHelper(slot, vehicle);
                } else if ((slot = getFirstEmptySlot(largeSlots)) != null) {
                    uniqueToken = parkHelper(slot, vehicle);
                }
            } else if (vehicle instanceof Car) {
                if ((slot = getFirstEmptySlot(compactSlots)) != null) {
                    uniqueToken = parkHelper(slot, vehicle);
                } else if ((slot = getFirstEmptySlot(largeSlots)) != null) {
                    uniqueToken = parkHelper(slot, vehicle);
                }
            } else {
                if ((slot = getFirstEmptySlot(largeSlots)) != null) {
                    uniqueToken = parkHelper(slot, vehicle);
                }
            }
            return uniqueToken;
        }
        public void unPark(long uniqueToken) {
            occupiedSlots.get(uniqueToken).unPark();
            occupiedSlots.remove(uniqueToken);
        }
        private Slot getFirstEmptySlot(List<Slot> slots) {
            Iterator<Slot> slotIterator = slots.iterator();
            boolean isSlotFound = false;
            Slot emptySlot = null;
            while (slotIterator.hasNext() && !isSlotFound) {
                emptySlot = slotIterator.next();
                if (!emptySlot.isOccupied()) {
                    isSlotFound = true;
                }
            }
            return emptySlot;
        }
        private long parkHelper(Slot slot, Vehicle vehicle) {
            slot.park();
            long uniqueToken = vehicle.hashCode() * 43;
            occupiedSlots.put(uniqueToken, slot);
            return uniqueToken;
        }
    }


    2. http://www.coderanch.com/t/628047/patterns/Parking-Lot-Design

    Extra:
    http://massivetechinterview.blogspot.in/2015/07/cc150v5-84-design-parking-lot.html

    Valet Parking
    http://www.careercup.com/question?id=5750856565653504



    Building Bridges Problem

    There is a river that runs horizontally through an area. There are a set of cities above and below the river. Each city above the river is matched with a city below the river, and you are given this matching as a set of pairs.
    You are interested in building a set of bridges across the river to connect the largest number of the matching pairs of cities, but you must do so in a way that no two bridges intersect one another.
    Devise an algorithm to solve this problem as efficiently as possible.


    Pending


    Design ATM Machine

    Design ATM Machine


    class ATM; class ReceiptInfo;
    class ATMImpl{
     friend class ATM;
     private:
      ATMImpl(){/*implementation*/}
     public:
      float getBalanceInfo(){/*implementation*/}
      ReceiptInfo getReceiptInfo(){/*implementation*/}
      bool deposit(float val){/*implementation*/}
      bool withdraw(float val){/*implementation*/}
      bool verifyPIN(int pinVal){/*implementation*/}
      ~ATMImpl(){/*implementation*/}
    };
    class ATM{
     private:
      ATMImpl *d; //pointer to ATM implementation
     public:
      inline float getBalance(){return d->getBalance();}
      inline ReceiptInfo getReceiptInfo(){return d->getReceiptInfo();}
      inline bool deposit(float val){return d->deposit(val);}
      inline bool withdraw(float val){return d->withdraw(val);}
      inline bool verifyPIN(int pinVal){return d->verifyPIN(pinVal);}
    };
    
    class ATM_GUI{
     private:
      ATM atmObj;
     public:
      ATM_GUI(){/*initialize GUI*/}
      void printReceipt(){atmObj.getReceiptInfo();/*more implementation*/}
      void printBalance(){atmObj.getBalance();/*more implementation*/}
      inline bool verifyPIN(int pinVal){atmObj.verifyPIN(pinVal);}
      inline bool withdraw(float amount){atmObj.withdraw(amount);}//Atomic operation
      inline bool deposit(float amount){atmObj.deposit(amount);}//Atomic operation
      //more methods (operations)
    };
    http://www.ijser.org/researchpaper/Designing-and-Implementing-of-ATM-System-Using-Object-Oriented-Approach.pdf
    http://www.math-cs.gordon.edu/courses/cs211/ATMExample/
    

    Design a Vending Machine

    Design a Vending Machine which can accept different coins, deliver different products

    http://javarevisited.blogspot.in/2016/06/design-vending-machine-in-java.html
    http://javarevisited.blogspot.in/2016/06/java-object-oriented-analysis-and-design-vending-machine-part-2.html

    class VendingMachine
        - boolean takeMoney(Money money);
        //Here item will contain type & quantity, no smart search required 
        //say user need half litere Coke.
        - Item pickItem(Item item); 
        - boolean isAvilable(Item item)
        - Double askForAmount(Input input);
        - Double valiDateAndReturnBalance(Money money);
    class Money
        -CurrencyType type;
        -Double amount  
    class MoneyValidator
        - boolean validate(Money amount);
    class Item
        -ItemType type;
        -Double quantity
        -String barcode; // May be anything else to identify it
    class Input
        - CommandType type;
        - Double quantity
        - ItemType type;
    class display
        - void updateDisplay(String instructions)
    class KeyPad
        - Input readUserInput(Key key);
    class Key
        -KeyType type
        -Double value

    enum CurrencyType
    enum ItemType
    enum KeyType
    enum CommandType

    http://javarevisited.blogspot.com/2012/06/20-design-pattern-and-software-design.html#ixzz4BcfqpY2j
    http://ramj2ee.blogspot.in/2014/02/state-design-pattern-implementation.html#.V7NUPph95nL

    Design a Hash Table [CCIB]

    Thursday, March 13, 2014

    Design and Search in a Maze

    On an office floor , there are e entities - Walls , Cubicles , Coffee Rooms. 

    In what data structure we should store this design that when a new member joins the company , the cubicle number which is empty and next closest to any coffee room should be assigned to it. 

    Basically , data structure DS.pop() should return that cubicle number in the most efficient way. 

    A Person can walk through cubicles to reach a coffee room but not through walls.

    http://shirleyisnotageek.blogspot.in/2015/01/the-amazing-maze.html

    three ways to design a maze:

    • Depth-first search;
    • Randomized Kruskal's algorithm;
    • Randomized Prim's algorithm;

    Useful Discussion:
    ---------------------

    http://www.careercup.com/question?id=6495252147863552

    Design a meeting scheduler

    Design a meeting scheduler:
    How you will identify conflicting meetings?
    How you will design data structure and supporting algorithm so that System will suggest Best Available Meeting time considering the fact that many folks on the invite might be in different geography.

    Approach: Using Array and Binary search
    Start with an empty list of meetings, each with a start_time and duration. We will maintain a sorted list of meetings by start_time.

    To add a meeting to the list, find where it belongs in the list by performing a binary search. Once you find the index, perform two checks to avoid a collision; consider the meetings immediately before and after the to-be-inserted meeting (if they exist).

    Assert the before-meeting's start_time + duration does not exceed the new meeting's start_time.
    Assert the new meeting's start_time+duration does not exceed the after-meeting's start_time.
    If the assertions are satisfied, add the meeting to the list.

    This add operation takes O(log(list_size)) time.

    Note: This approach assumes that adding a meeting with an overlap is an invalid operation. If overlaps are allowed to exist, you would have to check beyond the meetings immediately preceding/subsequent the new meeting.

    Approach 2: using BST
    We can have a Tree structure (BST) for storing the requests (Request object: start time/end time/date/priority etc.). By doing so, add/delete/search/update operations can be achieved by O(height_of_tree). If we use a balanced tree, we can get the optimized running time. i.e. O(log n) for each of the above mentioned operations.

    This approach is better than the sorted list approach as the list is backed by an fixed sized array in case of ArrayList which takes O(n) for copying the elements from old array to new array. If we use a linkedlist, binary search is not possible.

    Useful Discussion:------------------
    http://stackoverflow.com/questions/15150188/amazon-interview-design-meeting-scheduler
    https://www.careercup.com/question?id=15555745
    http://www.careercup.com/question?id=5720778041458688

    Producer–consumer problem--Multi process synchronisation-Using Semaphore

    Implement Producer–consumer problem using

    1.Semaphore and Mutex
    2.Monitors


    http://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem

    Trie - Information Retrieval Data Structure

    Design trie and discuss the applications

    http://en.wikipedia.org/wiki/Trie
    http://www.geeksforgeeks.org/trie-insert-and-search/
    http://www.geeksforgeeks.org/trie-delete/

    Design Patterns

    Design Patterns:

    http://www.geeksforgeeks.org/category/design/

    0. http://www.coderanch.com/t/659856/Wiki/Singleton-Pattern
    1. https://xmruibi.gitbooks.io/interview-preparation-notes/content/OOD/TypicalPattern/index.html
    2. http://javarevisited.blogspot.com/2012/06/20-design-pattern-and-software-design.html
    3.  https://sourcemaking.com/design-patterns-and-tips

    Factory, Singleton, Prototype and Builder Patterns:



    [Cracking the Coding Interview]
    Because interviewers are trying to test your capabilities and not your knowledge, design patterns are mostly beyond the scope of an interview. However, the Singleton and Factory Method design patterns are widely used in interviews, so we will cover them here. There are far more design patterns than this book could possibly discuss. A great way to improve your software engineering skills is to pick up a book that focuses on this area specifically. Be careful you don't fall into a trap of constantly trying to find the "right" design pattern for a particular problem. You should create the design that works for that problem. In some cases it might be an established pattern, but in many other cases it is not. 
    Singleton Class The Singleton pattern ensures that a class has only one instance and ensures access to the instance through the application. It can be useful in cases where you have a "global" object with exactly one instance. For example, we may want to implement Restaurant such that it has exactly one instance of Restaurant. 
    1 public class Restaurant { 
    2 private static Restaurant _instance = null; 
    3 protected Restaurant() { ... } 
    4 public static Restaurant getlnstance() { 
    5 if (_instance == null) { 
    6 _instance = new Restaurant(); 
    7 } 
    8 return _instance; 
    9 } 
    10 }
     It should be noted that many people dislike the Singleton design pattern, even calling it an "anti-pattern:' One reason for this is that it can interfere with unit testing. 
    Factory Method The Factory Method offers an interface for creating an instance of a class, with its subclasses deciding which class to instantiate. You might want to implement this with the creator class being abstract and not providing an implementation for the Factory method. Or, you could have the Creator class be a concrete class that provides an implementation for the Factory method. In this case, the Factory method would take a parameter representing which class to instantiate. 
    1 public class CardGame { 
    2 public static CardGame createCardGame(GameType type) { 
    3 if (type == GameType.Poker) { 
    4 return new PokerGame(); 
    5 } else if (type == GameType.BlackJack) { 
    6 return new BlackJackGame(); 
    7 } 
    8 return null; 
    9 } 

    10 }