Encode Number - Problem

Given a non-negative integer num, return its encoding string. The encoding follows a pattern where each number maps to a binary-like representation.

The encoding pattern can be deduced from these examples:

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

Your task is to find the pattern and implement the encoding function.

Input & Output

Example 1 — Small Number
$ Input: num = 5
Output: "10"
💡 Note: Number 5 belongs to group 2 (range 3-6), at position 1 within the group. Position 1 in 2-bit binary is "10".
Example 2 — Edge Case Zero
$ Input: num = 0
Output: ""
💡 Note: Zero maps to empty string according to the encoding pattern.
Example 3 — Group Boundary
$ Input: num = 3
Output: "00"
💡 Note: Number 3 is the first in group 2, at position 0. Position 0 in 2-bit binary is "00".

Constraints

  • 0 ≤ num ≤ 109

Visualization

Tap to expand
Encode Number - Optimal Solution INPUT num = 5 Encoding Pattern: num encoding 0 "" 1 "0" 2 "1" 3 "00" 4 "01" 5 "10" 6 "11" ALGORITHM STEPS 1 Discover Pattern encode(n) = binary(n+1) without leading bit 2 Calculate n + 1 5 + 1 = 6 3 Convert to Binary 6 in binary = "110" 1 1 0 4 Remove Leading Bit "110" --> "10" 1 1 0 bin(num+1)[1:] = "10" FINAL RESULT Output Encoding: "10" Verification: Input: num = 5 Step: 5 + 1 = 6 Binary(6) = "110" Remove first: "10" OK - Verified! Key Insight: The encoding of number n equals the binary representation of (n+1) with the leading bit removed. This works because numbers 1 to 2^k - 1 all share the same leading 1 in binary. Time: O(log n), Space: O(log n) TutorialsPoint - Encode Number | Optimal Solution
Asked in
Google 25 Facebook 18 Microsoft 15
23.0K Views
Medium Frequency
~15 min Avg. Time
890 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