2dbi

Extract unique numbers from strings

viaLeetCode

Problem Each input string contains zero or more embedded numbers (possibly with '-'/'+' signs adjacent, e.g. ["lksmdf-983kjasd78asdkn78", "-234klnsdf+345kmsdf234"]). Extract all numbers across the strings, deduplicated, and return them as integers.

Input / Output

  • Input: list of strings.
  • Output: list of unique integers.

Constraints

  • Clarify: do signs belong to the number (-983 vs 983)? Output order (first-seen vs sorted)? Values exceeding int range?

Example

  • ["a12b12", "-3c"] → sign-aware: [12, -3]; digits-only: [12, 3].

Expected approach

  • Scan each string once: accumulate digit runs (optionally capturing a preceding sign), parse each run, insert into a LinkedHashSet (dedupe + stable order) — O(total chars). Regex -?\d+ with a set is the concise alternative. The interview substance is the clarifying questions (signs, duplicates across vs within strings, overflow) and clean parsing code.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account