Talentd
FleetCode
Make and follow sheets.Sign in

Convert Date to Binary solution and explanation

EasyMathString4 min read88.8% acceptanceUpdated 9 Apr 2026
Convert Date to Binary || LeetCode Weekly Contest 414 || Leetcode Solutioncodi · 0:42 · 895 viewsWatch on YouTube
9 more videos on this problem
  1. Convert Date to Binary || LeetCode Weekly Contest 414 || Leetcode Solutioncodi · 0:42 · 895 views
  2. 3280. Convert Date to Binary (Leetcode Easy)Programming Live with Larry · 4:11 · 671 views
  3. Convert Date to Binary | Leetcode weekly-contest-414Developer Coder · 2:19 · 441 views
  4. 3280. Convert Date to BinaryLeetcode and Interview Question · 4:17 · 328 views
  5. 🔥🔥 Very Easy Explanation 🔥🔥 || Convert Date to Binary || String Methods || Weekly Contest 414Mohit Siwal · 4:03 · 222 views
  6. leetcode 3280 : convert date to binary python solutionleetcode blind 75 · 2:37 · 194 views
  7. #LeetCode 3280 | Convert Date to Binary #JavaSleepy Cracker · 2:42 · 136 views
  8. LeetCode 3280 | Convert Date to Binary [easy] [quicksolve]LeetCoders United · 3:37 · 55 views
  9. 3280. Convert Date to Binary || LeetCode problem solvingDreaming EyE · 33:25 · 46 views
  10. Leetcode easy problem 3280. Convert Date to Binary | devops python practiceADevOpsEngineer · 1:15 · 31 views

The problem

You are given a string date representing a Gregorian calendar date in the yyyy-mm-dd format.

date can be written in its binary representation obtained by converting year, month, and day to their binary representations without any leading zeroes and writing them down in year-month-day format.

Return the binary representation of date.

Example 1:

Input: date = "2080-02-29"

Output: "100000100000-10-11101"

Explanation:

100000100000, 10, and 11101 are the binary representations of 2080, 02, and 29 respectively.

Example 2:

Input: date = "1900-01-01"

Output: "11101101100-1-1"

Explanation:

11101101100, 1, and 1 are the binary representations of 1900, 1, and 1 respectively.

Constraints:

  • date.length == 10
  • date[4] == date[7] == '-', and all other date[i]'s are digits.
  • The input is generated such that date represents a valid Gregorian calendar date between Jan 1st, 1900 and Dec 31st, 2100 (both inclusive).

Approach overview

Problem Overview: You receive a date string in the format yyyy-mm-dd. The task is to convert the year, month, and day into their binary representations and return them joined by hyphens in the same order. Leading zeros are not required in the binary output.

Approach 1: String Split and Manual Conversion (O(n) time, O(1) space)

The most direct solution splits the input string using the - delimiter, producing three components: year, month, and day. Convert each component from string to integer, then convert the integer to its binary representation using built-in base conversion or manual division by 2. Finally, concatenate the binary strings with - between them. The algorithm performs a small number of conversions and string operations, so the runtime is effectively constant for a fixed date format, though conceptually O(n) with respect to the input string length.

This approach relies on basic operations from string manipulation and number conversion from math. It is easy to read, portable across languages, and maps directly to typical standard library functions like split() and toBinaryString(). Most production solutions follow this pattern because it is clear and requires minimal code.

Approach 2: Regular Expression Replacement (O(n) time, O(1) space)

A more compact alternative uses a regular expression to match the numeric parts of the date and replace them with their binary equivalents during substitution. The regex pattern captures groups of digits, and the replacement function converts each matched substring to an integer and then to binary. Each match is processed independently while preserving the hyphen separators.

This approach still performs the same underlying operations—parsing numbers and converting them to base 2—but embeds the transformation inside a regex replacement pipeline. It works well in languages like JavaScript or Python where replacement callbacks are concise. While elegant, it may be slightly harder to read for beginners compared to the explicit split-and-convert method.

