Final challenge: one problem per method
After this: Pick and run the right method on three new problems.
This challenge has three new problems, one for each method, and each is scored on its own. First you run two pointers from both ends on a new array. Then you predict what a fast and slow pass prints on a problem you have not seen. Last, you find the shortest window that reaches a target. You can try as many times as you like, and hints work as they do in the lessons.
Step 1 of 3Both ends
Both ends
The sorted array is [2, 4, 6, 9, 13, 15], and the target is 22. Run two pointers from both ends. Which indexes hold the pair, and how many comparisons does it take?
Fast and slow
Here is a new problem that uses the same method: move every zero to the end, and keep the other values in order. What does this print?
def move_zeros(nums): write = 0 for read in range(len(nums)): if nums[read] != 0: # keep it: copy into the write slot nums[write] = nums[read] write += 1 for i in range(write, len(nums)): # every cell after the kept part becomes 0 nums[i] = 0 return write
nums = [0, 3, 0, 5, 8]n = move_zeros(nums)print(nums, n)import java.util.Arrays;
public class Main { static int moveZeros(int[] nums) { int write = 0; for (int read = 0; read < nums.length; read++) { if (nums[read] != 0) { // keep it: copy into the write slot nums[write] = nums[read]; write++; } } for (int i = write; i < nums.length; i++) nums[i] = 0; // every cell after the kept part becomes 0 return write; }
public static void main(String[] args) { int[] nums = {0, 3, 0, 5, 8}; int n = moveZeros(nums); System.out.println(Arrays.toString(nums) + " " + n); }}A window
The array is [5, 1, 3, 5, 10, 7, 4, 9, 2, 8], and the target is 16. What does the smallest-window function return, and which window is it?
- Choose the method a new problem needs, run it by hand, and explain the moves: both ends, fast and slow, and a window.