Ambiguous Coordinates | JS, Python, Java, C++ | Easy Iterative Solution w/ Explanation
(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, please upvote this post.)\n\n---\n\n#### Idea:\n
*(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nFor this problem, we have two basic challenges. The first challenge is preventing invalid coordinates. For that, we can define a helper function (**parse**) which will take a string (**str**) and only pass on valid options for another helper (**process**) to handle.\n\nWe can break down the options into three categories:\n - _No decimal_: Any option except one with more than **1** digit and a leading **"0"**.\n - _Decimal after first digit_: Any option with more than **1** digit and no trailing **"0"**.\n - _Decimals throughout_: Any option that doesn\'t start and end with a **"0"**\n\nAfter defining our first 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**).\n\nThen 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.\n\nWhat we actually want is the product of two loops. The basic solution would be to create two arrays and iterate through their combinations, but there\'s really no need to actually build the second array, since we can just as easily process the combinations while we iterate through the second coordinate naturally.\n\nSo 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.\n\nTo aid in this, we can define **process**, which will either store the valid decimal options from **xStr** into **xPoss** or combine valid decimal options from **yStr** with the contents of **xPoss** and store the results in **ans**, depending on which coordinate string we\'re currently on (**xy**).\n\nOnce we finish iterating through all comma positions, we can **return ans**.\n\n---\n\n#### ***Javascript Code:***\n\nThe best result for the code below is **76ms / 42.3MB** (beats 100% / 100%).\n```javascript\nvar ambiguousCoordinates = function(S) {\n    let ans = [], xPoss\n    const process = (str, xy) => {\n        if (xy)\n            for (let x of xPoss)\n                ans.push(`(${x}, ${str})`)\n        else xPoss.push(str)\n    }\n    const parse = (str, xy) => {\n        if (str.length === 1 || str[0] !== "0")\n            process(str, xy)\n        if (str.length > 1 && str[str.length-1] !== "0")\n            process(str.slice(0,1) + "." + str.slice(1), xy)\n        if (str.length > 2 && str[0] !== "0" && str[str.length-1] !== "0")\n            for (let i = 2; i < str.length; i++)\n                process(str.slice(0,i) + "." + str.slice(i), xy)\n    }\n    for (let i = 2; i < S.length - 1; i++) {\n        let strs = [S.slice(1,i), S.slice(i, S.length - 1)]\n        xPoss = []\n        for (let j = 0; j < 2; j++)\n            if (xPoss.length || !j) parse(strs[j], j)\n    }\n    return ans\n};\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **32ms / 14.1MB** (beats 99% / 92%).\n```python\nclass Solution:\n    def ambiguousCoordinates(self, S: str) -> List[str]:\n        ans, xPoss = [], []\n        def process(st: str, xy: int):\n            if xy:\n                for x in xPoss:\n                    ans.append("(" + x + ", " + st + ")")\n            else: xPoss.append(st)\n        def parse(st: str, xy: int):\n            if len(st) == 1 or st[0] != "0":\n                process(st, xy)\n            if len(st) > 1 and st[-1] != "0":\n                process(st[:1] + "." + st[1:], xy)\n            if len(st) > 2 and st[0] != "0" and st[-1] != "0":\n                for i in range(2, len(st)):\n                    process(st[:i] + "." + st[i:], xy)  \n        for i in range(2, len(S)-1):\n            strs, xPoss = [S[1:i], S[i:-1]], []\n            for j in range(2):\n                if xPoss or not j: parse(strs[j], j)\n        return ans\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **7ms / 39.5MB** (beats 100% / 91%).\n```java\nclass Solution {\n    private List<String> xPoss, ans;\n    public List<String> ambiguousCoordinates(String S) {\n        ans = new ArrayList<>();\n        for (int i = 2; i < S.length() - 1; i++) {\n            String[] strs = {S.substring(1,i), S.substring(i, S.length() - 1)};\n            xPoss = new ArrayList<>();\n            for (int j = 0; j < 2; j++)\n                if (xPoss.size() > 0 || j == 0) parse(strs[j], j);\n        }\n        return ans;\n    }\n    private void parse(String str, int xy) {\n        if (str.length() == 1 || str.charAt(0) != \'0\')\n            process(str, xy);\n        if (str.length() > 1 && str.charAt(str.length()-1) != \'0\')\n            process(str.substring(0,1) + "." + str.substring(1), xy);\n        if (str.length() > 2 && str.charAt(0) != \'0\' && str.charAt(str.length()-1) != \'0\')\n            for (int i = 2; i < str.length(); i++)\n                process(str.substring(0,i) + "." + str.substring(i), xy);\n    }\n    private void process(String str, int xy) {\n        if (xy > 0)\n            for (String x : xPoss)\n                ans.add("(" + x + ", " + str + ")");\n        else xPoss.add(str);\n    }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **0ms / 9.1MB** (beats 100% / 95%).\n```c++\nclass Solution {\npublic:\n    vector<string> ambiguousCoordinates(string S) {\n        for (int i = 2; i < S.size() - 1; i++) {\n            string strs[2] = {S.substr(1,i-1), S.substr(i,S.size()-i-1)};\n            xPoss.clear();\n            for (int j = 0; j < 2; j++)\n                if (xPoss.size() || !j) parse(strs[j], j);\n        }\n        return ans;\n    }\nprivate:\n    vector<string> ans, xPoss;\n    void parse(string str, int xy) {\n        if (str.size() == 1 || str.front() != \'0\')\n            process(str, xy);\n        if (str.size() > 1 && str.back() != \'0\')\n            process(str.substr(0,1) + "." + str.substr(1), xy);\n        if (str.size() > 2 && str.front() != \'0\' && str.back() != \'0\')\n            for (int i = 2; i < str.size(); i++)\n                process(str.substr(0,i) + "." + str.substr(i), xy);\n    }\n    void process(string str, int xy) {\n        if (xy)\n            for (auto x : xPoss)\n                ans.push_back("(" + x + ", " + str + ")");\n        else xPoss.push_back(str);\n    }\n};\n```
[]