Zheng Qu
commited on
Commit
•
ee69a9c
1
Parent(s):
e720bf1
add json files
Browse files
MIDTERM2c/problem_2_12_find_k_closest_elements.json
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"Problem_markdown": "# Problem 2.12: [10pts]Find K Closest Elements\n\nGiven a sorted array, an integer `k` and an integer `x`, find the `k` closest elements to `x` in the array. The result should also be sorted in ascending order. \n\nThe array is guaranteed to be sorted in ascending order, and `k` is always smaller than the length of the array.\n\n**Example:**\n```python\narr = [1, 3, 5, 7, 9], k = 3, x = 6\nprint(find_k_closest(arr, k, x)) # Output: [5, 7, 9]\n```\n\n**Another example**\n```python\narr = [2, 4, 6, 8, 10], k = 2, x = 5\nprint(find_k_closest(arr, k, x)) # Output: [4, 6]\n```\n\n**Constraints:**\n- The array is sorted in non-decreasing order.\n- `1 <= k <= arr.length`\n- Absolute difference is computed as `abs(a - b)`, for comparing proximity to `x`.\n- O(log(n-k) + k) time complexity is expected.\n\n**Template Code:**\n```python\ndef find_k_closest(arr: list[int], k: int, x: int) -> list[int]:\n # Initialize boundaries\n left, right = 0, len(arr) - k\n \n # Perform modified binary search\n while left < right:\n pass\n # TODO\n\n```",
|
3 |
+
"Hint": "<details>\n<summary>Hint</summary>\n\n- Consider using binary search to reduce the range over which you must find the closest k elements.\n- Focus on comparing elements around `x` rather than sorting distances.\n- Remember, you're manipulating the boundaries of your search through conditions within the binary search loop.\n</details>",
|
4 |
+
"Template_Code": "def find_k_closest(arr: list[int], k: int, x: int) -> list[int]:\n # Initialize boundaries\n left, right = 0, len(arr) - k\n \n # Perform modified binary search\n while left < right:\n pass\n # TODO",
|
5 |
+
"Solution_Code": "def find_k_closest(arr: list[int], k: int, x: int) -> list[int]:\n left, right = 0, len(arr) - k\n while left < right:\n mid = (left + right) // 2\n if x - arr[mid] > arr[mid + k] - x:\n left = mid + 1\n else:\n right = mid\n return arr[left:left + k]",
|
6 |
+
"Solution_markdown": "# Solution Explanation:\n\n1. Search Space\n\n- Rather than searching for individual elements, we search for the starting position of a k-sized window\n- The window can start anywhere from index 0 to (array_length - k)\n\n2. Binary Search Logic\n\n- For any potential window starting at position mid:\n - Compare elements at mid and mid+k positions\n - If x is closer to arr[mid+k], we need to move right\n - If x is closer to arr[mid], we need to move left\n - This effectively finds the optimal starting point for our k-element window\n\n3. Final Result\n- Once binary search completes, 'left' pointer indicates the best starting position\n- We return k elements starting from that position\n\n**Time Complexity:**\n\n- Binary Search approach: O(log(n-k)) for finding the starting position\n- Slicing k elements: O(k)\n- Total: O(log(n-k) + k)",
|
7 |
+
"Testing_Code": "def test_find_k_closest():\n assert find_k_closest([1, 2, 3, 4, 5], 4, 3) == [1, 2, 3, 4]\n assert find_k_closest([1, 2, 3, 4, 5], 4, -1) == [1, 2, 3, 4]\n assert find_k_closest([1, 2, 3, 4, 5], 3, 5) == [3, 4, 5]\n assert find_k_closest([1, 3, 3, 3, 5], 2, 3) == [3, 3]\n assert find_k_closest([1, 3, 5, 7, 9], 1, 6) == [5]\n print(\"All tests passed!\")\n\ntest_find_k_closest()"
|
8 |
+
}
|
MIDTERM2c/problem_3_20_merge_sorted_arrays.json
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"Problem_markdown": "# Problem 3.20: [10pts]Merge Sorted Arrays\n\n### Problem Statement\nGiven two sorted arrays, the task is to merge them into a single sorted array. The function should take two lists of integers (`nums1` and `nums2`) as input and return a new list that contains all the elements from the two input lists, sorted in non-decreasing order.\n\n### Constraints\n- The input lists are already sorted in non-decreasing order.\n- You may assume the lists contain integer values.\n\n### Complexity\n- **Time Complexity:** O(n + m) where n and m are the lengths of `nums1` and `nums2`, respectively.\n- **Space Complexity:** O(n + m)\n\n### Template\n```python\ndef merge_sorted_arrays(nums1: list[int], nums2: list[int]) -> list[int]:\n # TODO: Implement the merging logic\n```",
|
3 |
+
"Hint": "<details>\n<summary>Hint</summary>\n\n- Use pointers to track current positions in each array.\n- Continuously compare elements at these positions and append the smaller element to the result.\n- After reaching the end of one array, append the leftover elements of the other array.\n</details>",
|
4 |
+
"Template_Code": "def merge_sorted_arrays(nums1: list[int], nums2: list[int]) -> list[int]:\n # TODO: Implement the merging logic",
|
5 |
+
"Solution_Code": "def merge_sorted_arrays(nums1: list[int], nums2: list[int]) -> list[int]:\n result = []\n i = j = 0\n\n while i < len(nums1) and j < len(nums2):\n if nums1[i] <= nums2[j]:\n result.append(nums1[i])\n i += 1\n else:\n result.append(nums2[j])\n j += 1\n\n result.extend(nums1[i:])\n result.extend(nums2[j:])\n return result",
|
6 |
+
"Solution_markdown": "# Solution Explanation\n\n- **Initialize Pointers:** Start with two pointers `i` and `j` initialized to 0. These pointers track the current index position for `nums1` and `nums2`.\n- **Merge by Comparison:**\n - Use a `while` loop to compare elements at the current index of both arrays:\n - If `nums1[i]` is less than or equal to `nums2[j]`, append `nums1[i]` to the result and increment `i`.\n - Otherwise, append `nums2[j]` to the result and increment `j`.\n- **Add Remaining Elements:**\n - After the loop, one of the arrays might still have elements left. Append these remaining elements directly to the result:\n - Use `result.extend(nums1[i:])` to add any leftover elements from `nums1`.\n - Use `result.extend(nums2[j:])` to add any leftover elements from `nums2`.\n- **Return Result:** Return the `result` list which contains all elements from `nums1` and `nums2` in sorted order.",
|
7 |
+
"Testing_Code": "def test_merge_sorted_arrays():\n # Test case 1: Normal case with interleaved values\n assert merge_sorted_arrays([1, 3, 5], [2, 4, 6]) == [1, 2, 3, 4, 5, 6]\n \n # Test case 2: One array is empty\n assert merge_sorted_arrays([], [1, 2, 3]) == [1, 2, 3]\n assert merge_sorted_arrays([1, 2, 3], []) == [1, 2, 3]\n \n # Test case 3: Both arrays are empty\n assert merge_sorted_arrays([], []) == []\n \n # Test case 4: Arrays with duplicate elements\n assert merge_sorted_arrays([1, 2, 2, 3], [2, 3, 4]) == [1, 2, 2, 2, 3, 3, 4]\n \n # Test case 5: Arrays of different lengths\n assert merge_sorted_arrays([1, 10, 20], [2, 3, 4, 5, 6]) == [1, 2, 3, 4, 5, 6, 10, 20]\n\ntest_merge_sorted_arrays()"
|
8 |
+
}
|
MIDTERM2c/problem_5_11_reverse_linked_list.json
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"Problem_markdown": "## Problem 5.11: [10pts]Reverse Linked List\n\nGiven the head of a singly linked list, reverse the list and return the reversed list.\n\n**Example:**\n- Input: head = [1,2,3,4,5]\n- Output: [5,4,3,2,1]\n\n**Constraints:**\n- The number of nodes in the list is in range [0, 5000]\n- -5000 <= Node.val <= 5000\n\n**Template Code:**\n```python\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n \ndef reverseList(head):\n # Your code here\n pass\n```",
|
3 |
+
"Hint": "<details>\n<summary>Hint</summary>\n\n- Think about how to maintain access to the next node before breaking links\n- Use three pointers to track previous, current, and next nodes\n- Handle edge cases like empty list or single node list\n</details>",
|
4 |
+
"Template_Code": "# Your code here\ndef reverseList(head):\n prev = None\n curr = head\n \n # TODO: Implement the reversal logic\n \n return prev",
|
5 |
+
"Solution_Code": "def reverseList(head):\n prev = None\n curr = head\n \n while curr:\n next_node = curr.next\n curr.next = prev\n prev = curr\n curr = next_node\n \n return prev",
|
6 |
+
"Solution_markdown": "# Solution Explanation\n\n1. Use three pointers: prev, curr, and next_node\n2. Initialize prev as None and curr as head\n3. While curr is not None:\n - Save next_node as curr.next\n - Reverse the link by setting curr.next to prev\n - Move prev to curr\n - Move curr to next_node\n4. Return prev as the new head",
|
7 |
+
"Testing_Code": "class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\ndef create_linked_list(arr):\n if not arr: return None\n head = ListNode(arr[0])\n curr = head\n for val in arr[1:]:\n curr.next = ListNode(val)\n curr = curr.next\n return head\n\ndef linked_list_to_array(head):\n result = []\n curr = head\n while curr:\n result.append(curr.val)\n curr = curr.next\n return result\n\n# Test cases\ndef test_reverse_list():\n # Test 1\n input1 = create_linked_list([1,2,3,4,5])\n result1 = linked_list_to_array(reverseList(input1))\n assert result1 == [5,4,3,2,1], f\"Test 1 Failed: Expected [5,4,3,2,1], but got {result1}\"\n \n # Test 2\n input2 = create_linked_list([1,2])\n result2 = linked_list_to_array(reverseList(input2))\n assert result2 == [2,1], f\"Test 2 Failed: Expected [2,1], but got {result2}\"\n \n # Test 3 (empty list)\n input3 = None\n result3 = reverseList(input3)\n assert result3 == None, \"Test 3 Failed: Expected None for empty list\"\n \n print(\"All test cases passed!\")\n\ntest_reverse_list()"
|
8 |
+
}
|
MIDTERM2c/problem_5_15_caesar_cipher_and_decipher.json
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"Problem_markdown": "## Problem 5.15: [10pts]Caesar Cipher and Decipher\n\nWrite two functions to implement the Caesar cipher encryption and decryption:\n\n1. `caesar_cipher(text, shift)`: Encrypts text using Caesar cipher with given shift\n2. `caesar_decipher(text, shift)`: Decrypts Caesar cipher text with given shift\n\n**Parameters**:\n- `text`: String containing only uppercase letters and spaces\n- `shift`: Integer between 0 and 25 (inclusive)\n\n**Example**:\n```python\ntext = \"HELLO\", shift = 3\nEncrypted: \"KHOOR\" \nDecrypted: \"HELLO\"\n```\n\n**Constraints**:\n- Text contains only uppercase letters and spaces\n- 0 \u2264 shift \u2264 25",
|
3 |
+
"Hint": "<details>\n<summary>Hint</summary>\n\n- Think about how to convert letters to numbers (0-25) using ASCII values\n- Use modulo 26 to handle alphabet wrapping\n- For decryption, consider how to reverse the shift operation\n</details>",
|
4 |
+
"Template_Code": "# Your code here\ndef caesar_cipher(text, shift):\n \"\"\"\n Encrypts text using Caesar cipher with given shift.\n \"\"\"\n pass\n\ndef caesar_decipher(text, shift):\n \"\"\"\n Decrypts Caesar cipher text with given shift.\n \"\"\"\n pass",
|
5 |
+
"Solution_Code": "def caesar_cipher(text, shift):\n result = []\n for char in text:\n if char == ' ':\n result.append(char)\n else:\n # Shift the character and wrap around using modulo\n shifted = (ord(char) - ord('A') + shift) % 26\n result.append(chr(shifted + ord('A')))\n return ''.join(result)\n\ndef caesar_decipher(text, shift):\n return caesar_cipher(text, 26 - shift)",
|
6 |
+
"Solution_markdown": "# Solution Explanation\n\n- **Encryption**:\n 1. For each character in input text:\n - If character is space, keep it unchanged\n - Otherwise, shift ASCII value by specified amount\n - Use modulo 26 to wrap around alphabet\n - Convert back to character\n 2. Join characters into result string\n\n- **Decryption**:\n 1. Use same logic as encryption\n 2. Apply reverse shift (26 - shift) to get original text\n 3. Handle spaces similarly to encryption",
|
7 |
+
"Testing_Code": "# Basic test\ntext = \"HELLO WORLD\"\nshift = 3\nencrypted = caesar_cipher(text, shift)\nassert encrypted == \"KHOOR ZRUOG\", f\"Expected 'KHOOR ZRUOG', got {encrypted}\"\ndecrypted = caesar_decipher(encrypted, shift)\nassert decrypted == \"HELLO WORLD\", f\"Expected 'HELLO WORLD', got {decrypted}\"\n\n# Edge cases\n# Test with shift 0\nassert caesar_cipher(\"ABC\", 0) == \"ABC\"\n# Test with shift 26 (should be same as shift 0)\nassert caesar_cipher(\"ABC\", 26) == \"ABC\"\n# Test with only spaces\nassert caesar_cipher(\"A B C\", 1) == \"B C D\"\n\nprint(\"All tests passed!\")"
|
8 |
+
}
|