Torna alle sfide
Facile 0 risolte 0% di accettazione

One Shared Configuration

Simulate a singleton settings object: every part of the program reads and writes the same instance.

Cosa imparerai

  • Share one object across the whole program
  • Create an instance lazily on first use
  • Read and update settings through one place

Problema

Mostra traduzione

The singleton pattern makes sure a class has exactly one instance that everyone shares, a common choice for application settings.

Simulate one shared configuration that starts empty. Process the operations in order:

  • set <key> <value>: store the value for the key (replacing any old value).
  • get <key>: read the key's current value, or missing if it was never set.

Because every caller uses the same instance, a value set by one operation is visible to every later get.

Implement shared_configuration(operations).

Input

operations: Strings in the two forms above. Keys and values contain no spaces.

Output

Return the results of the get operations, in order.

Vincoli

1 ≤ number of operations ≤ 10,000

Keys and values have 1 to 20 characters

Esempi

Esempio 1
Input:
operations = ["set theme dark", "get theme", "get language"]

Output atteso:
expected = ["dark", "missing"]
Input:
std::vector<std::string> operations = {"set theme dark", "get theme", "get language"};

Output atteso:
std::vector<std::string> expected = {"dark", "missing"};
Input:
string[] operations = new string[] {"set theme dark", "get theme", "get language"};

Output atteso:
string[] expected = new string[] {"dark", "missing"};

Spiegazione

theme was set to dark; language was never set, so it is missing: ["dark", "missing"].

Esempio 2
Input:
operations = ["set lang en", "set lang vi", "get lang"]

Output atteso:
expected = ["vi"]
Input:
std::vector<std::string> operations = {"set lang en", "set lang vi", "get lang"};

Output atteso:
std::vector<std::string> expected = {"vi"};
Input:
string[] operations = new string[] {"set lang en", "set lang vi", "get lang"};

Output atteso:
string[] expected = new string[] {"vi"};

Spiegazione

The second set replaces the first value in the same shared instance: ["vi"].

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

All operations read and write the same single object.

Suggerimento 2

A dictionary from key to value is enough to hold the settings.

Suggerimento 3

A key that was never set must return the text missing.

Complessità attesa

O(number of operations) time, O(number of keys) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.