Longest Binary Subsequence Less Than or Equal to K - Problem
Problem: You're given a binary string s and a positive integer k. Your task is to find the longest subsequence from the string that, when interpreted as a binary number, has a value less than or equal to k.

Key Points:
• A subsequence maintains the original order but can skip characters
• Leading zeros are allowed (e.g., "001" is valid)
• Empty subsequence equals 0
• You want the maximum length subsequence that stays ≤ k

Example: For s = "1001101" and k = 10, the subsequence "1010" (value 10) has length 4, which might be optimal.

Input & Output

example_1.py — Basic Case
$ Input: ["1001101", 10]
Output: 5
💡 Note: We can select subsequence "00101" which equals binary 101 = 5 in decimal. This gives us length 5 and stays within k=10.
example_2.py — All Zeros
$ Input: ["00001111", 5]
Output: 6
💡 Note: We can take all zeros (4) plus two rightmost ones "000011" = binary 11 = 3 ≤ 5, giving length 6.
example_3.py — Small k
$ Input: ["1111", 1]
Output: 1
💡 Note: k=1, so we can only take one rightmost '1' to get binary "1" = 1, giving length 1.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists only of 0s and 1s
  • 1 ≤ k ≤ 109
  • The subsequence can have leading zeros
  • Empty subsequence is considered to equal 0

Visualization

Tap to expand
Binary Subsequence: Position Values MatterExample: s = "10110", k = 612³ = 802² = 012¹ = 212⁰ = 10FreeGreedy Selection Process:1. Count zeros: 2 (positions 1,4 - always include)2. Try rightmost 1: value = 0 + 1 = 1 ≤ 6 ✓3. Try next 1: value = 1 + 2 = 3 ≤ 6 ✓4. Try leftmost 1: value = 3 + 8 = 11 > 6 ✗Optimal Subsequence: "0110"-0110Result: Binary "0110" = 6, Length = 4Why This Works:• Zeros never increase the value• Right-to-left selection minimizes cost• Greedy choice is always optimal• Each decision is independentTime: O(n) | Space: O(1)
Understanding the Visualization
1
Position Powers
Each position represents a power of 2: rightmost is 2⁰=1, next is 2¹=2, etc.
2
Zero Cost
Zeros at any position contribute 0 to the total value
3
Greedy Selection
Select ones from right to left to minimize their contribution
4
Optimal Result
This greedy strategy always produces the maximum length valid subsequence
Key Takeaway
🎯 Key Insight: In binary representation, position determines exponential contribution (2⁰, 2¹, 2², ...). Greedily selecting ones from right-to-left minimizes the total value while maximizing subsequence length.
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 15
21.5K 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