Problem 2864

Abstract / Summary

Given a list of integers, form the largest odd binary number by concatenating their binary representations.

Note

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

Python 2864.py

class Solution:
    def maximumOddBinaryNumber(self, s: str) -> str:
        t = sorted([ i for i in s ], reverse = True)
        return "".join(t[1:] + t[:1]) # move a "1" to the end
4 lines | 188 bytes | submitted November 2, 2023 | GitHub   25% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 83% (200k+ submissions).

Typical patterns to solve this problem:
  • Greedy
  • Math
  • 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 class Solution with a single method maximumOddBinaryNumber. The method receives a binary string s and returns a rearranged version that represents the largest possible odd binary number that can be formed using exactly the same characters. The core idea is to place all '1' characters at the most significant positions while ensuring that the least-significant bit is also '1', which guarantees odd parity. The algorithm accomplishes this by sorting the characters in descending order and then rotating the first character to the end of the sequence.

Key Steps

Extracting characters

The method begins by converting the input string into a list of its individual characters. This is performed with a list comprehension that iterates over the string directly.

t = [i for i in s]

The comprehension creates a mutable list t that holds each '0' or '1' from the original string, enabling subsequent in-place operations such as sorting.

Sorting in descending order

The next operation sorts the list t in reverse (descending) order. By specifying reverse=True, the sorting routine places all '1' characters before any '0' characters because '1' has a higher lexical value than '0'.

t = sorted(t, reverse=True)

This single call produces a list where the most significant bits are already maximized, satisfying the requirement for the largest binary value.

Rotating a '1' to the least-significant position

To guarantee that the resulting binary number is odd, the algorithm moves the first element of the sorted list (which is guaranteed to be '1' whenever at least one '1' exists) to the end of the list. This is achieved through slicing and concatenation.

result_list = t[1:] + t[:1]

If the input contains at least one '1', the slice t[:1] extracts that leading '1', and t[1:] contains the remaining characters. Concatenating them places the '1' at the least-significant position while preserving the descending order of the other bits.

Building the final string

Finally, the method joins the characters of result_list into a single string, which is returned as the answer.

return "".join(result_list)

The join operation efficiently concatenates the list of characters without creating intermediate strings for each addition.

Edge Cases Handled

When the input string consists solely of '0' characters, the sorting step yields a list of zeros. The rotation step still moves the first '0' to the end, leaving the string unchanged, which is appropriate because no odd binary number can be formed from all zeros.

If the input contains exactly one character, the slicing operations produce an empty list for t[1:] and a single-element list for t[:1]. Concatenating these yields the original character, and the join returns it unchanged. This behavior correctly handles the minimal input size.

For inputs that contain a single '1' among zeros, the sorted list begins with that '1'. Rotating it to the end results in a string where the only '1' occupies the least-significant position, producing the smallest odd number possible with those characters, which is also the maximum odd number under the constraint of using all characters.

When the input already ends with a '1' after sorting (for example, a string of all '1's), the rotation moves the first '1' to the end, but because all characters are identical, the final string is indistinguishable from the sorted version, preserving correctness.

Performance Optimizations

The algorithm leverages Python’s built-in sorted function with the reverse=True flag, which is implemented in C and provides a highly optimized sorting routine. By sorting the characters directly rather than counting them manually, the code avoids explicit loops for tallying '1' and '0' occurrences, reducing interpreter overhead.

The use of slicing (t[1:] and t[:1]) creates new list objects, but these operations are performed only once and involve copying references rather than deep copies of the characters, keeping the overhead minimal.

String construction is performed with a single join call, which is the most efficient way to concatenate a sequence of characters in Python. This avoids the quadratic cost associated with repeated string concatenation inside loops.

Overall, the method executes a constant number of high-level operations-list comprehension, sorting, slicing, concatenation, and joining-each of which is implemented with performance-aware internal mechanisms, resulting in a fast and memory-efficient solution for the problem size typically encountered in practice.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a row of blocks where some are labeled one and some are labeled zero. The code first collects all these blocks and arranges them in a special order, putting all the ones at the front of the line and keeping all the zeros at the back. Once the blocks are organized this way, the code moves just one of the ones from the very front all the way to the end of the line. This makes the row of blocks look like a long string that starts with many ones and finishes with a single one at the very end. By putting that one at the very end, the whole row becomes what is known as an odd number.

written by google gemini

Code Quality

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

Complexity Analysis

Time: loglinear
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 Python Java C++ TS
WalkCCC Python Java C++
leetcode.ca Python Java Go C++ Rust TS
Progiez Python Java C++
github chandansgowda Python
charles-wangkai Java
fsq C++
JoshCrozier JS
lkwq007 Python
muhammadfarhankt Go
pruthvikp Python
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
chandansgowda Python
charles-wangkai Java
fsq C++
JoshCrozier JavaScript
lkwq007 Python
muhammadfarhankt Go
pruthvikp Python
varunu28 Java
24 links | 12 authors | 7 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

2 easy 2 medium
5 solutions   November 2, 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