Longest Binary Subsequence Less Than or Equal to K - Problem
You are given a binary string s and a positive integer k.
Return the length of the longest subsequence of s that makes up a binary number less than or equal to k.
Note:
- The subsequence can contain leading zeroes.
- The empty string is considered to be equal to
0. - A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
Input & Output
Example 1 — Basic Case
$
Input:
s = "1001", k = 9
›
Output:
4
💡 Note:
The longest subsequence is "1001" which equals 9 in decimal (1×8 + 0×4 + 0×2 + 1×1 = 9), and 9 ≤ 9, so length is 4.
Example 2 — Limited by k
$
Input:
s = "111", k = 5
›
Output:
3
💡 Note:
We can take all characters to form "111" = 7, but 7 > 5. We can take "11" = 3 ≤ 5, or "101" = 5 ≤ 5. The longest is "101" with length 3.
Example 3 — All Zeros
$
Input:
s = "000", k = 5
›
Output:
3
💡 Note:
All zeros can be taken since "000" = 0 ≤ 5, giving us length 3.
Constraints
- 1 ≤ s.length ≤ 1000
- s consists only of '0' and '1'
- 1 ≤ k ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Binary string s and limit k
2
Process
Select characters to form valid binary number
3
Output
Length of longest valid subsequence
Key Takeaway
🎯 Key Insight: Greedily take all zeros first, then add ones while staying within the limit k
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code