15% off all plans & roadmaps Use code

See plans

Design Phone Directory

Updated

TL;DR: You must hand out numbers from a fixed range, check whether a number is free, and take back released numbers. The winning idea pairs a counter for never-issued numbers with a stack of released ones. A flag array blocks double releases.

Problem

Your directory holds phone numbers from 0 to maxNumbers - 1. Design a class PhoneDirectory that assigns and recycles these numbers.

The class supports four operations:

  • PhoneDirectory(int maxNumbers) creates a directory with maxNumbers free numbers.
  • int get() assigns a free number and returns it. It returns -1 when no number is free.
  • bool check(int number) returns true if the number is free, and false otherwise.
  • void release(int number) makes an assigned number free again.

Each number belongs to at most one user at a time. A released number can be assigned again. The class must handle up to 2 * 10^4 calls efficiently.

Example 1

Input: commands = ["PhoneDirectory", "get", "get", "get", "get", "check"], arguments = [[2], [], [], [], [], [2]]
Output: [null, 0, 1, -1, -1, false]

Constraints

  • The total number of calls is at most 2 * 10^4.

Constraints that matter

  • The total calls are up to 2 * 10^4, so a call cannot scan the whole directory. Scanning on every call can cost about 4 * 10^8 steps in the worst case.
  • release receives numbers in any order, so the design must record whether each number is assigned. One flag per number answers that in O(1).
  • get must return a free number without searching. Keeping free numbers in a stack or counter turns get into a pop or an increment.
  • A number can be released twice, so release must ignore numbers that are already free. Otherwise the same number enters the free pool twice.

View on LeetCode

Hints

Hint 1

The directory must answer three questions quickly: which number is free, is this number free, and mark this number free.

Hint 2

The beginner version keeps a list of every assigned number.

Solution

Intuition

The directory must answer three questions quickly: which number is free, is this number free, and mark this number free. A flag array answers the second and third in one step each, but finding a free number from it means a search. A stack answers the first in one step, but it cannot tell you the state of a given number. The design combines both, and each part covers the operation it handles best.

It is like a coat check: the counter is the next untouched hook, and the stack is the pile of returned tickets. The flag is the ticket marker that stops one coat from being returned twice.

The free numbers split into two groups. The first group holds numbers that were never handed out, and a counter gives the next one in order. The second group holds numbers that were handed out and then released, and they sit on a stack. Every free number is in exactly one group, so get can always find one in constant time.

The flag array keeps the design correct. release only acts on a number whose flag says it is assigned, so a number enters the stack only after it left. Without the flag, a second release of the same number would push it twice, and two users could receive it.

Watch the pattern animation

Worked example

Input: PhoneDirectory(2), then get(), get(), get(), get(), check(2)
Output: [null, 0, 1, -1, -1, false]
Explanation: The directory holds the numbers 0 and 1. The first two get calls return 0 and then 1, so both numbers are assigned. The third and fourth get calls find nothing free and return -1. Number 2 is outside the directory, so check(2) returns false.

Approach 1: Brute force: list of assigned numbers

The beginner version keeps a list of every assigned number. It answers each question by searching that list. get walks 0, 1, 2 and so on, and returns the first number missing from the list. check and release also search the list, because the list is the only record of who holds which number.

Every answer costs a scan. The list grows with each assignment, so each scan takes longer as the directory fills up.

Steps

  1. Create an empty list assigned and store maxNumbers.
  2. In get, loop i from 0 to maxNumbers - 1. If i is not in assigned, append it and return it.
  3. If the loop finishes without a match, return -1.
  4. In check, return false when the number is out of range. Otherwise return true only when the number is not in assigned.
  5. In release, remove the number from assigned if it is present.

Dry run

Start with assigned = []. The first get tries 0. Zero is not in the list, so assigned becomes [0] and the call returns 0.

The second get tries 0, which is in the list. It tries 1, which is not, so assigned becomes [0, 1] and the call returns 1.

The third get tries 0 and 1. Both are in the list, the loop ends, and the call returns -1. The fourth get does the same and returns -1.

The check(2) call sees that 2 is outside the range 0 to 1, so it returns false. The outputs are 0, 1, -1, -1, false, which matches the expected result.

Complexity

TimeO(M * A) per get, O(A) per check and release
SpaceO(A)

Let M be maxNumbers and A the number of assigned numbers. get tries up to M values, and each membership test scans up to A list entries, so one get costs O(M * A). check and release each scan the list once, which costs O(A). The list holds only assigned numbers, so it uses O(A) space, and A can reach M.

PythonTested in our runner

from typing import List, Optional

class PhoneDirectory:
    def __init__(self, maxNumbers: int):
        self.max_num = maxNumbers
        self.assigned = []

    def get(self) -> int:
        for i in range(self.max_num):
            if i not in self.assigned:
                self.assigned.append(i)
                return i
        return -1

    def check(self, number: int) -> bool:
        return 0 <= number < self.max_num and number not in self.assigned

    def release(self, number: int) -> None:
        if number in self.assigned:
            self.assigned.remove(number)

Approach 2: Boolean array with linear scan

What's slow: check and release still search the list, and get searches it too. The insight: one flag per number records the state directly. check reads one flag, and release writes one flag.

get still has to find a flag that is true, so it scans from index 0. The scan is a plain array read, which removes the list search. It still walks past assigned numbers, so a nearly full directory makes every get slow.

Steps

  1. Create free, an array of maxNumbers booleans, all set to true.
  2. In get, scan from index 0. At the first true flag, set it to false and return its index.
  3. If no flag is true, return -1.
  4. In check, return the flag for the number after a range check.
  5. In release, if the number is in range, set its flag to true. Setting an already free flag to true changes nothing.

Dry run

Start with free = [true, true]. The first get reads index 0, which is true. It sets index 0 to false and returns 0, so free = [false, true].

The second get reads index 0, which is false, and then index 1, which is true. It sets index 1 to false and returns 1, so free = [false, false].

The third get reads both flags, finds no true value, and returns -1. The fourth get does the same. The check(2) call fails the range test and returns false. The outputs are 0, 1, -1, -1, false.

Complexity

TimeO(M) per get, O(1) per check and release
SpaceO(M)

get reads at most M flags, so one call costs O(M) in the worst case. check does one range test and one array read, so it costs O(1). release does one range test and one write, so it costs O(1). The array holds M booleans, which gives O(M) space.

PythonTested in our runner

from typing import List, Optional

class PhoneDirectory:
    def __init__(self, maxNumbers: int):
        self.max_num = maxNumbers
        self.free = [True] * maxNumbers

    def get(self) -> int:
        for i in range(self.max_num):
            if self.free[i]:
                self.free[i] = False
                return i
        return -1

    def check(self, number: int) -> bool:
        return 0 <= number < self.max_num and self.free[number]

    def release(self, number: int) -> None:
        if 0 <= number < self.max_num:
            self.free[number] = True

The Design (General/Specific) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Design (General/Specific)

Part of Design Patterns

Approach 3: Stack of released numbers plus a counterOptimalDesign (General/Specific)

What's slow: get scans the flags from index 0 on every call, and it keeps passing numbers that are assigned. The insight: get never needs to search. The free numbers are the released numbers on a stack, plus every never-issued number at or above a counter.

Both sources give a number in constant time. get pops the stack when it is not empty, and otherwise it takes the counter and increments it. The flag array stays, so release can tell whether a number is really assigned.

Steps

  1. Store maxNumbers, a counter nextNew set to 0, an empty stack recycled, and an array available of maxNumbers true values.
  2. In get, pop from recycled if it is not empty. Otherwise, if nextNew is less than maxNumbers, take nextNew and add one to it. Otherwise return -1.
  3. Set the flag of the chosen number to false, and return it.
  4. In check, return the flag after a range test.
  5. In release, if the number is in range and its flag is false, set the flag to true and push the number onto recycled. Otherwise do nothing.

Dry run

The table shows the state after each call. The directory holds M = 2 numbers.

