Search code examples
javatime-complexitybitbitset

What is the Time Complexity of Set operation of a BitSet in java?


I have a Scenario where I have to set a range of BitSet index to 1. So if I use

   /*
    *Code snippet
    */
    BitSet myBitSet = new BitSet(100);
    myBitSet.set(10, 50);

    //**************************

What would be the time complexity for above code? will it iterate through 40 elements or some kind of bit operation will be performed?


Solution

  • For a single bit it will be O(1), the complexity for setting n bits is O(N).

    For the sceptics: setting n bits is O(N), because setting 10_000 bits takes about 10 times longer than setting 1_000 bits.

    That said, it is more effecient to call myBitSet.set(10,50) than to write for (int i=10; i<=50; i++) myBitSet.set(i);