Final challenge: contains a duplicate
After this: Take a fresh problem through the six steps, from restating it to testing its edges.
This challenge gives you a fresh problem and walks it through the method, one step at a time: restate it, count the slow answer, find the cue, write the check line, and test the edges. Step 2 of the method, the example by hand, is built into the others. Each step is scored on its own, every step shows the code in Python and in Java, and you can try as many times as you like.
By hand: [1, 2, 3, 1] has 1 twice, so the answer is yes. [1, 2, 3, 4] has no value twice, so the answer is no. If you get stuck on step 4, the hash-sets tutorial has this exact tool in Spotting repeats: the seen set.
Step 1 of 5Restate it
Step 1: restate it
The problem: given a list of whole numbers, answer yes if any value appears more than once, and no otherwise. Which restatement is right? (Yes is Truetrue, no is Falsefalse.)
Step 3: the slow answer and its cost
The slow answer compares every pair of positions and stops at the first pair of equal values. It needs 3 comparisons on [1, 2, 3, 1]. How many on [1, 2, 3, 4], and how does the work grow with n numbers?
Step 4: the cue and the tool
The slow answer keeps asking one question about each number. What is the question, and which tool answers it fast?
Step 5: write it
Complete the line that asks whether x has been seen already, so that the program prints yes for [1, 2, 3, 1] and no for [1, 2, 3, 4].
def has_duplicate(nums): seen = set() for x in nums: ____________________ # ← have we met x before? return True seen.add(x) return False
print(has_duplicate([1, 2, 3, 1]))print(has_duplicate([1, 2, 3, 4]))import java.util.HashSet;
public class Main { static boolean hasDuplicate(int[] nums) { HashSet<Integer> seen = new HashSet<>(); for (int x : nums) { ____________________ // ← have we met x before? return true; } seen.add(x); } return false; }
public static void main(String[] args) { System.out.println(hasDuplicate(new int[] {1, 2, 3, 1})); System.out.println(hasDuplicate(new int[] {1, 2, 3, 4})); }}Step 6: test the edges
Three edge cases: an empty list, one item, and two equal items. What does this print?
def has_duplicate(nums): seen = set() for x in nums: if x in seen: return True seen.add(x) return False
print(has_duplicate([]))print(has_duplicate([5]))print(has_duplicate([7, 7]))import java.util.HashSet;
public class Main { static boolean hasDuplicate(int[] nums) { HashSet<Integer> seen = new HashSet<>(); for (int x : nums) { if (seen.contains(x)) { return true; } seen.add(x); } return false; }
public static void main(String[] args) { System.out.println(hasDuplicate(new int[] {})); System.out.println(hasDuplicate(new int[] {5})); System.out.println(hasDuplicate(new int[] {7, 7})); }}- Take contains-a-duplicate through the six steps: restate it, count the brute force, find the cue that points to a hash set, write the check line, and test the empty, one-item and repeated cases.