Drill

ProblemsC++ › validation

Which required fields are missing

mediumvalidationHash mapsArraysC++

A form submission arrives as a bag of strings and the server checks it before touching the database.

missingFields(payload: map<string, string>, required: list<string>) → list<string>

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

std::vector<std::string> missingFields(std::map<std::string, std::string> payload, std::vector<std::string> required) {
    
}

Worked examples

CallResult
missingFields(std::map<std::string, std::string>{{std::string("name"), std::string("Ada")}, {std::string("email"), std::string("")}}, std::vector<std::string>{std::string("name"), std::string("email"), std::string("phone")})std::vector<std::string>{std::string("email"), std::string("phone")}
missingFields(std::map<std::string, std::string>{{std::string("name"), std::string(" ")}}, std::vector<std::string>{std::string("name")})std::vector<std::string>{std::string("name")}
missingFields(std::map<std::string, std::string>{{std::string("name"), std::string("Ada")}}, std::vector<std::string>{std::string("name")})std::vector<std::string>{}
missingFields(std::map<std::string, std::string>{}, std::vector<std::string>{})std::vector<std::string>{}

Hint

Walk the requirements, not the payload — that is what fixes the output order.

Reference solution in C++
std::vector<std::string> missingFields(std::map<std::string, std::string> payload, std::vector<std::string> required) {
    std::vector<string> result;
    for (const auto& key : required) {
        auto it = payload.find(key);
        if (it == payload.end()) { result.push_back(key); continue; }
        string v = it->second;
        size_t a = v.find_first_not_of(" \t\n\r");
        if (a == string::npos) result.push_back(key);
    }
    return result;
}

The same problem in another language

More validation problems in C++