UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 10.3 Free with a free account
Adding and Removing at Both Ends of a Sequence
Data Structures and Algorithms · Chapter 10: Stacks, Queues, and DequesSection 10.3 · lesson 41 of 8710 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Data Structures and Algorithms.
Lesson complete
Earn the 3 college credits for Data Structures and Algorithms
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Stack Applications: Expressions, Undo and Call Tracking →← Processing the Earliest Added Element FirstNext lesson: Stack Applications: Expressions, Undo and Call Tracking →
In this lesson
Double-ended queues with linked nodes, circular arrays, and ArrayDeque.
- Describe the deque operations at the first and last ends
- Implement a deque as a doubly linked list with sentinels and as a circular array
- Explain why doubling the array makes deque adds amortized constant time
- Use Java's ArrayDeque correctly as a stack or a queue
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,579 words). Read along, or search it.
Opening Question
A Fan of Playing Cards
Hold a hand of playing cards in a fan. You can slip a card in at either edge, or pull one out from either edge, but not from the middle. A stack works at one end only. A queue adds at one end, and removes at the other. A deque, pronounced deck, short for double-ended queue, drops the restriction. It can add, remove, and look, at both ends. So it can stand in for a stack or a queue. The puzzle is making all four add and remove operations constant time.
Definition
Deque Operations in Matching Pairs
A deque holds a sequence, from a first element to a last. Its operations come in matching pairs, one for each end. Add first and add last insert. Remove first and remove last take an element out and return it. On an empty deque, Java throws an exception. Peek first and peek last just look. And size and is empty report as usual. A plain array, with the first element pinned at index zero, can't keep up: adding at the front would slide every element one place right.
Implementation
A Doubly Linked Deque with Sentinels
The first design is a doubly linked list. Each node holds a value, a reference to the previous node, and one to the next. Two sentinel nodes, head and tail, sit before the first element and after the last. They never hold data. An empty deque is just the two sentinels, linked to each other. So every real node always has a neighbor on each side, and nothing needs a special case. Both adds are the same action: insert a node between two others. Add first inserts between head and the node after it. Add last inserts between the node before tail, and tail. Insert between rewires four links, and adds one to size. Removing is the mirror image. Unlink checks that the deque isn't empty, then makes a node's two neighbors point at each other. This test adds one and two at the back, then zero and minus one at the front. It removes one element from each end, then empties the deque, and tries one more removal. The lists print from first to last. Minus one leaves the front, two leaves the back, and the last removal throws a no such element exception. Every operation touches a fixed number of references, so each is order one. The price is memory: two extra references per element, and a new node on every add.
Implementation
A Circular Array with a Front Index
The second design is a circular array. Instead of pinning the first element at index zero, let it live anywhere. A variable, front, records its index, and size counts the elements. They occupy size slots in a row from front, wrapping to index zero, as if the array were a ring. Add last writes at front plus size, mod the length. Add first steps front one place backward, and writes there. That backward step adds the length before taking the remainder. In Java, minus one mod four is minus one, not three, so without it the index would go negative.
Growth
Copying in Reading Order
When the array is full, grow builds one twice as large. It copies the elements in reading order, starting from front, and resets front to zero. That straightens out a run that had wrapped around. Copy in plain index order instead, and the elements would come out scrambled.
Trace
A Capacity-Four Deque Wraps and Grows
Follow a deque of capacity four. Add last one, two and three. Front is zero, and one slot is free. Add first nine. Front steps back from zero and wraps to three, so nine sits in the last slot, and the run wraps around to index zero. Remove last returns three. Add last five fills that slot again, and the array is full. Now add last six. Grow doubles the array to eight slots, copies nine, one, two and five in reading order, and resets front to zero.
Quick Check
The Raw Array After Add First
Quick check. This ring has five slots, and starts empty. Add last puts in one and two. Then add first puts in seven, and then eight. The program prints the raw array, where an unused slot shows zero. What does it print? Pause and predict. It prints one, two, zero, eight, seven. Seven steps front back from zero to four, wrapping to the end. Eight steps back again, to three. Nothing moved: one and two never left slots zero and one. Eight, seven, one, two, zero is what a shifting array would hold. And one, two, seven, eight treats add first as if it were add last.
Analysis
Doubling Makes Adds Amortized Constant
One resize copies every element, which looks expensive. But the capacity doubles each time, so resizes are rare. Compare adding at the front of a plain array that shifts. Insert number k moves the k minus one elements already there, so ten thousand inserts make almost fifty million moves. The circular deque, starting at four slots, copies sixteen thousand, three hundred eighty elements in all: under two per add. The copies add up to four, plus eight, plus sixteen, and so on, which is less than twice the final size. So the average cost per add is constant: amortized order one.
Comparison
Linked Deque Versus Circular Array
So both designs give constant-time adds and removes, though the array's adds are amortized. The linked deque spends a node and two references per element, allocating on every add and freeing on removal. The array stores just the value, plus some spare slots. The linked version is known for simple pointer updates, and no resizing. The array is known for compact storage, and fewer allocations.
Key Idea
One Deque as Stack or Queue
Because a deque has every operation of a stack and a queue, it can replace either. The only decision is which end does which job. As a stack, push is add first, pop is remove first, and peek is peek first. What matters is that push and pop use the same end. As a queue, enqueue is add last, and dequeue is remove first: in at one end, out at the other.
Java Library
ArrayDeque and Its Two Spellings
Java ships this structure. Deque is an interface in java dot util, and its everyday implementation is ArrayDeque: a resizable circular array, much like the one just built. This program adds ten, twenty and thirty at the back, and five at the front. It looks at both ends, and polls from both ends. Each job has two spellings. Poll first returns null on an empty deque, while remove first throws a no such element exception. The stack and queue words map onto the same ends: push is add first, offer and add are add last, and poll is poll first.
Key Rule
Why ArrayDeque Refuses Null
ArrayDeque also refuses null. Add last of null throws a null pointer exception, and there's a reason. Poll first and peek first use null to mean empty. A stored null would make the two meanings impossible to tell apart. A few more facts. ArrayDeque isn't safe for several threads at once without extra care, and it has no access by index in the middle. Its documentation says it's likely faster than Stack when used as a stack, and faster than LinkedList when used as a queue. So it's the usual choice for both.
Worked Example
Checking Palindromes from Both Ends
Here's a job only a deque does naturally. A palindrome reads the same forward and backward. Keep only the letters and digits, lowercased, at the back of a deque. Then, while more than one is left, take one from each end, and compare. The loop stops with at most one letter left, which covers both the empty string and the middle letter of an odd-length word. A man, a plan, a canal, Panama is a palindrome. Deque is not. The empty string and a single a both pass, and so does never odd or even.
Common Mistake
Comparing Boxed Characters
One detail matters. Lines ten and eleven copy each removed value into a plain char before comparing. The deque holds boxed Character objects. Compare two of those with not-equals, and Java compares references, not letters. Two boxed characters with the value two hundred are different objects: double equals says false, while equals says true. Small values happen to be shared, so the bug hides until unusual input arrives.
Quick Check
Mixing Push and Add
Quick check. A program pushes one, adds two, pushes three, and adds four, all on one ArrayDeque. Then it prints the deque. What does it show? Pause and predict. It shows three, one, two, four. Push puts an element at the first end, but add puts it at the last end. So the pushes stack up at the front, newest first, and the adds line up at the back. One, two, three, four would need every call to use the same end. Mixing push with add is a classic slip. Pick one end for each job, and stick to it.
Common Mistakes
Deque Pitfalls to Avoid
A few more mistakes to avoid. Calling remove first where poll first was safer, or ignoring a null that poll returned. Letting an index go negative: add the length before the remainder. And copying into a bigger array without realigning to the front. In the linked version, all four links must change on an insert, and size must change on every add and remove.
Key Takeaways
Deque Essentials
To sum up. A deque adds, removes and looks at both ends, so it can act as a stack or a queue. A doubly linked deque with two sentinels makes every operation the same pointer rewiring, in order one. A circular array wraps a front index with the remainder operator, and doubling makes adds amortized order one. And Java's ArrayDeque is that array. It rejects null, because poll and peek use null to mean empty.
About Data Structures and Algorithms at UPI Study
Data Structures and Algorithms (Computer Science 251) is a self-paced online course of 87 video lessons in 17 chapters, from Java and object-oriented design to arrays, linked lists, recursion, stacks and queues, trees, heaps, hash tables, sorting and graphs. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: Discrete Math vs Data Structures and Algorithms · Intro to Java vs Data Structures and Algorithms
Why take it here
Why students take Data Structures and Algorithms with UPI Study
Where the credit goes
Universities that work with NCCRS
Data Structures and Algorithms carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Adding and Removing at Both Ends of a Sequence
What is a deque in Java?
How does a circular array deque update its front index?
What is the difference between pollFirst and removeFirst?
Why do push and add put elements at different ends of an ArrayDeque?
About the Data Structures and Algorithms course
How many college credits is Data Structures and Algorithms?
How much does Data Structures and Algorithms cost and what is included?
Which universities accept UPI Study credits?
How long does Data Structures and Algorithms take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Data Structures and Algorithms.
87 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →