#3280
Convert Date to Binary
EasyMathStringString ManipulationArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution is similar to the brute force but focuses on using efficient string manipulation and built-in functions to minimize overhead. This approach is efficient and clear.
⚙️
Algorithm
3 steps- 1Step 1: Split the input date string by the '-' character to separate year, month, and day.
- 2Step 2: Use a list comprehension to convert each component to binary, stripping the '0b' prefix.
- 3Step 3: Join the binary strings with '-' in between to form the final output.
solution.py3 lines
1def dateToBinary(date):
2 year, month, day = date.split('-')
3 return '-'.join(bin(int(x))[2:] for x in [year, month, day])ℹ
Complexity note: The time complexity remains O(n) as we still process each character of the date string. The space complexity is O(n) because we create a new string for the output.
- 1Binary representation is a direct conversion of decimal numbers.
- 2String manipulation can be efficiently handled with built-in functions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.