#2311

Longest Binary Subsequence Less Than or Equal to K

Medium
StringDynamic ProgrammingGreedyMemoizationGreedyDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach focuses on constructing the longest valid subsequence directly by counting zeros and ones, while ensuring the binary number formed is less than or equal to k. This avoids the need to generate all subsequences.

⚙️

Algorithm

4 steps
  1. 1Step 1: Count the number of '1's in the string s that can be included without exceeding k.
  2. 2Step 2: Count the number of '0's in the string s.
  3. 3Step 3: If the count of '1's is sufficient to form a number less than or equal to k, include all zeros and those '1's.
  4. 4Step 4: If not, include as many '1's as possible while ensuring the binary number remains <= k.
solution.py14 lines
1def longestSubsequence(s, k):
2    count_ones = s.count('1')
3    count_zeros = s.count('0')
4    if count_ones == 0:
5        return count_zeros
6    binary_value = 0
7    length = 0
8    for i in range(len(s)):
9        if s[i] == '1':
10            if binary_value + (1 << (count_ones - 1)) <= k:
11                binary_value += (1 << (count_ones - 1))
12                length += 1
13            count_ones -= 1
14    return length + count_zeros

Complexity note: The time complexity is O(n) because we only traverse the string a couple of times. The space complexity is O(1) as we only use a few integer variables to keep track of counts and lengths.

  • 1Leading zeros can be included in the subsequence without affecting the value.
  • 2The binary representation grows exponentially, so careful counting of bits is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.