Due before the start of lecture on October 7, 2025.
See below for a summary of the policies regarding late
submissions.
Homework is due prior to the start of lecture. If it is submitted more than 10 minutes after the start of lecture, it will be considered a full day late. There will be a 10% deduction for late submissions that are made by 11:59 p.m. Eastern time on the Sunday after the deadline, and a 20% deduction for submissions that are made after that Sunday and before the start of the next lecture. We will not accept any homework that is more than 7 days late. Plan your time carefully, and don’t wait until the last minute to begin an assignment. Starting early will give you ample time to ask questions and obtain assistance.
In your work on this assignment, make sure to abide by our policies on academic conduct.
If you have questions while working on this assignment, please come to
office hours, post them on Ed Discussion, or email
cscie22-staff@lists.fas.harvard.edu
55-65 points total
If you haven’t already created a folder named e22 for your
work in this course, follow these
instructions to do so.
Then create a subfolder called ps2 within your e22 folder,
and put all of the files for this assignment in that folder.
The problems from Part I will all be completed in a single PDF file. To create it, you should do the following:
Access the template that we have created by clicking on this link and signing into your Google account as needed.
When asked, click on the Make a copy button, which will save a copy of the template file to your Google Drive.
Select File->Rename, and change the name of the file to
ps2_partI.
Add your work for the problems from Part I to this file.
Once you have completed all of these problems, choose
File->Download->PDF document, and save the PDF file on your
machine. The resulting PDF file (ps2_partI.pdf) is the one that
you will submit. See the submission guidelines at the end of Part I.
Important
When big-O expressions are called for, please use them to specify tight bounds, as explained in the lecture notes.
14 points; 2 points for each part
Given the following array:
{14, 7, 27, 13, 24, 20, 10, 33}
If the array were sorted using selection sort, what would the array look like after the third pass of the algorithm (i.e., after the third time that the algorithm performs a pass or partial pass through the elements of the array)?
If the array were sorted using insertion sort, what would the array look like after the fourth iteration of the outer loop of the algorithm?
If the array were sorted using Shell sort, what would the array look like after the initial phase of the algorithm, if you assume that it uses an increment of 3? (The method presented in lecture would start with an increment of 7, but you should assume that it uses an increment of 3 instead.)
If the array were sorted using bubble sort, what would the array look like after the second pass of the algorithm?
If the array were sorted using the version of quicksort presented in lecture, what would the array look like after the second call to the partition method?
We will cover the material needed for the remaining two parts of this problem on July 3.
If the array were sorted using radix sort, what would the array look like after the initial pass of the algorithm?
If the array were sorted using the version of mergesort presented in
lecture, what would the array look like after the completion of the
third call to the merge() method—the method that merges two
subarrays? Note: the merge method is the helper method; is not the
recursive mSort method.
Important
There will be no partial credit on the above questions, so please check your answers carefully!
6 points total; 2 points each part
Given an already sorted array of 5 elements, how many comparisons of array elements would each of the following algorithms perform?
selection sort
Shell sort
We will cover the material needed for the remaining part of this problem on July 3.
Give an exact number of comparisons for each algorithm, and explain each answer briefly.
12 points total; 3 points each part
Swap sort is another sorting algorithm based on exchanges. Like bubble
sort, swap sort compares pairs of elements and swaps them when they
are out of order, but swap sort looks at different pairs of elements
than bubble sort does. On pass i of swap sort, the element in position
i of the array is compared with the elements in all positions to the
right of position i, and pairs of elements are swapped as needed. At
the end of pass i, the element in position i is where it belongs in
the sorted array.
Here is one possible implementation of this method:
public static void swapSort(int[] arr) { if (arr == null) { throw new IllegalArgumentException("arr must be non-null"); } for (int i = 0; i < arr.length - 1; i++) { for (int j = i + 1; j < arr.length; j++) { if (arr[i] > arr[j]) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } }
On pass 0, swap sort compares the element in position 0 with the
elements in positions 1 through (n - 1), where n is the number of
elements in the array, and it performs swaps when needed. On pass 1,
swap sort compares the element in position 1 with the elements in
positions 2 through (n - 1) and performs swaps when needed. The
process continues for passes 2 through (n - 2), at which point the
array is fully sorted.
For a given array length, n, this method performs the same number of comparisons of array elements, regardless of the contents of the array. What is the big-O expression for the number of such comparisons that the method performs? Give your answer as a function of the array length, and explain your answer briefly.
The number of moves that the method perform depends on the contents of the array. In the best case, what is the big-O expression for the number of moves? Explain your answer briefly.
In the worst case, what is the big-O expression for the number of moves? Explain your answer briefly.
What is the overall time efficiency of this method in the best case? In the worst case? Use big-O notation and explain your answers briefly.
6 points total; 3 points each part
Let’s say that you want to implement a method findMode(arr) that takes
an array of integers and returns the mode of the values in the array—
i.e., the value that appears most often in the array. For example, the
mode of the array {10, 8, 12, 8, 10, 5, 8} is 8.
If two or more values are tied for the mode, the method should return
the smallest of the most frequently occurring values. For example, in
the array {7, 5, 3, 5, 7, 11, 11}, three values (5, 7, and 11) each
appear twice, and no value appears more than twice; the method should
return 5 because it is the smallest of the three values that appear
twice.
One possible implementation of this method is:
public static int findMode(int[] arr) { int mode = -1; int modeFreq = 0; // number of times that the mode appears for (int i = 0; i < arr.length; i++) { int freq = 1; // number of times that arr[i] appears from // position i to the end of the array for (int j = i + 1; j < arr.length; j++) { if (arr[j] == arr[i]) { // how many times is this executed? freq++; } } if (freq > modeFreq || (freq == modeFreq && arr[i] < mode)) { mode = arr[i]; modeFreq = freq; } } return mode; }
Derive an exact formula for the number of times that the line
comparing arr[j] to arr[i] is executed, as a function of the
length n of the array.
What is the worst-case time efficiency of the method shown above as a
function of the length n of the array? Use big-O notation, and
explain your answer briefly.
findMode()10 points total; required for grad-credit students; may be completed for “partial” extra credit by others.
(7 points) Create an alternative implementation of the
findMode() method that has a better worst-case time efficiency
than the method from Problem 4. Hint: Begin by sorting the
array, which you can do by calling the sorting method from our
Sort class with the best
worst-case time efficiency. Make your implementation as efficient
as possible. Put your code in your ps2_partI file.
(3 points) What is the worst-case time efficiency of your alternative implementation as a function of the length n of the array? Use big-O notation, and explain your answer briefly.
17 points total
As discussed in lecture, a doubly linked list consists of nodes that
include two references: one called next to the next node in the
linked list, and one called prev to the previous node in the linked
list. The first node in such a list has a prev field whose value is
null, and the last node has a next field whose value is null.
The top portion of the diagram below shows a doubly linked list of
characters that could be used to represent the string "set".
Each of the nodes shown is an instance of the following class:
public class DNode { private char ch; private DNode next; private DNode prev; }
(In the diagram, we have labeled the individual fields of the DNode
object that contains the character 's'.)
In addition to the list representing "set", the diagram shows an
extra node containing the character 'a', and two reference
variables: n, which holds a reference to the second node in the list
(the 'e' node); and m, which holds a reference to the 'a'
node. The diagram also shows memory addresses of the start of the
variables and objects. For example, the 's' node begins at address
0x180.
(12 points) Complete the table we have provided in ps2_partI,
filling in the address and value of each expression from the
left-hand column. You should assume the following:
the address of the ch field of a DNode is the same as the
address of the DNode itself
the address of the next field of a DNode is 2 more than the
address of the DNode itself
the address of the prev field of a DNode is 6 more than the
address of the DNode itself, which means that it is also 4
more than the address of the next field.
(4 points) Write a Java code fragment that inserts the 'a' node
between the 'e' node and the 't' node, producing a linked list
that represents the string "seat". Your code fragment should
consist of a series of assignment statements. You should not make
any method calls, and you should not use any variables other than
the ones provided in the diagram. Make sure that the resulting
doubly linked list has correct values for the next and prev
fields in all nodes.
Testing your code fragment
You should start by convincing yourself on paper that your code
is correct. Draw the necessary diagrams and trace through your code,
making sure that it works correctly.
Once you have checked your work on paper, you can make use of a
simple version of the DNode class that we have created.
To use it, you should click on
this link
and save the file in your ps2 folder.
Open the ps2 folder in VSCode, and you should see a simple
DNode class that includes:
the definitions of the fields
a DNode constructor
a convert method that can be used to convert a Java String
object to a doubly-linked list of DNode objects
a toString() method that allows us to print a DNode object
and see the corresponding string
a main method with some initial test code – including code
that sets up the initial diagram that we have provided above.
To test your code fragment, you can add your lines of code
to the specified section of the main method and run the program
to see if you get the correct result.
The output of the program that we have provided should be:
before changes for 6-2: set after changes for 6-2: seat
Submit your ps2_partI.pdf file by taking the following steps:
If you still need to create a PDF file, open your file on Google Drive, choose File->Download->PDF document, and save the PDF file on your machine.
Click on the name of the assignment in the list of assignments on Gradescope. You should see a pop-up window labeled Submit Assignment. (If you don’t see it, click the Submit or Resubmit button at the bottom of the page.)
Choose the Submit PDF option, and then click the Select PDF button and find the PDF file that you created. Then click the Upload PDF button.
You should see a question outline along with thumbnails of the pages from your uploaded PDF. For each question in the outline:
As you do so, click on the magnifying glass icon for each page and doublecheck that the pages that you see contain the work that you want us to grade.
Once you have assigned pages to all of the problems in the question outline, click the Submit button in the lower-right corner of the window. You should see a box saying that your submission was successful.
Important
It is your responsibility to ensure that the correct version of every file is on Gradescope before the final deadline. We will not accept any file after the submission window for a given assignment has closed, so please check your submissions carefully using the steps outlined above.
If you are unable to access Gradescope and there is enough
time to do so, wait an hour or two and then try again. If you
are unable to submit and it is close to the deadline, email
your homework before the deadline to
cscie22-staff@lists.fas.harvard.edu
45 points total
25 points
If you haven’t already done so, create a folder named ps2
for your work on this assignment. You can find instructions for
doing so here.
Download our Sort class from lecture, making sure to save it in
your ps2 folder:
Sort.java
Make sure to put the file in your ps2 folder. If your
browser doesn’t allow you to specify where the file should be
saved, try right-clicking on the link above and choosing
Save as... or Save link as..., which should produce a
dialog box that allows you to choose the correct folder for
the file.
In VS Code, select the File->Open Folder or File->Open menu
option, and use the resulting dialog box to find and open your
ps2 folder. (Note: You must open the folder; it is not
sufficient to simply open the file.)
Select File->New File, which will open up an empty editor window.
Select File->Save, and give the new file the name
Problem7.java.
In the new file, create a class called Problem7.
In your Problem7 class, implement a method with the following header
public static int removeDups(int[] arr)
It should take an already sorted array of integers, and it should remove whatever values are necessary to ensure that there are no duplicates – i.e., that no value appears more than once. The remaining elements should still be sorted, and they should occupy the leftmost positions of the array. Any array locations that are unused after the duplicates are removed should be filled with zeroes.
In addition to making the necessary adjustments to the array, the method should return an integer that specifies the number of unique values in the array.
For example, if you add the following test code to a main method
in Problem7:
int[] a1 = {2, 5, 5, 5, 10, 12, 12}; int numUnique = removeDups(a1); System.out.println(Arrays.toString(a1)); System.out.println(numUnique);
it should display:
[2, 5, 10, 12, 0, 0, 0] 4
For full credit, your method must be as efficient as possible. See below for more details.
Important notes:
Your method should have a running time of O(n), where n is the length of the array. In addition, your method should use O(1) additional memory—i.e., it should not create and use a second array.
One inefficient approach would be to scan from left to right, and, whenever you encounter a duplicate, to shift all of the remaining elements left by one. The problem with this approach is that elements can end up being shifted multiple times, and thus the algorithm has a worst-case running time that is O(n²). Your method should move each element at most once. This will give it a running time that is O(n). Only half credit will be given for methods that move elements more than once.
If arr is null, the method should throw an
IllegalArgumentException.
If arr is not null, you may assume that it is a sorted
array of 0 or more integers.
Include a main method with code that tests your new method.
In order to use the Arrays.toString() method as we did in the
example above, you will need import the java.util package by
adding the following line of code before your class header:
import java.util.*;
In addition to the case shown above, you should include at least one other test case that you create.
20 points
As needed, select the File->Open Folder or File->Open menu
option, and use the resulting dialog box to find and open your
ps2 folder. (Note: You must open the folder; it is not
sufficient to simply open the file.)
Select File->New File, which will open up an empty editor window.
Select File->Save, and give the new file the name
Problem8.java.
In the new file, create a class called Problem8.
In your Problem8 class, implement a method with the following header
public static int[] intersect(int[] a1, int[] a2)
It should take two arrays of integers a1 and a2, and it should use
an approach based on merging to create and return a new array
containing the intersection of the values in a1 and a2 – i.e.,
all values that are found in both of the original arrays. The result
should be in sorted order, and it should not include any duplicate
values. For example, if you add the following test code to a main
method in Problem8:
int[] a1 = {10, 5, 7, 5, 9, 4}; int[] a2 = {7, 5, 15, 7, 7, 9, 10}; int[] result1 = intersect(a1, a2); System.out.println(Arrays.toString(result1)); int[] a3 = {0, 2, -4, 6, 10, 8}; int[] a4 = {12, 0, -4, 8}; int[] result2 = intersect(a3, a4); System.out.println(Arrays.toString(result2));
it should display:
[5, 7, 9, 10, 0, 0] [-4, 0, 8, 0]
(Note that we end up with extra 0s at the end of both of these result arrays for reasons that are discussed below.)
For full credit, your method must be as efficient as possible. See below for more details.
Begin by creating a new array for the intersection, giving it the length of the smaller of the two original arrays.
Use one of the more efficient sorting algorithms from our Sort
class to sort both of the original arrays. If you have downloaded
our Sort class into the same folder as your Problem8 class
(see the Getting started section at the start of Problem 7), you
should be able to make method calls to an appropriate method in
the Sort class from within your intersection method.
Find the intersection of the two arrays by employing an approach
that is similar to the one that we used to merge two sorted
subarrays (i.e., the approach taken by the merge method in
Sort.java)—using indices to “walk down” the two original
arrays and copying their values into the array that you created for
the intersection.
Important notes:
One important difference between merging and finding the intersection is that the intersection should not include any duplicates. In other words, a given number that appears in one or both of the original arrays should appear exactly once in the intersection. As a result, you will need to include code that skips over duplicate values as needed as you walk down the original arrays.
Your algorithm should be as efficient as possible. In particular, you should perform at most one complete pass through each of the arrays.
If either a1 or a2 is null, the method should throw an
IllegalArgumentException.
At the end of the method, return a reference to the array containing the intersection.
Add test code for your method to a main method. Recall that that
you can use the Arrays.toString() method to convert an array to
a string; import the java.util. package to gain access to the
Arrays class. In addition to the cases shown above, you
should include at least one other test case that you create.
Notes:
In both of the tests shown above, the array containing the intersection has the same length as the shorter of the original arrays.
When the number of values in the intersection (call it x) is smaller than the length of the shorter array, we end up with extra 0s at the end of the array containing the intersection. This happens because the array of integers that we create is initially filled with 0s, and we only use the first x positions of the array.
If 0 appears in both of the original arrays, it will also show
up in the results array as part of the intersection, as it does in
our second example above.
You should submit only the following files:
Problem7.javaProblem8.javaYou do not need to submit Sort.java.
Here are the steps:
Click on the name of the assignment in the list of assignments. You should see a pop-up window with a box labeled DRAG & DROP. (If you don’t see it, click the Submit or Resubmit button at the bottom of the page.)
Add all four files to the box labeled DRAG & DROP. You can either drag and drop the files from their folder into the box, or you can click on the box itself and browse for the files.
Click the Upload button.
You should see a box saying that your submission was successful.
Click the (x) button to close that box.
The Autograder will perform some tests on your files. Once it is done, check the results to ensure that the tests were passed. If one or more of the tests did not pass, the name of that test will be in red, and there should be a message describing the failure. Based on those messages, make any necessary changes. Feel free to ask a staff member for help.
Note: You will not see a complete Autograder score when you submit. That is because additional tests will be run later, after the final deadline for the submission has passed. For such problems, it is important to realize that passing all of the initial tests does not necessarily mean that you will ultimately get full credit on the problem. You should always run your own tests to convince yourself that the logic of your solutions is correct.
If needed, use the Resubmit button at the bottom of the page to resubmit your work. Important: Every time that you make a submission, you should submit all of the files for that Gradescope assignment, even if some of them have not changed since your last submission.
Near the top of the page, click on the box labeled Code. Then click on the name of each file to view its contents. Check to make sure that you see the code that you want us to grade.
Important
It is your responsibility to ensure that the correct version of every file is on Gradescope before the final deadline. We will not accept any file after the submission window for a given assignment has closed, so please check your submissions carefully using the steps outlined above.
If you are unable to access Gradescope and there is enough
time to do so, wait an hour or two and then try again. If you
are unable to submit and it is close to the deadline, email
your homework before the deadline to
cscie22-staff@lists.fas.harvard.edu
Last updated on September 30, 2025.