Longest Binary Subsequence Less Than or Equal to K - Problem
Problem: You're given a binary string
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 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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code