StepCallnextNewrecycledavailableReturned
0constructor0[][true, true]null
1get1[][false, true]0
2get2[][false, false]1
3get2[][false, false]-1
4get2[][false, false]-1
5check(2)2[][false, false]false

Rows 3 and 4 change nothing, because the stack is empty and the counter has reached 2. Row 5 fails the range test. If release(0) had come before step 3, the stack would hold [0], and step 3 would return 0 instead of -1.

Complexity

TimeO(1) per call, O(M) for the constructor
SpaceO(M)

get does one pop, one counter step, or returns -1, so it runs in constant time. check does one range test and one array read. release does one range test, one flag read, and at most one push, so it is O(1). The constructor fills an array of M values, so setup is O(M). The array and the stack hold at most M numbers, so space is O(M).

PythonTested in our runner

from typing import List, Optional

class PhoneDirectory:
    def __init__(self, maxNumbers: int):
        self.max_num = maxNumbers
        self.next_new = 0          # smallest number never handed out
        self.recycled = []         # stack of released numbers
        self.available = [True] * maxNumbers

    def get(self) -> int:
        if self.recycled:
            number = self.recycled.pop()
        elif self.next_new < self.max_num:
            number = self.next_new
            self.next_new += 1
        else:
            return -1
        self.available[number] = False
        return number

    def check(self, number: int) -> bool:
        return 0 <= number < self.max_num and self.available[number]

    def release(self, number: int) -> None:
        # Only an assigned number can be released, so it never enters the stack twice
        if 0 <= number < self.max_num and not self.available[number]:
            self.available[number] = True
            self.recycled.append(number)

Common mistakes

  • recycled.append(number) in release without checking available[number] first: releasing 5 twice puts 5 on the stack twice, and two later get calls return 5. Push only when the flag says the number is assigned.
  • Forgetting to set available[number] = False in get: a later check reports an assigned number as free. Update the flag in the same step as the pop or the counter increment.
  • if self.next_new < self.max_num missing in get: after all numbers are out, the counter keeps growing and get returns a value outside the range. Compare the counter before you issue a number.
  • self.available[number] read before the range test in Python: a negative number such as -1 wraps to the last element and gives a wrong answer silently. Test 0 <= number < max_num first.
  • Searching the directory for the smallest free number in get: that scan makes each get O(M). The problem does not require any order, so the stack pop is enough.
  • Calling pop or RemoveAt on an empty stack in Java or C#: the call throws. Check that the stack is not empty before taking from it.

Edge cases

  • get on a full directory: after all M numbers are assigned, get returns -1 and changes no state.
  • release of a number that is already free: nothing changes, and the number does not show up twice in later get calls.
  • release of an out-of-range number such as -1 or maxNumbers: the call is ignored, and check on that number returns false.
  • Release then get: the released number comes back before any never-issued number, because the stack is checked first.
  • A directory of size 1: get returns 0, the next get returns -1, and after release(0) the next get returns 0 again.
  • check on a never-issued number: it returns true, since the number is still free.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Design Phone Directory, with how to answer them.

Unlock the follow-ups

Design Phone Directory FAQ

What is the time complexity of Design Phone Directory?

The stack and counter design runs get, check and release in O(1) time each. The constructor takes O(M) time to create the flag array, where M is maxNumbers. The brute force list costs O(M * A) per get, where A is the number of assigned numbers.

Why use a flag array and a stack for Design Phone Directory?

The flag array answers check in one read and guards release against double entries. The stack and counter give get a free number without a search. Each structure covers the operation it handles best, so every call stays constant time.

Can Design Phone Directory be solved in O(1) extra space?

No, not with this design. Releases can return any earlier number, so the directory must remember which numbers are assigned. That record needs up to M entries, so the space is O(M) in the worst case. A hash set of assigned numbers can reduce it to O(A), at the cost of hashing.

Why does the Python version need a range check before reading the flag?

Python lists accept negative indexes and read from the end of the list. A call such as check(-1) would then read the last flag and return a wrong answer without an error. Testing 0 <= number < max_num first avoids that.

Asked at

See which companies ask this — Pro

Practise it