Leetcode 2311: Longest Binary Subsequence Less Than or Equal to K

grid47
grid47
Exploring patterns and algorithms
Mar 20, 2024 5 min read

You are given a binary string s and a positive integer k. Your task is to find the length of the longest subsequence of s that represents a binary number less than or equal to k when converted to decimal.
Problem
Approach
Steps
Complexity
Input: The input consists of a binary string s and an integer k.
Example: s = '1101011', k = 6
Constraints:
• 1 <= s.length <= 1000
• 1 <= k <= 10^9
• s[i] is either '0' or '1'.
Output: Return the length of the longest subsequence of s that forms a binary number less than or equal to k.
Example: For s = '1101011', k = 6, the output is 5.
Constraints:
• The subsequence should form a binary number less than or equal to k.
Goal: The goal is to find the longest subsequence of binary digits that represents a number less than or equal to k.
Steps:
• Start from the rightmost character in the string and traverse towards the left.
• Maintain a running total of the binary number formed and the length of the subsequence.
• For each '1', add its value to the running total and increment the subsequence length if the number is still less than or equal to k.
• Include all the '0's in the subsequence as they don't affect the binary value.
• Stop when you can no longer include '1's without exceeding k.
Goal: The problem constraints ensure that the string is manageable in size and contains only binary digits.
Steps:
• 1 <= s.length <= 1000
• 1 <= k <= 10^9
• s consists only of '0' and '1'.
Assumptions:
• The input string contains only '0's and '1's.
Input: s = '1101011', k = 6
Explanation: The longest subsequence of s that forms a binary number less than or equal to 6 is '00010', which is 2 in decimal. The length of the subsequence is 5.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus