Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance bug in RandomizedQueue of 1-2-queues #7

Open
vladkinoman opened this issue Aug 29, 2019 · 0 comments
Open

Performance bug in RandomizedQueue of 1-2-queues #7

vladkinoman opened this issue Aug 29, 2019 · 0 comments
Labels
bug part 1 "Algorithms, Part I" course on Coursera timing

Comments

@vladkinoman
Copy link
Owner

Performance bug in RandomizedQueue of 1-2-queues

Description

Test case on Coursera says that StdRandom() should be called at most once per method (enqueue() and dequeue()). So, in this case I have a problem with current implementation because I use random enumeration to select non-empty (!null) items to dequeue them off.

To reproduce

Test 1: make n calls to enqueue() followed by n calls to dequeue();
count calls to StdRandom

  • n = 10

    • enqueue() and dequeue() should call StdRandom() at most once per item
    • number of items = 10
    • number of elementary StdRandom() operations = 14
  • n = 100

    • enqueue() and dequeue() should call StdRandom() at most once per item
    • number of items = 100
    • number of elementary StdRandom() operations = 154
  • n = 1000

    • enqueue() and dequeue() should call StdRandom() at most once per item
    • number of items = 1000
    • number of elementary StdRandom() operations = 1686

==> FAILED

A possible solution

Maybe it would be nice to copy non-empty (!null) items into a new array, instead of random enumeration, and then enumerate them uniformly at random. But in this case the implementantion might not support all operations in constant amortized time.

Methods that need to be changed: dequeue(), sample(), resize() and RandomizedQueueIterator() constructor. If we don't want to keep track head and tail, enqueue() could be changed in the next lines of code:

if (count == resizingArray.length || tail == resizingArray.length)
            resize(2 * resizingArray.length);
@vladkinoman vladkinoman added bug part 1 "Algorithms, Part I" course on Coursera timing labels Aug 29, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug part 1 "Algorithms, Part I" course on Coursera timing
Projects
None yet
Development

No branches or pull requests

1 participant