Check if an encoding represents a unique binary string in Python

Suppose we have an array called nums that represents an encoding of a binary string of size k. We need to check whether the given encoding uniquely identifies a binary string or not. The encoding contains counts of contiguous 1s which are separated by single 0s.

So, if the input is like nums = [4, 2, 3] and k = 11, then the output will be True because there is a binary string like 11110110111 of length k = 11.

Understanding the Problem

The encoding works as follows ?

  • Each number in nums represents a group of consecutive 1s
  • Between each group of 1s, there is exactly one 0
  • We need to verify if the total length matches k

Solution Approach

To solve this, we will follow these steps ?

  • total := sum of all elements in nums (total 1s)
  • total := total + len(nums) - 1 (add separating 0s)
  • return True when total equals k, otherwise False

Example

Let's implement the solution ?

def solve(nums, k):
    total = sum(nums)  # Sum of all 1s
    total += len(nums) - 1  # Add separating 0s
    return total == k

# Test case
nums = [4, 2, 3]
k = 11
result = solve(nums, k)
print(f"Input: nums = {nums}, k = {k}")
print(f"Output: {result}")

# Let's trace the calculation
total_ones = sum(nums)
separating_zeros = len(nums) - 1
total_length = total_ones + separating_zeros
print(f"\nBreakdown:")
print(f"Total 1s: {total_ones}")
print(f"Separating 0s: {separating_zeros}")  
print(f"Total length: {total_length}")
print(f"Expected length k: {k}")
print(f"Match: {total_length == k}")
Input: nums = [4, 2, 3], k = 11
Output: True

Breakdown:
Total 1s: 9
Separating 0s: 2
Total length: 11
Expected length k: 11
Match: True

How It Works

For the example nums = [4, 2, 3] and k = 11 ?

  • First group: 4 consecutive 1s ? 1111
  • Separator: 1 zero ? 0
  • Second group: 2 consecutive 1s ? 11
  • Separator: 1 zero ? 0
  • Third group: 3 consecutive 1s ? 111
  • Result: 11110110111 (length = 11) ?

Additional Test Cases

def solve(nums, k):
    total = sum(nums)
    total += len(nums) - 1
    return total == k

# Test case 1: Valid encoding
print("Test 1:", solve([2, 1, 3], 7))  # 11010111 (length 7)

# Test case 2: Invalid encoding - too short
print("Test 2:", solve([1, 1, 1], 5))   # 10101 needs length 5, but we get 5

# Test case 3: Invalid encoding - too long  
print("Test 3:", solve([3, 2], 4))      # 11101 needs length 4, but we get 6

# Test case 4: Single group
print("Test 4:", solve([5], 5))         # 11111 (length 5)
Test 1: True
Test 2: True
Test 3: False
Test 4: True

Conclusion

This solution efficiently checks if an encoding represents a valid binary string by calculating the total length needed. The key insight is that we need the sum of all 1s plus the separating 0s between groups, which equals len(nums) - 1.

Updated on: 2026-03-25T14:17:18+05:30

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements