Drill

ProblemsC++ › validation

Compare two version strings

hardvalidationParsingStringsArraysC++

A deploy tool decides whether the version on the server is behind the one being released.

compareVersions(first: string, second: string) → int

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

int compareVersions(std::string first, std::string second) {
    
}

Worked examples

CallResult
compareVersions(std::string("1.2.10"), std::string("1.10.2"))-1
compareVersions(std::string("1.2"), std::string("1.2.0"))0
compareVersions(std::string("2.0"), std::string("1.9.9"))1
compareVersions(std::string("1.0.0"), std::string("1.0.0"))0

Hint

Walk both to the length of the longer one, reading a missing part as zero.

Reference solution in C++
int compareVersions(std::string first, std::string second) {
    auto parts = [](const string& s) {
        std::vector<int> out;
        string cur;
        for (char c : s) {
            if (c == '.') { out.push_back(cur.empty() ? 0 : std::stoi(cur)); cur.clear(); }
            else cur += c;
        }
        out.push_back(cur.empty() ? 0 : std::stoi(cur));
        return out;
    };
    auto a = parts(first), b = parts(second);
    size_t n = std::max(a.size(), b.size());
    for (size_t i = 0; i < n; i++) {
        int x = i < a.size() ? a[i] : 0;
        int y = i < b.size() ? b[i] : 0;
        if (x != y) return x < y ? -1 : 1;
    }
    return 0;
}

The same problem in another language

More validation problems in C++