๐น Problem: 2311. Longest Binary Subsequence Less Than or Equal to K
Difficulty: #Medium
Tags: #Greedy, #BitManipulation
๐ Problem Summary
You're given a binary string s and an integer k.
You need to select a subsequence (characters in order, skipping allowed) such that:
- That subsequence (as a binary number) is less than or equal to
k. - The length of this subsequence is maximized.
Return the maximum possible length of such a valid subsequence.
๐ง My Thought Process
Brute Force Idea:
This porblem is all theavengersof subsequences! Caught me off guard with the constraints. First of all it's a subsequence problem, so I I thoguht it has to be a [[dp]] problem. The it also is a binary string, so I it's a dynamic bit manipulation problem. Then it hit me that it's a medium problem, so it can't be that hard. So, I thought [[greedy]] would be the way to go. But couldn't figure out how to do it. I was thinking of generating all subsequences and checking their values, but that would be too slow (O(2^n)). So, as i did for many of my previous problems, I decided to look up the solution.Greedy Observations:
I noticed that'0's donโt contribute to the binary value, so you can safely include them all.
For'1's, their position in the binary string matters (left = more value), so we must be selective.
A key idea clicked when I realized we should iterate from the right (LSB side) so we can build up the smallest possible binary value, and greedily decide whether to include a '1'.
-
Bit Boundaries:
We can't include too many
'1's from the left, becausekmay only haveXbits โ any subsequence with more thanXbits is guaranteed to be greater thank.
โ Optimal Solution
Greedy Approach, scanning from the end (LSB):
- Start from the rightmost bit of the binary string.
- Always include
'0's โ they don't affect value. - For each
'1'at indexifrom the right:
- Check if adding
2^i(the value it would contribute in binary) keeps total โคk. - Only include it if the resulting value remains valid.
- Use
k.bit_length()to determine how many bits we can safely use.
This way, we maximize the count of characters (mostly '0's and safe '1's).
โ๏ธ Code Implementation (Python)
class Solution:
def longestSubsequence(self, s: str, k: int) -> int:
sm = 0 # running binary value of selected subsequence
cnt = 0 # number of selected characters
bits = k.bit_length() # how many bits max we can use to stay โค k
for i, ch in enumerate(reversed(s)):
if ch == "1":
if i < bits and sm + (1 << i) <= k:
sm += 1 << i
cnt += 1
else:
cnt += 1 # always include '0'
return cnt
โฑ๏ธ Time & Space Complexity
- Time: O(n) โ We iterate over each character once.
- Space: O(1) โ Only a few variables for counting.
๐งฉ Key Takeaways
- โ
Learned how
k.bit_length()helps bound the maximum size of binary values. - ๐ก Trickiest part was realizing that
'0'can always be included and that value contribution depends on position. - ๐ญ In future problems, Iโll be on the lookout for bit-based greedy constraints โ especially in problems involving subsequences and max values.
๐ Reflection (Self-Check)
- [ ] Could I solve this without help? โ โ Not entirely. I needed guidance to grasp the greedy logic fully.
- [ ] Did I write code from scratch? โ โ No, but I understand every line now.
- [โ ] Did I understand why it works?
- [โ ] Will I be able to recall this in a week?
๐ Related Problems
- [[1702 Maximum Binary String After Change]]
๐ Progress Tracker
| Metric | Value |
|---|---|
| Day | 31 |
| Total Problems Solved | 364 |
| Confidence Today | ๐ |
Top comments (0)