834. Ambiguous Coordinates
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to restore all possible original 2D coordinate strings of the form "(x, y)" from a condensed string s. This string s is formed by taking an original coordinate string, removing the comma, space, and any decimal points, and keeping only the digits and parentheses. For example, "(1, 2.3)" becomes "(123)".
Solution
Ambiguous Coordinates in Python
class Solution:
def ambiguousCoordinates(self, s: str) -> list[str]:
n = len(s)
digits = s[1:n-1]
ans = []
m = len(digits)
# Iterate through all possible split points of the digit string
for i in range(1, m):
left_str = digits[:i]
right_str = digits[i:]
left_parts = self._get_valid_parts(left_str)
right_parts = self._get_valid_parts(right_str)
# If either part has no valid representations, skip
if not left_parts or not right_parts:
continue
# Combine all valid left and right parts
for lp in left_parts:
for rp in right_parts:
ans.append(f"({lp}, {rp})")
return ans
def _get_valid_parts(self, part: str) -> list[str]:
"""Helper function to find all valid number representations of a digit string"""
n = len(part)
res = []
# Case 1: Integer representation
# A number is a valid integer if it doesn't start with '0', or if it's just "0".
if not part.startswith('0') or n == 1:
res.append(part)
# Case 2: Decimal representation
for i in range(1, n):
integer_part = part[:i]
fractional_part = part[i:]
# Check validity of the integer part of the decimal
# It can't have leading zeros if its length is greater than 1.
if integer_part.startswith('0') and len(integer_part) > 1:
continue
# Check validity of the fractional part of the decimal
# It can't end with a '0'.
if fractional_part.endswith('0'):
continue
# If both parts are valid, form the decimal string
res.append(f"{integer_part}.{fractional_part}")
return res
Ambiguous Coordinates in Java
class Solution {
public List<String> ambiguousCoordinates(String s) {
int n = s.length();
String digits = s.substring(1, n - 1);
List<String> ans = new ArrayList<>();
int m = digits.length();
// Iterate through all possible split points of the digit string
for (int i = 1; i < m; i++) {
String leftStr = digits.substring(0, i);
String rightStr = digits.substring(i);
List<String> leftParts = getValidParts(leftStr);
List<String> rightParts = getValidParts(rightStr);
// If either part has no valid representations, skip
if (leftParts.isEmpty() || rightParts.isEmpty()) {
continue;
}
// Combine all valid left and right parts
for (String lp : leftParts) {
for (String rp : rightParts) {
ans.add("(" + lp + ", " + rp + ")");
}
}
}
return ans;
}
// Helper function to find all valid number representations of a digit string
private List<String> getValidParts(String part) {
int n = part.length();
List<String> res = new ArrayList<>();
// Case 1: Integer representation
// A number is a valid integer if it doesn't start with '0', or if it's just "0".
if (!part.startsWith("0") || n == 1) {
res.add(part);
}
// Case 2: Decimal representation
for (int i = 1; i < n; i++) {
String integerPart = part.substring(0, i);
String fractionalPart = part.substring(i);
// Check validity of the integer part of the decimal
// It can't have leading zeros if its length is greater than 1.
if (integerPart.length() > 1 && integerPart.startsWith("0")) {
continue;
}
// Check validity of the fractional part of the decimal
// It can't end with a '0'.
if (fractionalPart.endsWith("0")) {
continue;
}
// If both parts are valid, form the decimal string
res.add(integerPart + "." + fractionalPart);
}
return res;
}
}
Ambiguous Coordinates in C++
class Solution {
public:
vector<string> ambiguousCoordinates(string s) {
int n = s.length();
string digits = s.substr(1, n - 2);
vector<string> ans;
int m = digits.length();
// Iterate through all possible split points of the digit string
for (int i = 1; i < m; ++i) {
string leftStr = digits.substr(0, i);
string rightStr = digits.substr(i);
vector<string> leftParts = getValidParts(leftStr);
vector<string> rightParts = getValidParts(rightStr);
// If either part has no valid representations, skip
if (leftParts.empty() || rightParts.empty()) {
continue;
}
// Combine all valid left and right parts
for (const string& lp : leftParts) {
for (const string& rp : rightParts) {
ans.push_back("(" + lp + ", " + rp + ")");
}
}
}
return ans;
}
private:
// Helper function to find all valid number representations of a digit string
vector<string> getValidParts(const string& part) {
int n = part.length();
vector<string> res;
// Case 1: Integer representation
// A number is a valid integer if it doesn't start with '0', or if it's just "0".
if (part[0] != '0' || n == 1) {
res.push_back(part);
}
// Case 2: Decimal representation
for (int i = 1; i < n; ++i) {
string integerPart = part.substr(0, i);
string fractionalPart = part.substr(i);
// Check validity of the integer part of the decimal
// It can't have leading zeros if its length is greater than 1.
if (integerPart.length() > 1 && integerPart[0] == '0') {
continue;
}
// Check validity of the fractional part of the decimal
// It can't end with a '0'.
if (fractionalPart.back() == '0') {
continue;
}
// If both parts are valid, form the decimal string
res.push_back(integerPart + "." + fractionalPart);
}
return res;
}
};
Ambiguous Coordinates in TypeScript
function ambiguousCoordinates(s: string): string[] {
const n = s.length;
const digits = s.substring(1, n - 1);
const ans: string[] = [];
const m = digits.length;
// Helper function to find all valid number representations of a digit string
const getValidParts = (part: string): string[] => {
const n_part = part.length;
const res: string[] = [];
// Case 1: Integer representation
// A number is a valid integer if it doesn't start with '0', or if it's just "0".
if (!part.startsWith('0') || n_part === 1) {
res.push(part);
}
// Case 2: Decimal representation
for (let i = 1; i < n_part; i++) {
const integerPart = part.substring(0, i);
const fractionalPart = part.substring(i);
// Check validity of the integer part of the decimal
// It can't have leading zeros if its length is greater than 1.
if (integerPart.startsWith('0') && integerPart.length > 1) {
continue;
}
// Check validity of the fractional part of the decimal
// It can't end with a '0'.
if (fractionalPart.endsWith('0')) {
continue;
}
// If both parts are valid, form the decimal string
res.push(`${integerPart}.${fractionalPart}`);
}
return res;
};
// Iterate through all possible split points of the digit string
for (let i = 1; i < m; i++) {
const leftStr = digits.substring(0, i);
const rightStr = digits.substring(i);
const leftParts = getValidParts(leftStr);
const rightParts = getValidParts(rightStr);
// If either part has no valid representations, skip
if (leftParts.length === 0 || rightParts.length === 0) {
continue;
}
// Combine all valid left and right parts
for (const lp of leftParts) {
for (const rp of rightParts) {
ans.push(`(${lp}, ${rp})`);
}
}
}
return ans;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.