Check if an encoding represents a unique binary string in Python


Suppose we have an array called nums represents an encoding of a binary string of size k, we have to check whether given encoding uniquely finds a binary string or not. Here the encoding has counts of contiguous 1s which are separated by single 0s.

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

To solve this, we will follow these steps −

  • total := sum of all elements in nums
  • total := total + size of nums - 1
  • return true when total is same as k otherwise false

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(nums, k):
   total = sum(nums)
   total += len(nums) - 1
   return total == k
nums = [4, 2, 3]
k = 11
print(solve(nums, k))

Input

[4, 2, 3], 11

Output

True

Updated on: 30-Dec-2020

65 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements