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

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

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; } } }