Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching for first set bit in a huge bitmap

Tags:

c

Interview question:

In a parking slot which can hold million cars, you need to find a free parking slot. There is no condition on where the slot could be, i.e., the parking lot can have multiple entrances and finding a slot near the entrance, etc., does not matter. The question was what kind of data structure should be used and what would be complexity of various operations.

I suggested using a bit array of million bits, with 0/1 for taken/free slot, so for finding free spot the question translated to finding first set bit. Do not assume anything about how many cars are there, etc., i.e., the bit array could be sparse or dense.

What is the fastest way to find a set bit in a huge bitmap? I did suggest binary search + efficient ffs() per word as the scheme.

like image 482
sandeep Avatar asked Jul 20 '12 14:07

sandeep


People also ask

How to find first bit set?

In computer software and hardware, find first set (ffs) or find first one is a bit operation that, given an unsigned machine word, designates the index or position of the least significant bit set to one in the word counting from the least significant bit position.

What is a Setbit?

Set bits in a binary number is represented by 1. Whenever we calculate the binary number of an integer value then it is formed as the combination of 0's and 1's. So, the digit 1 is known as set bit in the terms of the computer.


1 Answers

A million 32-bit integers require about 4MB of memory. So I'd say you keep a list of free slots. Whenever a car enters, you take an item off the list and assign that. Whenever a car leaves, you put the freed slot number into the list.

As you'd only ever be manipulating the end of the list (so this is in fact used as a stack or LIFO structure), this gives you optimal O(1) performance both for finding a free slot and for returning a slot to free state. If you do this on a low level with a raw chunk of memory, you'll need a pointer indicating the current end of the list. Finding a slot decrements that pointer and returns its value. Returning a slot assigns to the pointer and increments it afterwards.

If you decide to add additional requirements later on, you could do some manipulation of your data, e.g. turn it into a heap. With a big map of 0/1 bits, such extensions wouldn't be possible.

like image 125
MvG Avatar answered Oct 01 '22 15:10

MvG