Appearance
question:# Problem Statement You are given a 2D integer matrix `grid` representing a map where `1` represents land and `0` represents water. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are surrounded by water. The task is to calculate the area of the largest island in the given grid. The area is the number of cells with value `1` that are connected. Write a function `max_area_of_island(grid: List[List[int]]) -> int` that takes `grid`, a 2D list of integers, and returns the area of the largest island. # Example Input and Output - Example 1: ```python max_area_of_island( [[0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0]] ) ``` Output: ```python 6 ``` - Example 2: ```python max_area_of_island([[0,0,0,0,0,0,0,0]]) ``` Output: ```python 0 ``` # Constraints - `grid` will be a 2D list with dimensions between 1 and 1000. - Each cell in `grid` will have a value either `0` or `1`. # Requirements - The solution should efficiently calculate the largest island area in the given constraints. - Handle edge cases, such as a grid with no land or with all land.
answer:from typing import List def max_area_of_island(grid: List[List[int]]) -> int: def dfs(x, y): if x < 0 or y < 0 or x >= len(grid) or y >= len(grid[0]) or grid[x][y] == 0: return 0 grid[x][y] = 0 # Mark as visited return 1 + dfs(x + 1, y) + dfs(x - 1, y) + dfs(x, y + 1) + dfs(x, y - 1) max_area = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: max_area = max(max_area, dfs(i, j)) return max_area
question:# Coding Question: Implement a Custom Hash Map with Open Addressing **Context**: A HashMap (or Hash Table) is an essential data structure that offers efficient average-time complexity for insertion, deletion, and lookup operations. One method to handle collisions in a HashMap is Open Addressing with Linear Probing. **Challenge**: Your task is to implement a `CustomHashMap` class using Open Addressing with Linear Probing for collision handling. Also, implement a resizing mechanism to maintain HashMap efficiency when the load factor exceeds a threshold. **Function Signature**: ```python class CustomHashMap: def __init__(self, capacity: int = 8) -> None: pass def put(self, key: str, value: any) -> None: pass def get(self, key: str) -> any: pass def remove(self, key: str) -> None: pass def _hash(self, key: str, probe: int) -> int: pass def _resize(self) -> None: pass ``` **Detailed Requirements**: 1. **Initialization**: The constructor should initialize an empty HashMap with: - `capacity`: Initial size of the underlying array (default: 8). - A dynamic array (or list) to store key-value pairs. - A load factor threshold of `0.7` to trigger a resize operation. 2. **Hash Function**: - Implement a `_hash` method to compute the hash value of a given key using a probing mechanism. Use a combination of a base hash function and a probe number to manage collisions. 3. **Put Method**: - The `put` method should insert the key-value pair into the HashMap. - If the key already exists, update its value. - Use linear probing to find an appropriate slot in case of collision. - Trigger a resize operation if the load factor exceeds `0.7`. 4. **Get Method**: - The `get` method should retrieve the value associated with the given key. - Return `None` if the key does not exist. 5. **Remove Method**: - The `remove` method should remove the key-value pair associated with the given key. - Handle probe sequence appropriately when removing an element to maintain the integrity of the HashMap. 6. **Resize Method**: - The `_resize` method should double the size of the underlying array and rehash all existing entries. **Constraints**: - Keys will be non-empty strings. - Values will be any type of object. - The `put`, `get`, and `remove` methods should work efficiently even under high load, using linear probing correctly to maintain performance. **Example**: ```python >>> hashmap = CustomHashMap() >>> hashmap.put("apple", 1) >>> hashmap.put("banana", 2) >>> assert hashmap.get("apple") == 1 >>> assert hashmap.get("banana") == 2 >>> hashmap.put("apple", 10) >>> assert hashmap.get("apple") == 10 >>> hashmap.remove("banana") >>> assert hashmap.get("banana") is None >>> # This should trigger a resize >>> for i in range(10): ... hashmap.put(f"key{i}", i) >>> assert hashmap.get("key5") == 5 >>> assert hashmap.get("key9") == 9 ``` Implementing this `CustomHashMap` will test your knowledge of hash functions, collision handling, dynamic resizing, and hashing techniques.
answer:class CustomHashMap: def __init__(self, capacity: int = 8) -> None: self.capacity = capacity self.size = 0 self.load_factor_threshold = 0.7 self.buckets = [None] * self.capacity def put(self, key: str, value: any) -> None: if self.size / self.capacity >= self.load_factor_threshold: self._resize() index = self._find_slot(key, inserting=True) self._insert_at(index, key, value) def get(self, key: str) -> any: index = self._find_slot(key, inserting=False) if index is not None: return self.buckets[index][1] return None def remove(self, key: str) -> None: index = self._find_slot(key, inserting=False) if index is not None: self.buckets[index] = None self.size -= 1 # Rehash all items in the current probing sequence self._rehash_from_deleted_slot(index) def _hash(self, key: str, probe: int) -> int: return (hash(key) + probe) % self.capacity def _resize(self) -> None: old_buckets = self.buckets self.capacity *= 2 self.buckets = [None] * self.capacity self.size = 0 for item in old_buckets: if item is not None: self.put(item[0], item[1]) def _find_slot(self, key: str, inserting: bool) -> int: for probe in range(self.capacity): index = self._hash(key, probe) if self.buckets[index] is None: if inserting: return index return None if self.buckets[index][0] == key: return index raise RuntimeError("HashMap is full, which shouldn't happen due to resizing.") def _insert_at(self, index: int, key: str, value: any) -> None: if self.buckets[index] is None: self.size += 1 self.buckets[index] = (key, value) def _rehash_from_deleted_slot(self, deleted_index: int) -> None: next_index = (deleted_index + 1) % self.capacity while self.buckets[next_index] is not None: key, value = self.buckets[next_index] self.buckets[next_index] = None self.size -= 1 self.put(key, value) next_index = (next_index + 1) % self.capacity
question:# Scenario You have been given a set of utilities to manage and manipulate strings, but the current library lacks the functionality to handle the permutation of characters. Your task is to extend this library by adding a feature that generates all unique permutations of a given string. # Problem Statement Implement a function `generate_permutations(s: str) -> List[str]` that takes a string and returns a list of all unique permutations of the characters in the string. Ensure your implementation handles duplicate characters efficiently to avoid generating duplicate permutations. # Specifications * **Input**: A string `s` containing characters from the English alphabet (both uppercase and lowercase). * **Output**: A list of strings, each representing a unique permutation of the input string. * **Constraints**: * The length of the string `s` will be between 1 and 10. * The string may contain duplicate characters. * You must not generate any duplicate permutations in the output list. * **Performance**: Aim for a time complexity close to O(n * n!) where n is the length of the string. # Example ```python print(generate_permutations("AAB")) # Expected output: ["AAB", "ABA", "BAA"] print(generate_permutations("ABC")) # Expected output: ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"] print(generate_permutations("AAA")) # Expected output: ["AAA"] ``` # Bonus Optimize the function for better performance with large inputs by using techniques such as backtracking or leveraging libraries that handle permutations efficiently.
answer:from typing import List import itertools def generate_permutations(s: str) -> List[str]: Returns a list of all unique permutations of the given string. permutations = set(itertools.permutations(s)) return ["".join(permutation) for permutation in permutations]
question:# Scenario You are developing a simple contact management system that allows users to store and retrieve contact details. Each contact should have a unique identifier, name, and phone number. Your task is to implement a class to manage the contacts and ensure that the system works efficiently. # Task 1. Implement a class `ContactManager` with the following methods: - `add_contact` to add a new contact. This method should take a unique identifier (`contact_id`), name, and phone number. - `remove_contact` to remove a contact by their unique identifier. - `get_contact` to retrieve contact details by their unique identifier. - `list_contacts` to return a list of all contacts. 2. Write unit tests for each method to verify their correctness. # Requirements **Class Definition**: ```python class ContactManager: def __init__(self): # Your implementation here def add_contact(self, contact_id: str, name: str, phone: str) -> None: # Your implementation here def remove_contact(self, contact_id: str) -> None: # Your implementation here def get_contact(self, contact_id: str) -> dict: # Your implementation here def list_contacts(self) -> list: # Your implementation here ``` # Example ```python # Example usage cm = ContactManager() cm.add_contact("1", "Alice", "12345") cm.add_contact("2", "Bob", "67890") print(cm.get_contact("1")) # Expected output: {"contact_id": "1", "name": "Alice", "phone": "12345"} cm.remove_contact("1") print(cm.list_contacts()) # Expected output: [{"contact_id": "2", "name": "Bob", "phone": "67890"}] ``` # Constraints - The `contact_id` should be unique for each contact. - If a contact is added with an existing `contact_id`, the method should raise an exception. - If `remove_contact` or `get_contact` is called with a non-existent `contact_id`, the method should raise an exception. # Testing - Use the `unittest` or `pytest` framework to write tests for the class methods. - Ensure all edge cases, such as adding contacts with duplicate IDs or removing non-existent contacts, are tested. # Additional Information - You can use dictionaries or other appropriate data structures to manage the contacts internally. - Ensure that all methods handle edge cases and invalid inputs gracefully.
answer:class ContactManager: def __init__(self): self.contacts = {} def add_contact(self, contact_id: str, name: str, phone: str) -> None: if contact_id in self.contacts: raise ValueError("Contact ID already exists.") self.contacts[contact_id] = {"contact_id": contact_id, "name": name, "phone": phone} def remove_contact(self, contact_id: str) -> None: if contact_id not in self.contacts: raise ValueError("Contact ID does not exist.") del self.contacts[contact_id] def get_contact(self, contact_id: str) -> dict: if contact_id not in self.contacts: raise ValueError("Contact ID does not exist.") return self.contacts[contact_id] def list_contacts(self) -> list: return list(self.contacts.values())