816. Ambiguous Coordinates

Description

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 string s. 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.)

Constraints

  • 4 <= s.length <= 12.

  • s[0] = "(", s[s.length - 1] = ")", and the other elements in s are digits.

Approach

  • GeeksforGeeks

  • ProgramCreek

  • YouTube

Examples

Input: s = "(123)"

Output: ["(1, 23)", "(12, 3)", "(1.2, 3)", "(1, 2.3)"]

Solutions

/**
 * Time complexity : O(N^3), where N is the length S. 
 *    We evaluate the sum O(∑k(N−k)).
 * Space complexity : O(N^3), to store the answer.
 */

class Solution {
    public List<String> ambiguousCoordinates(String s) {
        List<String> result = new ArrayList();
        if(s != null && s.length() != 0) {
            int n = s.length();
            for(int i = 2; i < n-1; i++) {
                for(String x: getCoordinates(s, 1, i)) {
                    for(String y: getCoordinates(s, i, n-1)) {
                        result.add("(" + x + ", " + y + ")");
                    }
                }
            }
        }
        return result;
    }
    
    private List<String> getCoordinates(String s, int i, int j) {
        List<String> list = new ArrayList();
        for(int d = 1; d <= j-i; d++) {
            String left = s.substring(i, i+d);
            String right = s.substring(i+d, j);
            if((!left.startsWith("0") || left.equals("0")) && 
                    !right.endsWith("0")) {
                list.add(left + (d < j-i ? ".": "") + right);
            }
        }
        return list;
    }
}

Follow up

Last updated

Was this helpful?