Design Phone Directory - CPP Solution

1. Introduction

In this blog post, we will design a data structure to model a simple phone directory. The directory should efficiently assign and recycle phone numbers.

Problem

Design a phone directory system that can:

1. Assign an available phone number to a user.

2. Check if a specific number is available.

3. Release a number, making it available again.

The system should support up to maxNumbers phone numbers, starting from 0.

2. Solution Steps

1. Use a set to keep track of available numbers.

2. When assigning a number, remove it from the available numbers set.

3. For releasing a number, add it back to the set.

4. Ensure all operations have efficient time complexity.

3. Code Program

#include <iostream>
#include <set>
using namespace std;

class PhoneDirectory {
    set<int> availableNumbers;

public:
    PhoneDirectory(int maxNumbers) {
        for (int i = 0; i < maxNumbers; i++) {
            availableNumbers.insert(i);
        }
    }

    // Assign a number which is not assigned to anyone.
    int get() {
        if (availableNumbers.empty()) return -1;
        int number = *availableNumbers.begin();
        availableNumbers.erase(number);
        return number;
    }

    // Check if a number is available or not.
    bool check(int number) {
        return availableNumbers.find(number) != availableNumbers.end();
    }

    // Recycle or release a number.
    void release(int number) {
        availableNumbers.insert(number);
    }
};

// Function to demonstrate the usage of the PhoneDirectory
void testPhoneDirectory() {
    PhoneDirectory directory(3);
    cout << "Assigned Number: " << directory.get() << endl; // Should assign first available number
    cout << "Is Number 2 available? " << (directory.check(2) ? "Yes" : "No") << endl;
    directory.release(0); // Release a number
    cout << "Is Number 0 available after release? " << (directory.check(0) ? "Yes" : "No") << endl;
}

int main() {
    testPhoneDirectory();
    return 0;
}

Output:

Assigned Number: 0
Is Number 2 available? Yes
Is Number 0 available after release? Yes

Explanation:

The PhoneDirectory class uses a set to keep track of available numbers. The get method assigns an available number and removes it from the set, the check method verifies if a number is available, and the release method adds a number back to the set, making it available again. 

This design ensures efficient operations for assigning, checking, and releasing phone numbers, suitable for a basic phone directory system.


Comments