DEV Community

Cover image for ๐Ÿ‘น Longest Binary Subsequence K โ€“ LeetCode 2311 (C++ | JavaScript | Python )
Om Shree
Om Shree

Posted on

๐Ÿ‘น Longest Binary Subsequence K โ€“ LeetCode 2311 (C++ | JavaScript | Python )

๐Ÿ‘‹ Hey, binary sleuths! ๐Ÿ•ต๏ธโ€โ™‚๏ธ๐Ÿ’ก

Today, we dive into a clever bit manipulation puzzle โ€” LeetCode 2311: Longest Binary Subsequence Less Than or Equal to K. Itโ€™s all about squeezing the longest subsequence out of a binary string that forms a number โ‰ค k. Let's decode this one together! ๐Ÿง 


๐Ÿง  Problem Summary

You're given:

  • A binary string s
  • An integer k

You need to return the length of the longest subsequence of s such that:

  • That subsequence forms a valid binary number โ‰ค k
  • Leading zeroes are allowed
  • Subsequence must respect the original order of characters

๐Ÿงฉ Intuition

To maximize the length of the subsequence:

  • Include all '0's โ€” they do not increase the binary value.
  • Greedily add '1's from the right side โ€” since binary is weighted from right to left, rightmost '1's have smaller impact.
  • Stop adding when the resulting number exceeds k.

๐Ÿงฎ C++ Code

class Solution {
 public:
  int longestSubsequence(string s, int k) {
    int oneCount = 0;
    int num = 0;
    int pow = 1;

    // Take as many 1s as possible from the right.
    for (int i = s.length() - 1; i >= 0 && num + pow <= k; --i) {
      if (s[i] == '1') {
        ++oneCount;
        num += pow;
      }
      pow *= 2;
    }

    return ranges::count(s, '0') + oneCount;
  }
};
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ป JavaScript Code

var longestSubsequence = function(s, k) {
    let oneCount = 0;
    let num = 0;
    let pow = 1;

    for (let i = s.length - 1; i >= 0 && num + pow <= k; i--) {
        if (s[i] === '1') {
            oneCount++;
            num += pow;
        }
        pow *= 2;
    }

    const zeroCount = [...s].filter(ch => ch === '0').length;
    return zeroCount + oneCount;
};
Enter fullscreen mode Exit fullscreen mode

๐Ÿ Python Code

class Solution:
    def longestSubsequence(self, s: str, k: int) -> int:
        one_count = 0
        num = 0
        pow_ = 1

        for i in range(len(s) - 1, -1, -1):
            if s[i] == '1':
                if num + pow_ > k:
                    break
                one_count += 1
                num += pow_
            pow_ *= 2

        return s.count('0') + one_count
Enter fullscreen mode Exit fullscreen mode

โœ… Final Thoughts

This is a brilliant example of how understanding binary properties helps solve real problems. A few key insights let us:

  • Avoid brute-force subsequence generation
  • Use greedy and bitwise intuition
  • Keep things simple and efficient

Drop a โค๏ธ if this helped, and keep sharpening your problem-solving toolkit! ๐Ÿ’ปโœจ

Happy coding! ๐Ÿš€

Top comments (4)

Collapse
 
dotallio profile image
Dotallio

Really appreciate how you broke down the intuition for the greedy approach - it clicked for me right away. Have you found any real-world cases where this trick comes in handy beyond interview problems?

Collapse
 
om_shree_0709 profile image
Om Shree

You're very welcomeโ€”glad the intuition helped it click!

Collapse
 
thedeepseeker profile image
Anna kowoski

Well Explained.

Collapse
 
om_shree_0709 profile image
Om Shree

Thanks Anna