Leetcode 816. Ambiguous Coordinates Certainly! Let’s break it down step-by-step.
You are given a string representing coordinates. The string will be in the format "(x, y)"
. You need to return a list of all possible valid coordinates that can be formed by inserting commas and ensuring no leading zeroes (unless the number is “0”). For example, strings like "0001"
can only produce the coordinates [0, 0.001]
as 0.001
is the only valid decimal configuration without leading awkward zeroes.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> generateValidNumbers(string s) {
vector<string> result;
if (s.empty()) return result;
if (s[0] == '0' && s.size() > 1) {
// If the string starts with '0' and its length is > 1
// it must be "0.xxxx" format to be valid
if (s[s.size() - 1] != '0') {
result.push_back("0." + s.substr(1));
}
} else {
result.push_back(s); // whole number case
for (int i = 1; i < s.size(); ++i) {
// add the decimal point at position i
string left = s.substr(0, i);
string right = s.substr(i);
if (right.back() != '0') { // no trailing zeroes in fractional part
result.push_back(left + "." + right);
}
}
}
return result;
}
vector<string> ambiguousCoordinates(string s) {
vector<string> result;
// Remove the outer parentheses
s = s.substr(1, s.size()-2);
for (int i = 1; i < s.size(); ++i) {
string left = s.substr(0, i);
string right = s.substr(i);
vector<string> leftParts = generateValidNumbers(left);
vector<string> rightParts = generateValidNumbers(right);
for (string& l : leftParts) {
for (string& r : rightParts) {
result.push_back("(" + l + ", " + r + ")");
}
}
}
return result;
}
// Main function for testing
int main() {
string input = "(123)";
vector<string> coordinates = ambiguousCoordinates(input);
for (string& coord : coordinates) {
cout << coord << endl;
}
// Test for other cases
vector<string> testCases = {"(0123)", "(100)", "(00011)", "(0010)"};
for (const string& testCase : testCases) {
vector<string> coordinates = ambiguousCoordinates(testCase);
cout << "Coordinates for " << testCase << ":" << endl;
for (const string& coord : coordinates) {
cout << coord << endl;
}
cout << endl;
}
return 0;
}
n
, generating possible valid numbers involves O(n)
operations.n-1
possible valid numbers for each string.left
and right
parts, each with length up to n
.O(n^2)
, considering generating valid parts and nesting loops.Therefore, the time complexity is O(n^3)
due to the nested operations involved in combining valid numbers. The space complexity is also similar in the worst case.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?