Validate Palindrome Rearrangements and Sum High-Precision Decimals
StringsModel answerLast updated
Check if a string's characters can form a palindrome, and implement precise addition of non-negative decimal strings without using native floating-point types.
This practice problem consists of two tasks focused on string processing and custom arithmetic.
Part 1: Palindromic Permutation Check
Given a string s, determine whether any arrangement of its characters can form a valid palindrome.
- Return
Trueif a palindromic permutation exists, otherwiseFalse. - The input string may contain any standard printable characters. Case matters (e.g.,
'A'and'a'are distinct).
Part 2: High-Precision Decimal Addition
Given two strings num1 and num2 representing non-negative real numbers in decimal format, return their sum as a string.
- You must not convert the inputs directly to native floating-point types (like Python's
float), nor use built-in arbitrary-precision arithmetic libraries likedecimal.Decimal. - Inputs may or may not contain a decimal point
'.'. - Handle edge cases where inputs lack leading integer digits (e.g.,
".5"), lack explicit decimal points (e.g.,"12"), or end with a trailing decimal point (e.g.,"7."). - The output must be formatted canonically:
- No extraneous leading zeros in the integer component (e.g.,
"07"should become"7", but"0"remains"0"). - No trailing zeros in the fractional component, and no isolated trailing decimal point (e.g.,
"1.50"becomes"1.5", and"1.00"becomes"1").
- No extraneous leading zeros in the integer component (e.g.,
Hints
Hint 1
For Part 1: Consider the structural definition of a palindrome. What constraint does symmetry place on character frequencies?
Hint 2
For Part 2: Try aligning both numbers around their decimal points before adding. How can padding simplify carrying across the boundary?
Hint 3
Pay close attention to stripping extra zeros from the final result while preserving at least one digit for zero values.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Palindromic Permutation Check
Approach & Invariant
A palindrome reads identically forward and backward. Symmetry dictates that every character in the left half must mirror an identical character in the right half.
Therefore:
- In a palindrome of even length, every character must appear an even number of times.
- In a palindrome of odd length, exactly one character appears an odd number of times (occupying the center spot), while all other characters must appear an even number of times.
Thus, a string can be rearranged into a palindrome if and only if at most one character has an odd frequency count.
We can maintain a hash set of characters seen an odd number of times. We iterate through the string, toggling the presence of each character in the set. At the end, if the size of the set is $\le 1$, the string can form a palindrome.
Complexity
- Time Complexity: $O(n)$, where $n$ is the length of
s, as we traverse the string once. - Space Complexity: $O(k)$, where $k$ is the number of distinct characters in
s. For ASCII/Unicode with bounded character sets, this is $O(1)$.
Python Implementation
def can_form_palindrome(s: str) -> bool:
odd_chars = set()
for char in s:
if char in odd_chars:
odd_chars.remove(char)
else:
odd_chars.add(char)
return len(odd_chars) <= 1
Part 2: Arbitrary-Precision Decimal Addition
Approach
Converting decimal strings to native binary floating-point representations (float) introduces representation errors and precision loss for large numbers. Converting directly to single integers via int() fails when handling fractional parts.
Instead, we can implement manual grade-school addition aligned at the decimal point:
- Partitioning: Split both inputs into an integer portion and a fractional portion using the decimal point
'.'as the pivot. - Alignment:
- Right-pad fractional parts with
'0'to make them equal in length ($L_{\text{frac}}$). - Left-pad integer parts with
'0'to make them equal in length ($L_{\text{int}}$).
- Right-pad fractional parts with
- Unified Digit Addition: Concatenate the integer and fractional parts for each number into a single continuous digit string. Because both parts are padded, the decimal point is conceptually at position $L_{\text{int}}$ for both numbers.
- Digit-wise Sum: Iterate backwards from the rightmost digit to the leftmost digit, keeping track of the sum and a
carryvalue. - Reconstruction & Canonicalization:
- Place the decimal point back at index $\text{len(result)} - L_{\text{frac}}$.
- Strip unnecessary leading zeros from the integer side (retaining at least a single
"0"if the integer component is empty). - Strip unnecessary trailing zeros from the fractional side. If no fractional digits remain, omit the decimal point entirely.
Complexity
- Time Complexity: $O(m + n)$, where $m$ and $n$ are the lengths of
num1andnum2. - Space Complexity: $O(m + n)$ auxiliary space to construct padded strings and output representations.
Python Implementation
def add_decimal_strings(num1: str, num2: str) -> str:
# Separate integer and fractional components
int1, _, frac1 = num1.partition('.')
int2, _, frac2 = num2.partition('.')
# Determine maximum lengths for padding
max_frac_len = max(len(frac1), len(frac2))
max_int_len = max(len(int1), len(int2))
# Pad fractions on the right, integers on the left
frac1_padded = frac1.ljust(max_frac_len, '0')
frac2_padded = frac2.ljust(max_frac_len, '0')
int1_padded = int1.zfill(max_int_len)
int2_padded = int2.zfill(max_int_len)
# Combine into single digit sequences
seq1 = int1_padded + frac1_padded
seq2 = int2_padded + frac2_padded
# Perform grade-school addition from right to left
carry = 0
res_digits = []
for i in range(len(seq1) - 1, -1, -1):
digit_sum = int(seq1[i]) + int(seq2[i]) + carry
res_digits.append(str(digit_sum % 10))
carry = digit_sum // 10
if carry:
res_digits.append(str(carry))
res_digits.reverse()
full_str = "".join(res_digits)
# Re-insert decimal point location
split_idx = len(full_str) - max_frac_len
raw_int = full_str[:split_idx]
raw_frac = full_str[split_idx:]
# Canonicalize output
clean_int = raw_int.lstrip('0') or '0'
clean_frac = raw_frac.rstrip('0')
if clean_frac:
return f"{clean_int}.{clean_frac}"
return clean_int
Common Pitfalls & Edge Cases
- Carry Across Decimal Boundary: Treating integer and fractional parts as isolated additions often leads to bugs when a fractional sum exceeds $1.0$ (e.g.,
"0.6" + "0.4"). Concatenating padded segments eliminates this issue because carrying naturally flows past the boundary. - Missing Parts: Inputs like
".5"or"12."must be handled gracefully. Utilizingstr.partition('.')ensures missing parts are returned as empty strings""rather than raising errors. - Format Normalization: Returning outputs like
"1.0"or"012"fails typical requirements. Explicit stripping of leading/trailing zeros ensures canonical formatting.