Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Binary XOR Coding

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Binary XOR Coding. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

While validating diagnostic bitmasks for a Western Digital WD_BLACK SN850X device, implement binary XOR directly on strings. Return the result once with an iterative algorithm and once with a recursive algorithm, without converting the complete inputs to integers.

Formal Specification

Implement binary_xor(a, b, recursive=False):

  1. a and b are non-empty strings containing only '0' and '1'.
  2. Align both strings by their rightmost bit, padding the shorter string on the left with zeros.
  3. XOR corresponding bits and return a binary string with no leading zeros, except that zero must be returned as '0'.
  4. When recursive is False, use an iterative implementation.
  5. When recursive is True, use a recursive implementation. The recursive version should avoid one recursive call per bit so it remains practical for long inputs.

Do not use Python integer conversion on the complete binary strings, such as int(a, 2).

Constraints

  • 1 <= len(a), len(b) <= 100000
  • Each input contains only '0' and '1'
  • Inputs may contain leading zeros
  • The result must contain no leading zeros unless it is exactly '0'
  • Do not convert the complete strings to integers

Function Signature

def binary_xor(a, b, recursive=False):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output