SlideShare a Scribd company logo
1 of 8
Download to read offline
Works Applications Programming Assignment
Chinmay Chauhan, 09005010, IIT-Bombay
Interface1 Implementation (ExamPeekableQueue):
File: ExamPeekableQueue.java
package jp.co.worksapp.recruiting;
public interface ExamPeekableQueue<E extends Comparable<E>> {
public void enqueue(E e);
public E dequeue();
public E peekMedian();
public E peekMaximum();
public E peekMinimum();
public int size();
}
I have used 2 approaches to solve the problem. Below is the code and logic used for both approaches.
Approach #1: We maintain a sorted list of elements in queue. For enqueue, whenever we insert an element in
queue, we find the correct location of that element in the sorted List using binarySearch and insert it at that
location. As per java documentation, ArrayList.add operation takes amortized O(1) time, binary search takes
O(lgN) time where N is the number of elements in the queue, so overall complexity of insertion is O(lgN)
amortized, and O(N) worst case. Same complexity holds for dequeue operation. So we have O(lgN) amortized
time for enqueue and dequeue operation, but worst case is O(N). Finding minimum, maximum and median once
we have a sorted list is O(1) worst case.
Code for Approach #1 (File: ExamPeekableQueueImpl.java)
package jp.co.worksapp.recruiting;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
public class ExamPeekableQueueImpl<E extends Comparable<E>> implements ExamPeekableQueue<E>{
private List<E> queue;
// For storing queue elements in sorted Order for efficiently getting Min, Max, Median
private List<E> sortedQueue;
public ExamPeekableQueueImpl(){
queue = new ArrayList<E>();
sortedQueue = new ArrayList<E>();
}
@Override
public void enqueue(E e){
if (e == null) {
throw new IllegalArgumentException();
}
queue.add(e); // Adds e to the tail of queue
int index = Collections.binarySearch(sortedQueue, e);
if (index < 0) { // Element e is not present in the queue
sortedQueue.add(-index - 1, e);
} else { // Element e is present in the queue
sortedQueue.add(index + 1, e);
}
}
@Override
public E dequeue(){
if (queue.isEmpty()) {
throw new NoSuchElementException();
}
E e = queue.get(0);
queue.remove(0);
int index = Collections.binarySearch(sortedQueue, e);
sortedQueue.remove(index); // Remove e from sortedQueue
return e;
}
@Override
public E peekMedian(){
if (queue.isEmpty()) {
throw new NoSuchElementException();
}
int size = this.size();
return sortedQueue.get(size/2);
}
@Override
public E peekMaximum(){
if (queue.isEmpty()) {
throw new NoSuchElementException();
}
int size = this.size();
return sortedQueue.get(size-1);
}
@Override
public E peekMinimum(){
if (queue.isEmpty()) {
throw new NoSuchElementException();
}
return sortedQueue.get(0);
}
@Override
public int size(){
return queue.size();
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append("[ ");
for (E e : queue) {
s.append(e + " ");
}
s.append("]");
s.append(" [ ");
for (E e : sortedQueue) {
s.append(e + " ");
}
s.append("]");
return s.toString();
}
}
Approach #2: We maintain 2 TreeSets, 1st
one contains N/2 (or N/2 + 1) smallest elements and 2nd
one contains
the rest. If we maintain this invariant throughout, we see that median has to be either the Largest element of
TreeSet1 or the smallest element of TreeSet2. Enqueue & Dequeue both operation take O(lgN) time since
inserting or deleting elements from any TreeSet of size N is O(lgN). Even in this case, the maximum, minimum
and median operation needs O(1) time. So we have significantly improved our complexity. However, since Java
TreeSet doesn’t support duplicates, so our code works only for distinct elements. If Java had a implementation
of MultiSet, then we could have support for non-distinct elements too.
Code for Approach #2 (File: ExamPeekableQueueImpl.java)
package jp.co.worksapp.recruiting;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.TreeSet;
public class ExamPeekableQueueImpl<E extends Comparable<E>> implements ExamPeekableQueue<E>{
private List<E> queue;
private TreeSet<E> left;
private TreeSet<E> right;
public ExamPeekableQueueImpl(){
queue = new ArrayList<E>();
left = new TreeSet<E>();
right= new TreeSet<E>();
}
@Override
public void enqueue(E e){
if (e == null) {
throw new IllegalArgumentException();
}
queue.add(e);
if(left.isEmpty()){ // We are adding the first element
left.add(e);
return;
}
if (left.size() == 1 && right.size() == 0) {
if (e.compareTo(left.last()) == -1) {
right.add(left.last());
left.remove(left.last());
left.add(e);
}
else {
right.add(e);
}
return;
}
if(e.compareTo(left.last()) == -1 || e.compareTo(left.last()) == 0){ // Less or Equal
if (left.size() == right.size()) {
left.add(e);
}
else if (left.size() == right.size()+1) {
right.add(left.last());
left.remove(left.last());
left.add(e);
}
}
else if (e.compareTo(left.last()) == 1 && e.compareTo(right.first()) == -1) {
if (left.size() == right.size()){
left.add(e);
}
else if (left.size() == right.size()+1) {
right.add(e);
}
}
else {
if (left.size() == right.size()) {
left.add(right.first());
right.remove(right.first());
right.add(e);
}
else if (left.size() == right.size()+1) {
right.add(e);
}
}
}
@Override
public E dequeue(){
if (queue.isEmpty()) {
throw new NoSuchElementException();
}
E e = queue.get(0);
// Maintain the invariant (left.size - right.size) == 0 / 1
if(e.compareTo(left.last()) == -1 || e.compareTo(left.last()) == 0){ // Less or Equal
if (left.size() == right.size()) {
left.add(right.first());
left.remove(e);
right.remove(right.first());
}
else if (left.size() == right.size()+1) {
left.remove(e);
}
}
else {
if (left.size() == right.size()) {
right.remove(e);
}
else if (left.size() == right.size() + 1){
right.remove(e);
right.add(left.last());
left.remove(left.last());
}
}
// Remove element from FIFO queue
queue.remove(0);
// If queue is empty, empty left and right TreeSets
if (queue.isEmpty()) {
if (!left.isEmpty()) left.remove(0);
if (!right.isEmpty()) right.remove(0);
}
return e;
}
@Override
public E peekMedian(){
if (queue.isEmpty()) {
throw new NoSuchElementException();
}
if((left.size()+right.size())%2 == 0) return right.first();
else return left.last();
}
@Override
public E peekMaximum(){
if (queue.isEmpty()) {
throw new NoSuchElementException();
}
if(right.isEmpty()) return left.last();
else return right.last();
}
@Override
public E peekMinimum(){
if (queue.isEmpty()) {
throw new NoSuchElementException();
}
return left.first();
}
@Override
public int size(){
return queue.size();
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append("[ ");
for (E e : queue) {
s.append(e + " ");
}
s.append("]");
s.append(" [ ");
for (E e : left) {
s.append(e + " ");
}
s.append("]");
s.append(" [ ");
for (E e : right) {
s.append(e + " ");
}
s.append("]");
return s.toString();
}
}
Interface2 Implementation (ExamImmutableQueue):
Approach: We maintain 2 pointers enqueueHead, dequeueHead. We permanently add elements to the queue
using addElement(e) function. Functions enqueue(), dequeue(), peek() do not modify the queue and their
complexity is O(1) amortized. If we enqueue, elements are always appended at the start of enqueueHead list. If
while dequeuing, the dequeueHead is pointing to null, we move all elements from enqueueHead to
dequeueHead in the reverse Order. (More logic is explained as comments in source files)
File: ExamImmutableQueue.java
package jp.co.worksapp.recruiting;
public interface ExamImmutableQueue<E> {
public ExamImmutableQueue<E> enqueue(E e);
public ExamImmutableQueue<E> dequeue();
public E peek();
public int size();
}
File: ExamImmutableQueueImpl.java
package jp.co.worksapp.recruiting;
import java.util.NoSuchElementException;
/*
* Logic Used : We maintain 2 pointers enqueueHead, dequeueHead.
* We permanently add elements to the queue using addElement(e) function.
* Function enqueue/dequeue do not modify/mutate the queue.
* Functions enqueue(e) and dequeue() have O(1) amortized time complexity.
*
* If we enqueue, elements are always appended at the start of enqueueHead List, so
* if enqueueHead -> 3->2->1, and we do enqueueHead(10), then we return the appropriate
* pointer to 10->3->2->1, but DO NOT modify enqueueHead. So enqueueHead is still pointing to 3->2-
>1
* So enqueue(e) needs O(1) time in every case.
*
* If while dequeuing, the dequeueHead is pointing to null, we move all elements from
* enqueueHead to dequeueHead in the reverse Order.
* Eg. say enqueueHead -> 3->2->1, dequeueHead -> null, then on calling dequeue(),
* enqueueHead -> null, dequeueHead -> 1->2->3, so now dequeueHead points to the first
* element of queue. Only in this specific case we need O(N) time for dequeue(), in all
* other cases dequeue() is O(1). Hence the overall time complexity is O(1) amortized
*
* For peek(), if dequeueHead is not empty, then we return the first element that dequeueHead
* points to. Otherwise, we move all elements from enqueueHead list to dequeueHead (in reverse,
* and then return the first element that dequeueHead points to.
* Hence peek() has O(1) amortized time complexity.
*/
public class ExamImmutableQueueImpl<E> implements ExamImmutableQueue<E> {
class Node<T> {
public T data;
public Node<T> next;
public Node(T t){data = t; next = null;}
}
private Node<E> enqueueHead;
private Node<E> dequeueHead;
private int size;
public ExamImmutableQueueImpl() {
enqueueHead = null;
dequeueHead = null;
size = 0;
}
public ExamImmutableQueueImpl(Node<E> e, Node<E> d, int sz) {
enqueueHead = e;
dequeueHead = d;
size = sz;
}
@Override
public ExamImmutableQueue<E> enqueue(E e){
if (e == null) {
throw new IllegalArgumentException();
}
Node<E> temp = new Node<E>(e);
temp.next = enqueueHead;
return new ExamImmutableQueueImpl<E> (temp, dequeueHead, size+1);
}
@Override
public ExamImmutableQueue<E> dequeue(){
if (dequeueHead == null && enqueueHead == null){
throw new NoSuchElementException();
}
if(dequeueHead != null){
return new ExamImmutableQueueImpl<E> (enqueueHead, dequeueHead.next, size-1);
}
else {
while(enqueueHead != null){
Node<E> temp = new Node<E>(enqueueHead.data);
temp.next = dequeueHead;
dequeueHead = temp;
enqueueHead = enqueueHead.next;
}
return new ExamImmutableQueueImpl<E>(enqueueHead, dequeueHead.next, size-1);
}
}
// To permanently add some elements to the queue
public void addElement(E e) {
Node<E> temp = new Node<E>(e);
temp.next = enqueueHead;
enqueueHead = temp;
size++;
}
@Override
public E peek(){
if (enqueueHead == null && dequeueHead == null){
throw new NoSuchElementException();
}
else if (dequeueHead != null){
return dequeueHead.data;
}
else { // Move all elements of enqueueHead to dequeueHead in reverse order
while(enqueueHead != null){
Node<E> temp = new Node<E>(enqueueHead.data);
temp.next = dequeueHead;
dequeueHead = temp;
enqueueHead = enqueueHead.next;
}
return dequeueHead.data;
}
}
@Override
public int size(){
return size;
}
// For checking contents of the queue, Printing the queue contents
public String toString() {
if (dequeueHead != null) { // Print dequeueHead before enqueueHead
String s = "";
s = "[ " + s;
Node<E> tmp = dequeueHead;
while (tmp != null) {
s = s + tmp.data + " ";
tmp = tmp.next;
}
String t = "";
tmp = enqueueHead;
while (tmp != null) {
t = tmp.data + " " + t;
tmp = tmp.next;
}
s = s+t + "]";
return s;
}
else { // Since dequeueHead is null, just print enqueueHead in reverse
String s = "";
Node<E> tmp = enqueueHead;
while (tmp != null) {
s = tmp.data + " " + s;
tmp = tmp.next;
}
s = "[ " + s + "]";
return s;
}
}
}

