Encode Number - Problem

You've discovered a mysterious encoding system that converts non-negative integers into binary-like strings, but with a twist! Your task is to crack the encoding pattern and implement the secret function.

Given a non-negative integer num, return its encoded string representation. The encoding follows a specific pattern that you need to deduce from the examples:

  • 0"" (empty string)
  • 1"0"
  • 2"1"
  • 3"00"
  • 4"01"
  • 5"10"
  • 6"11"

Can you figure out the secret pattern? This encoding is related to a modified binary representation where the structure follows a unique mathematical relationship!

Input & Output

example_1.py — Basic Case
$ Input: num = 3
Output: "00"
💡 Note: Number 3 is in level 2 of the binary tree structure (range 3-6). Its position within the level is 3-3=0. Converting position 0 to 2-bit binary gives "00".
example_2.py — Mid-range Case
$ Input: num = 6
Output: "11"
💡 Note: Number 6 is in level 2 (range 3-6). Its position within the level is 6-3=3. Converting position 3 to 2-bit binary gives "11".
example_3.py — Edge Cases
$ Input: num = 0
Output: ""
💡 Note: The special case: 0 maps to an empty string according to the encoding rules.

Visualization

Tap to expand
Binary Tree Level StructureLevel 0: Special Case0 → ""Level 1: 1 bit1 → "0"2 → "1"Level 2: 2 bits3 → "00"4 → "01"5 → "10"6 → "11"Level 3: 3 bits7 → "000"8 → "001"... (8 total positions)Pattern: Level k has 2^k positions, each encoded with k bitsKey InsightAdd 1 to input number, then remove the highest bitExample: 5 + 1 = 6 = "110" → remove "1" → "10"
Understanding the Visualization
1
Understand the Structure
Numbers are organized in levels: Level 1 has 2 positions (1,2), Level 2 has 4 positions (3,4,5,6), etc.
2
Find the Level
Determine which level contains your target number using mathematical formulas
3
Calculate Position
Find the relative position within that level (0-indexed)
4
Binary Conversion
Convert the position to binary using the appropriate number of bits for that level
Key Takeaway
🎯 Key Insight: The encoding represents position within binary tree levels. Adding 1 and removing the highest bit directly computes this position!

Time & Space Complexity

Time Complexity
⏱️
O(log n)

Converting to binary representation takes O(log n) time

n
2n
Linearithmic
Space Complexity
O(log n)

Space for the result string of length log(n)

n
2n
Linearithmic Space

Constraints

  • 0 ≤ num ≤ 109
  • The output string will have length at most 32 characters
  • Follow-up: Can you solve this without using logarithmic functions?
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen