Dataset Preview
Duplicate
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
Previous task error: I/O error: I/O error: Permission denied (os error 13)
Error code:   UnexpectedError

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

seq_id
string
instruction
string
output
string
code
string
status
string
660113403
Write a function to check if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization.
```python def is_palindrome(s): # Normalize the string by removing non-alphanumeric characters and converting to lowercase. s = ''.join(c for c in s if c.isalnum()).lower() return s == s[::-1] ```
def is_palindrome(s): s = ''.join(c for c in s if c.isalnum()).lower() return s == s[::-1]
keep
14192481277
Write a function to find the missing number in a given list of numbers ranging from 0 to n.
```python def missing_number(nums): # Calculate expected sum using n*(n+1)/2 and subtract actual sum n = len(nums) total = n * (n + 1) // 2 sum_nums = sum(nums) return total - sum_nums ```
def missing_number(nums): n = len(nums) total = n * (n + 1) // 2 sum_nums = sum(nums) return total - sum_nums
keep
20383247274
Write a function to generate the nth row of Pascal's triangle.
```python def pascal_row(n): # Initialize the row with the first element as 1 row = [1] # Iterate to calculate subsequent elements using the previous value for i in range(1, n+1): row.append(row[i-1] * (n-i+1) // i) return row ```
def pascal_row(n): row = [1] for i in range(1, n+1): row.append(row[i-1] * (n-i+1) // i) return row
keep
19434228727
Write a function that checks if a given tree is a binary search tree. A binary search tree has the property that all nodes in the left subtree of a node have values less than the node's value and all nodes in the right subtree have values greater than the node's value.
```python def is_binary_search_tree(root, min_val=float('-inf'), max_val=float('inf')): # Return True if the tree is empty (base case) if root is None: return True # Check if the current node's value violates the min/max bounds. if not (root.val > min_val and root.val < max_val): return...
def is_binary_search_tree(root, min_val=float('-inf'), max_val=float('inf')): if root is None: return True if not (root.val > min_val and root.val < max_val): return False return (is_binary_search_tree(root.left, min_val, root.val) and is_binary_search_tree(root.right, root.val...
keep
28755799726
Write a python function to find the missing number in a given list of integers that contains n distinct numbers taken from 0, 1, 2, ..., n. The function should have a time complexity of O(n) and space complexity of O(1).
```python def missing_number(nums): # Calculate the expected sum of 0 to n and subtract the actual sum of the list. n = len(nums) total = n * (n + 1) // 2 sum_nums = sum(nums) return total - sum_nums ```
def missing_number(nums): n = len(nums) total = n * (n + 1) // 2 sum_nums = sum(nums) return total - sum_nums
keep
32279616255
Write a function to check if a given list of integers is sorted in ascending order and all elements are unique.
```python def check_sorted_unique(test_list): # Verify the list matches its sorted version and has no duplicates. return test_list == sorted(set(test_list)) ```
def check_sorted_unique(test_list): return test_list == sorted(set(test_list))
keep
12120976763
Write a python function to find the length of the longest substring without repeating characters in a given string.
```python def length_of_longest_substring(s): # Initialize variables for the sliding window start index and maximum length. if not s: return 0 char_map = {} left = 0 max_length = 0 # Iterate through the string with a right pointer to expand the sliding window. for right in range(len(...
def length_of_longest_substring(s): if not s: return 0 char_map = {} left = 0 max_length = 0 for right in range(len(s)): if s[right] in char_map: left = max(left, char_map[s[right]] + 1) char_map[s[right]] = right max_length = max(max_length, right - left ...
keep
18874307847
Create a function that takes a string as an input and returns a list of unique characters in the string in the order they appear.
```python def unique_char_in_order(input_str): # Initialize an empty list to store unique characters. unique_chars = [] # Iterate through each character in the input string. for char in input_str: if char not in unique_chars: unique_chars.append(char) return unique_chars ```
def unique_char_in_order(input_str): unique_chars = [] for char in input_str: if char not in unique_chars: unique_chars.append(char) return unique_chars
keep
72740153081
Write a function to find the largest continuous sum in an array.
```python def largest_continuous_sum(arr): # Handle edge case for empty array if len(arr) == 0: return 0 # Initialize current and max sum variables to the first element. max_sum = current_sum = arr[0] # Iterate through the remaining elements to update current and max sums. for num in a...
def largest_continuous_sum(arr): if len(arr) == 0: return 0 max_sum = current_sum = arr[0] for num in arr[1:]: current_sum = max(current_sum + num, num) max_sum = max(max_sum, current_sum) return max_sum
keep
25369038617
Write a function to check if a word is a palindrome. A palindrome is a word that reads the same backward as forward, e.g., "madam" or "racecar".
```python def is_palindrome(word): # Compare the word with its reverse to determine if it is a palindrome. return word == word[::-1] ```
def is_palindrome(word): return word == word[::-1]
keep
73965182520
Write a function that checks if a given string is a palindrome, considering only alphanumeric characters and ignoring cases.
```python def is_palindrome(s: str) -> bool: # Filter the string to keep only alphanumeric characters and convert to lowercase. s = ''.join([c.lower() for c in s if c.isalnum()]) return s == s[::-1] ```
def is_palindrome(s: str) -> bool: s = ''.join([c.lower() for c in s if c.isalnum()]) return s == s[::-1]
keep
74992079799
Write a function to find the median of two sorted arrays.
```python def find_median(nums1, nums2): # Merge the two sorted arrays and calculate the median. nums = sorted(nums1 + nums2) if len(nums) % 2 == 0: return (nums[len(nums)//2] + nums[len(nums)//2 - 1]) / 2 else: return nums[len(nums)//2] ```
def find_median(nums1, nums2): nums = sorted(nums1 + nums2) if len(nums) % 2 == 0: return (nums[len(nums)//2] + nums[len(nums)//2 - 1]) / 2 else: return nums[len(nums)//2]
keep
6257817307
Write a function that takes a string and a target character as input, and returns the number of times the target character appears in the string. The function should be case insensitive.
```python def count_char(string, target_char): # Convert both the string and target character to lowercase for case-insensitive comparison. string = string.lower() target_char = target_char.lower() return string.count(target_char) ```
def count_char(string, target_char): string = string.lower() target_char = target_char.lower() return string.count(target_char)
keep
15526957597
Write a function that checks if a given string is an anagram of a palindrome.
```python def is_anagram_of_palindrome(s: str) -> bool: # Count character frequencies to check if at most one character has an odd count. char_counts = Counter(s) odd_counts = sum(1 for count in char_counts.values() if count % 2 != 0) return odd_counts <= 1 ```
from collections import Counter def is_anagram_of_palindrome(s: str) -> bool: char_counts = Counter(s) odd_counts = sum(1 for count in char_counts.values() if count % 2 != 0) return odd_counts <= 1
keep
20004586671
Write a python function to find the maximum product of three numbers in a list. The function should return the maximum product.
```python def max_product(nums): # Sort the list to easily access the largest and smallest elements. nums.sort() return max(nums[0]*nums[1]*nums[-1], nums[-1]*nums[-2]*nums[-3]) ```
def max_product(nums): nums.sort() return max(nums[0]*nums[1]*nums[-1], nums[-1]*nums[-2]*nums[-3])
keep
2175400675
Write a function to find the maximum difference between two elements in a list, where the larger element comes after the smaller one.
```python def max_difference(lst): # Initialize variables to track the minimum element seen so far and the maximum difference found. if len(lst) < 2: return 0 min_val = lst[0] max_diff = 0 # Iterate through the list starting from the second element to update the minimum value and calculate t...
def max_difference(lst): if len(lst) < 2: return 0 min_val = lst[0] max_diff = 0 for i in range(1, len(lst)): if lst[i] - min_val > max_diff: max_diff = lst[i] - min_val if lst[i] < min_val: min_val = lst[i] return max_diff
keep
40713914324
Write a python function to find the longest substring without repeating characters in a given string.
```python def longest_substring_without_repeating_characters(s): # Initialize variables for the sliding window and character tracking char_map = {} left = 0 result = "" # Iterate through the string with a right pointer to expand the sliding window. for right in range(len(s)): if s[right]...
def longest_substring_without_repeating_characters(s): char_map = {} left = 0 result = "" for right in range(len(s)): if s[right] in char_map: left = max(left, char_map[s[right]] + 1) char_map[s[right]] = right if right - left + 1 > len(result): result = s...
keep
70034082307
Write a python function to find the maximum number of consecutive 1's in the array if you can change at most k 0's to 1's.
```python def max_ones(arr, k): # Initialize sliding window pointers and a counter for zeros. left = 0 max_len = 0 zero_count = 0 # Iterate through the array with a right pointer to expand the window. for right in range(len(arr)): if arr[right] == 0: zero_count += 1 ...
def max_ones(arr, k): left = 0 max_len = 0 zero_count = 0 for right in range(len(arr)): if arr[right] == 0: zero_count += 1 while zero_count > k: if arr[left] == 0: zero_count -= 1 left += 1 max_len = max(max_len, right - lef...
keep
6536870388
Create a function in Python that takes a list of positive integers as input and returns the maximum product that can be achieved by multiplying any three numbers from the list. Note that the list must contain at least three integers.
```python def max_product(nums: List[int]) -> int: # Sort the list in ascending order to easily access the largest and smallest elements. # Sort the list in ascending order nums.sort() # The maximum product can be either: # (1) The product of the three largest numbers # or (2) The product of the...
from typing import List def max_product(nums: List[int]) -> int: # Sort the list in ascending order nums.sort() # The maximum product can be either: # (1) The product of the three largest numbers # or (2) The product of the two smallest numbers (which could be negative) and the largest number r...
keep
40792144997
Write a python function to find the maximum difference between two elements in an array such that larger element appears after the smaller number.
```python def max_difference(arr): # Initialize variables to track the minimum element seen so far and the maximum difference. max_diff = 0 min_element = arr[0] # Iterate through the array starting from the second element to update the minimum element and calculate the maximum difference. for i in r...
def max_difference(arr): max_diff = 0 min_element = arr[0] for i in range(1, len(arr)): if (arr[i] - min_element) > max_diff: max_diff = arr[i] - min_element if arr[i] < min_element: min_element = arr[i] return max_diff
keep
1371984315
Write a function to find the length of the longest substring without repeating characters.
```python def length_of_longest_substring(s): # Initialize a dictionary to track the last seen index of each character. char_map = {} left = 0 max_length = 0 # Iterate through the string with a right pointer to expand the window. for right in range(len(s)): if s[right] in char_map: ...
def length_of_longest_substring(s): char_map = {} left = 0 max_length = 0 for right in range(len(s)): if s[right] in char_map: left = max(left, char_map[s[right]] + 1) char_map[s[right]] = right max_length = max(max_length, right - left + 1) return max_l...
keep
3765204287
Write a Python function to find the missing number in a given list of numbers ranging from 0 to n.
```python def missing_number(nums): # Calculate expected sum using n*(n+1)/2 and subtract actual sum n = len(nums) total = n * (n + 1) // 2 sum_nums = sum(nums) return total - sum_nums ```
def missing_number(nums): n = len(nums) total = n * (n + 1) // 2 sum_nums = sum(nums) return total - sum_nums
keep
3955043418
Write a function to find the number of times a given character appears in a string.
```python def count_char(s, char): # Initialize a counter variable to zero. count = 0 # Iterate through each character in the string to check for matches. for c in s: if c == char: count += 1 return count ```
def count_char(s, char): count = 0 for c in s: if c == char: count += 1 return count
keep
14031137760
Write a python function to calculate the total price for multiple items, considering the item's price and quantity. If the quantity of an item is less than 1, then the total price should not consider that item.
```python def total_price(items): # Initialize a variable to accumulate the total price. total = 0 # Iterate through each item in the list to process its price and quantity. for item in items: if item["quantity"] >= 1: total += item["price"] * item["quantity"] return total ```
def total_price(items): total = 0 for item in items: if item["quantity"] >= 1: total += item["price"] * item["quantity"] return total
keep
44169994535
Write a function to check if a given string is a palindrome, considering only alphanumeric characters and ignoring cases.
```python def is_palindrome(s: str) -> bool: # Filter the string to keep only alphanumeric characters and convert to lowercase. s = ''.join(ch.lower() for ch in s if ch.isalnum()) return s == s[::-1] ```
def is_palindrome(s: str) -> bool: s = ''.join(ch.lower() for ch in s if ch.isalnum()) return s == s[::-1]
keep
40713134224
Write a function to check if a string is a palindrome, ignoring case, spaces, and punctuation. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization).
```python def is_palindrome(s): # Normalize the string by removing non-alphanumeric characters and converting to lowercase. s = re.sub(r'[^A-Za-z0-9]', '', s).lower() return s == s[::-1] ```
import re def is_palindrome(s): s = re.sub(r'[^A-Za-z0-9]', '', s).lower() return s == s[::-1]
keep
70034026307
Write a python function to find the maximum product of two integers in a given list of integers.
```python def max_product(nums): # Sort the list to easily access the two largest and two smallest numbers. nums.sort() return max(nums[0] * nums[1], nums[-1] * nums[-2]) ```
def max_product(nums): nums.sort() return max(nums[0] * nums[1], nums[-1] * nums[-2])
keep
12618941165
Write a function to find the largest number in a list of integers using recursion.
```python def find_largest(lst): # Handle base case: return the single element if the list has only one item. if len(lst) == 1: return lst[0] else: return max(lst[0], find_largest(lst[1:])) ```
def find_largest(lst): if len(lst) == 1: return lst[0] else: return max(lst[0], find_largest(lst[1:]))
keep
35113014372
Write a function to find the longest substring without repeating characters in a given string.
```python def longest_substring(s: str) -> int: # Initialize variables to track the current window and the maximum length found. max_len = 0 i = 0 j = 0 smap = {} # Iterate through the string with the right pointer to expand the window. while j < len(s): if s[j] in smap: ...
def longest_substring(s: str) -> int: max_len = 0 i = 0 j = 0 smap = {} while j < len(s): if s[j] in smap: i = smap[s[j]] if smap[s[j]] > i else i max_len = j - i + 1 if j - i + 1 > max_len else max_len smap[s[j]] = j + 1 j += 1 return max_len
keep
40712593534
Write a function to find the largest palindrome number made from the product of two n-digit numbers.
```python def largest_palindrome_product(n): # Define the range of n-digit numbers to iterate over. max_num = 10 ** n - 1 min_num = 10 ** (n - 1) max_palindrome = 0 # Iterate downwards from max_num to min_num for both factors to find the largest palindrome product. for i in range(max_num, min_n...
def largest_palindrome_product(n): max_num = 10 ** n - 1 min_num = 10 ** (n - 1) max_palindrome = 0 for i in range(max_num, min_num - 1, -1): for j in range(i, min_num - 1, -1): product = i * j if product <= max_palindrome: break if str(produc...
keep
70592340280
Write a function that takes a list of strings and returns the length of the longest string in the list.
```python def longest_string_length(strings): # Handle empty list edge case by returning 0 if not strings: return 0 return max(len(s) for s in strings) ```
def longest_string_length(strings): if not strings: return 0 return max(len(s) for s in strings)
keep
30783133822
Write a function that takes a list of integers and returns a list where the elements at odd indices are sorted in ascending order, while the elements at even indices remain unchanged.
```python def odd_index_sort(lst): # Extract elements at odd indices into a separate list for sorting. odd_list = sorted([lst[i] for i in range(1, len(lst), 2)]) # Reconstruct the list by placing sorted odd-index elements back into their original positions. for i in range(1, len(lst), 2): lst[i]...
def odd_index_sort(lst): odd_list = sorted([lst[i] for i in range(1, len(lst), 2)]) for i in range(1, len(lst), 2): lst[i] = odd_list.pop(0) return lst
keep
31691770090
Write a python function to find the maximum product of three numbers in a given list.
```python def max_product(nums): # Sort the list to easily access the largest and smallest elements. nums.sort() return max(nums[0]*nums[1]*nums[-1], nums[-1]*nums[-2]*nums[-3]) ```
def max_product(nums): nums.sort() return max(nums[0]*nums[1]*nums[-1], nums[-1]*nums[-2]*nums[-3])
keep
42011505856
Write a python function to find the longest substring without repeating characters in a given string.
```python def longest_substring_without_repeating_characters(s): # Initialize variables for the sliding window and character tracking char_map = {} left = 0 result = "" max_length = 0 # Iterate through the string with a right pointer to expand the sliding window. for right in range(len(s)): ...
def longest_substring_without_repeating_characters(s): char_map = {} left = 0 result = "" max_length = 0 for right in range(len(s)): if s[right] in char_map: left = max(left, char_map[s[right]] + 1) char_map[s[right]] = right if right - left + 1 > max_length: ...
keep
33761176329
Write a function to check whether the parentheses in the input string are balanced or not. The parentheses are considered as balanced if the open parentheses have a matching close parentheses in the correct order.
```python def is_balanced(s): # Initialize an empty stack to track open parentheses. stack = [] mapping = {")": "(", "}": "{", "]": "["} # Iterate through each character in the string to process opening and closing parentheses. for char in s: if char in mapping: top_element = sta...
def is_balanced(s): stack = [] mapping = {")": "(", "}": "{", "]": "["} for char in s: if char in mapping: top_element = stack.pop() if stack else '#' if mapping[char] != top_element: return False else: stack.append(char) return not sta...
keep
14235356782
Write a python function to find the maximum sum of a subarray with the length of k.
```python def max_subarray_sum(arr,k): # Validate input constraints and handle edge cases where k is invalid or larger than array length. if len(arr) < k: return None max_sum = sum(arr[:k]) temp_sum = max_sum # Iterate through the remaining elements to update the sliding window sum. for ...
def max_subarray_sum(arr,k): if len(arr) < k: return None max_sum = sum(arr[:k]) temp_sum = max_sum for i in range(k,len(arr)): temp_sum = temp_sum - arr[i-k] + arr[i] max_sum = max(max_sum,temp_sum) return max_sum
keep
38729813815
Write a python function to find a given number is perfect or not. A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding the number itself.
```python def is_perfect(n): # Initialize a variable to store the sum of proper divisors. sum = 0 # Iterate from 1 to n-1 to find and sum all proper divisors. for x in range(1, n): if n % x == 0: sum += x return sum == n ```
def is_perfect(n): sum = 0 for x in range(1, n): if n % x == 0: sum += x return sum == n
keep
40713540414
Write a function to check if a given string is a palindrome ignoring case, spaces, and punctuation. A palindrome is a word, phrase, number, or other sequences of characters that reads the same backward or forward.
```python def is_palindrome(s): # Normalize the string by removing non-alphanumeric characters and converting to lowercase. s = re.sub(r'[\W_]', '', s).lower() return s == s[::-1] ```
import re def is_palindrome(s): s = re.sub(r'[\W_]', '', s).lower() return s == s[::-1]
keep
30529273687
Write a python function to find the length of the longest substring without repeating characters.
```python def length_of_longest_substring(s): # Initialize variables for max length, current start index, and character index map if not s: return 0 char_dict = {} left = 0 max_length = 0 # Iterate through the string with a right pointer to expand the window. for right in range(len(s...
def length_of_longest_substring(s): if not s: return 0 char_dict = {} left = 0 max_length = 0 for right in range(len(s)): if s[right] in char_dict: left = max(left, char_dict[s[right]] + 1) char_dict[s[right]] = right max_length = max(max_length, right - l...
keep
19765988651
Write a python function to calculate the minimum number of jumps required to reach the end of an array from the first position. Each element in the array represents the maximum jump length at that position.
```python def min_jumps(nums): # Handle edge cases where the array is empty or has only one element. if len(nums) <= 1: return 0 jumps = 0 current_end = 0 farthest = 0 # Iterate through the array to update the farthest reachable index and increment jumps when the current index reaches th...
def min_jumps(nums): if len(nums) <= 1: return 0 jumps = 0 current_end = 0 farthest = 0 for i in range(len(nums)-1): farthest = max(farthest, i + nums[i]) if i == current_end: jumps += 1 current_end = farthest return jumps
keep
6258425247
Write a python function to find the longest substring without repeating characters in a given string.
```python def longest_substring(s): # Initialize variables to track the start index, maximum length, and character positions. max_len = 0 max_substring = "" start = 0 used_char = {} # Iterate through the string to update the start index and track the longest substring. for i in range(len(s)...
def longest_substring(s): max_len = 0 max_substring = "" start = 0 used_char = {} for i in range(len(s)): if s[i] in used_char and start <= used_char[s[i]]: start = used_char[s[i]] + 1 else: if i - start + 1 > max_len: max_len = i - start + 1 ...
keep
70689234305
Write a python function to find the maximum product of two numbers in an array that contains both positive and negative numbers.
```python def max_product(arr): # Sort the array to easily access the largest and smallest elements. arr.sort() n = len(arr) return max(arr[0] * arr[1], arr[n-1] * arr[n-2]) # Test the function with edge cases including all negatives and mixed signs. print(max_product([1, 2, 3, 4, 5])) # 20 print(max_p...
def max_product(arr): arr.sort() n = len(arr) return max(arr[0] * arr[1], arr[n-1] * arr[n-2]) print(max_product([1, 2, 3, 4, 5])) # 20 print(max_product([-1, -2, -3, -4, -5])) # 20 print(max_product([-1, -2, 0, 1, 2])) # 2 print(max_product([0, 0, 0, 0])) # 0
keep
70726589561
Write a python function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
```python def longest_Common_Prefix(strs): # Handle edge case where the input list is empty. if not strs: return "" shortest_str = min(strs, key=len) # Iterate through characters of the shortest string to check for common prefix. for i, char in enumerate(shortest_str): # Check if the...
def longest_Common_Prefix(strs): if not strs: return "" shortest_str = min(strs, key=len) for i, char in enumerate(shortest_str): for other in strs: if other[i] != char: return shortest_str[:i] return shortest_str
keep
23277414497
Write a function to reverse the order of words in a given sentence.
```python def reverse_words(sentence): # Split the sentence into words, reverse the list, and join them back. words = sentence.split(' ') reversed_sentence = ' '.join(reversed(words)) return reversed_sentence ```
def reverse_words(sentence): words = sentence.split(' ') reversed_sentence = ' '.join(reversed(words)) return reversed_sentence
keep
36552424668
Write a function that takes a list of integers and returns a new list where each element is the product of all the other elements in the original list except the current one. Do this without using division.
```python def multiply_except_self(nums): # Initialize result list with ones. output = [1] * len(nums) left_product = 1 right_product = 1 # Iterate forward to compute left products for each index. for i in range(len(nums)): output[i] *= left_product left_product *= nums[i] ...
def multiply_except_self(nums): output = [1] * len(nums) left_product = 1 right_product = 1 for i in range(len(nums)): output[i] *= left_product left_product *= nums[i] output[-1 - i] *= right_product right_product *= nums[-1 - i] return output
keep
44204619250
Write a python function that takes a list of strings as input and returns a new list of strings where each string is reversed.
```python def reverse_strings(strings): # Initialize an empty list to store the reversed strings. reversed_strings = [] # Iterate through each string in the input list. for string in strings: reversed_strings.append(string[::-1]) return reversed_strings ```
def reverse_strings(strings): reversed_strings = [] for string in strings: reversed_strings.append(string[::-1]) return reversed_strings
keep
36797261519
Write a Python function to find the maximum subarray sum from a given array of integers.
```python def max_subarray_sum(arr): # Initialize variables for current sum and maximum sum. max_so_far = arr[0] curr_max = arr[0] # Iterate through the array starting from the second element to update current and maximum sums. for i in range(1, len(arr)): curr_max = max(arr[i], curr_max + ...
def max_subarray_sum(arr): max_so_far = arr[0] curr_max = arr[0] for i in range(1, len(arr)): curr_max = max(arr[i], curr_max + arr[i]) max_so_far = max(max_so_far, curr_max) return max_so_far
keep
26706759326
Write a python function to find the nth Fibonacci number using recursion.
```python def find_Fibonacci(n): # Handle base cases for n=0 and n=1 if n <= 0: return 0 elif n == 1: return 1 else: return find_Fibonacci(n-1) + find_Fibonacci(n-2) ```
def find_Fibonacci(n): if n <= 0: return 0 elif n == 1: return 1 else: return find_Fibonacci(n-1) + find_Fibonacci(n-2)
keep
70592327480
Write a python function to find the sum of the series 1^3 + 2^3 + 3^3 + ... + n^3.
```python def sum_of_cubes(n): # Initialize a variable to store the cumulative sum. sum = 0 # Iterate from 1 to n and add the cube of each number to the sum. for i in range(1, n+1): sum += i ** 3 return sum ```
def sum_of_cubes(n): sum = 0 for i in range(1, n+1): sum += i ** 3 return sum
keep
28852027848
Write a function to find the longest common prefix string amongst an array of strings.
```python def longest_common_prefix(strs): # Handle edge case where the input list is empty. if not strs: return "" shortest_str = min(strs, key=len) # Iterate through characters of the shortest string to check for a common prefix. for i, char in enumerate(shortest_str): # Check if t...
def longest_common_prefix(strs): if not strs: return "" shortest_str = min(strs, key=len) for i, char in enumerate(shortest_str): for other in strs: if other[i] != char: return shortest_str[:i] return shortest_str
keep
36716433919
Write a function that takes a list of numbers, and returns a new list with the numbers rounded to the nearest integer.
```python def round_list(lst): # Iterate through the list and round each number to the nearest integer. return [round(i) for i in lst] ```
def round_list(lst): return [round(i) for i in lst]
keep
24460749203
Write a function to find the maximum sum of a subarray with the length of exactly k.
```python def max_sum_subarray(arr, k): # Calculate the sum of the first k elements to initialize the sliding window. if len(arr) < k: return None max_sum = sum(arr[:k]) temp_sum = max_sum # Slide the window by subtracting the element going out and adding the element coming in. for i in ...
def max_sum_subarray(arr, k): if len(arr) < k: return None max_sum = sum(arr[:k]) temp_sum = max_sum for i in range(k, len(arr)): temp_sum = temp_sum - arr[i-k] + arr[i] max_sum = max(max_sum, temp_sum) return max_sum
keep
5268511178
Write a python function to find the intersection of two sorted arrays.
```python def intersection(arr1, arr2): # Initialize pointers for both arrays and an empty result list i, j = 0, 0 result = [] # Iterate while both pointers are within bounds while i < len(arr1) and j < len(arr2): if arr1[i] == arr2[j]: if result == [] or result[-1] != arr1[i]: ...
def intersection(arr1, arr2): i, j = 0, 0 result = [] while i < len(arr1) and j < len(arr2): if arr1[i] == arr2[j]: if result == [] or result[-1] != arr1[i]: result.append(arr1[i]) i += 1 j += 1 elif arr1[i] < arr2[j]: i += 1 ...
keep
14025911092
Write a function to find the number of days between two dates.
```python def date_difference(date1, date2): # Parse the input strings into datetime objects to enable arithmetic operations. date_format = "%Y-%m-%d" a = datetime.strptime(date1, date_format) b = datetime.strptime(date2, date_format) delta = b - a return abs(delta.days) ```
from datetime import datetime def date_difference(date1, date2): date_format = "%Y-%m-%d" a = datetime.strptime(date1, date_format) b = datetime.strptime(date2, date_format) delta = b - a return abs(delta.days)
keep
14032490830
Write a function to count the number of distinct words in a given string.
```python def count_distinct_words(s): # Split the string into words and convert to a set to remove duplicates. words = s.split() distinct_words = set(words) return len(distinct_words) ```
def count_distinct_words(s): words = s.split() distinct_words = set(words) return len(distinct_words)
keep
71593338026
Write a python function to find the length of the longest substring without repeating characters.
```python def lengthOfLongestSubstring(s): # Initialize variables to track the current window and maximum length. maxLength = 0 start = 0 usedChar = {} # Iterate through the string to expand the sliding window and update the maximum length. for i in range(len(s)): if s[i] in usedChar an...
def lengthOfLongestSubstring(s): maxLength = 0 start = 0 usedChar = {} for i in range(len(s)): if s[i] in usedChar and start <= usedChar[s[i]]: start = usedChar[s[i]] + 1 else: maxLength = max(maxLength, i - start + 1) usedChar[s[i]] = i return max...
keep
10788765025
Write a function to calculate the minimum number of operations required to make all elements of an array equal, given that you can only increase or decrease the elements by 1. The function should take an array of integers as input and return the minimum number of operations required.
```python def min_operations(nums): # Sort the array to find the median element. nums.sort() median = nums[len(nums) // 2] return sum(abs(num - median) for num in nums) ```
def min_operations(nums): nums.sort() median = nums[len(nums) // 2] return sum(abs(num - median) for num in nums)
keep
6798768329
Write a function to find the length of the longest substring without repeating characters.
```python def longest_substring(s): # Initialize variables to track the start index, max length, and character set char_map = {} left = 0 max_length = 0 # Iterate through the string with a right pointer to expand the window. for right in range(len(s)): if s[right] in char_map: ...
def longest_substring(s): char_map = {} left = 0 max_length = 0 for right in range(len(s)): if s[right] in char_map: left = max(left, char_map[s[right]] + 1) char_map[s[right]] = right max_length = max(max_length, right - left + 1) return max_length
keep
71483630199
Write a function to find the prime factors of a given number.
```python def prime_factors(n): # Initialize an empty list to store the prime factors. i = 2 factors = [] # Loop while i*i <= n to find factors up to the square root of n. while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n ...
def prime_factors(n): i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors
keep
37809494874
Write a python function to check if the given array is a permutation of the first N natural numbers.
```python def is_permutation(arr): # Determine N from the length of the array. n = len(arr) seen = [False] * n # Iterate through the array to mark indices corresponding to valid numbers. for num in arr: if num > n or seen[num - 1]: return False seen[num - 1] = True re...
def is_permutation(arr): n = len(arr) seen = [False] * n for num in arr: if num > n or seen[num - 1]: return False seen[num - 1] = True return all(seen)
keep
2471193636
Write a python function to find the maximum product of three numbers in a given array.
```python def maximum_product(arr): # Sort the array to easily access the largest and smallest elements. arr.sort() return max(arr[0]*arr[1]*arr[-1], arr[-1]*arr[-2]*arr[-3]) ```
def maximum_product(arr): arr.sort() return max(arr[0]*arr[1]*arr[-1], arr[-1]*arr[-2]*arr[-3])
keep
27726077850
Write a function to find the number of ways to decode a message given a mapping of characters to numbers. Each character is mapped to a unique number from 1 to 26, and a number can represent either a single character or a combination of two characters.
```python def decode_variations(s): # Handle edge cases for empty string or leading zeros if not s or s[0] == "0": return 0 n = len(s) dp = [0] * (n + 1) dp[0], dp[1] = 1, 1 # Iterate through the string to fill the DP table by checking single and double digit decodings. for i in rang...
def decode_variations(s): if not s or s[0] == "0": return 0 n = len(s) dp = [0] * (n + 1) dp[0], dp[1] = 1, 1 for i in range(2, n + 1): one = int(s[i-1:i]) two = int(s[i-2:i]) if 1 <= one <= 9: dp[i] += dp[i-1] if 10 <= two <= 26: dp[i]...
keep
34424813208
Write a function to find the minimum number of swaps required to sort a given array.
```python def minSwaps(nums): # Create a list of (value, original_index) pairs to track element positions. n = len(nums) arrPos = [*enumerate(nums)] arrPos.sort(key=lambda it: it[1]) vis = {k: False for k in range(n)} ans = 0 # Iterate through the array to identify and process disjoint cycle...
def minSwaps(nums): n = len(nums) arrPos = [*enumerate(nums)] arrPos.sort(key=lambda it: it[1]) vis = {k: False for k in range(n)} ans = 0 for i in range(n): if vis[i] or arrPos[i][0] == i: continue cycle_size = 0 j = i while not vis[j]: vi...
keep
44020145398
Write a python function to find the smallest positive integer that does not occur in a given list of integers.
```python def find_missing(A): # Convert list to a set for O(1) lookups and iterate from 1 to find the first missing positive. A_set = set(A) n = len(A) + 1 # Iterate from 1 to n to find the first integer not in A_set. for i in range(1, n+1): if i not in A_set: return i ```
def find_missing(A): A_set = set(A) n = len(A) + 1 for i in range(1, n+1): if i not in A_set: return i
keep
2067375753
Implement a function that checks if a given string is a valid IPv4 address. A valid IPv4 address consists of four numbers separated by periods. Each number is between 0 and 255. Leading zeros are allowed in the number, but not allowed between the numbers and the period.
```python def is_valid_ipv4(ip): # Split the input string by periods to isolate the four octets. parts = ip.split('.') if len(parts) != 4: return False # Validate that each part is a numeric string within the 0-255 range. for part in parts: if not part.isdigit(): return F...
def is_valid_ipv4(ip): parts = ip.split('.') if len(parts) != 4: return False for part in parts: if not part.isdigit(): return False if part[0] == '0' and len(part) > 1: return False if int(part) < 0 or int(part) > 255: return False ret...
keep
1098150279
Write a function that checks if a given string is a valid palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward, ignoring spaces, punctuation, and capitalization.
```python def is_valid_palindrome(s: str) -> bool: # Normalize the string by removing non-alphanumeric characters and converting to lowercase. s = re.sub(r'[^a-zA-Z0-9]', '', s).lower() return s == s[::-1] ```
import re def is_valid_palindrome(s: str) -> bool: s = re.sub(r'[^a-zA-Z0-9]', '', s).lower() return s == s[::-1]
keep
26753274806
Write a python function to find the smallest number evenly divisible by all numbers from 1 to n.
```python def smallest_divisible(n): # Calculate the Least Common Multiple (LCM) of all integers from 1 to n. def lcm(a, b): return a * b // gcd(a, b) return reduce(lcm, range(1, n + 1)) ```
from math import gcd from functools import reduce def smallest_divisible(n): def lcm(a, b): return a * b // gcd(a, b) return reduce(lcm, range(1, n + 1))
keep
893965871
Write a function to find the nth Fibonacci number using an iterative method.
```python def nth_fibonacci(n): # Handle base cases for n <= 1 if n <= 0: return 0 elif n == 1: return 1 else: a, b = 0, 1 # Iterate from 2 to n, updating a and b to calculate the next Fibonacci number for _ in range(2, n + 1): a, b = b, a + b ...
def nth_fibonacci(n): if n <= 0: return 0 elif n == 1: return 1 else: a, b = 0, 1 for _ in range(2, n + 1): a, b = b, a + b return b
keep
2389694147
Write a function to find the second largest number in a list of integers.
```python def find_second_largest(nums): # Check if the list has fewer than 2 elements to handle edge cases. if len(nums) < 2: return None nums = list(set(nums)) if len(nums) < 2: return None nums.remove(max(nums)) return max(nums) ```
def find_second_largest(nums): if len(nums) < 2: return None nums = list(set(nums)) if len(nums) < 2: return None nums.remove(max(nums)) return max(nums)
keep
7704079825
Write a Python function to calculate the factorial of a non-negative integer using recursion.
```python def factorial(n): # Check base case: return 1 if n is 0. if n == 0: return 1 else: return n * factorial(n-1) ```
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)
keep
42514511718
Write a function to find the smallest k elements in an array using a min heap.
```python def find_smallest_k(arr, k): # Import heapq and heapify the array to build a min heap heapq.heapify(arr) return heapq.nsmallest(k, arr) ```
import heapq def find_smallest_k(arr, k): heapq.heapify(arr) return heapq.nsmallest(k, arr)
keep
72101380907
Write a function to check if a given string is a valid palindrome ignoring non-alphanumeric characters and case sensitivity. An input string is valid palindrome if: - It reads the same backward as forward when ignoring non-alphanumeric characters and case sensitivity.
```python def is_valid_palindrome(s: str) -> bool: # Filter the string to keep only alphanumeric characters and convert to lowercase. s = ''.join([i.lower() for i in s if i.isalnum()]) # Remove non-alphanumeric characters and convert to lowercase return s == s[::-1] # Check if original string is equal to re...
def is_valid_palindrome(s: str) -> bool: s = ''.join([i.lower() for i in s if i.isalnum()]) # Remove non-alphanumeric characters and convert to lowercase return s == s[::-1] # Check if original string is equal to reversed string
keep
24589344654
Write a python function to find the largest continuous sum in a list.
```python def largest_cont_sum(arr): # Handle edge case where the input list is empty. if len(arr)==0: return 0 max_sum = current_sum = arr[0] # Iterate through the remaining elements to update current and max sums. for num in arr[1:]: current_sum = max(current_sum+num, num) ...
def largest_cont_sum(arr): if len(arr)==0: return 0 max_sum = current_sum = arr[0] for num in arr[1:]: current_sum = max(current_sum+num, num) max_sum = max(current_sum, max_sum) return max_sum
keep
33427248194
Write a python function to find the nth number in the Fibonacci sequence using dynamic programming.
```python def fibonacci(n): # Handle base cases for n <= 1 if n <= 1: return n temp = [0 for i in range(n + 1)] temp[0] = 0 temp[1] = 1 # Iterate from 2 to n to fill the array using the recurrence relation for i in range(2, n + 1): temp[i] = temp[i - 1] + temp[i - 2] retu...
def fibonacci(n): if n <= 1: return n temp = [0 for i in range(n + 1)] temp[0] = 0 temp[1] = 1 for i in range(2, n + 1): temp[i] = temp[i - 1] + temp[i - 2] return temp[n]
keep
32907098546
Write a python function to find the length of the longest substring without repeating characters in a given string.
```python def length_of_longest_substring(s): # Initialize variables for the sliding window start index and maximum length. """ :type s: str :rtype: int """ char_map = {} left = 0 max_length = 0 # Iterate through the string with a right pointer to expand the sliding window. for r...
def length_of_longest_substring(s): """ :type s: str :rtype: int """ char_map = {} left = 0 max_length = 0 for right in range(len(s)): if s[right] in char_map: left = max(left, char_map[s[right]] + 1) char_map[s[right]] = right max_length = max(max_len...
keep
38442874311
Write a python function to find the number of times a given target value appears in a list.
```python def count_occurrences(lst, target): # Use the list's built-in count method to return the frequency of the target. return lst.count(target) ```
def count_occurrences(lst, target): return lst.count(target)
keep
33520201148
Write a python function to find the maximum number that can be formed by rearranging the digits of a given number.
```python def max_number(n): # Convert the number to a list of digits, sort them in descending order, and join them back into a string. return int("".join(sorted(str(n), reverse=True))) ```
def max_number(n): return int("".join(sorted(str(n), reverse=True)))
keep
30783246802
Write a function that takes a list of integers and returns a list where the integers are replaced by their corresponding binary representations as strings.
```python def convert_to_binary(nums): # Iterate through the input list to convert each integer to its binary string representation using `bin()` and strip the '0b' prefix. return [bin(num)[2:] for num in nums] ```
def convert_to_binary(nums): return [bin(num)[2:] for num in nums]
keep
12638401079
Write a python function to find the maximum product of three numbers in an array.
```python def max_product(nums): # Sort the array to easily access the largest and smallest elements. nums.sort() return max(nums[0]*nums[1]*nums[-1], nums[-1]*nums[-2]*nums[-3]) # Add test cases to verify the function with positive, negative, and mixed number arrays. assert max_product([1,2,3,4]) == 24 as...
def max_product(nums): nums.sort() return max(nums[0]*nums[1]*nums[-1], nums[-1]*nums[-2]*nums[-3]) assert max_product([1,2,3,4]) == 24 assert max_product([-1,-2,-3,1]) == 6 assert max_product([1,2,3]) == 6
keep
15574996008
Write a function that takes a list of integers as input and returns a list of unique elements in the same order as they appear in the original list.
```python def unique_elements(lst): # Initialize an empty list to store unique elements and a set for O(1) lookups. seen = set() result = [] # Iterate through the input list to process each element. for i in lst: if i not in seen: result.append(i) seen.add(i) retu...
def unique_elements(lst): seen = set() result = [] for i in lst: if i not in seen: result.append(i) seen.add(i) return result
keep
17238465167
Write a Python function to find the kth smallest element from the given array using QuickSelect algorithm.
```python def partition(arr, low, high): # Choose the pivot and initialize the partition index. pivot = arr[high] i = low - 1 # Iterate through the array to move elements smaller than the pivot to the left side. for j in range(low, high): if arr[j] <= pivot: i += 1 ar...
def partition(arr, low, high): pivot = arr[high] i = low - 1 for j in range(low, high): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1 def quick_select(arr, low, high, k): if low == high: ...
keep
9880825531
Write a python function to check if a given string can be segmented into a space-separated sequence of one or more dictionary words.
```python def wordBreak(s: str, wordDict: List[str]) -> bool: # Convert wordDict to a set for O(1) lookup efficiency wordSet = set(wordDict) dp = [False] * (len(s) + 1) dp[0] = True # Iterate through each position to check if any preceding valid segment forms a word for i in range(1, len(s) + 1...
from typing import List def wordBreak(s: str, wordDict: List[str]) -> bool: wordSet = set(wordDict) dp = [False] * (len(s) + 1) dp[0] = True for i in range(1, len(s) + 1): for j in range(i): if dp[j] and s[j:i] in wordSet: dp[i] = True break ret...
keep
42089941302
Write a function that takes a list of strings as input and returns a dictionary where the keys are the unique strings from the input list and the values are the frequencies of those strings in the input list.
```python def string_frequency(strings): # Initialize an empty dictionary to store the frequencies. frequency = {} # Iterate through each string in the input list to count occurrences. for string in strings: if string in frequency: frequency[string] += 1 else: fre...
def string_frequency(strings): frequency = {} for string in strings: if string in frequency: frequency[string] += 1 else: frequency[string] = 1 return frequency
keep
71238505706
Write a function that takes a string as input and returns a new string where all the vowels are removed.
```python def remove_vowels(text): # Define a set of vowels to check against. vowels = "aeiouAEIOU" result = "" # Iterate through each character in the input string. for char in text: if char not in vowels: result += char return result ```
def remove_vowels(text): vowels = "aeiouAEIOU" result = "" for char in text: if char not in vowels: result += char return result
keep
22870469135
Write a function to find the least common multiple (LCM) of two positive integers.
```python def least_common_multiple(a, b): # Calculate LCM using the formula: (a * b) // gcd(a, b) def gcd(x, y): while(y): x, y = y, x % y return x return a * b // gcd(a, b) ```
def least_common_multiple(a, b): def gcd(x, y): while(y): x, y = y, x % y return x return a * b // gcd(a, b)
keep
22357532507
Write a python function to find the maximum subarray sum from a given list of integers.
```python def max_subarray_sum(nums): # Initialize variables to track current and maximum subarray sums. max_current = max_global = nums[0] # Iterate through the list starting from the second element to update current and global maximums. for i in range(1,len(nums)): max_current = max(nums[i], m...
def max_subarray_sum(nums): max_current = max_global = nums[0] for i in range(1,len(nums)): max_current = max(nums[i], max_current + nums[i]) if max_current > max_global: max_global = max_current return max_global
keep
26753646026
Write a function to find the maximum depth of a binary tree.
```python class TreeNode: # Define the TreeNode class with val, left, and right attributes. def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # Define the max_depth function to calculate the tree's height recursively. def max_depth(root...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def max_depth(root: TreeNode) -> int: if root is None: return 0 else: left_height = max_depth(root.left) right_height = max_depth(root.right) ...
keep
31707886
Write a function to find the missing number in the given array.
```python def find_missing(arr, n): # Calculate the expected sum of 1 to n and subtract the actual array sum. total = (n * (n + 1)) // 2 sum_of_arr = sum(arr) return total - sum_of_arr ```
def find_missing(arr, n): total = (n * (n + 1)) // 2 sum_of_arr = sum(arr) return total - sum_of_arr
keep
16103995269
Write a function that takes two lists as input and returns a new list with elements from the first list that are not present in the second list. The function should maintain the order of elements in the first list.
```python def list_difference(list1, list2): # Iterate through list1 and append elements not found in list2 to a result list. """ Returns a new list with elements from list1 that are not present in list2, preserving the order of elements in list1. """ return [x for x in list1 if x not in list2] ```
def list_difference(list1, list2): """ Returns a new list with elements from list1 that are not present in list2, preserving the order of elements in list1. """ return [x for x in list1 if x not in list2]
keep
16096067839
Write a function that takes in a list of strings and returns the longest common prefix among them.
```python def longest_common_prefix(strs): # Handle edge case where the input list is empty. if not strs: return "" shortest_str = min(strs, key=len) # Iterate through characters of the shortest string to build the common prefix. for i, char in enumerate(shortest_str): # Check if the...
def longest_common_prefix(strs): if not strs: return "" shortest_str = min(strs, key=len) for i, char in enumerate(shortest_str): for other in strs: if other[i] != char: return shortest_str[:i] return shortest_str
keep
2175887565
Write a function to calculate the length of the longest palindrome that can be built with the letters of the given string. A palindrome is a word, phrase, or sequence that reads the same backward as forward. For example, "radar" is a palindrome. The function should consider that a palindrome does not need to be limit...
```python def longest_palindrome(s: str) -> int: # Count the frequency of each character in the string. char_count = Counter(s) length = 0 odd_found = False # Iterate through character counts to add even pairs and handle the single odd character. for count in char_count.values(): if coun...
from collections import Counter def longest_palindrome(s: str) -> int: char_count = Counter(s) length = 0 odd_found = False for count in char_count.values(): if count % 2 == 0: length += count else: length += count - 1 odd_found = True return leng...
keep
25869496826
Write a function to determine if a given string is a valid parentheses string. A valid parentheses string is either empty, "(U)", or U + V where U and V are valid parentheses strings, and + represents concatenation. For example, "", "()", "(())()", and "(()(()))" are valid parentheses strings while "(", ")", and "(()" ...
```python def is_valid_parentheses(s: str) -> bool: # Initialize a counter to track the balance of open and close parentheses. # Initialize a counter for tracking the balance of parentheses balance = 0 # Iterate through the string # Check if the current character is an opening or closing parenthesis...
def is_valid_parentheses(s: str) -> bool: # Initialize a counter for tracking the balance of parentheses balance = 0 # Iterate through the string for char in s: # If an opening parenthesis is found, increment the balance if char == '(': balance += 1 # If a closing par...
keep
24491396334
Write a function to find the length of the longest substring without repeating characters in a given string.
```python def length_of_longest_substring(s): # Initialize variables for the sliding window and max length if not s: return 0 left = 0 max_length = 0 used_char = {} # Iterate through the string with a right pointer to expand the sliding window. for right in range(len(s)): if...
def length_of_longest_substring(s): if not s: return 0 left = 0 max_length = 0 used_char = {} for right in range(len(s)): if s[right] in used_char and left <= used_char[s[right]]: left = used_char[s[right]] + 1 else: max_length = max(max_length, right...
keep
32284727255
Write a python function to calculate the number of ways a given number can be expressed as the sum of 1, 3, and 4.
```python def number_of_ways(n): # Initialize base cases for n=0, n=1, n=2, and n=3 if n == 0 or n == 1: return 1 elif n == 2: return 1 elif n == 3: return 2 else: a, b, c, d = 1, 1, 1, 2 # Iterate from 4 to n, updating the window of the last four values to co...
def number_of_ways(n): if n == 0 or n == 1: return 1 elif n == 2: return 1 elif n == 3: return 2 else: a, b, c, d = 1, 1, 1, 2 for i in range(4, n+1): d = a + b + c a, b, c = b, c, d return d
keep
19434196447
Write a function to count the number of times a specific character occurs in a string.
```python def char_count(string, char): # Initialize a counter variable to zero. count = 0 # Iterate through each character in the string to check for matches. for c in string: if c == char: count += 1 return count ```
def char_count(string, char): count = 0 for c in string: if c == char: count += 1 return count
keep
10294423727
Write a Python function that checks if two strings are anagrams of each other.
```python def is_anagram(str1, str2): # Normalize strings by removing spaces and converting to lowercase # Remove whitespaces and convert strings to lowercase str1 = str1.replace(" ", "").lower() str2 = str2.replace(" ", "").lower() # Compare sorted characters of both strings to determine if th...
def is_anagram(str1, str2): # Remove whitespaces and convert strings to lowercase str1 = str1.replace(" ", "").lower() str2 = str2.replace(" ", "").lower() # Check if the sorted characters of both strings are equal return sorted(str1) == sorted(str2) # Test the function with provided test case...
keep
30529771337
Write a python function to find the maximum product of three numbers in a list. The list can contain both positive and negative numbers.
```python def max_product(nums): # Sort the list to easily access the largest and smallest elements. nums.sort() return max(nums[0]*nums[1]*nums[-1], nums[-1]*nums[-2]*nums[-3]) ```
def max_product(nums): nums.sort() return max(nums[0]*nums[1]*nums[-1], nums[-1]*nums[-2]*nums[-3])
keep
43310335251
Write a function to find the maximum subarray sum in a given list. The function should return the maximum sum of any contiguous subarray within the list. This problem is known as the Maximum Subarray problem and can be solved using Kadane's algorithm.
```python def max_subarray_sum(nums): # Initialize current_sum and max_sum to the first element of the list max_current = max_global = nums[0] # Iterate through the list starting from the second element to update current and global maximums for i in range(1, len(nums)): max_current = max(nums[i]...
def max_subarray_sum(nums): max_current = max_global = nums[0] for i in range(1, len(nums)): max_current = max(nums[i], max_current + nums[i]) if max_current > max_global: max_global = max_current return max_global
keep
1759476212
Write a python function to find the longest common prefix string amongst a list of strings. If there is no common prefix, return an empty string "".
```python def longest_common_prefix(strs): # Handle edge cases for empty input or single string. if not strs: return "" shortest_str = min(strs, key=len) # Iterate through characters of the shortest string to check for a common prefix. for i, char in enumerate(shortest_str): # Check ...
def longest_common_prefix(strs): if not strs: return "" shortest_str = min(strs, key=len) for i, char in enumerate(shortest_str): for other in strs: if other[i] != char: return shortest_str[:i] return shortest_str
keep
12120495253
Write a function to find the length of the longest substring without repeating characters in a given string.
```python def longest_substring(s): # Initialize variables to track the start index, maximum length, and character positions. char_map = {} left = 0 max_length = 0 # Iterate through the string to update the sliding window and track the maximum length. for right in range(len(s)): if ...
def longest_substring(s): char_map = {} left = 0 max_length = 0 for right in range(len(s)): if s[right] in char_map: left = max(left, char_map[s[right]] + 1) char_map[s[right]] = right max_length = max(max_length, right - left + 1) return max_length
keep
End of preview.
README.md exists but content is empty.
Downloads last month
4