This content originally appeared on DEV Community and was authored by seanpgallivan
This is part of a series of Leetcode solution explanations (index). If you liked this solution or found it useful, please like this post and/or upvote my solution post on Leetcode's forums.
Leetcode Problem #816 (Medium): Ambiguous Coordinates
Description:
(Jump to: Solution Idea || Code: JavaScript | Python | Java | C++)
We had some 2-dimensional coordinates, like
"(1, 3)"
or"(2, 0.5)"
. Then, we removed all commas, decimal points, and spaces, and ended up with the strings
. Return a list of strings representing all possibilities for what our original coordinates could have been.Our original representation never had extraneous zeroes, so we never started with numbers like
"00"
,"0.0"
,"0.00"
,"1.0"
,"001"
,"00.01"
, or any other number that can be represented with less digits. Also, a decimal point within a number never occurs without at least one digit occuring before it, so we never started with numbers like".1"
.The final answer list can be returned in any order. Also note that all coordinates in the final answer have exactly one space between them (occurring after the comma.)
Examples:
Example 1: Input: s = "(123)" Output: ["(1, 23)", "(12, 3)", "(1.2, 3)", "(1, 2.3)"]
Example 2: Input: s = "(00011)" Output: ["(0.001, 1)", "(0, 0.011)"] Explanation: 0.0, 00, 0001 or 00.01 are not allowed.
Example 3: Input: s = "(0123)" Output: ["(0, 123)", "(0, 12.3)", "(0, 1.23)", "(0.1, 23)", "(0.1, 2.3)", "(0.12, 3)"]
Example 4: Input: s = "(100)" Output: [(10, 0)] Explanation: 1.0 is not allowed.
Constraints:
4 <= s.length <= 12
s[0] = "("
,s[s.length - 1] = ")"
, and the other elements ins
are digits.
Idea:
(Jump to: Problem Description || Code: JavaScript | Python | Java | C++)
For this problem, we have two basic challenges. The first challenge is preventing invalid coordinates. For that, we can define a helper function (isValid) which will take a string (str) and a decimal location (dec). A value of 0 for dec will mean that there is no decimal.
The resulting number will be invalid if:
- The string ends with a "0", unless there is no decimal.
- The string starts with a "0", unless the entire string is just "0" or the decimal is right after the initial "0".
After defining our helper function, the next thing we should do is iterate through possible comma locations in our input string (S) and separate the coordinate pair strings (xStr, yStr).
Then we'll run into the second challenge, which is to avoid repeating the same processing. If we were to employ a simple nested loop or recursive function to solve this problem, it would end up redoing the same processes many times, since both coordinates can have a decimal.
What we actually want is the product of two loops, so we should first build and validate all decimal options for the xStr of a given comma position and store the valid possibilities in an array (xPoss). Once this is complete we should find each valid decimal option for yStr, combine it with each value in xPoss, and add the results to our answer array (ans) before moving onto the next comma position.
Once we finish iterating through all comma positions, we can return ans.
Javascript Code:
(Jump to: Problem Description || Solution Idea)
var ambiguousCoordinates = function(S) {
let ans = []
const isValid = (str, dec) => {
let n = str.length
if (dec && str[n-1] === "0") return false
if (n !== 1 && dec !== 1 && str[0] === "0") return false
return true
}
for (let i = 2; i < S.length - 1; i++) {
let xStr = S.slice(1,i), yStr = S.slice(i, S.length - 1),
xPoss = []
for (let j = 0; j < xStr.length; j++)
if (isValid(xStr, j))
xPoss.push(xStr.slice(0,j) + (j ? "." : "") + xStr.slice(j))
for (let j = 0; j < yStr.length; j++)
if (isValid(yStr, j)) {
let y = yStr.slice(0,j) + (j ? "." : "") + yStr.slice(j)
for (let x of xPoss)
ans.push(`(${x}, ${y})`)
}
}
return ans
};
Python Code:
(Jump to: Problem Description || Solution Idea)
class Solution:
def ambiguousCoordinates(self, S: str) -> List[str]:
ans = []
def isValid(st: str, dec: int) -> bool:
if dec and st[-1] == "0": return False
if len(st) != 1 and dec != 1 and st[0] == "0": return False
return True
for i in range(2, len(S)-1):
xStr, yStr = S[1:i], S[i:-1]
xPoss = []
for j in range(len(xStr)):
if isValid(xStr, j):
xPoss.append(xStr[:j] + ("." if j else "") + xStr[j:])
for j in range(len(yStr)):
if isValid(yStr, j):
y = yStr[:j] + ("." if j else "") + yStr[j:]
for x in xPoss:
ans.append("(" + x + ", " + y + ")")
return ans
Java Code:
(Jump to: Problem Description || Solution Idea)
class Solution {
public List<String> ambiguousCoordinates(String S) {
List<String> ans = new ArrayList<>();
for (int i = 2; i < S.length() - 1; i++) {
String xStr = S.substring(1,i), yStr = S.substring(i, S.length() - 1);
List<String> xPoss = new ArrayList<>();
for (int j = 0; j < xStr.length(); j++)
if (isValid(xStr, j))
xPoss.add(xStr.substring(0,j) + (j > 0 ? "." : "") + xStr.substring(j));
for (int j = 0; j < yStr.length(); j++)
if (isValid(yStr, j)) {
String y = yStr.substring(0,j) + (j > 0 ? "." : "") + yStr.substring(j);
for (String x : xPoss)
ans.add("(" + x + ", " + y + ")");
}
}
return ans;
}
public boolean isValid(String str, int dec) {
if (dec != 0 && str.charAt(str.length()-1) == '0') return false;
if (str.length() != 1 && dec != 1 && str.charAt(0) == '0') return false;
return true;
}
}
C++ Code:
(Jump to: Problem Description || Solution Idea)
class Solution {
public:
vector<string> ambiguousCoordinates(string S) {
vector<string> ans;
for (int i = 2; i < S.size() - 1; i++) {
string xStr = S.substr(1,i-1), yStr = S.substr(i, S.size() - 1 - i);
vector<string> xPoss;
for (int j = 0; j < xStr.size(); j++)
if (isValid(xStr, j))
xPoss.push_back(xStr.substr(0,j) + (j ? "." : "") + xStr.substr(j));
for (int j = 0; j < yStr.size(); j++)
if (isValid(yStr, j)) {
string y = yStr.substr(0,j) + (j ? "." : "") + yStr.substr(j);
for (auto x : xPoss)
ans.push_back("(" + x + ", " + y + ")");
}
}
return ans;
}
bool isValid(string str, int dec) {
if (dec && str[str.size()-1] == '0') return false;
if (str.size() != 1 && dec != 1 && str[0] == '0') return false;
return true;
}
};
This content originally appeared on DEV Community and was authored by seanpgallivan
seanpgallivan | Sciencx (2021-05-13T13:36:59+00:00) Solution: Ambiguous Coordinates. Retrieved from https://www.scien.cx/2021/05/13/solution-ambiguous-coordinates/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.