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
Longest Binary Subsequence ≤ KInput: s = "1001", k = 91001Choose subsequence: Can we take "1001"?"1001" in binary = 1×8 + 0×4 + 0×2 + 1×1 = 99 ≤ 9? ✓ Yes, we can include all 4 charactersLength: 4Result: 4
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
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
23.4K Views
Medium Frequency
~25 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