#816
Ambiguous Coordinates
MediumStringBacktrackingEnumeration
Approaches
💡
Intuition
Time Space
The brute-force approach generates all possible splits of the string into two parts for the x and y coordinates. It checks each split to see if the resulting numbers are valid according to the problem constraints.
⚙️
Algorithm
5 steps- 1Step 1: Remove the parentheses from the input string.
- 2Step 2: Iterate through all possible split points in the string to divide it into two parts for x and y coordinates.
- 3Step 3: For each split, generate all valid combinations of x and y by adding a decimal point where applicable.
- 4Step 4: Validate each combination to ensure it adheres to the rules (e.g., no leading zeros).
- 5Step 5: Collect all valid combinations into a result list.
solution.py30 lines
1# Full working Python code
2from typing import List
3
4def ambiguousCoordinates(s: str) -> List[str]:
5 s = s[1:-1] # Remove parentheses
6 result = []
7 for i in range(1, len(s)):
8 x_part = s[:i]
9 y_part = s[i:]
10 for x in generate_valid_numbers(x_part):
11 for y in generate_valid_numbers(y_part):
12 result.append(f'({x}, {y}')
13 return result
14
15def generate_valid_numbers(part: str) -> List[str]:
16 valid_numbers = []
17 n = len(part)
18 if n == 0:
19 return valid_numbers
20 if part == '0':
21 valid_numbers.append('0')
22 return valid_numbers
23 if part[0] != '0':
24 valid_numbers.append(part)
25 for i in range(1, n):
26 left = part[:i]
27 right = part[i:]
28 if right and right[-1] != '0':
29 valid_numbers.append(left + '.' + right)
30 return valid_numbersSolutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.