😭Design Phone Directory

Problem

https://leetcode.com/problems/design-phone-directoryarrow-up-right

Understanding of problem

At first, I thought I could solve it using a boolean array and a tracker. But not sure if it is a scalable solution as a lot of memory needs to be allocated for it.

The idea is to use a LinkedList so that only required nodes are created and not a burden on the memory. We can use Java LinkedList.

Proposed solutions

BitSetPhoneDirectory.java
public class PhoneDirectory {

    BitSet bitset;
    int max; // max limit allowed
    int smallestFreeIndex; // current smallest index of the free bit

    public PhoneDirectory(int maxNumbers) {
        this.bitset = new BitSet(maxNumbers);
        this.max = maxNumbers;
    }

    public int get() {
        // handle bitset fully allocated
        if(smallestFreeIndex == max) {
            return -1;
        }
        int num = smallestFreeIndex;
        bitset.set(smallestFreeIndex);
        //Only scan for the next free bit, from the previously known smallest free index
        smallestFreeIndex = bitset.nextClearBit(smallestFreeIndex);
        return num;
    }

    public boolean check(int number) {
        return bitset.get(number) == false;
    }

    public void release(int number) {
        //handle release of unallocated ones
        if(bitset.get(number) == false)
            return;
        bitset.clear(number);
        if(number < smallestFreeIndex) {
            smallestFreeIndex = number;
        }
    }
}

Solution

Last updated