iq.lab
Python starts when a code cell comes near or you run one
13 Greedy and a little math

Lesson 2 of 2

Bits and small math

Every integer is a row of bits, and a few operators work on all its bits at once: XOR cancels pairs, and `x & (x - 1)` removes the lowest 1. A little arithmetic does the rest: a sum formula finds a missing number, `%` keeps big numbers small, and Euclid's rule finds a gcd.

About 1 hour 45 minutes, with the 3 problems worked in it
By the end you can
  • Write a number in binary and read one back, using place values, % 2 and // 2

  • Predict &, |, ^, << and >> on small numbers, bit by bit

  • Use XOR to cancel pairs and find the value without a twin in O(1) extra space

  • Count 1 bits with x & (x - 1), and fill the counts for 0 to n from smaller counts

  • Find a missing number from the expected total, keep big numbers small with %, and compute a gcd with Euclid's rule

A nightly job writes two log records for every run: one when the run starts, one when it ends. Both carry the run's id. Tonight one run crashed and never wrote its end record. The ids from all the records, in no particular order, are [4, 1, 6, 1, 4]. Which run crashed?

A dict of counts finds it: count each id and look for a count of 1. That works, and it costs memory for every id. This lesson finds it with one integer of memory, using an operator you may never have typed: XOR.

The greedy walks in the previous lesson kept their notebook (the values a walk writes down as it goes) to one or two numbers by choosing well. This lesson keeps the notebook that small with bits and a little arithmetic. To see why XOR works, we first look at numbers the way the computer stores them, as rows of 0s and 1s.

Numbers as bits

How does a computer write 13? In base 10, the digits of 472 are worth hundreds, tens and ones. In base 2, called binary, each digit is worth twice the one to its right: 1, 2, 4, 8, 16 and so on. Each digit is a bit, and it is either 0 or 1. 13 is 8 + 4 + 1, so in binary it is 1101: a 1 in the 8s place, a 1 in the 4s place, a 0 in the 2s place and a 1 in the 1s place.

In module 1 you peeled the digits off 472 with % 10 (the last digit) and // 10 (drop the last digit). Binary works the same way with 2: n % 2 is the last bit, and n // 2 drops it. Before you step, guess the bits this loop finds for 13, in the order it finds them.

Step throughPeeling the bits off 13
Step 1 of 18
Line 1 is about to run.
n = 13
bits = ""
while n > 0:
bits = str(n % 2) + bits
n = n // 2
print(bits)
print(bin(13))
Names
no names yet
Output
(nothing printed yet)

The bits come out last one first, which is why each new one goes on the front. The loop is a walk like any other, with the four answers this course gives every algorithm (the promise is what stays true after every pass):

bin(n) writes n in binary for you, with 0b in front, and the prefix works the other way too: 0b1101 typed in your code is the number 13. To read binary back, add the place values where the bits are 1: 1101 is 8 + 4 + 1 = 13.

Work it outRead a binary number

The binary number 10110 is which number in decimal? From the right, its five places are worth 1, 2, 4, 8 and 16.

decimal value

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Operators that work bit by bit

What can you do with two rows of bits? Python has operators that line up the bits of two numbers and combine them one column at a time. Each column is worked out from the two bits in that column alone. & (AND) gives 1 only where both bits are 1. | (OR) gives 1 where either bit is 1. ^ (XOR, short for "exclusive or") gives 1 where the bits differ, so a pair of 1s gives 0. In Python, ^ is not a power: 2 ^ 3 is 1, and the power is 2 ** 3.

bit of abit of bandorxor
00000
01011
10011
11110

Two more operators move bits instead of combining them. x << 1 shifts every bit one place left, which doubles x. x >> 1 shifts every bit one place right and drops the last one, the same as x // 2. And x & 1 keeps only the last bit, because 1 has a single 1 bit, at the end. So x & 1 is the same as x % 2: 1 for odd numbers, 0 for even.

The instrument below lines up 12 and 10 as rows of 8 bits, a on top and b under it, with the place values above them and the result row at the bottom. Each bit is a button that flips it, and the Operation buttons switch between &, |, ^ and the two shifts. It opens on 12 & 10. Before you look at the result row, use the table: which places have a 1 in both numbers?

So far: a number is a row of bits; &, | and ^ combine two rows column by column; << and >> slide one row. x & 1 and x >> 1 are the bit versions of % 2 and // 2.

PredictFive operators on 6 and 5

6 is 110 and 5 is 101 in binary. Type exactly what this prints.

a = 6
b = 5
print(a & b, a | b, a ^ b)
print(a << 1, a >> 1)

For practice, Reverse the 32 bits uses four of these operators: & 1 reads the last bit, >> 1 drops it, and << 1 with | adds it to the end of the answer.

XOR cancels pairs

Back to the crashed run: how can one integer find the id without a twin? XOR has three properties that, together, do it:

  1. x ^ x is 0. Every bit meets an equal bit, and equal bits give 0.
  2. x ^ 0 is x. A 0 bit never changes the bit it meets.
  3. Order does not matter. a ^ b equals b ^ a, and (a ^ b) ^ c equals a ^ (b ^ c). Each column is worked out on its own, and it ends as 1 exactly when it saw an odd number of 1s.

So the XOR of all the ids can be regrouped as if each id sat next to its twin: (4 ^ 4) ^ (1 ^ 1) ^ 6. Each pair is 0, and 6 survives. The notebook is one integer, result, starting at 0. result ^= x is shorthand for result = result ^ x, the same way += works. The print line uses format(x, "03b"), which writes a number in binary with 3 digits, padded with zeros. Guess before you step: what is result after the third id, before any pair has closed?

Step throughXOR every id, and the pairs cancel
Step 1 of 20
Line 1 is about to run.
ids = [4, 1, 6, 1, 4]
result = 0
for x in ids:
result ^= x
print(format(x, "03b"), format(result, "03b"))
print(result)
Names
no names yet
Output
(nothing printed yet)

A dict of counts needs O(n) extra space, one key per distinct id. XOR keeps only the combined bits, and that is enough, because every pair cancels.

The promise speaks of values seen an odd number of times. Check it on a list where one value appears three times.

Quick checkThree copies

Start result at 0 and do result ^= x for every x in [7, 2, 7, 2, 7]. Here 2 appears twice and 7 appears three times. What is result at the end?

Choose one answer, then check.

Now write it as a function. The tests add the edge cases: one item, a single value of 0, and negative numbers.

easyBits and math target 15 min

The value without a twin

The list of integers nums was built from pairs. Each pair is two copies of one value, and no two pairs share a value. Then one extra value, different from every paired value, was added once. Return that extra value.

The list can be in any order: the two copies of a value need not be next to each other, and the extra value can sit anywhere.

Counting the copies of each value with nums.count is correct but fails the speed test. A dict of counts passes it, at the price of O(n) extra space. Aim for O(n) time and O(1) extra space: a few variables, however long the list. The tests can check only the time.

Example 1
Inputnums = [5, 3, 5]Output3

5 appears twice. 3 appears once.

Example 2
Inputnums = [2, 7, 9, 7, 2]Output9

The copies of 2 sit at positions 0 and 4, the copies of 7 at positions 1 and 3. Only 9 appears once.

Example 3
Inputnums = [8]Output8

A list of one item: that item is the one without a twin.

Constraints
  • 1 ≤ len(nums) ≤ 50,001, and the length is odd.

  • -109 ≤ nums[i] ≤ 109

  • Each value appears exactly twice, except the answer, which appears once.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

One integer did the work of a dict. A list of one item works because 0 ^ x is x. A single value of 0 works because every pair cancels and result stays 0. Negative numbers work because x ^ x is 0 for every integer, negative or not.

Counting the 1 bits

How many 1s does 44 have? Written out, 44 is 32 + 8 + 4, which is 101100: three 1s. A loop could check all six bits with x & 1 and x >> 1. A faster loop jumps from one 1 to the next, using one fact: x & (x - 1) is x with its lowest 1 bit turned off. (The lowest 1 bit is the rightmost 1. Many problems call a 1 bit a set bit.)

Why: subtracting 1 borrows from the lowest 1. In decimal, 500 − 1 is 499: the lowest digit that is not 0 drops by one, and every 0 to its right becomes the largest digit, 9. In binary the largest digit is 1, so 44 − 1 turns 101100 into 101011. The lowest 1 becomes 0, every 0 below it becomes 1, and the bits above it do not change. Then & keeps only the 1s both numbers share. Everything above survives, the lowest 1 is gone, and the bits below were 0 in x, so they stay 0.

The instrument shows 44 and 43 lined up with & chosen. Before you read the result row, work out 44 & 43 from 101100 and 101011.

A power of two (1, 2, 4, 8 and so on) has exactly one 1 bit, so removing it leaves 0. That gives a one-line test for powers of two. Turn away 0 first: it has no 1 bits at all, so 0 & (0 - 1) is 0 too. The usual guard, x <= 0, also turns away negative numbers, and no power of two is negative.

Put in orderIs it a power of two?

Put the lines in order to build is_power_of_two(x), which returns True when x is 1, 2, 4, 8 and so on, and False otherwise, including for 0 and negative numbers. Indentation is already part of each line. Two of the lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • if x < 0:
    • return (x & (x + 1)) == 0
    • if x <= 0:
    • def is_power_of_two(x):
    • return (x & (x - 1)) == 0
    • return False

    Counting the 1s is the same move in a loop: turn off the lowest 1 until nothing is left, and count the turns. Guess first: how many times does the loop body run for 44?

    Step throughRemove the lowest 1 until nothing is left
    Step 1 of 14
    Line 1 is about to run.
    44 is 101100 in binary.
    x = 44
    count = 0
    while x > 0:
    x = x & (x - 1)
    count += 1
    print(count)
    Names
    no names yet
    Output
    (nothing printed yet)

    This loop is the practice problem Count the 1 bits. Here, combine it with XOR: the number of places where two numbers differ is the number of 1s in their XOR. That count is called the Hamming distance.

    Code itCount the places that differ

    Write hamming_distance(x, y), which returns the number of bit positions where x and y differ. 1 is 001 and 4 is 100, so they differ in two places. Both numbers are 0 or more. Then press Watch it run to see the notebook change.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

    Now count the 1s of every number from 0 to n. Running the loop on each number works. The faster idea reuses work: the bits of i are the bits of i >> 1 with one more bit on the end, and that last bit is i & 1. 13 is 1101; 13 >> 1 is 6, which is 110; and 13 & 1 is 1. So the count for 13 is the count for 6, plus 1. If you fill the counts in increasing order, the count for i >> 1 is always ready, because i >> 1 is smaller than i for every i of 1 or more. Here are 0 to 7. Cover the last column and fill it yourself, reading each count from the row that i >> 1 names:

    ibinaryi >> 1i & 1count
    00000, the start
    11010 + 1 = 1
    210101 + 0 = 1
    311111 + 1 = 2
    4100201 + 0 = 1
    5101211 + 1 = 2
    6110302 + 0 = 2
    7111312 + 1 = 3

    Row 7 reads row 3, which reads row 1, which reads row 0. Every row reads a row above it, already filled. Now write it.

    easyBits and mathDynamic programming, 1D target 15 min

    Count the 1 bits from 0 to n

    For every whole number from 0 up to n (n is 0 or more), count the 1s in its binary form. Return those counts as a list counts in that order, so the list has n + 1 items and the item at position i is the count for i.

    Binary is base 2: each digit, called a bit, is 0 or 1 and is worth a power of two, 1, 2, 4, 8 and so on from the right. 6 is 110 in binary (4 + 2), so counts[6] is 2.

    Counting the bits of each number on its own is correct and passes the tests. Aim for one step per number by reusing a count you have already found.

    Example 1
    Inputn = 4Output[0, 1, 1, 2, 1]

    0 to 4 in binary are 0, 1, 10, 11 and 100, with 0, 1, 1, 2 and 1 ones.

    Example 2
    Inputn = 7Output[0, 1, 1, 2, 1, 2, 2, 3]

    5 is 101 and 6 is 110, two 1s each. 7 is 111, three 1s.

    Example 3
    Inputn = 0Output[0]

    One number, 0, with no 1s.

    Constraints
    • 0 ≤ n ≤ 105

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Each count is one lookup and one addition, so the whole list is O(n): the table idea from module 12, where each cell is built from a smaller cell already filled.

    Recap: x & (x - 1) turns off the lowest 1. Repeat it to count 1s in one pass per 1 bit; apply it once to test for a power of two. To count every number up to n, reuse the count of i >> 1.

    The missing number: what the total should be

    A loader expects sensor ids 1 to 5, and one never arrives: [3, 1, 5, 2]. You know what the total should be before you read a single id. 1 + 2 + 3 + 4 + 5 = 15, the ids that arrived add up to 11, and the missing id is 15 − 11 = 4.

    The sum 1 + 2 + ... + n is n(n + 1) / 2. To see why, write the numbers forward, and backward underneath. For n = 5:

    forward12345
    backward54321
    column sum66666

    Every column adds to n + 1, and there are n columns, so the two rows hold n(n + 1) and one row holds half of that. For n = 5: 5 × 6 = 30, and half is 15. In code, use // so the result stays an int: n(n + 1) is always even, because one of two neighboring numbers is even, so // divides it exactly. Guess before you step: which values does actual take?

    Step throughThe id that never arrived
    Step 1 of 15
    Line 1 is about to run.
    Ids 1 to 5 were sent. One never arrived.
    ids = [3, 1, 5, 2]
    n = len(ids) + 1
    expected = n * (n + 1) // 2
    actual = 0
    for x in ids:
    actual += x
    print(expected - actual)
    Names
    no names yet
    Output
    (nothing printed yet)
    Work it outThe total that falls short

    A list holds every whole number from 0 to 20 except one. Its items add up to 197. Which number is missing?

    missing number

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    Python integers do not overflow. Many languages store an integer in a fixed number of bits. A 32-bit integer, such as Java's int, holds at most 2,147,483,647 (231 − 1), and a result past that overflows: it comes out wrong. The full total for n = 100,000 is 5,000,050,000, more than twice that limit. Python integers grow as needed:

    print(2 ** 31 - 1)              # 2147483647, the 32-bit limit
    print(100_000 * 100_001 // 2)   # 5000050000, still exact
    print(2 ** 64)                  # 18446744073709551616, all 20 digits

    When a total could pass 32 bits, say out loud that Python's integers grow, and name the fix in a fixed-size language: a 64-bit type, or the XOR version below.

    The problem is the same idea with the range 0 to n. Notice what changes.

    easyBits and math target 15 min

    The missing number

    Someone wrote down every whole number from 0 to n, each once, and then lost one of them. The list nums holds the n numbers that are left, in any order. Return the lost number as an int.

    You are not given n separately: n + 1 numbers minus the lost one leaves n, so n is len(nums).

    Checking each candidate from 0 to n with in is correct but fails the speed test. Aim for O(n) time and O(1) extra space. The tests can check only the time.

    Example 1
    Inputnums = [4, 2, 0, 1]Output3

    n is 4, so the values should be 0 to 4. 3 is not in the list.

    Example 2
    Inputnums = [1, 2]Output0

    n is 2, so the values should be 0, 1 and 2. 0 is missing.

    Example 3
    Inputnums = [0]Output1

    n is 1, so the values should be 0 and 1. The missing value can be n itself.

    Constraints
    • 1 ≤ n = len(nums) ≤ 105

    • 0 ≤ nums[i] ≤ n

    • All values in nums are different.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    The range starts at 0, so n is len(nums) itself, and 0 adds nothing to the full total. Neither end needs special code: when 0 is missing the two totals are equal, and when n is missing the gap is n.

    The XOR version keeps every number small. XOR together every number from 0 to n and every number in the list. Each value in the list meets its twin from the range and cancels, and only the missing value is left. On [3, 0, 1], n is 3, and 0 ^ 1 ^ 2 ^ 3 ^ 3 ^ 0 ^ 1 is 2. Every number involved is at most n, and XOR never makes a number with more bits than its inputs have, so it cannot overflow in any language. The problem's solution writes it out.

    Remainders and the greatest common divisor

    What is % good for, beyond odd and even? % gives the remainder, and two uses come up again and again. The first is wrapping around. In a ring of 5 seats numbered 0 to 4, walking 7 seats from seat 0 lands on seat 7 % 5, which is 2. Python's % always gives a result from 0 to 4 here, even for a negative step: -1 % 5 is 4, one seat behind seat 0.

    The second is keeping big numbers small. When a problem says "return the answer modulo 109 + 7" (modulo means the remainder after dividing by it), take % MOD after each addition or multiplication, with MOD = 10**9 + 7. The final remainder is the same as if you took it once at the end. Python would not overflow, but a huge number makes every operation slower.

    Predict this small version, with 7 in place of 109 + 7.

    PredictThe remainder at every step

    The loop multiplies 5, 6 and 4, but keeps only the remainder after dividing by 7 at each step. Type exactly what it prints.

    MOD = 7
    total = 1
    for x in [5, 6, 4]:
        total = total * x % MOD
        print(total)
    print(5 * 6 * 4 % MOD, -1 % MOD)
    

    Euclid's rule

    The greatest common divisor, gcd(a, b), is the largest number that divides both a and b with no remainder. The divisors of 18 are 1, 2, 3, 6, 9 and 18. Of those, 1, 2, 3 and 6 also divide 48, so gcd(48, 18) is 6. Problems use it to put a fraction in lowest terms: 18/48 is 3/8 after dividing top and bottom by 6.

    Listing divisors is slow. Euclid's rule is fast: gcd(a, b) equals gcd(b, a % b). The two pairs have exactly the same common divisors. With 48 and 18, 48 % 18 is 12, which is 48 − 2 × 18. Any number that divides 48 and 18 also divides 48 − 2 × 18 = 12, and any number that divides 18 and 12 also divides 2 × 18 + 12 = 48. Each step swaps in a smaller pair. When the second number reaches 0, the first one is the answer, because every number divides 0, so gcd(a, 0) is a. Guess the pairs before you step.

    Step throughEuclid's greatest common divisor
    Step 1 of 11
    Line 1 is about to run.
    def gcd(a, b):
    while b > 0:
    a, b = b, a % b
    return a
    Names
    no names yet
    Output
    (nothing printed yet)

    In Python, math.gcd(48, 18) returns 6. Know the call, and be ready to write the loop.

    On paperEuclid by hand

    On paper, run Euclid's rule on gcd(84, 36). Write each pair (a, b), then the next pair (b, a % b), until b is 0. Reveal one step at a time to check.

    Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.

    gcd(84, 36)

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    Last, say it the way you would in the room.

    Say itSay it like you would in the room

    An interviewer asks you to find the one value without a twin in a list where every other value appears twice. You describe a dict of counts, and they ask: "Can you do it without the extra memory?" Write what you would say: the dict version and its cost, then the XOR version with its walk, notebook, promise and cost.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: the module checkpoint