Problem · String

Bit at an Index After Repeated Binary Expansion

Learn this problem
MediumAmazon logoAmazonFULLTIMEONSITE INTERVIEW
See Amazon hiring insights

Problem statement

Start with a binary string bits. In one expansion round, replace every character independently:

  • 0 becomes 00.
  • 1 becomes 10.

After exactly rounds expansions, return the bit at the zero-based position index. The position is guaranteed to exist in the expanded string.

Function

expandedBit(bits: String, rounds: int, index: int) → int

Examples

Example 1

bits = "01"rounds = 1index = 2return = 1

One expansion produces 0010, whose zero-based index 2 contains 1.

Example 2

bits = "1"rounds = 2index = 3return = 0

The two expansions are 1 -> 10 -> 1000, and its last bit is 0.

Example 3

bits = "101"rounds = 0index = 2return = 1

With zero rounds, query the original string directly.

Constraints

  • 1 <= bits.length <= 10^5
  • bits contains only 0 and 1.
  • 0 <= rounds <= 30
  • 0 <= index <= 10^9
  • index < bits.length * 2^rounds.

More Amazon problems

drafts saved locally
public int expandedBit(String bits, int rounds, int index) {
    // Write your solution here.
}
bits"01"
rounds1
index2
expected1
checking account