1533. Flipped Bit Detector

Easy1.5 points estimatedBit ManipulationBrainteaserString

A sender transmits a binary word bits whose positions are numbered from 1 at the left. The word is called valid when the XOR of the positions of all its '1' characters equals 0. For example, the word with ones at positions 1, 2 and 3 is valid because 1 ^ 2 ^ 3 = 0.

During transmission at most one character may have been flipped, from '0' to '1' or the other way round, so the received string is a valid word with at most one position toggled. Return the 1-based position of the flipped character, or 0 if the word arrived intact.

Input: the string bits. Output: one integer. Compute the XOR of the positions of the ones in a single pass: it is 0 for a valid word and equals the flipped position otherwise. Time O(n), space O(1).

Example 1

Input:
bits = "0110"
Output:
1
Explanation:

Positions 2 and 3 hold ones; 2 ^ 3 = 1, so position 1 was flipped (the original word was 1110).

Example 2

Input:
bits = "1110"
Output:
0
Explanation:

The ones are at positions 1, 2 and 3 and 1 ^ 2 ^ 3 = 0, so the word is intact.

Constraints

1 ≤ bits.length ≤ 1000

bits[i] is '0' or '1'

The input is a valid word with at most one flipped bit.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…