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: 2
💡 Note: We can take all characters to form "111" = 7, but 7 > 5. We need to find the longest subsequence ≤ 5. The best strategy is to take the rightmost ones first (lowest powers): we can take "11" (last two characters) = 3 ≤ 5, giving us length 2.
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 Less Than or Equal to K INPUT Binary String s: 1 0 0 1 i=0 i=1 i=2 i=3 Target k: k = 9 k in binary: 1001 Input Parameters s = "1001" k = 9 Length of s: 4 ALGORITHM STEPS 1 Count All Zeros Zeros are always safe zeros = 2 (at pos 1,2) 2 Process from Right Add 1s greedily from end Right to left: 1,0,0,1 3 Check Each 1 If adding 1 keeps value <= k, include it 4 Calculate Result Sum: zeros + valid 1s result = 2 + 2 = 4 Greedy Selection pos 3: add 1 --> val=1 <=9 OK pos 2: add 0 --> val=10 OK pos 1: add 0 --> val=100 OK pos 0: add 1 --> val=1001=9 OK FINAL RESULT Selected Subsequence: 1 0 0 1 All 4 characters selected! Binary Value Check "1001" = 9 (decimal) 9 <= 9 : Valid! Output: 4 Longest valid subsequence Length = 4 Key Insight: The greedy approach works because: 1) All zeros can always be included (they don't increase value). 2) For 1s, process from right to left - rightmost 1s contribute less to the binary value, so we greedily include them while keeping the total <= k. Time: O(n), Space: O(1). TutorialsPoint - Longest Binary Subsequence Less Than or Equal to K | Greedy Approach
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