Problem 816

Abstract / Summary

Describe all possible coordinate points that match a given ambiguous coordinate pattern.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0816.py

class Solution:
    def ambiguousCoordinates(self, s: str) -> List[str]:
        # remove brackets
        s = s[1:-1]

        # return list of possible numbers (as strings)
        def versions(text):
            if not text:
                return []

            if len(text) == 1:
                return [ text ]

            if text[-1] == "0":
                # must be an integer
                return [] if text[0] == "0" else [ text ]

            if text[0] == "0":
                # must be floating-point
                return [ "0." + text[1:] ]

            result = [ text ]
            # place dots
            for i in range(1, len(text)):
                result.append(text[:i] + "." + text[i:])
            return result

        for i in range(1, len(s)):
            one = versions(s[:i])
            two = versions(s[i:])
            for o in one:
                for t in two:
                    yield "(" + o + ", " + t + ")"
33 lines | 987 bytes | submitted December 19, 2023 | GitHub   22% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 56% (60k+ submissions).

Typical patterns to solve this problem:
  • Backtracking
  • Enumeration
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single public method ambiguousCoordinates. The method receives a string representation of a coordinate pair surrounded by parentheses, for example "(123)", and returns an iterator that yields every valid way to insert a decimal point in each of the two numbers after splitting the interior string at any possible position. The core logic is divided into three conceptual stages: preprocessing the input, generating all numeric representations for a substring, and combining the left- and right-hand side versions into coordinate strings.

Preprocessing the Input

The first operation strips the outer parentheses so that the subsequent logic works with a plain numeric string.

s = s[1:-1]

By removing the first and last characters, the method isolates the characters that can be partitioned into the two coordinate components.

Generating Numeric Versions

A nested helper function versions encapsulates the rules for turning a raw digit sequence into all permissible numeric strings. The function returns a list of strings, each representing a distinct way to interpret the substring as either an integer or a floating-point number.

Handling Empty and Single-Character Substrings

If the substring is empty, the function returns an empty list, effectively discarding any split that would produce an empty component. When the substring consists of a single digit, the only valid representation is the digit itself.

if not text:
    return []

if len(text) == 1:
    return [text]

Trailing Zero Constraint

When the last character of the substring is '0', the only acceptable representation is an integer without a decimal point, because a trailing zero after a decimal point would be ambiguous (e.g., "1.0" is not allowed by the problem’s rules). The code therefore returns an empty list if the substring also begins with '0' (which would create a leading zero integer like "00"), otherwise it returns the integer form.

if text[-1] == "0":
    # must be an integer
    return [] if text[0] == "0" else [text]

Leading Zero Constraint

If the substring starts with '0' but does not end with '0', the only legal representation is a fractional number that begins with "0.". This prevents numbers such as "01" or "00.5" from being generated.

if text[0] == "0":
    # must be floating-point
    return ["0." + text[1:]]

General Case - Integer and Decimal Insertion

When neither the leading nor trailing zero restrictions apply, the substring can be used as a plain integer, and additionally any placement of a single decimal point between characters yields a valid floating-point representation. The loop iterates over all possible split positions, constructing strings of the form prefix + "." + suffix.

result = [text]
# place dots
for i in range(1, len(text)):
    result.append(text[:i] + "." + text[i:])
return result

Combining Left and Right Versions

The outer loop iterates over every possible split position i that separates the stripped string into a left part s[:i] and a right part s[i:]. For each side, the versions function is invoked to obtain all legal numeric strings. Nested iteration over the two version lists produces every combination, and each pair is formatted as a coordinate string using the required parentheses and comma spacing.

for i in range(1, len(s)):
    one = versions(s[:i])
    two = versions(s[i:])
    for o in one:
        for t in two:
            yield "(" + o + ", " + t + ")"

The use of yield turns the method into a generator, allowing callers to consume results lazily without allocating a full list of coordinates up front.

Edge Cases Handled

The implementation explicitly addresses several edge conditions that could otherwise produce invalid coordinates:

  • An empty substring after a split is rejected because versions returns an empty list for text == "". This prevents coordinates like "(,123)" or "(123,)".
  • Substrings consisting of a single digit are always accepted, covering the minimal valid numbers such as "0" or "5".
  • Substrings ending with '0' are only accepted as whole integers, eliminating forms like "1.0" or "10.00" that would introduce unnecessary trailing zeros after a decimal point.
  • Substrings beginning with '0' are forced into the "0.xxx" format, ensuring that numbers like "01" or "00" are not produced, while still allowing "0.1" and "0.12" when appropriate.
  • The combination logic skips any split where either side yields no versions, effectively pruning impossible coordinate constructions early.

Performance Optimizations

The code incorporates a few design choices that reduce unnecessary work:

  • Early returns in versions avoid constructing lists when the substring length is zero or one, cutting down on loop overhead for trivial cases.
  • The check for a trailing zero short-circuits the generation of decimal variants, preventing the inner loop that would otherwise iterate over all possible dot positions.
  • The leading zero branch returns a single pre-computed string, bypassing the need for the decimal insertion loop.
  • By yielding results directly, the method avoids building an intermediate collection of all coordinate strings. This generator-based approach reduces memory pressure, especially when the caller only needs a subset of the possible coordinates or processes them incrementally.
  • The outer split loop runs only up to len(s) - 1, ensuring that each split produces non-empty left and right parts, which eliminates a class of invalid splits without extra condition checks inside the inner loops.
written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long string of numbers wrapped in little parentheses, like a secret code. First, the code throws away the parentheses so it can focus on the numbers sitting inside. It wants to find every way to turn those numbers into coordinate pairs, which look like x and y positions on a map.

The helper part of the code looks at a block of digits and tries to decide where to put a decimal point. It follows a few special rules. If the block is just one number, it stays the same. If it starts with a zero, the only way it can be a valid number is if the decimal point comes right after that first zero. If it ends in a zero, it cannot have a decimal point anywhere unless it is a whole number, because trailing zeros make things messy. Otherwise, the code tries sticking a decimal point in every possible spot between the digits to see what happens.

After the code figures out all the possible ways to turn the left side into numbers and the right side into numbers, it goes through them one by one. It pairs every possible left number with every possible right number and puts the parentheses back around them. This creates a big list of potential coordinate locations, showing every single path the numbers could take to form a pair.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.62 | σ = 1.92

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
halfrost Go
JoshCrozier JS
lkwq007 Python
ruoru Rust
suxrobGM C#
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
ruoru Rust
suxrobGM C#
wisdompeak C++
zfang399 C++
27 links | 14 authors | 8 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

11 solutions   December 19, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality