Coding Questions
Coding Questions
def find_max(arr):
if not arr:
raise ValueError("List is empty")
max_val = arr[0]
for item in arr:
if item > max_val:
max_val = item
return max_val
# Example usage
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
print(f"The {k}-th minimum value: {kth_min}") # Output: The 3-th minimum value: 3
print(f"The {k}-th maximum value: {kth_max}") # Output: The 3-th maximum value: 5
except ValueError as e:
print(e)
Args:
arr (list): The list containing only 0s, 1s, and 2s.
Returns:
None: The list is sorted in place.
"""
low = 0
mid = 0
high = len(arr) - 1
# Example usage
arr = [2, 0, 1, 2, 0, 1, 0]
sort_012(arr)
print(arr) # Output: [0, 0, 0, 1, 1, 2, 2]
5.Move all the negative elements to one side of the array
. # Python code for the same approach
def move(arr):
arr.sort()
# driver code
arr = [ -1, 2, -3, 4, 5, 6, -7, 8, 9 ]
move(arr)
for e in arr:
print(e , end = " ")
Args:
arr1 (list): The first sorted list.
arr2 (list): The second sorted list.
Returns:
tuple: A tuple containing two lists: (union, intersection).
"""
union = []
intersection = []
i=0
j=0
# Example usage
arr1 = [1, 2, 4, 5, 6]
arr2 = [2, 3, 5, 7]
7.def rotate_array_by_one(arr):
"""
Cyclically rotates an array by one position to the right.
Args:
arr (list): The list of elements to rotate.
Returns:
None: The array is rotated in place.
"""
if len(arr) <= 1:
return # No rotation needed for empty or single-element arrays
# Example usage
arr = [1, 2, 3, 4, 5]
rotate_array_by_one(arr)
print(arr) # Output: [5, 1, 2, 3, 4]
8. def max_subarray_sum(arr):
"""
Finds the largest sum of a contiguous subarray using Kadane's Algorithm.
Args:
arr (list): The list of integers.
Returns:
int: The largest sum of the contiguous subarray.
"""
if not arr:
return 0 # Handle edge case where the list is empty
return max_global
# Example usage
arr = [1, -2, 3, 4, -1, 2, 1, -5, 4]
result = max_subarray_sum(arr)
print("The largest sum of the contiguous subarray is:", result) # Output: 10
# Example usage:
heights = [1, 15, 10]
k=6
result = minimize_max_diff(heights, k)
print(f"The minimized maximum difference is: {result}")
# If current index is greater than or equal to the max reachable point, return -1
if i >= max_reach:
return -1
# Reinitialize steps
step = max_reach - i
# Example usage:
arr = [2, 3, 1, 1, 2, 4, 2, 0, 1, 1]
result = min_jumps(arr)
print(f"Minimum number of jumps to reach the end: {result}")
return slow
# Example usage:
nums = [3, 1, 3, 4, 2]
result
# Example usage:
arr1 = [1, 4, 7, 8, 10]
arr2 = [2, 3, 9]
n = len(arr1)
m = len(arr2)
merge(arr1, arr2, n, m)
print("Merged arr1:", arr1)
print("Merged arr2:", arr2)
return max_global
# Example usage:
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
result = kadane(arr)
print(f"The maximum subarray sum is: {result}")
def merge_intervals(intervals):
if not intervals:
return []
return merged
# Example usage:
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
result = merge_intervals(intervals)
print(f"Merged Intervals: {result}")
return nums
# Example usage:
nums = [1, 2, 3]
print(next_permutation(nums)) # Output: [1, 3, 2]
inv_count = 0
temp_arr[k] = arr[i]
i += 1
else:
temp_arr[k] = arr[j]
inv_count += (mid-i + 1) # All remaining elements in the left subarray are inversions
j += 1
k += 1
temp_arr[k] = arr[i]
i += 1
k += 1
j += 1
k += 1
arr[i] = temp_arr[i]
return inv_count
inv_count = 0
return inv_count
def count_inversions(arr):
temp_arr = [0]*len(arr)
return merge_sort_and_count(arr, temp_arr, 0, len(arr)-1)
# Example usage
return 0
return max_profit
# Example usage
prices = [7, 1, 5, 3, 6, 4]
if complement in seen:
pairs.append((complement, num))
seen.add(num)
return pairs
# Example usage
target_sum = 6
common_elements = []
# Traverse all three arrays while elements are left in all of them
# If all three elements are equal, add it to the result and move all pointers
common_elements.append(arr1[i])
i += 1
j += 1
k += 1
i += 1
j += 1
else:
k += 1
return common_elements
# Example usage
n = len(arr)
# Step 1: Partition the array to move negative numbers to the left side and positive numbers
to the right side
for j in range(n):
if arr[j] < 0:
i += 1
arr[i], arr[j] = arr[j], arr[i] # Swap negative number to the left side
# Now, all negative numbers are on the left and positive numbers are on the right
while pos < n and neg < pos and arr[neg] < 0:
pos += 1
neg += 2 # Move the negative index by 2 to maintain alternating order
return arr
# Example usage
result = rearrange_alternate(arr)
cumulative_sum = set()
current_sum = 0
current_sum += num
# If current sum is 0 or already exists in the set, we found a subarray with sum 0
return True
# Add the current sum to the set
cumulative_sum.add(current_sum)
return False
# Example usage
result = subarray_with_zero_sum(arr)
result = 1
result *= i
return result
# Example usage
if not arr:
return 0
# Initialize variables
if num < 0:
return result
# Example usage
result = max_product_subarray(arr)
if not arr:
return 0
num_set = set(arr)
longest_streak = 0
current_num = num
current_streak = 1
current_num += 1
current_streak += 1
# Example usage
result = longest_consecutive_subsequence(arr)
n = len(arr)
if k <= 1:
candidates = {}
if num in candidates:
candidates[num] += 1
candidates[num] = 1
else:
to_remove = []
candidates[key] -= 1
if candidates[key] == 0:
to_remove.append(key)
del candidates[key]
if num in candidates:
candidates[num] += 1
result = []
if count > n // k:
result.append(num)
return result
# Example usage
arr = [1, 2, 3, 1, 1, 2, 2, 3, 3, 4, 4]
k=3
result = find_elements_appearing_more_than_n_by_k(arr, k)
n = len(prices)
if n == 0:
return 0
profit_one = [0] * n
profit_two = [0] * n
min_price = prices[0]
max_price = prices[-1]
max_profit = 0
for i in range(n):
max_profit = max(max_profit, profit_one[i] + profit_two[i])
return max_profit
# Example usage
result = max_profit_with_two_transactions(prices)
# Convert arr1 to a set for O(1) average time complexity for membership checks
set_arr1 = set(arr1)
return False
return True
# Example usage
arr2 = [11, 3, 7]
n = len(arr)
triplets = []
left = i + 1
right = n - 1
if current_sum == target_sum:
left += 1
right -= 1
left += 1
right -= 1
left += 1
else:
right -= 1
return triplets
# Example usage
target_sum = 0
if not height:
return 0
n = len(height)
left_max = [0] * n
right_max = [0] * n
left_max[0] = height[0]
total_water = 0
for i in range(n):
return total_water
# Example usage
height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
result = trap(height)
n = len(arr)
if m > n:
return -1
min_diff = float('inf')
return min_diff
# Example usage
arr = [12, 4, 7, 9, 2, 23, 25, 41, 30, 40, 28, 42, 30, 44, 48, 43, 50]
m = 7 # Number of students
result = find_min_diff(arr, m)
n = len(arr)
min_length = float('inf')
current_sum = 0
start = 0
for end in range(n):
current_sum += arr[end]
# Contract the window as long as the current_sum is greater than the target_sum
current_sum -= arr[start]
start += 1
# Example usage
target_sum = 51
print(f"Length of the smallest subarray with sum greater than {target_sum}: {result}")
low = 0
mid = 0
high = len(arr) - 1
low += 1
mid += 1
mid += 1
else:
high -= 1
# Example usage
arr = [3, 8, 2, 1, 5, 6, 4, 7]
pivot = 5
three_way_partition(arr, pivot)
n = len(arr)
# Find the number of elements greater than K in the initial window of size `count`
min_swaps = current_window
# Slide the window across the array
if arr[i] > K:
current_window += 1
current_window -= 1
return min_swaps
# Example usage
arr = [1, 3, 5, 2, 8, 6, 4, 7]
K=5
result = min_swaps_to_bring_elements_together(arr, K)
n = len(arr)
l, r = 0, n - 1
operations = 0
while l < r:
if arr[l] != arr[r]:
operations += 1
l += 1
r -= 1
return operations
# Example usage
arr = [1, 3, 5, 3, 1]
result = min_operations_to_make_palindrome(arr)
n = len(A)
A, B = B, A
# Correct partition
if (n + n) % 2 == 0:
else:
high = partitionA - 1
else:
low = partitionA + 1
# Example usage
A = [1, 3, 8, 9, 15]
result = find_median_sorted_arrays(A, B)
A, B = B, A
m, n = len(A), len(B)
low, high = 0, m
partitionB = (m + n + 1) // 2 - partitionA
else:
high = partitionA - 1
else:
low = partitionA + 1
# Example usage
A = [1, 3, 8]
result = find_median_sorted_arrays(A, B)
count = 0
while n:
return count
# Example usage
result = count_set_bits_bitwise(n)
2. def find_two_non_repeating_elements(arr):
xor_all = 0
xor_all ^= num
num1, num2 = 0, 0
num1 ^= num
else:
num2 ^= num
# Example usage
arr = [4, 3, 2, 7, 8, 2, 3, 1]
result = find_two_non_repeating_elements(arr)
xor_result = A ^ B
count = 0
while xor_result:
count += xor_result & 1 # Increment count if the least significant bit is 1
return count
# Example usage
A = 29 # Binary: 11101
B = 15 # Binary: 01111
result = count_bits_to_flip(A, B)
4. def count_set_bits(n):
count = 0
i=0
i += 1
return count
# Example usage
n=5
result = count_set_bits(n)
5. def is_power_of_two(n):
# A number is a power of two if it has exactly one bit set and is greater than zero
# Example usage
n = 16
result = is_power_of_two(n)
6. def find_position_of_set_bit(n):
raise ValueError("The number does not have exactly one set bit.")
# Find the position of the only set bit
position = 1
while n > 1:
position += 1
return position
# Example usage
n = 16 # Binary: 00010000
position = find_position_of_set_bit(n)
left = all_ones << (end + 1) # Mask for bits left of the range
# Clear the bits in the target number within the range [start, end]
return target_with_bits
# Example usage
INT_MAX = 2**31 - 1
INT_MIN = -2**31
if dividend == 0:
return 0
if divisor == 0:
quotient = 0
# Find the highest bit where (divisor << power) is <= dividend
power -= 1
quotient = -quotient
return INT_MIN
return INT_MAX
return quotient
# Example usage
dividend = 10
divisor = 3
if n < 0:
n = -n # Square of a negative number is the same as the square of its positive counterpart
result = 0
odd_number = 1
# Sum the first n odd numbers
for _ in range(n):
result += odd_number
odd_number += 2
return result
# Example usage
number = 5
result = square_number(number)
result = []
for i in range(power_set_size):
subset = []
for j in range(len(nums)):
subset.append(nums[j])
result.append(subset)
return result
# Example usage
nums = [1, 2, 3]
result = power_set(nums)
1. class TrieNode:
def __init__(self):
self.children = {} # Dictionary to store child nodes
self.is_end_of_word = False # Flag to mark the end of a word
class Trie:
def __init__(self):
self.root = TrieNode() # Initialize the root of the trie
# Example usage
trie = Trie()
trie.insert("hello")
trie.insert("world")
2. class TrieNode:
def __init__(self):
self.children = {} # Dictionary to store child nodes
self.count = 0 # Count of how many words pass through this node
class Trie:
def __init__(self):
self.root = TrieNode()
return unique_prefixes
# Example usage
words = ["apple", "banana", "appetizer", "bat", "batman"]
unique_prefixes = find_shortest_unique_prefixes(words)
print("Shortest unique prefixes:")
for word, prefix in unique_prefixes.items():
print(f"{word}: {prefix}")
4. class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end_of_word = True
def word_break(s, dictionary):
# Build the trie from the dictionary
trie = Trie()
for word in dictionary:
trie.insert(word)
return dp[len(s)]
# Example usage
dictionary = ["apple", "pie", "applepie"]
s = "applepie"
print(word_break(s, dictionary)) # Output: True
s = "applepieb"
print(word_break(s, dictionary)) # Output: False
def group_anagrams(words):
# Dictionary to store lists of anagrams
anagram_dict = defaultdict(list)
# Example usage
words = ["eat", "tea", "tan", "ate", "nat", "bat"]
group_anagrams(words)
7. class PhoneDirectory:
def __init__(self):
self.contacts = {} # Dictionary to store contacts
def list_contacts(self):
"""List all contacts in the directory."""
if self.contacts:
for name, phone_number in self.contacts.items():
print(f"Name: {name}, Phone Number: {phone_number}")
else:
print("No contacts in the directory.")
# Example usage
directory = PhoneDirectory()
directory.add_contact("Alice", "123-456-7890")
directory.add_contact("Bob", "987-654-3210")
print(directory.search_contact("Alice"))
print(directory.search_contact("Charlie"))
directory.list_contacts()
directory.remove_contact("Alice")
directory.list_contacts()
8. def print_unique_rows(matrix):
unique_rows = set()
# Example usage
matrix = [
[1, 0, 1],
[0, 1, 0],
[1, 0, 1],
[0, 1, 0],
[1, 1, 0]
]
1. class MinHeap:
def __init__(self):
self.heap = []
if smallest != i:
self.heap[i], self.heap[smallest] = self.heap[smallest], self.heap[i]
self.min_heapify(smallest)
def extract_min(self):
if len(self.heap) < 1:
return None
min_item = self.heap[0]
self.heap[0] = self.heap.pop()
self.min_heapify(0)
return min_item
def build_min_heap(self):
for i in range(len(self.heap) // 2 - 1, -1, -1):
self.min_heapify(i)
def __str__(self):
return str(self.heap)
# Example usage
min_heap = MinHeap()
min_heap.insert(10)
min_heap.insert(20)
min_heap.insert(5)
min_heap.build_min_heap()
print("Min-Heap:", min_heap)
print("Extract Min:", min_heap.extract_min())
print("Min-Heap after extraction:", min_heap)
2. class MaxHeap:
def __init__(self, array):
self.heap = array
self.build_max_heap()
if largest != i:
self.heap[i], self.heap[largest] = self.heap[largest], self.heap[i]
self.max_heapify(largest, size)
def build_max_heap(self):
for i in range(len(self.heap) // 2 - 1, -1, -1):
self.max_heapify(i, len(self.heap))
def heap_sort(array):
max_heap = MaxHeap(array)
size = len(max_heap.heap)
return max_heap.heap
# Example usage
array = [4, 10, 3, 5, 1]
sorted_array = heap_sort(array)
print("Sorted Array:", sorted_array)
n = len(arr)
if k > n:
return []
max_elements = []
dq = deque() # To store indices of array elements
for i in range(n):
# Remove elements outside the current window
if dq and dq[0] == i - k:
dq.popleft()
# Remove elements from the deque that are smaller than the current element
while dq and arr[dq[-1]] < arr[i]:
dq.pop()
# Add the current element's index to the deque
dq.append(i)
return max_elements
# Example usage
arr = [1, 3, -1, -3, 5, 3, 6, 7]
k=3
print("Maximum of all subarrays of size", k, ":", max_of_subarrays
4. import heapq
# Example usage
arr = [3, 2, 1, 5, 6, 4]
k=2
print("The", k, "largest elements are:", k_largest_elements_heap(arr, k))
5. import heapq
def kth_smallest_largest_heap(arr, k):
if k <= 0 or k > len(arr):
return None, None
kth_largest = min_heap[0]
# Max-Heap for k-th smallest element (using negative values for max-heap simulation)
max_heap = []
for num in arr:
if len(max_heap) < k:
heapq.heappush(max_heap, -num)
elif -num > max_heap[0]:
heapq.heappushpop(max_heap, -num)
kth_smallest = -max_heap[0]
# Example usage
arr = [3, 2, 1, 5, 6, 4]
k=2
kth_smallest, kth_largest = kth_smallest_largest_heap(arr, k)
print(f"The {k}th smallest element is: {kth_smallest}")
print(f"The {k}th largest element is: {kth_largest}")
6. import heapq
kth_largest = min_heap[0]
# Max-Heap for k-th smallest element (using negative values for max-heap simulation)
max_heap = []
for num in arr:
if len(max_heap) < k:
heapq.heappush(max_heap, -num)
elif -num > max_heap[0]:
heapq.heappushpop(max_heap, -num)
kth_smallest = -max_heap[0]
# Example usage
arr = [3, 2, 1, 5, 6, 4]
k=2
kth_smallest, kth_largest = kth_smallest_largest_heap(arr, k)
print(f"The {k}th smallest element is: {kth_smallest}")
print(f"The {k}th largest element is: {kth_largest}")
7. import heapq
class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def merge_k_sorted_linked_lists(lists):
if not lists:
return None
min_heap = []
while min_heap:
_, index, node = heapq.heappop(min_heap)
current.next = node
current = current.next
return dummy.next
# Example usage
lists = [
create_linked_list([1, 4, 5]),
create_linked_list([1, 3, 4]),
create_linked_list([2, 6])
]
merged_head = merge_k_sorted_linked_lists(lists)
print("Merged linked list:")
print_linked_list(merged_head)
8.