I came across below interview question and I am working on it:
Build a queue class with the enqueue and dequeue methods. The queue can store an UNLIMITED number of elements but you are limited to using arrays that can store up to 5 elements max.
Here is what I was able to come up with. Is this the right way to do it in the interview or is there any better way we should implement in the interview?
class Solution { private final List<List<Integer>> array; public Solution() { this.array = new ArrayList<>(); } public void enqueue(int value) { if(array.isEmpty()) { List<Integer> arr = new ArrayList<>(); arr.add(value); array.add(arr); return; } if(array.get(array.size() - 1).size() != 5) { array.get(array.size() - 1).add(value); return; } List<Integer> arr = new ArrayList<>(); arr.add(value); array.add(arr); return; } public int dequeue() { if(array.isEmpty()) { return -1; } for(List<Integer> l : array) { for(int i=0; i<l.size(); i++) { return l.remove(i); } } return -1; } }
array
will contain more than 5 elements if the queue has more than 25 elements.\$\endgroup\$