Longest Binary Subsequence Less Than or Equal to K — LeetCode 2311 Python Solution

MediumGreedyMemoizationStringDynamic Programming
Problem
#2311
Pattern
Greedy
Reading time
2 min

The 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.

Example

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.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string s
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2311. Longest Binary Subsequence Less Than or Equal to K is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2311. Longest Binary Subsequence Less Than or Equal to K?
LeetCode 2311. Longest Binary Subsequence Less Than or Equal to K is rated Medium on LeetCode.
What is the time complexity of LeetCode 2311. Longest Binary Subsequence Less Than or Equal to K?
The Python solution on this page runs in O(n), where n is the length of the string s.
What is the space complexity of LeetCode 2311. Longest Binary Subsequence Less Than or Equal to K?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2311. Longest Binary Subsequence Less Than or Equal to K cover?
LeetCode 2311. Longest Binary Subsequence Less Than or Equal to K is tagged Greedy, Memoization, String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview