Maps app~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-191bit-manipulation
A map service stores each map tile with a flag word. Each bit of the word is a yes or no fact about the tile: it has a road, a bridge, a one-way street, and so on. A tile uses at most 19 flags.
A data check marks a tile as suspect when its word has an odd number of flags set, which is an odd number of 1 bits. Your team lead asks: "How many tiles are suspect?"
Write odd_flag_tiles(words).
words is the list of flag words, one for each tile.Input: words = [5, 7, 8, 12]
Output: 2Write each word in binary and count its 1 bits. Two words have an odd count.
| Word | Binary | 1 bits | Odd? |
|---|---|---|---|
| 5 | 101 | 2 | no |
| 7 | 111 | 3 | yes |
| 8 | 1000 | 1 | yes |
| 12 | 1100 | 2 | no |
Input: words = [0]
Output: 0The word 0 has no flags, and 0 is even, so no tile is suspect.
Input: words = [3, 8]
Output: 1The word 3 is odd as a number, but it has two 1 bits, which is even. The word 8 has one 1 bit, so only 8 is suspect.
1 ≤ len(words) ≤ 700,0000 ≤ words[i] ≤ 524,287Testing every one of 64 bit positions of every word costs 44,800,000 steps for 700,000 words. Only the parity of the count matters, not the count. Folding a word onto itself with 5 shifts and XORs gives the parity in 5 steps, so the whole list costs about 3,500,000 steps.