More Related Content

What's hot

Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2Technopark
 
Java 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR BeneluxJava 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR Beneluxyohanbeschi
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstituteSuresh Loganatha
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)Alok Kumar
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIjagriti srivastava
 
An Introduction to Property Based Testing
An Introduction to Property Based TestingAn Introduction to Property Based Testing
An Introduction to Property Based TestingC4Media
 
Java Puzzle
Java PuzzleJava Puzzle
Java PuzzleSFilipp
 
Groovy 1.8の新機能について
Groovy 1.8の新機能についてGroovy 1.8の新機能について
Groovy 1.8の新機能についてUehara Junji
 
The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180Mahmoud Samir Fayed
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL fileRACHIT_GUPTA
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Uehara Junji
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 

What's hot (20)

Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
 
Java 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR BeneluxJava 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR Benelux
 
Java programs
Java programsJava programs
Java programs
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstitute
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
An Introduction to Property Based Testing
An Introduction to Property Based TestingAn Introduction to Property Based Testing
An Introduction to Property Based Testing
 
Java Puzzlers
Java PuzzlersJava Puzzlers
Java Puzzlers
 
Akka
AkkaAkka
Akka
 
Java puzzles
Java puzzlesJava puzzles
Java puzzles
 
Java Puzzle
Java PuzzleJava Puzzle
Java Puzzle
 
Groovy 1.8の新機能について
Groovy 1.8の新機能についてGroovy 1.8の新機能について
Groovy 1.8の新機能について
 
The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180The Ring programming language version 1.5.1 book - Part 31 of 180
The Ring programming language version 1.5.1 book - Part 31 of 180
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
Guice2.0
Guice2.0Guice2.0
Guice2.0
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 

Viewers also liked

Increasing Resilience towards Floods in Mumbai city
Increasing Resilience towards Floods in Mumbai cityIncreasing Resilience towards Floods in Mumbai city
Increasing Resilience towards Floods in Mumbai cityChinmay Chauhan
 
An Introduction to Saville Comprehension Aptitude
An Introduction to Saville Comprehension Aptitude An Introduction to Saville Comprehension Aptitude
An Introduction to Saville Comprehension Aptitude JobTestPrep
 
An Introduction to Saville Analysis Aptitude
An Introduction to Saville Analysis Aptitude An Introduction to Saville Analysis Aptitude
An Introduction to Saville Analysis Aptitude JobTestPrep
 
Strategic Analysis of Microsoft Corp. (2014)
Strategic Analysis of Microsoft Corp. (2014)Strategic Analysis of Microsoft Corp. (2014)
Strategic Analysis of Microsoft Corp. (2014)Chinmay Chauhan
 
Software Testing Life Cycle
Software Testing Life CycleSoftware Testing Life Cycle
Software Testing Life CycleUdayakumar Sree
 
Public transport problems in mumbai
Public transport problems in mumbaiPublic transport problems in mumbai
Public transport problems in mumbaiaziz khan
 
Software testing life cycle
Software testing life cycleSoftware testing life cycle
Software testing life cycleGaruda Trainings
 

Viewers also liked (7)

Increasing Resilience towards Floods in Mumbai city
Increasing Resilience towards Floods in Mumbai cityIncreasing Resilience towards Floods in Mumbai city
Increasing Resilience towards Floods in Mumbai city
 
An Introduction to Saville Comprehension Aptitude
An Introduction to Saville Comprehension Aptitude An Introduction to Saville Comprehension Aptitude
An Introduction to Saville Comprehension Aptitude
 
An Introduction to Saville Analysis Aptitude
An Introduction to Saville Analysis Aptitude An Introduction to Saville Analysis Aptitude
An Introduction to Saville Analysis Aptitude
 
Strategic Analysis of Microsoft Corp. (2014)
Strategic Analysis of Microsoft Corp. (2014)Strategic Analysis of Microsoft Corp. (2014)
Strategic Analysis of Microsoft Corp. (2014)
 
Software Testing Life Cycle
Software Testing Life CycleSoftware Testing Life Cycle
Software Testing Life Cycle
 
Public transport problems in mumbai
Public transport problems in mumbaiPublic transport problems in mumbai
Public transport problems in mumbai
 
Software testing life cycle
Software testing life cycleSoftware testing life cycle
Software testing life cycle
 

Similar to Works Applications Test - Chinmay Chauhan

import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdfimport java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdfStewart29UReesa
 
The enqueue operation on the Queue ADT adds a new item to the back of (1).docx
The enqueue operation on the Queue ADT adds a new item to the back of (1).docxThe enqueue operation on the Queue ADT adds a new item to the back of (1).docx
The enqueue operation on the Queue ADT adds a new item to the back of (1).docxcarold11
 
import java-util--- public class MyLinkedList{ public static void.pdf
import java-util---  public class MyLinkedList{    public static void.pdfimport java-util---  public class MyLinkedList{    public static void.pdf
import java-util--- public class MyLinkedList{ public static void.pdfasarudheen07
 
output and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdfoutput and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdfaccess2future1
 
computer notes - Priority queue
computer notes -  Priority queuecomputer notes -  Priority queue
computer notes - Priority queueecomputernotes
 
i am looking for help on the method AddSorted and the method Copy only.pdf
i am looking for help on the method AddSorted and the method Copy only.pdfi am looking for help on the method AddSorted and the method Copy only.pdf
i am looking for help on the method AddSorted and the method Copy only.pdfsonunotwani
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
 
For this micro assignment, you must implement two Linked List functi.docx
For this micro assignment, you must implement two Linked List functi.docxFor this micro assignment, you must implement two Linked List functi.docx
For this micro assignment, you must implement two Linked List functi.docxmckellarhastings
 
SOURCE CODEimport java.util.Iterator;public class CircularLinke.pdf
SOURCE CODEimport java.util.Iterator;public class CircularLinke.pdfSOURCE CODEimport java.util.Iterator;public class CircularLinke.pdf
SOURCE CODEimport java.util.Iterator;public class CircularLinke.pdfarccreation001
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfkostikjaylonshaewe47
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdffreddysarabia1
 
public class TrequeT extends AbstractListT { .pdf
  public class TrequeT extends AbstractListT {  .pdf  public class TrequeT extends AbstractListT {  .pdf
public class TrequeT extends AbstractListT { .pdfinfo30292
 
UserInputHandlerjava package midterm2023 import javautil.pdf
UserInputHandlerjava package midterm2023 import javautil.pdfUserInputHandlerjava package midterm2023 import javautil.pdf
UserInputHandlerjava package midterm2023 import javautil.pdfadityknits
 
I cant figure out why I keep getting an -Exception in thread -main- ja.pdf
I cant figure out why I keep getting an -Exception in thread -main- ja.pdfI cant figure out why I keep getting an -Exception in thread -main- ja.pdf
I cant figure out why I keep getting an -Exception in thread -main- ja.pdfGordonF2XPatersonh
 
In java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfIn java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfaromalcom
 
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docxJAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docxGavinUJtMathist
 
JVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's TricksJVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's TricksDoug Hawkins
 

Similar to Works Applications Test - Chinmay Chauhan (20)

import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdfimport java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
 
The enqueue operation on the Queue ADT adds a new item to the back of (1).docx
The enqueue operation on the Queue ADT adds a new item to the back of (1).docxThe enqueue operation on the Queue ADT adds a new item to the back of (1).docx
The enqueue operation on the Queue ADT adds a new item to the back of (1).docx
 
import java-util--- public class MyLinkedList{ public static void.pdf
import java-util---  public class MyLinkedList{    public static void.pdfimport java-util---  public class MyLinkedList{    public static void.pdf
import java-util--- public class MyLinkedList{ public static void.pdf
 
output and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdfoutput and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdf
 
computer notes - Priority queue
computer notes -  Priority queuecomputer notes -  Priority queue
computer notes - Priority queue
 
i am looking for help on the method AddSorted and the method Copy only.pdf
i am looking for help on the method AddSorted and the method Copy only.pdfi am looking for help on the method AddSorted and the method Copy only.pdf
i am looking for help on the method AddSorted and the method Copy only.pdf
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
 
For this micro assignment, you must implement two Linked List functi.docx
For this micro assignment, you must implement two Linked List functi.docxFor this micro assignment, you must implement two Linked List functi.docx
For this micro assignment, you must implement two Linked List functi.docx
 
SOURCE CODEimport java.util.Iterator;public class CircularLinke.pdf
SOURCE CODEimport java.util.Iterator;public class CircularLinke.pdfSOURCE CODEimport java.util.Iterator;public class CircularLinke.pdf
SOURCE CODEimport java.util.Iterator;public class CircularLinke.pdf
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
 
Lec3
Lec3Lec3
Lec3
 
public class TrequeT extends AbstractListT { .pdf
  public class TrequeT extends AbstractListT {  .pdf  public class TrequeT extends AbstractListT {  .pdf
public class TrequeT extends AbstractListT { .pdf
 
UserInputHandlerjava package midterm2023 import javautil.pdf
UserInputHandlerjava package midterm2023 import javautil.pdfUserInputHandlerjava package midterm2023 import javautil.pdf
UserInputHandlerjava package midterm2023 import javautil.pdf
 
Lec3
Lec3Lec3
Lec3
 
I cant figure out why I keep getting an -Exception in thread -main- ja.pdf
I cant figure out why I keep getting an -Exception in thread -main- ja.pdfI cant figure out why I keep getting an -Exception in thread -main- ja.pdf
I cant figure out why I keep getting an -Exception in thread -main- ja.pdf
 
In java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfIn java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdf
 
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docxJAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
 
JVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's TricksJVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's Tricks
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 

Recently uploaded

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 

Recently uploaded (20)

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 

Works Applications Test - Chinmay Chauhan

  • 1. Works Applications Programming Assignment Chinmay Chauhan, 09005010, IIT-Bombay Interface1 Implementation (ExamPeekableQueue): File: ExamPeekableQueue.java package jp.co.worksapp.recruiting; public interface ExamPeekableQueue<E extends Comparable<E>> { public void enqueue(E e); public E dequeue(); public E peekMedian(); public E peekMaximum(); public E peekMinimum(); public int size(); } I have used 2 approaches to solve the problem. Below is the code and logic used for both approaches. Approach #1: We maintain a sorted list of elements in queue. For enqueue, whenever we insert an element in queue, we find the correct location of that element in the sorted List using binarySearch and insert it at that location. As per java documentation, ArrayList.add operation takes amortized O(1) time, binary search takes O(lgN) time where N is the number of elements in the queue, so overall complexity of insertion is O(lgN) amortized, and O(N) worst case. Same complexity holds for dequeue operation. So we have O(lgN) amortized time for enqueue and dequeue operation, but worst case is O(N). Finding minimum, maximum and median once we have a sorted list is O(1) worst case. Code for Approach #1 (File: ExamPeekableQueueImpl.java) package jp.co.worksapp.recruiting; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; public class ExamPeekableQueueImpl<E extends Comparable<E>> implements ExamPeekableQueue<E>{ private List<E> queue; // For storing queue elements in sorted Order for efficiently getting Min, Max, Median private List<E> sortedQueue; public ExamPeekableQueueImpl(){ queue = new ArrayList<E>(); sortedQueue = new ArrayList<E>(); } @Override public void enqueue(E e){
  • 2. if (e == null) { throw new IllegalArgumentException(); } queue.add(e); // Adds e to the tail of queue int index = Collections.binarySearch(sortedQueue, e); if (index < 0) { // Element e is not present in the queue sortedQueue.add(-index - 1, e); } else { // Element e is present in the queue sortedQueue.add(index + 1, e); } } @Override public E dequeue(){ if (queue.isEmpty()) { throw new NoSuchElementException(); } E e = queue.get(0); queue.remove(0); int index = Collections.binarySearch(sortedQueue, e); sortedQueue.remove(index); // Remove e from sortedQueue return e; } @Override public E peekMedian(){ if (queue.isEmpty()) { throw new NoSuchElementException(); } int size = this.size(); return sortedQueue.get(size/2); } @Override public E peekMaximum(){ if (queue.isEmpty()) { throw new NoSuchElementException(); } int size = this.size(); return sortedQueue.get(size-1); } @Override public E peekMinimum(){ if (queue.isEmpty()) { throw new NoSuchElementException(); } return sortedQueue.get(0); } @Override public int size(){ return queue.size(); } public String toString() { StringBuilder s = new StringBuilder(); s.append("[ "); for (E e : queue) { s.append(e + " "); } s.append("]"); s.append(" [ ");
  • 3. for (E e : sortedQueue) { s.append(e + " "); } s.append("]"); return s.toString(); } } Approach #2: We maintain 2 TreeSets, 1st one contains N/2 (or N/2 + 1) smallest elements and 2nd one contains the rest. If we maintain this invariant throughout, we see that median has to be either the Largest element of TreeSet1 or the smallest element of TreeSet2. Enqueue & Dequeue both operation take O(lgN) time since inserting or deleting elements from any TreeSet of size N is O(lgN). Even in this case, the maximum, minimum and median operation needs O(1) time. So we have significantly improved our complexity. However, since Java TreeSet doesn’t support duplicates, so our code works only for distinct elements. If Java had a implementation of MultiSet, then we could have support for non-distinct elements too. Code for Approach #2 (File: ExamPeekableQueueImpl.java) package jp.co.worksapp.recruiting; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.TreeSet; public class ExamPeekableQueueImpl<E extends Comparable<E>> implements ExamPeekableQueue<E>{ private List<E> queue; private TreeSet<E> left; private TreeSet<E> right; public ExamPeekableQueueImpl(){ queue = new ArrayList<E>(); left = new TreeSet<E>(); right= new TreeSet<E>(); } @Override public void enqueue(E e){ if (e == null) { throw new IllegalArgumentException(); } queue.add(e); if(left.isEmpty()){ // We are adding the first element left.add(e); return; } if (left.size() == 1 && right.size() == 0) { if (e.compareTo(left.last()) == -1) { right.add(left.last()); left.remove(left.last()); left.add(e); } else { right.add(e); } return;
  • 4. } if(e.compareTo(left.last()) == -1 || e.compareTo(left.last()) == 0){ // Less or Equal if (left.size() == right.size()) { left.add(e); } else if (left.size() == right.size()+1) { right.add(left.last()); left.remove(left.last()); left.add(e); } } else if (e.compareTo(left.last()) == 1 && e.compareTo(right.first()) == -1) { if (left.size() == right.size()){ left.add(e); } else if (left.size() == right.size()+1) { right.add(e); } } else { if (left.size() == right.size()) { left.add(right.first()); right.remove(right.first()); right.add(e); } else if (left.size() == right.size()+1) { right.add(e); } } } @Override public E dequeue(){ if (queue.isEmpty()) { throw new NoSuchElementException(); } E e = queue.get(0); // Maintain the invariant (left.size - right.size) == 0 / 1 if(e.compareTo(left.last()) == -1 || e.compareTo(left.last()) == 0){ // Less or Equal if (left.size() == right.size()) { left.add(right.first()); left.remove(e); right.remove(right.first()); } else if (left.size() == right.size()+1) { left.remove(e); } } else { if (left.size() == right.size()) { right.remove(e); } else if (left.size() == right.size() + 1){ right.remove(e); right.add(left.last()); left.remove(left.last()); } } // Remove element from FIFO queue queue.remove(0); // If queue is empty, empty left and right TreeSets if (queue.isEmpty()) { if (!left.isEmpty()) left.remove(0); if (!right.isEmpty()) right.remove(0); }
  • 5. return e; } @Override public E peekMedian(){ if (queue.isEmpty()) { throw new NoSuchElementException(); } if((left.size()+right.size())%2 == 0) return right.first(); else return left.last(); } @Override public E peekMaximum(){ if (queue.isEmpty()) { throw new NoSuchElementException(); } if(right.isEmpty()) return left.last(); else return right.last(); } @Override public E peekMinimum(){ if (queue.isEmpty()) { throw new NoSuchElementException(); } return left.first(); } @Override public int size(){ return queue.size(); } public String toString() { StringBuilder s = new StringBuilder(); s.append("[ "); for (E e : queue) { s.append(e + " "); } s.append("]"); s.append(" [ "); for (E e : left) { s.append(e + " "); } s.append("]"); s.append(" [ "); for (E e : right) { s.append(e + " "); } s.append("]"); return s.toString(); } }
  • 6. Interface2 Implementation (ExamImmutableQueue): Approach: We maintain 2 pointers enqueueHead, dequeueHead. We permanently add elements to the queue using addElement(e) function. Functions enqueue(), dequeue(), peek() do not modify the queue and their complexity is O(1) amortized. If we enqueue, elements are always appended at the start of enqueueHead list. If while dequeuing, the dequeueHead is pointing to null, we move all elements from enqueueHead to dequeueHead in the reverse Order. (More logic is explained as comments in source files) File: ExamImmutableQueue.java package jp.co.worksapp.recruiting; public interface ExamImmutableQueue<E> { public ExamImmutableQueue<E> enqueue(E e); public ExamImmutableQueue<E> dequeue(); public E peek(); public int size(); } File: ExamImmutableQueueImpl.java package jp.co.worksapp.recruiting; import java.util.NoSuchElementException; /* * Logic Used : We maintain 2 pointers enqueueHead, dequeueHead. * We permanently add elements to the queue using addElement(e) function. * Function enqueue/dequeue do not modify/mutate the queue. * Functions enqueue(e) and dequeue() have O(1) amortized time complexity. * * If we enqueue, elements are always appended at the start of enqueueHead List, so * if enqueueHead -> 3->2->1, and we do enqueueHead(10), then we return the appropriate * pointer to 10->3->2->1, but DO NOT modify enqueueHead. So enqueueHead is still pointing to 3->2- >1 * So enqueue(e) needs O(1) time in every case. * * If while dequeuing, the dequeueHead is pointing to null, we move all elements from * enqueueHead to dequeueHead in the reverse Order. * Eg. say enqueueHead -> 3->2->1, dequeueHead -> null, then on calling dequeue(), * enqueueHead -> null, dequeueHead -> 1->2->3, so now dequeueHead points to the first * element of queue. Only in this specific case we need O(N) time for dequeue(), in all * other cases dequeue() is O(1). Hence the overall time complexity is O(1) amortized * * For peek(), if dequeueHead is not empty, then we return the first element that dequeueHead * points to. Otherwise, we move all elements from enqueueHead list to dequeueHead (in reverse, * and then return the first element that dequeueHead points to. * Hence peek() has O(1) amortized time complexity. */ public class ExamImmutableQueueImpl<E> implements ExamImmutableQueue<E> { class Node<T> { public T data; public Node<T> next; public Node(T t){data = t; next = null;} }
  • 7. private Node<E> enqueueHead; private Node<E> dequeueHead; private int size; public ExamImmutableQueueImpl() { enqueueHead = null; dequeueHead = null; size = 0; } public ExamImmutableQueueImpl(Node<E> e, Node<E> d, int sz) { enqueueHead = e; dequeueHead = d; size = sz; } @Override public ExamImmutableQueue<E> enqueue(E e){ if (e == null) { throw new IllegalArgumentException(); } Node<E> temp = new Node<E>(e); temp.next = enqueueHead; return new ExamImmutableQueueImpl<E> (temp, dequeueHead, size+1); } @Override public ExamImmutableQueue<E> dequeue(){ if (dequeueHead == null && enqueueHead == null){ throw new NoSuchElementException(); } if(dequeueHead != null){ return new ExamImmutableQueueImpl<E> (enqueueHead, dequeueHead.next, size-1); } else { while(enqueueHead != null){ Node<E> temp = new Node<E>(enqueueHead.data); temp.next = dequeueHead; dequeueHead = temp; enqueueHead = enqueueHead.next; } return new ExamImmutableQueueImpl<E>(enqueueHead, dequeueHead.next, size-1); } } // To permanently add some elements to the queue public void addElement(E e) { Node<E> temp = new Node<E>(e); temp.next = enqueueHead; enqueueHead = temp; size++; } @Override public E peek(){ if (enqueueHead == null && dequeueHead == null){ throw new NoSuchElementException(); } else if (dequeueHead != null){ return dequeueHead.data; } else { // Move all elements of enqueueHead to dequeueHead in reverse order while(enqueueHead != null){ Node<E> temp = new Node<E>(enqueueHead.data); temp.next = dequeueHead; dequeueHead = temp;
  • 8. enqueueHead = enqueueHead.next; } return dequeueHead.data; } } @Override public int size(){ return size; } // For checking contents of the queue, Printing the queue contents public String toString() { if (dequeueHead != null) { // Print dequeueHead before enqueueHead String s = ""; s = "[ " + s; Node<E> tmp = dequeueHead; while (tmp != null) { s = s + tmp.data + " "; tmp = tmp.next; } String t = ""; tmp = enqueueHead; while (tmp != null) { t = tmp.data + " " + t; tmp = tmp.next; } s = s+t + "]"; return s; } else { // Since dequeueHead is null, just print enqueueHead in reverse String s = ""; Node<E> tmp = enqueueHead; while (tmp != null) { s = tmp.data + " " + s; tmp = tmp.next; } s = "[ " + s + "]"; return s; } } }