Longest Binary Subsequence Less Than or Equal to K Problem
#2311
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2311.
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.
Example 1:
Input: s = "1001010", k = 5
Output: 5
Explanation: The longest subsequence of s that makes up a binary number less than or equal to 5 is "00010", as this number is equal to 2 in decimal.
Note that "00100" and "00101" are also possible, which are equal to 4 and 5 in decimal, respectively.
The length of this subsequence is 5, so 5 is returned.
Example 2:
Input: s = "00101001", k = 1
Output: 6
Explanation: "000001" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.
The length of this subsequence is 6, so 6 is returned.
Constraints:
1 <= s.length <= 1000s[i]is either'0'or'1'.1 <= k <= 10^9
Solution
Approach: Greedy
Every 0 can be kept: leading zeros do not change the value. So the question is which 1s to keep. Scan s from right to left, keeping the value v of the chosen suffix and its length. A 0 is always taken. A 1 at bit position len is taken only if v + 2^len <= k, since a lower bit is cheaper than a higher one. Once len reaches 30, a 1 would exceed any k, so it is skipped.
Complexity: Time O(n), space O(1), where n is the length of s.
class Solution:
def longestSubsequence(self, s: str, k: int) -> int:
ans = v = 0
for c in s[::-1]:
if c == "0":
ans += 1
elif ans < 30 and (v | 1 << ans) <= k:
v |= 1 << ans
ans += 1
return ans