Recommended for interviews: The string split and manual conversion approach. Interviewers expect you to parse the date using split, convert each component to an integer, and generate binary output. It demonstrates solid fundamentals with string processing and simple number base conversion. Regex solutions are valid but usually unnecessary unless the interviewer specifically asks for pattern-based transformations.

Approach 1: String Split and Manual Conversion

This approach involves splitting the input date string into year, month, and day using the hyphen '-' as a delimiter. Once the components are isolated, each is converted from a string to an integer, then to its binary form. We use language-specific functions to convert integers to binary, strip leading zeros, and join the components back with hyphens.

def convert_date_to_binary(date):
    year, month, day = map(int, date.split('-'))
    return f"{bin(year)[2:]}-{bin(month)[2:]}-{bin(day)[2:]}"

print(convert_date_to_binary("2080-02-29"))
import java.util.*;

public class DateToBinary {
    public static void main(String[] args) {
        String date = "2080-02-29";
        System.out.println(convertDateToBinary(date));
    }
    
    public static String convertDateToBinary(String date) {
        String[] parts = date.split("-");
        int year = Integer.parseInt(parts[0]);
        int month = Integer.parseInt(parts[1]);
        int day = Integer.parseInt(parts[2]);
        
        String binaryYear = Integer.toBinaryString(year);
        String binaryMonth = Integer.toBinaryString(month);
        String binaryDay = Integer.toBinaryString(day);
        
        return String.join("-", binaryYear, binaryMonth, binaryDay);
    }
}
#include <iostream>
#include <bitset>
#include <sstream>

std::string convertDateToBinary(const std::string& date) {
    int year = std::stoi(date.substr(0, 4));
    int month = std::stoi(date.substr(5, 2));
    int day = std::stoi(date.substr(8, 2));

    std::stringstream ss;
    ss << std::bitset<12>(year).to_string() << "-"
       << std::bitset<4>(month).to_ulong() << "-"
       << std::bitset<5>(day).to_ulong();

    return ss.str();
}

int main() {
    std::string date = "2080-02-29";
    std::cout << convertDateToBinary(date) << std::endl;
    return 0;
}
function convertDateToBinary(date) {
    const [year, month, day] = date.split('-').map(Number);
    return `${year.toString(2)}-${month.toString(2)}-${day.toString(2)}`;
}

console.log(convertDateToBinary("2080-02-29"));
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* convertDateToBinary(const char* date) {
    char* result = malloc(50 * sizeof(char));
    char year[5], month[3], day[3];

    // Split the date into year, month, and day
    sscanf(date, "%4s-%2s-%2s", year, month, day);

    // Convert to integers
    int y = atoi(year);
    int m = atoi(month);
    int d = atoi(day);

    sprintf(result, "%b-%b-%b", y, m, d);

    return result;
}

int main() {
    const char* date = "2080-02-29";
    char* binaryDate = convertDateToBinary(date);
    printf("%s\n", binaryDate);
    free(binaryDate);
    return 0;
}
using System;

public class Program {
    public static void Main() {
        string date = "2080-02-29";
        Console.WriteLine(ConvertDateToBinary(date));
    }

    public static string ConvertDateToBinary(string date) {
        string[] parts = date.Split('-');
        int year = Int32.Parse(parts[0]);
        int month = Int32.Parse(parts[1]);
        int day = Int32.Parse(parts[2]);

        return Convert.ToString(year, 2) + "-" + Convert.ToString(month, 2) + "-" + Convert.ToString(day, 2);
    }
}

This approach utilizes Python's bin() function which provides a binary string representation prefixed with '0b'. Slicing is used to omit this prefix for each component. The formatted string offers intuitive result construction.

Complexity

Time Complexity: O(1) due to consistent conversion and operations for fixed string sizes.
Space Complexity: O(1) as the size of the created strings is effectively constant.

Try this approach in the editor

Approach 2: Regular Expression Replacement

This efficient technique leverages regular expressions to capture and transform each calendar component (year, month, day) from the original date string. It involves a two-step process: first identifying components and then calling the conversion function. The binary equivalent is aggregated in concise string formation.

import re

def convert_date_to_binary_regex(date):
    return "-".join(format(int(x), 'b') for x in re.findall(r'\d+', date))

print(convert_date_to_binary_regex("2080-02-29"))
function convertDateToBinaryRegex(date) {
    return date.replace(/\d+/g, (number) => parseInt(number, 10).toString(2));
}

console.log(convertDateToBinaryRegex("2080-02-29"));

The regular expression function re.findall retrieves all numeric sequences within a date string. These sequences convert to binary by utilizing Python's format function directly. Formatted components synchronize in the output through join.

Complexity

Time Complexity: O(1) by accounting for a finite and consistent count of transformation operations.
Space Complexity: O(1) aligning with constant space utilization owing to small, predictable output data strings.

Try this approach in the editor

Approach 3: Simulation

We first split the string date by -, then convert each part to its binary representation, and finally join these three parts with -.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the string date.

function convertDateToBinary(date: string): string {
    return date
        .split('-')
        .map(s => (+s).toString(2))
        .join('-');
}
func convertDateToBinary(date string) string {
	ans := []string{}
	for _, s := range strings.Split(date, "-") {
		x, _ := strconv.Atoi(s)
		ans = append(ans, strconv.FormatUint(uint64(x), 2))
	}
	return strings.Join(ans, "-")
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
String Split and Manual Conversion

Time Complexity: O(1) due to consistent conversion and operations for fixed string sizes.
Space Complexity: O(1) as the size of the created strings is effectively constant.

Regular Expression Replacement

Time Complexity: O(1) by accounting for a finite and consistent count of transformation operations.
Space Complexity: O(1) aligning with constant space utilization owing to small, predictable output data strings.

Simulation–

Complexity analysis

ApproachTimeSpaceWhen to Use
String Split and Manual ConversionO(n)O(1)Best general solution. Clear logic using split and integer-to-binary conversion.
Regular Expression ReplacementO(n)O(1)Useful when performing inline pattern-based replacements in languages with strong regex support.

Frequently asked questions

Is Convert Date to Binary easy or hard?

Convert Date to Binary is categorized as an Easy problem. The challenge mainly tests basic string parsing and number base conversion rather than complex algorithms or data structures.

Convert Date to Binary Python/Java solution

In Python, split the string using date.split('-'), convert each part with int(), and use bin(num)[2:] to get the binary string. In Java, use split("-") and Integer.toBinaryString(Integer.parseInt(part)) for each component before joining them with hyphens.

How to solve Convert Date to Binary in O(n)?

Split the date string using the '-' delimiter to extract year, month, and day. Convert each component to an integer and then to its binary representation using built-in base conversion. Join the binary values back together with hyphens to produce the final string.

What is the best approach for Convert Date to Binary?

The most practical approach splits the input string by '-' and converts each part (year, month, day) to binary individually. This method is simple, readable, and runs in O(n) time relative to the input string length with O(1) extra space.

Is Convert Date to Binary asked at Google/Amazon/Meta?

Problems like Convert Date to Binary appear in interview preparation platforms as easy warm-up questions. While not commonly reported in major company interview loops, similar tasks involving string parsing and base conversion are frequently used in coding screens.

What data structure is used in Convert Date to Binary?

No advanced data structures are required. The solution mainly uses basic string operations such as splitting and concatenation, along with integer conversion and binary formatting from standard libraries.

What is the time complexity of Convert Date to Binary?

The time complexity is O(n), where n is the length of the input string. Only a few operations are performed: splitting the string and converting three numbers to binary. Because the date format is fixed, the runtime behaves like constant time in practice.

Comments

Now write it yourselfClose this page and solve Convert Date to Binary in the editor, without looking.
Practise Convert Date to Binary